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.

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