platform-windows.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  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. bool os_sleepto_ns_fast(uint64_t time_target)
  283. {
  284. uint64_t current = os_gettime_ns();
  285. if (time_target < current)
  286. return false;
  287. do {
  288. uint64_t remain_ms = (time_target - current) / 1000000;
  289. if (!remain_ms)
  290. remain_ms = 1;
  291. Sleep((DWORD)remain_ms);
  292. current = os_gettime_ns();
  293. } while (time_target > current);
  294. return true;
  295. }
  296. void os_sleep_ms(uint32_t duration)
  297. {
  298. /* windows 8+ appears to have decreased sleep precision */
  299. if (get_winver() >= 0x0602 && duration > 0)
  300. duration--;
  301. Sleep(duration);
  302. }
  303. uint64_t os_gettime_ns(void)
  304. {
  305. LARGE_INTEGER current_time;
  306. QueryPerformanceCounter(&current_time);
  307. return util_mul_div64(current_time.QuadPart, 1000000000,
  308. get_clockfreq());
  309. }
  310. /* returns [folder]\[name] on windows */
  311. static int os_get_path_internal(char *dst, size_t size, const char *name,
  312. int folder)
  313. {
  314. wchar_t path_utf16[MAX_PATH];
  315. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path_utf16);
  316. if (os_wcs_to_utf8(path_utf16, 0, dst, size) != 0) {
  317. if (!name || !*name) {
  318. return (int)strlen(dst);
  319. }
  320. if (strcat_s(dst, size, "\\") == 0) {
  321. if (strcat_s(dst, size, name) == 0) {
  322. return (int)strlen(dst);
  323. }
  324. }
  325. }
  326. return -1;
  327. }
  328. static char *os_get_path_ptr_internal(const char *name, int folder)
  329. {
  330. char *ptr;
  331. wchar_t path_utf16[MAX_PATH];
  332. struct dstr path;
  333. SHGetFolderPathW(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path_utf16);
  334. os_wcs_to_utf8_ptr(path_utf16, 0, &ptr);
  335. dstr_init_move_array(&path, ptr);
  336. dstr_cat(&path, "\\");
  337. dstr_cat(&path, name);
  338. return path.array;
  339. }
  340. int os_get_config_path(char *dst, size_t size, const char *name)
  341. {
  342. return os_get_path_internal(dst, size, name, CSIDL_APPDATA);
  343. }
  344. char *os_get_config_path_ptr(const char *name)
  345. {
  346. return os_get_path_ptr_internal(name, CSIDL_APPDATA);
  347. }
  348. int os_get_program_data_path(char *dst, size_t size, const char *name)
  349. {
  350. return os_get_path_internal(dst, size, name, CSIDL_COMMON_APPDATA);
  351. }
  352. char *os_get_program_data_path_ptr(const char *name)
  353. {
  354. return os_get_path_ptr_internal(name, CSIDL_COMMON_APPDATA);
  355. }
  356. char *os_get_executable_path_ptr(const char *name)
  357. {
  358. char *ptr;
  359. char *slash;
  360. wchar_t path_utf16[MAX_PATH];
  361. struct dstr path;
  362. GetModuleFileNameW(NULL, path_utf16, MAX_PATH);
  363. os_wcs_to_utf8_ptr(path_utf16, 0, &ptr);
  364. dstr_init_move_array(&path, ptr);
  365. dstr_replace(&path, "\\", "/");
  366. slash = strrchr(path.array, '/');
  367. if (slash) {
  368. size_t len = slash - path.array + 1;
  369. dstr_resize(&path, len);
  370. }
  371. if (name && *name) {
  372. dstr_cat(&path, name);
  373. }
  374. return path.array;
  375. }
  376. bool os_file_exists(const char *path)
  377. {
  378. WIN32_FIND_DATAW wfd;
  379. HANDLE hFind;
  380. wchar_t *path_utf16;
  381. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  382. return false;
  383. hFind = FindFirstFileW(path_utf16, &wfd);
  384. if (hFind != INVALID_HANDLE_VALUE)
  385. FindClose(hFind);
  386. bfree(path_utf16);
  387. return hFind != INVALID_HANDLE_VALUE;
  388. }
  389. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  390. {
  391. wchar_t wpath[MAX_PATH];
  392. wchar_t wabspath[MAX_PATH];
  393. size_t out_len = 0;
  394. size_t len;
  395. if (!abspath)
  396. return 0;
  397. len = os_utf8_to_wcs(path, 0, wpath, MAX_PATH);
  398. if (!len)
  399. return 0;
  400. if (_wfullpath(wabspath, wpath, MAX_PATH) != NULL)
  401. out_len = os_wcs_to_utf8(wabspath, 0, abspath, size);
  402. return out_len;
  403. }
  404. char *os_get_abs_path_ptr(const char *path)
  405. {
  406. char *ptr = bmalloc(MAX_PATH);
  407. if (!os_get_abs_path(path, ptr, MAX_PATH)) {
  408. bfree(ptr);
  409. ptr = NULL;
  410. }
  411. return ptr;
  412. }
  413. struct os_dir {
  414. HANDLE handle;
  415. WIN32_FIND_DATA wfd;
  416. bool first;
  417. struct os_dirent out;
  418. };
  419. os_dir_t *os_opendir(const char *path)
  420. {
  421. struct dstr path_str = {0};
  422. struct os_dir *dir = NULL;
  423. WIN32_FIND_DATA wfd;
  424. HANDLE handle;
  425. wchar_t *w_path;
  426. dstr_copy(&path_str, path);
  427. dstr_cat(&path_str, "/*.*");
  428. if (os_utf8_to_wcs_ptr(path_str.array, path_str.len, &w_path) > 0) {
  429. handle = FindFirstFileW(w_path, &wfd);
  430. if (handle != INVALID_HANDLE_VALUE) {
  431. dir = bzalloc(sizeof(struct os_dir));
  432. dir->handle = handle;
  433. dir->first = true;
  434. dir->wfd = wfd;
  435. }
  436. bfree(w_path);
  437. }
  438. dstr_free(&path_str);
  439. return dir;
  440. }
  441. static inline bool is_dir(WIN32_FIND_DATA *wfd)
  442. {
  443. return !!(wfd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
  444. }
  445. struct os_dirent *os_readdir(os_dir_t *dir)
  446. {
  447. if (!dir)
  448. return NULL;
  449. if (dir->first) {
  450. dir->first = false;
  451. } else {
  452. if (!FindNextFileW(dir->handle, &dir->wfd))
  453. return NULL;
  454. }
  455. os_wcs_to_utf8(dir->wfd.cFileName, 0, dir->out.d_name,
  456. sizeof(dir->out.d_name));
  457. dir->out.directory = is_dir(&dir->wfd);
  458. return &dir->out;
  459. }
  460. void os_closedir(os_dir_t *dir)
  461. {
  462. if (dir) {
  463. FindClose(dir->handle);
  464. bfree(dir);
  465. }
  466. }
  467. int64_t os_get_free_space(const char *path)
  468. {
  469. ULARGE_INTEGER remainingSpace;
  470. char abs_path[512];
  471. wchar_t w_abs_path[512];
  472. if (os_get_abs_path(path, abs_path, 512) > 0) {
  473. if (os_utf8_to_wcs(abs_path, 0, w_abs_path, 512) > 0) {
  474. BOOL success = GetDiskFreeSpaceExW(
  475. w_abs_path, (PULARGE_INTEGER)&remainingSpace,
  476. NULL, NULL);
  477. if (success)
  478. return (int64_t)remainingSpace.QuadPart;
  479. }
  480. }
  481. return -1;
  482. }
  483. static void make_globent(struct os_globent *ent, WIN32_FIND_DATA *wfd,
  484. const char *pattern)
  485. {
  486. struct dstr name = {0};
  487. struct dstr path = {0};
  488. char *slash;
  489. dstr_from_wcs(&name, wfd->cFileName);
  490. dstr_copy(&path, pattern);
  491. if (path.array) {
  492. slash = strrchr(path.array, '/');
  493. if (slash)
  494. dstr_resize(&path, slash + 1 - path.array);
  495. else
  496. dstr_free(&path);
  497. }
  498. dstr_cat_dstr(&path, &name);
  499. ent->path = path.array;
  500. ent->directory = is_dir(wfd);
  501. dstr_free(&name);
  502. }
  503. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  504. {
  505. DARRAY(struct os_globent) files;
  506. HANDLE handle;
  507. WIN32_FIND_DATA wfd;
  508. int ret = -1;
  509. wchar_t *w_path;
  510. da_init(files);
  511. if (os_utf8_to_wcs_ptr(pattern, 0, &w_path) > 0) {
  512. handle = FindFirstFileW(w_path, &wfd);
  513. if (handle != INVALID_HANDLE_VALUE) {
  514. do {
  515. struct os_globent ent = {0};
  516. make_globent(&ent, &wfd, pattern);
  517. if (ent.path)
  518. da_push_back(files, &ent);
  519. } while (FindNextFile(handle, &wfd));
  520. FindClose(handle);
  521. *pglob = bmalloc(sizeof(**pglob));
  522. (*pglob)->gl_pathc = files.num;
  523. (*pglob)->gl_pathv = files.array;
  524. ret = 0;
  525. }
  526. bfree(w_path);
  527. }
  528. if (ret != 0)
  529. *pglob = NULL;
  530. UNUSED_PARAMETER(flags);
  531. return ret;
  532. }
  533. void os_globfree(os_glob_t *pglob)
  534. {
  535. if (pglob) {
  536. for (size_t i = 0; i < pglob->gl_pathc; i++)
  537. bfree(pglob->gl_pathv[i].path);
  538. bfree(pglob->gl_pathv);
  539. bfree(pglob);
  540. }
  541. }
  542. int os_unlink(const char *path)
  543. {
  544. wchar_t *w_path;
  545. bool success;
  546. os_utf8_to_wcs_ptr(path, 0, &w_path);
  547. if (!w_path)
  548. return -1;
  549. success = !!DeleteFileW(w_path);
  550. bfree(w_path);
  551. return success ? 0 : -1;
  552. }
  553. int os_rmdir(const char *path)
  554. {
  555. wchar_t *w_path;
  556. bool success;
  557. os_utf8_to_wcs_ptr(path, 0, &w_path);
  558. if (!w_path)
  559. return -1;
  560. success = !!RemoveDirectoryW(w_path);
  561. bfree(w_path);
  562. return success ? 0 : -1;
  563. }
  564. int os_mkdir(const char *path)
  565. {
  566. wchar_t *path_utf16;
  567. BOOL success;
  568. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  569. return MKDIR_ERROR;
  570. success = CreateDirectory(path_utf16, NULL);
  571. bfree(path_utf16);
  572. if (!success)
  573. return (GetLastError() == ERROR_ALREADY_EXISTS) ? MKDIR_EXISTS
  574. : MKDIR_ERROR;
  575. return MKDIR_SUCCESS;
  576. }
  577. int os_rename(const char *old_path, const char *new_path)
  578. {
  579. wchar_t *old_path_utf16 = NULL;
  580. wchar_t *new_path_utf16 = NULL;
  581. int code = -1;
  582. if (!os_utf8_to_wcs_ptr(old_path, 0, &old_path_utf16)) {
  583. return -1;
  584. }
  585. if (!os_utf8_to_wcs_ptr(new_path, 0, &new_path_utf16)) {
  586. goto error;
  587. }
  588. code = MoveFileExW(old_path_utf16, new_path_utf16,
  589. MOVEFILE_REPLACE_EXISTING)
  590. ? 0
  591. : -1;
  592. error:
  593. bfree(old_path_utf16);
  594. bfree(new_path_utf16);
  595. return code;
  596. }
  597. int os_safe_replace(const char *target, const char *from, const char *backup)
  598. {
  599. wchar_t *wtarget = NULL;
  600. wchar_t *wfrom = NULL;
  601. wchar_t *wbackup = NULL;
  602. int code = -1;
  603. if (!target || !from)
  604. return -1;
  605. if (!os_utf8_to_wcs_ptr(target, 0, &wtarget))
  606. return -1;
  607. if (!os_utf8_to_wcs_ptr(from, 0, &wfrom))
  608. goto fail;
  609. if (backup && !os_utf8_to_wcs_ptr(backup, 0, &wbackup))
  610. goto fail;
  611. if (ReplaceFileW(wtarget, wfrom, wbackup, 0, NULL, NULL)) {
  612. code = 0;
  613. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  614. code = MoveFileExW(wfrom, wtarget, MOVEFILE_REPLACE_EXISTING)
  615. ? 0
  616. : -1;
  617. }
  618. fail:
  619. bfree(wtarget);
  620. bfree(wfrom);
  621. bfree(wbackup);
  622. return code;
  623. }
  624. BOOL WINAPI DllMain(HINSTANCE hinst_dll, DWORD reason, LPVOID reserved)
  625. {
  626. switch (reason) {
  627. case DLL_PROCESS_ATTACH:
  628. timeBeginPeriod(1);
  629. #ifdef PTW32_STATIC_LIB
  630. pthread_win32_process_attach_np();
  631. #endif
  632. break;
  633. case DLL_PROCESS_DETACH:
  634. timeEndPeriod(1);
  635. #ifdef PTW32_STATIC_LIB
  636. pthread_win32_process_detach_np();
  637. #endif
  638. break;
  639. case DLL_THREAD_ATTACH:
  640. #ifdef PTW32_STATIC_LIB
  641. pthread_win32_thread_attach_np();
  642. #endif
  643. break;
  644. case DLL_THREAD_DETACH:
  645. #ifdef PTW32_STATIC_LIB
  646. pthread_win32_thread_detach_np();
  647. #endif
  648. break;
  649. }
  650. UNUSED_PARAMETER(hinst_dll);
  651. UNUSED_PARAMETER(reserved);
  652. return true;
  653. }
  654. os_performance_token_t *os_request_high_performance(const char *reason)
  655. {
  656. UNUSED_PARAMETER(reason);
  657. return NULL;
  658. }
  659. void os_end_high_performance(os_performance_token_t *token)
  660. {
  661. UNUSED_PARAMETER(token);
  662. }
  663. int os_copyfile(const char *file_in, const char *file_out)
  664. {
  665. wchar_t *file_in_utf16 = NULL;
  666. wchar_t *file_out_utf16 = NULL;
  667. int code = -1;
  668. if (!os_utf8_to_wcs_ptr(file_in, 0, &file_in_utf16)) {
  669. return -1;
  670. }
  671. if (!os_utf8_to_wcs_ptr(file_out, 0, &file_out_utf16)) {
  672. goto error;
  673. }
  674. code = CopyFileW(file_in_utf16, file_out_utf16, true) ? 0 : -1;
  675. error:
  676. bfree(file_in_utf16);
  677. bfree(file_out_utf16);
  678. return code;
  679. }
  680. char *os_getcwd(char *path, size_t size)
  681. {
  682. wchar_t *path_w;
  683. DWORD len;
  684. len = GetCurrentDirectoryW(0, NULL);
  685. if (!len)
  686. return NULL;
  687. path_w = bmalloc(((size_t)len + 1) * sizeof(wchar_t));
  688. GetCurrentDirectoryW(len + 1, path_w);
  689. os_wcs_to_utf8(path_w, (size_t)len, path, size);
  690. bfree(path_w);
  691. return path;
  692. }
  693. int os_chdir(const char *path)
  694. {
  695. wchar_t *path_w = NULL;
  696. size_t size;
  697. int ret;
  698. size = os_utf8_to_wcs_ptr(path, 0, &path_w);
  699. if (!path_w)
  700. return -1;
  701. ret = SetCurrentDirectoryW(path_w) ? 0 : -1;
  702. bfree(path_w);
  703. return ret;
  704. }
  705. typedef DWORD(WINAPI *get_file_version_info_size_w_t)(LPCWSTR module,
  706. LPDWORD unused);
  707. typedef BOOL(WINAPI *get_file_version_info_w_t)(LPCWSTR module, DWORD unused,
  708. DWORD len, LPVOID data);
  709. typedef BOOL(WINAPI *ver_query_value_w_t)(LPVOID data, LPCWSTR subblock,
  710. LPVOID *buf, PUINT sizeout);
  711. static get_file_version_info_size_w_t get_file_version_info_size = NULL;
  712. static get_file_version_info_w_t get_file_version_info = NULL;
  713. static ver_query_value_w_t ver_query_value = NULL;
  714. static bool ver_initialized = false;
  715. static bool ver_initialize_success = false;
  716. static bool initialize_version_functions(void)
  717. {
  718. HMODULE ver = GetModuleHandleW(L"version");
  719. ver_initialized = true;
  720. if (!ver) {
  721. ver = LoadLibraryW(L"version");
  722. if (!ver) {
  723. blog(LOG_ERROR, "Failed to load windows "
  724. "version library");
  725. return false;
  726. }
  727. }
  728. get_file_version_info_size =
  729. (get_file_version_info_size_w_t)GetProcAddress(
  730. ver, "GetFileVersionInfoSizeW");
  731. get_file_version_info = (get_file_version_info_w_t)GetProcAddress(
  732. ver, "GetFileVersionInfoW");
  733. ver_query_value =
  734. (ver_query_value_w_t)GetProcAddress(ver, "VerQueryValueW");
  735. if (!get_file_version_info_size || !get_file_version_info ||
  736. !ver_query_value) {
  737. blog(LOG_ERROR, "Failed to load windows version "
  738. "functions");
  739. return false;
  740. }
  741. ver_initialize_success = true;
  742. return true;
  743. }
  744. bool get_dll_ver(const wchar_t *lib, struct win_version_info *ver_info)
  745. {
  746. VS_FIXEDFILEINFO *info = NULL;
  747. UINT len = 0;
  748. BOOL success;
  749. LPVOID data;
  750. DWORD size;
  751. char utf8_lib[512];
  752. if (!ver_initialized && !initialize_version_functions())
  753. return false;
  754. if (!ver_initialize_success)
  755. return false;
  756. os_wcs_to_utf8(lib, 0, utf8_lib, sizeof(utf8_lib));
  757. size = get_file_version_info_size(lib, NULL);
  758. if (!size) {
  759. blog(LOG_ERROR, "Failed to get %s version info size", utf8_lib);
  760. return false;
  761. }
  762. data = bmalloc(size);
  763. if (!get_file_version_info(lib, 0, size, data)) {
  764. blog(LOG_ERROR, "Failed to get %s version info", utf8_lib);
  765. bfree(data);
  766. return false;
  767. }
  768. success = ver_query_value(data, L"\\", (LPVOID *)&info, &len);
  769. if (!success || !info || !len) {
  770. blog(LOG_ERROR, "Failed to get %s version info value",
  771. utf8_lib);
  772. bfree(data);
  773. return false;
  774. }
  775. ver_info->major = (int)HIWORD(info->dwFileVersionMS);
  776. ver_info->minor = (int)LOWORD(info->dwFileVersionMS);
  777. ver_info->build = (int)HIWORD(info->dwFileVersionLS);
  778. ver_info->revis = (int)LOWORD(info->dwFileVersionLS);
  779. bfree(data);
  780. return true;
  781. }
  782. bool is_64_bit_windows(void)
  783. {
  784. #if defined(_WIN64)
  785. return true;
  786. #elif defined(_WIN32)
  787. BOOL b64 = false;
  788. return IsWow64Process(GetCurrentProcess(), &b64) && b64;
  789. #endif
  790. }
  791. bool os_get_emulation_status(void)
  792. {
  793. return false;
  794. }
  795. void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name,
  796. struct reg_dword *info)
  797. {
  798. struct reg_dword reg = {0};
  799. HKEY key;
  800. LSTATUS status;
  801. status = RegOpenKeyEx(hkey, sub_key, 0, KEY_READ, &key);
  802. if (status != ERROR_SUCCESS) {
  803. info->status = status;
  804. info->size = 0;
  805. info->return_value = 0;
  806. return;
  807. }
  808. reg.size = sizeof(reg.return_value);
  809. reg.status = RegQueryValueExW(key, value_name, NULL, NULL,
  810. (LPBYTE)&reg.return_value, &reg.size);
  811. RegCloseKey(key);
  812. *info = reg;
  813. }
  814. #define WINVER_REG_KEY L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
  815. static inline void rtl_get_ver(struct win_version_info *ver)
  816. {
  817. HMODULE ntdll = GetModuleHandleW(L"ntdll");
  818. if (!ntdll)
  819. return;
  820. NTSTATUS(WINAPI * get_ver)
  821. (RTL_OSVERSIONINFOEXW *) =
  822. (void *)GetProcAddress(ntdll, "RtlGetVersion");
  823. if (!get_ver) {
  824. return;
  825. }
  826. RTL_OSVERSIONINFOEXW osver = {0};
  827. osver.dwOSVersionInfoSize = sizeof(osver);
  828. NTSTATUS s = get_ver(&osver);
  829. if (s < 0) {
  830. return;
  831. }
  832. ver->major = osver.dwMajorVersion;
  833. ver->minor = osver.dwMinorVersion;
  834. ver->build = osver.dwBuildNumber;
  835. ver->revis = 0;
  836. }
  837. static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf,
  838. DWORD size)
  839. {
  840. const LSTATUS status =
  841. RegGetValueW(key, NULL, val, RRF_RT_REG_SZ, NULL, buf, &size);
  842. return status == ERROR_SUCCESS;
  843. }
  844. static inline void get_reg_ver(struct win_version_info *ver)
  845. {
  846. HKEY key;
  847. DWORD size, dw_val;
  848. LSTATUS status;
  849. wchar_t str[MAX_SZ_LEN];
  850. status = RegOpenKeyW(HKEY_LOCAL_MACHINE, WINVER_REG_KEY, &key);
  851. if (status != ERROR_SUCCESS)
  852. return;
  853. size = sizeof(dw_val);
  854. status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL,
  855. (LPBYTE)&dw_val, &size);
  856. if (status == ERROR_SUCCESS)
  857. ver->major = (int)dw_val;
  858. status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL,
  859. (LPBYTE)&dw_val, &size);
  860. if (status == ERROR_SUCCESS)
  861. ver->minor = (int)dw_val;
  862. status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val,
  863. &size);
  864. if (status == ERROR_SUCCESS)
  865. ver->revis = (int)dw_val;
  866. if (get_reg_sz(key, L"CurrentBuildNumber", str, sizeof(str))) {
  867. ver->build = wcstol(str, NULL, 10);
  868. }
  869. if (get_reg_sz(key, L"ReleaseId", str, sizeof(str))) {
  870. os_wcs_to_utf8(str, 0, win_release_id, MAX_SZ_LEN);
  871. }
  872. RegCloseKey(key);
  873. }
  874. static inline bool version_higher(struct win_version_info *cur,
  875. struct win_version_info *new)
  876. {
  877. if (new->major > cur->major) {
  878. return true;
  879. }
  880. if (new->major == cur->major) {
  881. if (new->minor > cur->minor) {
  882. return true;
  883. }
  884. if (new->minor == cur->minor) {
  885. if (new->build > cur->build) {
  886. return true;
  887. }
  888. if (new->build == cur->build) {
  889. return new->revis > cur->revis;
  890. }
  891. }
  892. }
  893. return false;
  894. }
  895. static inline void use_higher_ver(struct win_version_info *cur,
  896. struct win_version_info *new)
  897. {
  898. if (version_higher(cur, new))
  899. *cur = *new;
  900. }
  901. void get_win_ver(struct win_version_info *info)
  902. {
  903. static struct win_version_info ver = {0};
  904. static bool got_version = false;
  905. if (!info)
  906. return;
  907. if (!got_version) {
  908. struct win_version_info reg_ver = {0};
  909. struct win_version_info rtl_ver = {0};
  910. struct win_version_info nto_ver = {0};
  911. get_reg_ver(&reg_ver);
  912. rtl_get_ver(&rtl_ver);
  913. get_dll_ver(L"ntoskrnl.exe", &nto_ver);
  914. ver = reg_ver;
  915. use_higher_ver(&ver, &rtl_ver);
  916. use_higher_ver(&ver, &nto_ver);
  917. got_version = true;
  918. }
  919. *info = ver;
  920. }
  921. const char *get_win_release_id(void)
  922. {
  923. return win_release_id;
  924. }
  925. uint32_t get_win_ver_int(void)
  926. {
  927. return get_winver();
  928. }
  929. struct os_inhibit_info {
  930. bool active;
  931. };
  932. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  933. {
  934. UNUSED_PARAMETER(reason);
  935. return bzalloc(sizeof(struct os_inhibit_info));
  936. }
  937. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  938. {
  939. if (!info)
  940. return false;
  941. if (info->active == active)
  942. return false;
  943. if (active) {
  944. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED |
  945. ES_AWAYMODE_REQUIRED |
  946. ES_DISPLAY_REQUIRED);
  947. } else {
  948. SetThreadExecutionState(ES_CONTINUOUS);
  949. }
  950. info->active = active;
  951. return true;
  952. }
  953. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  954. {
  955. if (info) {
  956. os_inhibit_sleep_set_active(info, false);
  957. bfree(info);
  958. }
  959. }
  960. void os_breakpoint(void)
  961. {
  962. __debugbreak();
  963. }
  964. DWORD num_logical_cores(ULONG_PTR mask)
  965. {
  966. DWORD left_shift = sizeof(ULONG_PTR) * 8 - 1;
  967. DWORD bit_set_count = 0;
  968. ULONG_PTR bit_test = (ULONG_PTR)1 << left_shift;
  969. for (DWORD i = 0; i <= left_shift; ++i) {
  970. bit_set_count += ((mask & bit_test) ? 1 : 0);
  971. bit_test /= 2;
  972. }
  973. return bit_set_count;
  974. }
  975. static int physical_cores = 0;
  976. static int logical_cores = 0;
  977. static bool core_count_initialized = false;
  978. static void os_get_cores_internal(void)
  979. {
  980. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION info = NULL, temp = NULL;
  981. DWORD len = 0;
  982. if (core_count_initialized)
  983. return;
  984. core_count_initialized = true;
  985. GetLogicalProcessorInformation(info, &len);
  986. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  987. return;
  988. info = malloc(len);
  989. if (info) {
  990. if (GetLogicalProcessorInformation(info, &len)) {
  991. DWORD num = len / sizeof(*info);
  992. temp = info;
  993. for (DWORD i = 0; i < num; i++) {
  994. if (temp->Relationship ==
  995. RelationProcessorCore) {
  996. ULONG_PTR mask = temp->ProcessorMask;
  997. physical_cores++;
  998. logical_cores +=
  999. num_logical_cores(mask);
  1000. }
  1001. temp++;
  1002. }
  1003. }
  1004. free(info);
  1005. }
  1006. }
  1007. int os_get_physical_cores(void)
  1008. {
  1009. if (!core_count_initialized)
  1010. os_get_cores_internal();
  1011. return physical_cores;
  1012. }
  1013. int os_get_logical_cores(void)
  1014. {
  1015. if (!core_count_initialized)
  1016. os_get_cores_internal();
  1017. return logical_cores;
  1018. }
  1019. static inline bool os_get_sys_memory_usage_internal(MEMORYSTATUSEX *msex)
  1020. {
  1021. if (!GlobalMemoryStatusEx(msex))
  1022. return false;
  1023. return true;
  1024. }
  1025. uint64_t os_get_sys_free_size(void)
  1026. {
  1027. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  1028. if (!os_get_sys_memory_usage_internal(&msex))
  1029. return 0;
  1030. return msex.ullAvailPhys;
  1031. }
  1032. static inline bool
  1033. os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc)
  1034. {
  1035. if (!GetProcessMemoryInfo(GetCurrentProcess(), pmc, sizeof(*pmc)))
  1036. return false;
  1037. return true;
  1038. }
  1039. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  1040. {
  1041. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1042. if (!os_get_proc_memory_usage_internal(&pmc))
  1043. return false;
  1044. usage->resident_size = pmc.WorkingSetSize;
  1045. usage->virtual_size = pmc.PagefileUsage;
  1046. return true;
  1047. }
  1048. uint64_t os_get_proc_resident_size(void)
  1049. {
  1050. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1051. if (!os_get_proc_memory_usage_internal(&pmc))
  1052. return 0;
  1053. return pmc.WorkingSetSize;
  1054. }
  1055. uint64_t os_get_proc_virtual_size(void)
  1056. {
  1057. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1058. if (!os_get_proc_memory_usage_internal(&pmc))
  1059. return 0;
  1060. return pmc.PagefileUsage;
  1061. }
  1062. uint64_t os_get_free_disk_space(const char *dir)
  1063. {
  1064. wchar_t *wdir = NULL;
  1065. if (!os_utf8_to_wcs_ptr(dir, 0, &wdir))
  1066. return 0;
  1067. ULARGE_INTEGER free;
  1068. bool success = !!GetDiskFreeSpaceExW(wdir, &free, NULL, NULL);
  1069. bfree(wdir);
  1070. return success ? free.QuadPart : 0;
  1071. }