Files

151 lines
9.3 KiB
Lua

-- Independent translator for the directives used by this bundled table.
-- Unknown directives and failed assertions are errors, never skipped.
Symbols, Allocations = {}, {}
local function trim(s) return s:match('^%s*(.-)%s*$') end
function resolveAddress(x,soft)
if type(x)=='number' then return x end
if type(x)~='string' then if soft then return nil end;error('Invalid address expression') end
x=trim(x)
if x:lower()=='pbz.exe' then return H('base') end
if Symbols[x:lower()] then return Symbols[x:lower()] end
local a,b=x:match('^(.-)%+([%da-fA-F]+)$')
if a then local v=resolveAddress(a,true);if v then return v+tonumber(b,16) end end
a,b=x:match('^(.-)%-([%da-fA-F]+)$')
if a then local v=resolveAddress(a,true);if v then return v-tonumber(b,16) end end
local n=tonumber(x:match('^0[xX](.+)$') or x,16)
if n then return n end
if soft then return nil end;error('Unresolved address: '..x)
end
local function hex(x) return ('0x%X'):format(x) end
local function args(s) local t={};for a in s:gmatch('[^,]+')do t[#t+1]=trim(a)end;return t end
local function bytesText(s)
local t={};for i=1,#s do t[#t+1]=('0x%02X'):format(s:byte(i))end
return 'db '..table.concat(t,',')
end
local function asmNumbers(line)
local function floatingLiteral(s,kind)
local value=assert(tonumber(s),'Invalid floating-point literal: '..s)
local packed=string.pack(kind=='float'and '<f'or '<d',value)
local bits=string.unpack(kind=='float'and '<I4'or '<i8',packed)
return ('0x%X'):format(bits)
end
line=line:gsub('%(float%)([-+%d%.]+)',function(s)return floatingLiteral(s,'float')end)
line=line:gsub('%(double%)([-+%d%.]+)',function(s)return floatingLiteral(s,'double')end)
line=line:gsub('#(%d+)',function(s)return ('0x%X'):format(tonumber(s))end)
local first=true;local opcodes={add=true,adc=true,dec=true,fadd=true}
line=line:gsub('(@?)([%w_%.]+)',function(prefix,s)
if prefix=='@'then return prefix..s end
if first then first=false;return s end
if s:match('^[%x]+$')and not opcodes[s:lower()]then return '0x'..s end
return s
end)
line=line:gsub('%f[%a]ptr%f[^%a]%s*',''):gsub('%f[%a]xmmword%f[^%a]','oword')
line=line:gsub('([fFgG][sS]):%[','[%1:')
line=line:gsub('%f[%a]short%f[^%a]%s*','short ')
local op,data=line:match('^(d[bwdq])%s+(.+)$')
if op then line=op..' '..data:gsub('%s+',','):gsub(',+',',')end
local count=line:match('^nop%s+(.+)$');if count then line='times '..count..' nop'end
return line
end
function AssembleIndependent(text)
local previousSymbols={};for k,v in pairs(Symbols)do previousSymbols[k]=v end
local definitions,labels,registers,unregisters,frees,newalloc,allocspec={},{},{},{},{},{},{}
local input={}
text=text:gsub('/%*.-%*/','')
for line in (text..'\n'):gmatch('(.-)\n') do
line=trim(line:gsub('//.*$',''):gsub(';.*$',''))
if line~='' and not line:match('^%[.*%]$') then input[#input+1]=line end
end
local function expand(s)
for pass=1,12 do local changed=false;s=s:gsub('([%w_%.]+)',function(w)if definitions[w] then changed=true;return definitions[w]end;return w end);if not changed then break end end
return s
end
-- Definitions can be referenced by later checks; original memory is read before writes.
local prepared,prepareError=pcall(function()
for _,line in ipairs(input) do local op,body=line:match('^([%w_]+)%s*%((.*)%)$');op=op and op:lower()
if op=='define' then local a=args(body);definitions[a[1]]=a[2]
elseif op=='aobscanmodule' then local a=args(body);local hits=H('scan',a[3],H('base'),H('base')+H('size')-1,true);if #hits~=1 then error('Signature '..a[1]..' expected one match, got '..#hits)end;Symbols[a[1]:lower()]=hits[1]
elseif op=='alloc' then allocspec[#allocspec+1]=args(body)
elseif op=='label' then labels[body]=true
elseif op=='registersymbol' then registers[#registers+1]=body
elseif op=='unregistersymbol' then unregisters[#unregisters+1]=body
elseif op=='dealloc' then frees[#frees+1]=body
elseif op=='assert' then local a=args(body);local at=resolveAddress(expand(a[1]));local pat=a[2];local count=0;for _ in pat:gmatch('%S+')do count=count+1 end;local b=H('read',at,count);if not b or not H('matches',b,pat)then error('Original bytes do not match: '..a[1])end
end
end
end)
if not prepared then Symbols=previousSymbols;error(prepareError)end
local blocks,code,syms={}, {'use64'},{}
local function startBlock(at)
if #blocks>0 then code[#code+1]='__end'..#blocks..':' end
local n=#blocks+1;blocks[n]={address=at};code[#code+1]='org '..hex(at);code[#code+1]='__begin'..n..':'
end
local ok,result=pcall(function()
for _,a in ipairs(allocspec)do local size=assert(tonumber(expand(a[2]):gsub('^%$',''),16),'Invalid allocation size');if Symbols[a[1]:lower()]then error('Allocation already owned: '..a[1])end;local near=a[3]and resolveAddress(expand(a[3]),true)or H('base');local p=H('alloc',size,near or 0);Symbols[a[1]:lower()]=p;Allocations[a[1]:lower()]={address=p,size=size};newalloc[#newalloc+1]=a[1]:lower()end
for name,value in pairs(Symbols)do if not labels[name]then code[#code+1]=name..' = '..hex(value)end end
for _,line in ipairs(input)do
local op,body=line:match('^([%w_]+)%s*%((.*)%)$');op=op and op:lower()
if op=='readmem' then local a=args(body);local at=resolveAddress(expand(a[1]));local n=assert(tonumber(expand(a[2]):gsub('^%$',''),16));local b=H('read',at,n);if not b then error('Unreadable source bytes: '..a[1])end;code[#code+1]=bytesText(b)
elseif op=='alloc' or op=='dealloc' or op=='label' or op=='define' or op=='aobscanmodule' or op=='assert' or op=='registersymbol' or op=='unregistersymbol' then
elseif op then error('Unsupported assembler directive: '..op)
else
local name=line:match('^([%w_%.+%-]+):$')
if name then local at=resolveAddress(expand(name),true)
if at then startBlock(at)else if #blocks==0 then error('Label has no allocation: '..name)end;code[#code+1]=name..':' end
else
if #blocks==0 then error('Instruction outside allocation: '..line)end
code[#code+1]=asmNumbers(expand(line))
end
end
end
if #blocks>0 then
code[#code+1]='__end'..#blocks..':'
-- A symbol table is appended to the binary, never written into the game.
code[#code+1]='dq 0x314154454D5A4250'
for i=1,#blocks do code[#code+1]='dq __end'..i..'-__begin'..i end
for name in pairs(labels)do syms[#syms+1]=name end;table.sort(syms)
for _,name in ipairs(syms)do code[#code+1]='dq '..name end
local bin=H('assemble',table.concat(code,'\n'):lower())
local tail=8+8*#blocks+8*#syms
local pos=#bin-tail+1;local marker=string.unpack('<i8',bin,pos);assert(marker==0x314154454D5A4250,'Assembler metadata mismatch');pos=pos+8
local offset=1
for i,b in ipairs(blocks)do local n;n,pos=string.unpack('<i8',bin,pos);assert(n>=0 and n<=#bin-tail,'Invalid assembled block');b.data=bin:sub(offset,offset+n-1);offset=offset+n end
assert(offset==#bin-tail+1,'Assembly block lengths do not match')
for _,name in ipairs(syms)do local address;address,pos=string.unpack('<i8',bin,pos);Symbols[name:lower()]=address end
for _,name in ipairs(registers)do local key=name:lower();if not Symbols[key]then Symbols[key]=resolveAddress(expand(name),true)end;assert(Symbols[key],'Cannot register unresolved symbol '..name)end
local snapshots={}
for _,b in ipairs(blocks)do if #b.data>0 then local before=H('read',b.address,#b.data);assert(before,'Patch target is unreadable');snapshots[#snapshots+1]={address=b.address,before=before,after=b.data,new=false};for _,a in pairs(Allocations)do if b.address>=a.address and b.address+#b.data<=a.address+a.size then snapshots[#snapshots].new=true;break end end end end
-- Populate private code first, then install entry-point jumps.
table.sort(snapshots,function(a,b)return a.new and not b.new end)
local written={}
for _,b in ipairs(snapshots)do
local succeeded,value=pcall(H,'write',b.address,b.after,true)
if not succeeded or not value then
local rollbackOK,restored=pcall(H,'write',b.address,b.before,true);rollbackOK=rollbackOK and restored
for j=#written,1,-1 do local w=written[j];local ok,done=pcall(H,'write',w.address,w.before,true);if not ok or not done then rollbackOK=false end end
if not rollbackOK then error('CRITICAL: patch rollback failed; allocation preserved for recovery')end
error('Patch write failed; previous writes were rolled back')
end
written[#written+1]=b
end
end
for _,name in ipairs(registers)do local key=name:lower();if not Symbols[key]then Symbols[key]=resolveAddress(expand(name),true)end end
for _,name in ipairs(frees)do local key=name:lower();local a=Allocations[key];if a then assert(H('free',a.address),'Could not release owned allocation');Allocations[key]=nil end;Symbols[key]=nil;previousSymbols[key]=nil end
for _,name in ipairs(unregisters)do Symbols[name:lower()]=nil end
for _,name in ipairs(registers)do assert(Symbols[name:lower()],'Cannot register unresolved symbol '..name)end
local persistent={};for k,v in pairs(previousSymbols)do persistent[k]=v end
for _,name in ipairs(registers)do persistent[name:lower()]=Symbols[name:lower()]end
for _,name in ipairs(unregisters)do persistent[name:lower()]=nil end
Symbols=persistent
return true
end)
if not ok then
if not tostring(result):find('CRITICAL:',1,true)then
for _,name in ipairs(newalloc)do local a=Allocations[name];if a then H('free',a.address);Allocations[name]=nil;Symbols[name]=nil end end
end
if not tostring(result):find('CRITICAL:',1,true)then Symbols=previousSymbols end
error(result)
end
return true
end