platform-windows.c 22 KB

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