client/runtime/linux_platform.c (16575B)
1 #define _GNU_SOURCE 2 #include "linux_path.h" 3 #include "linux_platform.h" 4 #include <errno.h> 5 #include <limits.h> 6 #include <pthread.h> 7 #include <sched.h> 8 #include <strings.h> 9 #include <sys/stat.h> 10 #ifdef __EMSCRIPTEN__ 11 #include <emscripten/heap.h> 12 #include <malloc.h> 13 #else 14 #include <sys/sysinfo.h> 15 #endif 16 #include <time.h> 17 #include <unistd.h> 18 19 uint64_t guest_memory_mapped_bytes(void); 20 21 /* Host mutex objects are keyed by guest addresses, never stored in guest memory. */ 22 struct critical_section { 23 uint32_t address; 24 pthread_mutex_t mutex; 25 struct critical_section *next; 26 }; 27 static struct critical_section *critical_sections; 28 static pthread_mutex_t sections_mutex = PTHREAD_MUTEX_INITIALIZER; 29 static uint32_t unhandled_exception_filter; 30 31 static void check_pthread(int error) 32 { 33 if (error) { fprintf(stderr, "pthread: %s\n", strerror(error)); abort(); } 34 } 35 36 static struct critical_section *find_critical_section_locked(uint32_t address) 37 { 38 for (struct critical_section *section = critical_sections; section; section = section->next) 39 if (section->address == address) return section; 40 fprintf(stderr, "Unknown guest critical section %08x\n", address); 41 abort(); 42 } 43 44 static struct critical_section *find_critical_section(uint32_t address) 45 { 46 check_pthread(pthread_mutex_lock(§ions_mutex)); 47 struct critical_section *section = find_critical_section_locked(address); 48 check_pthread(pthread_mutex_unlock(§ions_mutex)); 49 return section; 50 } 51 52 static void initialize_critical_section(void) 53 { 54 struct critical_section *section = malloc(sizeof(*section)); 55 if (!section) { perror("critical section allocation"); abort(); } 56 section->address = MEM32(g_esp + 4); 57 pthread_mutexattr_t attributes; 58 check_pthread(pthread_mutexattr_init(&attributes)); 59 check_pthread(pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE)); 60 check_pthread(pthread_mutex_init(§ion->mutex, &attributes)); 61 check_pthread(pthread_mutexattr_destroy(&attributes)); 62 check_pthread(pthread_mutex_lock(§ions_mutex)); 63 section->next = critical_sections; 64 critical_sections = section; 65 memset((void *)ADDR(section->address), 0, 24); 66 MEM32(section->address + 4) = UINT32_MAX; 67 check_pthread(pthread_mutex_unlock(§ions_mutex)); 68 g_esp += 8; 69 } 70 71 static void enter_critical_section(void) 72 { 73 struct critical_section *section = find_critical_section(MEM32(g_esp + 4)); 74 check_pthread(pthread_mutex_lock(§ion->mutex)); 75 ++MEM32(section->address + 4); 76 ++MEM32(section->address + 8); 77 MEM32(section->address + 12) = (uint32_t)gettid(); 78 g_esp += 8; 79 } 80 81 static void leave_critical_section(void) 82 { 83 struct critical_section *section = find_critical_section(MEM32(g_esp + 4)); 84 --MEM32(section->address + 4); 85 if (!--MEM32(section->address + 8)) MEM32(section->address + 12) = 0; 86 check_pthread(pthread_mutex_unlock(§ion->mutex)); 87 g_esp += 8; 88 } 89 90 static void delete_critical_section(void) 91 { 92 check_pthread(pthread_mutex_lock(§ions_mutex)); 93 struct critical_section *section = find_critical_section_locked(MEM32(g_esp + 4)); 94 check_pthread(pthread_mutex_destroy(§ion->mutex)); 95 struct critical_section **link = &critical_sections; 96 while (*link != section) link = &(*link)->next; 97 *link = section->next; 98 free(section); 99 check_pthread(pthread_mutex_unlock(§ions_mutex)); 100 g_esp += 8; 101 } 102 103 static void interlocked_exchange(void) 104 { 105 g_eax = __atomic_exchange_n((uint32_t *)ADDR(MEM32(g_esp + 4)), MEM32(g_esp + 8), __ATOMIC_SEQ_CST); 106 g_esp += 12; 107 } 108 109 static void interlocked_increment(void) 110 { 111 g_eax = __atomic_add_fetch((uint32_t *)ADDR(MEM32(g_esp + 4)), 1u, __ATOMIC_SEQ_CST); 112 g_esp += 8; 113 } 114 115 static void interlocked_decrement(void) 116 { 117 g_eax = __atomic_sub_fetch((uint32_t *)ADDR(MEM32(g_esp + 4)), 1u, __ATOMIC_SEQ_CST); 118 g_esp += 8; 119 } 120 121 static void performance_frequency(void) 122 { 123 MEM64(MEM32(g_esp + 4)) = 1000000000ull; 124 g_eax = 1; 125 g_esp += 8; 126 } 127 128 static void performance_counter(void) 129 { 130 struct timespec now; 131 if (clock_gettime(CLOCK_MONOTONIC, &now)) { perror("clock_gettime"); abort(); } 132 MEM64(MEM32(g_esp + 4)) = (uint64_t)now.tv_sec * 1000000000ull + now.tv_nsec; 133 g_eax = 1; 134 g_esp += 8; 135 } 136 137 static void tick_count(void) 138 { 139 /* Guest DWORD milliseconds wrap at 2^32, including time spent suspended. */ 140 struct timespec now; 141 #ifdef __EMSCRIPTEN__ 142 /* Browsers expose a monotonic clock but no system boot-time clock. */ 143 if (clock_gettime(CLOCK_MONOTONIC, &now)) { perror("clock_gettime"); abort(); } 144 #else 145 if (clock_gettime(CLOCK_BOOTTIME, &now)) { perror("clock_gettime"); abort(); } 146 #endif 147 g_eax = (uint32_t)((uint64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000); 148 g_esp += 4; 149 } 150 151 static void system_time_as_file_time(void) 152 { 153 struct timespec now; 154 if (clock_gettime(CLOCK_REALTIME, &now)) { perror("clock_gettime"); abort(); } 155 /* FILETIME counts 100 ns intervals from 1601-01-01 UTC. */ 156 MEM64(MEM32(g_esp + 4)) = ((uint64_t)now.tv_sec + 11644473600ull) * 10000000ull + now.tv_nsec / 100; 157 g_esp += 8; 158 } 159 160 static void current_thread_handle(void) 161 { 162 g_eax = 0xfffffffeu; 163 g_esp += 4; 164 } 165 166 static void sleep_milliseconds(void) 167 { 168 uint32_t milliseconds = MEM32(g_esp + 4); 169 if (milliseconds == UINT32_MAX) for (;;) pause(); 170 if (!milliseconds) { 171 sched_yield(); 172 } else { 173 struct timespec delay = {milliseconds / 1000, (milliseconds % 1000) * 1000000}; 174 while (nanosleep(&delay, &delay)) { 175 if (errno != EINTR) { perror("nanosleep"); abort(); } 176 } 177 } 178 g_esp += 8; 179 } 180 181 static void get_last_error(void) 182 { 183 g_eax = MEM32(g_fs_base + 0x34); 184 g_esp += 4; 185 } 186 187 static void current_thread_id(void) 188 { 189 g_eax = (uint32_t)gettid(); 190 g_esp += 4; 191 } 192 193 static void current_process_id(void) 194 { 195 g_eax = (uint32_t)getpid(); 196 g_esp += 4; 197 } 198 199 static void set_last_error(void) 200 { 201 MEM32(g_fs_base + 0x34) = MEM32(g_esp + 4); 202 g_esp += 8; 203 } 204 205 static void get_startup_info(void) 206 { 207 /* Direct Linux launches have no requested window placement or inherited handles. */ 208 uint32_t info = MEM32(g_esp + 4); 209 memset((void *)ADDR(info), 0, 68); 210 MEM32(info) = 68; /* sizeof(STARTUPINFOA) in the guest's 32-bit ABI */ 211 g_esp += 8; 212 } 213 214 static void get_version(void) 215 { 216 uint32_t info = MEM32(g_esp + 4), size = MEM32(info); 217 g_eax = 0; 218 if (size == 148 || size == 156) { 219 /* Match the unmanifested Windows reference's NT compatibility profile. 220 * This selects the guest's NT/Unicode paths, not a Linux kernel version. */ 221 MEM32(info + 4) = 6; 222 MEM32(info + 8) = 2; 223 MEM32(info + 12) = 9200; 224 MEM32(info + 16) = 2; 225 MEM8(info + 20) = 0; 226 if (size == 156) { 227 MEM16(info + 148) = 0; 228 MEM16(info + 150) = 0; 229 MEM16(info + 152) = 0x100; 230 MEM8(info + 154) = 1; 231 MEM8(info + 155) = 0; 232 } 233 g_eax = 1; 234 } else MEM32(g_fs_base + 0x34) = 122; /* ERROR_INSUFFICIENT_BUFFER */ 235 g_esp += 8; 236 } 237 238 static void set_unhandled_exception_filter(void) 239 { 240 /* Preserve guest callback registration; native fault dispatch is not implemented. */ 241 g_eax = unhandled_exception_filter; 242 unhandled_exception_filter = MEM32(g_esp + 4); 243 g_esp += 8; 244 } 245 246 static void get_module_filename(void) 247 { 248 if (MEM32(g_esp + 4)) { 249 fprintf(stderr, "Module filenames for compiled DLL handles are not implemented\n"); 250 abort(); 251 } 252 /* The native executable's real path is also valid for Linux filesystem calls. */ 253 char path[PATH_MAX]; 254 ssize_t length = readlink("/proc/self/exe", path, sizeof(path)); 255 if (length < 0 || length == sizeof(path)) { perror("executable path"); abort(); } 256 uint32_t destination = MEM32(g_esp + 8), size = MEM32(g_esp + 12); 257 uint32_t count = length < size ? (uint32_t)length : size; 258 if (size) { 259 uint32_t copied = count < size ? count : size - 1; 260 memcpy((void *)ADDR(destination), path, copied); 261 MEM8(destination + copied) = 0; 262 } 263 MEM32(g_fs_base + 0x34) = length >= size ? 122 : 0; 264 g_eax = count; 265 g_esp += 16; 266 } 267 268 static void delete_file(void) 269 { 270 const char *name = (const char *)ADDR(MEM32(g_esp + 4)); 271 if ((name[0] && name[1] == ':') || (name[0] == '\\' && name[1] == '\\')) { 272 fprintf(stderr, "Windows drive/UNC file paths are not implemented: %s\n", name); 273 abort(); 274 } 275 char *path = linux_path(name); 276 struct stat info; 277 int error = 0; 278 if (!*path) error = 3; /* ERROR_PATH_NOT_FOUND */ 279 else if (lstat(path, &info)) error = errno; 280 else if (S_ISDIR(info.st_mode) || (S_ISREG(info.st_mode) && !(info.st_mode & 0222))) error = EACCES; 281 else if (unlink(path)) error = errno; 282 g_eax = !error; 283 if (error) { 284 uint32_t windows_error; 285 if (!*path) windows_error = 3; 286 else if (error == ENOENT) { 287 windows_error = 2; /* Distinguish a missing leaf from a missing parent. */ 288 char *slash = strrchr(path, '/'); 289 if (slash) { 290 if (slash == path) slash[1] = 0; 291 else *slash = 0; 292 if (stat(path, &info) || !S_ISDIR(info.st_mode)) windows_error = 3; 293 } 294 } else if (error == ENOTDIR) windows_error = 3; 295 else if (error == EACCES || error == EPERM || error == EISDIR) windows_error = 5; 296 else if (error == ENAMETOOLONG) windows_error = 206; 297 else if (error == EROFS) windows_error = 19; 298 else { 299 fprintf(stderr, "Unhandled DeleteFile error for %s: %s\n", name, strerror(error)); 300 abort(); 301 } 302 MEM32(g_fs_base + 0x34) = windows_error; 303 } 304 free(path); 305 g_esp += 8; 306 } 307 308 static void create_directory(void) 309 { 310 const char *name = (const char *)ADDR(MEM32(g_esp + 4)); 311 if (MEM32(g_esp + 8) || strchr(name, ':') || !strncmp(name, "\\\\", 2)) { 312 fprintf(stderr, "Unsupported CreateDirectory path or security attributes: %s\n", name); 313 abort(); 314 } 315 char *path = linux_path(name); 316 g_eax = mkdir(path, 0777) == 0; 317 if (!g_eax) { 318 uint32_t error; 319 if (errno == EEXIST) error = 183; /* ERROR_ALREADY_EXISTS */ 320 else if (errno == ENOENT || errno == ENOTDIR) error = 3; 321 else if (errno == EACCES || errno == EPERM) error = 5; 322 else if (errno == ENAMETOOLONG) error = 206; 323 else if (errno == EROFS) error = 19; 324 else if (errno == ENOSPC) error = 112; 325 else { 326 fprintf(stderr, "Unhandled CreateDirectory error for %s: %s\n", name, strerror(errno)); 327 abort(); 328 } 329 MEM32(g_fs_base + 0x34) = error; 330 } 331 free(path); 332 g_esp += 12; 333 } 334 335 static void wide_char_to_multi_byte(void) 336 { 337 uint32_t code_page = MEM32(g_esp + 4), flags = MEM32(g_esp + 8); 338 uint32_t input = MEM32(g_esp + 12), output = MEM32(g_esp + 20); 339 int32_t count = MEM32(g_esp + 16), capacity = MEM32(g_esp + 24); 340 uint32_t default_char = MEM32(g_esp + 28), used_default = MEM32(g_esp + 32); 341 g_esp += 36; 342 g_eax = 0; 343 if (code_page != 65001) { 344 fprintf(stderr, "Unsupported WideCharToMultiByte code page %u\n", code_page); exit(3); 345 } 346 if (flags & ~0x80u) { MEM32(g_fs_base + 0x34) = 1004; return; } 347 if (!input || !count || capacity < 0 || (capacity && !output) || 348 input == output || default_char || used_default) { 349 MEM32(g_fs_base + 0x34) = 87; return; 350 } 351 352 /* Negative counts include the terminator; positive counts consume exact UTF-16 units. */ 353 uint32_t written = 0; 354 int invalid = 0; 355 for (uint32_t i = 0; count < 0 || i < (uint32_t)count; ++i) { 356 uint32_t character = MEM16(input + i * 2); 357 if (character >= 0xd800 && character <= 0xdbff && (count < 0 || i + 1 < (uint32_t)count)) { 358 uint32_t low = MEM16(input + (i + 1) * 2); 359 if (low >= 0xdc00 && low <= 0xdfff) { 360 character = 0x10000 + ((character - 0xd800) << 10) + low - 0xdc00; 361 ++i; 362 } 363 } 364 if (character >= 0xd800 && character <= 0xdfff) { 365 invalid = 1; 366 character = 0xfffd; 367 } 368 unsigned length = character < 0x80 ? 1 : character < 0x800 ? 2 : character < 0x10000 ? 3 : 4; 369 if (written > INT32_MAX - length || (capacity && written + length > (uint32_t)capacity)) { 370 MEM32(g_fs_base + 0x34) = 122; return; 371 } 372 if (capacity) { 373 uint32_t value = character; 374 for (unsigned j = length - 1; j; --j) { 375 MEM8(output + written + j) = 0x80 | (value & 0x3f); 376 value >>= 6; 377 } 378 MEM8(output + written) = length == 1 ? value : (length == 2 ? 0xc0 : length == 3 ? 0xe0 : 0xf0) | value; 379 } 380 written += length; 381 if (count < 0 && !character) break; 382 } 383 /* Windows retains replacement output even when strict validation fails. */ 384 if (invalid && (flags & 0x80)) MEM32(g_fs_base + 0x34) = 1113; 385 else g_eax = written; 386 } 387 388 static void set_handle_count(void) 389 { 390 /* Win32 keeps this DOS compatibility call as a no-op. */ 391 g_eax = MEM32(g_esp + 4); 392 g_esp += 8; 393 } 394 395 static void global_memory_status(void) 396 { 397 #ifdef __EMSCRIPTEN__ 398 /* Report the WASM address-space budget, not unavailable host RAM statistics. */ 399 uint64_t total = emscripten_get_heap_max(); 400 uint64_t available = total - emscripten_get_heap_size() + mallinfo().fordblks; 401 uint64_t page_total = total, page_available = available; 402 #else 403 struct sysinfo info; 404 if (sysinfo(&info)) { perror("sysinfo"); abort(); } 405 uint64_t total = (uint64_t)info.totalram * info.mem_unit; 406 uint64_t available = ((uint64_t)info.freeram + info.bufferram) * info.mem_unit; 407 uint64_t page_total = total + (uint64_t)info.totalswap * info.mem_unit; 408 uint64_t page_available = available + (uint64_t)info.freeswap * info.mem_unit; 409 #endif 410 uint64_t mapped = guest_memory_mapped_bytes(); 411 uint32_t output = MEM32(g_esp + 4); 412 413 /* MEMORYSTATUS is eight DWORDs for the non-LAA x86 guest. Physical values 414 * retain its signed 2 GiB ceiling; page-file values saturate at UINT32_MAX. */ 415 MEM32(output) = 32; 416 MEM32(output + 4) = (total - available) * 100 / total; 417 MEM32(output + 8) = total > INT32_MAX ? INT32_MAX : total; 418 MEM32(output + 12) = available > INT32_MAX ? INT32_MAX : available; 419 MEM32(output + 16) = page_total > UINT32_MAX ? UINT32_MAX : page_total; 420 MEM32(output + 20) = page_available > UINT32_MAX ? UINT32_MAX : page_available; 421 MEM32(output + 24) = 0x7ffe0000; 422 MEM32(output + 28) = mapped >= 0x7ffe0000 ? 0 : 0x7ffe0000 - mapped; 423 g_esp += 8; 424 } 425 426 recomp_func_t linux_platform_lookup(const char *dll, const char *name) 427 { 428 if (!strcasecmp(dll, "winmm.dll") && !strcmp(name, "timeGetTime")) return tick_count; 429 if (strcasecmp(dll, "kernel32.dll")) return NULL; 430 static const struct { const char *name; recomp_func_t function; } functions[] = { 431 {"QueryPerformanceFrequency", performance_frequency}, 432 {"QueryPerformanceCounter", performance_counter}, 433 {"GetTickCount", tick_count}, {"Sleep", sleep_milliseconds}, 434 {"GetSystemTimeAsFileTime", system_time_as_file_time}, 435 {"GetCurrentThread", current_thread_handle}, 436 {"GetLastError", get_last_error}, {"SetLastError", set_last_error}, 437 {"GetCurrentThreadId", current_thread_id}, 438 {"GetCurrentProcessId", current_process_id}, 439 {"GetStartupInfoA", get_startup_info}, 440 {"GetVersionExA", get_version}, 441 {"SetUnhandledExceptionFilter", set_unhandled_exception_filter}, 442 {"GetModuleFileNameA", get_module_filename}, 443 {"DeleteFileA", delete_file}, 444 {"CreateDirectoryA", create_directory}, 445 {"SetHandleCount", set_handle_count}, 446 {"WideCharToMultiByte", wide_char_to_multi_byte}, 447 {"GlobalMemoryStatus", global_memory_status}, 448 {"InterlockedExchange", interlocked_exchange}, 449 {"InterlockedIncrement", interlocked_increment}, 450 {"InterlockedDecrement", interlocked_decrement}, 451 {"InitializeCriticalSection", initialize_critical_section}, 452 {"EnterCriticalSection", enter_critical_section}, 453 {"LeaveCriticalSection", leave_critical_section}, 454 {"DeleteCriticalSection", delete_critical_section}, 455 }; 456 for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i) 457 if (!strcmp(name, functions[i].name)) return functions[i].function; 458 return NULL; 459 }