Skip to content

Commit 0d3e287

Browse files
authored
Merge pull request #252 from prometheus-lua/vm-data-and-shared-strings
Make VM data and generated helpers harder to identify
2 parents c988b7c + a37af3b commit 0d3e287

15 files changed

Lines changed: 534 additions & 94 deletions

File tree

‎doc/advanced/register-vm.md‎

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,28 +16,38 @@ compiler, or `loadstring` to execute the original source.
1616
- `vm/optimize.lua`: recursive, conservative basic-block optimizations and
1717
cleanup batching before emission.
1818
- `vm/opcodes.lua`: semantic instruction IDs.
19-
- `vm/layout.lua`: a per-emission opcode and operand layout.
19+
- `vm/layout.lua`: per-emission opcode, operand, and numeric metadata keys.
2020
- `vm/runtime.lua` and `vm/runtime_dispatch.lua`: runtime templates and the
2121
generated dispatcher, configured for the selected opcode IDs and operand
2222
positions.
2323
- `vm/runtime_calls.lua`: fixed-arity and packed call, return, and register
2424
cleanup handlers used by the generated runtime.
25-
- `vm/emit.lua`: instruction encoding, native prototype table literals, and the
26-
runtime function IIFE.
25+
- `vm/data.lua`: scattered table graph encoding and startup reconstruction.
26+
- `vm/emit.lua`: shard literals, the reconstruction helper, and the runtime
27+
function IIFE.
2728
- `vm/strings.lua`: optional hoisting of generated interpreter string literals
2829
into an outer initializer.
2930
- `vm/flatten.lua`: the Cff integration for generated VM interpreters.
3031

3132
A prototype contains instructions, constants, child prototypes, parameter
32-
metadata, and capture descriptors. The emitter passes the native prototype
33-
tables as an argument to a runtime function IIFE. The generated interpreter
34-
then uses that table data; the prototypes are not encoded as strings.
33+
metadata, and capture descriptors. Prototype fields use unique randomized
34+
numeric keys instead of fixed string keys. The emitter scatters assignments
35+
for the complete table graph across three to five native shard tables,
36+
including individual instruction operands and constant entries. Table IDs and
37+
record order are shuffled. A startup helper allocates all destination tables,
38+
resolves references, and passes the reconstructed root to the runtime function
39+
IIFE. It releases the consumed shards. Reconstruction happens once per chunk
40+
execution; the interpreter uses ordinary direct table lookups afterward.
41+
Scattering increases output size and startup work without adding shard lookups
42+
to the VM loop. The prototypes are not encoded as strings.
3543

3644
Each invocation owns its register table; vararg functions also carry a counted
3745
vararg tuple. Closures retain only
3846
their referenced upvalue cells; leaving a scope detaches its cells without
39-
destroying values shared by live closures. Value lists carry an explicit `n`
40-
so trailing nils survive calls, varargs, table constructors, and returns.
47+
destroying values shared by live closures. Value lists carry an explicit count
48+
under a per-emission negative numeric key, keeping it separate from positive
49+
array indices so trailing nils survive calls, varargs, table constructors, and
50+
returns.
4151
The compiler keeps ordinary scalar values in individual registers. Small calls
4252
and returns pass those registers directly to native Lua instead of first making
4353
a value-list table. Temporary registers are cleared after consumption, and
@@ -66,22 +76,24 @@ initialization path, which also builds the vararg tuple when needed.
6676
`Cff` normally flattens control flow throughout its input AST. When it receives
6777
the AST emitted by `Vmify`, a private `vmRuntime` annotation selects a special
6878
path: by default, `vm/flatten.lua` flattens the interpreter function only. The
69-
large native prototype table initialization remains outside the flattened
70-
function, keeping it out of the Cff control structure and jump limits used by
71-
Lua and LuaJIT.
79+
large native shard initialization and startup reconstruction remain outside
80+
the flattened function, keeping them out of the Cff control structure and jump
81+
limits used by Lua and LuaJIT.
7282

