| 1 | // Copyright 2008 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include <Windows.h> |
| 5 | #include <functional> |
| 6 | #include <optional> |
| 7 | #include <string> |
| 8 | #include <vector> |
| 9 | #include <winternl.h> |
| 10 | |
| 11 | #include <fmt/format.h> |
| 12 | #include <fmt/xchar.h> |
| 13 | |
| 14 | #include "Common/CommonFuncs.h" |
| 15 | #include "Common/CommonTypes.h" |
| 16 | #include "Common/LdrWatcher.h" |
| 17 | #include "Common/StringUtil.h" |
| 18 | |
| 19 | typedef NTSTATUS(NTAPI* PRTL_HEAP_COMMIT_ROUTINE)(IN PVOID Base, IN OUT PVOID* CommitAddress, |
| 20 | IN OUT PSIZE_T CommitSize); |
| 21 | |
| 22 | typedef struct _RTL_HEAP_PARAMETERS |
| 23 | { |
| 24 | ULONG Length; |
| 25 | SIZE_T SegmentReserve; |
| 26 | SIZE_T SegmentCommit; |
| 27 | SIZE_T DeCommitFreeBlockThreshold; |
| 28 | SIZE_T DeCommitTotalFreeThreshold; |
| 29 | SIZE_T MaximumAllocationSize; |
| 30 | SIZE_T VirtualMemoryThreshold; |
| 31 | SIZE_T InitialCommit; |
| 32 | SIZE_T InitialReserve; |
| 33 | PRTL_HEAP_COMMIT_ROUTINE CommitRoutine; |
| 34 | SIZE_T Reserved[2]; |
| 35 | } RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS; |
| 36 | |
| 37 | typedef PVOID (*RtlCreateHeap_t)(_In_ ULONG Flags, _In_opt_ PVOID HeapBase, |
| 38 | _In_opt_ SIZE_T ReserveSize, _In_opt_ SIZE_T CommitSize, |
| 39 | _In_opt_ PVOID Lock, _In_opt_ PRTL_HEAP_PARAMETERS Parameters); |
| 40 | |
| 41 | static HANDLE WINAPI HeapCreateLow4GB(_In_ DWORD flOptions, _In_ SIZE_T dwInitialSize, |
| 42 | _In_ SIZE_T dwMaximumSize) |
| 43 | { |
| 44 | auto ntdll = GetModuleHandleW(L"ntdll"); |
| 45 | if (!ntdll) |
| 46 | return nullptr; |
| 47 | auto RtlCreateHeap = reinterpret_cast<RtlCreateHeap_t>(GetProcAddress(ntdll, "RtlCreateHeap")); |
| 48 | if (!RtlCreateHeap) |
| 49 | return nullptr; |
| 50 | // These values are arbitrary; just change them if problems are encountered later. |
| 51 | uintptr_t target_addr = 0x00200000; |
| 52 | size_t max_heap_size = 0x01000000; |
| 53 | uintptr_t highest_addr = (1ull << 32) - max_heap_size; |
| 54 | void* low_heap = nullptr; |
| 55 | for (; !low_heap && target_addr <= highest_addr; target_addr += 0x1000) |
| 56 | low_heap = VirtualAlloc((void*)target_addr, max_heap_size, MEM_RESERVE, PAGE_READWRITE); |
| 57 | if (!low_heap) |
| 58 | return nullptr; |
| 59 | return RtlCreateHeap(0, low_heap, 0, 0, nullptr, nullptr); |
| 60 | } |
| 61 | |
| 62 | static bool ModifyProtectedRegion(void* address, size_t size, std::function<void()> func) |
| 63 | { |
| 64 | DWORD old_protect; |
| 65 | if (!VirtualProtect(address, size, PAGE_READWRITE, &old_protect)) |
| 66 | return false; |
| 67 | func(); |
| 68 | if (!VirtualProtect(address, size, old_protect, &old_protect)) |
| 69 | return false; |
| 70 | return true; |
| 71 | } |
| 72 | |
| 73 | // Does not do input sanitization - assumes well-behaved input since Ldr has already parsed it. |
| 74 | class ImportPatcher |
| 75 | { |
| 76 | public: |
| 77 | ImportPatcher(uintptr_t module_base) : base(module_base) |
| 78 | { |
| 79 | auto mz = reinterpret_cast<PIMAGE_DOS_HEADER>(base); |
| 80 | auto pe = reinterpret_cast<PIMAGE_NT_HEADERS>(base + mz->e_lfanew); |
| 81 | directories = pe->OptionalHeader.DataDirectory; |
| 82 | } |
| 83 | template <typename T> |
| 84 | T GetRva(uint32_t rva) |
| 85 | { |
| 86 | return reinterpret_cast<T>(base + rva); |
| 87 | } |
| 88 | bool PatchIAT(const char* module_name, const char* function_name, void* value) |
| 89 | { |
| 90 | auto import_dir = &directories[IMAGE_DIRECTORY_ENTRY_IMPORT]; |
| 91 | for (auto import_desc = GetRva<PIMAGE_IMPORT_DESCRIPTOR>(import_dir->VirtualAddress); |
| 92 | import_desc->OriginalFirstThunk; import_desc++) |
| 93 | { |
| 94 | auto module = GetRva<const char*>(import_desc->Name); |
| 95 | auto names = GetRva<PIMAGE_THUNK_DATA>(import_desc->OriginalFirstThunk); |
| 96 | auto thunks = GetRva<PIMAGE_THUNK_DATA>(import_desc->FirstThunk); |
| 97 | if (!stricmp(module, module_name)) |
| 98 | { |
| 99 | for (auto name = names; name->u1.Function; name++) |
| 100 | { |
| 101 | if (!IMAGE_SNAP_BY_ORDINAL(name->u1.Ordinal)) |
| 102 | { |
| 103 | auto import = GetRva<PIMAGE_IMPORT_BY_NAME>(name->u1.AddressOfData); |
| 104 | if (!strcmp(import->Name, function_name)) |
| 105 | { |
| 106 | auto index = name - names; |
| 107 | return ModifyProtectedRegion(&thunks[index], sizeof(thunks[index]), [=] { |
| 108 | thunks[index].u1.Function = |
| 109 | reinterpret_cast<decltype(thunks[index].u1.Function)>(value); |
| 110 | }); |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | // Function not found |
| 115 | return false; |
| 116 | } |
| 117 | } |
| 118 | // Module not found |
| 119 | return false; |
| 120 | } |
| 121 | |
| 122 | private: |
| 123 | uintptr_t base; |
| 124 | PIMAGE_DATA_DIRECTORY directories; |
| 125 | }; |
| 126 | |
| 127 | static void CompatPatchesInstall(LdrWatcher* watcher) |
| 128 | { |
| 129 | watcher->Install({{L"EZFRD64.dll", L"811EZFRD64.DLL"}, [](const LdrDllLoadEvent& event) { |
| 130 | // *EZFRD64 is included in software packages for cheapo third-party gamepads |
| 131 | // (and gamepad adapters). The module cannot handle its heap being above 4GB, |
| 132 | // which tends to happen very often on modern Windows. |
| 133 | // NOTE: The patch will always be applied, but it will only actually avoid the |
| 134 | // crash if applied before module initialization (i.e. called on the Ldr |
| 135 | // callout path). |
| 136 | auto patcher = ImportPatcher(event.base_address); |
| 137 | patcher.PatchIAT("kernel32.dll", "HeapCreate", HeapCreateLow4GB); |
| 138 | }}); |
| 139 | } |
| 140 | |
| 141 | int __cdecl EnableCompatPatches() |
| 142 | { |
| 143 | static LdrWatcher watcher; |
| 144 | CompatPatchesInstall(&watcher); |
| 145 | return 0; |
| 146 | } |
| 147 | |
| 148 | // Create a segment which is recognized by the linker to be part of the CRT |
| 149 | // initialization. XI* = C startup, XC* = C++ startup. "A" placement is reserved |
| 150 | // for system use. C startup is before C++. |
| 151 | // Use last C++ slot in hopes that makes using C++ from this code safe. |
| 152 | #pragma section(".CRT$XCZ", read) |
| 153 | |
| 154 | // Place a symbol in the special segment, make it have C linkage so that |
| 155 | // referencing it doesn't require ugly decorated names. |
| 156 | // Use /include:enableCompatPatches linker flag to enable this. |
| 157 | extern "C" { |
| 158 | __declspec(allocate(".CRT$XCZ")) decltype(&EnableCompatPatches) enableCompatPatches = |
| 159 | EnableCompatPatches; |
| 160 | } |