js-confuser-vm 0.0.4 → 0.0.5

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,749 @@
1
+ import { OP_ORIGINAL as OP } from "./compiler.js";
2
+ const BYTECODE = [];
3
+ const MAIN_START_PC = 0;
4
+ const CONSTANTS = [];
5
+ const ENCODE_BYTECODE = false;
6
+ const TIMING_CHECKS = false;
7
+ // The text above is not included in the compiled output - for type intellisense only
8
+ // @START
9
+
10
+ function decodeBytecode(s) {
11
+ if (!ENCODE_BYTECODE) return s;
12
+ var b = typeof Buffer !== "undefined" ? Buffer.from(s, "base64") : Uint8Array.from(atob(s), function (c) {
13
+ return c.charCodeAt(0);
14
+ });
15
+ // Each slot is a u16 stored as 2 little-endian bytes.
16
+ var r = new Uint16Array(b.length / 2);
17
+ for (var i = 0; i < r.length; i++) r[i] = b[i * 2] | b[i * 2 + 1] << 8;
18
+ return r;
19
+ }
20
+
21
+ // Closure symbol
22
+ // Used to tag shell functions so the VM can fast-path back to the
23
+ // inner Closure instead of going through a sub-VM on internal calls.
24
+ var CLOSURE_SYM = Symbol(); // Nameless for obfuscation
25
+
26
+ // Upvalue
27
+ // While the outer frame is alive: reads/writes go to frame.locals[slot].
28
+ // After the outer frame returns (closed): reads/writes hit this.value.
29
+ function Upvalue(frame, slot) {
30
+ this._frame = frame;
31
+ this._slot = slot;
32
+ this._closed = false;
33
+ this._value = undefined;
34
+ }
35
+ Upvalue.prototype._read = function () {
36
+ return this._closed ? this._value : this._frame.locals[this._slot];
37
+ };
38
+ Upvalue.prototype._write = function (v) {
39
+ if (this._closed) this._value = v;else this._frame.locals[this._slot] = v;
40
+ };
41
+ Upvalue.prototype._close = function () {
42
+ this._value = this._frame.locals[this._slot];
43
+ this._closed = true;
44
+ };
45
+
46
+ // Closure & Frame
47
+ function Closure(fn) {
48
+ this.fn = fn;
49
+ this.upvalues = [];
50
+ this.prototype = {}; // <- default prototype object for \`new\`
51
+ }
52
+ function Frame(closure, returnPc, parent, thisVal) {
53
+ this.closure = closure;
54
+ this.locals = new Array(closure.fn.localCount).fill(undefined);
55
+ this._pc = closure.fn.startPc; // <- initialize from fn descriptor
56
+ this._returnPc = returnPc; // pc to resume in parent frame after RETURN
57
+ this._parent = parent;
58
+ this.thisVal = thisVal !== undefined ? thisVal : undefined;
59
+ this._newObj = null; // <- set by NEW so RETURN can see it
60
+ this._handlerStack = []; // <- exception handlers pushed by TRY_SETUP
61
+ }
62
+
63
+ // VM
64
+ function VM(bytecode, mainStartPc, constants, globals) {
65
+ this.bytecode = bytecode;
66
+ this.constants = constants;
67
+ this.globals = globals;
68
+ this._stack = [];
69
+ this._frameStack = [];
70
+ this._openUpvalues = []; // all currently open Upvalue objects across all frames
71
+
72
+ var mainFn = {
73
+ paramCount: 0,
74
+ localCount: 0,
75
+ startPc: mainStartPc // <- where main begins
76
+ };
77
+ this._currentFrame = new Frame(new Closure(mainFn), null, null);
78
+ }
79
+ VM.prototype._push = function (v) {
80
+ this._stack.push(v);
81
+ };
82
+ VM.prototype._pop = function () {
83
+ return this._stack.pop();
84
+ };
85
+ VM.prototype.peek = function () {
86
+ return this._stack[this._stack.length - 1];
87
+ };
88
+
89
+ // Consume the next slot from the flat bytecode stream and advance the PC.
90
+ // Called by opcode handlers to read each of their operands in order.
91
+ VM.prototype._operand = function () {
92
+ return this.bytecode[this._currentFrame._pc++];
93
+ };
94
+ VM.prototype.captureUpvalue = function (frame, slot) {
95
+ // Reuse existing open upvalue for this frame+slot if one exists.
96
+ // This is what makes two closures share the same mutable cell.
97
+ for (var i = 0; i < this._openUpvalues.length; i++) {
98
+ var uv = this._openUpvalues[i];
99
+ if (uv._frame === frame && uv._slot === slot) return uv;
100
+ }
101
+ var uv = new Upvalue(frame, slot);
102
+ this._openUpvalues.push(uv);
103
+ return uv;
104
+ };
105
+ VM.prototype._closeUpvaluesFor = function (frame) {
106
+ // Called on RETURN - close every upvalue that was pointing into this frame.
107
+ // After this, closures that captured from the frame read from upvalue.value.
108
+ this._openUpvalues = this._openUpvalues.filter(function (uv) {
109
+ if (uv._frame === frame) {
110
+ uv._close();
111
+ return false;
112
+ }
113
+ return true;
114
+ });
115
+ };
116
+ VM.prototype.run = function () {
117
+ var now = () => {
118
+ return performance.now();
119
+ };
120
+ var lastTime = now();
121
+ while (true) {
122
+ var frame = this._currentFrame;
123
+ var bc = this.bytecode;
124
+ if (frame._pc >= bc.length) break;
125
+ var op = this.bytecode[frame._pc++];
126
+
127
+ // console.log(frame._pc - 1, op);
128
+
129
+ // Debugging protection: Detects debugger by checking for >1s pauses which can only happen from debugger; or extremely slow sync tasks
130
+ if (TIMING_CHECKS) {
131
+ var currentTime = now();
132
+ var isTamper = currentTime - lastTime > 1000;
133
+ lastTime = currentTime;
134
+ if (isTamper) {
135
+ // Poison the bytecode
136
+ for (var i = 0; i < this.bytecode.length; i++) this.bytecode[i] = 0;
137
+ // Break the current state
138
+ op = OP.POP;
139
+ this._stack = [];
140
+ }
141
+ }
142
+ try {
143
+ /* @SWITCH */
144
+ switch (op) {
145
+ case OP.LOAD_CONST:
146
+ this._push(this.constants[this._operand()]);
147
+ break;
148
+ case OP.LOAD_INT:
149
+ this._push(this._operand());
150
+ break;
151
+ case OP.LOAD_LOCAL:
152
+ this._push(frame.locals[this._operand()]);
153
+ break;
154
+ case OP.STORE_LOCAL:
155
+ frame.locals[this._operand()] = this._pop();
156
+ break;
157
+ case OP.LOAD_GLOBAL:
158
+ this._push(this.globals[this.constants[this._operand()]]);
159
+ break;
160
+ case OP.STORE_GLOBAL:
161
+ this.globals[this.constants[this._operand()]] = this._pop();
162
+ break;
163
+ case OP.GET_PROP:
164
+ {
165
+ // Stack: [..., obj, key] -> [..., obj, obj[key]]
166
+ // obj is PEEKED (not popped) - CALL_METHOD needs it as receiver
167
+ var key = this._pop();
168
+ var obj = this.peek();
169
+ this._push(obj[key]);
170
+ break;
171
+ }
172
+ case OP.ADD:
173
+ {
174
+ var b = this._pop();
175
+ this._push(this._pop() + b);
176
+ break;
177
+ }
178
+ case OP.SUB:
179
+ {
180
+ var b = this._pop();
181
+ this._push(this._pop() - b);
182
+ break;
183
+ }
184
+ case OP.MUL:
185
+ {
186
+ var b = this._pop();
187
+ this._push(this._pop() * b);
188
+ break;
189
+ }
190
+ case OP.DIV:
191
+ {
192
+ var b = this._pop();
193
+ this._push(this._pop() / b);
194
+ break;
195
+ }
196
+ case OP.MOD:
197
+ {
198
+ var b = this._pop();
199
+ this._push(this._pop() % b);
200
+ break;
201
+ }
202
+ case OP.BAND:
203
+ {
204
+ var b = this._pop();
205
+ this._push(this._pop() & b);
206
+ break;
207
+ }
208
+ case OP.BOR:
209
+ {
210
+ var b = this._pop();
211
+ this._push(this._pop() | b);
212
+ break;
213
+ }
214
+ case OP.BXOR:
215
+ {
216
+ var b = this._pop();
217
+ this._push(this._pop() ^ b);
218
+ break;
219
+ }
220
+ case OP.SHL:
221
+ {
222
+ var b = this._pop();
223
+ this._push(this._pop() << b);
224
+ break;
225
+ }
226
+ case OP.SHR:
227
+ {
228
+ var b = this._pop();
229
+ this._push(this._pop() >> b);
230
+ break;
231
+ }
232
+ case OP.USHR:
233
+ {
234
+ var b = this._pop();
235
+ this._push(this._pop() >>> b);
236
+ break;
237
+ }
238
+ case OP.LT:
239
+ {
240
+ var b = this._pop();
241
+ this._push(this._pop() < b);
242
+ break;
243
+ }
244
+ case OP.GT:
245
+ {
246
+ var b = this._pop();
247
+ this._push(this._pop() > b);
248
+ break;
249
+ }
250
+ case OP.EQ:
251
+ {
252
+ var b = this._pop();
253
+ this._push(this._pop() === b);
254
+ break;
255
+ }
256
+ case OP.LTE:
257
+ {
258
+ var b = this._pop();
259
+ this._push(this._pop() <= b);
260
+ break;
261
+ }
262
+ case OP.GTE:
263
+ {
264
+ var b = this._pop();
265
+ this._push(this._pop() >= b);
266
+ break;
267
+ }
268
+ case OP.NEQ:
269
+ {
270
+ var b = this._pop();
271
+ this._push(this._pop() !== b);
272
+ break;
273
+ }
274
+ case OP.LOOSE_EQ:
275
+ {
276
+ var b = this._pop();
277
+ this._push(this._pop() == b);
278
+ break;
279
+ }
280
+ case OP.LOOSE_NEQ:
281
+ {
282
+ var b = this._pop();
283
+ this._push(this._pop() != b);
284
+ break;
285
+ }
286
+ case OP.IN:
287
+ {
288
+ var b = this._pop();
289
+ this._push(this._pop() in b);
290
+ break;
291
+ }
292
+ case OP.INSTANCEOF:
293
+ {
294
+ var ctor = this._pop();
295
+ var obj = this._pop();
296
+ if (typeof ctor === "function") {
297
+ // Native constructor (e.g. Array, Date) - native instanceof is fine
298
+ this._push(obj instanceof ctor);
299
+ } else {
300
+ // VM Closure - ctor.prototype was set by MAKE_CLOSURE / user assignment.
301
+ // Walk obj's prototype chain looking for identity with ctor.prototype.
302
+ var proto = ctor.prototype; // the .prototype property on the Closure
303
+ var target = Object.getPrototypeOf(obj);
304
+ var result = false;
305
+ while (target !== null) {
306
+ if (target === proto) {
307
+ result = true;
308
+ break;
309
+ }
310
+ target = Object.getPrototypeOf(target);
311
+ }
312
+ this._push(result);
313
+ }
314
+ break;
315
+ }
316
+ case OP.UNARY_NEG:
317
+ this._push(-this._pop());
318
+ break;
319
+ case OP.UNARY_POS:
320
+ this._push(this._pop());
321
+ break;
322
+ case OP.UNARY_NOT:
323
+ this._push(!this._pop());
324
+ break;
325
+ case OP.UNARY_BITNOT:
326
+ this._push(~this._pop());
327
+ break;
328
+ case OP.TYPEOF:
329
+ this._push(typeof this._pop());
330
+ break;
331
+ case OP.VOID:
332
+ this._pop();
333
+ this._push(undefined);
334
+ break;
335
+ case OP.TYPEOF_SAFE:
336
+ {
337
+ // operand is a const index holding the variable name string.
338
+ // Mimics JS semantics: typeof undeclaredVar === "undefined" (no throw).
339
+ var name = this._pop(); // LOAD_CONST pushed the name - consume it
340
+ var val = Object.prototype.hasOwnProperty.call(this.globals, name) ? this.globals[name] : undefined;
341
+ this._push(typeof val);
342
+ break;
343
+ }
344
+ case OP.JUMP:
345
+ frame._pc = this._operand();
346
+ break;
347
+ case OP.JUMP_IF_FALSE:
348
+ {
349
+ var target = this._operand();
350
+ if (!this._pop()) frame._pc = target;
351
+ break;
352
+ }
353
+ case OP.JUMP_IF_TRUE_OR_POP:
354
+ {
355
+ // || semantics: if truthy, we're done - leave value, jump over RHS.
356
+ // If falsy, discard it and fall through to evaluate RHS.
357
+ var target = this._operand();
358
+ if (this.peek()) {
359
+ frame._pc = target;
360
+ } else {
361
+ this._pop();
362
+ }
363
+ break;
364
+ }
365
+ case OP.JUMP_IF_FALSE_OR_POP:
366
+ {
367
+ // && semantics: if falsy, we're done - leave value, jump over RHS.
368
+ // If truthy, discard it and fall through to evaluate RHS.
369
+ var target = this._operand();
370
+ if (!this.peek()) {
371
+ frame._pc = target;
372
+ } else {
373
+ this._pop();
374
+ }
375
+ break;
376
+ }
377
+ case OP.MAKE_CLOSURE:
378
+ {
379
+ // Inline operands: startPc, paramCount, localCount, uvCount,
380
+ // [isLocal_0, idx_0, isLocal_1, idx_1, ...]
381
+ var startPc = this._operand();
382
+ var paramCount = this._operand();
383
+ var localCount = this._operand();
384
+ var uvCount = this._operand();
385
+ var uvDescs = new Array(uvCount);
386
+ for (var i = 0; i < uvCount; i++) {
387
+ var isLocalRaw = this._operand();
388
+ var uvIndex = this._operand();
389
+ uvDescs[i] = {
390
+ isLocal: isLocalRaw,
391
+ _index: uvIndex
392
+ };
393
+ }
394
+ var fn = {
395
+ paramCount: paramCount,
396
+ localCount: localCount,
397
+ startPc: startPc,
398
+ upvalueDescriptors: uvDescs
399
+ };
400
+ var closure = new Closure(fn);
401
+ for (var i = 0; i < uvDescs.length; i++) {
402
+ var uvd = uvDescs[i];
403
+ if (uvd.isLocal) {
404
+ // Capture directly from current frame's local slot
405
+ closure.upvalues.push(this.captureUpvalue(frame, uvd._index));
406
+ } else {
407
+ // Relay - take upvalue from the enclosing closure's list
408
+ closure.upvalues.push(frame.closure.upvalues[uvd._index]);
409
+ }
410
+ }
411
+ // Wrap in a native callable shell so host code (array methods,
412
+ // test assertions, setTimeout, etc.) can invoke VM closures.
413
+ // CLOSURE_SYM lets VM-internal CALL/NEW bypass the sub-VM entirely.
414
+ var self = this;
415
+ var shell = function (c) {
416
+ return function () {
417
+ var args = Array.prototype.slice.call(arguments);
418
+ var sub = new VM(self.bytecode, 0, self.constants, self.globals);
419
+ // Sloppy-mode: null/undefined thisArg → global object
420
+ var f = new Frame(c, null, null, this == null ? self.globals : this);
421
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
422
+ f.locals[c.fn.paramCount] = args;
423
+ sub._currentFrame = f;
424
+ return sub.run();
425
+ };
426
+ }(closure);
427
+ shell[CLOSURE_SYM] = closure;
428
+ shell.prototype = closure.prototype; // unified prototype for new/instanceof
429
+ this._push(shell);
430
+ break;
431
+ }
432
+ case OP.LOAD_UPVALUE:
433
+ this._push(frame.closure.upvalues[this._operand()]._read());
434
+ break;
435
+ case OP.STORE_UPVALUE:
436
+ frame.closure.upvalues[this._operand()]._write(this._pop());
437
+ break;
438
+ case OP.BUILD_ARRAY:
439
+ {
440
+ var elems = this._stack.splice(this._stack.length - this._operand());
441
+ this._push(elems);
442
+ break;
443
+ }
444
+ case OP.BUILD_OBJECT:
445
+ {
446
+ // Stack has: key0, val0, key1, val1 ... keyN, valN (pushed left->right)
447
+ // Pop all pairs and build the object.
448
+ var pairs = this._stack.splice(this._stack.length - this._operand() * 2);
449
+ var o = {};
450
+ for (var i = 0; i < pairs.length; i += 2) {
451
+ o[pairs[i]] = pairs[i + 1]; // key at even index, val at odd
452
+ }
453
+ this._push(o);
454
+ break;
455
+ }
456
+ case OP.SET_PROP:
457
+ {
458
+ // Stack: [..., obj, key, val]
459
+ // Leaves val on stack - assignment is an expression in JS.
460
+ var val = this._pop();
461
+ var key = this._pop();
462
+ var obj = this._pop();
463
+ // Reflect.set performs [[Set]] without throwing on failure,
464
+ // correctly simulating sloppy-mode assignment from a strict-mode host
465
+ // (output.js is an ES module). This also properly invokes inherited
466
+ // or prototype-chain setter functions.
467
+ Reflect.set(obj, key, val);
468
+ this._push(val); // assignment expression evaluates to the assigned value
469
+ break;
470
+ }
471
+ case OP.GET_PROP_COMPUTED:
472
+ {
473
+ // Stack: [..., obj, key] - key is a runtime value (nums[i])
474
+ // Mirrors GET_PROP but pops the key that was pushed dynamically.
475
+ var key = this._pop();
476
+ var obj = this._pop();
477
+ this._push(obj[key]);
478
+ break;
479
+ }
480
+ case OP.DELETE_PROP:
481
+ {
482
+ var key = this._pop();
483
+ var obj = this._pop();
484
+ this._push(delete obj[key]);
485
+ break;
486
+ }
487
+ case OP.CALL:
488
+ {
489
+ var args = this._stack.splice(this._stack.length - this._operand());
490
+ var callee = this._pop();
491
+ if (callee && callee[CLOSURE_SYM]) {
492
+ // VM closure - run directly in this VM, no sub-VM overhead
493
+ var c = callee[CLOSURE_SYM];
494
+ // Sloppy-mode: plain function call → global object as this
495
+ var f = new Frame(c, frame._pc, frame, this.globals);
496
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
497
+ f.locals[c.fn.paramCount] = args;
498
+ this._frameStack.push(this._currentFrame);
499
+ this._currentFrame = f;
500
+ } else {
501
+ // Native function
502
+ this._push(callee.apply(null, args));
503
+ }
504
+ break;
505
+ }
506
+ case OP.CALL_METHOD:
507
+ {
508
+ var args = this._stack.splice(this._stack.length - this._operand());
509
+ var callee = this._pop();
510
+ var receiver = this._pop(); // left on stack by GET_PROP
511
+ if (callee && callee[CLOSURE_SYM]) {
512
+ // VM closure - run directly in this VM with receiver as this
513
+ var c = callee[CLOSURE_SYM];
514
+ var f = new Frame(c, frame._pc, frame, receiver);
515
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
516
+ f.locals[c.fn.paramCount] = args;
517
+ this._frameStack.push(this._currentFrame);
518
+ this._currentFrame = f;
519
+ } else {
520
+ // Native method
521
+ this._push(callee.apply(receiver, args));
522
+ }
523
+ break;
524
+ }
525
+ case OP.LOAD_THIS:
526
+ this._push(frame.thisVal);
527
+ break;
528
+ case OP.NEW:
529
+ {
530
+ var args = this._stack.splice(this._stack.length - this._operand());
531
+ var callee = this._pop();
532
+ if (callee && callee[CLOSURE_SYM]) {
533
+ // VM closure constructor - prototype is unified via shell.prototype = closure.prototype
534
+ var c = callee[CLOSURE_SYM];
535
+ var newObj = Object.create(c.prototype || null);
536
+ var f = new Frame(c, frame._pc, frame, newObj);
537
+ f._newObj = newObj;
538
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
539
+ f.locals[c.fn.paramCount] = args;
540
+ this._frameStack.push(this._currentFrame);
541
+ this._currentFrame = f;
542
+ } else {
543
+ // Native constructor (e.g. new Error(), new Date()).
544
+ // Reflect.construct is required - Object.create+apply does NOT set
545
+ // internal slots ([[NumberData]], [[StringData]], etc.) for built-ins.
546
+ this._push(Reflect.construct(callee, args));
547
+ }
548
+ break;
549
+ }
550
+ case OP.RETURN:
551
+ {
552
+ var retVal = this._pop();
553
+ this._closeUpvaluesFor(frame); // must happen before frame is abandoned
554
+ if (this._frameStack.length === 0) return retVal;
555
+
556
+ // new-call rule: primitive return -> discard, use the constructed object instead
557
+ if (frame._newObj !== null) {
558
+ if (typeof retVal !== "object" || retVal === null) retVal = frame._newObj;
559
+ }
560
+ this._currentFrame = this._frameStack.pop();
561
+ this._push(retVal);
562
+ break;
563
+ }
564
+ case OP.POP:
565
+ this._pop();
566
+ break;
567
+ case OP.DUP:
568
+ this._push(this.peek());
569
+ break;
570
+ case OP.THROW:
571
+ throw this._pop();
572
+ case OP.FOR_IN_SETUP:
573
+ {
574
+ // Pop the object; build an ordered list of all enumerable own+inherited
575
+ // string keys by walking the prototype chain manually.
576
+ // Uses getOwnPropertyNames (includes non-enumerable) + descriptor check,
577
+ // so we never rely on Object.keys() and we handle inheritance correctly.
578
+ var obj = this._pop();
579
+ var keys = [];
580
+ if (obj !== null && obj !== undefined) {
581
+ var seen = Object.create(null);
582
+ var cur = Object(obj); // box primitives
583
+ while (cur !== null) {
584
+ var ownNames = Object.getOwnPropertyNames(cur);
585
+ for (var i = 0; i < ownNames.length; i++) {
586
+ var k = ownNames[i];
587
+ if (!(k in seen)) {
588
+ seen[k] = true;
589
+ var propDesc = Object.getOwnPropertyDescriptor(cur, k);
590
+ if (propDesc && propDesc.enumerable) {
591
+ keys.push(k);
592
+ }
593
+ }
594
+ }
595
+ cur = Object.getPrototypeOf(cur);
596
+ }
597
+ }
598
+ this._push({
599
+ _keys: keys,
600
+ i: 0
601
+ });
602
+ break;
603
+ }
604
+ case OP.FOR_IN_NEXT:
605
+ {
606
+ // Operand = jump target for the done case. Must be read before the
607
+ // conditional so the PC stays correctly aligned either way.
608
+ var target = this._operand();
609
+ var iter = this._pop();
610
+ if (iter.i >= iter._keys.length) {
611
+ frame._pc = target;
612
+ } else {
613
+ this._push(iter._keys[iter.i++]);
614
+ }
615
+ break;
616
+ }
617
+ case OP.PATCH:
618
+ {
619
+ // Inline operands: destPc, sliceStart, sliceEnd
620
+ // Copies bytecode[sliceStart..sliceEnd) flat u16 slots to destPc.
621
+ var destPc = this._operand();
622
+ var sliceStart = this._operand();
623
+ var sliceEnd = this._operand();
624
+ for (var pi = sliceStart; pi < sliceEnd; pi++) {
625
+ this.bytecode[destPc + (pi - sliceStart)] = this.bytecode[pi];
626
+ }
627
+ break;
628
+ }
629
+ case OP.TRY_SETUP:
630
+ {
631
+ // Push an exception handler record onto the current frame.
632
+ // Saves: catch PC (operand), current stack depth, current frame-stack depth.
633
+ // If an exception is thrown before TRY_END fires, the VM jumps here.
634
+ frame._handlerStack.push({
635
+ handlerPc: this._operand(),
636
+ stackDepth: this._stack.length,
637
+ frameStackDepth: this._frameStack.length
638
+ });
639
+ break;
640
+ }
641
+ case OP.TRY_END:
642
+ {
643
+ // Normal exit from a try block — disarm the exception handler.
644
+ frame._handlerStack.pop();
645
+ break;
646
+ }
647
+ case OP.DEFINE_GETTER:
648
+ {
649
+ // Stack: [..., obj, key, getterFn]
650
+ // Pops all three; defines an enumerable, configurable getter on obj.
651
+ // If a setter was already defined for this key, it is preserved.
652
+ var getterFn = this._pop();
653
+ var key = this._pop();
654
+ var obj = this._pop();
655
+ var existingDesc = Object.getOwnPropertyDescriptor(obj, key);
656
+ var getDesc = {
657
+ get: getterFn,
658
+ configurable: true,
659
+ enumerable: true
660
+ };
661
+ if (existingDesc && typeof existingDesc.set === "function") {
662
+ getDesc.set = existingDesc.set;
663
+ }
664
+ Object.defineProperty(obj, key, getDesc);
665
+ break;
666
+ }
667
+ case OP.DEFINE_SETTER:
668
+ {
669
+ // Stack: [..., obj, key, setterFn]
670
+ // Pops all three; defines an enumerable, configurable setter on obj.
671
+ // If a getter was already defined for this key, it is preserved.
672
+ var setterFn = this._pop();
673
+ var key = this._pop();
674
+ var obj = this._pop();
675
+ var existingDesc = Object.getOwnPropertyDescriptor(obj, key);
676
+ var setDesc = {
677
+ set: setterFn,
678
+ configurable: true,
679
+ enumerable: true
680
+ };
681
+ if (existingDesc && typeof existingDesc.get === "function") {
682
+ setDesc.get = existingDesc.get;
683
+ }
684
+ Object.defineProperty(obj, key, setDesc);
685
+ break;
686
+ }
687
+ case OP.DEBUGGER:
688
+ {
689
+ debugger;
690
+ break;
691
+ }
692
+ default:
693
+ throw new Error("Unknown opcode: " + op + " at pc " + (frame._pc - 1));
694
+ }
695
+ } catch (err) {
696
+ // Exception handler unwinding (CPython-style frame walk, Lua-style upvalue close).
697
+ // Walk from the current frame upward until we find a frame that has an open
698
+ // exception handler (TRY_SETUP without a matching TRY_END).
699
+ // For every frame we abandon along the way, close its captured upvalues.
700
+ var handledFrame = null;
701
+ var searchFrame = this._currentFrame;
702
+ while (true) {
703
+ if (searchFrame._handlerStack.length > 0) {
704
+ handledFrame = searchFrame;
705
+ break;
706
+ }
707
+ // No handler in this frame — abandon it and walk up.
708
+ this._closeUpvaluesFor(searchFrame);
709
+ if (this._frameStack.length === 0) break;
710
+ searchFrame = this._frameStack.pop();
711
+ this._currentFrame = searchFrame;
712
+ }
713
+ if (!handledFrame) throw err; // no handler anywhere — propagate to host
714
+
715
+ var h = handledFrame._handlerStack.pop();
716
+ // Restore the VM value stack to the depth recorded at TRY_SETUP time,
717
+ // then push the caught exception so the catch binding can store it.
718
+ this._stack.length = h.stackDepth;
719
+ this._push(err);
720
+ // Discard any call-frames that were pushed inside the try body
721
+ // (functions called from within the try block that are still live).
722
+ this._frameStack.length = h.frameStackDepth;
723
+ // Jump to the catch block.
724
+ handledFrame._pc = h.handlerPc;
725
+ this._currentFrame = handledFrame;
726
+ }
727
+ }
728
+ };
729
+
730
+ // Boot
731
+ var globals = {}; // global object for globals
732
+
733
+ // Always pull built-ins from globalThis so eval() scoping can't shadow them
734
+ // with a local `window` variable (e.g. the test harness fake window).
735
+ for (var k of Object.getOwnPropertyNames(globalThis)) {
736
+ globals[k] = globalThis[k];
737
+ }
738
+ // If a window object is in scope (browser or test harness), capture it
739
+ // explicitly so VM code can read/write window.TEST_OUTPUT etc.
740
+ if (typeof window !== "undefined") {
741
+ globals["window"] = window;
742
+ }
743
+
744
+ // Transfer common primitives
745
+ globals.undefined = undefined;
746
+ globals.Infinity = Infinity;
747
+ globals.NaN = NaN;
748
+ var vm = new VM(decodeBytecode(BYTECODE), MAIN_START_PC, CONSTANTS, globals);
749
+ vm.run();