platform-windows.c 27 KB

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