platform-windows.c 27 KB

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