platform-windows.c 31 KB

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