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.

484 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. // Call the original mono_jit_init_version to initialize the Unity Root Domain
  96. if (debug) {
  97. char* opts[1];
  98. opts[0] = "";
  99. ownMonoJitParseOptions(0, opts);
  100. }
  101. #ifdef WIN32
  102. if (debug_info) {
  103. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  104. }
  105. #endif
  106. void *domain = mono_jit_init_version(root_domain_name, runtime_version);
  107. if (debug_info) {
  108. #ifdef WIN64
  109. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  110. #endif
  111. mono_debug_domain_create(domain);
  112. }
  113. size_t len = WideCharToMultiByte(CP_UTF8, 0, targetAssembly, -1, NULL, 0, NULL, NULL);
  114. char *dll_path = memalloc(sizeof(char) * len);
  115. WideCharToMultiByte(CP_UTF8, 0, targetAssembly, -1, dll_path, len, NULL, NULL);
  116. LOG("Loading assembly: %s\n", dll_path);
  117. // Load our custom assembly into the domain
  118. void *assembly = mono_domain_assembly_open(domain, dll_path);
  119. if (assembly == NULL)
  120. LOG("Failed to load assembly\n");
  121. memfree(dll_path);
  122. ASSERT_SOFT(assembly != NULL, domain);
  123. // Get assembly's image that contains CIL code
  124. void *image = mono_assembly_get_image(assembly);
  125. ASSERT_SOFT(image != NULL, domain);
  126. // Note: we use the runtime_invoke route since jit_exec will not work on DLLs
  127. // Create a descriptor for a random Main method
  128. void *desc = mono_method_desc_new("*:Main", FALSE);
  129. // Find the first possible Main method in the assembly
  130. void *method = mono_method_desc_search_in_image(desc, image);
  131. ASSERT_SOFT(method != NULL, domain);
  132. void *signature = mono_method_signature(method);
  133. // Get the number of parameters in the signature
  134. UINT32 params = mono_signature_get_param_count(signature);
  135. void **args = NULL;
  136. wchar_t *app_path = NULL;
  137. if (params == 1)
  138. {
  139. // If there is a parameter, it's most likely a string[].
  140. // Populate it as follows
  141. // 0 => path to the game's executable
  142. // 1 => --doorstop-invoke
  143. get_module_path(NULL, &app_path, NULL, 0);
  144. void *exe_path = MONO_STRING(app_path);
  145. void *doorstop_handle = MONO_STRING(L"--doorstop-invoke");
  146. void *args_array = mono_array_new(domain, mono_get_string_class(), 2);
  147. SET_ARRAY_REF(args_array, 0, exe_path);
  148. SET_ARRAY_REF(args_array, 1, doorstop_handle);
  149. args = memalloc(sizeof(void*) * 1);
  150. _ASSERTE(args != nullptr);
  151. args[0] = args_array;
  152. }
  153. LOG("Installing uncaught exception handler\n");
  154. mono_install_unhandled_exception_hook(unhandledException, NULL);
  155. wchar_t* dll_path_w; // self path
  156. size_t dll_path_len = get_module_path((HINSTANCE)&__ImageBase, &dll_path_w, NULL, 0);
  157. char* self_dll_path = memalloc(dll_path_len + 1);
  158. WideCharToMultiByte(CP_UTF8, 0, dll_path_w, -1, self_dll_path, dll_path_len + 1, NULL, NULL);
  159. mono_dllmap_insert(NULL, "i:bsipa-doorstop", NULL, self_dll_path, NULL); // remap `bsipa-doorstop` to this assembly
  160. memfree(self_dll_path);
  161. memfree(dll_path_w);
  162. unhandledMutex = CreateMutexW(NULL, FALSE, NULL);
  163. LOG("Invoking method!\n");
  164. void* exception = NULL;
  165. mono_runtime_invoke(method, NULL, args, &exception);
  166. WaitForSingleObject(unhandledMutex, INFINITE); // if the EH is triggered, wait for it
  167. if (args != NULL)
  168. {
  169. memfree(app_path);
  170. memfree(args);
  171. NULL;
  172. }
  173. #ifdef _VERBOSE
  174. if (exception != NULL)
  175. {
  176. void* monostr = mono_object_to_string(exception, &exception);
  177. if (exception != NULL)
  178. LOG("An error occurred while invoking the injector, but the error could not be stringified.\n")
  179. else
  180. {
  181. char* str = mono_string_to_utf8(monostr);
  182. LOG("An error occurred invoking the injector: %s\n", str);
  183. mono_free(str);
  184. }
  185. }
  186. #endif
  187. cleanupConfig();
  188. free_logger();
  189. ReleaseMutex(unhandledMutex);
  190. return domain;
  191. }
  192. void ownMonoJitParseOptions(int argc, char * argv[])
  193. {
  194. setOptions = TRUE;
  195. int size = argc;
  196. #ifdef WIN64
  197. if (debug) size += 2;
  198. #elif defined(WIN32)
  199. if (debug) size += 1;
  200. #endif
  201. char** arguments = memalloc(sizeof(char*) * size);
  202. _ASSERTE(arguments != nullptr);
  203. memcpy(arguments, argv, sizeof(char*) * argc);
  204. if (debug) {
  205. //arguments[argc++] = "--debug";
  206. #ifdef WIN64
  207. arguments[argc++] = "--soft-breakpoints";
  208. #endif
  209. if (debug_server)
  210. arguments[argc] = "--debugger-agent=transport=dt_socket,address=0.0.0.0:10000,server=y";
  211. else
  212. arguments[argc] = "--debugger-agent=transport=dt_socket,address=127.0.0.1:10000,server=n";
  213. }
  214. mono_jit_parse_options(size, arguments);
  215. memfree(arguments);
  216. }
  217. BOOL initialized = FALSE;
  218. void init(HMODULE module)
  219. {
  220. if (!initialized)
  221. {
  222. initialized = TRUE;
  223. LOG("Got mono.dll at %p\n", module);
  224. loadMonoFunctions(module);
  225. }
  226. }
  227. void * WINAPI hookGetProcAddress(HMODULE module, char const *name)
  228. {
  229. if (lstrcmpA(name, "mono_jit_init_version") == 0)
  230. {
  231. init(module);
  232. return (void*)&ownMonoJitInitVersion;
  233. }
  234. if (lstrcmpA(name, "mono_jit_parse_options") == 0 && debug)
  235. {
  236. init(module);
  237. return (void*)&ownMonoJitParseOptions;
  238. }
  239. return (void*)GetProcAddress(module, name);
  240. }
  241. BOOL hookGetMessage(
  242. BOOL isW,
  243. LPMSG msg,
  244. HWND hwnd,
  245. UINT wMsgFilterMin,
  246. UINT wMsgFilterMax
  247. );
  248. BOOL WINAPI hookGetMessageA(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax)
  249. {
  250. return hookGetMessage(FALSE, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  251. }
  252. BOOL WINAPI hookGetMessageW(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax)
  253. {
  254. return hookGetMessage(TRUE, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  255. }
  256. typedef BOOL(*GetMessageHook)(BOOL isW, BOOL result, LPMSG msg, HWND hwnd, UINT filterMin, UINT filterMax);
  257. GetMessageHook getMessageHook = NULL;
  258. __declspec(dllexport) void __stdcall SetGetMessageHook(GetMessageHook hook) {
  259. getMessageHook = hook;
  260. }
  261. BOOL hookGetMessage(
  262. BOOL isW,
  263. LPMSG msg,
  264. HWND hwnd,
  265. UINT wMsgFilterMin,
  266. UINT wMsgFilterMax
  267. )
  268. {
  269. BOOL loop = FALSE;
  270. BOOL result;
  271. do {
  272. if (isW) {
  273. result = GetMessageW(msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  274. } else {
  275. result = GetMessageA(msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  276. }
  277. if (getMessageHook) {
  278. loop = getMessageHook(isW, result, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  279. }
  280. } while (loop);
  281. return result;
  282. }
  283. BOOL hookPeekMessage(
  284. BOOL isW,
  285. LPMSG msg,
  286. HWND hwnd,
  287. UINT wMsgFilterMin,
  288. UINT wMsgFilterMax,
  289. UINT wRemoveMsg
  290. );
  291. BOOL WINAPI hookPeekMessageA(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg)
  292. {
  293. return hookPeekMessage(FALSE, msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  294. }
  295. BOOL WINAPI hookPeekMessageW(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg)
  296. {
  297. return hookPeekMessage(TRUE, msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  298. }
  299. typedef BOOL(*PeekMessageHook)(BOOL isW, BOOL result, LPMSG msg, HWND hwnd, UINT filterMin, UINT filterMax, UINT* wRemoveMsg);
  300. PeekMessageHook peekMessageHook = NULL;
  301. __declspec(dllexport) void __stdcall SetPeekMessageHook(PeekMessageHook hook) {
  302. peekMessageHook = hook;
  303. }
  304. BOOL hookPeekMessage(
  305. BOOL isW,
  306. LPMSG msg,
  307. HWND hwnd,
  308. UINT wMsgFilterMin,
  309. UINT wMsgFilterMax,
  310. UINT wRemoveMsg
  311. )
  312. {
  313. BOOL loop = FALSE;
  314. BOOL result;
  315. do {
  316. if (isW) {
  317. result = PeekMessageW(msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  318. }
  319. else {
  320. result = PeekMessageA(msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  321. }
  322. if (peekMessageHook) {
  323. loop = peekMessageHook(isW, result, msg, hwnd, wMsgFilterMin, wMsgFilterMax, &wRemoveMsg);
  324. }
  325. } while (loop);
  326. return result;
  327. }
  328. BOOL WINAPI DllMain(HINSTANCE hInstDll, DWORD reasonForDllLoad, LPVOID reserved)
  329. {
  330. if (reasonForDllLoad != DLL_PROCESS_ATTACH)
  331. return TRUE;
  332. hHeap = GetProcessHeap();
  333. init_logger();
  334. LOG("Doorstop started!\n");
  335. wchar_t *dll_path = NULL;
  336. size_t dll_path_len = get_module_path((HINSTANCE)&__ImageBase, &dll_path, NULL, 0);
  337. LOG("DLL Path: %S\n", dll_path);
  338. wchar_t *dll_name = get_file_name_no_ext(dll_path, dll_path_len);
  339. LOG("Doorstop DLL Name: %S\n", dll_name);
  340. loadProxy(dll_name);
  341. loadConfig();
  342. // If the loader is disabled, don't inject anything.
  343. if (enabled)
  344. {
  345. LOG("Doorstop enabled!\n");
  346. ASSERT_SOFT(GetFileAttributesW(targetAssembly) != INVALID_FILE_ATTRIBUTES, TRUE);
  347. HMODULE targetModule = GetModuleHandleA("UnityPlayer");
  348. if(targetModule == NULL)
  349. {
  350. LOG("No UnityPlayer.dll; using EXE as the hook target.");
  351. targetModule = GetModuleHandleA(NULL);
  352. }
  353. LOG("Installing IAT hook\n");
  354. if (!iat_hook(targetModule, "kernel32.dll", &GetProcAddress, &hookGetProcAddress))
  355. {
  356. LOG("Failed to install IAT hook!\n");
  357. free_logger();
  358. }
  359. LOG("Hook installed!\n");
  360. LOG("Attempting to install GetMessageA and GetMessageW hooks\n");
  361. if (!iat_hook(targetModule, "user32.dll", &GetMessageA, &hookGetMessageA)) {
  362. LOG("Could not hook GetMessageA! (not an error)\n");
  363. }
  364. if (!iat_hook(targetModule, "user32.dll", &GetMessageW, &hookGetMessageW)) {
  365. LOG("Could not hook GetMessageW! (not an error)\n");
  366. }
  367. LOG("Attempting to install PeekMessageA and PeekMessageW hooks\n");
  368. if (!iat_hook(targetModule, "user32.dll", &PeekMessageA, &hookPeekMessageA)) {
  369. LOG("Could not hook PeekMessageA! (not an error)\n");
  370. }
  371. if (!iat_hook(targetModule, "user32.dll", &PeekMessageW, &hookPeekMessageW)) {
  372. LOG("Could not hook PeekMessageW! (not an error)\n");
  373. }
  374. }
  375. else
  376. {
  377. LOG("Doorstop disabled! memfreeing resources\n");
  378. free_logger();
  379. }
  380. memfree(dll_name);
  381. memfree(dll_path);
  382. return TRUE;
  383. }