js-confuser-vm 0.0.4 → 0.0.6

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