js-confuser-vm 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +242 -89
  2. package/dist/compiler.js +583 -208
  3. package/dist/disassembler.js +58 -8
  4. package/dist/runtime.js +93 -74
  5. package/dist/template.js +81 -76
  6. package/dist/transforms/bytecode/concealConstants.js +2 -2
  7. package/dist/transforms/bytecode/controlFlowFlattening.js +143 -25
  8. package/dist/transforms/bytecode/dispatcher.js +3 -3
  9. package/dist/transforms/bytecode/resolveRegisters.js +19 -4
  10. package/dist/transforms/bytecode/selfModifying.js +88 -21
  11. package/dist/transforms/bytecode/specializedOpcodes.js +6 -3
  12. package/dist/transforms/bytecode/stringConcealing.js +253 -75
  13. package/dist/utils/ast-utils.js +61 -0
  14. package/dist/utils/op-utils.js +1 -0
  15. package/package.json +7 -1
  16. package/.gitmodules +0 -4
  17. package/.prettierignore +0 -1
  18. package/CHANGELOG.md +0 -358
  19. package/babel-plugin-inline-runtime.cjs +0 -34
  20. package/babel.config.json +0 -23
  21. package/bench.ts +0 -146
  22. package/disassemble.ts +0 -12
  23. package/index.ts +0 -43
  24. package/jest-strip-types.js +0 -10
  25. package/jest.config.js +0 -64
  26. package/output.disassembled.js +0 -41
  27. package/src/build-runtime.ts +0 -113
  28. package/src/compiler.ts +0 -2703
  29. package/src/disassembler.ts +0 -329
  30. package/src/index.ts +0 -24
  31. package/src/minify.ts +0 -21
  32. package/src/options.ts +0 -24
  33. package/src/runtime.ts +0 -956
  34. package/src/template.ts +0 -265
  35. package/src/transforms/bytecode/aliasedOpcodes.ts +0 -151
  36. package/src/transforms/bytecode/concealConstants.ts +0 -52
  37. package/src/transforms/bytecode/controlFlowFlattening.ts +0 -566
  38. package/src/transforms/bytecode/dispatcher.ts +0 -292
  39. package/src/transforms/bytecode/macroOpcodes.ts +0 -193
  40. package/src/transforms/bytecode/resolveConstants.ts +0 -126
  41. package/src/transforms/bytecode/resolveLabels.ts +0 -112
  42. package/src/transforms/bytecode/resolveRegisters.ts +0 -226
  43. package/src/transforms/bytecode/selfModifying.ts +0 -121
  44. package/src/transforms/bytecode/specializedOpcodes.ts +0 -164
  45. package/src/transforms/bytecode/stringConcealing.ts +0 -130
  46. package/src/transforms/runtime/aliasedOpcodes.ts +0 -191
  47. package/src/transforms/runtime/classObfuscation.ts +0 -59
  48. package/src/transforms/runtime/macroOpcodes.ts +0 -138
  49. package/src/transforms/runtime/minify.ts +0 -1
  50. package/src/transforms/runtime/shuffleOpcodes.ts +0 -24
  51. package/src/transforms/runtime/specializedOpcodes.ts +0 -161
  52. package/src/types.ts +0 -134
  53. package/src/utils/ast-utils.ts +0 -19
  54. package/src/utils/op-utils.ts +0 -46
  55. package/src/utils/pass-utils.ts +0 -126
  56. package/src/utils/profile-utils.ts +0 -3
  57. package/src/utils/random-utils.ts +0 -31
  58. package/tsconfig.json +0 -12
