graphics-hook.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. #include <windows.h>
  2. #include <psapi.h>
  3. #include <inttypes.h>
  4. #include "graphics-hook.h"
  5. #include "../graphics-hook-ver.h"
  6. #include "../obfuscate.h"
  7. #include "../funchook.h"
  8. #define DEBUG_OUTPUT
  9. #ifdef DEBUG_OUTPUT
  10. #define DbgOut(x) OutputDebugStringA(x)
  11. #else
  12. #define DbgOut(x)
  13. #endif
  14. struct thread_data {
  15. CRITICAL_SECTION mutexes[NUM_BUFFERS];
  16. CRITICAL_SECTION data_mutex;
  17. void *volatile cur_data;
  18. uint8_t *shmem_textures[2];
  19. HANDLE copy_thread;
  20. HANDLE copy_event;
  21. HANDLE stop_event;
  22. volatile int cur_tex;
  23. unsigned int pitch;
  24. unsigned int cy;
  25. volatile bool locked_textures[NUM_BUFFERS];
  26. };
  27. ipc_pipe_client_t pipe = {0};
  28. HANDLE signal_restart = NULL;
  29. HANDLE signal_stop = NULL;
  30. HANDLE signal_ready = NULL;
  31. HANDLE signal_exit = NULL;
  32. static HANDLE signal_init = NULL;
  33. HANDLE tex_mutexes[2] = {NULL, NULL};
  34. static HANDLE filemap_hook_info = NULL;
  35. static HINSTANCE dll_inst = NULL;
  36. static volatile bool stop_loop = false;
  37. static HANDLE dup_hook_mutex = NULL;
  38. static HANDLE capture_thread = NULL;
  39. char system_path[MAX_PATH] = {0};
  40. char process_name[MAX_PATH] = {0};
  41. wchar_t keepalive_name[64] = {0};
  42. HWND dummy_window = NULL;
  43. static unsigned int shmem_id_counter = 0;
  44. static void *shmem_info = NULL;
  45. static HANDLE shmem_file_handle = 0;
  46. static struct thread_data thread_data = {0};
  47. volatile bool active = false;
  48. struct hook_info *global_hook_info = NULL;
  49. static inline void wait_for_dll_main_finish(HANDLE thread_handle)
  50. {
  51. if (thread_handle) {
  52. WaitForSingleObject(thread_handle, 100);
  53. CloseHandle(thread_handle);
  54. }
  55. }
  56. bool init_pipe(void)
  57. {
  58. char new_name[64];
  59. sprintf(new_name, "%s%lu", PIPE_NAME, GetCurrentProcessId());
  60. if (!ipc_pipe_client_open(&pipe, new_name)) {
  61. DbgOut("[OBS] Failed to open pipe\n");
  62. return false;
  63. }
  64. return true;
  65. }
  66. static HANDLE init_event(const wchar_t *name, DWORD pid)
  67. {
  68. HANDLE handle = create_event_plus_id(name, pid);
  69. if (!handle)
  70. hlog("Failed to get event '%s': %lu", name, GetLastError());
  71. return handle;
  72. }
  73. static HANDLE init_mutex(const wchar_t *name, DWORD pid)
  74. {
  75. HANDLE handle = create_mutex_plus_id(name, pid);
  76. if (!handle)
  77. hlog("Failed to open mutex '%s': %lu", name, GetLastError());
  78. return handle;
  79. }
  80. static inline bool init_signals(void)
  81. {
  82. DWORD pid = GetCurrentProcessId();
  83. signal_restart = init_event(EVENT_CAPTURE_RESTART, pid);
  84. if (!signal_restart) {
  85. return false;
  86. }
  87. signal_stop = init_event(EVENT_CAPTURE_STOP, pid);
  88. if (!signal_stop) {
  89. return false;
  90. }
  91. signal_ready = init_event(EVENT_HOOK_READY, pid);
  92. if (!signal_ready) {
  93. return false;
  94. }
  95. signal_exit = init_event(EVENT_HOOK_EXIT, pid);
  96. if (!signal_exit) {
  97. return false;
  98. }
  99. signal_init = init_event(EVENT_HOOK_INIT, pid);
  100. if (!signal_init) {
  101. return false;
  102. }
  103. return true;
  104. }
  105. static inline bool init_mutexes(void)
  106. {
  107. DWORD pid = GetCurrentProcessId();
  108. tex_mutexes[0] = init_mutex(MUTEX_TEXTURE1, pid);
  109. if (!tex_mutexes[0]) {
  110. return false;
  111. }
  112. tex_mutexes[1] = init_mutex(MUTEX_TEXTURE2, pid);
  113. if (!tex_mutexes[1]) {
  114. return false;
  115. }
  116. return true;
  117. }
  118. static inline bool init_system_path(void)
  119. {
  120. UINT ret = GetSystemDirectoryA(system_path, MAX_PATH);
  121. if (!ret) {
  122. hlog("Failed to get windows system path: %lu", GetLastError());
  123. return false;
  124. }
  125. return true;
  126. }
  127. static inline void log_current_process(void)
  128. {
  129. DWORD len = GetModuleBaseNameA(GetCurrentProcess(), NULL, process_name,
  130. MAX_PATH);
  131. if (len > 0) {
  132. process_name[len] = 0;
  133. hlog("graphics-hook.dll loaded against process: %s",
  134. process_name);
  135. } else {
  136. hlog("graphics-hook.dll loaded");
  137. }
  138. hlog("(half life scientist) everything.. seems to be in order");
  139. }
  140. static inline bool init_hook_info(void)
  141. {
  142. filemap_hook_info = create_hook_info(GetCurrentProcessId());
  143. if (!filemap_hook_info) {
  144. hlog("Failed to create hook info file mapping: %lu",
  145. GetLastError());
  146. return false;
  147. }
  148. global_hook_info = MapViewOfFile(filemap_hook_info, FILE_MAP_ALL_ACCESS,
  149. 0, 0, sizeof(struct hook_info));
  150. if (!global_hook_info) {
  151. hlog("Failed to map the hook info file mapping: %lu",
  152. GetLastError());
  153. return false;
  154. }
  155. return true;
  156. }
  157. #define DEF_FLAGS (WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS)
  158. static DWORD WINAPI dummy_window_thread(LPVOID *unused)
  159. {
  160. static const wchar_t dummy_window_class[] = L"temp_d3d_window_4039785";
  161. WNDCLASSW wc;
  162. MSG msg;
  163. memset(&wc, 0, sizeof(wc));
  164. wc.style = CS_OWNDC;
  165. wc.hInstance = dll_inst;
  166. wc.lpfnWndProc = (WNDPROC)DefWindowProc;
  167. wc.lpszClassName = dummy_window_class;
  168. if (!RegisterClass(&wc)) {
  169. hlog("Failed to create temp D3D window class: %lu",
  170. GetLastError());
  171. return 0;
  172. }
  173. dummy_window = CreateWindowExW(0, dummy_window_class, L"Temp Window",
  174. DEF_FLAGS, 0, 0, 1, 1, NULL, NULL,
  175. dll_inst, NULL);
  176. if (!dummy_window) {
  177. hlog("Failed to create temp D3D window: %lu", GetLastError());
  178. return 0;
  179. }
  180. while (GetMessage(&msg, NULL, 0, 0)) {
  181. TranslateMessage(&msg);
  182. DispatchMessage(&msg);
  183. }
  184. (void)unused;
  185. return 0;
  186. }
  187. static inline void init_dummy_window_thread(void)
  188. {
  189. HANDLE thread =
  190. CreateThread(NULL, 0, dummy_window_thread, NULL, 0, NULL);
  191. if (!thread) {
  192. hlog("Failed to create temp D3D window thread: %lu",
  193. GetLastError());
  194. return;
  195. }
  196. CloseHandle(thread);
  197. }
  198. static inline bool init_hook(HANDLE thread_handle)
  199. {
  200. wait_for_dll_main_finish(thread_handle);
  201. _snwprintf(keepalive_name, sizeof(keepalive_name) / sizeof(wchar_t),
  202. L"%s%lu", WINDOW_HOOK_KEEPALIVE, GetCurrentProcessId());
  203. init_pipe();
  204. init_dummy_window_thread();
  205. log_current_process();
  206. SetEvent(signal_restart);
  207. return true;
  208. }
  209. static inline void close_handle(HANDLE *handle)
  210. {
  211. if (*handle) {
  212. CloseHandle(*handle);
  213. *handle = NULL;
  214. }
  215. }
  216. static void free_hook(void)
  217. {
  218. if (filemap_hook_info) {
  219. CloseHandle(filemap_hook_info);
  220. filemap_hook_info = NULL;
  221. }
  222. if (global_hook_info) {
  223. UnmapViewOfFile(global_hook_info);
  224. global_hook_info = NULL;
  225. }
  226. close_handle(&tex_mutexes[1]);
  227. close_handle(&tex_mutexes[0]);
  228. close_handle(&signal_exit);
  229. close_handle(&signal_ready);
  230. close_handle(&signal_stop);
  231. close_handle(&signal_restart);
  232. close_handle(&dup_hook_mutex);
  233. ipc_pipe_client_free(&pipe);
  234. }
  235. static inline bool d3d8_hookable(void)
  236. {
  237. return !!global_hook_info->offsets.d3d8.present;
  238. }
  239. static inline bool ddraw_hookable(void)
  240. {
  241. return !!global_hook_info->offsets.ddraw.surface_create &&
  242. !!global_hook_info->offsets.ddraw.surface_restore &&
  243. !!global_hook_info->offsets.ddraw.surface_release &&
  244. !!global_hook_info->offsets.ddraw.surface_unlock &&
  245. !!global_hook_info->offsets.ddraw.surface_blt &&
  246. !!global_hook_info->offsets.ddraw.surface_flip &&
  247. !!global_hook_info->offsets.ddraw.surface_set_palette &&
  248. !!global_hook_info->offsets.ddraw.palette_set_entries;
  249. }
  250. static inline bool d3d9_hookable(void)
  251. {
  252. return !!global_hook_info->offsets.d3d9.present &&
  253. !!global_hook_info->offsets.d3d9.present_ex &&
  254. !!global_hook_info->offsets.d3d9.present_swap;
  255. }
  256. static inline bool dxgi_hookable(void)
  257. {
  258. return !!global_hook_info->offsets.dxgi.present &&
  259. !!global_hook_info->offsets.dxgi.resize;
  260. }
  261. static inline bool attempt_hook(void)
  262. {
  263. //static bool ddraw_hooked = false;
  264. static bool d3d8_hooked = false;
  265. static bool d3d9_hooked = false;
  266. static bool dxgi_hooked = false;
  267. static bool gl_hooked = false;
  268. #if COMPILE_VULKAN_HOOK
  269. static bool vulkan_hooked = false;
  270. if (!vulkan_hooked) {
  271. vulkan_hooked = hook_vulkan();
  272. if (vulkan_hooked) {
  273. return true;
  274. }
  275. }
  276. #endif //COMPILE_VULKAN_HOOK
  277. if (!d3d9_hooked) {
  278. if (!d3d9_hookable()) {
  279. DbgOut("[OBS] no D3D9 hook address found!\n");
  280. d3d9_hooked = true;
  281. } else {
  282. d3d9_hooked = hook_d3d9();
  283. if (d3d9_hooked) {
  284. return true;
  285. }
  286. }
  287. }
  288. if (!dxgi_hooked) {
  289. if (!dxgi_hookable()) {
  290. DbgOut("[OBS] no DXGI hook address found!\n");
  291. dxgi_hooked = true;
  292. } else {
  293. dxgi_hooked = hook_dxgi();
  294. if (dxgi_hooked) {
  295. return true;
  296. }
  297. }
  298. }
  299. if (!gl_hooked) {
  300. gl_hooked = hook_gl();
  301. if (gl_hooked) {
  302. return true;
  303. }
  304. /*} else {
  305. rehook_gl();*/
  306. }
  307. if (!d3d8_hooked) {
  308. if (!d3d8_hookable()) {
  309. d3d8_hooked = true;
  310. } else {
  311. d3d8_hooked = hook_d3d8();
  312. if (d3d8_hooked) {
  313. return true;
  314. }
  315. }
  316. }
  317. /*if (!ddraw_hooked) {
  318. if (!ddraw_hookable()) {
  319. ddraw_hooked = true;
  320. } else {
  321. ddraw_hooked = hook_ddraw();
  322. if (ddraw_hooked) {
  323. return true;
  324. }
  325. }
  326. }*/
  327. return false;
  328. }
  329. static inline void capture_loop(void)
  330. {
  331. WaitForSingleObject(signal_init, INFINITE);
  332. while (!attempt_hook())
  333. Sleep(40);
  334. for (size_t n = 0; !stop_loop; n++) {
  335. /* this causes it to check every 4 seconds, but still with
  336. * a small sleep interval in case the thread needs to stop */
  337. if (n % 100 == 0)
  338. attempt_hook();
  339. Sleep(40);
  340. }
  341. }
  342. static DWORD WINAPI main_capture_thread(HANDLE thread_handle)
  343. {
  344. if (!init_hook(thread_handle)) {
  345. DbgOut("[OBS] Failed to init hook\n");
  346. free_hook();
  347. return 0;
  348. }
  349. capture_loop();
  350. return 0;
  351. }
  352. static inline void hlogv(const char *format, va_list args)
  353. {
  354. char message[1024] = "";
  355. int num = _vsprintf_p(message, 1024, format, args);
  356. if (num > 0) {
  357. if (!ipc_pipe_client_write(&pipe, message, (size_t)num + 1)) {
  358. ipc_pipe_client_free(&pipe);
  359. }
  360. DbgOut("[OBS] ");
  361. DbgOut(message);
  362. DbgOut("\n");
  363. }
  364. }
  365. void hlog(const char *format, ...)
  366. {
  367. va_list args;
  368. va_start(args, format);
  369. hlogv(format, args);
  370. va_end(args);
  371. }
  372. void hlog_hr(const char *text, HRESULT hr)
  373. {
  374. LPSTR buffer = NULL;
  375. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
  376. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  377. FORMAT_MESSAGE_IGNORE_INSERTS,
  378. NULL, hr, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  379. (LPSTR)&buffer, 0, NULL);
  380. if (buffer) {
  381. hlog("%s (0x%08lX): %s", text, hr, buffer);
  382. LocalFree(buffer);
  383. } else {
  384. hlog("%s (0x%08lX)", text, hr);
  385. }
  386. }
  387. static inline uint64_t get_clockfreq(void)
  388. {
  389. static bool have_clockfreq = false;
  390. static LARGE_INTEGER clock_freq;
  391. if (!have_clockfreq) {
  392. QueryPerformanceFrequency(&clock_freq);
  393. have_clockfreq = true;
  394. }
  395. return clock_freq.QuadPart;
  396. }
  397. uint64_t os_gettime_ns(void)
  398. {
  399. LARGE_INTEGER current_time;
  400. double time_val;
  401. QueryPerformanceCounter(&current_time);
  402. time_val = (double)current_time.QuadPart;
  403. time_val *= 1000000000.0;
  404. time_val /= (double)get_clockfreq();
  405. return (uint64_t)time_val;
  406. }
  407. static inline int try_lock_shmem_tex(int id)
  408. {
  409. int next = id == 0 ? 1 : 0;
  410. DWORD wait_result = WAIT_FAILED;
  411. wait_result = WaitForSingleObject(tex_mutexes[id], 0);
  412. if (wait_result == WAIT_OBJECT_0 || wait_result == WAIT_ABANDONED) {
  413. return id;
  414. }
  415. wait_result = WaitForSingleObject(tex_mutexes[next], 0);
  416. if (wait_result == WAIT_OBJECT_0 || wait_result == WAIT_ABANDONED) {
  417. return next;
  418. }
  419. return -1;
  420. }
  421. static inline void unlock_shmem_tex(int id)
  422. {
  423. if (id != -1) {
  424. ReleaseMutex(tex_mutexes[id]);
  425. }
  426. }
  427. static inline bool init_shared_info(size_t size, HWND window)
  428. {
  429. wchar_t name[64];
  430. HWND top = GetAncestor(window, GA_ROOT);
  431. swprintf(name, 64, SHMEM_TEXTURE "_%" PRIu64 "_%u",
  432. (uint64_t)(uintptr_t)top, ++shmem_id_counter);
  433. shmem_file_handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  434. PAGE_READWRITE, 0, (DWORD)size,
  435. name);
  436. if (!shmem_file_handle) {
  437. hlog("init_shared_info: Failed to create shared memory: %d",
  438. GetLastError());
  439. return false;
  440. }
  441. shmem_info = MapViewOfFile(shmem_file_handle, FILE_MAP_ALL_ACCESS, 0, 0,
  442. size);
  443. if (!shmem_info) {
  444. hlog("init_shared_info: Failed to map shared memory: %d",
  445. GetLastError());
  446. return false;
  447. }
  448. return true;
  449. }
  450. bool capture_init_shtex(struct shtex_data **data, HWND window, uint32_t cx,
  451. uint32_t cy, uint32_t format, bool flip,
  452. uintptr_t handle)
  453. {
  454. if (!init_shared_info(sizeof(struct shtex_data), window)) {
  455. hlog("capture_init_shtex: Failed to initialize memory");
  456. return false;
  457. }
  458. *data = shmem_info;
  459. (*data)->tex_handle = (uint32_t)handle;
  460. global_hook_info->hook_ver_major = HOOK_VER_MAJOR;
  461. global_hook_info->hook_ver_minor = HOOK_VER_MINOR;
  462. global_hook_info->window = (uint32_t)(uintptr_t)window;
  463. global_hook_info->type = CAPTURE_TYPE_TEXTURE;
  464. global_hook_info->format = format;
  465. global_hook_info->flip = flip;
  466. global_hook_info->map_id = shmem_id_counter;
  467. global_hook_info->map_size = sizeof(struct shtex_data);
  468. global_hook_info->cx = cx;
  469. global_hook_info->cy = cy;
  470. global_hook_info->UNUSED_base_cx = cx;
  471. global_hook_info->UNUSED_base_cy = cy;
  472. if (!SetEvent(signal_ready)) {
  473. hlog("capture_init_shtex: Failed to signal ready: %d",
  474. GetLastError());
  475. return false;
  476. }
  477. active = true;
  478. return true;
  479. }
  480. static DWORD CALLBACK copy_thread(LPVOID unused)
  481. {
  482. uint32_t pitch = thread_data.pitch;
  483. uint32_t cy = thread_data.cy;
  484. HANDLE events[2] = {NULL, NULL};
  485. int shmem_id = 0;
  486. if (!duplicate_handle(&events[0], thread_data.copy_event)) {
  487. hlog_hr("copy_thread: Failed to duplicate copy event: %d",
  488. GetLastError());
  489. return 0;
  490. }
  491. if (!duplicate_handle(&events[1], thread_data.stop_event)) {
  492. hlog_hr("copy_thread: Failed to duplicate stop event: %d",
  493. GetLastError());
  494. goto finish;
  495. }
  496. for (;;) {
  497. int copy_tex;
  498. void *cur_data;
  499. DWORD ret = WaitForMultipleObjects(2, events, false, INFINITE);
  500. if (ret != WAIT_OBJECT_0) {
  501. break;
  502. }
  503. EnterCriticalSection(&thread_data.data_mutex);
  504. copy_tex = thread_data.cur_tex;
  505. cur_data = thread_data.cur_data;
  506. LeaveCriticalSection(&thread_data.data_mutex);
  507. if (copy_tex < NUM_BUFFERS && !!cur_data) {
  508. EnterCriticalSection(&thread_data.mutexes[copy_tex]);
  509. int lock_id = try_lock_shmem_tex(shmem_id);
  510. if (lock_id != -1) {
  511. memcpy(thread_data.shmem_textures[lock_id],
  512. cur_data, (size_t)pitch * (size_t)cy);
  513. unlock_shmem_tex(lock_id);
  514. ((struct shmem_data *)shmem_info)->last_tex =
  515. lock_id;
  516. shmem_id = lock_id == 0 ? 1 : 0;
  517. }
  518. LeaveCriticalSection(&thread_data.mutexes[copy_tex]);
  519. }
  520. }
  521. finish:
  522. for (size_t i = 0; i < 2; i++) {
  523. if (events[i]) {
  524. CloseHandle(events[i]);
  525. }
  526. }
  527. (void)unused;
  528. return 0;
  529. }
  530. void shmem_copy_data(size_t idx, void *volatile data)
  531. {
  532. EnterCriticalSection(&thread_data.data_mutex);
  533. thread_data.cur_tex = (int)idx;
  534. thread_data.cur_data = data;
  535. thread_data.locked_textures[idx] = true;
  536. LeaveCriticalSection(&thread_data.data_mutex);
  537. SetEvent(thread_data.copy_event);
  538. }
  539. bool shmem_texture_data_lock(int idx)
  540. {
  541. bool locked;
  542. EnterCriticalSection(&thread_data.data_mutex);
  543. locked = thread_data.locked_textures[idx];
  544. LeaveCriticalSection(&thread_data.data_mutex);
  545. if (locked) {
  546. EnterCriticalSection(&thread_data.mutexes[idx]);
  547. return true;
  548. }
  549. return false;
  550. }
  551. void shmem_texture_data_unlock(int idx)
  552. {
  553. EnterCriticalSection(&thread_data.data_mutex);
  554. thread_data.locked_textures[idx] = false;
  555. LeaveCriticalSection(&thread_data.data_mutex);
  556. LeaveCriticalSection(&thread_data.mutexes[idx]);
  557. }
  558. static inline bool init_shmem_thread(uint32_t pitch, uint32_t cy)
  559. {
  560. struct shmem_data *data = shmem_info;
  561. thread_data.pitch = pitch;
  562. thread_data.cy = cy;
  563. thread_data.shmem_textures[0] = (uint8_t *)data + data->tex1_offset;
  564. thread_data.shmem_textures[1] = (uint8_t *)data + data->tex2_offset;
  565. thread_data.copy_event = CreateEvent(NULL, false, false, NULL);
  566. if (!thread_data.copy_event) {
  567. hlog("init_shmem_thread: Failed to create copy event: %d",
  568. GetLastError());
  569. return false;
  570. }
  571. thread_data.stop_event = CreateEvent(NULL, true, false, NULL);
  572. if (!thread_data.stop_event) {
  573. hlog("init_shmem_thread: Failed to create stop event: %d",
  574. GetLastError());
  575. return false;
  576. }
  577. for (size_t i = 0; i < NUM_BUFFERS; i++) {
  578. InitializeCriticalSection(&thread_data.mutexes[i]);
  579. }
  580. InitializeCriticalSection(&thread_data.data_mutex);
  581. thread_data.copy_thread =
  582. CreateThread(NULL, 0, copy_thread, NULL, 0, NULL);
  583. if (!thread_data.copy_thread) {
  584. hlog("init_shmem_thread: Failed to create thread: %d",
  585. GetLastError());
  586. return false;
  587. }
  588. return true;
  589. }
  590. #ifndef ALIGN
  591. #define ALIGN(bytes, align) (((bytes) + ((align)-1)) & ~((align)-1))
  592. #endif
  593. bool capture_init_shmem(struct shmem_data **data, HWND window, uint32_t cx,
  594. uint32_t cy, uint32_t pitch, uint32_t format, bool flip)
  595. {
  596. uint32_t tex_size = cy * pitch;
  597. uint32_t aligned_header = ALIGN(sizeof(struct shmem_data), 32);
  598. uint32_t aligned_tex = ALIGN(tex_size, 32);
  599. uint32_t total_size = aligned_header + aligned_tex * 2 + 32;
  600. uintptr_t align_pos;
  601. if (!init_shared_info(total_size, window)) {
  602. hlog("capture_init_shmem: Failed to initialize memory");
  603. return false;
  604. }
  605. *data = shmem_info;
  606. /* to ensure fast copy rate, align texture data to 256bit addresses */
  607. align_pos = (uintptr_t)shmem_info;
  608. align_pos += aligned_header;
  609. align_pos &= ~(32 - 1);
  610. align_pos -= (uintptr_t)shmem_info;
  611. if (align_pos < sizeof(struct shmem_data))
  612. align_pos += 32;
  613. (*data)->last_tex = -1;
  614. (*data)->tex1_offset = (uint32_t)align_pos;
  615. (*data)->tex2_offset = (*data)->tex1_offset + aligned_tex;
  616. global_hook_info->hook_ver_major = HOOK_VER_MAJOR;
  617. global_hook_info->hook_ver_minor = HOOK_VER_MINOR;
  618. global_hook_info->window = (uint32_t)(uintptr_t)window;
  619. global_hook_info->type = CAPTURE_TYPE_MEMORY;
  620. global_hook_info->format = format;
  621. global_hook_info->flip = flip;
  622. global_hook_info->map_id = shmem_id_counter;
  623. global_hook_info->map_size = total_size;
  624. global_hook_info->pitch = pitch;
  625. global_hook_info->cx = cx;
  626. global_hook_info->cy = cy;
  627. global_hook_info->UNUSED_base_cx = cx;
  628. global_hook_info->UNUSED_base_cy = cy;
  629. if (!init_shmem_thread(pitch, cy)) {
  630. return false;
  631. }
  632. if (!SetEvent(signal_ready)) {
  633. hlog("capture_init_shmem: Failed to signal ready: %d",
  634. GetLastError());
  635. return false;
  636. }
  637. active = true;
  638. return true;
  639. }
  640. static inline void thread_data_free(void)
  641. {
  642. if (thread_data.copy_thread) {
  643. DWORD ret;
  644. SetEvent(thread_data.stop_event);
  645. ret = WaitForSingleObject(thread_data.copy_thread, 500);
  646. if (ret != WAIT_OBJECT_0)
  647. TerminateThread(thread_data.copy_thread, (DWORD)-1);
  648. CloseHandle(thread_data.copy_thread);
  649. }
  650. if (thread_data.stop_event)
  651. CloseHandle(thread_data.stop_event);
  652. if (thread_data.copy_event)
  653. CloseHandle(thread_data.copy_event);
  654. for (size_t i = 0; i < NUM_BUFFERS; i++)
  655. DeleteCriticalSection(&thread_data.mutexes[i]);
  656. DeleteCriticalSection(&thread_data.data_mutex);
  657. memset(&thread_data, 0, sizeof(thread_data));
  658. }
  659. void capture_free(void)
  660. {
  661. thread_data_free();
  662. if (shmem_info) {
  663. UnmapViewOfFile(shmem_info);
  664. shmem_info = NULL;
  665. }
  666. close_handle(&shmem_file_handle);
  667. SetEvent(signal_restart);
  668. active = false;
  669. }
  670. #define HOOK_NAME L"graphics_hook_dup_mutex"
  671. static inline HANDLE open_mutex_plus_id(const wchar_t *name, DWORD id)
  672. {
  673. wchar_t new_name[64];
  674. _snwprintf(new_name, 64, L"%s%lu", name, id);
  675. return open_mutex(new_name);
  676. }
  677. static bool init_dll(void)
  678. {
  679. DWORD pid = GetCurrentProcessId();
  680. HANDLE h;
  681. h = open_mutex_plus_id(HOOK_NAME, pid);
  682. if (h) {
  683. CloseHandle(h);
  684. return false;
  685. }
  686. dup_hook_mutex = create_mutex_plus_id(HOOK_NAME, pid);
  687. return !!dup_hook_mutex;
  688. }
  689. BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID unused1)
  690. {
  691. if (reason == DLL_PROCESS_ATTACH) {
  692. wchar_t name[MAX_PATH];
  693. dll_inst = hinst;
  694. if (!init_dll()) {
  695. DbgOut("[OBS] Duplicate hook library");
  696. return false;
  697. }
  698. HANDLE cur_thread;
  699. bool success = DuplicateHandle(GetCurrentProcess(),
  700. GetCurrentThread(),
  701. GetCurrentProcess(), &cur_thread,
  702. SYNCHRONIZE, false, 0);
  703. if (!success)
  704. DbgOut("[OBS] Failed to get current thread handle");
  705. if (!init_signals()) {
  706. return false;
  707. }
  708. if (!init_system_path()) {
  709. return false;
  710. }
  711. if (!init_hook_info()) {
  712. return false;
  713. }
  714. if (!init_mutexes()) {
  715. return false;
  716. }
  717. /* this prevents the library from being automatically unloaded
  718. * by the next FreeLibrary call */
  719. GetModuleFileNameW(hinst, name, MAX_PATH);
  720. LoadLibraryW(name);
  721. capture_thread = CreateThread(
  722. NULL, 0, (LPTHREAD_START_ROUTINE)main_capture_thread,
  723. (LPVOID)cur_thread, 0, 0);
  724. if (!capture_thread) {
  725. CloseHandle(cur_thread);
  726. return false;
  727. }
  728. } else if (reason == DLL_PROCESS_DETACH) {
  729. if (!dup_hook_mutex) {
  730. return true;
  731. }
  732. if (capture_thread) {
  733. stop_loop = true;
  734. WaitForSingleObject(capture_thread, 300);
  735. CloseHandle(capture_thread);
  736. }
  737. free_hook();
  738. }
  739. (void)unused1;
  740. return true;
  741. }
  742. __declspec(dllexport) LRESULT CALLBACK
  743. dummy_debug_proc(int code, WPARAM wparam, LPARAM lparam)
  744. {
  745. static bool hooking = true;
  746. MSG *msg = (MSG *)lparam;
  747. if (hooking && msg->message == (WM_USER + 432)) {
  748. HMODULE user32 = GetModuleHandleW(L"USER32");
  749. BOOL(WINAPI * unhook_windows_hook_ex)(HHOOK) = NULL;
  750. unhook_windows_hook_ex = get_obfuscated_func(
  751. user32, "VojeleY`bdgxvM`hhDz", 0x7F55F80C9EE3A213ULL);
  752. if (unhook_windows_hook_ex)
  753. unhook_windows_hook_ex((HHOOK)msg->lParam);
  754. hooking = false;
  755. }
  756. return CallNextHookEx(0, code, wparam, lparam);
  757. }