7383
Set `Cff`'s `ExcludeVm` setting to `true` to leave both the generated
74-
interpreter and the native prototype table literal out of flattening. Cff then
75-
flattens the surrounding code, including helpers introduced by intervening
76-
steps such as string decoders or tamper checks. The interpreter remains native
77-
Lua, so its lexical captures continue to share variables with surrounding
84+
interpreter and the native shard literal out of flattening. Cff then flattens
85+
the startup reconstruction helper and its call along with surrounding code,
86+
including helpers introduced by intervening steps such as string decoders or
87+
tamper checks. The interpreter remains native Lua, so its lexical captures
88+
continue to share variables with surrounding
7889
closures according to ordinary Lua upvalue semantics.
7990

8091
`cff/native.lua` emits the excluded expressions directly and bridges their
8192
external locals through Cff's shared upvalue cells. Garbage-collected capture
8293
proxies keep those cells alive for native closures; captures are not value
83-
snapshots. The `vmData` annotation identifies the entire prototype initializer,
84-
including its child prototypes.
94+
snapshots. The `vmData` annotation identifies only the shard literal containing
95+
the complete prototype graph. It does not exclude the reconstruction helper
96+
or its invocation from Cff.
8597

8698
With the default `ExcludeVm = false` behavior, the special path passes
8799
read-only external lexical helpers through function arguments. This supports
@@ -94,8 +106,9 @@ arity and cleanup instructions use the same ID scheme. At emission,
94106
`layout.lua` chooses a permutation of the opcode IDs and a permutation of
95107
operand slots 2 through 5; slot 1 always contains the opcode. The emitter
96108
encodes each instruction with that layout without changing the compiler
97-
prototypes. One layout is shared by the root prototype and all child
98-
prototypes in the emitted chunk.
109+
prototypes. The layout also selects numeric prototype field keys and the
110+
packed-value count key. One layout is shared by the root prototype and all
111+
child prototypes in the emitted chunk.
99112

100113
Before emission, `optimize.lua` visits the root prototype and its children and
101114
applies conservative basic-block-local rewrites. At emission,
@@ -111,15 +124,17 @@ the generated interpreter's literal strings into an outer initializer, where
111124
normal string encryption and later `ConstantArray` processing apply. The
112125
initializer decodes them once at startup and binds them to native lexical
113126
locals used by the interpreter, avoiding decoder or wrapper calls on hot
114-
paths. Strings in `vmData` prototype tables remain encrypted by the normal
127+
paths. Strings in the `vmData` shards remain encrypted by the normal
115128
`EncryptStrings` behavior. `vm/strings.lua` implements this transformation.
116129

117130
Medium then applies `AntiTamper`, `ConstantArray`, and `WrapInFunction`,
118-
followed by `Cff` with `ExcludeVm = true`. The interpreter and prototype table
119-
initializers stay native while Cff flattens the surrounding code and generated
120-
helpers. `NumbersToExpressions` runs after Cff: it adds no helper functions,
121-
and this ordering prevents Cff from virtualizing arithmetic constant
122-
expressions.
131+
followed by `Cff` with `ExcludeVm = true`. The interpreter and shard literal
132+
stay native while Cff protects startup reconstruction, surrounding code, and
133+
generated helpers. After generating its helpers, Cff puts repeated string
134+
literals in a shared outer table, including any new diagnostics and counted-value
135+
keys. Each value is embedded only once in Medium output. `NumbersToExpressions`
136+
runs after Cff: it adds no helper functions, and this ordering prevents Cff
137+
from virtualizing arithmetic constant expressions.
123138

124139
`Strong` applies one `Vmify` pass followed by `EncryptStrings`, `AntiTamper`,
125140
and one default `Cff` pass over the generated VM interpreter. It retains the

‎doc/reference/steps/cff.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,15 @@ When `Cff` receives `Vmify` output, it recognizes the private VM runtime annotat
88

99
Set `ExcludeVm` to `true` to leave the generated interpreter and native prototype table literal out of Cff flattening. Cff then flattens the surrounding code, including helpers such as decoders and tamper checks, and the outer string initializer emitted by `EncryptStrings` when `HoistVmStrings` is enabled. The interpreter keeps its native Lua lexical captures, preserving shared variable behavior between the interpreter and surrounding closures.
1010

