platform-windows.c 27 KB

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