diff --git a/src/prometheus/steps/NumbersToExpressions.lua b/src/prometheus/steps/NumbersToExpressions.lua index 1011b053..6ee259f1 100644 --- a/src/prometheus/steps/NumbersToExpressions.lua +++ b/src/prometheus/steps/NumbersToExpressions.lua @@ -163,7 +163,12 @@ function NumbersToExpressions:CreateNumberExpression(val, depth) local exp = math.floor(math.log10(math.abs(val))) local mantissa = val / (10 ^ exp) - return Ast.NumberExpression(string.format("%.15ge%d", mantissa, exp)) + local formatted = string.format("%.15ge%d", mantissa, exp) + -- Round-trip check. Not exact for every value. + if tonumber(formatted) ~= val then + return Ast.NumberExpression(val) + end + return Ast.NumberExpression(formatted) end if format == "normal" then diff --git a/src/prometheus/steps/Vmify.lua b/src/prometheus/steps/Vmify.lua index 05a14cd4..462d548c 100644 --- a/src/prometheus/steps/Vmify.lua +++ b/src/prometheus/steps/Vmify.lua @@ -2,16 +2,34 @@ local Step = require('prometheus.step') local Compiler = require('prometheus.vm.compiler') local Emit = require('prometheus.vm.emit') +local EncryptOperands = require('prometheus.vm.encrypt_operands') local Vmify = Step:extend() Vmify.Name = 'Vmify' Vmify.Description = 'Compiles functions into register instructions executed by a generated Lua VM.' -Vmify.SettingsDescriptor = {} +Vmify.SettingsDescriptor = { + -- Encrypts every plain numeric VM operand (register indices, constant + -- indices, jump targets, call-arity flags) with a keystream chained off + -- each previously-decrypted operand's own value. Operands exist in + -- cleartext only transiently, inside the generated interpreter's + -- registers, while it is actually running; nothing in the emitted data + -- or source ever holds a decrypted operand or a static per-instruction + -- key. Must run here, before the instruction stream is scattered into + -- the emitted literal data by Emit.ast -- by the time any later + -- pipeline step sees the AST, Vmify's instructions no longer exist as + -- a walkable array of {opcode, operands...}, only as shuffled table + -- records, so this cannot be a separate post-Vmify step. + EncryptOperands = {type = 'boolean', default = false}, +} function Vmify:init() end function Vmify:apply(ast) - return Emit.ast(Compiler:compile(ast)) + local proto = Compiler:compile(ast) + if self.EncryptOperands then + EncryptOperands.apply(proto) + end + return Emit.ast(proto, self.EncryptOperands) end return Vmify diff --git a/src/prometheus/vm/data.lua b/src/prometheus/vm/data.lua index 1e058f10..9be53ad1 100644 --- a/src/prometheus/vm/data.lua +++ b/src/prometheus/vm/data.lua @@ -35,6 +35,18 @@ function Data.encode(proto, layout) for _, name in ipairs({'constants', 'captures', 'params', 'vararg', 'maxRegister'}) do result[layout.fields[name]] = value[name] end + if value.operandSeed then + result[layout.fields.operandSeed] = value.operandSeed + -- The leader set is a sparse { [pc] = true } map over + -- 1..#code+1; encode it densely as a plain array of booleans + -- so it collects and scatters through Data.encode like any + -- other table value. + local leaders = {} + for pc = 1, #value.code + 1 do + leaders[pc] = value.operandLeaders[pc] or false + end + result[layout.fields.operandLeaders] = leaders + end return result end local root = {prototype(proto)} diff --git a/src/prometheus/vm/emit.lua b/src/prometheus/vm/emit.lua index 9854769b..e5f13b05 100644 --- a/src/prometheus/vm/emit.lua +++ b/src/prometheus/vm/emit.lua @@ -7,17 +7,17 @@ local Data = require('prometheus.vm.data') local Source = require('prometheus.source') local Emit = {} -function Emit.source(proto, layout) +function Emit.source(proto, layout, encryptOperands) layout = layout or Layout.new() local data, tables, root = Data.encode(proto, layout) local initializer = 'rebuild(' .. data .. ',' .. tables .. ',' .. root .. ')' - local source, count = Runtime.build(layout):gsub('__PROTOTYPES__', function() return initializer end) + local source, count = Runtime.build(layout, encryptOperands):gsub('__PROTOTYPES__', function() return initializer end) assert(count == 1, 'Runtime template must contain one prototype marker') return Data.rebuild .. source end -function Emit.ast(proto) - local source = Emit.source(proto) +function Emit.ast(proto, encryptOperands) + local source = Emit.source(proto, nil, encryptOperands) local ast = Parser:new({LuaVersion = Enums.LuaVersion.Lua51}):parse(source, Source.internal('VM', source)) local invocation = ast.body.statements[#ast.body.statements].args[1] ast.vmRuntime = invocation.base diff --git a/src/prometheus/vm/encrypt_operands.lua b/src/prometheus/vm/encrypt_operands.lua new file mode 100644 index 00000000..e01e89ee --- /dev/null +++ b/src/prometheus/vm/encrypt_operands.lua @@ -0,0 +1,196 @@ +-- Encrypts VM instruction operands with a running keystream chained off each +-- previously-decrypted operand's own value, so operands exist in cleartext +-- only transiently during execution and never in the emitted data or in any +-- static per-instruction table. Intended to run after vm/optimize.lua (so +-- PCs, and therefore JMP/JFALSE/JTRUE targets, are final) and before +-- vm/emit.lua (so it sees plain IR instructions, not the shuffled, per-build +-- operand/opcode layout that Layout:encode applies just before unparsing). +-- +-- Cipher: an arithmetic-only 32-bit mix, mirrored exactly (as a Lua source +-- template, see vm/runtime_cipher.lua) inside the generated interpreter, so +-- decryption happens identically at runtime with no native bitwise +-- operators -- the Lua 5.1 target this project emits for has none. +local opcodes = require('prometheus.vm.opcodes') +local signature = require('prometheus.vm.operand_signature') + +-- proto.code stores numeric opcode IDs (vm/compiler.lua emits opcodes[op] +-- directly); recover the name so operand_signature.lua can be indexed by it. +local opcodeNames = {} +for name, id in pairs(opcodes) do opcodeNames[id] = name end + +-- A pure forward chain across the whole instruction stream only gives a +-- well-defined decrypt key when every instruction is reached exactly one +-- way. Any join point -- a jump target, or the PC right after a jump, that +-- more than one edge can reach -- breaks that: the runtime's running hash +-- reflects whichever path was actually taken, but each instruction's +-- operands were encrypted against only one specific prior state. So the +-- chain is instead reset at every basic-block leader (this mirrors the +-- leader computation vm/optimize.lua already does for its own passes) and +-- only ever threaded *within* a block, where a single entry point means +-- the incoming state is unambiguous regardless of how that block was +-- reached. Each instruction still extends the chain for every later +-- instruction in the same block, exactly as specified; blocks simply +-- bound how far any one chain runs. +local function computeLeaders(code) + local count = #code + local leaders = {[1] = true, [count + 1] = true} + for pc, instruction in ipairs(code) do + local op = opcodeNames[instruction[1]] + if op == 'JMP' then + leaders[pc + 1] = true; leaders[instruction[2]] = true + elseif op == 'JTRUE' or op == 'JFALSE' then + leaders[pc + 1] = true; leaders[instruction[3]] = true + elseif op == 'RETURN' or op == 'RETURN0' or op == 'RETURN1' + or op == 'RETURN2' or op == 'RETURN3' or op == 'TAILCALL' + or op == 'TAILCALL0' or op == 'TAILCALL1' or op == 'TAILCALL2' + or op == 'TAILCALL3' then + leaders[pc + 1] = true + end + end + return leaders +end + +local MASK = 4294967296 -- 2^32 +local PRIME1, PRIME2, PRIME3 = 2654435761, 2246822519, 3266489917 +local floor = math.floor + +local function bxor32(a, b) + a, b = a % MASK, b % MASK + local result, bit = 0, 1 + while a > 0 or b > 0 do + local abit, bbit = a % 2, b % 2 + if abit ~= bbit then result = result + bit end + a, b = (a - abit) / 2, (b - bbit) / 2 + bit = bit * 2 + end + return result +end + +local function rotl32(x, r) + x = x % MASK + local hi = floor(x / 2 ^ (32 - r)) + local lo = (x * 2 ^ r) % MASK + return (lo + hi) % MASK +end + +-- Operands are not all non-negative: CALL/TAILCALL's trailing result-count +-- flag is one of {-1, 0, 1} (variable results, none, or a known fixed +-- count). bxor32/mix only ever see or produce values in [0, 2^32), the +-- two's-complement bit pattern of a 32-bit int -- -1 and 4294967295 are the +-- same bits. Encrypting must fold a negative operand's bit pattern in +-- (toUnsigned32), and decrypting must fold the bit pattern back out to the +-- signed value the rest of the interpreter actually compares against +-- (toSigned32) -- otherwise a decrypted -1 comes back as 4294967295, which +-- is numerically different even though every bit matches. +local function toUnsigned32(value) + return value % MASK +end + +local function toSigned32(value) + value = value % MASK + if value >= MASK / 2 then + return value - MASK + end + return value +end + +-- Folds one plaintext operand value into the running hash state. Any real +-- number is accepted (operands are always non-negative integers in +-- practice: register slots, constant indices, child/jump indices, or the +-- small {-1,0,1} CALL result-mode flag), so the value is reduced mod 2^32 +-- before mixing to keep every intermediate an exact double. +local function mix(h, value) + value = value % MASK + h = bxor32(h, value) + h = (h * PRIME1) % MASK + h = bxor32(h, floor(h / 65536)) + h = (h * PRIME2) % MASK + h = bxor32(h, floor(h / 32771)) + h = (h + PRIME3) % MASK + return rotl32(h, 13) +end + +-- Derives this step's keystream word from the current hash state. Kept +-- separate from mix() so encrypting an operand does not itself perturb the +-- state used to decrypt it -- the state only advances once the operand's +-- plaintext value is folded in via mix(), after the XOR is applied. +local function keystream(h) + local k = bxor32(h, floor(h / 15)) + k = (k * PRIME2) % MASK + return bxor32(k, floor(k / 13)) +end + +local Encrypt = {} + +-- Seeds one prototype's cipher. Each prototype (top-level chunk and every +-- nested function) gets its own independent chain, started from an +-- unpredictable per-build seed, so nothing about one function's operands +-- can be inferred from another's. +function Encrypt.seed() + return math.random(0, MASK - 1) +end + +-- Encrypts one prototype's instruction stream in place, in final PC order, +-- then recurses into children (each with its own seed), storing each +-- prototype's seed as proto.operandSeed so the emitter carries it into the +-- data the generated interpreter reads at startup. +-- +-- The running state h starts at the prototype's seed (itself an opaque +-- number baked into the emitted data, not a secret derived at runtime) and +-- advances exactly once per plain-numeric operand, in instruction order, +-- regardless of opcode. 'X' (opaque, non-numeric) operand slots are left +-- untouched and do not advance h -- a table has no single plaintext value +-- to fold in, and skipping it keeps the runtime decrypt loop a fixed, +-- opcode-driven sequence of XORs with no conditional structure to branch on. +function Encrypt.apply(proto) + local seed = Encrypt.seed() + local leaders = computeLeaders(proto.code) + local h = seed + for pc, instruction in ipairs(proto.code) do + if leaders[pc] then h = seed end + local name = opcodeNames[instruction[1]] + local shape = assert(signature[name], + 'EncryptOperands: no operand signature for opcode ' .. tostring(name)) + for position = 1, #shape do + if shape[position] == 'N' then + local slot = position + 1 -- instruction[1] is the opcode + local plain = instruction[slot] + if plain ~= nil then + instruction[slot] = bxor32(plain, keystream(h)) + h = mix(h, plain) + end + end + end + end + -- The leader set itself: which PCs must reseed h = seed before + -- decrypting. This is the only static per-instruction information the + -- cipher relies on (one bit per PC, carried as its own prototype field + -- rather than a variable-position extra operand, since IR instructions + -- already vary in length per opcode and Layout:encode's fixed 2..5 + -- operand slots have no room for a fifth, opcode-dependent element). + -- It says nothing about any operand's value, only where block + -- boundaries fall -- information control-flow structure already + -- reveals on its own. + proto.operandLeaders = leaders + -- Stored as plain prototype metadata (alongside maxRegister etc.); the + -- seed is not a secret by itself -- without re-running the exact chain + -- of decrypts the interpreter performs, it reveals nothing about any + -- individual operand's plaintext. + proto.operandSeed = seed + for _, child in ipairs(proto.children or {}) do + Encrypt.apply(child) + end +end + +Encrypt.bxor32 = bxor32 +Encrypt.rotl32 = rotl32 +Encrypt.mix = mix +Encrypt.keystream = keystream +Encrypt.toUnsigned32 = toUnsigned32 +Encrypt.toSigned32 = toSigned32 +Encrypt.MASK = MASK +Encrypt.PRIME1 = PRIME1 +Encrypt.PRIME2 = PRIME2 +Encrypt.PRIME3 = PRIME3 + +return Encrypt diff --git a/src/prometheus/vm/layout.lua b/src/prometheus/vm/layout.lua index 782b7a38..47451e91 100644 --- a/src/prometheus/vm/layout.lua +++ b/src/prometheus/vm/layout.lua @@ -1,7 +1,7 @@ -- Choose instruction encoding and metadata keys per VM. Compiler IR stays semantic. local opcodes = require('prometheus.vm.opcodes') local shuffle = require('prometheus.util').shuffle -local fields = {'code', 'constants', 'captures', 'params', 'vararg', 'maxRegister', 'children'} +local fields = {'code', 'constants', 'captures', 'params', 'vararg', 'maxRegister', 'children', 'operandSeed', 'operandLeaders'} local Layout = {} Layout.__index = Layout diff --git a/src/prometheus/vm/operand_signature.lua b/src/prometheus/vm/operand_signature.lua new file mode 100644 index 00000000..b0624756 --- /dev/null +++ b/src/prometheus/vm/operand_signature.lua @@ -0,0 +1,76 @@ +-- Declares, per opcode, which IR operand slots are plain numbers (register +-- indices, constant indices, jump targets, small control flags) versus +-- opaque values that are not numbers (register-list tables used by ARGS, +-- CLOSURE's capture list is read via the child prototype, CLEARS' register +-- list, and the fixed-arity CALL/TAILCALL family's args table). +-- +-- Instructions are {opcode, operand2, operand3, operand4, operand5} in +-- compiler IR (see vm/compiler.lua Compiler:emit). This table is indexed by +-- opcode *name* and lists, for operand positions 2..5, whether the operand +-- at that position is a plain number ('N') or must be left alone ('X'). +-- Positions beyond the listed length do not occur for that opcode. +-- +-- EncryptOperands (vm/encrypt_operands.lua) uses this to decide which +-- operand values join the running cipher stream; the generated runtime +-- decrypts exactly those same positions, for exactly those opcodes, using +-- a layout-independent per-opcode arity table derived from this file. + +local signatures = { + LOAD = {'N', 'N'}, + NIL = {'N'}, + MOVE = {'N', 'N'}, + CLEAR = {'N'}, + CELL = {'N', 'N'}, + GETCELL = {'N', 'N'}, + SETCELL = {'N', 'N'}, + GETUP = {'N', 'N'}, + SETUP = {'N', 'N'}, + GLOBAL = {'N', 'N'}, + SETGLOBAL = {'N', 'N'}, + GETTABLE = {'N', 'N', 'N'}, + SETTABLE = {'N', 'N', 'N'}, + TABLE = {'N'}, + EXPAND = {'N', 'N', 'N'}, + ARGS = {'N', 'X', 'N'}, + TAKE = {'N', 'N', 'N'}, + VARARG = {'N'}, + RETURN = {'N'}, + CLOSURE = {'N', 'N'}, + JMP = {'N'}, + JFALSE = {'N', 'N'}, + JTRUE = {'N', 'N'}, + ADD = {'N', 'N', 'N'}, + SUB = {'N', 'N', 'N'}, + MUL = {'N', 'N', 'N'}, + DIV = {'N', 'N', 'N'}, + MOD = {'N', 'N', 'N'}, + POW = {'N', 'N', 'N'}, + CONCAT = {'N', 'N', 'N'}, + LT = {'N', 'N', 'N'}, + LE = {'N', 'N', 'N'}, + GT = {'N', 'N', 'N'}, + GE = {'N', 'N', 'N'}, + EQ = {'N', 'N', 'N'}, + NE = {'N', 'N', 'N'}, + NOT = {'N', 'N'}, + NEG = {'N', 'N'}, + LEN = {'N', 'N'}, + FORPREP = {'N', 'N', 'N'}, + FORCHECK = {'N', 'N', 'N', 'N'}, + CALL = {'N', 'N', 'X', 'N'}, + TAILCALL = {'N', 'X'}, + RETURN0 = {}, + RETURN1 = {'N'}, + RETURN2 = {'N', 'N'}, + RETURN3 = {'N', 'N', 'N'}, + CLEARS = {'X'}, +} + +-- Fixed-arity call/tailcall families: args/registers table is opaque ('X'); +-- everything else numeric. +for arity = 0, 3 do + signatures['CALL' .. arity] = {'N', 'N', 'X', 'N'} + signatures['TAILCALL' .. arity] = {'N', 'X'} +end + +return signatures diff --git a/src/prometheus/vm/runtime.lua b/src/prometheus/vm/runtime.lua index 9b2f4fd9..964ee2ac 100644 --- a/src/prometheus/vm/runtime.lua +++ b/src/prometheus/vm/runtime.lua @@ -1,6 +1,9 @@ -- Builds the Lua 5.1 runtime used by the bytecode emitter. The emitter replaces -- __PROTOTYPES__ with the startup reconstruction call before parsing the source. local dispatch = require("prometheus.vm.runtime_dispatch") +local decryptDispatch = require("prometheus.vm.runtime_decrypt") +local cipherSource = require("prometheus.vm.runtime_cipher") +local Encrypt = require("prometheus.vm.encrypt_operands") local Layout = require("prometheus.vm.layout") local Runtime = {} @@ -18,17 +21,22 @@ local function pack(...) return { [__COUNT_KEY__] = nativeSelect("#", ...), ... } end +__CIPHER_FUNCTIONS__ + local make local function loop(P, U, Env, R, V) local code, K = P[__FIELD_code__], P[__FIELD_constants__] local pc = 1 local I, opcode, a, b, c, d, x, y, z + __OPERAND_HASH_INIT__ while true do I = code[pc] + __OPERAND_HASH_RESEED__ pc = pc + 1 opcode = I[1] __FETCH_OPERANDS__ + __DECRYPT_OPERANDS__ __DISPATCH__ I, opcode, a, b, c, d, x, y, z = nil, nil, nil, nil, nil, nil, nil, nil, nil end @@ -99,16 +107,52 @@ return make(prototypes[1], {}, entryEnv)(...) end)(__PROTOTYPES__, ...) ]=] -function Runtime.build(layout) +-- encryptOperands selects, at generation time, whether the interpreter +-- carries the operand cipher at all. When false (the default, and what +-- every existing preset still gets), __DECRYPT_OPERANDS__ and +-- __CIPHER_FUNCTIONS__ expand to nothing: no seed/leader locals, no XOR, +-- no behavior change whatsoever versus the pre-cipher runtime. This must +-- be a build-time choice rather than a per-instruction runtime check -- +-- a disabled cipher has to generate code that cannot touch an operand, +-- not code that asks every single instruction not to. +function Runtime.build(layout, encryptOperands) layout = layout or Layout.new() local operands = layout.operands local fetch = "a, b, c, d = I[" .. tostring(operands[1]) .. "], I[" .. tostring(operands[2]) .. "], I[" .. tostring(operands[3]) .. "], I[" .. tostring(operands[4]) .. "]" + local cipherFunctions, decrypt, hashInit, hashReseed = '', '', '', '' + if encryptOperands then + cipherFunctions = cipherSource + :gsub('__CIPHER_MASK__', tostring(Encrypt.MASK)) + :gsub('__CIPHER_PRIME1__', tostring(Encrypt.PRIME1)) + :gsub('__CIPHER_PRIME2__', tostring(Encrypt.PRIME2)) + :gsub('__CIPHER_PRIME3__', tostring(Encrypt.PRIME3)) + decrypt = decryptDispatch.build(layout.opcodes) + -- Per-activation cipher state: reseeded from the prototype's seed + -- at startup and again on entry to every basic block (a block can + -- be reached along more than one control-flow edge, and only a + -- single, path-independent starting state gives every instruction + -- in it one well-defined key). Within a block it just keeps + -- advancing, each decrypted operand feeding the key for the next. + -- Nothing here exists except as a local inside this one call. + hashInit = 'local __vmOperandSeed = P[' .. tostring(layout.fields.operandSeed) .. '] or 0\n' + .. ' local __vmOperandLeaders = P[' .. tostring(layout.fields.operandLeaders) .. ']\n' + .. ' local __vmOperandHash = __vmOperandSeed' + hashReseed = 'if __vmOperandLeaders and __vmOperandLeaders[pc] then __vmOperandHash = __vmOperandSeed end' + end local source = template:gsub("__FETCH_OPERANDS__", function() return fetch + end):gsub("__DECRYPT_OPERANDS__", function() + return decrypt end):gsub("__DISPATCH__", function() return dispatch.build(layout.opcodes) + end):gsub("__CIPHER_FUNCTIONS__", function() + return cipherFunctions + end):gsub("__OPERAND_HASH_INIT__", function() + return hashInit + end):gsub("__OPERAND_HASH_RESEED__", function() + return hashReseed end) source = source:gsub('__FIELD_(%w+)__', function(name) return tostring(assert(layout.fields[name], 'Missing VM prototype key')) diff --git a/src/prometheus/vm/runtime_cipher.lua b/src/prometheus/vm/runtime_cipher.lua new file mode 100644 index 00000000..15ac9c5b --- /dev/null +++ b/src/prometheus/vm/runtime_cipher.lua @@ -0,0 +1,61 @@ +-- Source text for the operand-decrypt cipher, inlined into the generated +-- VM interpreter by vm/runtime.lua. Must stay arithmetically identical to +-- vm/encrypt_operands.lua's bxor32/rotl32/mix/keystream -- both sides are +-- the same algorithm, one run once at build time to encrypt, the other run +-- every single instruction at run time to decrypt. +-- +-- __CIPHER_MASK__, __CIPHER_PRIME1__, __CIPHER_PRIME2__, __CIPHER_PRIME3__ +-- are substituted by vm/runtime.lua from the same constants +-- vm/encrypt_operands.lua uses, so a future change to those constants only +-- has to happen in one place. +-- +-- Some operands are negative (CALL/TAILCALL's -1/0/1 result-mode +-- flag); bxor32/mix work purely in [0, 2^32) bit patterns, so a +-- decrypted operand must be folded back from that unsigned range to +-- the signed value the rest of the interpreter compares against. +return [==[ +local __hBxor32, __hRotl32, __hMix, __hKeystream, __hToSigned32 +do + local hFloor = math.floor + local hMASK, hP1, hP2, hP3 = __CIPHER_MASK__, __CIPHER_PRIME1__, __CIPHER_PRIME2__, __CIPHER_PRIME3__ + function __hBxor32(a, b) + a, b = a % hMASK, b % hMASK + local result, bit = 0, 1 + while a > 0 or b > 0 do + local abit, bbit = a % 2, b % 2 + if abit ~= bbit then result = result + bit end + a, b = (a - abit) / 2, (b - bbit) / 2 + bit = bit * 2 + end + return result + end + function __hRotl32(x, r) + x = x % hMASK + local hi = hFloor(x / 2 ^ (32 - r)) + local lo = (x * 2 ^ r) % hMASK + return (lo + hi) % hMASK + end + function __hMix(h, value) + value = value % hMASK + h = __hBxor32(h, value) + h = (h * hP1) % hMASK + h = __hBxor32(h, hFloor(h / 65536)) + h = (h * hP2) % hMASK + h = __hBxor32(h, hFloor(h / 32771)) + h = (h + hP3) % hMASK + return __hRotl32(h, 13) + end + function __hKeystream(h) + local k = __hBxor32(h, hFloor(h / 15)) + k = (k * hP2) % hMASK + return __hBxor32(k, hFloor(k / 13)) + end + function __hToSigned32(value) + value = value % hMASK + if value >= hMASK / 2 then + return value - hMASK + end + return value + end +end +]==] diff --git a/src/prometheus/vm/runtime_decrypt.lua b/src/prometheus/vm/runtime_decrypt.lua new file mode 100644 index 00000000..2b35d95b --- /dev/null +++ b/src/prometheus/vm/runtime_decrypt.lua @@ -0,0 +1,80 @@ +-- Builds the Lua source for decrypting VM instruction operands at runtime, +-- in lockstep with vm/encrypt_operands.lua's compile-time pass. For every +-- opcode, decrypts exactly the operand slots that opcode's entry in +-- operand_signature.lua marks numeric ('N'), each against the keystream +-- derived from the running per-prototype hash state h, then folds that same +-- (now-decrypted) plaintext value into h so it becomes part of the key for +-- the next numeric operand anywhere in the stream -- across instructions, +-- across jumps, across loop iterations. There is no per-PC key table: h +-- only ever exists as a transient local in the interpreter loop, rebuilt +-- from the prototype's seed at the start of every call and advanced solely +-- by the chain of values actually decrypted along the path execution took. +-- +-- Operand slots not marked 'N' (table-valued operands such as ARGS' and +-- CALLn/TAILCALLn's register lists, and CLEARS' register list) are left +-- exactly as fetched: there is nothing to decrypt and nothing to fold in, +-- so they neither consume nor advance the keystream. +local opcodes = require('prometheus.vm.opcodes') +local signature = require('prometheus.vm.operand_signature') + +local M = {} + +local slotName = {[1] = 'a', [2] = 'b', [3] = 'c', [4] = 'd'} + +function M.build(layoutOpcodes) + local entries = {} + for name, id in pairs(layoutOpcodes) do + entries[#entries + 1] = {name = name, id = id} + end + table.sort(entries, function(left, right) return left.id < right.id end) + + local function body(name) + local shape = assert(signature[name], + 'EncryptOperands: no operand signature for opcode ' .. tostring(name)) + local lines = {} + for position = 1, #shape do + if shape[position] == 'N' then + local var = slotName[position] + -- XOR recovers the operand's unsigned 32-bit bit pattern; + -- fold that (not yet sign-corrected) value into h, since + -- that is exactly what encryption folded in on the other + -- side, then convert to the signed value the dispatch + -- bodies actually compare and index with (e.g. CALL's + -- -1/0/1 result-mode flag). + lines[#lines + 1] = var .. ' = __hBxor32(' .. var .. ', __hKeystream(__vmOperandHash))' + lines[#lines + 1] = '__vmOperandHash = __hMix(__vmOperandHash, ' .. var .. ')' + lines[#lines + 1] = var .. ' = __hToSigned32(' .. var .. ')' + end + end + if #lines == 0 then return nil end + return table.concat(lines, '\n') + end + + local function indent(source, prefix) + return prefix .. source:gsub('\n', '\n' .. prefix) + end + + local function emit(first, last, depth) + local prefix = string.rep(' ', depth) + if first == last then + local entry = entries[first] + local decrypt = body(entry.name) + if not decrypt then return prefix .. '-- opcode ' .. tostring(entry.id) .. ' has no numeric operands' end + return prefix .. 'if opcode == ' .. tostring(entry.id) .. ' then\n' + .. indent(decrypt, prefix .. ' ') .. '\n' + .. prefix .. 'end' + end + local middle = math.floor((first + last) / 2) + local split = entries[middle].id + return prefix .. 'if opcode <= ' .. tostring(split) .. ' then\n' + .. emit(first, middle, depth + 1) .. '\n' + .. prefix .. 'else\n' + .. emit(middle + 1, last, depth + 1) .. '\n' + .. prefix .. 'end' + end + + assert(#entries > 0, 'No VM opcodes registered') + return emit(1, #entries, 0) +end + +return M