11+
After generating its runtime and helpers, Cff shares repeated string literals
12+
through one outer table with shuffled slots. Each repeated value is embedded
13+
once and reused through indexed references, including diagnostics and counted
14+
argument/result keys introduced by Cff itself. Unique literals stay in place.
15+
This also applies to literals inside preserved native VM expressions; their
16+
control flow stays native. Sharing does not encrypt the remaining literal.
17+
Later steps may introduce new strings. Medium only runs `NumbersToExpressions`
18+
after Cff, so its final output retains one literal per distinct string value.
19+
1120
## Settings
1221

1322
| Setting | Type | Default | Description |

‎doc/reference/steps/vmify.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@ slot 1 always stores the opcode. The same layout applies to the root function
1010
and its child prototypes. For the same input, configuration, and Lua runtime,
1111
a fixed pipeline seed reproduces the layout.
1212

13+
Prototype fields and packed-value counts use per-emission numeric keys;
14+
Vmify introduces no fixed string keys for these internal tables. The complete
15+
prototype graph, including instructions and constants, is scattered across
16+
three to five tables with shuffled records and table IDs. A generated helper
17+
reconstructs ordinary tables once at chunk startup and releases the shards,
18+
leaving direct lookups during VM execution. This adds output size and startup
19+
work. In Medium, Cff protects the reconstruction helper and its invocation;
20+
only the interpreter and large shard literal remain excluded from flattening.
21+
Source-program strings and keys retain their normal semantics.
22+
1323
## Settings
1424

1525
None.

