1
0

platform-windows.c 32 KB

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