package/src/template.ts DELETED
@@ -1,265 +0,0 @@
1
- // Template
2
- // Compiles a JS code snippet into raw IR bytecode that can be spliced into the
3
- // parent compiler's bytecode stream at any point before resolveRegisters /
4
- // resolveLabels run.
5
- //
6
- // ── Usage ─────────────────────────────────────────────────────────────────────
7
- //
8
- // const tmpl = new Template(`
9
- // function {name}(x, y) {
10
- // return x + y;
11
- // }
12
- // `);
13
- //
14
- // const bc = tmpl.compile({ name: "myHelper" }, parentCompiler);
15
- // result.push(...bc);
16
- //
17
- // ── How it works ──────────────────────────────────────────────────────────────
18
- //
19
- // 1. {name} placeholders are replaced with the caller-supplied string values.
20
- // 2. A fresh child Compiler is created, inheriting the parent's OP table so
21
- // opcode numbers match exactly (including randomizeOpcodes mappings).
22
- // 3. The child compiles the snippet to raw IR (no passes, no label/register
23
- // resolution).
24
- // 4. Post-processing makes the child's bytecode compatible with the parent:
25
- //
26
- // Labels — every label string is renamed via parentCompiler._makeLabel()
27
- // so names never collide with existing or future labels.
28
- //
29
- // FnIds — the child's main scope (fnDescriptors[0]) is mapped to
30
- // targetFnId (default 0). Any inner functions (closures
31
- // declared inside the template) are appended to
32
- // parentCompiler.fnDescriptors with fresh indices.
33
- //
34
- // 5. The main function's entry defineLabel is stripped from the output — it is
35
- // a synthetic wrapper added by _compileMain and is not part of the injected
36
- // code. All other instructions (including the implicit RETURN at the end of
37
- // the main scope and any inner-function blocks) are returned as-is so the
38
- // caller can append them wherever appropriate.
39
- //
40
- // ── Limitations (MVP) ─────────────────────────────────────────────────────────
41
- // • Variables are plain string/number interpolation only — no AST-node
42
- // substitution.
43
- // • Templates that reference upvalue-captured registers from the call site are
44
- // not supported (inner functions closing over template-local variables work).
45
- // • Opcodes with no JS equivalent (JUMP_REG, BXOR used as decode, etc.) cannot
46
- // be expressed in a template; write those instruction arrays manually.
47
-
48
- import { Compiler } from "./compiler.ts";
49
- import { DEFAULT_OPTIONS } from "./options.ts";
50
- import type { Bytecode, Instruction, RegisterOperand } from "./types.ts";
51
-
52
- export class Template {
53
- private readonly _source: string;
54
-
55
- constructor(source: string) {
56
- this._source = source;
57
- }
58
-
59
- // ── String interpolation ──────────────────────────────────────────────────
60
- private _interpolate(variables: Record<string, string | number>): string {
61
- return this._source.replace(/\{(\w+)\}/g, (match, name) => {
62
- if (!(name in variables)) {
63
- throw new Error(`Template: missing variable {${name}}`);
64
- }
65
- return String(variables[name]);
66
- });
67
- }
68
-
69
- // ── Main entry point ───────────────────────────────────────────────────────
70
- /**
71
- * Compile the template and return the inner (non-main) function descriptors
72
- * and their bytecode blocks, ready to splice into the parent compiler's
73
- * instruction stream.
74
- *
75
- * The template source should declare one or more named functions. The
76
- * top-level ("main") scope of the template is discarded — it exists only as
77
- * a syntactic wrapper so that function declarations parse correctly.
78
- *
79
- * Each inner function is registered in parentCompiler.fnDescriptors with a
80
- * fresh fnIdx, and its bytecode block (defineLabel + body instructions) is
81
- * returned so the caller can append it to the parent bytecode stream at the
82
- * desired location (typically at the end, after all function bodies).
83
- *
84
- * @param variables Substitution map for {name} placeholders.
85
- * @param parentCompiler The Compiler whose OP table, label counter, and
86
- * fnDescriptors are shared.
87
- *
88
- * @returns
89
- * functions — ordered list of inner FnDescriptors (index 0 = first named
90
- * function in the template source). Use .entryLabel and
91
- * ._fnIdx to build MAKE_CLOSURE operands.
92
- * bytecode — IR bytecode blocks for all inner functions, ready to splice
93
- * after the parent's function bodies. Does NOT include the
94
- * template's main-scope instructions.
95
- */
96
- compile(
97
- variables: Record<string, string | number>,
98
- parentCompiler: Compiler,
99
- ): { functions: any[]; bytecode: Bytecode } {
100
- // ── 1. Interpolate ────────────────────────────────────────────────────
101
- const code = this._interpolate(variables);
102
-
103
- // ── 2. Create child compiler, inherit parent's OP table ───────────────
104
- // randomizeOpcodes is disabled — we copy the parent's already-randomized
105
- // mapping directly so all opcode numbers are identical.
106
- const child = new Compiler({ ...DEFAULT_OPTIONS, randomizeOpcodes: false });
107
- child.OP = { ...parentCompiler.OP };
108
- child.OP_NAME = { ...parentCompiler.OP_NAME };
109
- child.JUMP_OPS = new Set(parentCompiler.JUMP_OPS);
110
-
111
- child._makeLabel = parentCompiler._makeLabel.bind(parentCompiler);
112
-
113
- // Record how many descriptors the parent already has so we can find the
114
- // child's main (index = startIdx) and inner functions (startIdx+1 …).
115
- const startIdx = parentCompiler.fnDescriptors.length;
116
- child.fnDescriptors = parentCompiler.fnDescriptors; // share — inner functions auto-register
117
-
118
- // ── 3. Compile to raw IR (no passes) ──────────────────────────────────
119
- child.compile(code);
120
-
121
- // parentCompiler.fnDescriptors[startIdx] → child's main (discard)
122
- // parentCompiler.fnDescriptors[startIdx+1…] → inner helper functions
123
- const innerDescs = parentCompiler.fnDescriptors.slice(startIdx + 1);
124
-
125
- // Build bytecode blocks for inner functions only.
126
- // child.bytecode was assembled by _compileMain from ALL fnDescriptors
127
- // starting at startIdx. We rebuild it here from the inner descs only.
128
- const innerBytecode: Bytecode = [];
129
- for (const desc of innerDescs) {
130
- innerBytecode.push([
131
- null,
132
- { type: "defineLabel", label: desc.entryLabel },
133
- ] as Instruction);
134
- for (const instr of (desc as any).bytecode as Bytecode) {
135
- innerBytecode.push(instr);
136
- }
137
- }
138
-
139
- return { functions: innerDescs, bytecode: innerBytecode };
140
- }
141
-
142
- // ── Inline compilation ───────────────────────────────────────────────────
143
- /**
144
- * Compile the template and return the **main scope** bytecode, with all
145
- * register operands remapped to belong to `targetFnId`. This allows
146
- * bytecode transforms to express high-level JS control flow (while-loops,
147
- * if-chains, variable declarations) via Template and splice the result
148
- * directly into an existing function's instruction stream.
149
- *
150
- * The implicit trailing RETURN added by _compileFunctionDecl is stripped —
151
- * inline code should flow into the surrounding bytecode, not return.
152
- *
153
- * @param variables Substitution map for {name} placeholders.
154
- * @param parentCompiler The Compiler whose OP table, label counter, and
155
- * fnDescriptors are shared.
156
- * @param targetFnId The function whose register file the template's
157
- * registers should be remapped into.
158
- * @param maxId Live map of max register id per fnId — updated
159
- * in-place as new registers are allocated.
160
- *
161
- * @returns
162
- * bytecode — main-scope IR (no entry defineLabel, no trailing RETURN),
163
- * ready to splice into the target function's instruction stream.
164
- * registers — mapping of JS variable names → remapped RegisterOperands,
165
- * so the caller can reference template-declared variables
166
- * (e.g. the `state` variable in CFF).
167
- * functions — inner function descriptors (same as compile()).
168
- * innerBytecode — inner function bytecode blocks (same as compile()).
169
- */
170
- compileInline(
171
- variables: Record<string, string | number>,
172
- parentCompiler: Compiler,
173
- targetFnId: number,
174
- maxId: Map<number, number>,
175
- ): {
176
- bytecode: Bytecode;
177
- registers: Map<string, RegisterOperand>;
178
- functions: any[];
179
- innerBytecode: Bytecode;
180
- } {
181
- const code = this._interpolate(variables);
182
-
183
- const child = new Compiler({ ...DEFAULT_OPTIONS, randomizeOpcodes: false });
184
- child.OP = { ...parentCompiler.OP };
185
- child.OP_NAME = { ...parentCompiler.OP_NAME };
186
- child.JUMP_OPS = new Set(parentCompiler.JUMP_OPS);
187
- child._makeLabel = parentCompiler._makeLabel.bind(parentCompiler);
188
-
189
- const startIdx = parentCompiler.fnDescriptors.length;
190
- child.fnDescriptors = parentCompiler.fnDescriptors;
191
-
192
- child.compile(code);
193
-
194
- const mainDesc = parentCompiler.fnDescriptors[startIdx] as any;
195
- const mainFnId: number = mainDesc._fnIdx;
196
- const mainBc = mainDesc.bytecode as Bytecode;
197
-
198
- // ── Remap registers from the template's main fnId → targetFnId ────────
199
- // Build a mapping: old register id → new RegisterOperand in targetFnId.
200
- const regRemap = new Map<number, RegisterOperand>();
201
- const remapReg = (id: number): RegisterOperand => {
202
- if (!regRemap.has(id)) {
203
- const next = (maxId.get(targetFnId) ?? -1) + 1;
204
- maxId.set(targetFnId, next);
205
- regRemap.set(id, { type: "register", id: next, fnId: targetFnId });
206
- }
207
- return regRemap.get(id)!;
208
- };
209
-
210
- for (const instr of mainBc) {
211
- for (let j = 1; j < instr.length; j++) {
212
- const op = instr[j] as any;
213
- if (op && typeof op === "object" && op.type === "register" && op.fnId === mainFnId) {
214
- const mapped = remapReg(op.id);
215
- op.id = mapped.id;
216
- op.fnId = mapped.fnId;
217
- }
218
- }
219
- }
220
-
221
- // ── Build variable name → remapped register mapping ───────────────────
222
- const registers = new Map<string, RegisterOperand>();
223
- const locals: Map<string, RegisterOperand> = mainDesc.ctx.scope._locals;
224
- for (const [name, reg] of locals) {
225
- const mapped = regRemap.get(reg.id);
226
- if (mapped) registers.set(name, mapped);
227
- }
228
-
229
- // ── Strip entry defineLabel and trailing implicit RETURN ───────────────
230
- let bytecode = mainBc.filter((instr) => {
231
- const op0 = instr[1] as any;
232
- return !(
233
- instr[0] === null &&
234
- op0?.type === "defineLabel" &&
235
- op0.label === mainDesc.entryLabel
236
- );
237
- });
238
-
239
- // Remove trailing LOAD_CONST undefined + RETURN (implicit return added
240
- // by _compileFunctionDecl).
241
- const OP = parentCompiler.OP;
242
- if (
243
- bytecode.length >= 2 &&
244
- bytecode[bytecode.length - 1][0] === OP.RETURN &&
245
- bytecode[bytecode.length - 2][0] === OP.LOAD_CONST
246
- ) {
247
- bytecode = bytecode.slice(0, -2);
248
- }
249
-
250
- // ── Inner function bytecode (same as compile()) ───────────────────────
251
- const innerDescs = parentCompiler.fnDescriptors.slice(startIdx + 1);
252
- const innerBytecode: Bytecode = [];
253
- for (const desc of innerDescs) {
254
- innerBytecode.push([
255
- null,
256
- { type: "defineLabel", label: desc.entryLabel },
257
- ] as Instruction);
258
- for (const instr of (desc as any).bytecode as Bytecode) {
259
- innerBytecode.push(instr);
260
- }
261
- }
262
-
263
- return { bytecode, registers, functions: innerDescs, innerBytecode };
264
- }
265
- }
@@ -1,151 +0,0 @@
1
- import type { Bytecode, InstrOperand, Instruction } from "../../types.ts";
2
- import { Compiler, OP_ORIGINAL, SOURCE_NODE_SYM } from "../../compiler.ts";
3
- import { nextFreeSlot } from "../../utils/op-utils.ts";
4
- import { shuffle } from "../../utils/random-utils.ts";
5
-
6
- // Opcodes that must not be aliased.
7
- // Variable-length operand opcodes cannot be statically aliased since the
8
- // number of this._operand() calls varies at runtime.
9
- // Infrastructure opcodes (PATCH, TRY_SETUP, TRY_END, DEBUGGER) are excluded
10
- // because aliasing them would interfere with self-modifying bytecode and
11
- // exception-handling machinery.
12
- const DISALLOWED_OP_NAMES = new Set([
13
- "MAKE_CLOSURE",
14
- "BUILD_ARRAY",
15
- "BUILD_OBJECT",
16
- "CALL",
17
- "CALL_METHOD",
18
- "NEW",
19
- "PATCH",
20
- "TRY_SETUP",
21
- "TRY_END",
22
- "DEBUGGER",
23
- ]);
24
-
25
- // Creates aliased opcodes: duplicate handlers for commonly-used opcodes,
26
- // optionally with a permuted operand read order in the bytecode stream.
27
- //
28
- // For each aliased op, we record an `order` permutation of length `arity`.
29
- // order[i] = j means: bytecode slot i holds what was originally operand j.
30
- //
31
- // Example: LOAD_GLOBAL [dst, nameIdx] with order=[1,0]:
32
- // Bytecode stores: [ALIAS_OP, nameIdx, dst]
33
- // Handler reads: _unsortedOperands = [nameIdx, dst]
34
- // _operands = [_unsortedOperands[1], _unsortedOperands[0]]
35
- // = [dst, nameIdx] ← original order restored
36
- //
37
- // Runs LAST among bytecode transforms (after selfModifying), before resolveLabels.
38
- export function aliasedOpcodes(
39
- bc: Bytecode,
40
- compiler: Compiler,
41
- ): { bytecode: Bytecode } {
42
- // Build a map of base opcode value → name, excluding disallowed ops
43
- const baseOpValueToName = new Map<number, string>();
44
- for (const [name, val] of Object.entries(compiler.OP)) {
45
- if (DISALLOWED_OP_NAMES.has(name)) continue;
46
- baseOpValueToName.set(val as number, name);
47
- }
48
-
49
- // ── Step 1: count frequency and determine arity for each eligible base opcode ─
50
- // We scan the actual post-transform bytecode so frequency reflects what's
51
- // really left (specialized/macro ops already consumed their share).
52
- const opStats = new Map<number, { freq: number; arity: number | null }>();
53
-
54
- for (const instr of bc) {
55
- const op = instr[0];
56
- if (op === null || !baseOpValueToName.has(op)) continue;
57
-
58
- const arity = instr.length - 1;
59
- if (arity < 1) continue; // 0-operand opcodes have nothing to permute
60
-
61
- const opName = compiler.OP_NAME[op];
62
- if (!OP_ORIGINAL[opName]) continue; // only consider original ops, not already-specialized ones
63
-
64
- const existing = opStats.get(op);
65
- if (!existing) {
66
- opStats.set(op, { freq: 1, arity });
67
- } else {
68
- if (existing.arity !== arity) {
69
- // Inconsistent arity → variable-length; skip
70
- existing.arity = null;
71
- }
72
- existing.freq++;
73
- }
74
- }
75
-
76
- // ── Step 2: sort by frequency descending, keep only consistent-arity ops ────
77
- const candidates = Array.from(opStats.entries())
78
- .filter(([, s]) => s.arity !== null)
79
- .sort(([, a], [, b]) => b.freq - a.freq);
80
-
81
- if (candidates.length === 0) return { bytecode: bc };
82
-
83
- // ── Step 3: assign free slots, build order permutations ─────────────────────
84
- // aliasMap: originalOp → aliasOp (only the winning alias per original op)
85
- const aliasMap = new Map<number, number>();
86
- const aliasedOps: Compiler["ALIASED_OPS"] = {};
87
-
88
- for (const [originalOp, stats] of candidates) {
89
- const aliasOp = nextFreeSlot(compiler);
90
- if (aliasOp === -1) break;
91
-
92
- const arity = stats.arity!;
93
-
94
- // Build a permutation of [0 .. arity-1].
95
- // For arity >= 2: shuffle until we get a non-identity permutation so the
96
- // operand order is actually different (makes the alias more confusing).
97
- // For arity == 1: only one permutation exists ([0]); still useful as a clone.
98
- let order: number[];
99
- if (arity >= 2) {
100
- const identity = Array.from({ length: arity }, (_, i) => i);
101
- let attempts = 0;
102
- do {
103
- order = shuffle([...identity]);
104
- attempts++;
105
- } while (attempts < 20 && order.every((v, i) => v === i));
106
- } else {
107
- order = [0];
108
- }
109
-
110
- aliasMap.set(originalOp, aliasOp);
111
- aliasedOps[aliasOp] = { originalOp, order };
112
-
113
- const originalName = compiler.OP_NAME[originalOp] ?? `OP_${originalOp}`;
114
- compiler.OP_NAME[aliasOp] = `ALIAS_${originalName}_${order.join("_")}`;
115
- }
116
-
117
- compiler.ALIASED_OPS = aliasedOps;
118
-
119
- if (aliasMap.size === 0) return { bytecode: bc };
120
-
121
- // ── Step 4: rewrite bytecode ─────────────────────────────────────────────────
122
- const result: Bytecode = [];
123
-
124
- for (const instr of bc) {
125
- const op = instr[0];
126
- if (op === null || !aliasMap.has(op)) {
127
- result.push(instr);
128
- continue;
129
- }
130
-
131
- const aliasOp = aliasMap.get(op)!;
132
- const { order } = aliasedOps[aliasOp];
133
- const originalOperands = instr.slice(1) as InstrOperand[];
134
-
135
- // Guard: if arity changed (shouldn't happen after the consistency check),
136
- // fall back to the original instruction.
137
- if (originalOperands.length !== order.length) {
138
- result.push(instr);
139
- continue;
140
- }
141
-
142
- // Rearrange operands: new slot i receives original operand order[i].
143
- const newOperands = order.map((i) => originalOperands[i]);
144
-
145
- const newInstr: Instruction = [aliasOp, ...newOperands];
146
- (newInstr as any)[SOURCE_NODE_SYM] = (instr as any)[SOURCE_NODE_SYM];
147
- result.push(newInstr);
148
- }
149
-
150
- return { bytecode: result };
151
- }
@@ -1,52 +0,0 @@
1
- import { Compiler } from "../../compiler.ts";
2
- import type * as b from "../../types.ts";
3
-
4
- export function concealConstants(
5
- bytecode: b.Bytecode,
6
- compiler: Compiler,
7
- ): {
8
- bytecode: b.Bytecode;
9
- } {
10
- const newBytecode: b.Bytecode = [];
11
-
12
- for (const instr of bytecode) {
13
- const [op, ...operands] = instr;
14
-
15
- const hasContant = operands.some(
16
- (o) =>
17
- o !== undefined &&
18
- o !== null &&
19
- typeof o === "object" &&
20
- (o as any).type === "constant",
21
- );
22
-
23
- if (!hasContant) {
24
- newBytecode.push(instr);
25
- continue;
26
- }
27
-
28
- const newOperands = [];
29
- for (const operand of operands) {
30
- if ((operand as any)?.type === "constant") {
31
- const tsOperand = operand as any;
32
- newOperands.push(operand);
33
- newOperands.push({
34
- type: "constant",
35
- value: tsOperand.value,
36
- key: true,
37
- });
38
- } else {
39
- newOperands.push(operand);
40
- }
41
- }
42
-
43
- instr.length = 0;
44
- instr.push(op, ...newOperands);
45
-
46
- newBytecode.push(instr);
47
- }
48
-
49
- return {
50
- bytecode: newBytecode,
51
- };
52
- }