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.

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