platform-windows.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. /*
  2. * Copyright (c) 2023 Lain Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include <windows.h>
  17. #include <mmsystem.h>
  18. #include <shellapi.h>
  19. #include <shlobj.h>
  20. #include <intrin.h>
  21. #include <psapi.h>
  22. #include <math.h>
  23. #include <rpc.h>
  24. #include "base.h"
  25. #include "platform.h"
  26. #include "darray.h"
  27. #include "dstr.h"
  28. #include "util_uint64.h"
  29. #include "windows/win-registry.h"
  30. #include "windows/win-version.h"
  31. #include "../../deps/w32-pthreads/pthread.h"
  32. #define MAX_SZ_LEN 256
  33. static bool have_clockfreq = false;
  34. static LARGE_INTEGER clock_freq;
  35. static uint32_t winver = 0;
  36. static char win_release_id[MAX_SZ_LEN] = "unavailable";
  37. static inline uint64_t get_clockfreq(void)
  38. {
  39. if (!have_clockfreq) {
  40. QueryPerformanceFrequency(&clock_freq);
  41. have_clockfreq = true;
  42. }
  43. return clock_freq.QuadPart;
  44. }
  45. static inline uint32_t get_winver(void)
  46. {
  47. if (!winver) {
  48. struct win_version_info ver;
  49. get_win_ver(&ver);
  50. winver = (ver.major << 8) | ver.minor;
  51. }
  52. return winver;
  53. }
  54. void *os_dlopen(const char *path)
  55. {
  56. struct dstr dll_name;
  57. wchar_t *wpath;
  58. wchar_t *wpath_slash;
  59. HMODULE h_library = NULL;
  60. if (!path)
  61. return NULL;
  62. dstr_init_copy(&dll_name, path);
  63. dstr_replace(&dll_name, "\\", "/");
  64. if (!dstr_find(&dll_name, ".dll"))
  65. dstr_cat(&dll_name, ".dll");
  66. os_utf8_to_wcs_ptr(dll_name.array, 0, &wpath);
  67. dstr_free(&dll_name);
  68. /* to make module dependency issues easier to deal with, allow
  69. * dynamically loaded libraries on windows to search for dependent
  70. * libraries that are within the library's own directory */
  71. wpath_slash = wcsrchr(wpath, L'/');
  72. if (wpath_slash) {
  73. *wpath_slash = 0;
  74. SetDllDirectoryW(wpath);
  75. *wpath_slash = L'/';
  76. }
  77. h_library = LoadLibraryW(wpath);
  78. bfree(wpath);
  79. if (wpath_slash)
  80. SetDllDirectoryW(NULL);
  81. if (!h_library) {
  82. DWORD error = GetLastError();
  83. /* don't print error for libraries that aren't meant to be
  84. * dynamically linked */
  85. if (error == ERROR_PROC_NOT_FOUND)
  86. return NULL;
  87. char *message = NULL;
  88. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
  89. FORMAT_MESSAGE_ALLOCATE_BUFFER,
  90. NULL, error, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPSTR)&message, 0, NULL);
  91. blog(LOG_INFO, "LoadLibrary failed for '%s': %s (%lu)", path, message, error);
  92. if (message)
  93. LocalFree(message);
  94. }
  95. return h_library;
  96. }
  97. void *os_dlsym(void *module, const char *func)
  98. {
  99. void *handle;
  100. handle = (void *)GetProcAddress(module, func);
  101. return handle;
  102. }
  103. void os_dlclose(void *module)
  104. {
  105. FreeLibrary(module);
  106. }
  107. static bool has_obs_export(VOID *base, PIMAGE_NT_HEADERS nt_headers)
  108. {
  109. __try {
  110. PIMAGE_DATA_DIRECTORY data_dir;
  111. data_dir = &nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  112. if (data_dir->Size == 0)
  113. return false;
  114. PIMAGE_SECTION_HEADER section, last_section;
  115. section = IMAGE_FIRST_SECTION(nt_headers);
  116. last_section = section;
  117. /* find the section that contains the export directory */
  118. int i;
  119. for (i = 0; i < nt_headers->FileHeader.NumberOfSections; i++) {
  120. if (section->VirtualAddress <= data_dir->VirtualAddress) {
  121. last_section = section;
  122. section++;
  123. continue;
  124. } else {
  125. break;
  126. }
  127. }
  128. /* double check in case we exited early */
  129. if (last_section->VirtualAddress > data_dir->VirtualAddress ||
  130. section->VirtualAddress <= data_dir->VirtualAddress)
  131. return false;
  132. section = last_section;
  133. /* get a pointer to the export directory */
  134. PIMAGE_EXPORT_DIRECTORY export;
  135. export = (PIMAGE_EXPORT_DIRECTORY)((byte *)base + data_dir->VirtualAddress - section->VirtualAddress +
  136. section->PointerToRawData);
  137. if (export->NumberOfNames == 0)
  138. return false;
  139. /* get a pointer to the export directory names */
  140. DWORD *names_ptr;
  141. names_ptr = (DWORD *)((byte *)base + export->AddressOfNames - section->VirtualAddress +
  142. section->PointerToRawData);
  143. /* iterate through each name and see if its an obs plugin */
  144. CHAR *name;
  145. size_t j;
  146. for (j = 0; j < export->NumberOfNames; j++) {
  147. name = (CHAR *)base + names_ptr[j] - section->VirtualAddress + section->PointerToRawData;
  148. if (!strcmp(name, "obs_module_load")) {
  149. return true;
  150. }
  151. }
  152. } __except (EXCEPTION_EXECUTE_HANDLER) {
  153. /* we failed somehow, for compatibility let's assume it
  154. * was a valid plugin and let the loader deal with it */
  155. return true;
  156. }
  157. return false;
  158. }
  159. void get_plugin_info(const char *path, bool *is_obs_plugin)
  160. {
  161. struct dstr dll_name;
  162. wchar_t *wpath;
  163. HANDLE hFile = INVALID_HANDLE_VALUE;
  164. HANDLE hFileMapping = NULL;
  165. VOID *base = NULL;
  166. PIMAGE_DOS_HEADER dos_header;
  167. PIMAGE_NT_HEADERS nt_headers;
  168. *is_obs_plugin = false;
  169. if (!path)
  170. return;
  171. dstr_init_copy(&dll_name, path);
  172. dstr_replace(&dll_name, "\\", "/");
  173. if (!dstr_find(&dll_name, ".dll"))
  174. dstr_cat(&dll_name, ".dll");
  175. os_utf8_to_wcs_ptr(dll_name.array, 0, &wpath);
  176. dstr_free(&dll_name);
  177. hFile = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  178. bfree(wpath);
  179. if (hFile == INVALID_HANDLE_VALUE)
  180. goto cleanup;
  181. hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  182. if (hFileMapping == NULL)
  183. goto cleanup;
  184. base = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
  185. if (!base)
  186. goto cleanup;
  187. /* all mapped file i/o must be prepared to handle exceptions */
  188. __try {
  189. dos_header = (PIMAGE_DOS_HEADER)base;
  190. if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
  191. goto cleanup;
  192. nt_headers = (PIMAGE_NT_HEADERS)((byte *)dos_header + dos_header->e_lfanew);
  193. if (nt_headers->Signature != IMAGE_NT_SIGNATURE)
  194. goto cleanup;
  195. *is_obs_plugin = has_obs_export(base, nt_headers);
  196. } __except (EXCEPTION_EXECUTE_HANDLER) {
  197. /* we failed somehow, for compatibility let's assume it
  198. * was a valid plugin and let the loader deal with it */
  199. *is_obs_plugin = true;
  200. goto cleanup;
  201. }
  202. cleanup:
  203. if (base)
  204. UnmapViewOfFile(base);
  205. if (hFileMapping != NULL)
  206. CloseHandle(hFileMapping);
  207. if (hFile != INVALID_HANDLE_VALUE)
  208. CloseHandle(hFile);
  209. }
  210. bool os_is_obs_plugin(const char *path)
  211. {
  212. bool is_obs_plugin;
  213. get_plugin_info(path, &is_obs_plugin);
  214. return is_obs_plugin;
  215. }
  216. union time_data {
  217. FILETIME ft;
  218. unsigned long long val;
  219. };
  220. struct os_cpu_usage_info {
  221. union time_data last_time, last_sys_time, last_user_time;
  222. DWORD core_count;
  223. };
  224. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  225. {
  226. struct os_cpu_usage_info *info = bzalloc(sizeof(*info));
  227. SYSTEM_INFO si;
  228. FILETIME dummy;
  229. GetSystemInfo(&si);
  230. GetSystemTimeAsFileTime(&info->last_time.ft);
  231. GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, &info->last_sys_time.ft, &info->last_user_time.ft);
  232. info->core_count = si.dwNumberOfProcessors;
  233. return info;
  234. }
  235. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  236. {
  237. union time_data cur_time, cur_sys_time, cur_user_time;
  238. FILETIME dummy;
  239. double percent;
  240. if (!info)
  241. return 0.0;
  242. GetSystemTimeAsFileTime(&cur_time.ft);
  243. GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, &cur_sys_time.ft, &cur_user_time.ft);
  244. percent = (double)(cur_sys_time.val - info->last_sys_time.val + (cur_user_time.val - info->last_user_time.val));
  245. percent /= (double)(cur_time.val - info->last_time.val);
  246. percent /= (double)info->core_count;
  247. info->last_time.val = cur_time.val;
  248. info->last_sys_time.val = cur_sys_time.val;
  249. info->last_user_time.val = cur_user_time.val;
  250. return percent * 100.0;
  251. }
  252. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  253. {
  254. if (info)
  255. bfree(info);
  256. }
  257. bool os_sleepto_ns(uint64_t time_target)
  258. {
  259. const uint64_t freq = get_clockfreq();
  260. const LONGLONG count_target = util_mul_div64(time_target, freq, 1000000000);
  261. LARGE_INTEGER count;
  262. QueryPerformanceCounter(&count);
  263. const bool stall = count.QuadPart < count_target;
  264. if (stall) {
  265. const DWORD milliseconds = (DWORD)(((count_target - count.QuadPart) * 1000.0) / freq);
  266. if (milliseconds > 1)
  267. Sleep(milliseconds - 1);
  268. for (;;) {
  269. QueryPerformanceCounter(&count);
  270. if (count.QuadPart >= count_target)
  271. break;
  272. YieldProcessor();
  273. }
  274. }
  275. return stall;
  276. }
  277. bool os_sleepto_ns_fast(uint64_t time_target)
  278. {
  279. uint64_t current = os_gettime_ns();
  280. if (time_target < current)
  281. return false;
  282. do {
  283. uint64_t remain_ms = (time_target - current) / 1000000;
  284. if (!remain_ms)
  285. remain_ms = 1;
  286. Sleep((DWORD)remain_ms);
  287. current = os_gettime_ns();
  288. } while (time_target > current);
  289. return true;
  290. }
  291. void os_sleep_ms(uint32_t duration)
  292. {
  293. /* windows 8+ appears to have decreased sleep precision */
  294. if (get_winver() >= 0x0602 && duration > 0)
  295. duration--;
  296. Sleep(duration);
  297. }
  298. uint64_t os_gettime_ns(void)
  299. {
  300. LARGE_INTEGER current_time;
  301. QueryPerformanceCounter(&current_time);
  302. return util_mul_div64(current_time.QuadPart, 1000000000, get_clockfreq());
  303. }
  304. /* returns [folder]\[name] on windows */
  305. static int os_get_path_internal(char *dst, size_t size, const char *name, int folder)
  306. {
  307. wchar_t path_utf16[MAX_PATH];
  308. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path_utf16);
  309. if (os_wcs_to_utf8(path_utf16, 0, dst, size) != 0) {
  310. if (!name || !*name) {
  311. return (int)strlen(dst);
  312. }
  313. if (strcat_s(dst, size, "\\") == 0) {
  314. if (strcat_s(dst, size, name) == 0) {
  315. return (int)strlen(dst);
  316. }
  317. }
  318. }
  319. return -1;
  320. }
  321. static char *os_get_path_ptr_internal(const char *name, int folder)
  322. {
  323. char *ptr;
  324. wchar_t path_utf16[MAX_PATH];
  325. struct dstr path;
  326. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path_utf16);
  327. os_wcs_to_utf8_ptr(path_utf16, 0, &ptr);
  328. dstr_init_move_array(&path, ptr);
  329. dstr_cat(&path, "\\");
  330. dstr_cat(&path, name);
  331. return path.array;
  332. }
  333. int os_get_config_path(char *dst, size_t size, const char *name)
  334. {
  335. return os_get_path_internal(dst, size, name, CSIDL_APPDATA);
  336. }
  337. char *os_get_config_path_ptr(const char *name)
  338. {
  339. return os_get_path_ptr_internal(name, CSIDL_APPDATA);
  340. }
  341. int os_get_program_data_path(char *dst, size_t size, const char *name)
  342. {
  343. return os_get_path_internal(dst, size, name, CSIDL_COMMON_APPDATA);
  344. }
  345. char *os_get_program_data_path_ptr(const char *name)
  346. {
  347. return os_get_path_ptr_internal(name, CSIDL_COMMON_APPDATA);
  348. }
  349. char *os_get_executable_path_ptr(const char *name)
  350. {
  351. char *ptr;
  352. char *slash;
  353. wchar_t path_utf16[MAX_PATH];
  354. struct dstr path;
  355. GetModuleFileNameW(NULL, path_utf16, MAX_PATH);
  356. os_wcs_to_utf8_ptr(path_utf16, 0, &ptr);
  357. dstr_init_move_array(&path, ptr);
  358. dstr_replace(&path, "\\", "/");
  359. slash = strrchr(path.array, '/');
  360. if (slash) {
  361. size_t len = slash - path.array + 1;
  362. dstr_resize(&path, len);
  363. }
  364. if (name && *name) {
  365. dstr_cat(&path, name);
  366. }
  367. return path.array;
  368. }
  369. bool os_file_exists(const char *path)
  370. {
  371. WIN32_FIND_DATAW wfd;
  372. HANDLE hFind;
  373. wchar_t *path_utf16;
  374. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  375. return false;
  376. hFind = FindFirstFileW(path_utf16, &wfd);
  377. if (hFind != INVALID_HANDLE_VALUE)
  378. FindClose(hFind);
  379. bfree(path_utf16);
  380. return hFind != INVALID_HANDLE_VALUE;
  381. }
  382. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  383. {
  384. wchar_t wpath[MAX_PATH];
  385. wchar_t wabspath[MAX_PATH];
  386. size_t out_len = 0;
  387. size_t len;
  388. if (!abspath)
  389. return 0;
  390. len = os_utf8_to_wcs(path, 0, wpath, MAX_PATH);
  391. if (!len)
  392. return 0;
  393. if (_wfullpath(wabspath, wpath, MAX_PATH) != NULL)
  394. out_len = os_wcs_to_utf8(wabspath, 0, abspath, size);
  395. return out_len;
  396. }
  397. char *os_get_abs_path_ptr(const char *path)
  398. {
  399. char *ptr = bmalloc(MAX_PATH);
  400. if (!os_get_abs_path(path, ptr, MAX_PATH)) {
  401. bfree(ptr);
  402. ptr = NULL;
  403. }
  404. return ptr;
  405. }
  406. struct os_dir {
  407. HANDLE handle;
  408. WIN32_FIND_DATA wfd;
  409. bool first;
  410. struct os_dirent out;
  411. };
  412. os_dir_t *os_opendir(const char *path)
  413. {
  414. struct dstr path_str = {0};
  415. struct os_dir *dir = NULL;
  416. WIN32_FIND_DATA wfd;
  417. HANDLE handle;
  418. wchar_t *w_path;
  419. dstr_copy(&path_str, path);
  420. dstr_cat(&path_str, "/*.*");
  421. if (os_utf8_to_wcs_ptr(path_str.array, path_str.len, &w_path) > 0) {
  422. handle = FindFirstFileW(w_path, &wfd);
  423. if (handle != INVALID_HANDLE_VALUE) {
  424. dir = bzalloc(sizeof(struct os_dir));
  425. dir->handle = handle;
  426. dir->first = true;
  427. dir->wfd = wfd;
  428. }
  429. bfree(w_path);
  430. }
  431. dstr_free(&path_str);
  432. return dir;
  433. }
  434. static inline bool is_dir(WIN32_FIND_DATA *wfd)
  435. {
  436. return !!(wfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  437. }
  438. struct os_dirent *os_readdir(os_dir_t *dir)
  439. {
  440. if (!dir)
  441. return NULL;
  442. if (dir->first) {
  443. dir->first = false;
  444. } else {
  445. if (!FindNextFileW(dir->handle, &dir->wfd))
  446. return NULL;
  447. }
  448. os_wcs_to_utf8(dir->wfd.cFileName, 0, dir->out.d_name, sizeof(dir->out.d_name));
  449. dir->out.directory = is_dir(&dir->wfd);
  450. return &dir->out;
  451. }
  452. void os_closedir(os_dir_t *dir)
  453. {
  454. if (dir) {
  455. FindClose(dir->handle);
  456. bfree(dir);
  457. }
  458. }
  459. int64_t os_get_free_space(const char *path)
  460. {
  461. ULARGE_INTEGER remainingSpace;
  462. char abs_path[512];
  463. wchar_t w_abs_path[512];
  464. if (os_get_abs_path(path, abs_path, 512) > 0) {
  465. if (os_utf8_to_wcs(abs_path, 0, w_abs_path, 512) > 0) {
  466. BOOL success = GetDiskFreeSpaceExW(w_abs_path, (PULARGE_INTEGER)&remainingSpace, NULL, NULL);
  467. if (success)
  468. return (int64_t)remainingSpace.QuadPart;
  469. }
  470. }
  471. return -1;
  472. }
  473. static void make_globent(struct os_globent *ent, WIN32_FIND_DATA *wfd, const char *pattern)
  474. {
  475. struct dstr name = {0};
  476. struct dstr path = {0};
  477. char *slash;
  478. dstr_from_wcs(&name, wfd->cFileName);
  479. dstr_copy(&path, pattern);
  480. if (path.array) {
  481. slash = strrchr(path.array, '/');
  482. if (slash)
  483. dstr_resize(&path, slash + 1 - path.array);
  484. else
  485. dstr_free(&path);
  486. }
  487. dstr_cat_dstr(&path, &name);
  488. ent->path = path.array;
  489. ent->directory = is_dir(wfd);
  490. dstr_free(&name);
  491. }
  492. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  493. {
  494. DARRAY(struct os_globent) files;
  495. HANDLE handle;
  496. WIN32_FIND_DATA wfd;
  497. int ret = -1;
  498. wchar_t *w_path;
  499. da_init(files);
  500. if (os_utf8_to_wcs_ptr(pattern, 0, &w_path) > 0) {
  501. handle = FindFirstFileW(w_path, &wfd);
  502. if (handle != INVALID_HANDLE_VALUE) {
  503. do {
  504. struct os_globent ent = {0};
  505. make_globent(&ent, &wfd, pattern);
  506. if (ent.path)
  507. da_push_back(files, &ent);
  508. } while (FindNextFile(handle, &wfd));
  509. FindClose(handle);
  510. *pglob = bmalloc(sizeof(**pglob));
  511. (*pglob)->gl_pathc = files.num;
  512. (*pglob)->gl_pathv = files.array;
  513. ret = 0;
  514. }
  515. bfree(w_path);
  516. }
  517. if (ret != 0)
  518. *pglob = NULL;
  519. UNUSED_PARAMETER(flags);
  520. return ret;
  521. }
  522. void os_globfree(os_glob_t *pglob)
  523. {
  524. if (pglob) {
  525. for (size_t i = 0; i < pglob->gl_pathc; i++)
  526. bfree(pglob->gl_pathv[i].path);
  527. bfree(pglob->gl_pathv);
  528. bfree(pglob);
  529. }
  530. }
  531. int os_unlink(const char *path)
  532. {
  533. wchar_t *w_path;
  534. bool success;
  535. os_utf8_to_wcs_ptr(path, 0, &w_path);
  536. if (!w_path)
  537. return -1;
  538. success = !!DeleteFileW(w_path);
  539. bfree(w_path);
  540. return success ? 0 : -1;
  541. }
  542. int os_rmdir(const char *path)
  543. {
  544. wchar_t *w_path;
  545. bool success;
  546. os_utf8_to_wcs_ptr(path, 0, &w_path);
  547. if (!w_path)
  548. return -1;
  549. success = !!RemoveDirectoryW(w_path);
  550. bfree(w_path);
  551. return success ? 0 : -1;
  552. }
  553. int os_mkdir(const char *path)
  554. {
  555. wchar_t *path_utf16;
  556. BOOL success;
  557. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  558. return MKDIR_ERROR;
  559. success = CreateDirectory(path_utf16, NULL);
  560. bfree(path_utf16);
  561. if (!success)
  562. return (GetLastError() == ERROR_ALREADY_EXISTS) ? MKDIR_EXISTS : MKDIR_ERROR;
  563. return MKDIR_SUCCESS;
  564. }
  565. int os_rename(const char *old_path, const char *new_path)
  566. {
  567. wchar_t *old_path_utf16 = NULL;
  568. wchar_t *new_path_utf16 = NULL;
  569. int code = -1;
  570. if (!os_utf8_to_wcs_ptr(old_path, 0, &old_path_utf16)) {
  571. return -1;
  572. }
  573. if (!os_utf8_to_wcs_ptr(new_path, 0, &new_path_utf16)) {
  574. goto error;
  575. }
  576. code = MoveFileExW(old_path_utf16, new_path_utf16, MOVEFILE_REPLACE_EXISTING) ? 0 : -1;
  577. error:
  578. bfree(old_path_utf16);
  579. bfree(new_path_utf16);
  580. return code;
  581. }
  582. int os_safe_replace(const char *target, const char *from, const char *backup)
  583. {
  584. wchar_t *wtarget = NULL;
  585. wchar_t *wfrom = NULL;
  586. wchar_t *wbackup = NULL;
  587. int code = -1;
  588. if (!target || !from)
  589. return -1;
  590. if (!os_utf8_to_wcs_ptr(target, 0, &wtarget))
  591. return -1;
  592. if (!os_utf8_to_wcs_ptr(from, 0, &wfrom))
  593. goto fail;
  594. if (backup && !os_utf8_to_wcs_ptr(backup, 0, &wbackup))
  595. goto fail;
  596. if (ReplaceFileW(wtarget, wfrom, wbackup, 0, NULL, NULL)) {
  597. code = 0;
  598. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  599. code = MoveFileExW(wfrom, wtarget, MOVEFILE_REPLACE_EXISTING) ? 0 : -1;
  600. }
  601. fail:
  602. bfree(wtarget);
  603. bfree(wfrom);
  604. bfree(wbackup);
  605. return code;
  606. }
  607. BOOL WINAPI DllMain(HINSTANCE hinst_dll, DWORD reason, LPVOID reserved)
  608. {
  609. switch (reason) {
  610. case DLL_PROCESS_ATTACH:
  611. timeBeginPeriod(1);
  612. #ifdef PTW32_STATIC_LIB
  613. pthread_win32_process_attach_np();
  614. #endif
  615. break;
  616. case DLL_PROCESS_DETACH:
  617. timeEndPeriod(1);
  618. #ifdef PTW32_STATIC_LIB
  619. pthread_win32_process_detach_np();
  620. #endif
  621. break;
  622. case DLL_THREAD_ATTACH:
  623. #ifdef PTW32_STATIC_LIB
  624. pthread_win32_thread_attach_np();
  625. #endif
  626. break;
  627. case DLL_THREAD_DETACH:
  628. #ifdef PTW32_STATIC_LIB
  629. pthread_win32_thread_detach_np();
  630. #endif
  631. break;
  632. }
  633. UNUSED_PARAMETER(hinst_dll);
  634. UNUSED_PARAMETER(reserved);
  635. return true;
  636. }
  637. os_performance_token_t *os_request_high_performance(const char *reason)
  638. {
  639. UNUSED_PARAMETER(reason);
  640. return NULL;
  641. }
  642. void os_end_high_performance(os_performance_token_t *token)
  643. {
  644. UNUSED_PARAMETER(token);
  645. }
  646. int os_copyfile(const char *file_in, const char *file_out)
  647. {
  648. wchar_t *file_in_utf16 = NULL;
  649. wchar_t *file_out_utf16 = NULL;
  650. int code = -1;
  651. if (!os_utf8_to_wcs_ptr(file_in, 0, &file_in_utf16)) {
  652. return -1;
  653. }
  654. if (!os_utf8_to_wcs_ptr(file_out, 0, &file_out_utf16)) {
  655. goto error;
  656. }
  657. code = CopyFileW(file_in_utf16, file_out_utf16, true) ? 0 : -1;
  658. error:
  659. bfree(file_in_utf16);
  660. bfree(file_out_utf16);
  661. return code;
  662. }
  663. char *os_getcwd(char *path, size_t size)
  664. {
  665. wchar_t *path_w;
  666. DWORD len;
  667. len = GetCurrentDirectoryW(0, NULL);
  668. if (!len)
  669. return NULL;
  670. path_w = bmalloc(((size_t)len + 1) * sizeof(wchar_t));
  671. GetCurrentDirectoryW(len + 1, path_w);
  672. os_wcs_to_utf8(path_w, (size_t)len, path, size);
  673. bfree(path_w);
  674. return path;
  675. }
  676. int os_chdir(const char *path)
  677. {
  678. wchar_t *path_w = NULL;
  679. size_t size;
  680. int ret;
  681. size = os_utf8_to_wcs_ptr(path, 0, &path_w);
  682. if (!path_w)
  683. return -1;
  684. ret = SetCurrentDirectoryW(path_w) ? 0 : -1;
  685. bfree(path_w);
  686. return ret;
  687. }
  688. typedef DWORD(WINAPI *get_file_version_info_size_w_t)(LPCWSTR module, LPDWORD unused);
  689. typedef BOOL(WINAPI *get_file_version_info_w_t)(LPCWSTR module, DWORD unused, DWORD len, LPVOID data);
  690. typedef BOOL(WINAPI *ver_query_value_w_t)(LPVOID data, LPCWSTR subblock, LPVOID *buf, PUINT sizeout);
  691. static get_file_version_info_size_w_t get_file_version_info_size = NULL;
  692. static get_file_version_info_w_t get_file_version_info = NULL;
  693. static ver_query_value_w_t ver_query_value = NULL;
  694. static bool ver_initialized = false;
  695. static bool ver_initialize_success = false;
  696. static bool initialize_version_functions(void)
  697. {
  698. HMODULE ver = GetModuleHandleW(L"version");
  699. ver_initialized = true;
  700. if (!ver) {
  701. ver = LoadLibraryW(L"version");
  702. if (!ver) {
  703. blog(LOG_ERROR, "Failed to load windows "
  704. "version library");
  705. return false;
  706. }
  707. }
  708. get_file_version_info_size = (get_file_version_info_size_w_t)GetProcAddress(ver, "GetFileVersionInfoSizeW");
  709. get_file_version_info = (get_file_version_info_w_t)GetProcAddress(ver, "GetFileVersionInfoW");
  710. ver_query_value = (ver_query_value_w_t)GetProcAddress(ver, "VerQueryValueW");
  711. if (!get_file_version_info_size || !get_file_version_info || !ver_query_value) {
  712. blog(LOG_ERROR, "Failed to load windows version "
  713. "functions");
  714. return false;
  715. }
  716. ver_initialize_success = true;
  717. return true;
  718. }
  719. bool get_dll_ver(const wchar_t *lib, struct win_version_info *ver_info)
  720. {
  721. VS_FIXEDFILEINFO *info = NULL;
  722. UINT len = 0;
  723. BOOL success;
  724. LPVOID data;
  725. DWORD size;
  726. char utf8_lib[512];
  727. if (!ver_initialized && !initialize_version_functions())
  728. return false;
  729. if (!ver_initialize_success)
  730. return false;
  731. os_wcs_to_utf8(lib, 0, utf8_lib, sizeof(utf8_lib));
  732. size = get_file_version_info_size(lib, NULL);
  733. if (!size) {
  734. blog(LOG_ERROR, "Failed to get %s version info size", utf8_lib);
  735. return false;
  736. }
  737. data = bmalloc(size);
  738. if (!get_file_version_info(lib, 0, size, data)) {
  739. blog(LOG_ERROR, "Failed to get %s version info", utf8_lib);
  740. bfree(data);
  741. return false;
  742. }
  743. success = ver_query_value(data, L"\\", (LPVOID *)&info, &len);
  744. if (!success || !info || !len) {
  745. blog(LOG_ERROR, "Failed to get %s version info value", utf8_lib);
  746. bfree(data);
  747. return false;
  748. }
  749. ver_info->major = (int)HIWORD(info->dwFileVersionMS);
  750. ver_info->minor = (int)LOWORD(info->dwFileVersionMS);
  751. ver_info->build = (int)HIWORD(info->dwFileVersionLS);
  752. ver_info->revis = (int)LOWORD(info->dwFileVersionLS);
  753. bfree(data);
  754. return true;
  755. }
  756. bool is_64_bit_windows(void)
  757. {
  758. #if defined(_WIN64)
  759. return true;
  760. #elif defined(_WIN32)
  761. BOOL b64 = false;
  762. return IsWow64Process(GetCurrentProcess(), &b64) && b64;
  763. #endif
  764. }
  765. bool is_arm64_windows(void)
  766. {
  767. #if defined(_M_ARM64) || defined(_M_ARM64EC)
  768. return true;
  769. #else
  770. USHORT processMachine;
  771. USHORT nativeMachine;
  772. bool result = IsWow64Process2(GetCurrentProcess(), &processMachine, &nativeMachine);
  773. return (result && (nativeMachine == IMAGE_FILE_MACHINE_ARM64));
  774. #endif
  775. }
  776. bool os_get_emulation_status(void)
  777. {
  778. #if defined(_M_ARM64) || defined(_M_ARM64EC)
  779. return false;
  780. #else
  781. return is_arm64_windows();
  782. #endif
  783. }
  784. void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, struct reg_dword *info)
  785. {
  786. struct reg_dword reg = {0};
  787. HKEY key;
  788. LSTATUS status;
  789. status = RegOpenKeyEx(hkey, sub_key, 0, KEY_READ, &key);
  790. if (status != ERROR_SUCCESS) {
  791. info->status = status;
  792. info->size = 0;
  793. info->return_value = 0;
  794. return;
  795. }
  796. reg.size = sizeof(reg.return_value);
  797. reg.status = RegQueryValueExW(key, value_name, NULL, NULL, (LPBYTE)&reg.return_value, &reg.size);
  798. RegCloseKey(key);
  799. *info = reg;
  800. }
  801. #define WINVER_REG_KEY L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
  802. static inline void rtl_get_ver(struct win_version_info *ver)
  803. {
  804. HMODULE ntdll = GetModuleHandleW(L"ntdll");
  805. if (!ntdll)
  806. return;
  807. NTSTATUS(WINAPI * get_ver)
  808. (RTL_OSVERSIONINFOEXW *) = (void *)GetProcAddress(ntdll, "RtlGetVersion");
  809. if (!get_ver) {
  810. return;
  811. }
  812. RTL_OSVERSIONINFOEXW osver = {0};
  813. osver.dwOSVersionInfoSize = sizeof(osver);
  814. NTSTATUS s = get_ver(&osver);
  815. if (s < 0) {
  816. return;
  817. }
  818. ver->major = osver.dwMajorVersion;
  819. ver->minor = osver.dwMinorVersion;
  820. ver->build = osver.dwBuildNumber;
  821. ver->revis = 0;
  822. }
  823. static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf, DWORD size)
  824. {
  825. const LSTATUS status = RegGetValueW(key, NULL, val, RRF_RT_REG_SZ, NULL, buf, &size);
  826. return status == ERROR_SUCCESS;
  827. }
  828. static inline void get_reg_ver(struct win_version_info *ver)
  829. {
  830. HKEY key;
  831. DWORD size, dw_val;
  832. LSTATUS status;
  833. wchar_t str[MAX_SZ_LEN];
  834. status = RegOpenKeyW(HKEY_LOCAL_MACHINE, WINVER_REG_KEY, &key);
  835. if (status != ERROR_SUCCESS)
  836. return;
  837. size = sizeof(dw_val);
  838. status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size);
  839. if (status == ERROR_SUCCESS)
  840. ver->major = (int)dw_val;
  841. status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size);
  842. if (status == ERROR_SUCCESS)
  843. ver->minor = (int)dw_val;
  844. status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val, &size);
  845. if (status == ERROR_SUCCESS)
  846. ver->revis = (int)dw_val;
  847. if (get_reg_sz(key, L"CurrentBuildNumber", str, sizeof(str))) {
  848. ver->build = wcstol(str, NULL, 10);
  849. }
  850. const wchar_t *release_key = ver->build > 19041 ? L"DisplayVersion" : L"ReleaseId";
  851. if (get_reg_sz(key, release_key, str, sizeof(str))) {
  852. os_wcs_to_utf8(str, 0, win_release_id, MAX_SZ_LEN);
  853. }
  854. RegCloseKey(key);
  855. }
  856. static inline bool version_higher(struct win_version_info *cur, struct win_version_info *new)
  857. {
  858. if (new->major > cur->major) {
  859. return true;
  860. }
  861. if (new->major == cur->major) {
  862. if (new->minor > cur->minor) {
  863. return true;
  864. }
  865. if (new->minor == cur->minor) {
  866. if (new->build > cur->build) {
  867. return true;
  868. }
  869. if (new->build == cur->build) {
  870. return new->revis > cur->revis;
  871. }
  872. }
  873. }
  874. return false;
  875. }
  876. static inline void use_higher_ver(struct win_version_info *cur, struct win_version_info *new)
  877. {
  878. if (version_higher(cur, new))
  879. *cur = *new;
  880. }
  881. void get_win_ver(struct win_version_info *info)
  882. {
  883. static struct win_version_info ver = {0};
  884. static bool got_version = false;
  885. if (!info)
  886. return;
  887. if (!got_version) {
  888. struct win_version_info reg_ver = {0};
  889. struct win_version_info rtl_ver = {0};
  890. struct win_version_info nto_ver = {0};
  891. get_reg_ver(&reg_ver);
  892. rtl_get_ver(&rtl_ver);
  893. get_dll_ver(L"ntoskrnl.exe", &nto_ver);
  894. ver = reg_ver;
  895. use_higher_ver(&ver, &rtl_ver);
  896. use_higher_ver(&ver, &nto_ver);
  897. got_version = true;
  898. }
  899. *info = ver;
  900. }
  901. const char *get_win_release_id(void)
  902. {
  903. return win_release_id;
  904. }
  905. uint32_t get_win_ver_int(void)
  906. {
  907. return get_winver();
  908. }
  909. struct os_inhibit_info {
  910. bool active;
  911. };
  912. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  913. {
  914. UNUSED_PARAMETER(reason);
  915. return bzalloc(sizeof(struct os_inhibit_info));
  916. }
  917. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  918. {
  919. if (!info)
  920. return false;
  921. if (info->active == active)
  922. return false;
  923. if (active) {
  924. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED |
  925. ES_DISPLAY_REQUIRED);
  926. } else {
  927. SetThreadExecutionState(ES_CONTINUOUS);
  928. }
  929. info->active = active;
  930. return true;
  931. }
  932. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  933. {
  934. if (info) {
  935. os_inhibit_sleep_set_active(info, false);
  936. bfree(info);
  937. }
  938. }
  939. void os_breakpoint(void)
  940. {
  941. __debugbreak();
  942. }
  943. void os_oom(void)
  944. {
  945. __debugbreak();
  946. }
  947. DWORD num_logical_cores(ULONG_PTR mask)
  948. {
  949. DWORD left_shift = sizeof(ULONG_PTR) * 8 - 1;
  950. DWORD bit_set_count = 0;
  951. ULONG_PTR bit_test = (ULONG_PTR)1 << left_shift;
  952. for (DWORD i = 0; i <= left_shift; ++i) {
  953. bit_set_count += ((mask & bit_test) ? 1 : 0);
  954. bit_test /= 2;
  955. }
  956. return bit_set_count;
  957. }
  958. static int physical_cores = 0;
  959. static int logical_cores = 0;
  960. static bool core_count_initialized = false;
  961. static void os_get_cores_internal(void)
  962. {
  963. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION info = NULL, temp = NULL;
  964. DWORD len = 0;
  965. if (core_count_initialized)
  966. return;
  967. core_count_initialized = true;
  968. GetLogicalProcessorInformation(info, &len);
  969. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  970. return;
  971. info = malloc(len);
  972. if (info) {
  973. if (GetLogicalProcessorInformation(info, &len)) {
  974. DWORD num = len / sizeof(*info);
  975. temp = info;
  976. for (DWORD i = 0; i < num; i++) {
  977. if (temp->Relationship == RelationProcessorCore) {
  978. ULONG_PTR mask = temp->ProcessorMask;
  979. physical_cores++;
  980. logical_cores += num_logical_cores(mask);
  981. }
  982. temp++;
  983. }
  984. }
  985. free(info);
  986. }
  987. }
  988. int os_get_physical_cores(void)
  989. {
  990. if (!core_count_initialized)
  991. os_get_cores_internal();
  992. return physical_cores;
  993. }
  994. int os_get_logical_cores(void)
  995. {
  996. if (!core_count_initialized)
  997. os_get_cores_internal();
  998. return logical_cores;
  999. }
  1000. static inline bool os_get_sys_memory_usage_internal(MEMORYSTATUSEX *msex)
  1001. {
  1002. if (!GlobalMemoryStatusEx(msex))
  1003. return false;
  1004. return true;
  1005. }
  1006. uint64_t os_get_sys_free_size(void)
  1007. {
  1008. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  1009. if (!os_get_sys_memory_usage_internal(&msex))
  1010. return 0;
  1011. return msex.ullAvailPhys;
  1012. }
  1013. static uint64_t total_memory = 0;
  1014. static bool total_memory_initialized = false;
  1015. static void os_get_sys_total_size_internal()
  1016. {
  1017. total_memory_initialized = true;
  1018. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  1019. if (!os_get_sys_memory_usage_internal(&msex))
  1020. return;
  1021. total_memory = msex.ullTotalPhys;
  1022. }
  1023. uint64_t os_get_sys_total_size(void)
  1024. {
  1025. if (!total_memory_initialized)
  1026. os_get_sys_total_size_internal();
  1027. return total_memory;
  1028. }
  1029. static inline bool os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc)
  1030. {
  1031. if (!GetProcessMemoryInfo(GetCurrentProcess(), pmc, sizeof(*pmc)))
  1032. return false;
  1033. return true;
  1034. }
  1035. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  1036. {
  1037. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1038. if (!os_get_proc_memory_usage_internal(&pmc))
  1039. return false;
  1040. usage->resident_size = pmc.WorkingSetSize;
  1041. usage->virtual_size = pmc.PagefileUsage;
  1042. return true;
  1043. }
  1044. uint64_t os_get_proc_resident_size(void)
  1045. {
  1046. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1047. if (!os_get_proc_memory_usage_internal(&pmc))
  1048. return 0;
  1049. return pmc.WorkingSetSize;
  1050. }
  1051. uint64_t os_get_proc_virtual_size(void)
  1052. {
  1053. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1054. if (!os_get_proc_memory_usage_internal(&pmc))
  1055. return 0;
  1056. return pmc.PagefileUsage;
  1057. }
  1058. uint64_t os_get_free_disk_space(const char *dir)
  1059. {
  1060. wchar_t *wdir = NULL;
  1061. os_utf8_to_wcs_ptr(dir, 0, &wdir);
  1062. if (!wdir)
  1063. return 0;
  1064. ULARGE_INTEGER free;
  1065. bool success = !!GetDiskFreeSpaceExW(wdir, &free, NULL, NULL);
  1066. bfree(wdir);
  1067. return success ? free.QuadPart : 0;
  1068. }
  1069. char *os_generate_uuid(void)
  1070. {
  1071. UUID uuid;
  1072. RPC_STATUS res = UuidCreate(&uuid);
  1073. if (res != RPC_S_OK && res != RPC_S_UUID_LOCAL_ONLY)
  1074. bcrash("Failed to get UUID, RPC_STATUS: %l", res);
  1075. struct dstr uuid_str = {0};
  1076. dstr_printf(&uuid_str, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid.Data1, uuid.Data2, uuid.Data3,
  1077. uuid.Data4[0], uuid.Data4[1], uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], uuid.Data4[5],
  1078. uuid.Data4[6], uuid.Data4[7]);
  1079. return uuid_str.array;
  1080. }