platform-windows.c 27 KB

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