‎src/prometheus/cff/strings.lua‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
-- Share repeated literals after Cff has introduced its own helper strings.
2+
local Ast = require('prometheus.ast')
3+
local visitast = require('prometheus.visitast')
4+
local shuffle = require('prometheus.util').shuffle
5+
local Kind = Ast.AstKind
6+
7+
return function(ast)
8+
local counts, strings = {}, {}
9+
visitast(ast, function(node)
10+
if node.kind == Kind.StringExpression then
11+
local value = node.value
12+
counts[value] = (counts[value] or 0) + 1
13+
if counts[value] == 2 then strings[#strings + 1] = value end
14+
end
15+
end)
16+
if #strings == 0 then return ast end
17+
18+
shuffle(strings)
19+
local scope = ast.body.scope
20+
local pool = scope:addVariable()
21+
local indices, entries = {}, {}
22+
for i, value in ipairs(strings) do
23+
indices[value] = i
24+
entries[i] = Ast.TableEntry(Ast.StringExpression(value))
25+
end
26+
-- Track blocks explicitly: strings after a nested function literal still
27+
-- belong to the enclosing block, regardless of the visitor's last scope.
28+
local scopes = {}
29+
visitast(ast, function(node)
30+
if node.kind == Kind.Block then scopes[#scopes + 1] = node.scope end
31+
end, function(node)
32+
if node.kind == Kind.Block then
33+
scopes[#scopes] = nil
34+
elseif node.kind == Kind.StringExpression then
35+
local index = indices[node.value]
36+
if index then
37+
scopes[#scopes]:addReferenceToHigherScope(scope, pool)
38+
return Ast.IndexExpression(Ast.VariableExpression(scope, pool), Ast.NumberExpression(index))
39+
end
40+
end
41+
end)
42+
-- Insert only after replacement so each pooled value remains embedded once.
43+
table.insert(ast.body.statements, 1,
44+
Ast.LocalVariableDeclaration(scope, {pool}, {Ast.TableConstructorExpression(entries)}))
45+
return ast
46+
end

‎src/prometheus/steps/Cff.lua‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
local Step = require("prometheus.step");
88
local Compiler = require("prometheus.cff.compiler");
99
local flattenVm = require("prometheus.vm.flatten");
10+
local shareStrings = require("prometheus.cff.strings");
1011

1112
local Cff = Step:extend();
1213
Cff.Description = "Flattens control flow into Lua statements executed by a randomized block dispatcher.";
@@ -26,15 +27,15 @@ function Cff:apply(ast)
2627
local flattened = compiler:compile(ast);
2728
flattened.vmRuntime = compiler.nativeResults[ast.vmRuntime];
2829
flattened.vmData = compiler.nativeResults[ast.vmData];
29-
return flattened;
30+
return shareStrings(flattened);
3031
end
3132
if ast.vmRuntime then
3233
local flattened = flattenVm(ast);
33-
if flattened then return flattened; end
34+
if flattened then return shareStrings(flattened); end
3435
end
3536
local compiler = Compiler:new();
3637

37-
return compiler:compile(ast);
38+
return shareStrings(compiler:compile(ast));
3839
end
3940

4041
return Cff;

‎src/prometheus/vm/data.lua‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
-- Scatter the emitted table graph; rebuild ordinary tables once before VM startup.
2+
local Ast = require('prometheus.ast')
3+
local Unparser = require('prometheus.unparser')
4+
local Enums = require('prometheus.enums')
5+
local shuffle = require('prometheus.util').shuffle
6+
local Data = {}
7+
8+
Data.rebuild = [=[
9+
local function rebuild(shards, count, root)
10+
local tables = {}
11+
for i = 1, count do tables[i] = {} end
12+
for i = 1, #shards do
13+
local shard = shards[i]
14+
for j = 1, #shard do
15+
local record = shard[j]
16+
local value = record[3]
17+
if record[4] then value = tables[value] end
18+
tables[record[1]][record[2]] = value
19+
end
20+
shards[i] = nil
21+
end
22+
return tables[root]
23+
end
24+
]=]
25+
26+
function Data.encode(proto, layout)
27+
local function prototype(value)
28+
local result, code, children = {}, {}, {}
29+
for i, instruction in ipairs(value.code) do
30+
code[i] = layout:encode(instruction)
31+
end
32+
for i, child in ipairs(value.children) do children[i] = prototype(child) end
33+
result[layout.fields.code] = code
34+
result[layout.fields.children] = children
35+
for _, name in ipairs({'constants', 'captures', 'params', 'vararg', 'maxRegister'}) do
36+
result[layout.fields[name]] = value[name]
37+
end
38+
return result
39+
end
40+
local root = {prototype(proto)}
41+
local tables, indices, keys = {}, {}, {}
42+
local function collect(value)
43+
if indices[value] then return end
44+
tables[#tables + 1] = value
45+
indices[value] = #tables
46+
local sorted = {}
47+
for key in pairs(value) do sorted[#sorted + 1] = key end
48+
table.sort(sorted)
49+
keys[value] = sorted
50+
for _, key in ipairs(sorted) do
51+
if type(value[key]) == 'table' then collect(value[key]) end
52+
end
53+
end
54+
collect(root)
55+
local ids = {}
56+
for i = 1, #tables do ids[i] = i end
57+
shuffle(ids)
58+
local unparser = Unparser:new({LuaVersion = Enums.LuaVersion.Lua51})
59+
local records = {}
60+
for i, value in ipairs(tables) do
61+
for _, key in ipairs(keys[value]) do
62+
local entry, reference = value[key], ''
63+
if type(entry) == 'table' then
64+
entry, reference = ids[indices[entry]], ',1'
65+
end
66+
local literal = unparser:unparseExpression(Ast.ConstantNode(entry), 0)
67+
records[#records + 1] = '{' .. ids[i] .. ',' .. key .. ',' .. literal .. reference .. '}'
68+
end
69+
end
70+
shuffle(records)
71+
local shards = {}
72+
local count = math.random(3, 5)
73+
for i = 1, count do shards[i] = {} end
74+
for i, record in ipairs(records) do
75+
local shard = shards[(i - 1) % count + 1]
76+
shard[#shard + 1] = record
77+
end
78+
for i, shard in ipairs(shards) do shards[i] = '{' .. table.concat(shard, ',') .. '}' end
79+
return '{' .. table.concat(shards, ',') .. '}', #tables, ids[indices[root]]
80+
end
81+
82+
return Data

‎src/prometheus/vm/emit.lua‎

Lines changed: 10 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,26 @@
1-
-- Emit native table data and a generated interpreter, then parse the complete AST.
2-
local Ast = require('prometheus.ast')
1+
-- Emit scattered data, startup reconstruction, and a generated interpreter.
32
local Parser = require('prometheus.parser')
4-
local Unparser = require('prometheus.unparser')
53
local Enums = require('prometheus.enums')
64
local Runtime = require('prometheus.vm.runtime')
75
local Layout = require('prometheus.vm.layout')
6+
local Data = require('prometheus.vm.data')
87
local Emit = {}
98

109
function Emit.source(proto, layout)
1110
layout = layout or Layout.new()
12-
local unparser = Unparser:new({LuaVersion = Enums.LuaVersion.Lua51})
13-
local function literal(value)
14-
if type(value) ~= 'table' then
15-
return unparser:unparseExpression(Ast.ConstantNode(value), 0)
16-
end
17-
local parts = {}
18-
for _, entry in ipairs(value) do parts[#parts + 1] = literal(entry) end
19-
return '{' .. table.concat(parts, ',') .. '}'
20-
end
21-
local function prototype(value)
22-
local instructions = {}
23-
for _, instruction in ipairs(value.code) do
24-
local encoded, length = layout:encode(instruction)
25-
local operands = {}
26-
for slot = 1, length do operands[slot] = literal(encoded[slot]) end
27-
instructions[#instructions + 1] = '{' .. table.concat(operands, ',') .. '}'
28-
end
29-
local parts = {'code={' .. table.concat(instructions, ',') .. '}'}
30-
for _, key in ipairs({'constants', 'captures', 'params', 'vararg', 'maxRegister'}) do
31-
parts[#parts + 1] = key .. '=' .. literal(value[key])
32-
end
33-
local children = {}
34-
for _, child in ipairs(value.children) do children[#children + 1] = prototype(child) end
35-
parts[#parts + 1] = 'children={' .. table.concat(children, ',') .. '}'
36-
return '{' .. table.concat(parts, ',') .. '}'
37-
end
38-
local data = '{' .. prototype(proto) .. '}'
39-
local source, count = Runtime.build(layout):gsub('__PROTOTYPES__', function() return data end)
11+
local data, tables, root = Data.encode(proto, layout)
12+
local initializer = 'rebuild(' .. data .. ',' .. tables .. ',' .. root .. ')'
13+
local source, count = Runtime.build(layout):gsub('__PROTOTYPES__', function() return initializer end)
4014
assert(count == 1, 'Runtime template must contain one prototype marker')
41-
return source
15+
return Data.rebuild .. source
4216
end
4317

4418
function Emit.ast(proto)
4519
local ast = Parser:new({LuaVersion = Enums.LuaVersion.Lua51}):parse(Emit.source(proto))
46-
ast.vmRuntime = ast.body.statements[1].args[1].base
47-
ast.vmData = ast.body.statements[1].args[1].args[1]
20+
local invocation = ast.body.statements[#ast.body.statements].args[1]
21+
ast.vmRuntime = invocation.base
22+
-- Only the large shard literal stays native. Cff protects the reconstruction call/helper.
23+
ast.vmData = invocation.args[1].args[1]
4824
return ast
4925
end
5026

‎src/prometheus/vm/layout.lua‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
-- Choose one instruction encoding for each generated VM. Compiler IR stays semantic.
1+
-- Choose instruction encoding and metadata keys per VM. Compiler IR stays semantic.
22
local opcodes = require('prometheus.vm.opcodes')
33
local shuffle = require('prometheus.util').shuffle
4+
local fields = {'code', 'constants', 'captures', 'params', 'vararg', 'maxRegister', 'children'}
45
local Layout = {}
56
Layout.__index = Layout
67

@@ -18,6 +19,16 @@ function Layout.new()
1819
layout.opcodes[entry.name] = ids[i]
1920
layout.ids[entry.id] = ids[i]
2021
end
22+
layout.fields = {}
23+
local used = {}
24+
for _, name in ipairs(fields) do
25+
local key
26+
repeat key = math.random(1024, 16777215) until not used[key]
27+
used[key] = true
28+
layout.fields[name] = key
29+
end
30+
-- Counted tuples also contain positive array indices, so keep metadata negative.
31+
layout.countKey = -math.random(1024, 16777215)
2132
return layout
2233
end
2334

0 commit comments

Comments
 (0)