#!/usr/bin/env python3
"""Probe 5: identity-map the parser locals to proto slots inside l[56]."""
STAGE2 = '/root/luad/samples/boulder/stage2.lua'
PAYLOAD = '/root/luad/samples/boulder/payload.bin'
OUT = '/tmp/opencode/dump_run5.luau'

SHIM = r'''
local __realprint = print
tick = function() return 0 end
time = function() return 0 end
warn = function() end
typeof = function(v) return type(v) end
__PROTO_ID = 0
__ID = function(pid, m, P, d, t, p, h, o, y, b)
	local names = { "P", "d", "t", "p", "h", "o", "y", "b" }
	local vals = { P, d, t, p, h, o, y, b }
	local out = {}
	for si = 1, 11 do
		local slot = m[si]
		local hit = "?"
		for vi = 1, 8 do
			if type(slot) == "table" and slot == vals[vi] then hit = names[vi] end
		end
		out[#out + 1] = si .. "=" .. hit
	end
	__realprint("ID", pid, table.concat(out, " "), "ycount", tostring(y))
end
'''

def main():
    stage2 = open(STAGE2, 'rb').read().decode('latin-1')
    payload = open(PAYLOAD, 'rb').read()
    rlit = '"' + ''.join('\\x%02x' % b for b in payload) + '"'
    stage2 = stage2.replace('local R=...;', 'local R=buffer.fromstring(' + rlit + ');', 1)
    needle0 = '(l)[56]=(function()local T,O,m,A,e,P;'
    assert stage2.count(needle0) == 1
    stage2 = stage2.replace(needle0, '(l)[56]=(function()__PROTO_ID=__PROTO_ID+1;local T,O,m,A,e,P;', 1)
    needle2 = 'for e=1.0,y,1 do local y,q;'
    assert stage2.count(needle2) == 1, stage2.count(needle2)
    stage2 = stage2.replace(needle2, '__ID(__PROTO_ID,m,P,d,t,p,h,o,y,b);' + needle2, 1)
    out = SHIM + 'local __ok,__err=pcall(function()\n' + stage2 + '\nend)\n'
    out += '__realprint("EXEC", __ok, tostring(__err))\n'
    open(OUT, 'w').write(out)
    print("wrote", OUT, len(out))

if __name__ == '__main__':
    main()
