platform-windows.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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 "base.h"
  23. #include "platform.h"
  24. #include "darray.h"
  25. #include "dstr.h"
  26. #include "windows/win-version.h"
  27. #include "../../deps/w32-pthreads/pthread.h"
  28. static bool have_clockfreq = false;
  29. static LARGE_INTEGER clock_freq;
  30. static uint32_t winver = 0;
  31. static inline uint64_t get_clockfreq(void)
  32. {
  33. if (!have_clockfreq)
  34. QueryPerformanceFrequency(&clock_freq);
  35. return clock_freq.QuadPart;
  36. }
  37. static inline uint32_t get_winver(void)
  38. {
  39. if (!winver) {
  40. struct win_version_info ver;
  41. get_win_ver(&ver);
  42. winver = (ver.major << 16) | ver.minor;
  43. }
  44. return winver;
  45. }
  46. void *os_dlopen(const char *path)
  47. {
  48. struct dstr dll_name;
  49. wchar_t *wpath;
  50. wchar_t *wpath_slash;
  51. HMODULE h_library = NULL;
  52. if (!path)
  53. return NULL;
  54. dstr_init_copy(&dll_name, path);
  55. dstr_replace(&dll_name, "\\", "/");
  56. if (!dstr_find(&dll_name, ".dll"))
  57. dstr_cat(&dll_name, ".dll");
  58. os_utf8_to_wcs_ptr(dll_name.array, 0, &wpath);
  59. /* to make module dependency issues easier to deal with, allow
  60. * dynamically loaded libraries on windows to search for dependent
  61. * libraries that are within the library's own directory */
  62. wpath_slash = wcsrchr(wpath, L'/');
  63. if (wpath_slash) {
  64. *wpath_slash = 0;
  65. SetDllDirectoryW(wpath);
  66. *wpath_slash = L'/';
  67. }
  68. h_library = LoadLibraryW(wpath);
  69. bfree(wpath);
  70. dstr_free(&dll_name);
  71. if (wpath_slash)
  72. SetDllDirectoryW(NULL);
  73. if (!h_library) {
  74. DWORD error = GetLastError();
  75. char *message = NULL;
  76. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
  77. FORMAT_MESSAGE_IGNORE_INSERTS |
  78. FORMAT_MESSAGE_ALLOCATE_BUFFER,
  79. NULL, error,
  80. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  81. (LPSTR)&message, 0, NULL);
  82. blog(LOG_INFO, "LoadLibrary failed for '%s': %s (%lu)",
  83. path, message, error);
  84. if (message)
  85. LocalFree(message);
  86. }
  87. return h_library;
  88. }
  89. void *os_dlsym(void *module, const char *func)
  90. {
  91. void *handle;
  92. handle = (void*)GetProcAddress(module, func);
  93. return handle;
  94. }
  95. void os_dlclose(void *module)
  96. {
  97. FreeLibrary(module);
  98. }
  99. union time_data {
  100. FILETIME ft;
  101. unsigned long long val;
  102. };
  103. struct os_cpu_usage_info {
  104. union time_data last_time, last_sys_time, last_user_time;
  105. DWORD core_count;
  106. };
  107. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  108. {
  109. struct os_cpu_usage_info *info = bzalloc(sizeof(*info));
  110. SYSTEM_INFO si;
  111. FILETIME dummy;
  112. GetSystemInfo(&si);
  113. GetSystemTimeAsFileTime(&info->last_time.ft);
  114. GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
  115. &info->last_sys_time.ft, &info->last_user_time.ft);
  116. info->core_count = si.dwNumberOfProcessors;
  117. return info;
  118. }
  119. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  120. {
  121. union time_data cur_time, cur_sys_time, cur_user_time;
  122. FILETIME dummy;
  123. double percent;
  124. if (!info)
  125. return 0.0;
  126. GetSystemTimeAsFileTime(&cur_time.ft);
  127. GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
  128. &cur_sys_time.ft, &cur_user_time.ft);
  129. percent = (double)(cur_sys_time.val - info->last_sys_time.val +
  130. (cur_user_time.val - info->last_user_time.val));
  131. percent /= (double)(cur_time.val - info->last_time.val);
  132. percent /= (double)info->core_count;
  133. info->last_time.val = cur_time.val;
  134. info->last_sys_time.val = cur_sys_time.val;
  135. info->last_user_time.val = cur_user_time.val;
  136. return percent * 100.0;
  137. }
  138. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  139. {
  140. if (info)
  141. bfree(info);
  142. }
  143. bool os_sleepto_ns(uint64_t time_target)
  144. {
  145. uint64_t t = os_gettime_ns();
  146. uint32_t milliseconds;
  147. if (t >= time_target)
  148. return false;
  149. milliseconds = (uint32_t)((time_target - t)/1000000);
  150. if (milliseconds > 1)
  151. Sleep(milliseconds-1);
  152. for (;;) {
  153. t = os_gettime_ns();
  154. if (t >= time_target)
  155. return true;
  156. #if 0
  157. Sleep(1);
  158. #else
  159. Sleep(0);
  160. #endif
  161. }
  162. }
  163. void os_sleep_ms(uint32_t duration)
  164. {
  165. /* windows 8+ appears to have decreased sleep precision */
  166. if (get_winver() >= 0x0602 && duration > 0)
  167. duration--;
  168. Sleep(duration);
  169. }
  170. uint64_t os_gettime_ns(void)
  171. {
  172. LARGE_INTEGER current_time;
  173. double time_val;
  174. QueryPerformanceCounter(&current_time);
  175. time_val = (double)current_time.QuadPart;
  176. time_val *= 1000000000.0;
  177. time_val /= (double)get_clockfreq();
  178. return (uint64_t)time_val;
  179. }
  180. /* returns [folder]\[name] on windows */
  181. static int os_get_path_internal(char *dst, size_t size, const char *name,
  182. int folder)
  183. {
  184. wchar_t path_utf16[MAX_PATH];
  185. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT,
  186. path_utf16);
  187. if (os_wcs_to_utf8(path_utf16, 0, dst, size) != 0) {
  188. if (!name || !*name) {
  189. return (int)strlen(dst);
  190. }
  191. if (strcat_s(dst, size, "\\") == 0) {
  192. if (strcat_s(dst, size, name) == 0) {
  193. return (int)strlen(dst);
  194. }
  195. }
  196. }
  197. return -1;
  198. }
  199. static char *os_get_path_ptr_internal(const char *name, int folder)
  200. {
  201. char *ptr;
  202. wchar_t path_utf16[MAX_PATH];
  203. struct dstr path;
  204. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT,
  205. path_utf16);
  206. os_wcs_to_utf8_ptr(path_utf16, 0, &ptr);
  207. dstr_init_move_array(&path, ptr);
  208. dstr_cat(&path, "\\");
  209. dstr_cat(&path, name);
  210. return path.array;
  211. }
  212. int os_get_config_path(char *dst, size_t size, const char *name)
  213. {
  214. return os_get_path_internal(dst, size, name, CSIDL_APPDATA);
  215. }
  216. char *os_get_config_path_ptr(const char *name)
  217. {
  218. return os_get_path_ptr_internal(name, CSIDL_APPDATA);
  219. }
  220. int os_get_program_data_path(char *dst, size_t size, const char *name)
  221. {
  222. return os_get_path_internal(dst, size, name, CSIDL_COMMON_APPDATA);
  223. }
  224. char *os_get_program_data_path_ptr(const char *name)
  225. {
  226. return os_get_path_ptr_internal(name, CSIDL_COMMON_APPDATA);
  227. }
  228. bool os_file_exists(const char *path)
  229. {
  230. WIN32_FIND_DATAW wfd;
  231. HANDLE hFind;
  232. wchar_t *path_utf16;
  233. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  234. return false;
  235. hFind = FindFirstFileW(path_utf16, &wfd);
  236. if (hFind != INVALID_HANDLE_VALUE)
  237. FindClose(hFind);
  238. bfree(path_utf16);
  239. return hFind != INVALID_HANDLE_VALUE;
  240. }
  241. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  242. {
  243. wchar_t wpath[512];
  244. wchar_t wabspath[512];
  245. size_t out_len = 0;
  246. size_t len;
  247. if (!abspath)
  248. return 0;
  249. len = os_utf8_to_wcs(path, 0, wpath, 512);
  250. if (!len)
  251. return 0;
  252. if (_wfullpath(wabspath, wpath, 512) != NULL)
  253. out_len = os_wcs_to_utf8(wabspath, 0, abspath, size);
  254. return out_len;
  255. }
  256. char *os_get_abs_path_ptr(const char *path)
  257. {
  258. char *ptr = bmalloc(512);
  259. if (!os_get_abs_path(path, ptr, 512)) {
  260. bfree(ptr);
  261. ptr = NULL;
  262. }
  263. return ptr;
  264. }
  265. struct os_dir {
  266. HANDLE handle;
  267. WIN32_FIND_DATA wfd;
  268. bool first;
  269. struct os_dirent out;
  270. };
  271. os_dir_t *os_opendir(const char *path)
  272. {
  273. struct dstr path_str = {0};
  274. struct os_dir *dir = NULL;
  275. WIN32_FIND_DATA wfd;
  276. HANDLE handle;
  277. wchar_t *w_path;
  278. dstr_copy(&path_str, path);
  279. dstr_cat(&path_str, "/*.*");
  280. if (os_utf8_to_wcs_ptr(path_str.array, path_str.len, &w_path) > 0) {
  281. handle = FindFirstFileW(w_path, &wfd);
  282. if (handle != INVALID_HANDLE_VALUE) {
  283. dir = bzalloc(sizeof(struct os_dir));
  284. dir->handle = handle;
  285. dir->first = true;
  286. dir->wfd = wfd;
  287. }
  288. bfree(w_path);
  289. }
  290. dstr_free(&path_str);
  291. return dir;
  292. }
  293. static inline bool is_dir(WIN32_FIND_DATA *wfd)
  294. {
  295. return !!(wfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  296. }
  297. struct os_dirent *os_readdir(os_dir_t *dir)
  298. {
  299. if (!dir)
  300. return NULL;
  301. if (dir->first) {
  302. dir->first = false;
  303. } else {
  304. if (!FindNextFileW(dir->handle, &dir->wfd))
  305. return NULL;
  306. }
  307. os_wcs_to_utf8(dir->wfd.cFileName, 0, dir->out.d_name,
  308. sizeof(dir->out.d_name));
  309. dir->out.directory = is_dir(&dir->wfd);
  310. return &dir->out;
  311. }
  312. void os_closedir(os_dir_t *dir)
  313. {
  314. if (dir) {
  315. FindClose(dir->handle);
  316. bfree(dir);
  317. }
  318. }
  319. int64_t os_get_free_space(const char *path)
  320. {
  321. ULARGE_INTEGER remainingSpace;
  322. char abs_path[512];
  323. wchar_t w_abs_path[512];
  324. if (os_get_abs_path(path, abs_path, 512) > 0) {
  325. if (os_utf8_to_wcs(abs_path, 0, w_abs_path, 512) > 0) {
  326. BOOL success = GetDiskFreeSpaceExW(w_abs_path,
  327. (PULARGE_INTEGER)&remainingSpace,
  328. NULL, NULL);
  329. if (success)
  330. return (int64_t)remainingSpace.QuadPart;
  331. }
  332. }
  333. return -1;
  334. }
  335. static void make_globent(struct os_globent *ent, WIN32_FIND_DATA *wfd,
  336. const char *pattern)
  337. {
  338. struct dstr name = {0};
  339. struct dstr path = {0};
  340. char *slash;
  341. dstr_from_wcs(&name, wfd->cFileName);
  342. dstr_copy(&path, pattern);
  343. slash = strrchr(path.array, '/');
  344. if (slash)
  345. dstr_resize(&path, slash + 1 - path.array);
  346. else
  347. dstr_free(&path);
  348. dstr_cat_dstr(&path, &name);
  349. ent->path = path.array;
  350. ent->directory = is_dir(wfd);
  351. dstr_free(&name);
  352. }
  353. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  354. {
  355. DARRAY(struct os_globent) files;
  356. HANDLE handle;
  357. WIN32_FIND_DATA wfd;
  358. int ret = -1;
  359. wchar_t *w_path;
  360. da_init(files);
  361. if (os_utf8_to_wcs_ptr(pattern, 0, &w_path) > 0) {
  362. handle = FindFirstFileW(w_path, &wfd);
  363. if (handle != INVALID_HANDLE_VALUE) {
  364. do {
  365. struct os_globent ent = {0};
  366. make_globent(&ent, &wfd, pattern);
  367. if (ent.path)
  368. da_push_back(files, &ent);
  369. } while (FindNextFile(handle, &wfd));
  370. FindClose(handle);
  371. *pglob = bmalloc(sizeof(**pglob));
  372. (*pglob)->gl_pathc = files.num;
  373. (*pglob)->gl_pathv = files.array;
  374. ret = 0;
  375. }
  376. bfree(w_path);
  377. }
  378. if (ret != 0)
  379. *pglob = NULL;
  380. UNUSED_PARAMETER(flags);
  381. return ret;
  382. }
  383. void os_globfree(os_glob_t *pglob)
  384. {
  385. if (pglob) {
  386. for (size_t i = 0; i < pglob->gl_pathc; i++)
  387. bfree(pglob->gl_pathv[i].path);
  388. bfree(pglob->gl_pathv);
  389. bfree(pglob);
  390. }
  391. }
  392. int os_unlink(const char *path)
  393. {
  394. wchar_t *w_path;
  395. bool success;
  396. os_utf8_to_wcs_ptr(path, 0, &w_path);
  397. if (!w_path)
  398. return -1;
  399. success = !!DeleteFileW(w_path);
  400. bfree(w_path);
  401. return success ? 0 : -1;
  402. }
  403. int os_rmdir(const char *path)
  404. {
  405. wchar_t *w_path;
  406. bool success;
  407. os_utf8_to_wcs_ptr(path, 0, &w_path);
  408. if (!w_path)
  409. return -1;
  410. success = !!RemoveDirectoryW(w_path);
  411. bfree(w_path);
  412. return success ? 0 : -1;
  413. }
  414. int os_mkdir(const char *path)
  415. {
  416. wchar_t *path_utf16;
  417. BOOL success;
  418. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  419. return MKDIR_ERROR;
  420. success = CreateDirectory(path_utf16, NULL);
  421. bfree(path_utf16);
  422. if (!success)
  423. return (GetLastError() == ERROR_ALREADY_EXISTS) ?
  424. MKDIR_EXISTS : MKDIR_ERROR;
  425. return MKDIR_SUCCESS;
  426. }
  427. int os_rename(const char *old_path, const char *new_path)
  428. {
  429. wchar_t *old_path_utf16 = NULL;
  430. wchar_t *new_path_utf16 = NULL;
  431. int code = -1;
  432. if (!os_utf8_to_wcs_ptr(old_path, 0, &old_path_utf16)) {
  433. return -1;
  434. }
  435. if (!os_utf8_to_wcs_ptr(new_path, 0, &new_path_utf16)) {
  436. goto error;
  437. }
  438. code = MoveFileExW(old_path_utf16, new_path_utf16,
  439. MOVEFILE_REPLACE_EXISTING) ? 0 : -1;
  440. error:
  441. bfree(old_path_utf16);
  442. bfree(new_path_utf16);
  443. return code;
  444. }
  445. int os_safe_replace(const char *target, const char *from, const char *backup)
  446. {
  447. wchar_t *wtarget = NULL;
  448. wchar_t *wfrom = NULL;
  449. wchar_t *wbackup = NULL;
  450. int code = -1;
  451. if (!target || !from)
  452. return -1;
  453. if (!os_utf8_to_wcs_ptr(target, 0, &wtarget))
  454. return -1;
  455. if (!os_utf8_to_wcs_ptr(from, 0, &wfrom))
  456. goto fail;
  457. if (backup && !os_utf8_to_wcs_ptr(backup, 0, &wbackup))
  458. goto fail;
  459. if (ReplaceFileW(wtarget, wfrom, wbackup, 0, NULL, NULL)) {
  460. code = 0;
  461. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  462. code = MoveFileExW(wfrom, wtarget, MOVEFILE_REPLACE_EXISTING)
  463. ? 0 : -1;
  464. }
  465. fail:
  466. bfree(wtarget);
  467. bfree(wfrom);
  468. bfree(wbackup);
  469. return code;
  470. }
  471. BOOL WINAPI DllMain(HINSTANCE hinst_dll, DWORD reason, LPVOID reserved)
  472. {
  473. switch (reason) {
  474. case DLL_PROCESS_ATTACH:
  475. timeBeginPeriod(1);
  476. #ifdef PTW32_STATIC_LIB
  477. pthread_win32_process_attach_np();
  478. #endif
  479. break;
  480. case DLL_PROCESS_DETACH:
  481. timeEndPeriod(1);
  482. #ifdef PTW32_STATIC_LIB
  483. pthread_win32_process_detach_np();
  484. #endif
  485. break;
  486. case DLL_THREAD_ATTACH:
  487. #ifdef PTW32_STATIC_LIB
  488. pthread_win32_thread_attach_np();
  489. #endif
  490. break;
  491. case DLL_THREAD_DETACH:
  492. #ifdef PTW32_STATIC_LIB
  493. pthread_win32_thread_detach_np();
  494. #endif
  495. break;
  496. }
  497. UNUSED_PARAMETER(hinst_dll);
  498. UNUSED_PARAMETER(reserved);
  499. return true;
  500. }
  501. os_performance_token_t *os_request_high_performance(const char *reason)
  502. {
  503. UNUSED_PARAMETER(reason);
  504. return NULL;
  505. }
  506. void os_end_high_performance(os_performance_token_t *token)
  507. {
  508. UNUSED_PARAMETER(token);
  509. }
  510. int os_copyfile(const char *file_in, const char *file_out)
  511. {
  512. wchar_t *file_in_utf16 = NULL;
  513. wchar_t *file_out_utf16 = NULL;
  514. int code = -1;
  515. if (!os_utf8_to_wcs_ptr(file_in, 0, &file_in_utf16)) {
  516. return -1;
  517. }
  518. if (!os_utf8_to_wcs_ptr(file_out, 0, &file_out_utf16)) {
  519. goto error;
  520. }
  521. code = CopyFileW(file_in_utf16, file_out_utf16, true) ? 0 : -1;
  522. error:
  523. bfree(file_in_utf16);
  524. bfree(file_out_utf16);
  525. return code;
  526. }
  527. char *os_getcwd(char *path, size_t size)
  528. {
  529. wchar_t *path_w;
  530. DWORD len;
  531. len = GetCurrentDirectoryW(0, NULL);
  532. if (!len)
  533. return NULL;
  534. path_w = bmalloc((len + 1) * sizeof(wchar_t));
  535. GetCurrentDirectoryW(len + 1, path_w);
  536. os_wcs_to_utf8(path_w, (size_t)len, path, size);
  537. bfree(path_w);
  538. return path;
  539. }
  540. int os_chdir(const char *path)
  541. {
  542. wchar_t *path_w = NULL;
  543. size_t size;
  544. int ret;
  545. size = os_utf8_to_wcs_ptr(path, 0, &path_w);
  546. if (!path_w)
  547. return -1;
  548. ret = SetCurrentDirectoryW(path_w) ? 0 : -1;
  549. bfree(path_w);
  550. return ret;
  551. }
  552. typedef DWORD (WINAPI *get_file_version_info_size_w_t)(
  553. LPCWSTR module,
  554. LPDWORD unused);
  555. typedef BOOL (WINAPI *get_file_version_info_w_t)(
  556. LPCWSTR module,
  557. DWORD unused,
  558. DWORD len,
  559. LPVOID data);
  560. typedef BOOL (WINAPI *ver_query_value_w_t)(
  561. LPVOID data,
  562. LPCWSTR subblock,
  563. LPVOID *buf,
  564. PUINT sizeout);
  565. static get_file_version_info_size_w_t get_file_version_info_size = NULL;
  566. static get_file_version_info_w_t get_file_version_info = NULL;
  567. static ver_query_value_w_t ver_query_value = NULL;
  568. static bool ver_initialized = false;
  569. static bool ver_initialize_success = false;
  570. static bool initialize_version_functions(void)
  571. {
  572. HMODULE ver = GetModuleHandleW(L"version");
  573. ver_initialized = true;
  574. if (!ver) {
  575. ver = LoadLibraryW(L"version");
  576. if (!ver) {
  577. blog(LOG_ERROR, "Failed to load windows "
  578. "version library");
  579. return false;
  580. }
  581. }
  582. get_file_version_info_size = (get_file_version_info_size_w_t)
  583. GetProcAddress(ver, "GetFileVersionInfoSizeW");
  584. get_file_version_info = (get_file_version_info_w_t)
  585. GetProcAddress(ver, "GetFileVersionInfoW");
  586. ver_query_value = (ver_query_value_w_t)
  587. GetProcAddress(ver, "VerQueryValueW");
  588. if (!get_file_version_info_size ||
  589. !get_file_version_info ||
  590. !ver_query_value) {
  591. blog(LOG_ERROR, "Failed to load windows version "
  592. "functions");
  593. return false;
  594. }
  595. ver_initialize_success = true;
  596. return true;
  597. }
  598. bool get_dll_ver(const wchar_t *lib, struct win_version_info *ver_info)
  599. {
  600. VS_FIXEDFILEINFO *info = NULL;
  601. UINT len = 0;
  602. BOOL success;
  603. LPVOID data;
  604. DWORD size;
  605. char utf8_lib[512];
  606. if (!ver_initialized && !initialize_version_functions())
  607. return false;
  608. if (!ver_initialize_success)
  609. return false;
  610. os_wcs_to_utf8(lib, 0, utf8_lib, sizeof(utf8_lib));
  611. size = get_file_version_info_size(lib, NULL);
  612. if (!size) {
  613. blog(LOG_ERROR, "Failed to get %s version info size", utf8_lib);
  614. return false;
  615. }
  616. data = bmalloc(size);
  617. if (!get_file_version_info(lib, 0, size, data)) {
  618. blog(LOG_ERROR, "Failed to get %s version info", utf8_lib);
  619. bfree(data);
  620. return false;
  621. }
  622. success = ver_query_value(data, L"\\", (LPVOID*)&info, &len);
  623. if (!success || !info || !len) {
  624. blog(LOG_ERROR, "Failed to get %s version info value", utf8_lib);
  625. bfree(data);
  626. return false;
  627. }
  628. ver_info->major = (int)HIWORD(info->dwFileVersionMS);
  629. ver_info->minor = (int)LOWORD(info->dwFileVersionMS);
  630. ver_info->build = (int)HIWORD(info->dwFileVersionLS);
  631. ver_info->revis = (int)LOWORD(info->dwFileVersionLS);
  632. bfree(data);
  633. return true;
  634. }
  635. bool is_64_bit_windows(void)
  636. {
  637. #if defined(_WIN64)
  638. return true;
  639. #elif defined(_WIN32)
  640. BOOL b64 = false;
  641. return IsWow64Process(GetCurrentProcess(), &b64) && b64;
  642. #endif
  643. }
  644. #define WINVER_REG_KEY L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
  645. void get_win_ver(struct win_version_info *info)
  646. {
  647. static struct win_version_info ver = {0};
  648. static bool got_version = false;
  649. if (!info)
  650. return;
  651. if (!got_version) {
  652. get_dll_ver(L"kernel32", &ver);
  653. got_version = true;
  654. if (ver.major == 10 && ver.revis == 0) {
  655. HKEY key;
  656. DWORD size, win10_revision;
  657. LSTATUS status;
  658. status = RegOpenKeyW(HKEY_LOCAL_MACHINE,
  659. WINVER_REG_KEY, &key);
  660. if (status != ERROR_SUCCESS)
  661. return;
  662. size = sizeof(win10_revision);
  663. status = RegQueryValueExW(key, L"UBR", NULL, NULL,
  664. (LPBYTE)&win10_revision, &size);
  665. if (status == ERROR_SUCCESS)
  666. ver.revis = (int)win10_revision;
  667. RegCloseKey(key);
  668. }
  669. }
  670. *info = ver;
  671. }
  672. struct os_inhibit_info {
  673. bool active;
  674. };
  675. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  676. {
  677. UNUSED_PARAMETER(reason);
  678. return bzalloc(sizeof(struct os_inhibit_info));
  679. }
  680. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  681. {
  682. if (!info)
  683. return false;
  684. if (info->active == active)
  685. return false;
  686. if (active) {
  687. SetThreadExecutionState(
  688. ES_CONTINUOUS |
  689. ES_SYSTEM_REQUIRED |
  690. ES_AWAYMODE_REQUIRED |
  691. ES_DISPLAY_REQUIRED);
  692. } else {
  693. SetThreadExecutionState(ES_CONTINUOUS);
  694. }
  695. info->active = active;
  696. return true;
  697. }
  698. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  699. {
  700. if (info) {
  701. os_inhibit_sleep_set_active(info, false);
  702. bfree(info);
  703. }
  704. }
  705. void os_breakpoint(void)
  706. {
  707. __debugbreak();
  708. }
  709. DWORD num_logical_cores(ULONG_PTR mask)
  710. {
  711. DWORD left_shift = sizeof(ULONG_PTR) * 8 - 1;
  712. DWORD bit_set_count = 0;
  713. ULONG_PTR bit_test = (ULONG_PTR)1 << left_shift;
  714. for (DWORD i = 0; i <= left_shift; ++i) {
  715. bit_set_count += ((mask & bit_test) ? 1 : 0);
  716. bit_test /= 2;
  717. }
  718. return bit_set_count;
  719. }
  720. static int physical_cores = 0;
  721. static int logical_cores = 0;
  722. static bool core_count_initialized = false;
  723. static void os_get_cores_internal(void)
  724. {
  725. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION info = NULL, temp = NULL;
  726. DWORD len = 0;
  727. if (core_count_initialized)
  728. return;
  729. core_count_initialized = true;
  730. GetLogicalProcessorInformation(info, &len);
  731. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  732. return;
  733. info = malloc(len);
  734. if (GetLogicalProcessorInformation(info, &len)) {
  735. DWORD num = len / sizeof(*info);
  736. temp = info;
  737. for (DWORD i = 0; i < num; i++) {
  738. if (temp->Relationship == RelationProcessorCore) {
  739. ULONG_PTR mask = temp->ProcessorMask;
  740. physical_cores++;
  741. logical_cores += num_logical_cores(mask);
  742. }
  743. temp++;
  744. }
  745. }
  746. free(info);
  747. }
  748. int os_get_physical_cores(void)
  749. {
  750. if (!core_count_initialized)
  751. os_get_cores_internal();
  752. return physical_cores;
  753. }
  754. int os_get_logical_cores(void)
  755. {
  756. if (!core_count_initialized)
  757. os_get_cores_internal();
  758. return logical_cores;
  759. }
  760. static inline bool os_get_sys_memory_usage_internal(MEMORYSTATUSEX *msex)
  761. {
  762. if (!GlobalMemoryStatusEx(msex))
  763. return false;
  764. return true;
  765. }
  766. uint64_t os_get_sys_free_size(void)
  767. {
  768. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  769. if (!os_get_sys_memory_usage_internal(&msex))
  770. return 0;
  771. return msex.ullAvailPhys;
  772. }
  773. static inline bool os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc)
  774. {
  775. if (!GetProcessMemoryInfo(GetCurrentProcess(), pmc, sizeof(*pmc)))
  776. return false;
  777. return true;
  778. }
  779. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  780. {
  781. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  782. if (!os_get_proc_memory_usage_internal(&pmc))
  783. return false;
  784. usage->resident_size = pmc.WorkingSetSize;
  785. usage->virtual_size = pmc.PagefileUsage;
  786. return true;
  787. }
  788. uint64_t os_get_proc_resident_size(void)
  789. {
  790. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  791. if (!os_get_proc_memory_usage_internal(&pmc))
  792. return 0;
  793. return pmc.WorkingSetSize;
  794. }
  795. uint64_t os_get_proc_virtual_size(void)
  796. {
  797. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  798. if (!os_get_proc_memory_usage_internal(&pmc))
  799. return 0;
  800. return pmc.PagefileUsage;
  801. }
  802. uint64_t os_get_free_disk_space(const char *dir)
  803. {
  804. wchar_t *wdir = NULL;
  805. if (!os_utf8_to_wcs_ptr(dir, 0, &wdir))
  806. return 0;
  807. ULARGE_INTEGER free;
  808. bool success = !!GetDiskFreeSpaceExW(wdir, &free, NULL, NULL);
  809. bfree(wdir);
  810. return success ? free.QuadPart : 0;
  811. }