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