/* Read-only, sampled original-state observer. It never patches target memory. Launch only a generated game copy, with an explicitly attested path. Build: i686-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror tools/recon/original_state_observer.c -lbcrypt -o observer.exe See docs/gameplay/original-state-observer.md for source identity and limits. */ #define WIN32_LEAN_AND_MEAN #define _WIN32_WINNT 0x0601 #include #include #include #include #include #include #include #include #include #define MAX_NODES 1024 #define GAME_BYTES 0x1d44 #define CANONICAL_SHA "f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8" #define HD_SHA "b6675b7e7f3fc37512185ddb4d6ce1fbe9a36c8b83f3b4b3ed6979a56db3d2d4" #define HD_NOCD_SHA "8cd5d21997835a40978b8b83e344c97c92217bf6cd6858f7458b76935d64dedb" typedef struct { const char *name, *sha; uint32_t owner, registry, dt, current, skip, input, modal, suppression; } Profile; static const Profile profiles[] = { {"canonical",CANONICAL_SHA,0x5099e4,0x50999c,0x696030,0x509948,0x4f83e4,0x4f8430,0x4f8198,0x4f8182}, {"hd-resolution",HD_SHA,0x5099e4,0x50999c,0x696030,0x509948,0x4f83e4,0x4f8430,0x4f8198,0x4f8182}, {"hd-nocd",HD_NOCD_SHA,0x509a04,0x5099bc,0x696050,0x509968,0x4f8404,0x4f8450,0x4f81b8,0x4f81a2} }; typedef struct { uint32_t payload, vtable; } Node; typedef struct { uint32_t sentinel, current, owner, jimmy, count; int current_index, jimmy_index, registry_complete; Node nodes[MAX_NODES]; } Registry; static int read_memory(HANDLE process, uint32_t address, void *dest, SIZE_T length) { SIZE_T got = 0; return address >= 0x10000 && ReadProcessMemory(process, (const void *)(uintptr_t)address, dest, length, &got) && got == length; } static uint32_t u32(const unsigned char *p) { return (uint32_t)p[0] | (uint32_t)p[1]<<8 | (uint32_t)p[2]<<16 | (uint32_t)p[3]<<24; } static float f32(const unsigned char *p) { uint32_t bits = u32(p); float value; memcpy(&value, &bits, sizeof(value)); return value; } static void json_float(float value) { if (isfinite(value)) printf("%.9g", (double)value); else fputs("null", stdout); } static void json_string(const char *s) { putchar('"'); for (; *s; ++s) { unsigned char c = (unsigned char)*s; if (c == '\\' || c == '"') printf("\\%c", c); else if (c < 32 || c >= 127) printf("\\u%04x", (unsigned)c); else putchar(c); } putchar('"'); } static int original_component(const char *path) { while (*path) { const char *begin; size_t length; while (*path == '\\' || *path == '/') ++path; begin = path; while (*path && *path != '\\' && *path != '/') ++path; length = (size_t)(path-begin); if (length == 8 && !_strnicmp(begin, "Original", 8)) return 1; } return 0; } static int sha256(HANDLE file, char hex[65]) { BCRYPT_ALG_HANDLE alg = NULL; BCRYPT_HASH_HANDLE hash = NULL; unsigned char buffer[16384], digest[32]; DWORD got; LARGE_INTEGER zero; int ok = 0; zero.QuadPart = 0; if (!SetFilePointerEx(file, zero, NULL, FILE_BEGIN) || BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, NULL, 0) < 0 || BCryptCreateHash(alg, &hash, NULL, 0, NULL, 0, 0) < 0) goto done; for (;;) { if (!ReadFile(file, buffer, sizeof(buffer), &got, NULL)) goto done; if (!got) break; if (BCryptHashData(hash, buffer, got, 0) < 0) goto done; } if (BCryptFinishHash(hash, digest, sizeof(digest), 0) < 0) goto done; for (unsigned i = 0; i < sizeof(digest); ++i) sprintf(hex+2*i, "%02x", digest[i]); hex[64] = 0; ok = 1; done: if (hash) BCryptDestroyHash(hash); if (alg) BCryptCloseAlgorithmProvider(alg, 0); return ok; } /* The allow-listed hashes authenticate these anchors and all source offsets. Retain an independent anchor check to detect an incorrectly mapped image. */ static int operand_guard(HANDLE process, uint32_t pc, const unsigned char *expected, size_t length, unsigned operand, uint32_t address) { unsigned char actual[16], guarded[16]; if (length > sizeof(actual) || operand+4 > length) return 0; memcpy(guarded, expected, length); for (unsigned i = 0; i < 4; ++i) guarded[operand+i] = (unsigned char)(address>>(8*i)); return read_memory(process, pc, actual, length) && !memcmp(actual, guarded, length); } static int runtime_identity(HANDLE process, const Profile *p) { static const unsigned char setter[] = {0x8b,0x44,0x24,0x04,0xa3,0,0,0,0,0xc2,0x04,0x00}; static const unsigned char registry[] = {0xa1,0,0,0,0,0x56,0x8b,0x30}; static const unsigned char dt[] = {0x8b,0x15,0,0,0,0}; static const unsigned char current[] = {0xa3,0,0,0,0}; static const unsigned char skip[] = {0xc6,0x05,0,0,0,0,1}; static const unsigned char input[] = {0xa0,0,0,0,0}; static const unsigned char suppression[] = {0x38,0x1d,0,0,0,0}; return operand_guard(process,0x475a40,setter,sizeof(setter),5,p->owner) && operand_guard(process,0x473740,registry,sizeof(registry),1,p->registry) && operand_guard(process,0x47374f,dt,sizeof(dt),2,p->dt) && operand_guard(process,0x46e360,current,sizeof(current),1,p->current) && operand_guard(process,0x430f3e,skip,sizeof(skip),2,p->skip) && operand_guard(process,0x426062,input,sizeof(input),1,p->input) && operand_guard(process,0x407060,input,sizeof(input),1,p->modal) && operand_guard(process,0x430f11,suppression,sizeof(suppression),2,p->suppression); } static void registry_snapshot(HANDLE process, const Profile *profile, Registry *r) { uint32_t next, node[3]; memset(r, 0, sizeof(*r)); r->current_index = r->jimmy_index = -1; if (!read_memory(process, profile->current, &r->current, 4) || !read_memory(process, profile->owner, &r->owner, 4) || !read_memory(process, profile->registry, &r->sentinel, 4) || !read_memory(process, r->sentinel, &next, 4)) return; while (next != r->sentinel && r->count < MAX_NODES) { if (!read_memory(process, next, node, sizeof(node))) return; for (uint32_t i = 0; i < r->count; ++i) if (r->nodes[i].payload == node[2]) return; /* concurrent mutation/cycle */ r->nodes[r->count].payload = node[2]; if (!read_memory(process, node[2], &r->nodes[r->count].vtable, 4)) return; if (node[2] == r->current+0x8c) r->current_index = (int)r->count; if (r->nodes[r->count].vtable == 0x4a373c) { r->jimmy = node[2]; r->jimmy_index = (int)r->count; } ++r->count; next = node[0]; } r->registry_complete = next == r->sentinel; } static void print_registry(const Registry *r, ULONGLONG elapsed) { printf("{\"kind\":\"registry\",\"elapsed_ms\":%llu,\"complete\":%s,\"sentinel\":%lu," "\"current_game\":%lu,\"raw_owner\":%lu,\"jimmy\":%lu,\"game_index\":%d,\"jimmy_index\":%d,\"nodes\":[", (unsigned long long)elapsed, r->registry_complete ? "true" : "false", (unsigned long)r->sentinel, (unsigned long)r->current, (unsigned long)r->owner, (unsigned long)r->jimmy, r->current_index, r->jimmy_index); for (uint32_t i = 0; i < r->count; ++i) printf("%s[%lu,%lu]", i ? "," : "", (unsigned long)r->nodes[i].payload, (unsigned long)r->nodes[i].vtable); puts("]}"); } static void vector(const unsigned char *p) { putchar('['); for (unsigned i = 0; i < 4; ++i) { if (i) putchar(','); json_float(f32(p+4*i)); } putchar(']'); } static void print_sample(HANDLE process, const Profile *profile, const Registry *r, ULONGLONG elapsed) { unsigned char actor[GAME_BYTES], flags[4], dt[4]; const uint32_t addresses[] = {profile->skip,profile->input,profile->modal,profile->suppression}; unsigned valid = 0; memset(actor, 0, sizeof(actor)); memset(flags, 0, sizeof(flags)); memset(dt, 0, sizeof(dt)); for (unsigned i = 0; i < 4; ++i) if (read_memory(process, addresses[i], flags+i, 1)) valid |= 1u<dt, dt, 4)) valid |= 16; if (r->jimmy && read_memory(process, r->jimmy, actor, sizeof(actor))) valid |= 32; printf("{\"kind\":\"sample\",\"elapsed_ms\":%llu,\"valid_mask\":%u,\"raw_owner\":%lu,\"current_game\":%lu,\"jimmy\":%lu,\"dt\":", (unsigned long long)elapsed, valid, (unsigned long)r->owner, (unsigned long)r->current, (unsigned long)r->jimmy); json_float(f32(dt)); printf(",\"shared_skip\":%u,\"input_block\":%u,\"modal_gate\":%u,\"skip_suppression\":%u", flags[0],flags[1],flags[2],flags[3]); if (valid & 32) { printf(",\"mode\":%d,\"turn\":", (int)(int16_t)(actor[0x704] | actor[0x705]<<8)); json_float(f32(actor+0x614)); printf(",\"dirty\":%u,\"action_latch\":%u,\"cached_support\":%u,\"force_support\":%u,\"current_euler\":", actor[0xa], actor[0x1d40], actor[0x13f], actor[0x4a0]); vector(actor+0x224); fputs(",\"destination_euler\":", stdout); vector(actor+0x274); } puts("}"); } static BOOL CALLBACK owned_window(HWND window, LPARAM parameter) { DWORD pid; DWORD *search = (DWORD *)parameter; GetWindowThreadProcessId(window, &pid); if (pid == search[0] && IsWindowVisible(window) && !GetWindow(window, GW_OWNER)) { search[1] = (DWORD)(uintptr_t)window; return FALSE; } return TRUE; } static HWND find_window(DWORD pid) { DWORD search[2] = {pid, 0}; EnumWindows(owned_window, (LPARAM)search); return (HWND)(uintptr_t)search[1]; } static void menu_key(DWORD pid, ULONGLONG elapsed, int release) { HWND window = find_window(pid); HWND foreground; INPUT event; char title[256]; DWORD thread = window ? GetWindowThreadProcessId(window,NULL) : 0; unsigned sent = 0; memset(&event, 0, sizeof(event)); memset(title,0,sizeof(title)); if (window) GetWindowTextA(window,title,sizeof(title)); if (window && !release) { int attached = thread != GetCurrentThreadId() && AttachThreadInput(GetCurrentThreadId(),thread,TRUE); BringWindowToTop(window); SetForegroundWindow(window); SetActiveWindow(window); SetFocus(window); if (attached) AttachThreadInput(GetCurrentThreadId(),thread,FALSE); } foreground = GetForegroundWindow(); if (release || (window && foreground == window)) { event.type = INPUT_KEYBOARD; event.ki.wVk = VK_RETURN; event.ki.dwFlags = release ? KEYEVENTF_KEYUP : 0; sent = SendInput(1, &event, sizeof(INPUT)); } printf("{\"kind\":\"normal_input\",\"elapsed_ms\":%llu,\"key\":\"Return\",\"release\":%s,\"events_sent\":%u,\"window\":%lu,\"foreground\":%lu,\"title\":", (unsigned long long)elapsed, release?"true":"false",sent, (unsigned long)(uintptr_t)window,(unsigned long)(uintptr_t)foreground); json_string(title); puts("}"); } static void usage(FILE *stream) { fputs("Usage: observer.exe --copied-game= [--seconds=1..120] [--menu-keys]\n" " observer.exe --copied-game-menu= (single-argument menu-input opt-in)\n" " observer.exe --attach-copied-pid= [--seconds=1..120] (read-only, no input/close)\n" "Each copied option explicitly attests that the selected executable is a generated copy outside Original.\n",stream); } int main(int argc, char **argv) { char path[32768], final[32768], directory[32768], hash[65], command[32772]; HANDLE file; STARTUPINFOA start; PROCESS_INFORMATION child; Registry previous, current; unsigned seconds = 15, key_index = 0, samples = 0; int keys = 0, previous_valid = 0, identified = 0; DWORD attach_pid = 0; int key_down = 0; ULONGLONG key_began = 0; const Profile *profile = NULL; ULONGLONG began, elapsed; DWORD exit_code = STILL_ACTIVE; const char *target = NULL; memset(&child,0,sizeof(child)); if (argc == 2 && !strcmp(argv[1],"--help")) { usage(stdout); return 0; } if (argc >= 2 && !strncmp(argv[1], "--copied-game=", 14)) target=argv[1]+14; else if (argc >= 2 && !strncmp(argv[1], "--copied-game-menu=", 19)) { target=argv[1]+19; keys=1; } else if (argc >= 2 && !strncmp(argv[1], "--attach-copied-pid=", 20)) { char *end; const char *number=argv[1]+20; errno=0; unsigned long pid=strtoul(number,&end,10); if (!isdigit((unsigned char)*number) || *end || errno || !pid) return 2; attach_pid=(DWORD)pid; } if ((!target || !*target) && !attach_pid) { usage(stderr); return 2; } for (int i = 2; i < argc; ++i) { char *end; if (!strncmp(argv[i], "--seconds=", 10)) { unsigned long n = strtoul(argv[i]+10, &end, 10); if (*end || n < 1 || n > 120) return 2; seconds = (unsigned)n; } else if (!strcmp(argv[i], "--menu-keys")) keys = 1; else return 2; } if (attach_pid && keys) { fputs("Attach mode never sends input; remove --menu-keys.\n",stderr); return 2; } setbuf(stdout, NULL); DWORD length; if (attach_pid) { child.hProcess=OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,attach_pid); if (!child.hProcess) { fprintf(stderr,"OpenProcess failed: %lu\n",GetLastError()); return 2; } child.dwProcessId=attach_pid; length=sizeof(path); if (!QueryFullProcessImageNameA(child.hProcess,0,path,&length) || !length || length>=sizeof(path)) { fprintf(stderr,"QueryFullProcessImageName failed: %lu\n",GetLastError()); CloseHandle(child.hProcess); return 2; } } else length=GetFullPathNameA(target, sizeof(path), path, NULL); if (!length || length >= sizeof(path) || original_component(path)) { fputs("Rejected target path: use an explicitly attested generated copy outside Original.\n", stderr); if (child.hProcess) CloseHandle(child.hProcess); return 2; } file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) { fprintf(stderr,"Cannot open copied game: %lu\n",GetLastError()); if (child.hProcess) CloseHandle(child.hProcess); return 2; } LARGE_INTEGER size; if (!GetFileSizeEx(file,&size) || size.QuadPart != 1019904) { fputs("Rejected target size.\n",stderr); CloseHandle(file); if (child.hProcess) CloseHandle(child.hProcess); return 2; } length = GetFinalPathNameByHandleA(file, final, sizeof(final), FILE_NAME_NORMALIZED); if (sha256(file, hash)) for (unsigned i = 0; i < sizeof(profiles)/sizeof(profiles[0]); ++i) if (!strcmp(hash,profiles[i].sha)) profile = profiles+i; if (!length || length >= sizeof(final) || original_component(final) || !profile) { fputs("Rejected target identity/path; only explicitly supported verified source profiles are accepted.\n", stderr); CloseHandle(file); if (child.hProcess) CloseHandle(child.hProcess); return 2; } /* Keep the authenticated file handle open without FILE_SHARE_WRITE/DELETE through process creation, preventing target-file replacement after hashing. */ if (!attach_pid) { strcpy(directory, path); char *slash = strrchr(directory, '\\'); if (!slash) { CloseHandle(file); return 2; } *slash = 0; snprintf(command, sizeof(command), "\"%s\"", path); memset(&start, 0, sizeof(start)); start.cb = sizeof(start); if (!CreateProcessA(path, command, NULL, NULL, FALSE, 0, NULL, directory, &start, &child)) { fprintf(stderr,"CreateProcess failed: %lu\n",GetLastError()); CloseHandle(file); return 2; } CloseHandle(child.hThread); } CloseHandle(file); fputs("{\"kind\":\"identity\",\"target\":", stdout); json_string(path); printf(",\"sha256\":\"%s\",\"profile\":\"%s\",\"pid\":%lu,\"attached\":%s,\"interval_ms\":10,\"duration_ms\":%u,\"scope\":\"read-only sampled process state; no callback-order or whole-frame guarantee\"}\n", hash, profile->name, child.dwProcessId, attach_pid?"true":"false",seconds*1000); began = GetTickCount64(); do { elapsed = GetTickCount64()-began; if (WaitForSingleObject(child.hProcess, 0) == WAIT_OBJECT_0) break; if (!identified) { identified = runtime_identity(child.hProcess,profile); if (!identified && elapsed > 5000) { fputs("{\"kind\":\"error\",\"reason\":\"runtime source anchors unavailable after 5s; sampling refused\"}\n",stdout); break; } } if (identified) { registry_snapshot(child.hProcess,profile,¤t); if (!previous_valid || memcmp(¤t, &previous, sizeof(current))) { print_registry(¤t, elapsed); previous = current; previous_valid = 1; } print_sample(child.hProcess,profile,¤t,elapsed); ++samples; } if (!attach_pid && key_down && elapsed-key_began >= 100) { menu_key(child.dwProcessId,elapsed,1); key_down=0; } if (!attach_pid && keys && !key_down && key_index < 3 && elapsed >= (ULONGLONG)(key_index+1)*3000) { menu_key(child.dwProcessId,elapsed,0); ++key_index; key_began=elapsed; key_down=1; } Sleep(10); } while (elapsed < seconds*1000); if (!attach_pid && key_down) menu_key(child.dwProcessId,GetTickCount64()-began,1); GetExitCodeProcess(child.hProcess, &exit_code); printf("{\"kind\":\"finish\",\"elapsed_ms\":%llu,\"samples\":%u,\"identified\":%s,\"game_exit\":%lu,\"left_running\":%s}\n", (unsigned long long)(GetTickCount64()-began), samples, identified?"true":"false", exit_code, exit_code == STILL_ACTIVE ? "true" : "false"); /* Request ordinary shutdown only for this launcher-owned process. Do not terminate it or enumerate/kill unrelated game or Wine processes. */ if (!attach_pid && exit_code == STILL_ACTIVE) { HWND window = find_window(child.dwProcessId); if (window) PostMessageA(window, WM_CLOSE, 0, 0); } CloseHandle(child.hProcess); if (!identified || !samples) return 3; puts("{\"kind\":\"complete\",\"marker\":\"ORIGINAL_STATE_OBSERVER_COMPLETE\"}"); return 0; }