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.

486 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. size_t multibyte_path_len = WideCharToMultiByte(CP_UTF8, 0, dll_path_w, dll_path_len, NULL, 0, NULL, NULL);
  158. char* self_dll_path = memalloc(multibyte_path_len + 1);
  159. WideCharToMultiByte(CP_UTF8, 0, dll_path_w, dll_path_len, self_dll_path, multibyte_path_len + 1, NULL, NULL);
  160. self_dll_path[multibyte_path_len] = 0;
  161. mono_dllmap_insert(NULL, "i:bsipa-doorstop", NULL, self_dll_path, NULL); // remap `bsipa-doorstop` to this assembly
  162. memfree(self_dll_path);
  163. memfree(dll_path_w);
  164. unhandledMutex = CreateMutexW(NULL, FALSE, NULL);
  165. LOG("Invoking method!\n");
  166. void* exception = NULL;
  167. mono_runtime_invoke(method, NULL, args, &exception);
  168. WaitForSingleObject(unhandledMutex, INFINITE); // if the EH is triggered, wait for it
  169. if (args != NULL)
  170. {
  171. memfree(app_path);
  172. memfree(args);
  173. NULL;
  174. }
  175. #ifdef _VERBOSE
  176. if (exception != NULL)
  177. {
  178. void* monostr = mono_object_to_string(exception, &exception);
  179. if (exception != NULL)
  180. LOG("An error occurred while invoking the injector, but the error could not be stringified.\n")
  181. else
  182. {
  183. char* str = mono_string_to_utf8(monostr);
  184. LOG("An error occurred invoking the injector: %s\n", str);
  185. mono_free(str);
  186. }
  187. }
  188. #endif
  189. cleanupConfig();
  190. free_logger();
  191. ReleaseMutex(unhandledMutex);
  192. return domain;
  193. }
  194. void ownMonoJitParseOptions(int argc, char * argv[])
  195. {
  196. setOptions = TRUE;
  197. int size = argc;
  198. #ifdef WIN64
  199. if (debug) size += 2;
  200. #elif defined(WIN32)
  201. if (debug) size += 1;
  202. #endif
  203. char** arguments = memalloc(sizeof(char*) * size);
  204. _ASSERTE(arguments != nullptr);
  205. memcpy(arguments, argv, sizeof(char*) * argc);
  206. if (debug) {
  207. //arguments[argc++] = "--debug";
  208. #ifdef WIN64
  209. arguments[argc++] = "--soft-breakpoints";
  210. #endif
  211. if (debug_server)
  212. arguments[argc] = "--debugger-agent=transport=dt_socket,address=0.0.0.0:10000,server=y";
  213. else
  214. arguments[argc] = "--debugger-agent=transport=dt_socket,address=127.0.0.1:10000,server=n";
  215. }
  216. mono_jit_parse_options(size, arguments);
  217. memfree(arguments);
  218. }
  219. BOOL initialized = FALSE;
  220. void init(HMODULE module)
  221. {
  222. if (!initialized)
  223. {
  224. initialized = TRUE;
  225. LOG("Got mono.dll at %p\n", module);
  226. loadMonoFunctions(module);
  227. }
  228. }
  229. void * WINAPI hookGetProcAddress(HMODULE module, char const *name)
  230. {
  231. if (lstrcmpA(name, "mono_jit_init_version") == 0)
  232. {
  233. init(module);
  234. return (void*)&ownMonoJitInitVersion;
  235. }
  236. if (lstrcmpA(name, "mono_jit_parse_options") == 0 && debug)
  237. {
  238. init(module);
  239. return (void*)&ownMonoJitParseOptions;
  240. }
  241. return (void*)GetProcAddress(module, name);
  242. }
  243. BOOL hookGetMessage(
  244. BOOL isW,
  245. LPMSG msg,
  246. HWND hwnd,
  247. UINT wMsgFilterMin,
  248. UINT wMsgFilterMax
  249. );
  250. BOOL WINAPI hookGetMessageA(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax)
  251. {
  252. return hookGetMessage(FALSE, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  253. }
  254. BOOL WINAPI hookGetMessageW(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax)
  255. {
  256. return hookGetMessage(TRUE, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  257. }
  258. typedef BOOL(*GetMessageHook)(BOOL isW, BOOL result, LPMSG msg, HWND hwnd, UINT filterMin, UINT filterMax);
  259. GetMessageHook getMessageHook = NULL;
  260. __declspec(dllexport) void __stdcall SetGetMessageHook(GetMessageHook hook) {
  261. getMessageHook = hook;
  262. }
  263. BOOL hookGetMessage(
  264. BOOL isW,
  265. LPMSG msg,
  266. HWND hwnd,
  267. UINT wMsgFilterMin,
  268. UINT wMsgFilterMax
  269. )
  270. {
  271. BOOL loop = FALSE;
  272. BOOL result;
  273. do {
  274. if (isW) {
  275. result = GetMessageW(msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  276. } else {
  277. result = GetMessageA(msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  278. }
  279. if (getMessageHook) {
  280. loop = getMessageHook(isW, result, msg, hwnd, wMsgFilterMin, wMsgFilterMax);
  281. }
  282. } while (loop);
  283. return result;
  284. }
  285. BOOL hookPeekMessage(
  286. BOOL isW,
  287. LPMSG msg,
  288. HWND hwnd,
  289. UINT wMsgFilterMin,
  290. UINT wMsgFilterMax,
  291. UINT wRemoveMsg
  292. );
  293. BOOL WINAPI hookPeekMessageA(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg)
  294. {
  295. return hookPeekMessage(FALSE, msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  296. }
  297. BOOL WINAPI hookPeekMessageW(LPMSG msg, HWND hwnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg)
  298. {
  299. return hookPeekMessage(TRUE, msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  300. }
  301. typedef BOOL(*PeekMessageHook)(BOOL isW, BOOL result, LPMSG msg, HWND hwnd, UINT filterMin, UINT filterMax, UINT* wRemoveMsg);
  302. PeekMessageHook peekMessageHook = NULL;
  303. __declspec(dllexport) void __stdcall SetPeekMessageHook(PeekMessageHook hook) {
  304. peekMessageHook = hook;
  305. }
  306. BOOL hookPeekMessage(
  307. BOOL isW,
  308. LPMSG msg,
  309. HWND hwnd,
  310. UINT wMsgFilterMin,
  311. UINT wMsgFilterMax,
  312. UINT wRemoveMsg
  313. )
  314. {
  315. BOOL loop = FALSE;
  316. BOOL result;
  317. do {
  318. if (isW) {
  319. result = PeekMessageW(msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  320. }
  321. else {
  322. result = PeekMessageA(msg, hwnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
  323. }
  324. if (peekMessageHook) {
  325. loop = peekMessageHook(isW, result, msg, hwnd, wMsgFilterMin, wMsgFilterMax, &wRemoveMsg);
  326. }
  327. } while (loop);
  328. return result;
  329. }
  330. BOOL WINAPI DllMain(HINSTANCE hInstDll, DWORD reasonForDllLoad, LPVOID reserved)
  331. {
  332. if (reasonForDllLoad != DLL_PROCESS_ATTACH)
  333. return TRUE;
  334. hHeap = GetProcessHeap();
  335. init_logger();
  336. LOG("Doorstop started!\n");
  337. wchar_t *dll_path = NULL;
  338. size_t dll_path_len = get_module_path((HINSTANCE)&__ImageBase, &dll_path, NULL, 0);
  339. LOG("DLL Path: %S\n", dll_path);
  340. wchar_t *dll_name = get_file_name_no_ext(dll_path, dll_path_len);
  341. LOG("Doorstop DLL Name: %S\n", dll_name);
  342. loadProxy(dll_name);
  343. loadConfig();
  344. // If the loader is disabled, don't inject anything.
  345. if (enabled)
  346. {
  347. LOG("Doorstop enabled!\n");
  348. ASSERT_SOFT(GetFileAttributesW(targetAssembly) != INVALID_FILE_ATTRIBUTES, TRUE);
  349. HMODULE targetModule = GetModuleHandleA("UnityPlayer");
  350. if(targetModule == NULL)
  351. {
  352. LOG("No UnityPlayer.dll; using EXE as the hook target.");
  353. targetModule = GetModuleHandleA(NULL);
  354. }
  355. LOG("Installing IAT hook\n");
  356. if (!iat_hook(targetModule, "kernel32.dll", &GetProcAddress, &hookGetProcAddress))
  357. {
  358. LOG("Failed to install IAT hook!\n");
  359. free_logger();
  360. }
  361. LOG("Hook installed!\n");
  362. LOG("Attempting to install GetMessageA and GetMessageW hooks\n");
  363. if (!iat_hook(targetModule, "user32.dll", &GetMessageA, &hookGetMessageA)) {
  364. LOG("Could not hook GetMessageA! (not an error)\n");
  365. }
  366. if (!iat_hook(targetModule, "user32.dll", &GetMessageW, &hookGetMessageW)) {
  367. LOG("Could not hook GetMessageW! (not an error)\n");
  368. }
  369. LOG("Attempting to install PeekMessageA and PeekMessageW hooks\n");
  370. if (!iat_hook(targetModule, "user32.dll", &PeekMessageA, &hookPeekMessageA)) {
  371. LOG("Could not hook PeekMessageA! (not an error)\n");
  372. }
  373. if (!iat_hook(targetModule, "user32.dll", &PeekMessageW, &hookPeekMessageW)) {
  374. LOG("Could not hook PeekMessageW! (not an error)\n");
  375. }
  376. }
  377. else
  378. {
  379. LOG("Doorstop disabled! memfreeing resources\n");
  380. free_logger();
  381. }
  382. memfree(dll_name);
  383. memfree(dll_path);
  384. return TRUE;
  385. }