platform-windows.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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 "base.h"
  21. #include "platform.h"
  22. #include "darray.h"
  23. #include "dstr.h"
  24. #include "windows/win-version.h"
  25. #include "../../deps/w32-pthreads/pthread.h"
  26. static bool have_clockfreq = false;
  27. static LARGE_INTEGER clock_freq;
  28. static uint32_t winver = 0;
  29. static inline uint64_t get_clockfreq(void)
  30. {
  31. if (!have_clockfreq)
  32. QueryPerformanceFrequency(&clock_freq);
  33. return clock_freq.QuadPart;
  34. }
  35. static inline uint32_t get_winver(void)
  36. {
  37. if (!winver) {
  38. struct win_version_info ver;
  39. get_win_ver(&ver);
  40. winver = (ver.major << 16) | ver.minor;
  41. }
  42. return winver;
  43. }
  44. void *os_dlopen(const char *path)
  45. {
  46. struct dstr dll_name;
  47. wchar_t *wpath;
  48. wchar_t *wpath_slash;
  49. HMODULE h_library = NULL;
  50. if (!path)
  51. return NULL;
  52. dstr_init_copy(&dll_name, path);
  53. dstr_replace(&dll_name, "\\", "/");
  54. if (!dstr_find(&dll_name, ".dll"))
  55. dstr_cat(&dll_name, ".dll");
  56. os_utf8_to_wcs_ptr(dll_name.array, 0, &wpath);
  57. /* to make module dependency issues easier to deal with, allow
  58. * dynamically loaded libraries on windows to search for dependent
  59. * libraries that are within the library's own directory */
  60. wpath_slash = wcsrchr(wpath, L'/');
  61. if (wpath_slash) {
  62. *wpath_slash = 0;
  63. SetDllDirectoryW(wpath);
  64. *wpath_slash = L'/';
  65. }
  66. h_library = LoadLibraryW(wpath);
  67. bfree(wpath);
  68. dstr_free(&dll_name);
  69. if (wpath_slash)
  70. SetDllDirectoryW(NULL);
  71. if (!h_library)
  72. blog(LOG_INFO, "LoadLibrary failed for '%s', error: %ld",
  73. path, GetLastError());
  74. return h_library;
  75. }
  76. void *os_dlsym(void *module, const char *func)
  77. {
  78. void *handle;
  79. handle = (void*)GetProcAddress(module, func);
  80. return handle;
  81. }
  82. void os_dlclose(void *module)
  83. {
  84. FreeLibrary(module);
  85. }
  86. union time_data {
  87. FILETIME ft;
  88. unsigned long long val;
  89. };
  90. struct os_cpu_usage_info {
  91. union time_data last_time, last_sys_time, last_user_time;
  92. DWORD core_count;
  93. };
  94. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  95. {
  96. struct os_cpu_usage_info *info = bzalloc(sizeof(*info));
  97. SYSTEM_INFO si;
  98. FILETIME dummy;
  99. GetSystemInfo(&si);
  100. GetSystemTimeAsFileTime(&info->last_time.ft);
  101. GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
  102. &info->last_sys_time.ft, &info->last_user_time.ft);
  103. info->core_count = si.dwNumberOfProcessors;
  104. return info;
  105. }
  106. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  107. {
  108. union time_data cur_time, cur_sys_time, cur_user_time;
  109. FILETIME dummy;
  110. double percent;
  111. if (!info)
  112. return 0.0;
  113. GetSystemTimeAsFileTime(&cur_time.ft);
  114. GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
  115. &cur_sys_time.ft, &cur_user_time.ft);
  116. percent = (double)(cur_sys_time.val - info->last_sys_time.val +
  117. (cur_user_time.val - info->last_user_time.val));
  118. percent /= (double)(cur_time.val - info->last_time.val);
  119. percent /= (double)info->core_count;
  120. info->last_time.val = cur_time.val;
  121. info->last_sys_time.val = cur_sys_time.val;
  122. info->last_user_time.val = cur_user_time.val;
  123. return percent * 100.0;
  124. }
  125. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  126. {
  127. if (info)
  128. bfree(info);
  129. }
  130. bool os_sleepto_ns(uint64_t time_target)
  131. {
  132. uint64_t t = os_gettime_ns();
  133. uint32_t milliseconds;
  134. if (t >= time_target)
  135. return false;
  136. milliseconds = (uint32_t)((time_target - t)/1000000);
  137. if (milliseconds > 1)
  138. Sleep(milliseconds-1);
  139. for (;;) {
  140. t = os_gettime_ns();
  141. if (t >= time_target)
  142. return true;
  143. #if 0
  144. Sleep(1);
  145. #else
  146. Sleep(0);
  147. #endif
  148. }
  149. }
  150. void os_sleep_ms(uint32_t duration)
  151. {
  152. /* windows 8+ appears to have decreased sleep precision */
  153. if (get_winver() >= 0x0602 && duration > 0)
  154. duration--;
  155. Sleep(duration);
  156. }
  157. uint64_t os_gettime_ns(void)
  158. {
  159. LARGE_INTEGER current_time;
  160. double time_val;
  161. QueryPerformanceCounter(&current_time);
  162. time_val = (double)current_time.QuadPart;
  163. time_val *= 1000000000.0;
  164. time_val /= (double)get_clockfreq();
  165. return (uint64_t)time_val;
  166. }
  167. /* returns %appdata%\[name] on windows */
  168. int os_get_config_path(char *dst, size_t size, const char *name)
  169. {
  170. wchar_t path_utf16[MAX_PATH];
  171. SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT,
  172. path_utf16);
  173. if (os_wcs_to_utf8(path_utf16, 0, dst, size) != 0) {
  174. if (!name || !*name) {
  175. return (int)strlen(dst);
  176. }
  177. if (strcat_s(dst, size, "\\") == 0) {
  178. if (strcat_s(dst, size, name) == 0) {
  179. return (int)strlen(dst);
  180. }
  181. }
  182. }
  183. return -1;
  184. }
  185. char *os_get_config_path_ptr(const char *name)
  186. {
  187. char *ptr;
  188. wchar_t path_utf16[MAX_PATH];
  189. struct dstr path;
  190. SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT,
  191. path_utf16);
  192. os_wcs_to_utf8_ptr(path_utf16, 0, &ptr);
  193. dstr_init_move_array(&path, ptr);
  194. dstr_cat(&path, "\\");
  195. dstr_cat(&path, name);
  196. return path.array;
  197. }
  198. bool os_file_exists(const char *path)
  199. {
  200. WIN32_FIND_DATAW wfd;
  201. HANDLE hFind;
  202. wchar_t *path_utf16;
  203. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  204. return false;
  205. hFind = FindFirstFileW(path_utf16, &wfd);
  206. if (hFind != INVALID_HANDLE_VALUE)
  207. FindClose(hFind);
  208. bfree(path_utf16);
  209. return hFind != INVALID_HANDLE_VALUE;
  210. }
  211. struct os_dir {
  212. HANDLE handle;
  213. WIN32_FIND_DATA wfd;
  214. bool first;
  215. struct os_dirent out;
  216. };
  217. os_dir_t *os_opendir(const char *path)
  218. {
  219. struct dstr path_str = {0};
  220. struct os_dir *dir = NULL;
  221. WIN32_FIND_DATA wfd;
  222. HANDLE handle;
  223. wchar_t *w_path;
  224. dstr_copy(&path_str, path);
  225. dstr_cat(&path_str, "/*.*");
  226. if (os_utf8_to_wcs_ptr(path_str.array, path_str.len, &w_path) > 0) {
  227. handle = FindFirstFileW(w_path, &wfd);
  228. if (handle != INVALID_HANDLE_VALUE) {
  229. dir = bzalloc(sizeof(struct os_dir));
  230. dir->handle = handle;
  231. dir->first = true;
  232. dir->wfd = wfd;
  233. }
  234. bfree(w_path);
  235. }
  236. dstr_free(&path_str);
  237. return dir;
  238. }
  239. static inline bool is_dir(WIN32_FIND_DATA *wfd)
  240. {
  241. return !!(wfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  242. }
  243. struct os_dirent *os_readdir(os_dir_t *dir)
  244. {
  245. if (!dir)
  246. return NULL;
  247. if (dir->first) {
  248. dir->first = false;
  249. } else {
  250. if (!FindNextFileW(dir->handle, &dir->wfd))
  251. return NULL;
  252. }
  253. os_wcs_to_utf8(dir->wfd.cFileName, 0, dir->out.d_name,
  254. sizeof(dir->out.d_name));
  255. dir->out.directory = is_dir(&dir->wfd);
  256. return &dir->out;
  257. }
  258. void os_closedir(os_dir_t *dir)
  259. {
  260. if (dir) {
  261. FindClose(dir->handle);
  262. bfree(dir);
  263. }
  264. }
  265. static void make_globent(struct os_globent *ent, WIN32_FIND_DATA *wfd,
  266. const char *pattern)
  267. {
  268. struct dstr name = {0};
  269. struct dstr path = {0};
  270. char *slash;
  271. dstr_from_wcs(&name, wfd->cFileName);
  272. dstr_copy(&path, pattern);
  273. slash = strrchr(path.array, '/');
  274. if (slash)
  275. dstr_resize(&path, slash + 1 - path.array);
  276. else
  277. dstr_free(&path);
  278. dstr_cat_dstr(&path, &name);
  279. ent->path = path.array;
  280. ent->directory = is_dir(wfd);
  281. dstr_free(&name);
  282. }
  283. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  284. {
  285. DARRAY(struct os_globent) files;
  286. HANDLE handle;
  287. WIN32_FIND_DATA wfd;
  288. int ret = -1;
  289. wchar_t *w_path;
  290. da_init(files);
  291. if (os_utf8_to_wcs_ptr(pattern, 0, &w_path) > 0) {
  292. handle = FindFirstFileW(w_path, &wfd);
  293. if (handle != INVALID_HANDLE_VALUE) {
  294. do {
  295. struct os_globent ent = {0};
  296. make_globent(&ent, &wfd, pattern);
  297. if (ent.path)
  298. da_push_back(files, &ent);
  299. } while (FindNextFile(handle, &wfd));
  300. FindClose(handle);
  301. *pglob = bmalloc(sizeof(**pglob));
  302. (*pglob)->gl_pathc = files.num;
  303. (*pglob)->gl_pathv = files.array;
  304. ret = 0;
  305. }
  306. bfree(w_path);
  307. }
  308. if (ret != 0)
  309. *pglob = NULL;
  310. UNUSED_PARAMETER(flags);
  311. return ret;
  312. }
  313. void os_globfree(os_glob_t *pglob)
  314. {
  315. if (pglob) {
  316. for (size_t i = 0; i < pglob->gl_pathc; i++)
  317. bfree(pglob->gl_pathv[i].path);
  318. bfree(pglob->gl_pathv);
  319. bfree(pglob);
  320. }
  321. }
  322. int os_unlink(const char *path)
  323. {
  324. wchar_t *w_path;
  325. bool success;
  326. os_utf8_to_wcs_ptr(path, 0, &w_path);
  327. if (!w_path)
  328. return -1;
  329. success = !!DeleteFileW(w_path);
  330. bfree(w_path);
  331. return success ? 0 : -1;
  332. }
  333. int os_rmdir(const char *path)
  334. {
  335. wchar_t *w_path;
  336. bool success;
  337. os_utf8_to_wcs_ptr(path, 0, &w_path);
  338. if (!w_path)
  339. return -1;
  340. success = !!RemoveDirectoryW(w_path);
  341. bfree(w_path);
  342. return success ? 0 : -1;
  343. }
  344. int os_mkdir(const char *path)
  345. {
  346. wchar_t *path_utf16;
  347. BOOL success;
  348. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  349. return MKDIR_ERROR;
  350. success = CreateDirectory(path_utf16, NULL);
  351. bfree(path_utf16);
  352. if (!success)
  353. return (GetLastError() == ERROR_ALREADY_EXISTS) ?
  354. MKDIR_EXISTS : MKDIR_ERROR;
  355. return MKDIR_SUCCESS;
  356. }
  357. int os_rename(const char *old_path, const char *new_path)
  358. {
  359. wchar_t *old_path_utf16 = NULL;
  360. wchar_t *new_path_utf16 = NULL;
  361. int code = -1;
  362. if (!os_utf8_to_wcs_ptr(old_path, 0, &old_path_utf16)) {
  363. return -1;
  364. }
  365. if (!os_utf8_to_wcs_ptr(new_path, 0, &new_path_utf16)) {
  366. goto error;
  367. }
  368. code = MoveFileW(old_path_utf16, new_path_utf16) ? 0 : -1;
  369. error:
  370. bfree(old_path_utf16);
  371. bfree(new_path_utf16);
  372. return code;
  373. }
  374. BOOL WINAPI DllMain(HINSTANCE hinst_dll, DWORD reason, LPVOID reserved)
  375. {
  376. switch (reason) {
  377. case DLL_PROCESS_ATTACH:
  378. timeBeginPeriod(1);
  379. #ifdef PTW32_STATIC_LIB
  380. pthread_win32_process_attach_np();
  381. #endif
  382. break;
  383. case DLL_PROCESS_DETACH:
  384. timeEndPeriod(1);
  385. #ifdef PTW32_STATIC_LIB
  386. pthread_win32_process_detach_np();
  387. #endif
  388. break;
  389. case DLL_THREAD_ATTACH:
  390. #ifdef PTW32_STATIC_LIB
  391. pthread_win32_thread_attach_np();
  392. #endif
  393. break;
  394. case DLL_THREAD_DETACH:
  395. #ifdef PTW32_STATIC_LIB
  396. pthread_win32_thread_detach_np();
  397. #endif
  398. break;
  399. }
  400. UNUSED_PARAMETER(hinst_dll);
  401. UNUSED_PARAMETER(reserved);
  402. return true;
  403. }
  404. os_performance_token_t *os_request_high_performance(const char *reason)
  405. {
  406. UNUSED_PARAMETER(reason);
  407. return NULL;
  408. }
  409. void os_end_high_performance(os_performance_token_t *token)
  410. {
  411. UNUSED_PARAMETER(token);
  412. }
  413. int os_copyfile(const char *file_in, const char *file_out)
  414. {
  415. wchar_t *file_in_utf16 = NULL;
  416. wchar_t *file_out_utf16 = NULL;
  417. int code = -1;
  418. if (!os_utf8_to_wcs_ptr(file_in, 0, &file_in_utf16)) {
  419. return -1;
  420. }
  421. if (!os_utf8_to_wcs_ptr(file_out, 0, &file_out_utf16)) {
  422. goto error;
  423. }
  424. code = CopyFileW(file_in_utf16, file_out_utf16, true) ? 0 : -1;
  425. error:
  426. bfree(file_in_utf16);
  427. bfree(file_out_utf16);
  428. return code;
  429. }
  430. char *os_getcwd(char *path, size_t size)
  431. {
  432. wchar_t *path_w;
  433. DWORD len;
  434. len = GetCurrentDirectoryW(0, NULL);
  435. if (!len)
  436. return NULL;
  437. path_w = bmalloc((len + 1) * sizeof(wchar_t));
  438. GetCurrentDirectoryW(len + 1, path_w);
  439. os_wcs_to_utf8(path_w, (size_t)len, path, size);
  440. bfree(path_w);
  441. return path;
  442. }
  443. int os_chdir(const char *path)
  444. {
  445. wchar_t *path_w = NULL;
  446. size_t size;
  447. int ret;
  448. size = os_utf8_to_wcs_ptr(path, 0, &path_w);
  449. if (!path_w)
  450. return -1;
  451. ret = SetCurrentDirectoryW(path_w) ? 0 : -1;
  452. bfree(path_w);
  453. return ret;
  454. }
  455. typedef DWORD (WINAPI *get_file_version_info_size_w_t)(
  456. LPCWSTR module,
  457. LPDWORD unused);
  458. typedef BOOL (WINAPI *get_file_version_info_w_t)(
  459. LPCWSTR module,
  460. DWORD unused,
  461. DWORD len,
  462. LPVOID data);
  463. typedef BOOL (WINAPI *ver_query_value_w_t)(
  464. LPVOID data,
  465. LPCWSTR subblock,
  466. LPVOID *buf,
  467. PUINT sizeout);
  468. static void actually_get_win_ver(struct win_version_info *ver_info)
  469. {
  470. HMODULE ver = GetModuleHandleW(L"version");
  471. VS_FIXEDFILEINFO *info = NULL;
  472. UINT len = 0;
  473. BOOL success;
  474. LPVOID data;
  475. DWORD size;
  476. get_file_version_info_size_w_t get_file_version_info_size;
  477. get_file_version_info_w_t get_file_version_info;
  478. ver_query_value_w_t ver_query_value;
  479. if (!ver) {
  480. ver = LoadLibraryW(L"version");
  481. if (!ver) {
  482. blog(LOG_ERROR, "Failed to load windows version "
  483. "library");
  484. return;
  485. }
  486. }
  487. get_file_version_info_size = (get_file_version_info_size_w_t)
  488. GetProcAddress(ver, "GetFileVersionInfoSizeW");
  489. get_file_version_info = (get_file_version_info_w_t)
  490. GetProcAddress(ver, "GetFileVersionInfoW");
  491. ver_query_value = (ver_query_value_w_t)
  492. GetProcAddress(ver, "VerQueryValueW");
  493. if (!get_file_version_info_size ||
  494. !get_file_version_info ||
  495. !ver_query_value) {
  496. blog(LOG_ERROR, "Failed to load windows version "
  497. "functions");
  498. return;
  499. }
  500. size = get_file_version_info_size(L"kernel32", NULL);
  501. if (!size) {
  502. blog(LOG_ERROR, "Failed to get windows version info size");
  503. return;
  504. }
  505. data = bmalloc(size);
  506. if (!get_file_version_info(L"kernel32", 0, size, data)) {
  507. blog(LOG_ERROR, "Failed to get windows version info");
  508. bfree(data);
  509. return;
  510. }
  511. success = ver_query_value(data, L"\\", (LPVOID*)&info, &len);
  512. if (!success || !info || !len) {
  513. blog(LOG_ERROR, "Failed to get windows version info value");
  514. bfree(data);
  515. return;
  516. }
  517. ver_info->major = (int)HIWORD(info->dwFileVersionMS);
  518. ver_info->minor = (int)LOWORD(info->dwFileVersionMS);
  519. ver_info->build = (int)HIWORD(info->dwFileVersionLS);
  520. ver_info->revis = (int)LOWORD(info->dwFileVersionLS);
  521. bfree(data);
  522. return;
  523. }
  524. void get_win_ver(struct win_version_info *info)
  525. {
  526. static struct win_version_info ver = {0};
  527. static bool got_version = false;
  528. if (!info)
  529. return;
  530. if (!got_version) {
  531. actually_get_win_ver(&ver);
  532. got_version = true;
  533. }
  534. *info = ver;
  535. }
  536. struct os_inhibit_info {
  537. BOOL was_active;
  538. bool active;
  539. };
  540. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  541. {
  542. UNUSED_PARAMETER(reason);
  543. return bzalloc(sizeof(struct os_inhibit_info));
  544. }
  545. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  546. {
  547. if (!info)
  548. return false;
  549. if (info->active == active)
  550. return false;
  551. if (active) {
  552. SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0,
  553. &info->was_active, 0);
  554. SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, false,
  555. NULL, 0);
  556. SetThreadExecutionState(
  557. ES_CONTINUOUS |
  558. ES_SYSTEM_REQUIRED |
  559. ES_AWAYMODE_REQUIRED |
  560. ES_DISPLAY_REQUIRED);
  561. } else {
  562. SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, info->was_active,
  563. NULL, 0);
  564. SetThreadExecutionState(ES_CONTINUOUS);
  565. }
  566. info->active = active;
  567. return true;
  568. }
  569. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  570. {
  571. if (info) {
  572. os_inhibit_sleep_set_active(info, false);
  573. bfree(info);
  574. }
  575. }