os_win32.c (11522B)
1 /* See LICENSE for license details. */ 2 3 #define OS_SHARED_MEMORY_NAME "Local\\ogl_beamformer_parameters" 4 5 #define OS_PATH_SEPARATOR_CHAR '\\' 6 #define OS_PATH_SEPARATOR "\\" 7 8 #include "util.h" 9 10 #define STD_INPUT_HANDLE -10 11 #define STD_OUTPUT_HANDLE -11 12 #define STD_ERROR_HANDLE -12 13 14 #define PAGE_READWRITE 0x04 15 #define MEM_COMMIT 0x1000 16 #define MEM_RESERVE 0x2000 17 18 #define GENERIC_WRITE 0x40000000 19 #define GENERIC_READ 0x80000000 20 21 #define FILE_SHARE_READ 0x00000001 22 #define FILE_MAP_ALL_ACCESS 0x000F001F 23 #define FILE_FLAG_BACKUP_SEMANTICS 0x02000000 24 #define FILE_FLAG_OVERLAPPED 0x40000000 25 26 #define FILE_NOTIFY_CHANGE_LAST_WRITE 0x00000010 27 28 #define FILE_ACTION_MODIFIED 0x00000003 29 30 #define CREATE_ALWAYS 2 31 #define OPEN_EXISTING 3 32 33 #define THREAD_SET_LIMITED_INFORMATION 0x0400 34 35 /* NOTE: this is packed because the w32 api designers are dumb and ordered the members 36 * incorrectly. They worked around it be making the ft* members a struct {u32, u32} which 37 * is aligned on a 4-byte boundary. Then in their documentation they explicitly tell you not 38 * to cast to u64 because "it can cause alignment faults on 64-bit Windows" - go figure */ 39 typedef struct w32_file_info w32_file_info; 40 pack_struct(struct w32_file_info { 41 u32 dwFileAttributes; 42 u64 ftCreationTime; 43 u64 ftLastAccessTime; 44 u64 ftLastWriteTime; 45 u32 dwVolumeSerialNumber; 46 u32 nFileSizeHigh; 47 u32 nFileSizeLow; 48 u32 nNumberOfLinks; 49 u32 nFileIndexHigh; 50 u32 nFileIndexLow; 51 }); 52 53 typedef struct { 54 u32 next_entry_offset; 55 u32 action; 56 u32 filename_size; 57 u16 filename[]; 58 } w32_file_notify_info; 59 60 typedef struct { 61 uptr internal, internal_high; 62 union { 63 struct {u32 off, off_high;}; 64 iptr pointer; 65 }; 66 iptr event_handle; 67 } w32_overlapped; 68 69 typedef enum { 70 W32_IO_FILE_WATCH, 71 W32_IO_PIPE, 72 } W32_IO_Event; 73 74 typedef struct { 75 u64 tag; 76 iptr context; 77 } w32_io_completion_event; 78 79 typedef struct { 80 iptr *semaphores; 81 u32 reserved_count; 82 } w32_shared_memory_context; 83 84 #define W32(r) __declspec(dllimport) r __stdcall 85 W32(b32) CloseHandle(iptr); 86 W32(b32) CopyFileA(c8 *, c8 *, b32); 87 W32(iptr) CreateFileA(c8 *, u32, u32, void *, u32, u32, void *); 88 W32(iptr) CreateFileMappingA(iptr, void *, u32, u32, u32, c8 *); 89 W32(iptr) CreateIoCompletionPort(iptr, iptr, uptr, u32); 90 W32(iptr) CreateSemaphoreA(iptr, i32, i32, c8 *); 91 W32(iptr) CreateThread(iptr, uz, iptr, iptr, u32, u32 *); 92 W32(b32) DeleteFileA(c8 *); 93 W32(void) ExitProcess(i32); 94 W32(b32) FreeLibrary(void *); 95 W32(i32) GetFileAttributesA(c8 *); 96 W32(b32) GetFileInformationByHandle(iptr, void *); 97 W32(i32) GetLastError(void); 98 W32(void *) GetModuleHandleA(c8 *); 99 W32(void *) GetProcAddress(void *, c8 *); 100 W32(b32) GetQueuedCompletionStatus(iptr, u32 *, uptr *, w32_overlapped **, u32); 101 W32(iptr) GetStdHandle(i32); 102 W32(void) GetSystemInfo(void *); 103 W32(void *) LoadLibraryA(c8 *); 104 W32(void *) MapViewOfFile(iptr, u32, u32, u32, u64); 105 W32(b32) QueryPerformanceCounter(u64 *); 106 W32(b32) QueryPerformanceFrequency(u64 *); 107 W32(b32) ReadDirectoryChangesW(iptr, u8 *, u32, b32, u32, u32 *, void *, void *); 108 W32(b32) ReadFile(iptr, u8 *, i32, i32 *, void *); 109 W32(b32) ReleaseSemaphore(iptr, i32, i32 *); 110 W32(i32) SetThreadDescription(iptr, u16 *); 111 W32(u32) WaitForSingleObject(iptr, u32); 112 W32(b32) WaitOnAddress(void *, void *, uz, u32); 113 W32(i32) WakeByAddressAll(void *); 114 W32(iptr) wglGetProcAddress(c8 *); 115 W32(b32) WriteFile(iptr, u8 *, i32, i32 *, void *); 116 W32(void *) VirtualAlloc(u8 *, iz, u32, u32); 117 118 typedef struct { 119 iptr error_handle; 120 iptr io_completion_handle; 121 u64 timer_frequency; 122 } OS_W32Context; 123 global OS_W32Context os_w32_context; 124 125 #ifdef _DEBUG 126 function void * 127 os_get_module(char *name, Stream *e) 128 { 129 void *result = GetModuleHandleA(name); 130 if (!result && e) { 131 stream_append_s8s(e, s8("os_get_module(\""), c_str_to_s8(name), s8("\"): ")); 132 stream_append_i64(e, GetLastError()); 133 stream_append_byte(e, '\n'); 134 } 135 return result; 136 } 137 #endif 138 139 function OS_WRITE_FILE_FN(os_write_file) 140 { 141 i32 wlen = 0; 142 if (raw.len > 0 && raw.len <= U32_MAX) WriteFile(file, raw.data, (i32)raw.len, &wlen, 0); 143 return raw.len == wlen; 144 } 145 146 function no_return void 147 os_exit(i32 code) 148 { 149 ExitProcess(1); 150 unreachable(); 151 } 152 153 function no_return void 154 os_fatal(s8 msg) 155 { 156 os_write_file(GetStdHandle(STD_ERROR_HANDLE), msg); 157 os_exit(1); 158 unreachable(); 159 } 160 161 function iptr 162 os_error_handle(void) 163 { 164 return os_w32_context.error_handle; 165 } 166 167 function s8 168 os_path_separator(void) 169 { 170 return s8("\\"); 171 } 172 173 function u64 174 os_get_timer_frequency(void) 175 { 176 u64 result; 177 QueryPerformanceFrequency(&result); 178 return result; 179 } 180 181 function u64 182 os_get_timer_counter(void) 183 { 184 u64 result; 185 QueryPerformanceCounter(&result); 186 return result; 187 } 188 189 function iz 190 os_round_up_to_page_size(iz value) 191 { 192 struct { 193 u16 architecture; 194 u16 _pad1; 195 u32 page_size; 196 iz minimum_application_address; 197 iz maximum_application_address; 198 u64 active_processor_mask; 199 u32 number_of_processors; 200 u32 processor_type; 201 u32 allocation_granularity; 202 u16 processor_level; 203 u16 processor_revision; 204 } info; 205 GetSystemInfo(&info); 206 iz result = round_up_to(value, info.page_size); 207 return result; 208 } 209 210 function OS_ALLOC_ARENA_FN(os_alloc_arena) 211 { 212 Arena result = {0}; 213 capacity = os_round_up_to_page_size(capacity); 214 result.beg = VirtualAlloc(0, capacity, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); 215 if (!result.beg) 216 os_fatal(s8("os_alloc_arena: couldn't allocate memory\n")); 217 result.end = result.beg + capacity; 218 asan_poison_region(result.beg, result.end - result.beg); 219 return result; 220 } 221 222 function OS_READ_WHOLE_FILE_FN(os_read_whole_file) 223 { 224 s8 result = s8(""); 225 226 w32_file_info fileinfo; 227 iptr h = CreateFileA(file, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); 228 if (h >= 0 && GetFileInformationByHandle(h, &fileinfo)) { 229 iz filesize = (iz)fileinfo.nFileSizeHigh << 32; 230 filesize |= (iz)fileinfo.nFileSizeLow; 231 if (filesize <= U32_MAX) { 232 result = s8_alloc(arena, filesize); 233 i32 rlen; 234 if (!ReadFile(h, result.data, (i32)result.len, &rlen, 0) || rlen != result.len) 235 result = s8(""); 236 } 237 } 238 if (h >= 0) CloseHandle(h); 239 240 return result; 241 } 242 243 function OS_WRITE_NEW_FILE_FN(os_write_new_file) 244 { 245 b32 result = 0; 246 iptr h = CreateFileA(fname, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); 247 if (h >= 0) { 248 while (raw.len > 0) { 249 s8 chunk = raw; 250 chunk.len = MIN(chunk.len, (iz)GB(2)); 251 result = os_write_file(h, chunk); 252 if (!result) break; 253 raw = s8_cut_head(raw, chunk.len); 254 } 255 CloseHandle(h); 256 } 257 return result; 258 } 259 260 function b32 261 os_file_exists(char *path) 262 { 263 b32 result = GetFileAttributesA(path) != -1; 264 return result; 265 } 266 267 function SharedMemoryRegion 268 os_create_shared_memory_area(Arena *arena, char *name, u32 lock_count, iz requested_capacity) 269 { 270 iz capacity = os_round_up_to_page_size(requested_capacity); 271 assert(capacity <= (iz)U32_MAX); 272 SharedMemoryRegion result = {0}; 273 iptr h = CreateFileMappingA(-1, 0, PAGE_READWRITE, 0, (u32)capacity, name); 274 if (h != INVALID_FILE) { 275 void *new = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, (u32)capacity); 276 if (new) { 277 w32_shared_memory_context *ctx = push_struct(arena, typeof(*ctx)); 278 ctx->semaphores = push_array(arena, typeof(*ctx->semaphores), lock_count); 279 ctx->reserved_count = lock_count; 280 result.os_context = (iptr)ctx; 281 result.region = new; 282 283 Stream sb = arena_stream(*arena); 284 stream_append_s8s(&sb, c_str_to_s8(name), s8("_lock_")); 285 for (u32 i = 0; i < lock_count; i++) { 286 Stream lb = sb; 287 stream_append_u64(&lb, i); 288 stream_append_byte(&lb, 0); 289 ctx->semaphores[i] = CreateSemaphoreA(0, 1, 1, (c8 *)lb.data); 290 if (ctx->semaphores[i] == INVALID_FILE) 291 os_fatal(s8("os_create_shared_memory_area: failed to create semaphore\n")); 292 293 /* NOTE(rnp): hacky garbage because CreateSemaphore will just open an existing 294 * semaphore without any indication. Sometimes the other side of the shared memory 295 * will provide incorrect parameters or will otherwise fail and its faster to 296 * restart this program than to get that application to release the semaphores */ 297 /* TODO(rnp): figure out something more robust */ 298 ReleaseSemaphore(ctx->semaphores[i], 1, 0); 299 } 300 } 301 } 302 return result; 303 } 304 305 function b32 306 os_copy_file(char *name, char *new) 307 { 308 return CopyFileA(name, new, 0); 309 } 310 311 function void * 312 os_load_library(char *name, char *temp_name, Stream *e) 313 { 314 if (temp_name && os_copy_file(name, temp_name)) 315 name = temp_name; 316 317 void *result = LoadLibraryA(name); 318 if (!result && e) { 319 stream_append_s8s(e, s8("os_load_library(\""), c_str_to_s8(name), s8("\"): ")); 320 stream_append_i64(e, GetLastError()); 321 stream_append_byte(e, '\n'); 322 } 323 324 if (temp_name) 325 DeleteFileA(temp_name); 326 327 return result; 328 } 329 330 function void * 331 os_lookup_dynamic_symbol(void *h, char *name, Stream *e) 332 { 333 void *result = 0; 334 if (h) { 335 result = GetProcAddress(h, name); 336 if (!result && e) { 337 stream_append_s8s(e, s8("os_lookup_dynamic_symbol(\""), c_str_to_s8(name), 338 s8("\"): ")); 339 stream_append_i64(e, GetLastError()); 340 stream_append_byte(e, '\n'); 341 } 342 } 343 return result; 344 } 345 346 function void 347 os_unload_library(void *h) 348 { 349 FreeLibrary(h); 350 } 351 352 function OS_ADD_FILE_WATCH_FN(os_add_file_watch) 353 { 354 s8 directory = path; 355 directory.len = s8_scan_backwards(path, '\\'); 356 assert(directory.len > 0); 357 358 u64 hash = u64_hash_from_s8(directory); 359 FileWatchDirectory *dir = lookup_file_watch_directory(fwctx, hash); 360 if (!dir) { 361 assert(path.data[directory.len] == '\\'); 362 363 dir = da_push(a, fwctx); 364 dir->hash = hash; 365 dir->name = push_s8(a, directory); 366 dir->handle = CreateFileA((c8 *)dir->name.data, GENERIC_READ, FILE_SHARE_READ, 0, 367 OPEN_EXISTING, 368 FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED, 0); 369 370 w32_io_completion_event *event = push_struct(a, typeof(*event)); 371 event->tag = W32_IO_FILE_WATCH; 372 event->context = (iptr)dir; 373 CreateIoCompletionPort(dir->handle, os_w32_context.io_completion_handle, (uptr)event, 0); 374 375 dir->buffer = sub_arena(a, 4096 + sizeof(w32_overlapped), 64); 376 w32_overlapped *overlapped = (w32_overlapped *)(dir->buffer.beg + 4096); 377 zero_struct(overlapped); 378 379 ReadDirectoryChangesW(dir->handle, dir->buffer.beg, 4096, 0, 380 FILE_NOTIFY_CHANGE_LAST_WRITE, 0, overlapped, 0); 381 } 382 383 FileWatch *fw = da_push(a, dir); 384 fw->user_data = user_data; 385 fw->callback = callback; 386 fw->hash = u64_hash_from_s8(s8_cut_head(path, dir->name.len + 1)); 387 } 388 389 function iptr 390 os_create_thread(Arena arena, iptr user_context, s8 name, os_thread_entry_point_fn *fn) 391 { 392 iptr result = CreateThread(0, 0, (iptr)fn, user_context, 0, 0); 393 SetThreadDescription(result, s8_to_s16(&arena, name).data); 394 return result; 395 } 396 397 function OS_WAIT_ON_VALUE_FN(os_wait_on_value) 398 { 399 return WaitOnAddress(value, ¤t, sizeof(*value), timeout_ms); 400 } 401 402 function OS_WAKE_WAITERS_FN(os_wake_waiters) 403 { 404 if (sync) { 405 atomic_store_u32(sync, 0); 406 WakeByAddressAll(sync); 407 } 408 } 409 410 function OS_SHARED_MEMORY_LOCK_REGION_FN(os_shared_memory_region_lock) 411 { 412 w32_shared_memory_context *ctx = (typeof(ctx))sm->os_context; 413 b32 result = !WaitForSingleObject(ctx->semaphores[lock_index], timeout_ms); 414 if (result) atomic_store_u32(locks + lock_index, 1); 415 return result; 416 } 417 418 function OS_SHARED_MEMORY_UNLOCK_REGION_FN(os_shared_memory_region_unlock) 419 { 420 w32_shared_memory_context *ctx = (typeof(ctx))sm->os_context; 421 assert(atomic_load_u32(locks + lock_index)); 422 os_wake_waiters(locks + lock_index); 423 ReleaseSemaphore(ctx->semaphores[lock_index], 1, 0); 424 }