platform-windows.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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. #ifdef DEBUG
  946. __debugbreak();
  947. #else
  948. RaiseException(ERROR_OUTOFMEMORY, EXCEPTION_NONCONTINUABLE, 0, NULL);
  949. #endif
  950. }
  951. DWORD num_logical_cores(ULONG_PTR mask)
  952. {
  953. DWORD left_shift = sizeof(ULONG_PTR) * 8 - 1;
  954. DWORD bit_set_count = 0;
  955. ULONG_PTR bit_test = (ULONG_PTR)1 << left_shift;
  956. for (DWORD i = 0; i <= left_shift; ++i) {
  957. bit_set_count += ((mask & bit_test) ? 1 : 0);
  958. bit_test /= 2;
  959. }
  960. return bit_set_count;
  961. }
  962. static int physical_cores = 0;
  963. static int logical_cores = 0;
  964. static bool core_count_initialized = false;
  965. static void os_get_cores_internal(void)
  966. {
  967. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION info = NULL, temp = NULL;
  968. DWORD len = 0;
  969. if (core_count_initialized)
  970. return;
  971. core_count_initialized = true;
  972. GetLogicalProcessorInformation(info, &len);
  973. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  974. return;
  975. info = malloc(len);
  976. if (info) {
  977. if (GetLogicalProcessorInformation(info, &len)) {
  978. DWORD num = len / sizeof(*info);
  979. temp = info;
  980. for (DWORD i = 0; i < num; i++) {
  981. if (temp->Relationship == RelationProcessorCore) {
  982. ULONG_PTR mask = temp->ProcessorMask;
  983. physical_cores++;
  984. logical_cores += num_logical_cores(mask);
  985. }
  986. temp++;
  987. }
  988. }
  989. free(info);
  990. }
  991. }
  992. int os_get_physical_cores(void)
  993. {
  994. if (!core_count_initialized)
  995. os_get_cores_internal();
  996. return physical_cores;
  997. }
  998. int os_get_logical_cores(void)
  999. {
  1000. if (!core_count_initialized)
  1001. os_get_cores_internal();
  1002. return logical_cores;
  1003. }
  1004. static inline bool os_get_sys_memory_usage_internal(MEMORYSTATUSEX *msex)
  1005. {
  1006. if (!GlobalMemoryStatusEx(msex))
  1007. return false;
  1008. return true;
  1009. }
  1010. uint64_t os_get_sys_free_size(void)
  1011. {
  1012. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  1013. if (!os_get_sys_memory_usage_internal(&msex))
  1014. return 0;
  1015. return msex.ullAvailPhys;
  1016. }
  1017. static uint64_t total_memory = 0;
  1018. static bool total_memory_initialized = false;
  1019. static void os_get_sys_total_size_internal()
  1020. {
  1021. total_memory_initialized = true;
  1022. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  1023. if (!os_get_sys_memory_usage_internal(&msex))
  1024. return;
  1025. total_memory = msex.ullTotalPhys;
  1026. }
  1027. uint64_t os_get_sys_total_size(void)
  1028. {
  1029. if (!total_memory_initialized)
  1030. os_get_sys_total_size_internal();
  1031. return total_memory;
  1032. }
  1033. static inline bool os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc)
  1034. {
  1035. if (!GetProcessMemoryInfo(GetCurrentProcess(), pmc, sizeof(*pmc)))
  1036. return false;
  1037. return true;
  1038. }
  1039. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  1040. {
  1041. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1042. if (!os_get_proc_memory_usage_internal(&pmc))
  1043. return false;
  1044. usage->resident_size = pmc.WorkingSetSize;
  1045. usage->virtual_size = pmc.PagefileUsage;
  1046. return true;
  1047. }
  1048. uint64_t os_get_proc_resident_size(void)
  1049. {
  1050. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1051. if (!os_get_proc_memory_usage_internal(&pmc))
  1052. return 0;
  1053. return pmc.WorkingSetSize;
  1054. }
  1055. uint64_t os_get_proc_virtual_size(void)
  1056. {
  1057. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1058. if (!os_get_proc_memory_usage_internal(&pmc))
  1059. return 0;
  1060. return pmc.PagefileUsage;
  1061. }
  1062. uint64_t os_get_free_disk_space(const char *dir)
  1063. {
  1064. wchar_t *wdir = NULL;
  1065. os_utf8_to_wcs_ptr(dir, 0, &wdir);
  1066. if (!wdir)
  1067. return 0;
  1068. ULARGE_INTEGER free;
  1069. bool success = !!GetDiskFreeSpaceExW(wdir, &free, NULL, NULL);
  1070. bfree(wdir);
  1071. return success ? free.QuadPart : 0;
  1072. }
  1073. char *os_generate_uuid(void)
  1074. {
  1075. UUID uuid;
  1076. RPC_STATUS res = UuidCreate(&uuid);
  1077. if (res != RPC_S_OK && res != RPC_S_UUID_LOCAL_ONLY)
  1078. bcrash("Failed to get UUID, RPC_STATUS: %l", res);
  1079. struct dstr uuid_str = {0};
  1080. dstr_printf(&uuid_str, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid.Data1, uuid.Data2, uuid.Data3,
  1081. uuid.Data4[0], uuid.Data4[1], uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], uuid.Data4[5],
  1082. uuid.Data4[6], uuid.Data4[7]);
  1083. return uuid_str.array;
  1084. }