js-confuser-vm 0.1.0 → 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 (63) hide show
  1. package/README.md +281 -147
  2. package/dist/build-runtime.js +41 -15
  3. package/dist/compiler.js +714 -265
  4. package/dist/disassembler.js +367 -0
  5. package/dist/index.js +7 -2
  6. package/dist/runtime.js +160 -119
  7. package/dist/template.js +163 -42
  8. package/dist/transforms/bytecode/aliasedOpcodes.js +4 -1
  9. package/dist/transforms/bytecode/concealConstants.js +2 -2
  10. package/dist/transforms/bytecode/controlFlowFlattening.js +569 -0
  11. package/dist/transforms/bytecode/dispatcher.js +15 -111
  12. package/dist/transforms/bytecode/macroOpcodes.js +2 -2
  13. package/{src/transforms/bytecode/resolveContants.ts → dist/transforms/bytecode/resolveConstants.js} +30 -56
  14. package/dist/transforms/bytecode/resolveRegisters.js +23 -4
  15. package/dist/transforms/bytecode/selfModifying.js +88 -21
  16. package/dist/transforms/bytecode/semanticOpcodes.js +162 -0
  17. package/dist/transforms/bytecode/specializedOpcodes.js +23 -12
  18. package/dist/transforms/bytecode/stringConcealing.js +288 -0
  19. package/dist/transforms/runtime/classObfuscation.js +43 -0
  20. package/dist/transforms/runtime/handlerTable.js +91 -0
  21. package/dist/transforms/runtime/semanticOpcodes.js +35 -0
  22. package/dist/transforms/runtime/specializedOpcodes.js +11 -5
  23. package/dist/types.js +1 -1
  24. package/dist/utils/ast-utils.js +75 -0
  25. package/dist/utils/op-utils.js +1 -2
  26. package/dist/utils/pass-utils.js +100 -0
  27. package/dist/utils/profile-utils.js +3 -0
  28. package/package.json +8 -1
  29. package/.gitmodules +0 -4
  30. package/.prettierignore +0 -1
  31. package/CHANGELOG.md +0 -335
  32. package/babel-plugin-inline-runtime.cjs +0 -34
  33. package/babel.config.json +0 -23
  34. package/index.ts +0 -38
  35. package/jest-strip-types.js +0 -10
  36. package/jest.config.js +0 -52
  37. package/src/build-runtime.ts +0 -78
  38. package/src/compiler.ts +0 -2593
  39. package/src/index.ts +0 -14
  40. package/src/minify.ts +0 -21
  41. package/src/options.ts +0 -18
  42. package/src/runtime.ts +0 -923
  43. package/src/template.ts +0 -141
  44. package/src/transforms/bytecode/aliasedOpcodes.ts +0 -148
  45. package/src/transforms/bytecode/concealConstants.ts +0 -52
  46. package/src/transforms/bytecode/dispatcher.ts +0 -398
  47. package/src/transforms/bytecode/macroOpcodes.ts +0 -193
  48. package/src/transforms/bytecode/microOpcodes.ts +0 -291
  49. package/src/transforms/bytecode/resolveLabels.ts +0 -112
  50. package/src/transforms/bytecode/resolveRegisters.ts +0 -221
  51. package/src/transforms/bytecode/selfModifying.ts +0 -121
  52. package/src/transforms/bytecode/specializedOpcodes.ts +0 -153
  53. package/src/transforms/runtime/aliasedOpcodes.ts +0 -191
  54. package/src/transforms/runtime/internalVariables.ts +0 -270
  55. package/src/transforms/runtime/macroOpcodes.ts +0 -138
  56. package/src/transforms/runtime/microOpcodes.ts +0 -93
  57. package/src/transforms/runtime/minify.ts +0 -1
  58. package/src/transforms/runtime/shuffleOpcodes.ts +0 -24
  59. package/src/transforms/runtime/specializedOpcodes.ts +0 -156
  60. package/src/types.ts +0 -93
  61. package/src/utils/op-utils.ts +0 -48
  62. package/src/utils/random-utils.ts +0 -31
  63. package/tsconfig.json +0 -12
