platform-windows.c 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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. slash = strrchr(path.array, '/');
  478. if (slash)
  479. dstr_resize(&path, slash + 1 - path.array);
  480. else
  481. dstr_free(&path);
  482. dstr_cat_dstr(&path, &name);
  483. ent->path = path.array;
  484. ent->directory = is_dir(wfd);
  485. dstr_free(&name);
  486. }
  487. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  488. {
  489. DARRAY(struct os_globent) files;
  490. HANDLE handle;
  491. WIN32_FIND_DATA wfd;
  492. int ret = -1;
  493. wchar_t *w_path;
  494. da_init(files);
  495. if (os_utf8_to_wcs_ptr(pattern, 0, &w_path) > 0) {
  496. handle = FindFirstFileW(w_path, &wfd);
  497. if (handle != INVALID_HANDLE_VALUE) {
  498. do {
  499. struct os_globent ent = {0};
  500. make_globent(&ent, &wfd, pattern);
  501. if (ent.path)
  502. da_push_back(files, &ent);
  503. } while (FindNextFile(handle, &wfd));
  504. FindClose(handle);
  505. *pglob = bmalloc(sizeof(**pglob));
  506. (*pglob)->gl_pathc = files.num;
  507. (*pglob)->gl_pathv = files.array;
  508. ret = 0;
  509. }
  510. bfree(w_path);
  511. }
  512. if (ret != 0)
  513. *pglob = NULL;
  514. UNUSED_PARAMETER(flags);
  515. return ret;
  516. }
  517. void os_globfree(os_glob_t *pglob)
  518. {
  519. if (pglob) {
  520. for (size_t i = 0; i < pglob->gl_pathc; i++)
  521. bfree(pglob->gl_pathv[i].path);
  522. bfree(pglob->gl_pathv);
  523. bfree(pglob);
  524. }
  525. }
  526. int os_unlink(const char *path)
  527. {
  528. wchar_t *w_path;
  529. bool success;
  530. os_utf8_to_wcs_ptr(path, 0, &w_path);
  531. if (!w_path)
  532. return -1;
  533. success = !!DeleteFileW(w_path);
  534. bfree(w_path);
  535. return success ? 0 : -1;
  536. }
  537. int os_rmdir(const char *path)
  538. {
  539. wchar_t *w_path;
  540. bool success;
  541. os_utf8_to_wcs_ptr(path, 0, &w_path);
  542. if (!w_path)
  543. return -1;
  544. success = !!RemoveDirectoryW(w_path);
  545. bfree(w_path);
  546. return success ? 0 : -1;
  547. }
  548. int os_mkdir(const char *path)
  549. {
  550. wchar_t *path_utf16;
  551. BOOL success;
  552. if (!os_utf8_to_wcs_ptr(path, 0, &path_utf16))
  553. return MKDIR_ERROR;
  554. success = CreateDirectory(path_utf16, NULL);
  555. bfree(path_utf16);
  556. if (!success)
  557. return (GetLastError() == ERROR_ALREADY_EXISTS) ? MKDIR_EXISTS
  558. : MKDIR_ERROR;
  559. return MKDIR_SUCCESS;
  560. }
  561. int os_rename(const char *old_path, const char *new_path)
  562. {
  563. wchar_t *old_path_utf16 = NULL;
  564. wchar_t *new_path_utf16 = NULL;
  565. int code = -1;
  566. if (!os_utf8_to_wcs_ptr(old_path, 0, &old_path_utf16)) {
  567. return -1;
  568. }
  569. if (!os_utf8_to_wcs_ptr(new_path, 0, &new_path_utf16)) {
  570. goto error;
  571. }
  572. code = MoveFileExW(old_path_utf16, new_path_utf16,
  573. MOVEFILE_REPLACE_EXISTING)
  574. ? 0
  575. : -1;
  576. error:
  577. bfree(old_path_utf16);
  578. bfree(new_path_utf16);
  579. return code;
  580. }
  581. int os_safe_replace(const char *target, const char *from, const char *backup)
  582. {
  583. wchar_t *wtarget = NULL;
  584. wchar_t *wfrom = NULL;
  585. wchar_t *wbackup = NULL;
  586. int code = -1;
  587. if (!target || !from)
  588. return -1;
  589. if (!os_utf8_to_wcs_ptr(target, 0, &wtarget))
  590. return -1;
  591. if (!os_utf8_to_wcs_ptr(from, 0, &wfrom))
  592. goto fail;
  593. if (backup && !os_utf8_to_wcs_ptr(backup, 0, &wbackup))
  594. goto fail;
  595. if (ReplaceFileW(wtarget, wfrom, wbackup, 0, NULL, NULL)) {
  596. code = 0;
  597. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  598. code = MoveFileExW(wfrom, wtarget, MOVEFILE_REPLACE_EXISTING)
  599. ? 0
  600. : -1;
  601. }
  602. fail:
  603. bfree(wtarget);
  604. bfree(wfrom);
  605. bfree(wbackup);
  606. return code;
  607. }
  608. BOOL WINAPI DllMain(HINSTANCE hinst_dll, DWORD reason, LPVOID reserved)
  609. {
  610. switch (reason) {
  611. case DLL_PROCESS_ATTACH:
  612. timeBeginPeriod(1);
  613. #ifdef PTW32_STATIC_LIB
  614. pthread_win32_process_attach_np();
  615. #endif
  616. break;
  617. case DLL_PROCESS_DETACH:
  618. timeEndPeriod(1);
  619. #ifdef PTW32_STATIC_LIB
  620. pthread_win32_process_detach_np();
  621. #endif
  622. break;
  623. case DLL_THREAD_ATTACH:
  624. #ifdef PTW32_STATIC_LIB
  625. pthread_win32_thread_attach_np();
  626. #endif
  627. break;
  628. case DLL_THREAD_DETACH:
  629. #ifdef PTW32_STATIC_LIB
  630. pthread_win32_thread_detach_np();
  631. #endif
  632. break;
  633. }
  634. UNUSED_PARAMETER(hinst_dll);
  635. UNUSED_PARAMETER(reserved);
  636. return true;
  637. }
  638. os_performance_token_t *os_request_high_performance(const char *reason)
  639. {
  640. UNUSED_PARAMETER(reason);
  641. return NULL;
  642. }
  643. void os_end_high_performance(os_performance_token_t *token)
  644. {
  645. UNUSED_PARAMETER(token);
  646. }
  647. int os_copyfile(const char *file_in, const char *file_out)
  648. {
  649. wchar_t *file_in_utf16 = NULL;
  650. wchar_t *file_out_utf16 = NULL;
  651. int code = -1;
  652. if (!os_utf8_to_wcs_ptr(file_in, 0, &file_in_utf16)) {
  653. return -1;
  654. }
  655. if (!os_utf8_to_wcs_ptr(file_out, 0, &file_out_utf16)) {
  656. goto error;
  657. }
  658. code = CopyFileW(file_in_utf16, file_out_utf16, true) ? 0 : -1;
  659. error:
  660. bfree(file_in_utf16);
  661. bfree(file_out_utf16);
  662. return code;
  663. }
  664. char *os_getcwd(char *path, size_t size)
  665. {
  666. wchar_t *path_w;
  667. DWORD len;
  668. len = GetCurrentDirectoryW(0, NULL);
  669. if (!len)
  670. return NULL;
  671. path_w = bmalloc((len + 1) * sizeof(wchar_t));
  672. GetCurrentDirectoryW(len + 1, path_w);
  673. os_wcs_to_utf8(path_w, (size_t)len, path, size);
  674. bfree(path_w);
  675. return path;
  676. }
  677. int os_chdir(const char *path)
  678. {
  679. wchar_t *path_w = NULL;
  680. size_t size;
  681. int ret;
  682. size = os_utf8_to_wcs_ptr(path, 0, &path_w);
  683. if (!path_w)
  684. return -1;
  685. ret = SetCurrentDirectoryW(path_w) ? 0 : -1;
  686. bfree(path_w);
  687. return ret;
  688. }
  689. typedef DWORD(WINAPI *get_file_version_info_size_w_t)(LPCWSTR module,
  690. LPDWORD unused);
  691. typedef BOOL(WINAPI *get_file_version_info_w_t)(LPCWSTR module, DWORD unused,
  692. DWORD len, LPVOID data);
  693. typedef BOOL(WINAPI *ver_query_value_w_t)(LPVOID data, LPCWSTR subblock,
  694. LPVOID *buf, PUINT sizeout);
  695. static get_file_version_info_size_w_t get_file_version_info_size = NULL;
  696. static get_file_version_info_w_t get_file_version_info = NULL;
  697. static ver_query_value_w_t ver_query_value = NULL;
  698. static bool ver_initialized = false;
  699. static bool ver_initialize_success = false;
  700. static bool initialize_version_functions(void)
  701. {
  702. HMODULE ver = GetModuleHandleW(L"version");
  703. ver_initialized = true;
  704. if (!ver) {
  705. ver = LoadLibraryW(L"version");
  706. if (!ver) {
  707. blog(LOG_ERROR, "Failed to load windows "
  708. "version library");
  709. return false;
  710. }
  711. }
  712. get_file_version_info_size =
  713. (get_file_version_info_size_w_t)GetProcAddress(
  714. ver, "GetFileVersionInfoSizeW");
  715. get_file_version_info = (get_file_version_info_w_t)GetProcAddress(
  716. ver, "GetFileVersionInfoW");
  717. ver_query_value =
  718. (ver_query_value_w_t)GetProcAddress(ver, "VerQueryValueW");
  719. if (!get_file_version_info_size || !get_file_version_info ||
  720. !ver_query_value) {
  721. blog(LOG_ERROR, "Failed to load windows version "
  722. "functions");
  723. return false;
  724. }
  725. ver_initialize_success = true;
  726. return true;
  727. }
  728. bool get_dll_ver(const wchar_t *lib, struct win_version_info *ver_info)
  729. {
  730. VS_FIXEDFILEINFO *info = NULL;
  731. UINT len = 0;
  732. BOOL success;
  733. LPVOID data;
  734. DWORD size;
  735. char utf8_lib[512];
  736. if (!ver_initialized && !initialize_version_functions())
  737. return false;
  738. if (!ver_initialize_success)
  739. return false;
  740. os_wcs_to_utf8(lib, 0, utf8_lib, sizeof(utf8_lib));
  741. size = get_file_version_info_size(lib, NULL);
  742. if (!size) {
  743. blog(LOG_ERROR, "Failed to get %s version info size", utf8_lib);
  744. return false;
  745. }
  746. data = bmalloc(size);
  747. if (!get_file_version_info(lib, 0, size, data)) {
  748. blog(LOG_ERROR, "Failed to get %s version info", utf8_lib);
  749. bfree(data);
  750. return false;
  751. }
  752. success = ver_query_value(data, L"\\", (LPVOID *)&info, &len);
  753. if (!success || !info || !len) {
  754. blog(LOG_ERROR, "Failed to get %s version info value",
  755. utf8_lib);
  756. bfree(data);
  757. return false;
  758. }
  759. ver_info->major = (int)HIWORD(info->dwFileVersionMS);
  760. ver_info->minor = (int)LOWORD(info->dwFileVersionMS);
  761. ver_info->build = (int)HIWORD(info->dwFileVersionLS);
  762. ver_info->revis = (int)LOWORD(info->dwFileVersionLS);
  763. bfree(data);
  764. return true;
  765. }
  766. bool is_64_bit_windows(void)
  767. {
  768. #if defined(_WIN64)
  769. return true;
  770. #elif defined(_WIN32)
  771. BOOL b64 = false;
  772. return IsWow64Process(GetCurrentProcess(), &b64) && b64;
  773. #endif
  774. }
  775. void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name,
  776. struct reg_dword *info)
  777. {
  778. struct reg_dword reg = {0};
  779. HKEY key;
  780. LSTATUS status;
  781. status = RegOpenKeyEx(hkey, sub_key, 0, KEY_READ, &key);
  782. if (status != ERROR_SUCCESS) {
  783. info->status = status;
  784. info->size = 0;
  785. info->return_value = 0;
  786. return;
  787. }
  788. reg.size = sizeof(reg.return_value);
  789. reg.status = RegQueryValueExW(key, value_name, NULL, NULL,
  790. (LPBYTE)&reg.return_value, &reg.size);
  791. RegCloseKey(key);
  792. *info = reg;
  793. }
  794. #define WINVER_REG_KEY L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
  795. static inline void rtl_get_ver(struct win_version_info *ver)
  796. {
  797. RTL_OSVERSIONINFOEXW osver = {0};
  798. HMODULE ntdll = GetModuleHandleW(L"ntdll");
  799. NTSTATUS s;
  800. NTSTATUS(WINAPI * get_ver)
  801. (RTL_OSVERSIONINFOEXW *) =
  802. (void *)GetProcAddress(ntdll, "RtlGetVersion");
  803. if (!get_ver) {
  804. return;
  805. }
  806. osver.dwOSVersionInfoSize = sizeof(osver);
  807. s = get_ver(&osver);
  808. if (s < 0) {
  809. return;
  810. }
  811. ver->major = osver.dwMajorVersion;
  812. ver->minor = osver.dwMinorVersion;
  813. ver->build = osver.dwBuildNumber;
  814. ver->revis = 0;
  815. }
  816. static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf,
  817. const size_t size)
  818. {
  819. DWORD dwsize = (DWORD)size;
  820. LSTATUS status;
  821. status = RegQueryValueExW(key, val, NULL, NULL, (LPBYTE)buf, &dwsize);
  822. buf[(size / sizeof(wchar_t)) - 1] = 0;
  823. return status == ERROR_SUCCESS;
  824. }
  825. static inline void get_reg_ver(struct win_version_info *ver)
  826. {
  827. HKEY key;
  828. DWORD size, dw_val;
  829. LSTATUS status;
  830. wchar_t str[MAX_SZ_LEN];
  831. status = RegOpenKeyW(HKEY_LOCAL_MACHINE, WINVER_REG_KEY, &key);
  832. if (status != ERROR_SUCCESS)
  833. return;
  834. size = sizeof(dw_val);
  835. status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL,
  836. (LPBYTE)&dw_val, &size);
  837. if (status == ERROR_SUCCESS)
  838. ver->major = (int)dw_val;
  839. status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL,
  840. (LPBYTE)&dw_val, &size);
  841. if (status == ERROR_SUCCESS)
  842. ver->minor = (int)dw_val;
  843. status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val,
  844. &size);
  845. if (status == ERROR_SUCCESS)
  846. ver->revis = (int)dw_val;
  847. if (get_reg_sz(key, L"CurrentBuildNumber", str, sizeof(str))) {
  848. ver->build = wcstol(str, NULL, 10);
  849. }
  850. if (get_reg_sz(key, L"ReleaseId", str, sizeof(str))) {
  851. os_wcs_to_utf8(str, 0, win_release_id, MAX_SZ_LEN);
  852. }
  853. RegCloseKey(key);
  854. }
  855. static inline bool version_higher(struct win_version_info *cur,
  856. struct win_version_info *new)
  857. {
  858. if (new->major > cur->major) {
  859. return true;
  860. }
  861. if (new->major == cur->major) {
  862. if (new->minor > cur->minor) {
  863. return true;
  864. }
  865. if (new->minor == cur->minor) {
  866. if (new->build > cur->build) {
  867. return true;
  868. }
  869. if (new->build == cur->build) {
  870. return new->revis > cur->revis;
  871. }
  872. }
  873. }
  874. return false;
  875. }
  876. static inline void use_higher_ver(struct win_version_info *cur,
  877. struct win_version_info *new)
  878. {
  879. if (version_higher(cur, new))
  880. *cur = *new;
  881. }
  882. void get_win_ver(struct win_version_info *info)
  883. {
  884. static struct win_version_info ver = {0};
  885. static bool got_version = false;
  886. if (!info)
  887. return;
  888. if (!got_version) {
  889. struct win_version_info reg_ver = {0};
  890. struct win_version_info rtl_ver = {0};
  891. struct win_version_info nto_ver = {0};
  892. get_reg_ver(&reg_ver);
  893. rtl_get_ver(&rtl_ver);
  894. get_dll_ver(L"ntoskrnl.exe", &nto_ver);
  895. ver = reg_ver;
  896. use_higher_ver(&ver, &rtl_ver);
  897. use_higher_ver(&ver, &nto_ver);
  898. got_version = true;
  899. }
  900. *info = ver;
  901. }
  902. const char *get_win_release_id(void)
  903. {
  904. return win_release_id;
  905. }
  906. uint32_t get_win_ver_int(void)
  907. {
  908. return get_winver();
  909. }
  910. struct os_inhibit_info {
  911. bool active;
  912. };
  913. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  914. {
  915. UNUSED_PARAMETER(reason);
  916. return bzalloc(sizeof(struct os_inhibit_info));
  917. }
  918. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  919. {
  920. if (!info)
  921. return false;
  922. if (info->active == active)
  923. return false;
  924. if (active) {
  925. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED |
  926. ES_AWAYMODE_REQUIRED |
  927. ES_DISPLAY_REQUIRED);
  928. } else {
  929. SetThreadExecutionState(ES_CONTINUOUS);
  930. }
  931. info->active = active;
  932. return true;
  933. }
  934. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  935. {
  936. if (info) {
  937. os_inhibit_sleep_set_active(info, false);
  938. bfree(info);
  939. }
  940. }
  941. void os_breakpoint(void)
  942. {
  943. __debugbreak();
  944. }
  945. DWORD num_logical_cores(ULONG_PTR mask)
  946. {
  947. DWORD left_shift = sizeof(ULONG_PTR) * 8 - 1;
  948. DWORD bit_set_count = 0;
  949. ULONG_PTR bit_test = (ULONG_PTR)1 << left_shift;
  950. for (DWORD i = 0; i <= left_shift; ++i) {
  951. bit_set_count += ((mask & bit_test) ? 1 : 0);
  952. bit_test /= 2;
  953. }
  954. return bit_set_count;
  955. }
  956. static int physical_cores = 0;
  957. static int logical_cores = 0;
  958. static bool core_count_initialized = false;
  959. static void os_get_cores_internal(void)
  960. {
  961. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION info = NULL, temp = NULL;
  962. DWORD len = 0;
  963. if (core_count_initialized)
  964. return;
  965. core_count_initialized = true;
  966. GetLogicalProcessorInformation(info, &len);
  967. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  968. return;
  969. info = malloc(len);
  970. if (GetLogicalProcessorInformation(info, &len)) {
  971. DWORD num = len / sizeof(*info);
  972. temp = info;
  973. for (DWORD i = 0; i < num; i++) {
  974. if (temp->Relationship == RelationProcessorCore) {
  975. ULONG_PTR mask = temp->ProcessorMask;
  976. physical_cores++;
  977. logical_cores += num_logical_cores(mask);
  978. }
  979. temp++;
  980. }
  981. }
  982. free(info);
  983. }
  984. int os_get_physical_cores(void)
  985. {
  986. if (!core_count_initialized)
  987. os_get_cores_internal();
  988. return physical_cores;
  989. }
  990. int os_get_logical_cores(void)
  991. {
  992. if (!core_count_initialized)
  993. os_get_cores_internal();
  994. return logical_cores;
  995. }
  996. static inline bool os_get_sys_memory_usage_internal(MEMORYSTATUSEX *msex)
  997. {
  998. if (!GlobalMemoryStatusEx(msex))
  999. return false;
  1000. return true;
  1001. }
  1002. uint64_t os_get_sys_free_size(void)
  1003. {
  1004. MEMORYSTATUSEX msex = {sizeof(MEMORYSTATUSEX)};
  1005. if (!os_get_sys_memory_usage_internal(&msex))
  1006. return 0;
  1007. return msex.ullAvailPhys;
  1008. }
  1009. static inline bool
  1010. os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc)
  1011. {
  1012. if (!GetProcessMemoryInfo(GetCurrentProcess(), pmc, sizeof(*pmc)))
  1013. return false;
  1014. return true;
  1015. }
  1016. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  1017. {
  1018. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1019. if (!os_get_proc_memory_usage_internal(&pmc))
  1020. return false;
  1021. usage->resident_size = pmc.WorkingSetSize;
  1022. usage->virtual_size = pmc.PagefileUsage;
  1023. return true;
  1024. }
  1025. uint64_t os_get_proc_resident_size(void)
  1026. {
  1027. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1028. if (!os_get_proc_memory_usage_internal(&pmc))
  1029. return 0;
  1030. return pmc.WorkingSetSize;
  1031. }
  1032. uint64_t os_get_proc_virtual_size(void)
  1033. {
  1034. PROCESS_MEMORY_COUNTERS pmc = {sizeof(PROCESS_MEMORY_COUNTERS)};
  1035. if (!os_get_proc_memory_usage_internal(&pmc))
  1036. return 0;
  1037. return pmc.PagefileUsage;
  1038. }
  1039. uint64_t os_get_free_disk_space(const char *dir)
  1040. {
  1041. wchar_t *wdir = NULL;
  1042. if (!os_utf8_to_wcs_ptr(dir, 0, &wdir))
  1043. return 0;
  1044. ULARGE_INTEGER free;
  1045. bool success = !!GetDiskFreeSpaceExW(wdir, &free, NULL, NULL);
  1046. bfree(wdir);
  1047. return success ? free.QuadPart : 0;
  1048. }