fork/m-overlay

git clone https://git.julia.blue/fork/m-overlay

BkacjiosMerge pull request #185 from MORImementos/mainlined568a79

v2.1.5
9.6 KiB378 linesraw
1local ffi = require("ffi")
2local log = require("log")
3
4local format = string.format
5local tohex = string.tohex
6
7local cast = ffi.cast
8local cdef = ffi.cdef
9local load = ffi.load
10local metatype = ffi.metatype
11local new = ffi.new
12local typeof = ffi.typeof
13local sizeof = ffi.sizeof
14local string = ffi.string
15
16local lshift = bit.lshift
17local rshift = bit.rshift
18local bswap = bit.bswap
19local band = bit.band
20local bor = bit.bor
21
22local kernel = load("Kernel32.dll")
23local psapi = load("Psapi.dll")
24
25local libc = ffi.C
26
27cdef [[
28// Stupid Windows typenames..
29
30//#define MAX_PATH 260
31
32typedef int BOOL;
33typedef unsigned long DWORD;
34typedef long LONG;
35
36typedef void *PVOID;
37typedef PVOID HANDLE;
38
39typedef void *LPVOID;
40typedef const void *LPCVOID;
41
42typedef DWORD *LPDWORD;
43
44typedef char CHAR;
45
46typedef unsigned __int64 ULONG_PTR; // 64-bit
47// typedef unsigned long ULONG_PTR; // 32-bit
48
49typedef ULONG_PTR SIZE_T;
50
51typedef struct {
52	HANDLE process_handle;
53	ULONG_PTR dolphin_base_addr;
54	ULONG_PTR dolphin_addr_size;
55} MEMORY_STRUCT;
56
57typedef struct tagPROCESSENTRY32 {
58	DWORD dwSize;
59	DWORD cntUsage;
60	DWORD th32ProcessID;
61	ULONG_PTR th32DefaultHeapID; // DWORD on 32-bit
62	DWORD th32ModuleID;
63	DWORD cntThreads;
64	DWORD th32ParentProcessID;
65	LONG pcPriClassBase;
66	DWORD dwFlags;
67	CHAR  szExeFile[260];
68} PROCESSENTRY32,*PPROCESSENTRY32,*LPPROCESSENTRY32;
69
70HANDLE CreateToolhelp32Snapshot(
71	DWORD dwFlags,
72	DWORD th32ProcessID
73);
74
75BOOL Process32First(
76	HANDLE           hSnapshot,
77	LPPROCESSENTRY32 lppe
78);
79
80BOOL Process32Next(
81	HANDLE           hSnapshot,
82	LPPROCESSENTRY32 lppe
83);
84
85HANDLE OpenProcess(
86	DWORD dwDesiredAccess,
87	BOOL  bInheritHandle,
88	DWORD dwProcessId
89);
90
91BOOL ReadProcessMemory(
92	HANDLE  hProcess,
93	LPCVOID lpBaseAddress,
94	LPVOID  lpBuffer,
95	SIZE_T  nSize,
96	SIZE_T  *lpNumberOfBytesRead
97);
98
99BOOL WriteProcessMemory(
100	HANDLE  hProcess,
101	LPVOID  lpBaseAddress,
102	LPCVOID lpBuffer,
103	SIZE_T  nSize,
104	SIZE_T  *lpNumberOfBytesWritten
105);
106
107BOOL CloseHandle(
108	HANDLE hObject
109);
110
111typedef struct _MEMORY_BASIC_INFORMATION {
112	PVOID  BaseAddress;
113	PVOID  AllocationBase;
114	DWORD  AllocationProtect;
115	SIZE_T RegionSize;
116	DWORD  State;
117	DWORD  Protect;
118	DWORD  Type;
119} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;
120
121typedef union _PSAPI_WORKING_SET_EX_BLOCK {
122	ULONG_PTR Flags;
123	/*union {
124		struct {
125			ULONG_PTR Valid : 1;
126			ULONG_PTR ShareCount : 3;
127			ULONG_PTR Win32Protection : 11;
128			ULONG_PTR Shared : 1;
129			ULONG_PTR Node : 6;
130			ULONG_PTR Locked : 1;
131			ULONG_PTR LargePage : 1;
132			ULONG_PTR Reserved : 7;
133			ULONG_PTR Bad : 1;
134			ULONG_PTR ReservedUlong : 32;
135		};
136		struct {
137			ULONG_PTR Valid : 1;
138			ULONG_PTR Reserved0 : 14;
139			ULONG_PTR Shared : 1;
140			ULONG_PTR Reserved1 : 15;
141			ULONG_PTR Bad : 1;
142			ULONG_PTR ReservedUlong : 32;
143		} Invalid;
144	};*/
145} PSAPI_WORKING_SET_EX_BLOCK, *PPSAPI_WORKING_SET_EX_BLOCK;
146
147typedef struct _PSAPI_WORKING_SET_EX_INFORMATION {
148	PVOID                      VirtualAddress;
149	PSAPI_WORKING_SET_EX_BLOCK VirtualAttributes;
150} PSAPI_WORKING_SET_EX_INFORMATION, *PPSAPI_WORKING_SET_EX_INFORMATION;
151
152SIZE_T VirtualQueryEx(
153	HANDLE                    hProcess,
154	LPCVOID                   lpAddress,
155	PMEMORY_BASIC_INFORMATION lpBuffer,
156	SIZE_T                    dwLength
157);
158
159BOOL QueryWorkingSetEx(
160	HANDLE hProcess,
161	PVOID  pv,
162	DWORD  cb
163);
164
165BOOL GetExitCodeProcess(
166	HANDLE  hProcess,
167	LPDWORD lpExitCode
168);
169
170DWORD WaitForSingleObject(
171	HANDLE hHandle,
172	DWORD  dwMilliseconds
173);
174
175DWORD GetLastError();
176]]
177
178local MEMORY = {}
179MEMORY.__index = MEMORY
180MEMORY.init = metatype("MEMORY_STRUCT", MEMORY)
181
182local TH32CS_SNAPPROCESS = 0x02
183
184local PROCESS_QUERY_INFORMATION = 0x0400
185local PROCESS_VM_OPERATION = 0x0008
186local PROCESS_VM_READ = 0x0010
187local PROCESS_VM_WRITE = 0x0020
188
189local MEM_MAPPED = 0x40000
190
191local STILL_ACTIVE = 259
192
193local function NOTWITHINMEMRANGE(addr)
194	return addr < 0x80000000 or addr > 0x81800000
195end
196
197local PROCESSENTRY32_PTR = typeof("PROCESSENTRY32[1]")
198local MEMORY_BASIC_INFORMATION_PTR = typeof("MEMORY_BASIC_INFORMATION[1]")
199local PSAPI_WORKING_SET_EX_INFORMATION_PTR = typeof("PSAPI_WORKING_SET_EX_INFORMATION[1]")
200
201function MEMORY:hasPermissions()
202	-- Windows doesn't need any special permissions to read memory from another process
203	return true
204end
205
206local valid_process_names = {
207	["Dolphin.exe"] = true,
208	["Slippi Dolphin.exe"] = true,
209	["Slippi_Dolphin.exe"] = true,
210	["Citrus Dolphin.exe"] = true,
211	["DolphinWx.exe"] = true,
212	["DolphinQt2.exe"] = true,
213	["Project Rio.exe"] = true,
214}
215
216do
217	local status = new("DWORD[1]")
218
219	function MEMORY:findprocess()
220		if self:hasProcess() then return false end
221
222		local handle
223		local snapshot = kernel.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) -- Create the snapshot
224
225		local pe32 = PROCESSENTRY32_PTR()[0] -- Will store the info about the process
226		pe32.dwSize = sizeof(pe32)
227
228		repeat
229			local name = string(pe32.szExeFile)
230			if valid_process_names[name] then
231				local handle = kernel.OpenProcess(PROCESS_VM_OPERATION + PROCESS_VM_READ + PROCESS_QUERY_INFORMATION, false, pe32.th32ProcessID)
232
233				-- Check if the process is active, we don't want to rehook the closing application
234				if handle ~= nil and kernel.GetExitCodeProcess(handle, status) and status[0] == STILL_ACTIVE then
235					-- We have an active process that matches, let's use it
236					self.process_handle = handle
237					break
238				elseif handle then
239					-- Dolphin is closing.. ignore and close the handle..
240					kernel.CloseHandle(handle)
241				end
242			end
243		until kernel.Process32Next(snapshot, pe32) == 0
244		
245		kernel.CloseHandle(snapshot)
246
247		return self:hasProcess()
248	end
249end
250
251do
252	local status = new("DWORD[1]")
253	
254	function MEMORY:isProcessActive()
255		return self.process_handle ~= nil and kernel.GetExitCodeProcess(self.process_handle, status) and status[0] == STILL_ACTIVE
256	end
257end
258
259function MEMORY:hasProcess()
260	return self.process_handle ~= nil
261end
262
263function MEMORY:clearGamecubeRAMOffset()
264	self.dolphin_base_addr = nil
265end
266
267function MEMORY:hasGamecubeRAMOffset()
268	return self.dolphin_base_addr ~= nil
269end
270
271function MEMORY:getGamecubeRAMOffset()
272	return tonumber(self.dolphin_base_addr)
273end
274
275function MEMORY:getGamecubeRAMSize()
276	return tonumber(self.dolphin_addr_size)
277end
278
279function MEMORY:close()
280	if self:hasProcess() then
281		kernel.CloseHandle(self.process_handle)
282		self.process_handle = nil
283		self.dolphin_base_addr = nil
284	end
285end
286
287function MEMORY:__gc()
288	self:close()
289end
290
291local regionptr = new("ULONG_PTR*[1]")
292
293local NULL = cast("ULONG_PTR", 0x00000000)
294local GC_RAM_SIZE = cast("ULONG_PTR", 0x2000000)
295
296function MEMORY:findGamecubeRAMOffset()
297	local info = MEMORY_BASIC_INFORMATION_PTR()[0]
298
299	local address = regionptr[0]
300
301	-- Scan all virtual address spaces the process is using.
302	while kernel.VirtualQueryEx(self.process_handle, address, info, sizeof(info)) == sizeof(info) do
303		address = address + info.RegionSize / sizeof(info.RegionSize)
304
305		-- Dolphin stores the GameCube RAM address space in 32MB chunks.
306		-- Extended memory override can allow up to 64MB.
307		if (info.RegionSize >= GC_RAM_SIZE and info.RegionSize % GC_RAM_SIZE == 0 and info.Type == MEM_MAPPED) then
308			local wsinfo = PSAPI_WORKING_SET_EX_INFORMATION_PTR()[0]
309			wsinfo.VirtualAddress = info.BaseAddress
310
311			-- Retrieve extended information about the virtual address space
312			if psapi.QueryWorkingSetEx(self.process_handle, wsinfo, sizeof(wsinfo)) == 1 then
313				local flags = tonumber(wsinfo.VirtualAttributes.Flags)
314
315				local base = cast("ULONG_PTR", info.BaseAddress)
316				local region = cast("ULONG_PTR", info.RegionSize)
317
318				-- Check that the VirtualAttributes flags contains VALID and the base address is not null
319				if band(flags, lshift(1, 0)) == 1 and cast("ULONG_PTR", info.BaseAddress) ~= NULL then
320					--log.debug("%08X %x", tonumber(base), tonumber(region))
321					self.dolphin_base_addr = base
322					self.dolphin_addr_size = region
323					return true
324				end
325			end
326		end
327	end
328
329	return false
330end
331
332local GC_RAM_START = cast("uint32_t", 0x80000000)
333local GC_RAM_END = cast("uint32_t", 0x81800000)
334local WII_RAM_START = cast("uint32_t", 0x90000000)
335local WII_RAM_END = cast("uint32_t", 0x94000000)
336
337local WII_RAM_LOCAL_START = cast("uint32_t", 0x02000000)
338
339local CAST_ADDR = ffi.new("uint32_t", 0x00000000)
340local memread = ffi.new("SIZE_T[1]") -- How many bytes are read from memory
341
342function MEMORY:read(addr, output, size)
343	if not self:hasProcess() or not self:hasGamecubeRAMOffset() then return false end
344
345	CAST_ADDR = cast("uint32_t", addr)
346
347	if CAST_ADDR >= WII_RAM_START and CAST_ADDR <= WII_RAM_END then
348		CAST_ADDR = cast("uint32_t", WII_RAM_LOCAL_START + (CAST_ADDR % WII_RAM_START))
349	elseif CAST_ADDR >= GC_RAM_START and CAST_ADDR <= GC_RAM_END then
350		CAST_ADDR = cast("uint32_t", CAST_ADDR % GC_RAM_START)
351	else
352		log.warn("[MEMORY] Attempt to read from invalid address %08X", tonumber(CAST_ADDR))
353		return false
354	end
355
356	local raddr = cast("LPCVOID", self.dolphin_base_addr + CAST_ADDR)
357	local success = kernel.ReadProcessMemory(self.process_handle, raddr, output, size, memread)
358	if not success then
359		log.debug("[MEMORY] Failed reading from address [%08X] ERROR #%d", CAST_ADDR, tonumber(kernel.GetLastError()))
360	else
361	 	log.trace("[MEMORY] Read 0x%X size 0x%X bytes from 0x%08X = %q", tonumber(memread[0]), size, tonumber(CAST_ADDR), string(output, memread[0]))
362	end
363	return success and memread[0] == size
364end
365
366local memwritten = ffi.new("SIZE_T[1]")
367
368function MEMORY:write(addr, input, size)
369	if not self:hasProcess() or not self:hasGamecubeRAMOffset() then return false end
370	local waddr = cast("LPVOID", self.dolphin_base_addr + (addr % GC_RAM_START))
371	local success = kernel.WriteProcessMemory(self.process_handle, waddr, input, size, memwritten)
372	if not success then
373		log.debug("[MEMORY] Failed writing to address [%08X = %08X] ERROR #%d", addr, tonumber(input), tonumber(kernel.GetLastError()))
374	end
375	return success and memwritten[0] == size
376end
377
378return MEMORY