fork/m-overlay

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

BkacjiosDisable reading JIS strings since they cause errors60fa5b3

master
19.0 KiB725 linesraw
1local bit = require("bit")
2local ffi = require("ffi")
3local log = require("log")
4local cloneloader = require("memory.cloneloader")
5local process = require("memory." .. jit.os:lower())
6local notification = require("notification")
7
8require("extensions.string")
9require("extensions.table")
10
11local NULL = 0x00000000
12
13local GAME_ID_ADDR  = 0x80000000
14local GAME_VER_ADDR = 0x80000007
15local GAME_ID_LEN   = 0x06
16local GAME_NONE     = "\0\0\0\0\0\0"
17
18local VC_ID_ADDR    = 0x80003180
19local VC_ID_LEN     = 0x04
20local VC_NONE       = "\0\0\0\0"
21
22local memory = {
23	clones = require("games.clones"),
24	vcclones = require("games.vcclones"),
25
26	gameid = GAME_NONE,
27	vcid = VC_NONE,
28	process = process,
29	permissions = process:hasPermissions(),
30
31	hooked = false,
32	initialized = false,
33	ingame = false,
34
35	map = {},
36	values = {},
37
38	hooks = {},
39	wildcard_hooks = {},
40
41	hook_queue = {},
42}
43
44cloneloader.loadFile("clones.lua", memory.clones)
45
46setmetatable(memory, {__index = memory.values})
47
48local bswap = bit.bswap
49local function bswap16(n)
50	return bit.bor(bit.rshift(n, 8), bit.lshift(bit.band(n, 0xFF), 8))
51end
52
53function memory.readGameID()
54	return memory.read(GAME_ID_ADDR, GAME_ID_LEN)
55end
56
57function memory.readVirtualConsoleID()
58	return memory.read(VC_ID_ADDR, VC_ID_LEN)
59end
60
61function memory.readGameVersion()
62	return memory.readUByte(GAME_VER_ADDR)
63end
64
65local typecache = {}
66
67local function cache(typ, len)
68	-- This stops us from constantly calling ffi.new by recycling old variables
69	len = len or 1
70	if not typecache[typ] then
71		-- Create new cache for this type
72		typecache[typ] = {}
73	elseif typecache[typ][len] then
74		-- Set the cached value to all 0's so it can be reused safely
75		ffi.fill(typecache[typ][len], len)
76		-- Return the cached value
77		return typecache[typ][len]
78	end
79	-- Create a new variable
80	local cached = ffi.new(string.format("%s[?]", typ), len)
81	-- Store it in the cache
82	typecache[typ][len] = cached
83	return cached
84end
85
86function memory.read(addr, len)
87	local output = cache("uint8_t", len)
88	local size = ffi.sizeof(output)
89	process:read(addr, output, size)
90	return ffi.string(output, size)
91end
92
93function memory.readByte(addr)
94	if not process:hasProcess() then return 0 end
95	local output = cache("int8_t")
96	process:read(addr, output, ffi.sizeof(output))
97	return output[0]
98end
99
100function memory.writeByte(addr, value)
101	if not process:hasProcess() then return end
102	local input = cache("int8_t")
103	return process:write(addr, input, ffi.sizeof(input))
104end
105
106function memory.readBool(addr)
107	if not process:hasProcess() then return false end
108	return memory.readByte(addr) == 1
109end
110
111function memory.writeBool(addr, value)
112	if not self:hasProcess() then return end
113	self:writeByte(addr, value == true and 1 or 0)
114end
115
116function memory.readUByte(addr)
117	if not process:hasProcess() then return 0 end
118	local output = cache("uint8_t")
119	process:read(addr, output, ffi.sizeof(output))
120	return output[0]
121end
122
123function memory.writeUByte(addr, value)
124	if not process:hasProcess() then return end
125	local input = cache("uint8_t")
126	return process:write(addr, input, ffi.sizeof(input))
127end
128
129function memory.readShort(addr)
130	if not process:hasProcess() then return 0 end
131	local output = cache("int16_t")
132	process:read(addr, output, ffi.sizeof(output))
133	return bswap16(output[0])
134end
135
136function memory.writeShort(addr, value)
137	if not process:hasProcess() then return end
138	local input = cache("int16_t")
139	return process:write(addr, input, ffi.sizeof(input))
140end
141
142function memory.readUShort(addr)
143	if not process:hasProcess() then return 0 end
144	local output = cache("uint16_t")
145	process:read(addr, output, ffi.sizeof(output))
146	return bswap16(output[0])
147end
148
149function memory.writeUShort(addr, value)
150	if not process:hasProcess() then return end
151	local input = cache("uint16_t")
152	return process:write(addr, input, ffi.sizeof(input))
153end
154
155do
156	local floatconversion = ffi.new("union { uint32_t i; float f; }")
157
158	function memory.readFloat(addr)
159		if not process:hasProcess() then return 0 end
160		local output = cache("uint32_t")
161		process:read(addr, output, ffi.sizeof(output))
162		floatconversion.i = bswap(output[0])
163		return floatconversion.f, floatconversion.i
164	end
165end
166
167function memory.writeFloat(addr, value)
168	if not process:hasProcess() then return end
169	local input = cache("float")
170	return process:write(addr, input, ffi.sizeof(input))
171end
172
173function memory.readInt(addr)
174	if not process:hasProcess() then return 0 end
175	local output = cache("int32_t")
176	process:read(addr, output, ffi.sizeof(output))
177	return bswap(output[0])
178end
179
180function memory.writeInt(addr, value)
181	if not process:hasProcess() then return end
182	local input = cache("int32_t")
183	return process:write(addr, input, ffi.sizeof(input))
184end
185
186function memory.readUInt(addr)
187	if not process:hasProcess() then return 0 end
188	local output = cache("uint32_t")
189	process:read(addr, output, ffi.sizeof(output))
190	return bswap(output[0])
191end
192
193function memory.writeUInt(addr, value)
194	if not process:hasProcess() then return end
195	local input = cache("uint32_t")
196	return process:write(addr, input, ffi.sizeof(input))
197end
198
199local char_replacement_map = {
200	[0x8149] = "!", [0x8168] = "\"", [0x8194] = "#", [0x8190] = "$",
201	[0x8193] = "%", [0x8195] = "&", [0x8166] = "'", [0x8169] = "(",
202	[0x816A] = ")", [0x8196] = "*", [0x817B] = "+", [0x8143] = ",",
203	[0x817C] = "-", [0x8144] = ".", [0x815E] = "/", [0x8146] = ":",
204	[0x8147] = ";", [0x8183] = "<", [0x8181] = "=", [0x8184] = ">",
205	[0x8148] = "?", [0x8197] = "@", [0x816D] = "[", [0x815F] = "\\",
206	[0x816E] = "]", [0x814F] = "^", [0x8151] = "_", [0x814D] = "`",
207	[0x816F] = "{", [0x8162] = "|", [0x8170] = "}", [0x8160] = "~",
208}
209
210local function convertJisStr(str)
211	local niceStr = ""
212	local i = 1
213	while i <= #str do
214		local c1 = string.sub(str, i, i)
215		local b1 = string.byte(c1)
216		if b1 then
217			if bit.band(b1, 0x80) == 0x80 then
218				local c2 = string.sub(str, i + 1, i + 1)
219				local b2 = string.byte(c2)
220
221				local b16 = bit.bor(bit.lshift(b1, 8), bit.lshift(b2, 0))
222
223				if char_replacement_map[b16] then
224					niceStr = niceStr .. char_replacement_map[b16]
225				end
226
227				i = i + 2
228			else
229				niceStr = niceStr .. c1
230				i = i + 1
231			end
232		end
233	end
234	return niceStr
235end
236
237-- Captures all characters up to any amount of NULL characters
238local STRING_PATTERN = "^(.-)%z-$"
239
240local TYPES_READ = {
241	["bool"] = memory.readBool,
242
243	["sbyte"] = memory.readByte,
244	["byte"] = memory.readUByte,
245	["short"] = memory.readShort,
246	["int"] = memory.readInt,
247
248	["u8"] = memory.readUByte,
249	["s8"] = memory.readByte,
250	["u16"] = memory.readUShort,
251	["s16"] = memory.readShort,
252	["u32"] = memory.readUInt,
253	["s32"] = memory.readInt,
254
255	["float"] = memory.readFloat,
256
257	["data"] = memory.read,
258	["string"] = function(addr, len)
259		local value = memory.read(addr, len)
260		return value:match(STRING_PATTERN)
261	end,
262	["string-jis"] = function(addr, len)
263		local value = memory.read(addr, len)
264		return convertJisStr(value:match(STRING_PATTERN) or value)
265	end,
266}
267
268-- Creates or updates a tree of values for easy indexing
269-- Example a path of "player.name" will become memory.players = { name = value }
270function memory.cacheValue(table, path, value)
271	local last = table
272	local last_key = nil
273
274	local keys = {}
275	for key in string.gmatch(path, "[^%.]+") do
276		keys[#keys + 1] = tonumber(key) or key
277	end
278
279	for i, key in ipairs(keys) do
280		if i < #keys then
281			last[key] = last[key] or {}
282			last = last[key]
283		else
284			if type(last) ~= "table" then
285				return error(("Failed to index a %s value (%q)"):format(type(last), keys[i-1]))
286			end
287			last[key] = value
288			last_key = key
289		end
290	end
291
292	-- Return the table that the value is being stored in, and the key name
293	return last, last_key
294end
295
296local ADDRESS = {}
297ADDRESS.__index = ADDRESS
298
299function memory.newvalue(addr, offset, struct, name)
300	assert(type(addr) == "number", "argument #1 'address' must be a number")
301	assert(TYPES_READ[struct.type] ~= nil, "unhandled type: " .. struct.type)
302
303	name = name or struct.name or addr
304
305	local init = struct.init or NULL
306
307	-- create/get a new value cache based off of the value name
308	local tbl, key = memory.cacheValue(memory.values, name, init)
309
310	log.trace("[MEMORY] VALUE CACHE %08X + %X %q", addr, offset, name)
311
312	--local shoulddebug = name ~= "frame" and name:sub(1,10) ~= "controller"
313
314	return setmetatable({
315		name = name,
316
317		address = addr, -- Where in memory this value is located
318		offset = offset, -- How far past the address value we should get the value from
319
320		type = struct.type,
321		-- Assign the function we will be using to read from memory
322		read = TYPES_READ[struct.type],
323		len = struct.len,
324
325		-- Setup the cache
326		cache = tbl,
327		cache_key = key,
328		cache_value = init,
329
330		debug = struct.debug,
331	}, ADDRESS)
332end
333
334function ADDRESS:update()
335	if self.address == NULL then return end
336
337	local address = self.address + self.offset
338
339	-- value = converted value
340	-- orig = Non-converted value (Only available for floats)
341	local value, orig = self.read(address, self.len)
342
343	-- Check if there has been a value change
344	if self.cache_value ~= value then
345		self.cache_value = value
346		self.cache[self.cache_key] = self.cache_value
347
348		if self.debug then
349			if self.type == "string" or self.type == "string-jis" or self.type == "data" then
350				log.debug("[MEMORY] [0x%08X  = 0x%s] %s = %q", address, string.tohex(value), self.name, value)
351			else
352				local numValue = tonumber(orig) or tonumber(value) or (value and 1 or 0)
353				log.debug("[MEMORY] [0x%08X  = 0x%08X] %s = %s", address, numValue, self.name, value)
354			end
355		end
356
357		-- Queue up a hook event
358		table.insert(memory.hook_queue, {name = self.name, value = value})
359	end
360end
361
362local POINTER = {}
363POINTER.__index = POINTER
364
365function memory.newpointer(addr, offset, pointer, name)
366	local pstruct = {}
367
368	name = name or pointer.name
369
370	--log.debug("[MEMORY] POINTER CREATED %08X + %X %q", addr, offset, name or "nil")
371
372	-- Loop through the pointers children
373	for poffset, struct in pairs(pointer.struct) do
374		local sname = name
375		if sname and struct.name then
376			sname = sname .. "." .. struct.name
377		end
378		if struct.type == "pointer" then
379			pstruct[poffset] = memory.newpointer(NULL, poffset, struct, sname)
380		else
381			pstruct[poffset] = memory.newvalue(NULL, poffset, struct, sname)
382		end
383	end
384
385	return setmetatable({
386		parent = addr ~= NULL and pointer or nil,
387		name = name,
388		address = addr,
389		offset = offset,
390		location = NULL,
391		struct = pstruct,
392		debug = pointer.debug,
393	}, POINTER)
394end
395
396function POINTER:getAddress()
397	return ("0x%08X"):format(self.address + self.offset)
398end
399
400function POINTER:getPointerPath()
401	local parent = self
402	while parent do
403		local path = parent:getAddress()
404		path = parent:getAddress() .. " -> " .. path
405		parent = parent.parent
406	end
407	return path
408end
409
410do
411	local cast = ffi.cast
412	local GC_RAM_START = cast("uint32_t", 0x80000000)
413	local GC_RAM_END = cast("uint32_t", 0x81800000)
414	local WII_RAM_START = cast("uint32_t", 0x90000000)
415	local WII_RAM_END = cast("uint32_t", 0x94000000)
416
417	local function isValidPointer(ptr)
418		ptr = cast("uint32_t", ptr)
419		return ptr ~= NULL and ((ptr >= GC_RAM_START and ptr <= GC_RAM_END) or (ptr >= WII_RAM_START and ptr <= WII_RAM_END))
420	end
421
422	function POINTER:update()
423		local addr = self.address + self.offset
424		local ploc = memory.readUInt(addr)
425		local valid = isValidPointer(ploc)
426
427		if self.location ~= ploc then
428			self.location = ploc
429
430			if self.debug then
431				if valid then
432					log.debug("[MEMORY] [0x%08X -> 0x%08X] %s -> 0x%08X", addr, ploc, self.name, ploc)
433				else
434					log.debug("[MEMORY] [0x%08X -> 0x0 (NULL)] %s -> 0x%08X", addr, self.name, ploc)
435				end
436			end
437		end
438
439		if valid then
440			for offset, struct in pairs(self.struct) do
441				-- Set the address space to be where the containing pointer is pointing to
442				struct.address = ploc
443				-- Update the value/pointer recursively
444				struct:update()
445			end
446		end
447	end
448end
449
450function memory.loadmap(map)
451	for address, struct in pairs(map) do
452		if struct.type == "pointer" then
453			memory.map[address] = memory.newpointer(address, NULL, struct)
454		else
455			memory.map[address] = memory.newvalue(address, NULL, struct)
456		end
457	end
458end
459
460function memory.hasPermissions()
461	return memory.permissions
462end
463
464function memory.isInGame()
465	local gid = memory.gameid
466	local vcid = memory.vcid
467	return gid ~= GAME_NONE or vcid ~= VC_NONE
468end
469
470function memory.isMelee()
471	local gid = memory.gameid
472	local version = memory.version
473
474	if not gid or not version then return false end
475
476	-- Force the GAMEID and VERSION to be Melee 1.02, since Fizzi seems to be using the gameid address space for something..
477	if not memory.isSupportedGame(gid, version) and gid ~= GAME_NONE and PANEL_SETTINGS:IsSlippiNetplay() then
478		gid = "GALE01"
479		version = 0x02
480	end
481
482	-- See if this GameID is a clone of another
483	local clone = memory.clones[gid] and memory.clones[gid][version] or nil
484
485	if clone then
486		version = clone.version
487		gid = clone.id
488	end
489
490	return gid == "GALE01" and version == 0x02
491end
492
493local timer = love.timer.getTime()
494
495function memory.isSupportedGame(gid, version)
496	return love.filesystem.getInfo(string.format("modules/games/%s-%d.lua", gid, version)) ~= nil
497end
498
499function memory.loadGameScript(path)
500	-- Try to load the game table
501	local status, game = xpcall(require, debug.traceback, ("games.%s"):format(path))
502
503	if status then
504		memory.game = game
505		log.info("[DOLPHIN] Loaded game config: %s", path)
506		notification.info(("Game %q detected"):format(path))
507		if not game.translateCStick then
508			game.translateCStick = game.translateJoyStick
509		end
510		memory.init(game.memorymap)
511	else
512		notification.error(("Unsupported game %s"):format(path))
513		notification.error("Playing slippi netplay? Press 'escape' and enable Rollback/Netplay mode")
514		log.error("[DOLPHIN] %s", game) -- game variable is an error string
515	end
516end
517
518function memory.findGame()
519	local gid = memory.readGameID()
520	local version = memory.readGameVersion()
521	local vcid = memory.readVirtualConsoleID()
522
523	-- Force the GAMEID and VERSION to be Melee 1.02, since Fizzi seems to be using the gameid address space for something..
524	if not memory.isSupportedGame(gid, version) and gid ~= GAME_NONE and PANEL_SETTINGS:IsSlippiNetplay() then
525		gid = "GALE01"
526		version = 0x02
527	end
528
529	-- When playing Slippi netplay.. the game ID can and will change..
530	-- This would normally break things, but if you enable Rollback/Netplay mode it will force the gameid to always be GALE01 v1.02
531	local meleeMode = (memory.isMelee() and memory.gameid ~= gid)
532
533	if not memory.ingame and gid == GAME_NONE and vcid ~= VC_NONE then
534		memory.reset()
535		memory.ingame = true
536		memory.vcid = vcid
537
538		log.info("[DOLPHIN] Game: %s", vcid)
539		love.updateTitle(("M'Overlay - Dolphin hooked (%s)"):format(vcid))
540
541		-- Check for VC clones
542		vcid = memory.vcclones[vcid] or vcid
543
544		memory.loadGameScript(vcid)
545		memory.runhook("OnGameOpen", vcid)
546	elseif (not memory.ingame or meleeMode) and gid ~= GAME_NONE then
547		memory.reset()
548		memory.ingame = true
549		memory.gameid = gid
550		memory.version = version
551
552		log.info("[DOLPHIN] Game: %s revision %i", gid, version)
553		love.updateTitle(("M'Overlay - Dolphin hooked (%s-%i)"):format(gid, version))
554
555		-- See if this GameID is a clone of another
556		local clone = memory.clones[gid] and memory.clones[gid][version] or nil
557
558		if clone then
559			version = clone.version
560			gid = clone.id
561		end
562
563		memory.loadGameScript(("%s-%d"):format(gid, version))
564		memory.runhook("OnGameOpen", gid, version)
565	elseif (memory.ingame or meleeMode) and (gid == GAME_NONE and vcid == VC_NONE) then
566		memory.ingame = false
567		memory.gameid = gid
568		memory.vcid = vcid
569		memory.version = version
570
571		love.updateTitle("M'Overlay - Dolphin hooked")
572		memory.runhook("OnGameClosed")
573		memory.process:clearGamecubeRAMOffset() -- Clear the memory address space location (When a new game is opened, we recheck this)
574		log.info("[DOLPHIN] Game closed..")
575	end
576end
577
578function memory.update()
579	if not memory.hasPermissions() then return end
580
581	if not process:isProcessActive() and process:hasProcess() then
582		process:close()
583		love.updateTitle("M'Overlay - Waiting for Dolphin..")
584		log.info("[DOLPHIN] Unhooked")
585		memory.hooked = false
586	end
587
588	local t = love.timer.getTime()
589
590	-- Only check for the dolphin process once per second to reduce CPU load
591	if not process:hasProcess() or not process:hasGamecubeRAMOffset() then
592		if timer <= t then
593			timer = t + 0.5
594			if process:findprocess() then
595				log.info("[DOLPHIN] Hooked")
596				love.updateTitle("M'Overlay - Dolphin hooked")
597				memory.hooked = true
598			elseif not process:hasGamecubeRAMOffset() and process:findGamecubeRAMOffset() then
599				log.debug("[DOLPHIN] Watching ram address: 0x%X [%s]", process:getGamecubeRAMOffset(), string.toSize(process:getGamecubeRAMSize()))
600			end
601		end
602	else
603		memory.updatememory()
604
605		local frame = memory.frame or 0
606		if frame == 0 or memory.game_frame ~= frame then
607			memory.game_frame = frame
608			memory.runhooks()
609		end
610	end
611end
612
613function memory.init(map)
614	memory.initialized = true
615	memory.loadmap(map)
616	log.info("[MEMORY] Mapped game memory structure")
617end
618
619function memory.reset()
620	memory.initialized = false
621	memory.ingame = false
622	memory.map = {}
623	memory.values = {}
624	memory.gameid = GAME_NONE
625	memory.version = 0
626	memory.game = nil
627	setmetatable(memory, {__index = memory.values})
628end
629
630function memory.updatememory()
631	memory.findGame()
632
633	if memory.ingame then
634		for addr, value in pairs(memory.map) do
635			value:update()
636		end
637	end
638end
639
640local function hookPattern(name)
641	-- Convert '*' into capture patterns
642	if string.find(name, "*", 1, true) then
643		return true, '^' .. name:escape():gsub("%%%*", "([^.]-)") .. '$'
644	end
645	return false, name
646end
647
648function memory.hook(name, desc, callback)
649	local wildcard, name = hookPattern(name)
650	if wildcard then
651		memory.wildcard_hooks[name] = memory.wildcard_hooks[name] or {}
652		memory.wildcard_hooks[name][desc] = callback
653	else
654		memory.hooks[name] = memory.hooks[name] or {}
655		memory.hooks[name][desc] = callback
656	end
657end
658
659function memory.unhook(name, desc)
660	memory.hook(name, desc, nil)
661end
662
663function memory.runhooks()
664	local pop
665	while true do
666		pop = table.remove(memory.hook_queue, 1)
667		if not pop then break end
668		memory.runhook(pop.name, pop.value)
669	end
670end
671
672do
673	local args = {}
674	local matches = {}
675
676	function memory.runhook(name, ...)
677		-- Normal hooks
678		if memory.hooks[name] then
679			for desc, callback in pairs(memory.hooks[name]) do
680				local succ, err
681				if type(desc) == "table" then
682					-- Assume a table is an object, so call it as so
683					succ, err = xpcall(callback, debug.traceback, desc, ...)
684				else
685					succ, err = xpcall(callback, debug.traceback, ...)
686				end
687				if not succ then
688					log.error("[MEMORY] hook error: %s (%s)", desc, err)
689				end
690			end
691		end
692
693		local varargs = {...}
694
695		-- Allow for wildcard hooks
696		for pattern, hooks in pairs(memory.wildcard_hooks) do
697			if string.find(name, pattern) then
698				args = {}
699				matches = {name:match(pattern)}
700
701				for k, match in ipairs(matches) do
702					table.insert(args, tonumber(match) or match)
703				end
704				for k, arg in ipairs(varargs) do
705					table.insert(args, arg)
706				end
707
708				for desc, callback in pairs(hooks) do
709					local succ, err
710					if type(desc) == "table" then
711						-- Assume a table is an object, so call it as so
712						succ, err = xpcall(callback, debug.traceback, desc, unpack(args))
713					else
714						succ, err = xpcall(callback, debug.traceback, unpack(args))
715					end
716					if not succ then
717						log.error("[MEMORY] wildcard hook error: %s (%s)", desc, err)
718					end
719				end
720			end
721		end
722	end
723end
724
725return memory