client/runtime/linux_tls.c (2601B)
1 #include "linux_tls.h" 2 #include <pthread.h> 3 4 /* Index allocation is process-wide; values are 32-bit guest words per host thread. 5 * Generations invalidate every thread's value when a slot is freed or reused. */ 6 static struct { uint64_t generation; int allocated; } slots[1088]; 7 static _Thread_local struct { uint64_t generation; uint32_t value; } values[1088]; 8 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 9 10 static void check_pthread(int error) 11 { 12 if (error) { fprintf(stderr, "TLS pthread: %s\n", strerror(error)); abort(); } 13 } 14 15 static void allocate_slot(void) 16 { 17 g_eax = UINT32_MAX; /* TLS_OUT_OF_INDEXES */ 18 check_pthread(pthread_mutex_lock(&mutex)); 19 for (unsigned index = 0; index < 1088; ++index) { 20 if (!slots[index].allocated) { 21 slots[index].allocated = 1; 22 ++slots[index].generation; 23 g_eax = index; 24 break; 25 } 26 } 27 check_pthread(pthread_mutex_unlock(&mutex)); 28 if (g_eax == UINT32_MAX) MEM32(g_fs_base + 0x34) = 8; /* ERROR_NOT_ENOUGH_MEMORY */ 29 g_esp += 4; 30 } 31 32 static void free_slot(void) 33 { 34 uint32_t index = MEM32(g_esp + 4); 35 g_eax = 0; 36 check_pthread(pthread_mutex_lock(&mutex)); 37 if (index < 1088 && slots[index].allocated) { 38 slots[index].allocated = 0; 39 ++slots[index].generation; 40 g_eax = 1; 41 } 42 check_pthread(pthread_mutex_unlock(&mutex)); 43 if (!g_eax) MEM32(g_fs_base + 0x34) = 87; 44 g_esp += 8; 45 } 46 47 static void access_slot(int write) 48 { 49 uint32_t index = MEM32(g_esp + 4); 50 g_eax = 0; 51 if (index >= 1088) MEM32(g_fs_base + 0x34) = 87; 52 else { 53 check_pthread(pthread_mutex_lock(&mutex)); 54 if (values[index].generation != slots[index].generation) { 55 values[index].generation = slots[index].generation; 56 values[index].value = 0; 57 } 58 /* Windows Get/Set accept in-range slots even when not allocated. */ 59 if (write) { 60 values[index].value = MEM32(g_esp + 8); 61 g_eax = 1; 62 } else { 63 g_eax = values[index].value; 64 MEM32(g_fs_base + 0x34) = 0; 65 } 66 check_pthread(pthread_mutex_unlock(&mutex)); 67 } 68 g_esp += write ? 12 : 8; 69 } 70 71 static void get_value(void) { access_slot(0); } 72 static void set_value(void) { access_slot(1); } 73 74 recomp_func_t linux_tls_lookup(const char *name) 75 { 76 if (!strcmp(name, "TlsAlloc")) return allocate_slot; 77 if (!strcmp(name, "TlsFree")) return free_slot; 78 if (!strcmp(name, "TlsGetValue")) return get_value; 79 if (!strcmp(name, "TlsSetValue")) return set_value; 80 return NULL; 81 }