Repository navigation
Expand file tree
/
Copy pathxsbug-debugmachine.js
More file actions
3159 lines (2895 loc) · 93 KB
/
Copy pathxsbug-debugmachine.js
File metadata and controls
3159 lines (2895 loc) · 93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022-2026 Moddable Tech, Inc.
*
* This file is part of the Moddable SDK Tools.
*
* The Moddable SDK Tools is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Moddable SDK Tools is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Moddable SDK Tools. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
Generated by Claude Code and Google Antigravity. Beware.
*/
const fs = require('node:fs');
const { Machine } = require('./xsbug-machine.js');
const { TestRunner } = require('./xsbug-test.js');
class DebugMachine extends Machine {
// View data from the protocol
view = {};
// Log accumulation (from LogMachine)
log = "";
binaryOutput = null;
// Debugger state
broken = false;
running = false;
connected = false;
// Current stop location
currentPath = null;
currentLine = null;
// Known file paths (collected from frames)
knownPaths = new Set();
// Settings
exceptionsMode = 'off';
breakOnStart = false;
// Timestamps on device traces: 'off', 'time', 'delta', 'elapsed', 'iso', 'epoch'
timestamps = 'off';
// Reference points for 'delta' and 'elapsed' (host arrival times, in ms). Shared by every
// thread: traces from all threads interleave in one console, so the timeline must be one
// timeline — a per-thread delta would hide the time for events to travel between threads.
static sessionTime = null;
static lastLogTime = null;
// User breakpoints: array of { path, line }
breakpoints = [];
// Source file cache: path -> lines array
sourceCache = {};
// Last list position: { path, line } for "list" continuation
listPosition = null;
// Command history
lastCommand = '';
// Prompt state
promptShown = false;
// Pending callback for async toggle/view updates
pendingViewCallback = null;
pendingViewName = null;
// command output format "text" or "JSON"
outputFormat = 'text';
completionsShown = false;
completer(line, callback) {
const finish = (result) => {
let [completions, matched] = result;
// Nothing to complete if only match is what's already typed
if (completions.length === 1 && completions[0] === matched)
completions = [];
if (completions.length > 1) {
if (!this.completionsShown)
this._displayCompletions(completions);
// The list is ours to show. Hand readline only a longer common prefix to insert, never the list:
// on a second consecutive tab it would print its own table and redraw the prompt below it.
let prefix = completions[0];
for (const completion of completions) {
let i = 0;
while ((i < prefix.length) && (i < completion.length) && (prefix[i] === completion[i])) i++;
prefix = prefix.slice(0, i);
}
completions = (prefix.length > matched.length) ? [prefix] : [];
}
callback(null, [completions, matched]);
};
if (this.broken) {
const args = line.trimStart().split(/\s+/);
const cmd = args[0];
if (cmd === 'print' || cmd === 'p') {
const expr = line.substring(line.indexOf(cmd) + cmd.length).trimLeft();
if (expr && expr.includes('.')) {
this._expandForCompletion(expr, () => {
finish(this._syncCompleter(line));
});
return;
}
if (expr) {
// Expand (..) in globals so built-ins are available for completion
this._expandGlobalPrototype(() => {
finish(this._syncCompleter(line));
});
return;
}
}
}
finish(this._syncCompleter(line));
}
_displayCompletions(completions) {
const width = process.stdout.columns || 80;
const maxLen = Math.max(...completions.map(c => c.length)) + 2;
const cols = Math.max(1, Math.floor((width - 1) / maxLen)); // a row must stay short of the width, or the terminal wraps before our newline and the cursor math is off by one
let out = '';
for (let i = 0; i < completions.length; i++) {
out += completions[i].padEnd(maxLen);
if ((i + 1) % cols === 0) out += '\r\n';
}
if (completions.length % cols !== 0) out += '\r\n';
// Count lines written (initial newline + completion rows)
const linesDown = (out.match(/\n/g) || []).length + 1;
// Write completions below, move cursor back up to prompt
process.stdout.write(`\r\n${out}\x1b[${linesDown}A`);
// Position cursor at end of current input
const col = (this.rl._prompt || '').length + this.rl.line.length;
process.stdout.write(`\r\x1b[${col}C`);
this.completionsShown = true;
// Clear completions on next non-TAB keypress
const handler = (str, key) => {
if (key && key.name === 'tab')
return;
const col = (this.rl._prompt || '').length + this.rl.line.length;
process.stdout.write(`\r\n\x1b[J\x1b[A\r\x1b[${col}C`);
this.completionsShown = false;
process.stdin.removeListener('keypress', handler);
};
process.stdin.on('keypress', handler);
}
_expandGlobalPrototype(callback) {
const globals = this.view.global || [];
const dotdot = globals.find(i => i.name === '(..)');
if (dotdot && this.isExpandable(dotdot) && !dotdot.children) {
this.toggleOpen(dotdot, () => this._expandGlobalPrototype(callback));
return;
}
callback();
}
_expandForCompletion(expr, callback) {
const parts = [];
const regex = /\["([^"]*)"?\]?|\['([^']*)'?\]?|\[`([^`]*)`?\]?|(\[[0-9]*\]?)|\.([^.\[]*)|^([^.\[]+)/g;
let match;
while ((match = regex.exec(expr)) !== null) {
let val;
if (match[1] !== undefined) val = match[1];
else if (match[2] !== undefined) val = match[2];
else if (match[3] !== undefined) val = match[3];
else if (match[4] !== undefined) val = match[4];
else if (match[5] !== undefined) val = match[5];
else if (match[6] !== undefined) val = match[6];
if (val !== undefined) parts.push(val);
}
if (parts.length < 2) {
callback();
return;
}
const locals = this.view.local || [];
const globals = this.view.global || [];
let items;
let startIndex;
if (parts[0] === 'globalThis' || parts[0] === 'global') {
items = globals;
startIndex = 1;
} else {
let root = locals.find(i => i.name === parts[0]);
if (!root) root = globals.find(i => i.name === parts[0]);
if (!root) {
// Search globals as if globalThis — Date, Math, etc. live there
items = globals;
startIndex = 0;
} else {
if (this.isExpandable(root) && !root.children) {
this.toggleOpen(root, () => this._expandForCompletion(expr, callback));
return;
}
items = root.children;
startIndex = 1;
}
}
this._expandPath(expr, items, parts, startIndex, callback);
}
_expandNextPrototype(items, expr, callback, visited = new Set()) {
const dotdot = items.find(i => i.name === '(..)');
if (!dotdot || !dotdot.value) return false;
if (visited.has(dotdot.value)) return false;
visited.add(dotdot.value);
if (this.isExpandable(dotdot) && !dotdot.children) {
this.toggleOpen(dotdot, () => this._expandForCompletion(expr, callback));
return true;
}
if (dotdot.children)
return this._expandNextPrototype(dotdot.children, expr, callback, visited);
return false;
}
_expandPath(expr, items, parts, index, callback) {
if (!items || index >= parts.length - 1) {
if (items) {
const needsExpand = items.find(c =>
this.isPrivateContainer(c) && this.isExpandable(c) && !c.children
);
if (needsExpand) {
this.toggleOpen(needsExpand, () => {
this._expandForCompletion(expr, callback);
});
return;
}
if (this._expandNextPrototype(items, expr, callback))
return;
}
callback();
return;
}
const name = parts[index];
// Expand unexpanded private containers before searching #fields
if (name.startsWith('#')) {
const unexpandedContainer = items.find(i =>
this.isPrivateContainer(i) && this.isExpandable(i) && !i.children
);
if (unexpandedContainer) {
this.toggleOpen(unexpandedContainer, () => this._expandForCompletion(expr, callback));
return;
}
}
// Expand (..) if it's needed but not yet expanded
const dotdot = items.find(i => i.name === '(..)');
if (dotdot && this.isExpandable(dotdot) && !dotdot.children) {
// Only expand if the name isn't found directly
if (!items.find(i => i.name === name)) {
this.toggleOpen(dotdot, () => this._expandForCompletion(expr, callback));
return;
}
}
const item = this.findProperty(items, name);
if (!item) {
callback();
return;
}
if (this.isExpandable(item) && !item.children) {
this.toggleOpen(item, () => this._expandForCompletion(expr, callback));
return;
}
this._expandPath(expr, item.children, parts, index + 1, callback);
}
_syncCompleter(line) {
const commands = ['run', 'continue', 'next', 'step', 'finish', 'until', 'break', 'clear', 'delete', 'condition', 'trace', 'hitcount', 'eval', 'info', 'list', 'backtrace', 'where', 'frame', 'print', 'set', 'quit', 'help', 'thread', 'test'];
const args = line.trimStart().split(/\s+/);
if (args.length === 1 && !line.match(/\s$/)) {
const hits = commands.filter(c => c.startsWith(args[0]));
return [hits.length ? hits : commands, args[0]];
}
const cmd = args[0];
// If line ends with space, the prefix being typed is empty
const prefix = line.match(/\s$/) ? "" : args[args.length - 1];
const argCount = line.match(/\s$/) ? args.filter(Boolean).length + 1 : args.length; // a trailing space starts a new, empty argument
if (cmd === 'info') {
const subcmds = ['breakpoints', 'locals', 'globals', 'modules', 'module', 'instruments', 'exceptions', 'start', 'threads', 'tests', 'test262'];
if (argCount === 2) {
const hits = subcmds.filter(c => c.startsWith(prefix));
return [hits.map(h => `${cmd} ${h}`), line];
}
if (argCount === 3 && (args[1] === 'module')) {
if (this.view.modules) {
const names = this.view.modules.map(m => m.name).filter(n => n !== '(map)' && n.startsWith(prefix));
return [names.map(n => `${cmd} ${args[1]} ${n}`), line];
}
}
}
if (cmd === 'test') {
if (argCount === 2) {
const hits = ['stop'].filter(c => c.startsWith(prefix)).concat(this.tests?.complete(prefix) ?? []);
return [hits.map(h => `${cmd} ${h}`), line];
}
}
if (cmd === 'delete' || cmd === 'clear') {
if (argCount === 2) {
const hits = ['all'].filter(c => c.startsWith(prefix));
return [hits.map(h => `${cmd} ${h}`), line];
}
}
if (cmd === 'set') {
if (argCount === 2) {
const subcmds = ['exceptions', 'output', 'mcsim', 'start', 'timestamps', 'test262', 'test'];
const hits = subcmds.filter(c => c.startsWith(prefix));
return [hits.map(h => `${cmd} ${h}`), line];
}
if (argCount === 3) {
let options = [];
if (args[1] === 'exceptions') options = ['on', 'off', 'silent'];
else if (args[1] === 'test') options = ['timeout'];
else if (args[1] === 'output') options = ['json', 'text'];
else if (args[1] === 'timestamps') options = ['on', 'off', 'time', 'delta', 'elapsed', 'iso', 'epoch'];
else if (args[1] === 'mcsim' || args[1] === 'start') options = ['on', 'off'];
else if (args[1] === 'test') options = ['timeout', 'log'];
const hits = options.filter(c => c.startsWith(prefix));
return [hits.map(h => `${cmd} ${args[1]} ${h}`), line];
}
}
if (cmd === 'print' || cmd === 'p') {
const locals = this.view.local || [];
const globals = this.view.global || [];
const expr = line.substring(cmd.length).trimLeft();
if (!expr) {
let options = [...new Set([...this.getCompletableNames(locals, ''), ...this.getCompletableNames(globals, '')])];
options.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
return [options, ''];
}
const parts = [];
const regex = /\["([^"]*)"?\]?|\['([^']*)'?\]?|\[`([^`]*)`?\]?|(\[[0-9]*\]?)|\.([^.\[]*)|^([^.\[]+)/g;
let match;
while ((match = regex.exec(expr)) !== null) {
let val;
if (match[1] !== undefined) val = match[1];
else if (match[2] !== undefined) val = match[2];
else if (match[3] !== undefined) val = match[3];
else if (match[4] !== undefined) val = match[4];
else if (match[5] !== undefined) val = match[5];
else if (match[6] !== undefined) val = match[6];
if (val !== undefined) parts.push(val);
}
const resolveDotPathCompletion = (items, partsArr, partIndex) => {
if (partIndex === partsArr.length - 1) {
return this.getCompletableNames(items, partsArr[partIndex], true);
}
const item = this.findProperty(items, partsArr[partIndex]);
if (item && item.children)
return resolveDotPathCompletion(item.children, partsArr, partIndex + 1);
return [];
};
let options = [];
if (parts.length === 1) {
const localNames = resolveDotPathCompletion(locals, parts, 0);
const globalNames = resolveDotPathCompletion(globals, parts, 0);
options = [...new Set([...localNames, ...globalNames])];
} else {
if (parts[0] === 'globalThis' || parts[0] === 'global') {
options = resolveDotPathCompletion(globals, parts, 1);
} else {
options = resolveDotPathCompletion(locals, parts, 0);
if (options.length === 0) {
options = resolveDotPathCompletion(globals, parts, 0);
}
}
options = [...new Set(options)];
}
options.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
return [options, parts[parts.length - 1]];
}
return [[], line];
}
// --- Output helpers ---
clearLine() {
// Implemented dynamically via Router in xsbug-log.js
}
showPrompt() {
if (!this.promptShown) {
this.promptShown = true;
this.rl.prompt(true);
}
}
print(text, path, line, eventType = 'print', time) {
const payload = { text };
if (path !== undefined && path !== null) payload.path = path;
if (line !== undefined && line !== null) payload.line = parseInt(line);
// Only traces from the device are timestamped. The time is when the host received
// the trace, so it trails the moment the device emitted it by the transport latency.
let stamp = '';
if (eventType === 'log') {
payload.time = time ?? Date.now();
stamp = this.formatTimestamp(payload.time);
}
this.report(eventType, payload, undefined, (data) => {
this.clearLine();
let out = data.text;
if (data.path) out = `${data.path} (${data.line}) ${out}`;
if (this.id !== undefined) out = `[Thread ${this.id}] ${out}`;
if (stamp) out = `${stamp} ${out}`;
console.log(out);
this.showPrompt();
});
}
// Returns the display prefix for a trace received at `time` (empty when timestamps are off).
// Always advances the reference points, so switching modes mid-session gives a sane first value.
formatTimestamp(time) {
const previous = DebugMachine.lastLogTime;
DebugMachine.lastLogTime = time;
DebugMachine.sessionTime ??= time;
switch (this.timestamps) {
case 'time': {
const d = new Date(time);
const pad = (value, count = 2) => String(value).padStart(count, '0');
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;
}
case 'iso':
return new Date(time).toISOString();
case 'epoch':
return String(time);
case 'delta':
return this.formatSeconds((previous === null) ? 0 : time - previous);
case 'elapsed':
return this.formatSeconds(time - DebugMachine.sessionTime);
default:
return '';
}
}
formatSeconds(ms) {
return `+${(ms / 1000).toFixed(3)}`.padStart(8);
}
commandError(message) {
const cmd = this.currentCommand || 'error';
this.report(cmd, undefined, (typeof message === 'string') ? { message } : message, (data, err) => {
this.clearLine();
console.log(err.message);
this.showPrompt();
});
}
report(event, data, error, formatter) {
if (this.outputFormat === 'json') {
this.clearLine();
const output = { event };
if (this.id !== undefined) output.thread = this.id;
if (data !== undefined && data !== null) output.data = data;
if (error !== undefined && error !== null) output.error = error;
console.log(JSON.stringify(output, null, 2));
this.showPrompt();
} else if (formatter) {
formatter(data, error);
}
}
// --- Protocol event handlers ---
onTitleChanged(title, tag) {
this.tag = tag;
this.title = title;
this.connected = true;
DebugMachine.sessionTime ??= Date.now(); // first connection anchors "set timestamps elapsed"
this.interactive = (title !== "mcsim");
this.once = true;
this.onTitleReady?.();
if (this.interactive && !this.tests?.running) // the test app reconnects after every test
this.print(`Connected to "${title}"`);
}
onParsed() {
if (this.once) {
this.once = false;
// Send <go/> BEFORE <set-all-breakpoints> to precisely match the xsbug GUI protocol initialization sequence.
// This addresses an unblocking state machine issue on certain targets (like ESP/Zephyr) when breakOnStart is active.
this.doGo();
this.doSetAllBreakpoint(this.breakpoints, this.breakOnStart, this.exceptionsMode === 'on');
this.running = true;
}
}
onViewChanged(name, items) {
if (name === 'property') {
if (items && items.length > 0) {
const prop = items[0];
if (prop && prop.value) {
const hydrateNode = (nodes, visited = new Set()) => {
if (!nodes) return;
for (const node of nodes) {
if (visited.has(node)) continue;
visited.add(node);
if (node.value === prop.value) {
node.children = prop.children;
node.flags = prop.flags;
}
if (node.children) {
hydrateNode(node.children, visited);
}
}
};
hydrateNode(this.view.local);
hydrateNode(this.view.global);
}
}
}
if (this.view[name] && name !== 'property') {
const hydrateView = (oldItems, newItems, visited = new Set()) => {
if (!oldItems || !newItems) return;
for (const newItem of newItems) {
if (visited.has(newItem.name)) continue;
visited.add(newItem.name);
const oldItem = oldItems.find(i => i.name === newItem.name);
if (oldItem) {
if (oldItem.children && (!newItem.children || newItem.children.length === 0)) {
newItem.children = oldItem.children;
// Also preserve the expanded flag if we hydrated children
if (newItem.flags && newItem.flags.charAt(0) === '+') {
newItem.flags = '-' + newItem.flags.slice(1);
}
} else if (oldItem.children && newItem.children) {
hydrateView(oldItem.children, newItem.children, new Set());
}
}
}
};
hydrateView(this.view[name], items);
}
if (name !== 'property') {
this.view[name] = items;
}
if (name === 'frames') {
for (const frame of items) {
if (frame.path)
this.knownPaths.add(frame.path);
}
}
if (this.pendingViewCallback) {
if (!this.pendingViewName || this.pendingViewName === name) {
const pendingViewCallback = this.pendingViewCallback;
this.pendingViewCallback = null;
this.pendingViewName = null;
pendingViewCallback(items, name);
}
}
}
onFileChanged(path, line) {
this.currentPath = path;
this.currentLine = line;
}
onFrameChanged(name, value) {
this.currentFrameValue = value;
}
onResult(items, data) {
let result;
if (items.length === 0) {
result = data;
}
else {
const prop = items[0];
if (!prop.children || prop.children.length === 0)
result = prop.value;
else {
let parts = [];
for (const child of prop.children) {
if (child.name && child.name !== "(..)")
parts.push(`${child.name}: ${child.value}`);
if (parts.length > 20) {
parts.push("…");
break;
}
}
result = "{ " + parts.join(", ") + " }";
}
}
this.clearLine();
console.log(result);
this.showPrompt();
}
onBroken(path, line, text) {
// Auto-continue for non-interactive connections (e.g., mcsim)
if (!this.interactive) {
this.doGo();
return;
}
this.broken = true;
this.running = false;
if (path) {
this.currentPath = path;
this.knownPaths.add(path);
}
if (line)
this.currentLine = line;
// Handle temporary breakpoint (until command)
if (this.temporaryBreakpoint) {
const temporaryBreakpoint = this.temporaryBreakpoint;
this.doClearBreakpoint(temporaryBreakpoint.path, temporaryBreakpoint.line);
// Remove from user breakpoints if it was added there
const i = this.breakpoints.findIndex(bp => bp.path === temporaryBreakpoint.path && bp.line === temporaryBreakpoint.line);
if (i >= 0)
this.breakpoints.splice(i, 1);
delete this.temporaryBreakpoint;
}
this.clearLine();
const msg = text ? text.replace(/\n$/, '') : '';
if (this.onBreakpointHit) this.onBreakpointHit();
this.report('stopped', {
path: this.currentPath ?? '',
line: this.currentLine ?? 0,
reason: msg
}, undefined, (data) => {
this.printLocation(data.reason);
this.showPrompt();
});
}
onLogged(path, line, data) {
this.log += data;
// Stamp when the first fragment arrives: a trace may be delivered in several pieces.
this.logTime ??= Date.now();
if (!this.logPath && path) {
this.logPath = path;
this.logLine = line;
this.knownPaths.add(path);
}
if (this.log.endsWith("\n")) {
if (this.log.startsWith("|:") && this.log.endsWith(":|\n")) {
const payload = this.log.slice(2, this.log.length - 3);
if (payload.startsWith("@filename ")) {
const parts = payload.split(" ");
if (parts[1])
this.binaryName = parts[1];
}
else if (payload.startsWith("@close")) {
if (this.binaryOutput) {
fs.closeSync(this.binaryOutput);
this.print(`#xsbug-log capture: ${this.binaryPath}`);
}
delete this.binaryOutput;
delete this.binaryName;
delete this.binaryPath;
}
else if (payload.startsWith("@")) {
// ignore unknown directives
}
else if (payload) {
if (!this.binaryOutput) {
this.binaryPath = process.env.MODDABLE + "/build/tmp/" + (this.binaryName ? this.binaryName : "log.bin");
this.binaryOutput = fs.openSync(this.binaryPath, "w+");
}
fs.writeSync(this.binaryOutput, Buffer.from(payload, "base64"), 0);
}
}
else if (this.log.startsWith("# Break: ")) {
// Suppress — onBroken will display this with full context
}
else if (this.log.startsWith("# Exception: ")) {
if (this.exceptionsMode !== 'silent') {
// Show exception with file/line like xsbug does
const msg = this.log.slice(0, this.log.length - 1);
this.print(msg, this.logPath, this.logLine, 'log', this.logTime);
}
}
else {
this.print(this.log.slice(0, this.log.length - 1), this.logPath, this.logLine, 'log', this.logTime);
}
this.log = "";
this.logPath = null;
this.logLine = null;
this.logTime = null;
}
}
// Bubbles carry a conversation name. The test apps use "test262" to talk to the test runner.
onBubbled(path, line, id, flags, message) {
if (id === 'test262') {
this.tests?.onMessage(this, message);
return;
}
if (this.isHidden?.()) // mcsim's own traces, unless "set mcsim on"
return;
this.report('bubble', { name: id ?? '', flags: parseInt(flags) || 0, text: message, path, line: parseInt(line) || 0 }, undefined, (data) => {
this.clearLine();
console.log(data.name ? `${data.name}: ${data.text}` : data.text);
this.showPrompt();
});
}
// The engine is waiting for the source of a module the debugger was asked to import (test fixtures).
onImport(path) {
TestRunner.answerImport(this, path);
}
onInstrumentValues(values) {
super.onInstrumentValues(values);
this.instrumentHistory ??= [];
this.instrumentHistory.push({
time: Date.now(),
readings: this.instruments.map(i => ({ name: i.name, value: i.value, unit: i.unit }))
});
// Assuming ~1 second intervals per VM, retain 5 minutes of logs
if (this.instrumentHistory.length > 300)
this.instrumentHistory.shift();
}
// --- Display helpers ---
printLocation(reason) {
// Reset list position on each stop
this.listPosition = null;
let frameLocation = {};
if (this.view.frames && this.view.frames.length > 0) {
const frame = this.view.frames[0];
frameLocation = { name: frame.name, path: frame.path, line: frame.line, shortPath: this.shortPath(frame.path) };
}
else if (this.currentPath) {
frameLocation = { path: this.currentPath, line: this.currentLine, shortPath: this.shortPath(this.currentPath) };
}
this.report('location', { ...frameLocation, reason }, undefined, (data) => {
let loc = '';
if (data.name) {
loc = `${data.name}()`;
if (data.path)
loc += ` at ${data.shortPath}:${data.line}`;
} else if (data.path) {
loc = `at ${data.shortPath}:${data.line}`;
}
if (data.reason === '# Break: breakpoint!') {
const bpIndex = this.breakpoints.findIndex(b => {
if (b.line == 0)
return b.path === data.name;
return b.path === data.path && b.line == data.line;
});
const bpNum = bpIndex >= 0 ? this.breakpoints[bpIndex].id : '?';
console.log(`Breakpoint ${bpNum}, ${loc}`);
} else if (data.reason === '# Break: step!') {
console.log(`Step, ${loc}`);
} else if (data.reason === '# Break: debugger!') {
console.log(`Debugger, ${loc}`);
} else if (data.reason && data.reason.startsWith('# Break: ')) {
let txt = data.reason.replace('# Break: ', '');
if (txt.startsWith('Error: '))
txt = 'Exception: ' + txt.slice(7);
console.log(`${txt}, ${loc}`);
} else if (data.reason) {
console.log(`${data.reason}, ${loc}`);
} else {
console.log(loc);
}
});
// Show the current source line
if (this.currentPath && this.currentLine)
this.printSourceLine(this.currentPath, this.currentLine);
}
shortPath(path) {
// Show just the filename for readability
if (!path)
return path;
const slash = path.lastIndexOf('/');
if (slash >= 0)
return path.slice(slash + 1);
return path;
}
isExpandable(item) {
return item && item.flags && item.flags.charAt(0) === '+';
}
findItem(items, name) {
if (!items)
return null;
return items.find(item => item.name === name) || null;
}
// Shared property resolution: find a named property in items,
// handling prototype→(..), #private containers, and (..) chain.
// Returns the found item or null.
findProperty(items, name) {
if (!items)
return null;
// Direct lookup
let found = items.find(i => i.name === name);
if (found)
return found;
// Map 'prototype' to (..)
if (name === 'prototype')
return items.find(i => i.name === '(..)') || null;
// Synthetic 'length' from (array) node value "N items"
if (name === 'length') {
const arr = items.find(i => i.name === '(array)');
if (arr && arr.value) {
const m = arr.value.match(/^(\d+)\s+item/);
if (m)
return { name: 'length', value: m[1], flags: ' ' };
}
}
// Accessor properties: "get X" matches lookup for "X"
found = items.find(i => i.name === 'get ' + name);
if (found)
return found;
// Search #private in (ClassName) containers
if (name.startsWith('#')) {
for (const c of items) {
if (this.isPrivateContainer(c) && c.children) {
found = c.children.find(i => i.name === name);
if (found)
return found;
}
}
return null;
}
// Walk (..) prototype chain
const dotdot = items.find(i => i.name === '(..)');
if (dotdot && dotdot.children)
return this.findProperty(dotdot.children, name);
return null;
}
// Shared completion: collect all visible property names matching a prefix.
// Traverses own properties, private containers, (..) chain, and adds synthetic 'prototype'.
getCompletableNames(items, prefix, followPrototype = true) {
if (!items)
return [];
let names = [];
// Own non-internal properties
for (const item of items) {
if (!item.name || item.name.startsWith('('))
continue;
if (item.name.startsWith(prefix))
names.push(item.name);
// Accessor "get X" / "set X" → expose "X"
if (item.name.startsWith('get ')) {
const stripped = item.name.slice(4);
if (stripped.startsWith(prefix))
names.push(stripped);
}
}
// Synthetic 'length' from (array) node
if ('length'.startsWith(prefix)) {
const arr = items.find(i => i.name === '(array)');
if (arr && arr.value && /^\d+\s+item/.test(arr.value))
names.push('length');
}
// Private fields from (ClassName) containers
for (const item of items) {
if (this.isPrivateContainer(item) && item.children) {
for (const child of item.children) {
if (child.name && child.name.startsWith(prefix))
names.push(child.name);
}
}
}
// Synthetic 'prototype' when (..) exists and no real 'prototype' property
const dotdot = items.find(i => i.name === '(..)');
if (dotdot && 'prototype'.startsWith(prefix) && !items.find(i => i.name === 'prototype'))
names.push('prototype');
// Recurse into (..) chain only when requested (top-level variable completion)
if (followPrototype && dotdot && dotdot.children)
names = names.concat(this.getCompletableNames(dotdot.children, prefix, true));
return names;
}
// Toggle an item open (expand it). After the view updates, fires callback.
// viewName optionally specifies which view to wait for (e.g. 'modules').
toggleOpen(item, callback, viewName) {
if (!this.isExpandable(item) || !item.value) {
callback();
return;
}
this.pendingViewName = viewName || 'global';
this.pendingViewCallback = (items, name) => {
if (name === 'property' && items) {
item.children = items;
item.flags = '-' + item.flags.slice(1);
}
callback();
};
this.doToggle(item.value);
}
// Format a value for display in compact WebKit-style format.
// depth 0 = expand one level of properties; depth 1+ = abbreviate.
formatValue(item, depth = 0) {
if (!item)
return 'undefined';
const val = item.value;
// Leaf node — no children, not expandable
if (!item.children && !this.isExpandable(item)) {
if (val === undefined)
return '(uninitialized)';
return this.formatLeafValue(val);
}
// Has children (expanded object) — format inline
if (item.children)
return this.formatObject(item, depth);
// Expandable but not yet expanded — format from value hint
if (val === undefined)
return '{...}';
return this.formatLeafValue(val);
}
formatLeafValue(val) {
if (val === undefined)
return '';
// Function types
if (val === '(C code)' || val === '(host function)')
return '[native]';
// XS code function — value is a file path
if (typeof val === 'string' && val.startsWith('/') && !val.startsWith("'"))
return 'function';
// Hex addresses for unexpanded objects
if (typeof val === 'string' && val.startsWith('@'))
return '{...}';
return val;
}
getClassName(children) {
if (!children)
return null;
let promiseState = null;
// Look for (ClassName) private containers and promises
for (const child of children) {