js-confuser-vm 0.0.8 → 0.1.0

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.
@@ -0,0 +1,221 @@
1
+ // resolveRegisters
2
+ // Converts virtual RegisterOperand objects into concrete slot indices and sets
3
+ // each FnDescriptor's regCount.
4
+ //
5
+ // Two-tier slot assignment:
6
+ //
7
+ // "local::" pool (params, `arguments`, hoisted vars, upvalue-captured vars)
8
+ // ─────────────────────────────────────────────────────────────────────────
9
+ // Sorted by virtual-id, slots assigned sequentially with NO reuse.
10
+ // This is required because:
11
+ // • The runtime writes args[i] to regs[base + i] at call time, so params
12
+ // MUST occupy slots 0..paramCount-1 in virtual-id order.
13
+ // • Open upvalues hold an absolute slot index and read regs[base+slot] for
14
+ // the lifetime of the outer frame — reusing a captured slot corrupts reads.
15
+ //
16
+ // All other pools (e.g. "temp::", "canary::", pass-introduced pools)
17
+ // ─────────────────────────────────────────────────────────────────────────
18
+ // Linear-scan with a free list: registers are sorted by firstUse, and any
19
+ // slot whose previous occupant's lastUse < current register's firstUse is
20
+ // recycled. An explicit [null, freeRegOperand(reg)] pseudo-instruction clamps
21
+ // lastUse early, enabling reuse before the natural end of the live range.
22
+ //
23
+ // Pools are processed in priority order: "local::" always first (slots
24
+ // 0..N), then remaining pools alphabetically. This keeps temp slots above
25
+ // the reserved param/local region.
26
+ //
27
+ // regCount = max concrete slot used across all pools + 1.
28
+ //
29
+ // Run AFTER all IR-level passes but BEFORE resolveLabels / resolveConstants.
30
+
31
+ import type { Bytecode } from "../../types.ts";
32
+ import { Compiler } from "../../compiler.ts";
33
+
34
+ export function resolveRegisters(
35
+ bc: Bytecode,
36
+ compiler: Compiler,
37
+ ): { bytecode: Bytecode } {
38
+ function registerPoolKey(op: {
39
+ kind?: string;
40
+ scopeId?: string | number;
41
+ }): string {
42
+ return `${op.kind ?? "local"}::${op.scopeId ?? ""}`;
43
+ }
44
+
45
+ // ── Pass 1: collect live ranges ───────────────────────────────────────────
46
+ // For each (fnId, virtId) record the first and last instruction index where
47
+ // the register appears as a real operand. A freeReg marker clamps lastUse.
48
+ type RegInfo = {
49
+ firstUse: number;
50
+ lastUse: number;
51
+ poolKey: string;
52
+ freed: boolean; // true once a freeReg has been seen; prevents further extension
53
+ };
54
+ // fnId -> virtId -> RegInfo
55
+ const fnRegInfo = new Map<number, Map<number, RegInfo>>();
56
+
57
+ for (let i = 0; i < bc.length; i++) {
58
+ const instr = bc[i];
59
+ for (let j = 1; j < instr.length; j++) {
60
+ const op = instr[j] as any;
61
+ if (!op || typeof op !== "object") continue;
62
+
63
+ if (op.type === "register") {
64
+ const { fnId, id } = op;
65
+ const poolKey = registerPoolKey(op);
66
+ let fnMap = fnRegInfo.get(fnId);
67
+ if (!fnMap) {
68
+ fnMap = new Map();
69
+ fnRegInfo.set(fnId, fnMap);
70
+ }
71
+ const existing = fnMap.get(id);
72
+ if (!existing) {
73
+ fnMap.set(id, { firstUse: i, lastUse: i, poolKey, freed: false });
74
+ } else if (!existing.freed) {
75
+ // Only extend lastUse if no explicit freeReg has clamped it yet.
76
+ existing.lastUse = i;
77
+ }
78
+ } else if (op.type === "freeReg") {
79
+ // Explicit end-of-life marker: clamp lastUse and prevent extension.
80
+ const { fnId, id } = op;
81
+ const fnMap = fnRegInfo.get(fnId);
82
+ if (fnMap) {
83
+ const info = fnMap.get(id);
84
+ if (info && !info.freed) {
85
+ info.lastUse = i;
86
+ info.freed = true;
87
+ }
88
+ }
89
+ }
90
+ }
91
+ }
92
+
93
+ // ── Pass 2: slot assignment per function ──────────────────────────────────
94
+ // fnId -> virtId -> concrete slot
95
+ const fnSlotMaps = new Map<number, Map<number, number>>();
96
+
97
+ // Pool ordering: "local::" always first; all other keys sorted alphabetically.
98
+ function poolSortKey(key: string): [number, string] {
99
+ return key === "local::" ? [0, ""] : [1, key];
100
+ }
101
+
102
+ for (const [fnId, regMap] of fnRegInfo) {
103
+ // Group by pool key.
104
+ const pools = new Map<
105
+ string,
106
+ Array<{ id: number; firstUse: number; lastUse: number }>
107
+ >();
108
+ for (const [id, info] of regMap) {
109
+ let pool = pools.get(info.poolKey);
110
+ if (!pool) {
111
+ pool = [];
112
+ pools.set(info.poolKey, pool);
113
+ }
114
+ pool.push({ id, firstUse: info.firstUse, lastUse: info.lastUse });
115
+ }
116
+
117
+ const sortedPoolKeys = Array.from(pools.keys()).sort((a, b) => {
118
+ const [pa, sa] = poolSortKey(a);
119
+ const [pb, sb] = poolSortKey(b);
120
+ if (pa !== pb) return pa - pb;
121
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
122
+ });
123
+
124
+ const slotMap = new Map<number, number>(); // virtId -> slot
125
+ fnSlotMaps.set(fnId, slotMap);
126
+
127
+ // nextSlot is the high-water mark: the next fresh slot to allocate.
128
+ // It is shared across all pools so each pool's slots start above the
129
+ // previous pool's maximum slot.
130
+ let nextSlot = 0;
131
+
132
+ for (const poolKey of sortedPoolKeys) {
133
+ const regs = pools.get(poolKey)!;
134
+
135
+ if (poolKey === "local::") {
136
+ // ── Local pool: virtual-id order, no reuse ────────────────────────
137
+ // Params must be at the lowest slots (written by the runtime at call
138
+ // time); upvalue captures must keep their slot for the frame's lifetime.
139
+ regs.sort((a, b) => a.id - b.id);
140
+ for (const reg of regs) {
141
+ slotMap.set(reg.id, nextSlot++);
142
+ }
143
+ } else {
144
+ // ── Non-local pool: firstUse order, linear-scan reuse ─────────────
145
+ regs.sort((a, b) => a.firstUse - b.firstUse);
146
+
147
+ // freeList entries: { slot, freeAt } where freeAt = lastUse of current
148
+ // occupant. A slot becomes available when freeAt < next reg's firstUse.
149
+ const freeList: Array<{ slot: number; freeAt: number }> = [];
150
+
151
+ for (const reg of regs) {
152
+ // Find the lowest-numbered slot whose last occupant has ended.
153
+ let bestSlot = -1;
154
+ let bestIdx = -1;
155
+ for (let k = 0; k < freeList.length; k++) {
156
+ if (freeList[k].freeAt < reg.firstUse) {
157
+ if (bestSlot === -1 || freeList[k].slot < bestSlot) {
158
+ bestSlot = freeList[k].slot;
159
+ bestIdx = k;
160
+ }
161
+ }
162
+ }
163
+
164
+ let assignedSlot: number;
165
+ if (bestIdx !== -1) {
166
+ assignedSlot = bestSlot;
167
+ freeList.splice(bestIdx, 1);
168
+ } else {
169
+ assignedSlot = nextSlot++;
170
+ }
171
+
172
+ slotMap.set(reg.id, assignedSlot);
173
+ freeList.push({ slot: assignedSlot, freeAt: reg.lastUse });
174
+ }
175
+ // nextSlot already reflects the high-water mark; reused slots are
176
+ // always < nextSlot by construction.
177
+ }
178
+ }
179
+ }
180
+
181
+ // ── Pass 3: patch register operands ──────────────────────────────────────
182
+ for (const instr of bc) {
183
+ for (let i = 1; i < instr.length; i++) {
184
+ const op = instr[i] as any;
185
+ if (!op || typeof op !== "object") continue;
186
+ if (op.type === "register") {
187
+ op.resolvedValue = fnSlotMaps.get(op.fnId)?.get(op.id);
188
+ }
189
+ }
190
+ }
191
+
192
+ // ── Pass 4: set regCount on each FnDescriptor ─────────────────────────────
193
+ // regCount = max concrete slot used + 1 (not sum of virtual-register counts).
194
+ for (const desc of compiler.fnDescriptors) {
195
+ const fnId = desc._fnIdx!;
196
+ const slotMap = fnSlotMaps.get(fnId);
197
+ let regCount = 0;
198
+ if (slotMap) {
199
+ for (const slot of slotMap.values()) {
200
+ if (slot + 1 > regCount) regCount = slot + 1;
201
+ }
202
+ }
203
+ desc.regCount = regCount;
204
+ }
205
+
206
+ compiler.mainRegCount = compiler.mainFn?.regCount ?? 0;
207
+
208
+ // ── Pass 5: patch fnRegCount operands ────────────────────────────────────
209
+ for (const instr of bc) {
210
+ for (let i = 1; i < instr.length; i++) {
211
+ const op = instr[i] as any;
212
+ if (!op || typeof op !== "object") continue;
213
+ if (op.type === "fnRegCount") {
214
+ const desc = compiler.fnDescriptors[op.fnId];
215
+ op.resolvedValue = desc?.regCount ?? 0;
216
+ }
217
+ }
218
+ }
219
+
220
+ return { bytecode: bc };
221
+ }
@@ -1,12 +1,6 @@
1
1
  import type { Bytecode, InstrOperand, Instruction } from "../../types.ts";
