You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

493 lines
13 KiB

  1. /*
  2. * main.cpp -- The main "entry point" and the main logic of the DLL.
  3. *
  4. * Here, we define and initialize struct Main that contains the main code of this DLL.
  5. *
  6. * The main procedure goes as follows:
  7. * 1. The loader checks that PatchLoader.dll and mono.dll exist
  8. * 2. mono.dll is loaded into memory and some of its functions are looked up
  9. * 3. mono_jit_init_version is hooked with the help of MinHook
  10. *
  11. * Then, the loader waits until Unity creates its root domain for mono (which is done with mono_jit_init_version).
  12. *
  13. * Inside mono_jit_init_version hook:
  14. * 1. Call the original mono_jit_init_version to get the Unity root domain
  15. * 2. Load PatchLoader.dll into the root domain
  16. * 3. Find and invoke PatchLoader.Loader.Run()
  17. *
  18. * Rest of the work is done on the managed side.
  19. *
  20. */
  21. #pragma warning( disable : 4267 100 152 6387 4456 6011 )
  22. #include "winapi_util.h"
  23. #include <Windows.h>
  24. #include "config.h"
  25. #include "mono.h"
  26. #include "hook.h"
  27. #include "assert_util.h"
  28. #include "proxy.h"
  29. #include <synchapi.h>
  30. #include <intrin.h>
  31. EXTERN_C IMAGE_DOS_HEADER __ImageBase; // This is provided by MSVC with the infomration about this DLL
  32. HANDLE unhandledMutex;
  33. void ownMonoJitParseOptions(int argc, char * argv[]);
  34. BOOL setOptions = FALSE;
  35. BOOL shouldBreakOnUnhandledException = TRUE;
  36. __declspec(dllexport) void SetIgnoreUnhandledExceptions(BOOL ignore)
  37. {
  38. shouldBreakOnUnhandledException = ignore;
  39. }
  40. void unhandledException(void* exc, void* data)
  41. {
  42. WaitForSingleObject(unhandledMutex, INFINITE);
  43. void* exception = NULL;
  44. void* mstr = mono_object_to_string(exc, &exception);
  45. if (exception != NULL)
  46. {
  47. #ifdef _VERBOSE
  48. void* monostr = mono_object_to_string(exception, &exception);
  49. if (exception != NULL)
  50. {
  51. DEBUG_BREAK;
  52. LOG("An error occurred while stringifying uncaught error, but the error could not be stringified.\n");
  53. ASSERT(FALSE, L"Uncaught exception; could not stringify");
  54. }
  55. else
  56. {
  57. char* str = mono_string_to_utf8(monostr);
  58. DEBUG_BREAK;
  59. LOG("An error occurred stringifying uncaught error: %s\n", str);
  60. /*size_t len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  61. wchar_t* wstr = memalloc(sizeof(wchar_t) * len);
  62. MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, len);*/
  63. wchar_t* wstr = mono_string_to_utf16(monostr);
  64. ASSERT_F(FALSE, L"Uncaught exception; stringify failed: %wS", wstr);
  65. mono_free(wstr);
  66. mono_free(str);
  67. }
  68. #else
  69. ASSERT(FALSE, L"Could not stringify uncaught exception");
  70. #endif
  71. }
  72. char* str = mono_string_to_utf8(mstr);
  73. DEBUG_BREAK;
  74. LOG("Uncaught exception: %s\n", str);
  75. /*size_t len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  76. wchar_t* wstr = memalloc(sizeof(wchar_t) * len);
  77. MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, len);*/
  78. wchar_t* wstr = mono_string_to_utf16(mstr);
  79. if (shouldBreakOnUnhandledException)
  80. {
  81. #ifdef _VERBOSE
  82. ASSERT(FALSE, L"Uncaught exception; see doorstop.log for details");
  83. #else
  84. ASSERT_F(FALSE, L"Uncaught exception: %wS", wstr);
  85. #endif
  86. }
  87. mono_free(wstr);
  88. mono_free(str);
  89. ReleaseMutex(unhandledMutex);
  90. }
  91. // The hook for mono_jit_init_version
  92. // We use this since it will always be called once to initialize Mono's JIT
  93. void *ownMonoJitInitVersion(const char *root_domain_name, const char *runtime_version)
  94. {
  95. const BOOL debugger_already_initialized = mono_debug_enabled();
  96. if(debugger_already_initialized)
  97. {
  98. LOG("Debugger was already initialized\n");
  99. }
  100. // Call the original mono_jit_init_version to initialize the Unity Root Domain
  101. if (debug) {
  102. char* opts[1];
  103. opts[0] = "";
  104. ownMonoJitParseOptions(0, opts);
  105. }
  106. #ifdef WIN32
  107. if (debug_info && !debugger_already_initialized) {
  108. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  109. }
  110. #endif
  111. void *domain = mono_jit_init_version(root_domain_name, runtime_version);
  112. if (debug_info && !debugger_already_initialized) {
  113. #ifdef WIN64
  114. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  115. #endif
  116. mono_debug_domain_create(domain);
  117. }
  118. size_t len = WideCharToMultiByte(CP_UTF8, 0, targetAssembly, -1, NULL, 0, NULL, NULL);
  119. char *dll_path = memalloc(sizeof(char) * len);
  120. WideCharToMultiByte(CP_UTF8, 0, targetAssembly, -1, dll_path, len, NULL, NULL);
  121. LOG("Loading assembly: %s\n", dll_path);
  122. // Load our custom assembly into the domain
  123. void *assembly = mono_domain_assembly_open(domain, dll_path);
  124. if (assembly == NULL)
  125. LOG("Failed to load assembly\n");
  126. memfree(dll_path);
  127. ASSERT_SOFT(assembly != NULL, domain);
  128. // Get assembly's image that contains CIL code
  129. void *image = mono_assembly_get_image(assembly);
  130. ASSERT_SOFT(image != NULL, domain);
  131. // Note: we use the runtime_invoke route since jit_exec will not work on DLLs
  132. // Create a descriptor for a random Main method
  133. void *desc = mono_method_desc_new("*:Main", FALSE);
  134. // Find the first possible Main method in the assembly
  135. void *method = mono_method_desc_search_in_image(desc, image);
  136. ASSERT_SOFT(method != NULL, domain);
  137. void *signature = mono_method_signature(method);
  138. // Get the number of parameters in the signature
  139. UINT32 params = mono_signature_get_param_count(signature);
  140. void **args = NULL;
  141. wchar_t *app_path = NULL;
  142. if (params == 1)
  143. {
  144. // If there is a parameter, it's most likely a string[].
  145. // Populate it as follows
  146. // 0 => path to the game's executable
  147. // 1 => --doorstop-invoke
  148. get_module_path(NULL, &app_path, NULL, 0);
  149. void *exe_path = MONO_STRING(app_path);
  150. void *doorstop_handle = MONO_STRING(L"--doorstop-invoke");
  151. void *args_array = mono_array_new(domain, mono_get_string_class(), 2);
  152. SET_ARRAY_REF(args_array, 0, exe_path);
  153. SET_ARRAY_REF(args_array, 1, doorstop_handle);
  154. args = memalloc(sizeof(void*) * 1);
  155. _ASSERTE(args != nullptr);
  156. args[0] = args_array;
  157. }
  158. LOG("Installing uncaught exception handler\n");
  159. mono_install_unhandled_exception_hook(unhandledException, NULL);
  160. wchar_t* dll_path_w; // self path
  161. size_t dll_path_len = get_module_path((HINSTANCE)&__ImageBase, &dll_path_w, NULL, 0);
  162. size_t multibyte_path_len = WideCharToMultiByte(CP_UTF8, 0, dll_path_w, dll_path_len, NULL, 0, NULL, NULL);
  163. char* self_dll_path = memalloc(multibyte_path_len + 1);
  164. WideCharToMultiByte(CP_UTF8, 0, dll_path_w, dll_path_len, self_dll_path, multibyte_path_len + 1, NULL, NULL);
  165. self_dll_path[multibyte_path_len] = 0;
  166. mono_dllmap_insert(NULL, "i:bsipa-doorstop", NULL, self_dll_path, NULL); // remap `bsipa-doorstop` to this assembly
  167. memfree(self_dll_path);
  168. memfree(dll_path_w);
  169. unhandledMutex = CreateMutexW(NULL, FALSE, NULL);
  170. LOG("Invoking method!\n");
  171. void* exception = NULL;
  172. mono_runtime_invoke(method, NULL, args, &exception);
  173. WaitForSingleObject(unhandledMutex, INFINITE); // if the EH is triggered, wait for it
  174. if (args != NULL)
  175. {
  176. memfree(app_path);
  177. memfree(args);
  178. NULL;
  179. }
  180. #ifdef _VERBOSE
  181. if (exception != NULL)
  182. {
  183. void* monostr = mono_object_to_string(exception, &exception);
  184. if (exception != NULL)
  185. LOG("An error occurred while invoking the injector, but the error could not be stringified.\n")
  186. else
  187. {
  188. char* str = mono_string_to_utf8(monostr);
  189. LOG("An error occurred invoking the injector: %s\n", str);
  190. mono_free(str);
  191. }
  192. }
  193. #endif
  194. cleanupConfig();
  195. free_logger();
  196. ReleaseMutex(unhandledMutex);
  197. return domain;
  198. }
  199. void ownMonoJitParseOptions(int argc, char * argv[])
  200. {
  201. setOptions = TRUE;
  202. int size = argc;
  203. #ifdef WIN64
  204. if (debug) size += 2;
  205. #elif defined(WIN32)
  206. if (debug) size += 1;
  207. #endif
  208. char** arguments = memalloc(sizeof(char*) * size);
  209. _ASSERTE(arguments != nullptr);
  210. memcpy(arguments, argv, sizeof(char*) * argc);
  211. if (debug) {
  212. //arguments[argc++] = "--debug";
  213. #ifdef WIN64
  214. arguments[argc++] = "--soft-breakpoints";
  215. #endif
  216. if (debug_server)
  217. arguments[argc] = "--debugger-agent=transport=dt_socket,address=0.0.0.0:10000,server=y";
  218. else
  219. arguments[argc] = "--debugger-agent=transport=dt_socket,address=127.0.0.1:10000,server=n";
  220. }
  221. mono_jit_parse_options(size, arguments);
  222. memfree(arguments);
  223. }
  224. BOOL initialized = FALSE;
  225. void init(HMODULE module)
  226. {
  227. if (!initialized)
  228. {
  229. initialized = TRUE;
  230. LOG("Got mono.dll at %p\n", module);
  231. loadMonoFunctions(module);
  232. }
  233. }
  234. void * WINAPI hookGetProcAddress(HMODULE module, char const *name)
  235. {
  236. if (lstrcmpA(name, "mono_jit_init_version") == 0)
  237. {
  238. init(module);
  239. return (void*)&ownMonoJitInitVersion;
  240. }
  241. if (lstrcmpA(name, "mono_jit_parse_options") == 0 && debug)
  242. {
  243. init(module);
  244. return (void*)&ownMonoJitParseOptions;
  245. }
  246. return (void*)GetProcAddress(module, name);
  247. }
  248. BOOL hookGetMessage(
  249. BOOL isW,
  250. LPMSG msg,
  251. HWND hwnd,
  252. UINT wMsgFilterMin,
  253. UINT wMsgFilterMax
  254. );
  255. BOOL WINAPI hookGetMessageA(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax)
  256. {
  257. return hookGetMessage(FALSE, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  258. }
  259. BOOL WINAPI hookGetMessageW(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax)
  260. {
  261. return hookGetMessage(TRUE, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  262. }
  263. typedef BOOL(*GetMessageHook)(BOOL isW, BOOL result, LPMSG msg, HWND hwnd, UINT filterMin, UINT filterMax);
  264. GetMessageHook getMessageHook = NULL;
  265. __declspec(dllexport) void __stdcall SetGetMessageHook(GetMessageHook hook) {
  266. getMessageHook = hook;
  267. }
  268. BOOL hookGetMessage(
  269. BOOL isW,
  270. LPMSG msg,
  271. HWND hwnd,
  272. UINT wMsgFilterMin,
  273. UINT wMsgFilterMax
  274. )
  275. {
  276. BOOL loop = FALSE;
  277. BOOL result;
  278. do {
  279. if (isW) {
  280. result = GetMessageW(msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  281. } else {
  282. result = GetMessageA(msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  283. }
  284. if (getMessageHook) {
  285. loop = getMessageHook(isW, result, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  286. }
  287. } while (loop);
  288. return result;
  289. }
  290. BOOL hookPeekMessage(
  291. BOOL isW,
  292. LPMSG msg,
  293. HWND hwnd,
  294. UINT wMsgFilterMin,
  295. UINT wMsgFilterMax,
  296. UINT wRemoveMsg
  297. );
  298. BOOL WINAPI hookPeekMessageA(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg)
  299. {
  300. return hookPeekMessage(FALSE, msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  301. }
  302. BOOL WINAPI hookPeekMessageW(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg)
  303. {
  304. return hookPeekMessage(TRUE, msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  305. }
  306. typedef BOOL(*PeekMessageHook)(BOOL isW, BOOL result, LPMSG msg, HWND hwnd, UINT filterMin, UINT filterMax, UINT* wRemoveMsg);
  307. PeekMessageHook peekMessageHook = NULL;
  308. __declspec(dllexport) void __stdcall SetPeekMessageHook(PeekMessageHook hook) {
  309. peekMessageHook = hook;
  310. }
  311. BOOL hookPeekMessage(
  312. BOOL isW,
  313. LPMSG msg,
  314. HWND hwnd,
  315. UINT wMsgFilterMin,
  316. UINT wMsgFilterMax,
  317. UINT wRemoveMsg
  318. )
  319. {
  320. BOOL loop = FALSE;
  321. BOOL result;
  322. do {
  323. if (isW) {
  324. result = PeekMessageW(msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  325. }
  326. else {
  327. result = PeekMessageA(msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  328. }
  329. if (peekMessageHook) {
  330. loop = peekMessageHook(isW, result, msg, hwnd, wMsgFilterMin, wMsgFilterMax, &wRemoveMsg);
  331. }
  332. } while (loop);
  333. return result;
  334. }
  335. BOOL WINAPI DllMain(HINSTANCE hInstDll, DWORD reasonForDllLoad, LPVOID reserved)
  336. {
  337. if (reasonForDllLoad != DLL_PROCESS_ATTACH)
  338. return TRUE;
  339. hHeap = GetProcessHeap();
  340. init_logger();
  341. LOG("Doorstop started!\n");
  342. wchar_t *dll_path = NULL;
  343. size_t dll_path_len = get_module_path((HINSTANCE)&__ImageBase, &dll_path, NULL, 0);
  344. LOG("DLL Path: %S\n", dll_path);
  345. wchar_t *dll_name = get_file_name_no_ext(dll_path, dll_path_len);
  346. LOG("Doorstop DLL Name: %S\n", dll_name);
  347. loadProxy(dll_name);
  348. loadConfig();
  349. // If the loader is disabled, don't inject anything.
  350. if (enabled)
  351. {
  352. LOG("Doorstop enabled!\n");
  353. ASSERT_SOFT(GetFileAttributesW(targetAssembly) != INVALID_FILE_ATTRIBUTES, TRUE);
  354. HMODULE targetModule = GetModuleHandleA("UnityPlayer");
  355. if(targetModule == NULL)
  356. {
  357. LOG("No UnityPlayer.dll; using EXE as the hook target.");
  358. targetModule = GetModuleHandleA(NULL);
  359. }
  360. LOG("Installing IAT hook\n");
  361. if (!iat_hook(targetModule, "kernel32.dll", &GetProcAddress, &hookGetProcAddress))
  362. {
  363. LOG("Failed to install IAT hook!\n");
  364. free_logger();
  365. }
  366. LOG("Hook installed!\n");
  367. LOG("Attempting to install GetMessageA and GetMessageW hooks\n");
  368. if (!iat_hook(targetModule, "user32.dll", &GetMessageA, &hookGetMessageA)) {
  369. LOG("Could not hook GetMessageA! (not an error)\n");
  370. }
  371. if (!iat_hook(targetModule, "user32.dll", &GetMessageW, &hookGetMessageW)) {
  372. LOG("Could not hook GetMessageW! (not an error)\n");
  373. }
  374. LOG("Attempting to install PeekMessageA and PeekMessageW hooks\n");
  375. if (!iat_hook(targetModule, "user32.dll", &PeekMessageA, &hookPeekMessageA)) {
  376. LOG("Could not hook PeekMessageA! (not an error)\n");
  377. }
  378. if (!iat_hook(targetModule, "user32.dll", &PeekMessageW, &hookPeekMessageW)) {
  379. LOG("Could not hook PeekMessageW! (not an error)\n");
  380. }
  381. }
  382. else
  383. {
  384. LOG("Doorstop disabled! memfreeing resources\n");
  385. free_logger();
  386. }
  387. memfree(dll_name);
  388. memfree(dll_path);
  389. return TRUE;
  390. }