package/src/runtime.ts DELETED
@@ -1,923 +0,0 @@
1
- import { OP_ORIGINAL as OP } from "./compiler.ts";
2
- const BYTECODE = [];
3
- const MAIN_START_PC = 0;
4
- const MAIN_REG_COUNT = 0;
5
- const CONSTANTS = [];
6
- const ENCODE_BYTECODE = false;
7
- const TIMING_CHECKS = false;
8
- // The text above is not included in the compiled output - for type intellisense only
9
- // @START
10
-
11
- function decodeBytecode(s) {
12
- if (!ENCODE_BYTECODE) return s;
13
-
14
- var b =
15
- typeof Buffer !== "undefined"
16
- ? Buffer.from(s, "base64")
17
- : Uint8Array.from(atob(s), function (c) {
18
- return c.charCodeAt(0);
19
- });
20
- // Each slot is a u16 stored as 2 little-endian bytes.
21
- var r = new Uint16Array(b.length / 2);
22
- for (var i = 0; i < r.length; i++) r[i] = b[i * 2] | (b[i * 2 + 1] << 8);
23
- return r;
24
- }
25
-
26
- // Closure symbol
27
- // Used to tag shell functions so the VM can fast-path back to the
28
- // inner Closure instead of going through a sub-VM on internal calls.
29
- var CLOSURE_SYM = Symbol(); // Nameless for obfuscation
30
-
31
- // Upvalue — Lua/CPython style.
32
- // While the outer frame is alive: reads/writes go to vm._regs[_absSlot].
33
- // After the outer frame returns (closed): reads/writes hit this._value.
34
- // _absSlot is the absolute index in VM._regs (frame._base + local slot).
35
- function Upvalue(regs, absSlot) {
36
- this._regs = regs; // shared reference to VM._regs flat array
37
- this._absSlot = absSlot; // absolute index; stable as long as frame is alive
38
- this._closed = false;
39
- this._value = undefined;
40
- }
41
- Upvalue.prototype._read = function () {
42
- return this._closed ? this._value : this._regs[this._absSlot];
43
- };
44
- Upvalue.prototype._write = function (v) {
45
- if (this._closed) this._value = v;
46
- else this._regs[this._absSlot] = v;
47
- };
48
- Upvalue.prototype._close = function () {
49
- this._value = this._regs[this._absSlot];
50
- this._closed = true;
51
- };
52
-
53
- // Closure & Frame
54
- function Closure(fn) {
55
- this.fn = fn;
56
- this.upvalues = [];
57
- this.prototype = {}; // <- default prototype object for `new`
58
- }
59
-
60
- // Frame — analogous to Lua CallInfo / CPython PyFrameObject.
61
- // Does NOT own a register array; registers live in VM._regs[_base .. _base+regCount).
62
- function Frame(closure, returnPc, parent, thisVal, retDstReg, base) {
63
- this.closure = closure;
64
- this._base = base; // absolute offset into VM._regs for this frame's r0
65
- this._pc = closure.fn.startPc;
66
- this._returnPc = returnPc;
67
- this._parent = parent;
68
- this.thisVal = thisVal !== undefined ? thisVal : undefined;
69
- this._retDstReg = retDstReg !== undefined ? retDstReg : 0;
70
- this._newObj = null;
71
- this._handlerStack = [];
72
- }
73
-
74
- // VM
75
- function VM(bytecode, mainStartPc, mainRegCount, constants, globals) {
76
- this.bytecode = bytecode;
77
- this.constants = constants;
78
- this.globals = globals;
79
- this._frameStack = [];
80
- this._openUpvalues = [];
81
-
82
- // ── Flat register file (Lua-style) ────────────────────────────────────────
83
- // All frames share a single array. Each Frame records its _base offset.
84
- // _regsTop is the next free slot (= base of the hypothetical next frame).
85
- // On CALL: newBase = _regsTop; _regsTop += fn.regCount
86
- // On RETURN: _regsTop = frame._base (pop the frame's register window)
87
- this._regs = new Array(mainRegCount).fill(undefined);
88
- this._regsTop = mainRegCount; // main frame occupies [0, mainRegCount)
89
-
90
- var mainFn = {
91
- paramCount: 0,
92
- regCount: mainRegCount,
93
- startPc: mainStartPc,
94
- };
95
- this._currentFrame = new Frame(
96
- new Closure(mainFn),
97
- null,
98
- null,
99
- undefined,
100
- 0,
101
- 0,
102
- );
103
- this._internals = {};
104
- }
105
-
106
- // Consume the next slot from the flat bytecode stream and advance the PC.
107
- // Called by opcode handlers to read each of their operands in order.
108
- VM.prototype._operand = function () {
109
- return this.bytecode[this._currentFrame._pc++];
110
- };
111
-
112
- VM.prototype.captureUpvalue = function (frame, slot) {
113
- // Dedup by absolute slot — two closures capturing the same local share one Upvalue.
114
- var absSlot = frame._base + slot;
115
- for (var i = 0; i < this._openUpvalues.length; i++) {
116
- var uv = this._openUpvalues[i];
117
- if (!uv._closed && uv._absSlot === absSlot) return uv;
118
- }
119
- var uv = new Upvalue(this._regs, absSlot);
120
- this._openUpvalues.push(uv);
121
- return uv;
122
- };
123
-
124
- // Reads and decodes a constant from the pool.
125
- // idx — pool index (first operand of the constant pair emitted by resolveConstants).
126
- // key — conceal key (second operand). 0 means no concealment.
127
- //
128
- // For integers: stored value is (original ^ key); XOR again to recover.
129
- // For strings: stored value is a base64 string containing u16 LE byte pairs.
130
- // Mirrors decodeBytecode: base64 → bytes → u16 LE → XOR with
131
- // (key + i) & 0xFFFF to recover the original char codes.
132
- // idxIn, keyIn are passed in from specializedOpcodes when the operands are determined at compile time.
133
- VM.prototype._constant = function (idxIn, keyIn) {
134
- var idx = idxIn ?? this._operand();
135
- var key = keyIn ?? this._operand();
136
-
137
- var v = this.constants[idx];
138
- if (!key) return v;
139
- if (typeof v === "number") return v ^ key;
140
- // String: base64-decode to u16 LE byte pairs, then XOR each code with (key+i).
141
- var b =
142
- typeof Buffer !== "undefined"
143
- ? Buffer.from(v, "base64")
144
- : Uint8Array.from(atob(v), function (c) {
145
- return c.charCodeAt(0);
146
- });
147
- var out = "";
148
- for (var i = 0; i < b.length / 2; i++) {
149
- var code = b[i * 2] | (b[i * 2 + 1] << 8); // u16 LE
150
- out += String.fromCharCode(code ^ ((key + i) & 0xffff));
151
- }
152
- return out;
153
- };
154
-
155
- VM.prototype._closeUpvaluesFor = function (frame) {
156
- // Called on RETURN — close every upvalue whose absolute slot falls within
157
- // this frame's register window [_base, _base + regCount).
158
- var lo = frame._base;
159
- var hi = frame._base + frame.closure.fn.regCount;
160
- this._openUpvalues = this._openUpvalues.filter(function (uv) {
161
- if (!uv._closed && uv._absSlot >= lo && uv._absSlot < hi) {
162
- uv._close();
163
- return false;
164
- }
165
- return true;
166
- });
167
- };
168
-
169
- VM.prototype._ensureRegisterWindow = function (base, regCount) {
170
- var end = base + regCount;
171
- while (this._regs.length < end) this._regs.push(undefined);
172
- for (var i = base; i < end; i++) this._regs[i] = undefined;
173
- };
174
-
175
- VM.prototype.run = function () {
176
- var now = () => {
177
- return performance.now();
178
- };
179
-
180
- var lastTime = now();
181
-
182
- while (true) {
183
- var frame = this._currentFrame;
184
- var bc = this.bytecode;
185
- if (frame._pc >= bc.length) break;
186
-
187
- var pc = frame._pc++;
188
- var op = this.bytecode[pc];
189
- var opcode = this.bytecode[pc];
190
- // console.log(
191
- // "pc=" + pc,
192
- // "opcode=" + opcode,
193
- // Object.keys(OP).find((key) => OP[key] === opcode),
194
- // );
195
-
196
- // Debugging protection: Detects debugger by checking for >1s pauses which can only happen from debugger; or extremely slow sync tasks
197
- if (TIMING_CHECKS) {
198
- var currentTime = now();
199
- var isTamper = currentTime - lastTime > 1000;
200
- lastTime = currentTime;
201
- if (isTamper) {
202
- // Poison the bytecode
203
- for (var i = 0; i < this.bytecode.length; i++) this.bytecode[i] = 0;
204
- // Break the current state
205
- for (var i2 = frame._base; i2 < this._regsTop; i2++)
206
- this._regs[i2] = undefined;
207
- op = OP.JUMP;
208
- frame._pc = this.bytecode.length; // jump past end to halt
209
- }
210
- }
211
-
212
- try {
213
- var regs = this._regs;
214
- var base = frame._base;
215
- /* @SWITCH */
216
- switch (op) {
217
- case OP.LOAD_CONST: {
218
- var dst = this._operand();
219
- regs[base + dst] = this._constant();
220
- break;
221
- }
222
-
223
- case OP.LOAD_INT: {
224
- var dst = this._operand();
225
- regs[base + dst] = this._operand();
226
- break;
227
- }
228
-
229
- case OP.LOAD_GLOBAL: {
230
- var dst = this._operand();
231
- var globalName = this._constant();
232
-
233
- if (!(globalName in this.globals)) {
234
- throw new ReferenceError(`${globalName} is not defined`);
235
- }
236
-
237
- regs[base + dst] = this.globals[globalName];
238
- break;
239
- }
240
-
241
- case OP.LOAD_UPVALUE: {
242
- var dst = this._operand();
243
- regs[base + dst] = frame.closure.upvalues[this._operand()]._read();
244
- break;
245
- }
246
-
247
- case OP.LOAD_THIS: {
248
- var dst = this._operand();
249
- regs[base + dst] = frame.thisVal;
250
- break;
251
- }
252
-
253
- case OP.MOVE: {
254
- var dst = this._operand();
255
- regs[base + dst] = regs[base + this._operand()];
256
- break;
257
- }
258
-
259
- case OP.STORE_GLOBAL: {
260
- // nameIdx and key are consumed inline so the concealConstants runtime
261
- // transform can rewrite this._constant() consistently.
262
- this.globals[this._constant()] = regs[base + this._operand()];
263
- break;
264
- }
265
-
266
- case OP.STORE_UPVALUE: {
267
- var uvIdx = this._operand();
268
- frame.closure.upvalues[uvIdx]._write(regs[base + this._operand()]);
269
- break;
270
- }
271
-
272
- case OP.GET_PROP: {
273
- // dst = regs[obj][regs[key]]
274
- var dst = this._operand();
275
- var obj = regs[base + this._operand()];
276
- var key = regs[base + this._operand()];
277
- regs[base + dst] = obj[key];
278
- break;
279
- }
280
-
281
- case OP.SET_PROP: {
282
- // regs[obj][regs[key]] = regs[val]
283
- var obj = regs[base + this._operand()];
284
- var key = regs[base + this._operand()];
285
- var val = regs[base + this._operand()];
286
- // Reflect.set performs [[Set]] without throwing on failure,
287
- // correctly simulating sloppy-mode assignment from a strict-mode host.
288
- Reflect.set(obj, key, val);
289
- break;
290
- }
291
-
292
- case OP.DELETE_PROP: {
293
- var dst = this._operand();
294
- var obj = regs[base + this._operand()];
295
- var key = regs[base + this._operand()];
296
- regs[base + dst] = delete obj[key];
297
- break;
298
- }
299
-
300
- // ── Arithmetic (dst, src1, src2) ────────────────────────────────────
301
- case OP.ADD: {
302
- var dst = this._operand();
303
- var a = regs[base + this._operand()];
304
- regs[base + dst] = a + regs[base + this._operand()];
305
- break;
306
- }
307
- case OP.SUB: {
308
- var dst = this._operand();
309
- var a = regs[base + this._operand()];
310
- regs[base + dst] = a - regs[base + this._operand()];
311
- break;
312
- }
313
- case OP.MUL: {
314
- var dst = this._operand();
315
- var a = regs[base + this._operand()];
316
- regs[base + dst] = a * regs[base + this._operand()];
317
- break;
318
- }
319
- case OP.DIV: {
320
- var dst = this._operand();
321
- var a = regs[base + this._operand()];
322
- regs[base + dst] = a / regs[base + this._operand()];
323
- break;
324
- }
325
- case OP.MOD: {
326
- var dst = this._operand();
327
- var a = regs[base + this._operand()];
328
- regs[base + dst] = a % regs[base + this._operand()];
329
- break;
330
- }
331
- case OP.BAND: {
332
- var dst = this._operand();
333
- var a = regs[base + this._operand()];
334
- regs[base + dst] = a & regs[base + this._operand()];
335
- break;
336
- }
337
- case OP.BOR: {
338
- var dst = this._operand();
339
- var a = regs[base + this._operand()];
340
- regs[base + dst] = a | regs[base + this._operand()];
341
- break;
342
- }
343
- case OP.BXOR: {
344
- var dst = this._operand();
345
- var a = regs[base + this._operand()];
346
- regs[base + dst] = a ^ regs[base + this._operand()];
347
- break;
348
- }
349
- case OP.SHL: {
350
- var dst = this._operand();
351
- var a = regs[base + this._operand()];
352
- regs[base + dst] = a << regs[base + this._operand()];
353
- break;
354
- }
355
- case OP.SHR: {
356
- var dst = this._operand();
357
- var a = regs[base + this._operand()];
358
- regs[base + dst] = a >> regs[base + this._operand()];
359
- break;
360
- }
361
- case OP.USHR: {
362
- var dst = this._operand();
363
- var a = regs[base + this._operand()];
364
- regs[base + dst] = a >>> regs[base + this._operand()];
365
- break;
366
- }
367
-
368
- // ── Comparison (dst, src1, src2) ─────────────────────────────────────
369
- case OP.LT: {
370
- var dst = this._operand();
371
- var a = regs[base + this._operand()];
372
- regs[base + dst] = a < regs[base + this._operand()];
373
- break;
374
- }
375
- case OP.GT: {
376
- var dst = this._operand();
377
- var a = regs[base + this._operand()];
378
- regs[base + dst] = a > regs[base + this._operand()];
379
- break;
380
- }
381
- case OP.LTE: {
382
- var dst = this._operand();
383
- var a = regs[base + this._operand()];
384
- regs[base + dst] = a <= regs[base + this._operand()];
385
- break;
386
- }
387
- case OP.GTE: {
388
- var dst = this._operand();
389
- var a = regs[base + this._operand()];
390
- regs[base + dst] = a >= regs[base + this._operand()];
391
- break;
392
- }
393
- case OP.EQ: {
394
- var dst = this._operand();
395
- var a = regs[base + this._operand()];
396
- regs[base + dst] = a === regs[base + this._operand()];
397
- break;
398
- }
399
- case OP.NEQ: {
400
- var dst = this._operand();
401
- var a = regs[base + this._operand()];
402
- regs[base + dst] = a !== regs[base + this._operand()];
403
- break;
404
- }
405
- case OP.LOOSE_EQ: {
406
- var dst = this._operand();
407
- var a = regs[base + this._operand()];
408
- regs[base + dst] = a == regs[base + this._operand()];
409
- break;
410
- }
411
- case OP.LOOSE_NEQ: {
412
- var dst = this._operand();
413
- var a = regs[base + this._operand()];
414
- regs[base + dst] = a != regs[base + this._operand()];
415
- break;
416
- }
417
- case OP.IN: {
418
- var dst = this._operand();
419
- var a = regs[base + this._operand()];
420
- regs[base + dst] = a in regs[base + this._operand()];
421
- break;
422
- }
423
- case OP.INSTANCEOF: {
424
- var dst = this._operand();
425
- var obj = regs[base + this._operand()];
426
- var ctor = regs[base + this._operand()];
427
- if (typeof ctor === "function") {
428
- regs[base + dst] = obj instanceof ctor;
429
- } else {
430
- // VM Closure - walk prototype chain for identity with ctor.prototype.
431
- var proto = ctor.prototype;
432
- var target = Object.getPrototypeOf(obj);
433
- var result = false;
434
- while (target !== null) {
435
- if (target === proto) {
436
- result = true;
437
- break;
438
- }
439
- target = Object.getPrototypeOf(target);
440
- }
441
- regs[base + dst] = result;
442
- }
443
- break;
444
- }
445
-
446
- // ── Unary (dst, src) ─────────────────────────────────────────────────
447
- case OP.UNARY_NEG: {
448
- var dst = this._operand();
449
- regs[base + dst] = -regs[base + this._operand()];
450
- break;
451
- }
452
- case OP.UNARY_POS: {
453
- var dst = this._operand();
454
- regs[base + dst] = +regs[base + this._operand()];
455
- break;
456
- }
457
- case OP.UNARY_NOT: {
458
- var dst = this._operand();
459
- regs[base + dst] = !regs[base + this._operand()];
460
- break;
461
- }
462
- case OP.UNARY_BITNOT: {
463
- var dst = this._operand();
464
- regs[base + dst] = ~regs[base + this._operand()];
465
- break;
466
- }
467
- case OP.TYPEOF: {
468
- var dst = this._operand();
469
- regs[base + dst] = typeof regs[base + this._operand()];
470
- break;
471
- }
472
- case OP.VOID: {
473
- var dst = this._operand();
474
- this._operand(); // consume src — evaluated for side-effects by compiler
475
- regs[base + dst] = undefined;
476
- break;
477
- }
478
- case OP.TYPEOF_SAFE: {
479
- // dst, nameConstIdx — safe typeof for potentially-undeclared globals.
480
- var dst = this._operand();
481
- var name = this._constant();
482
- var val = Object.prototype.hasOwnProperty.call(this.globals, name)
483
- ? this.globals[name]
484
- : undefined;
485
- regs[base + dst] = typeof val;
486
- break;
487
- }
488
-
489
- // ── Control flow ──────────────────────────────────────────────────────
490
- case OP.JUMP:
491
- frame._pc = this._operand();
492
- break;
493
-
494
- case OP.JUMP_IF_FALSE: {
495
- var src = this._operand();
496
- var target = this._operand();
497
- if (!regs[base + src]) frame._pc = target;
498
- break;
499
- }
500
-
501
- case OP.JUMP_IF_TRUE: {
502
- // || short-circuit: if truthy, jump over RHS.
503
- var src = this._operand();
504
- var target = this._operand();
505
- if (regs[base + src]) frame._pc = target;
506
- break;
507
- }
508
-
509
- // ── Calls ─────────────────────────────────────────────────────────────
510
- case OP.CALL: {
511
- // dst, calleeReg, argc, [argReg...]
512
- var dst = this._operand();
513
- var callee = regs[base + this._operand()];
514
- var argc = this._operand();
515
- var args = new Array(argc);
516
- for (var i = 0; i < argc; i++) args[i] = regs[base + this._operand()];
517
-
518
- if (callee && callee[CLOSURE_SYM]) {
519
- var closure = callee[CLOSURE_SYM];
520
- var newBase = this._regsTop;
521
- this._ensureRegisterWindow(newBase, closure.fn.regCount);
522
- this._regsTop = newBase + closure.fn.regCount;
523
- var f = new Frame(
524
- closure,
525
- frame._pc,
526
- frame,
527
- this.globals,
528
- dst,
529
- newBase,
530
- );
531
- for (var i = 0; i < args.length && i < closure.fn.regCount; i++) {
532
- this._regs[newBase + i] = args[i];
533
- }
534
- if (closure.fn.paramCount < closure.fn.regCount) {
535
- this._regs[newBase + closure.fn.paramCount] = args;
536
- }
537
- this._frameStack.push(this._currentFrame);
538
- this._currentFrame = f;
539
- } else {
540
- regs[base + dst] = callee.apply(null, args);
541
- }
542
- break;
543
- }
544
-
545
- case OP.CALL_METHOD: {
546
- // dst, receiverReg, calleeReg, argc, [argReg...]
547
- var dst = this._operand();
548
- var receiver = regs[base + this._operand()];
549
- var callee = regs[base + this._operand()];
550
- var argc = this._operand();
551
- var args = new Array(argc);
552
- for (var i = 0; i < argc; i++) args[i] = regs[base + this._operand()];
553
-
554
- if (callee && callee[CLOSURE_SYM]) {
555
- var closure = callee[CLOSURE_SYM];
556
- var newBase = this._regsTop;
557
- this._ensureRegisterWindow(newBase, closure.fn.regCount);
558
- this._regsTop = newBase + closure.fn.regCount;
559
- var f = new Frame(
560
- closure,
561
- frame._pc,
562
- frame,
563
- receiver,
564
- dst,
565
- newBase,
566
- );
567
- for (var i = 0; i < args.length && i < closure.fn.regCount; i++) {
568
- this._regs[newBase + i] = args[i];
569
- }
570
- if (closure.fn.paramCount < closure.fn.regCount) {
571
- this._regs[newBase + closure.fn.paramCount] = args;
572
- }
573
- this._frameStack.push(this._currentFrame);
574
- this._currentFrame = f;
575
- } else {
576
- regs[base + dst] = callee.apply(receiver, args);
577
- }
578
- break;
579
- }
580
-
581
- case OP.NEW: {
582
- // dst, calleeReg, argc, [argReg...]
583
- var dst = this._operand();
584
- var callee = regs[base + this._operand()];
585
- var argc = this._operand();
586
- var args = new Array(argc);
587
- for (var i = 0; i < argc; i++) args[i] = regs[base + this._operand()];
588
-
589
- if (callee && callee[CLOSURE_SYM]) {
590
- var closure = callee[CLOSURE_SYM];
591
- var newObj = Object.create(closure.prototype || null);
592
- var newBase = this._regsTop;
593
- this._ensureRegisterWindow(newBase, closure.fn.regCount);
594
- this._regsTop = newBase + closure.fn.regCount;
595
- var f = new Frame(closure, frame._pc, frame, newObj, dst, newBase);
596
- for (var i = 0; i < args.length && i < closure.fn.regCount; i++) {
597
- this._regs[newBase + i] = args[i];
598
- }
599
- if (closure.fn.paramCount < closure.fn.regCount) {
600
- this._regs[newBase + closure.fn.paramCount] = args;
601
- }
602
- f._newObj = newObj;
603
- this._frameStack.push(this._currentFrame);
604
- this._currentFrame = f;
605
- } else {
606
- // Reflect.construct is required - Object.create+apply does NOT set
607
- // internal slots ([[NumberData]], [[StringData]], etc.) for built-ins.
608
- regs[base + dst] = Reflect.construct(callee, args);
609
- }
610
- break;
611
- }
612
-
613
- case OP.RETURN: {
614
- var retVal = regs[base + this._operand()];
615
- this._closeUpvaluesFor(frame); // must happen before frame is abandoned
616
- this._regsTop = frame._base;
617
-
618
- if (this._frameStack.length === 0) return retVal; // main script returning
619
-
620
- // new-call rule: primitive return -> discard, use the constructed object instead
621
- if (frame._newObj !== null) {
622
- if (typeof retVal !== "object" || retVal === null)
623
- retVal = frame._newObj;
624
- }
625
-
626
- var parentFrame = this._frameStack.pop();
627
- this._regs[parentFrame._base + frame._retDstReg] = retVal;
628
- this._currentFrame = parentFrame;
629
- break;
630
- }
631
-
632
- case OP.THROW:
633
- throw regs[base + this._operand()];
634
-
635
- // ── Closures ──────────────────────────────────────────────────────────
636
- case OP.MAKE_CLOSURE: {
637
- // dst, startPc, paramCount, regCount, uvCount, [isLocal, idx, ...]
638
- var dst = this._operand();
639
- var startPc = this._operand();
640
- var paramCount = this._operand();
641
- var regCount = this._operand();
642
- var uvCount = this._operand();
643
-
644
- var uvDescs = new Array(uvCount);
645
- for (var i = 0; i < uvCount; i++) {
646
- var isLocalRaw = this._operand();
647
- var uvIndex = this._operand();
648
- uvDescs[i] = { isLocal: isLocalRaw, _index: uvIndex };
649
- }
650
-
651
- var fn = {
652
- paramCount: paramCount,
653
- regCount: regCount,
654
- startPc: startPc,
655
- upvalueDescriptors: uvDescs,
656
- };
657
-
658
- var closure = new Closure(fn);
659
- for (var i = 0; i < uvDescs.length; i++) {
660
- var uvd = uvDescs[i];
661
- if (uvd.isLocal) {
662
- closure.upvalues.push(this.captureUpvalue(frame, uvd._index));
663
- } else {
664
- closure.upvalues.push(frame.closure.upvalues[uvd._index]);
665
- }
666
- }
667
-
668
- // Wrap in a native callable shell so host code (array methods,
669
- // test assertions, setTimeout, etc.) can invoke VM closures.
670
- // CLOSURE_SYM lets VM-internal CALL/NEW bypass the sub-VM entirely.
671
- var self = this;
672
- var shell = (function (c) {
673
- return function () {
674
- var args = Array.prototype.slice.call(arguments);
675
- var sub = new VM(
676
- self.bytecode,
677
- 0,
678
- c.fn.regCount,
679
- self.constants,
680
- self.globals,
681
- );
682
- var f = new Frame(
683
- c,
684
- null,
685
- null,
686
- this == null ? self.globals : this,
687
- 0,
688
- 0,
689
- );
690
- sub._currentFrame = f;
691
- for (var i = 0; i < args.length && i < c.fn.regCount; i++) {
692
- sub._regs[i] = args[i];
693
- }
694
- if (c.fn.paramCount < c.fn.regCount) {
695
- sub._regs[c.fn.paramCount] = args;
696
- }
697
- return sub.run();
698
- };
699
- })(closure);
700
- shell[CLOSURE_SYM] = closure;
701
- shell.prototype = closure.prototype; // unified prototype for new/instanceof
702
- regs[base + dst] = shell;
703
- break;
704
- }
705
-
706
- // ── Collections ───────────────────────────────────────────────────────
707
- case OP.BUILD_ARRAY: {
708
- // dst, count, [elemReg...]
709
- var dst = this._operand();
710
- var count = this._operand();
711
- var elems = new Array(count);
712
- for (var i = 0; i < count; i++)
713
- elems[i] = regs[base + this._operand()];
714
- regs[base + dst] = elems;
715
- break;
716
- }
717
-
718
- case OP.BUILD_OBJECT: {
719
- // dst, pairCount, [keyReg, valReg, ...]
720
- var dst = this._operand();
721
- var pairCount = this._operand();
722
- var o = {};
723
- for (var i = 0; i < pairCount; i++) {
724
- var key = regs[base + this._operand()];
725
- var val = regs[base + this._operand()];
726
- o[key] = val;
727
- }
728
- regs[base + dst] = o;
729
- break;
730
- }
731
-
732
- // ── Property definitions (getters / setters) ──────────────────────────
733
- case OP.DEFINE_GETTER: {
734
- // obj, key, fn
735
- var obj = regs[base + this._operand()];
736
- var key = regs[base + this._operand()];
737
- var getterFn = regs[base + this._operand()];
738
- var existingDesc = Object.getOwnPropertyDescriptor(obj, key);
739
- var getDesc: PropertyDescriptor = {
740
- get: getterFn,
741
- configurable: true,
742
- enumerable: true,
743
- };
744
- if (existingDesc && typeof existingDesc.set === "function") {
745
- getDesc.set = existingDesc.set;
746
- }
747
- Object.defineProperty(obj, key, getDesc);
748
- break;
749
- }
750
-
751
- case OP.DEFINE_SETTER: {
752
- // obj, key, fn
753
- var obj = regs[base + this._operand()];
754
- var key = regs[base + this._operand()];
755
- var setterFn = regs[base + this._operand()];
756
- var existingDesc = Object.getOwnPropertyDescriptor(obj, key);
757
- var setDesc: PropertyDescriptor = {
758
- set: setterFn,
759
- configurable: true,
760
- enumerable: true,
761
- };
762
- if (existingDesc && typeof existingDesc.get === "function") {
763
- setDesc.get = existingDesc.get;
764
- }
765
- Object.defineProperty(obj, key, setDesc);
766
- break;
767
- }
768
-
769
- // ── For-in iteration ──────────────────────────────────────────────────
770
- case OP.FOR_IN_SETUP: {
771
- // dst, src — build iterator object from enumerable keys of regs[src]
772
- var dst = this._operand();
773
- var obj = regs[base + this._operand()];
774
- var keys = [];
775
- if (obj !== null && obj !== undefined) {
776
- var seen = Object.create(null);
777
- var cur = Object(obj); // box primitives
778
- while (cur !== null) {
779
- var ownNames = Object.getOwnPropertyNames(cur);
780
- for (var i = 0; i < ownNames.length; i++) {
781
- var k = ownNames[i];
782
- if (!(k in seen)) {
783
- seen[k] = true;
784
- var propDesc = Object.getOwnPropertyDescriptor(cur, k);
785
- if (propDesc && propDesc.enumerable) {
786
- keys.push(k);
787
- }
788
- }
789
- }
790
- cur = Object.getPrototypeOf(cur);
791
- }
792
- }
793
- regs[base + dst] = { _keys: keys, i: 0 };
794
- break;
795
- }
796
-
797
- case OP.FOR_IN_NEXT: {
798
- // dst, iterReg, exitTarget
799
- // Advances iterator; writes next key to dst, or jumps to exitTarget when done.
800
- var dst = this._operand();
801
- var iter = regs[base + this._operand()];
802
- var exitTarget = this._operand();
803
- if (iter.i >= iter._keys.length) {
804
- frame._pc = exitTarget;
805
- } else {
806
- regs[base + dst] = iter._keys[iter.i++];
807
- }
808
- break;
809
- }
810
-
811
- // ── Exception handling ────────────────────────────────────────────────
812
- case OP.TRY_SETUP: {
813
- // handlerPc, exceptionReg — push exception handler record onto current frame.
814
- frame._handlerStack.push({
815
- handlerPc: this._operand(),
816
- exceptionReg: this._operand(),
817
- frameStackDepth: this._frameStack.length,
818
- });
819
- break;
820
- }
821
-
822
- case OP.TRY_END: {
823
- // Normal exit from a try block — disarm the exception handler.
824
- frame._handlerStack.pop();
825
- break;
826
- }
827
-
828
- // ── Self-modifying bytecode ───────────────────────────────────────────
829
- case OP.PATCH: {
830
- // destPc, sliceStart, sliceEnd
831
- var destPc = this._operand();
832
- var sliceStart = this._operand();
833
- var sliceEnd = this._operand();
834
- for (var pi = sliceStart; pi < sliceEnd; pi++) {
835
- this.bytecode[destPc + (pi - sliceStart)] = this.bytecode[pi];
836
- }
837
- break;
838
- }
839
-
840
- case OP.JUMP_REG: {
841
- // Indirect jump: target PC is read from a register rather than a
842
- // bytecode immediate. Used by the jumpDispatcher pass so that static
843
- // analysis cannot determine the jump destination without tracking the
844
- // register value (which contains an encoded PC resolved at runtime).
845
- frame._pc = regs[base + this._operand()];
846
- break;
847
- }
848
-
849
- case OP.DEBUGGER: {
850
- debugger;
851
- break;
852
- }
853
-
854
- default:
855
- throw new Error(
856
- "Unknown opcode: " + op + " at pc " + (frame._pc - 1),
857
- );
858
- }
859
- } catch (err) {
860
- // Exception handler unwinding (CPython-style frame walk, Lua-style upvalue close).
861
- // Walk from the current frame upward until we find a frame that has an open
862
- // exception handler (TRY_SETUP without a matching TRY_END).
863
- // For every frame we abandon along the way, close its captured upvalues.
864
- var handledFrame = null;
865
- var searchFrame = this._currentFrame;
866
- while (true) {
867
- if (searchFrame._handlerStack.length > 0) {
868
- handledFrame = searchFrame;
869
- break;
870
- }
871
- // No handler in this frame — abandon it and walk up.
872
- this._closeUpvaluesFor(searchFrame);
873
- this._regsTop = searchFrame._base;
874
- if (this._frameStack.length === 0) break;
875
- searchFrame = this._frameStack.pop();
876
- this._currentFrame = searchFrame;
877
- }
878
-
879
- if (!handledFrame) throw err; // no handler anywhere — propagate to host
880
-
881
- var h = handledFrame._handlerStack.pop();
882
- // Discard any call-frames that were pushed inside the try body.
883
- this._frameStack.length = h.frameStackDepth;
884
- // Write the caught exception directly into the designated register.
885
- this._regs[handledFrame._base + h.exceptionReg] = err;
886
- // Jump to the catch block.
887
- handledFrame._pc = h.handlerPc;
888
- this._regsTop = handledFrame._base + handledFrame.closure.fn.regCount;
889
- this._currentFrame = handledFrame;
890
- }
891
- }
892
- };
893
-
894
- // Boot
895
- var globals: any = {}; // global object for globals
896
-
897
- // Always pull built-ins from globalThis so eval() scoping can't shadow them
898
- // with a local `window` variable (e.g. the test harness fake window).
899
- for (var k of Object.getOwnPropertyNames(globalThis)) {
900
- globals[k] = globalThis[k];
901
- }
902
- // If a window object is in scope (browser or test harness), capture it
903
- // explicitly so VM code can read/write window.TEST_OUTPUT etc.
904
- if (typeof window !== "undefined") {
905
- globals.window = window;
906
- for (var k of Object.getOwnPropertyNames(window)) {
907
- globals[k] = window[k];
908
- }
909
- }
910
-
911
- // Transfer common primitives
912
- globals.undefined = undefined;
913
- globals.Infinity = Infinity;
914
- globals.NaN = NaN;
915
-
916
- var vm = new VM(
917
- decodeBytecode(BYTECODE),
918
- MAIN_START_PC,
919
- MAIN_REG_COUNT,
920
- CONSTANTS,
921
- globals,
922
- );
923
- vm.run();