2
2
  import { Compiler, SOURCE_NODE_SYM } from "../../compiler.ts";
3
- import {
4
- getInstructionSize,
5
- nextFreeSlot,
6
- U16_MAX,
7
- } from "../../utils/op-utils.ts";
8
- import * as t from "@babel/types";
9
- import * as b from "../../types.ts";
3
+ import { getInstructionSize, nextFreeSlot } from "../../utils/op-utils.ts";
10
4
 
11
5
  export const nSizedOps = [
12
6
  "MAKE_CLOSURE",
@@ -19,9 +13,11 @@ export const nSizedOps = [
19
13
 
20
14
  // Creates specialized opcodes for the most frequent (OPCODE + single_integer_operand) pairs.
21
15
  // Example: [OP.LOAD_CONST, 1] becomes [SPECIALIZED_LOAD_CONST_1].
22
- // Only instructions with *exactly one numeric operand* are considered.
16
+ // Only instructions that are fixed-sized are considered.
23
17
  // MAKE_CLOSURE and other N-sized instructions cannot be specialized
24
- // Runs after selfModifying but before resolveLabels (operands stay plain numbers).
18
+ // Operands are converted into objects and marked as 'placeholder' - other passes can mutate and the reference stays intact
19
+ // We need a reference throughout the pipeline so that final AST generation can place the actual value
20
+ // The 'placeholder' flag drops the operand from the final bytecode - any size calculation must not count these
25
21
  export function specializedOpcodes(
26
22
  bc: Bytecode,
27
23
  compiler: Compiler,
package/src/types.ts CHANGED
@@ -6,17 +6,58 @@
6
6
  // All "null" instructions are dropped before assembly time.
7
7
  // Instructions may carry any number of operands; the flat output serializes
8
8
  // each operand as a separate u16 slot in the bytecode array.
9
+ // A virtual register reference emitted by the compiler.
10
+ // fnId identifies which function's register file this belongs to.
11
+ // resolveRegisters() replaces these with concrete slot indices (type:"number").
12
+ export type RegisterOperand = Op<{
13
+ type: "register";
14
+ id: number;
15
+ fnId: number;
16
+ kind?: string;
17
+ scopeId?: string | number;
18
+ }>;
19
+
20
+ // A placeholder for a function's concrete regCount, emitted in MAKE_CLOSURE.
21
+ // resolveRegisters() fills resolvedValue once it knows the concrete slot count.
22
+ export type FnRegCountOperand = Op<{ type: "fnRegCount"; fnId: number }>;
23
+
24
+ // IR pseudo-instruction that marks the end of a register's live range.
25
+ // Emitted as [null, FreeRegOperand] so it is dropped before final assembly.
26
+ //
27
+ // NOTE: resolveRegisters() already computes correct lastUse from the last real
28
+ // operand appearance, so freeReg is EXTRANEOUS for any programmatically generated
29
+ // IR — the scanner will find the tightest possible range without it.
30
+ // It is only useful when a register has a late syntactic appearance that does
31
+ // NOT reflect its true logical end-of-life (e.g. a read emitted purely for
32
+ // side-effects long after the value is logically dead). No current pass in this
33
+ // codebase emits freeReg; it is kept as an extension point only.
34
+ export type FreeRegOperand = Op<{
35
+ type: "freeReg";
36
+ fnId: number;
37
+ id: number;
38
+ kind?: string;
39
+ scopeId?: string | number;
40
+ }>;
41
+
9
42
  export type InstrOperand =
10
43
  | number
11
44
  | Op<{ type: "number"; value?: number }>
12
- | Op<{ type: "label"; label: string; offset?: number }>
45
+ | Op<{
46
+ type: "label";
47
+ label: string;
48
+ offset?: number;
49
+ transform?: (resolvedPC: number) => number;
50
+ }>
13
51
  | Op<{ type: "defineLabel"; label: string }>
14
- | Op<{ type: "constant"; value: any }>;
52
+ | Op<{ type: "constant"; value: any }>
53
+ | RegisterOperand
54
+ | FnRegCountOperand
55
+ | FreeRegOperand;
15
56
 
16
57
  export interface Operand {
17
58
  type: string;
18
- placeholder?: boolean;
19
- resolvedValue?: number;
59
+ placeholder?: boolean; // This operand will not be emitted in the final bytecode, but used as a reference
60
+ resolvedValue?: number; // This operand knows its resolved value, but kept as a object to keep metadata info available
20
61
  }
21
62
 
22
63
  type Op<T extends object> = Operand & T;
@@ -31,3 +72,22 @@ export function constantOperand(value: any): Instruction[1] {
31
72
  value: value,
32
73
  };
33
74
  }
75
+
76
+ export function registerOperand(
77
+ id: number,
78
+ fnId: number,
79
+ metadata: Partial<Pick<RegisterOperand, "kind" | "scopeId">> = {},
80
+ ): RegisterOperand {
81
+ return { type: "register", id, fnId, ...metadata };
82
+ }
83
+
84
+ export function fnRegCountOperand(fnId: number): FnRegCountOperand {
85
+ return { type: "fnRegCount", fnId };
86
+ }
87
+
88
+ export function freeRegOperand(reg: RegisterOperand): FreeRegOperand {
89
+ const op: FreeRegOperand = { type: "freeReg", fnId: reg.fnId, id: reg.id };
90
+ if (reg.kind !== undefined) op.kind = reg.kind;
91
+ if (reg.scopeId !== undefined) op.scopeId = reg.scopeId;
92
+ return op;
93
+ }
@@ -40,6 +40,8 @@ export function nextFreeSlot(compiler: Compiler): number {
40
40
  }
41
41
 
42
42
  export function getInstructionSize(instr: b.Instruction): number {
43
+ if (instr[0] === null) return 0;
44
+
43
45
  const size = instr.filter((op) => (op as any)?.placeholder !== true).length;
44
46
 
45
47
  return size;
@@ -1,25 +0,0 @@
1
- import { getRandomInt } from "./random-utils.js";
2
- export const U16_MAX = 0xffff; // bytecode operands are u16
3
-
4
- /** Returns the next free opcode slot, or -1 when the space is exhausted. */
5
- export function nextFreeSlot(usedOpcodes) {
6
- if (usedOpcodes.size > U16_MAX) return -1;
7
- let attempts = 0;
8
- while (attempts++ < 512) {
9
- const candidate = getRandomInt(0, U16_MAX);
10
- if (!usedOpcodes.has(candidate)) {
11
- usedOpcodes.add(candidate);
12
- return candidate;
13
- }
14
- }
15
- // Fallback: linear scan from a random start
16
- const start = getRandomInt(0, U16_MAX);
17
- for (let i = 0; i <= U16_MAX; i++) {
18
- const v = start + i & U16_MAX;
19
- if (!usedOpcodes.has(v)) {
20
- usedOpcodes.add(v);
21
- return v;
22
- }
23
- }
24
- return -1;
25
- }
@@ -1,27 +0,0 @@
1
- import { ok } from "assert";
2
- export function getPlaceholder() {
3
- return Math.random().toString(36).substring(2, 15);
4
- }
5
- export function choice(elements) {
6
- ok(elements.length > 0, "choice() called on empty sequence");
7
- return elements[Math.floor(Math.random() * elements.length)];
8
- }
9
- export function getRandom() {
10
- return Math.random();
11
- }
12
- export function getRandomInt(min, max) {
13
- ok(min <= max, "min must be <= max");
14
- return Math.floor(Math.random() * (max - min + 1)) + min;
15
- }
16
-
17
- /**
18
- * Shuffles an array in-place using the Fisher-Yates algorithm.
19
- * @param array - The array to shuffle (mutated)
20
- */
21
- export function shuffle(array) {
22
- for (let i = array.length - 1; i > 0; i--) {
23
- const j = Math.floor(Math.random() * (i + 1));
24
- [array[i], array[j]] = [array[j], array[i]];
25
- }
26
- return array;
27
- }
package/dist/utilts.js DELETED
@@ -1,3 +0,0 @@
1
- export function escapeRegex(s) {
2
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3
- }