forked from svaarala/duktape
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduk_debug.js
More file actions
executable file
·2491 lines (2182 loc) · 83.1 KB
/
duk_debug.js
File metadata and controls
executable file
·2491 lines (2182 loc) · 83.1 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
/*
* Minimal debug web console for Duktape command line tool
*
* See debugger/README.rst.
*
* The web UI socket.io communication can easily become a bottleneck and
* it's important to ensure that the web UI remains responsive. Basic rate
* limiting mechanisms (token buckets, suppressing identical messages, etc)
* are used here now. Ideally the web UI would pull data on its own terms
* which would provide natural rate limiting.
*
* Promises are used to structure callback chains.
*
* https://github.com/petkaantonov/bluebird
* https://github.com/petkaantonov/bluebird/blob/master/API.md
* https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns
*/
var Promise = require('bluebird');
var events = require('events');
var stream = require('stream');
var path = require('path');
var fs = require('fs');
var net = require('net');
var byline = require('byline');
var util = require('util');
var readline = require('readline');
var sprintf = require('sprintf').sprintf;
var utf8 = require('utf8');
var yaml = require('yamljs');
var recursiveReadSync = require('recursive-readdir-sync');
// Command line options (defaults here, overwritten if necessary)
var optTargetHost = '127.0.0.1';
var optTargetPort = 9091;
var optHttpPort = 9092;
var optJsonProxyPort = 9093;
var optJsonProxy = false;
var optSourceSearchDirs = [ '../tests/ecmascript' ];
var optDumpDebugRead = null;
var optDumpDebugWrite = null;
var optDumpDebugPretty = null;
var optLogMessages = false;
// Constants
var UI_MESSAGE_CLIPLEN = 128;
var LOCALS_CLIPLEN = 64;
var EVAL_CLIPLEN = 4096;
var GETVAR_CLIPLEN = 4096;
var SUPPORTED_DEBUG_PROTOCOL_VERSION = 2;
// Commands initiated by Duktape
var CMD_STATUS = 0x01;
var CMD_UNUSED_2 = 0x02; // Duktape 1.x: print notify
var CMD_UNUSED_3 = 0x03; // Duktape 1.x: alert notify
var CMD_UNUSED_4 = 0x04; // Duktape 1.x: log notify
var CMD_THROW = 0x05;
var CMD_DETACHING = 0x06;
// Commands initiated by the debug client (= us)
var CMD_BASICINFO = 0x10;
var CMD_TRIGGERSTATUS = 0x11;
var CMD_PAUSE = 0x12;
var CMD_RESUME = 0x13;
var CMD_STEPINTO = 0x14;
var CMD_STEPOVER = 0x15;
var CMD_STEPOUT = 0x16;
var CMD_LISTBREAK = 0x17;
var CMD_ADDBREAK = 0x18;
var CMD_DELBREAK = 0x19;
var CMD_GETVAR = 0x1a;
var CMD_PUTVAR = 0x1b;
var CMD_GETCALLSTACK = 0x1c;
var CMD_GETLOCALS = 0x1d;
var CMD_EVAL = 0x1e;
var CMD_DETACH = 0x1f;
var CMD_DUMPHEAP = 0x20;
var CMD_GETBYTECODE = 0x21;
// Errors
var ERR_UNKNOWN = 0x00;
var ERR_UNSUPPORTED = 0x01;
var ERR_TOOMANY = 0x02;
var ERR_NOTFOUND = 0x03;
// Marker objects for special protocol values
var DVAL_EOM = { type: 'eom' };
var DVAL_REQ = { type: 'req' };
var DVAL_REP = { type: 'rep' };
var DVAL_ERR = { type: 'err' };
var DVAL_NFY = { type: 'nfy' };
// String map for commands (debug dumping). A single map works (instead of
// separate maps for each direction) because command numbers don't currently
// overlap. So merge the YAML metadata.
var debugCommandMeta = yaml.load('duk_debugcommands.yaml');
var debugCommandNames = []; // list of command names, merged client/target
debugCommandMeta.target_commands.forEach(function (k, i) {
debugCommandNames[i] = k;
});
debugCommandMeta.client_commands.forEach(function (k, i) { // override
debugCommandNames[i] = k;
});
var debugCommandNumbers = {}; // map from (merged) command name to number
debugCommandNames.forEach(function (k, i) {
debugCommandNumbers[k] = i;
});
// Duktape heaphdr type constants, must match C headers
var DUK_HTYPE_STRING = 0;
var DUK_HTYPE_OBJECT = 1;
var DUK_HTYPE_BUFFER = 2;
// Duktape internal class numbers, must match C headers
var dukClassNameMeta = yaml.load('duk_classnames.yaml');
var dukClassNames = dukClassNameMeta.class_names;
// Bytecode opcode/extraop metadata
var dukOpcodes = yaml.load('duk_opcodes.yaml');
if (dukOpcodes.opcodes.length != 256) {
throw new Error('opcode metadata length incorrect');
}
/*
* Miscellaneous helpers
*/
var nybbles = '0123456789abcdef';
/* Convert a buffer into a string using Unicode codepoints U+0000...U+00FF.
* This is the NodeJS 'binary' encoding, but since it's being deprecated,
* reimplement it here. We need to avoid parsing strings as e.g. UTF-8:
* although Duktape strings are usually UTF-8/CESU-8 that's not always the
* case, e.g. for internal strings. Buffer values are also represented as
* strings in the debug protocol, so we must deal accurately with arbitrary
* byte arrays.
*/
function bufferToDebugString(buf) {
var cp = [];
var i, n;
/*
// This fails with "RangeError: Maximum call stack size exceeded" for some
// reason, so use a much slower variant.
for (i = 0, n = buf.length; i < n; i++) {
cp[i] = buf[i];
}
return String.fromCharCode.apply(String, cp);
*/
for (i = 0, n = buf.length; i < n; i++) {
cp[i] = String.fromCharCode(buf[i]);
}
return cp.join('');
}
/* Write a string into a buffer interpreting codepoints U+0000...U+00FF
* as bytes. Drop higher bits.
*/
function writeDebugStringToBuffer(str, buf, off) {
var i, n;
for (i = 0, n = str.length; i < n; i++) {
buf[off + i] = str.charCodeAt(i) & 0xff; // truncate higher bits
}
}
/* Encode an ordinary Unicode string into a dvalue compatible format, i.e.
* into a byte array represented as codepoints U+0000...U+00FF. Concretely,
* encode with UTF-8 and then represent the bytes with U+0000...U+00FF.
*/
function stringToDebugString(str) {
return utf8.encode(str);
}
/* Pretty print a dvalue. Useful for dumping etc. */
function prettyDebugValue(x) {
if (typeof x === 'object' && x !== null) {
if (x.type === 'eom') {
return 'EOM';
} else if (x.type === 'req') {
return 'REQ';
} else if (x.type === 'rep') {
return 'REP';
} else if (x.type === 'err') {
return 'ERR';
} else if (x.type === 'nfy') {
return 'NFY';
}
}
return JSON.stringify(x);
}
/* Pretty print a number for UI usage. Types and values should be easy to
* read and typing should be obvious. For numbers, support Infinity, NaN,
* and signed zeroes properly.
*/
function prettyUiNumber(x) {
if (x === 1 / 0) { return 'Infinity'; }
if (x === -1 / 0) { return '-Infinity'; }
if (Number.isNaN(x)) { return 'NaN'; }
if (x === 0 && 1 / x > 0) { return '0'; }
if (x === 0 && 1 / x < 0) { return '-0'; }
return x.toString();
}
/* Pretty print a dvalue string (bytes represented as U+0000...U+00FF)
* for UI usage. Try UTF-8 decoding to get a nice Unicode string (JSON
* encoded) but if that fails, ensure that bytes are encoded transparently.
* The result is a quoted string with a special quote marker for a "raw"
* string when UTF-8 decoding fails. Very long strings are optionally
* clipped.
*/
function prettyUiString(x, cliplen) {
var ret;
if (typeof x !== 'string') {
throw new Error('invalid input to prettyUiString: ' + typeof x);
}
try {
// Here utf8.decode() is better than decoding using NodeJS buffer
// operations because we want strict UTF-8 interpretation.
ret = JSON.stringify(utf8.decode(x));
} catch (e) {
// When we fall back to representing bytes, indicate that the string
// is "raw" with a 'r"' prefix (a somewhat arbitrary convention).
// U+0022 = ", U+0027 = '
ret = 'r"' + x.replace(/[\u0022\u0027\u0000-\u001f\u0080-\uffff]/g, function (match) {
var cp = match.charCodeAt(0);
return '\\x' + nybbles[(cp >> 4) & 0x0f] + nybbles[cp & 0x0f];
}) + '"';
}
if (cliplen && ret.length > cliplen) {
ret = ret.substring(0, cliplen) + '...'; // trailing '"' intentionally missing
}
return ret;
}
/* Pretty print a dvalue string (bytes represented as U+0000...U+00FF)
* for UI usage without quotes.
*/
function prettyUiStringUnquoted(x, cliplen) {
var ret;
if (typeof x !== 'string') {
throw new Error('invalid input to prettyUiStringUnquoted: ' + typeof x);
}
try {
// Here utf8.decode() is better than decoding using NodeJS buffer
// operations because we want strict UTF-8 interpretation.
// XXX: unprintable characters etc? In some UI cases we'd want to
// e.g. escape newlines and in others not.
ret = utf8.decode(x);
} catch (e) {
// For the unquoted version we don't need to escape single or double
// quotes.
ret = x.replace(/[\u0000-\u001f\u0080-\uffff]/g, function (match) {
var cp = match.charCodeAt(0);
return '\\x' + nybbles[(cp >> 4) & 0x0f] + nybbles[cp & 0x0f];
});
}
if (cliplen && ret.length > cliplen) {
ret = ret.substring(0, cliplen) + '...';
}
return ret;
}
/* Pretty print a dvalue for UI usage. Everything comes out as a ready-to-use
* string.
*
* XXX: Currently the debug client formats all values for UI use. A better
* solution would be to pass values in typed form and let the UI format them,
* so that styling etc. could take typing into account.
*/
function prettyUiDebugValue(x, cliplen) {
if (typeof x === 'object' && x !== null) {
// Note: typeof null === 'object', so null special case explicitly
if (x.type === 'eom') {
return 'EOM';
} else if (x.type === 'req') {
return 'REQ';
} else if (x.type === 'rep') {
return 'REP';
} else if (x.type === 'err') {
return 'ERR';
} else if (x.type === 'nfy') {
return 'NFY';
} else if (x.type === 'unused') {
return 'unused';
} else if (x.type === 'undefined') {
return 'undefined';
} else if (x.type === 'buffer') {
return '|' + x.data + '|';
} else if (x.type === 'object') {
return '[object ' + (dukClassNames[x.class] || ('class ' + x.class)) + ' ' + x.pointer + ']';
} else if (x.type === 'pointer') {
return '<pointer ' + x.pointer + '>';
} else if (x.type === 'lightfunc') {
return '<lightfunc 0x' + x.flags.toString(16) + ' ' + x.pointer + '>';
} else if (x.type === 'number') {
// duk_tval number, any IEEE double
var tmp = new Buffer(x.data, 'hex'); // decode into hex
var val = tmp.readDoubleBE(0); // big endian ieee double
return prettyUiNumber(val);
}
} else if (x === null) {
return 'null';
} else if (typeof x === 'boolean') {
return x ? 'true' : 'false';
} else if (typeof x === 'string') {
return prettyUiString(x, cliplen);
} else if (typeof x === 'number') {
// Debug protocol integer
return prettyUiNumber(x);
}
// We shouldn't come here, but if we do, JSON is a reasonable default.
return JSON.stringify(x);
}
/* Pretty print a debugger message given as an array of parsed dvalues.
* Result should be a pure ASCII one-liner.
*/
function prettyDebugMessage(msg) {
return msg.map(prettyDebugValue).join(' ');
}
/* Pretty print a debugger command. */
function prettyDebugCommand(cmd) {
return debugCommandNames[cmd] || String(cmd);
}
/* Decode and normalize source file contents: UTF-8, tabs to 8,
* CR LF to LF.
*/
function decodeAndNormalizeSource(data) {
var tmp;
var lines, line, repl;
var i, n;
var j, m;
try {
tmp = data.toString('utf8');
} catch (e) {
console.log('Failed to UTF-8 decode source file, ignoring: ' + e);
tmp = String(data);
}
lines = tmp.split(/\r?\n/);
for (i = 0, n = lines.length; i < n; i++) {
line = lines[i];
if (/\t/.test(line)) {
repl = '';
for (j = 0, m = line.length; j < m; j++) {
if (line.charAt(j) === '\t') {
repl += ' ';
while ((repl.length % 8) != 0) {
repl += ' ';
}
} else {
repl += line.charAt(j);
}
}
lines[i] = repl;
}
}
// XXX: normalize last newline (i.e. force a newline if contents don't
// end with a newline)?
return lines.join('\n');
}
/* Token bucket rate limiter for a given callback. Calling code calls
* trigger() to request 'cb' to be called, and the rate limiter ensures
* that 'cb' is not called too often.
*/
function RateLimited(tokens, rate, cb) {
var _this = this;
this.maxTokens = tokens;
this.tokens = this.maxTokens;
this.rate = rate;
this.cb = cb;
this.delayedCb = false;
// Right now the implementation is setInterval-based, but could also be
// made timerless. There are so few rate limited resources that this
// doesn't matter in practice.
this.tokenAdder = setInterval(function () {
if (_this.tokens < _this.maxTokens) {
_this.tokens++;
}
if (_this.delayedCb) {
_this.delayedCb = false;
_this.tokens--;
_this.cb();
}
}, this.rate);
}
RateLimited.prototype.trigger = function () {
if (this.tokens > 0) {
this.tokens--;
this.cb();
} else {
this.delayedCb = true;
}
};
/*
* Source file manager
*
* Scan the list of search directories for ECMAScript source files and
* build an index of them. Provides a mechanism to find a source file
* based on a raw 'fileName' property provided by the debug target, and
* to provide a file list for the web UI.
*
* NOTE: it's tempting to do loose matching for filenames, but this does
* not work in practice. Filenames must match 1:1 with the debug target
* so that e.g. breakpoints assigned based on filenames found from the
* search paths will match 1:1 on the debug target. If this is not the
* case, breakpoints won't work as expected.
*/
function SourceFileManager(directories) {
this.directories = directories;
this.extensions = { '.js': true, '.jsm': true };
this.fileMap = {}; // filename as seen by debug target -> file path
this.files = []; // filenames as seen by debug target
}
SourceFileManager.prototype.scan = function () {
var _this = this;
var fileMap = {}; // relative path -> file path
var files;
this.directories.forEach(function (dir) {
console.log('Scanning source files: ' + dir);
try {
recursiveReadSync(dir).forEach(function (fn) {
// Example: dir ../../tests
// normFn ../../tests/foo/bar.js
// relFn foo/bar.js
var normDir = path.normalize(dir);
var normFn = path.normalize(fn);
var relFn = path.relative(normDir, normFn);
if (fs.existsSync(normFn) && fs.lstatSync(normFn).isFile() &&
_this.extensions[path.extname(normFn)]) {
// We want the fileMap to contain the filename relative to
// the search dir root. First directory containing a
// certail relFn wins.
if (relFn in fileMap) {
console.log('Found', relFn, 'multiple times, first match wins');
} else {
fileMap[relFn] = normFn;
}
}
});
} catch (e) {
console.log('Failed to scan ' + dir + ': ' + e);
}
});
files = Object.keys(fileMap);
files.sort();
this.files = files;
this.fileMap = fileMap;
console.log('Found ' + files.length + ' source files in ' + this.directories.length + ' search directories');
};
SourceFileManager.prototype.getFiles = function () {
return this.files;
};
SourceFileManager.prototype.search = function (fileName) {
var _this = this;
// Loose matching is tempting but counterproductive: filenames must
// match 1:1 between the debug client and the debug target for e.g.
// breakpoints to work as expected. Note that a breakpoint may be
// assigned by selecting a file from a dropdown populated by scanning
// the filesystem for available sources and there's no way of knowing
// if the debug target uses the exact same name.
//
// We intentionally allow any files from the search paths, not just
// those scanned to this.fileMap.
function tryLookup() {
var i, fn, data;
for (i = 0; i < _this.directories.length; i++) {
fn = path.join(_this.directories[i], fileName);
if (fs.existsSync(fn) && fs.lstatSync(fn).isFile()) {
data = fs.readFileSync(fn); // Raw bytes
return decodeAndNormalizeSource(data); // Unicode string
}
}
return null;
}
return tryLookup(fileName);
};
/*
* Debug protocol parser
*
* The debug protocol parser is an EventEmitter which parses debug messages
* from an input stream and emits 'debug-message' events for completed
* messages ending in an EOM. The parser also provides debug dumping, stream
* logging functionality, and statistics gathering functionality.
*
* This parser is used to parse both incoming and outgoing messages. For
* outgoing messages the only function is to validate and debug dump the
* messages we're about to send. The downside of dumping at this low level
* is that we can't match request and reply/error messages here.
*
* http://www.sitepoint.com/nodejs-events-and-eventemitter/
*/
function DebugProtocolParser(inputStream,
protocolVersion,
rawDumpFileName,
textDumpFileName,
textDumpFilePrefix,
hexDumpConsolePrefix,
textDumpConsolePrefix) {
var _this = this;
this.inputStream = inputStream;
this.closed = false; // stream is closed/broken, don't parse anymore
this.bytes = 0;
this.dvalues = 0;
this.messages = 0;
this.requests = 0;
this.prevBytes = 0;
this.bytesPerSec = 0;
this.statsTimer = null;
this.readableNumberValue = true;
events.EventEmitter.call(this);
var buf = new Buffer(0); // accumulate data
var msg = []; // accumulated message until EOM
var versionIdentification;
var statsInterval = 2000;
var statsIntervalSec = statsInterval / 1000;
this.statsTimer = setInterval(function () {
_this.bytesPerSec = (_this.bytes - _this.prevBytes) / statsIntervalSec;
_this.prevBytes = _this.bytes;
_this.emit('stats-update');
}, statsInterval);
function consume(n) {
var tmp = new Buffer(buf.length - n);
buf.copy(tmp, 0, n);
buf = tmp;
}
inputStream.on('data', function (data) {
var i, n, x, v, gotValue, len, t, tmpbuf, verstr;
var prettyMsg;
if (_this.closed || !_this.inputStream) {
console.log('Ignoring incoming data from closed input stream, len ' + data.length);
return;
}
_this.bytes += data.length;
if (rawDumpFileName) {
fs.appendFileSync(rawDumpFileName, data);
}
if (hexDumpConsolePrefix) {
console.log(hexDumpConsolePrefix + data.toString('hex'));
}
buf = Buffer.concat([ buf, data ]);
// Protocol version handling. When dumping an output stream, the
// caller gives a non-null protocolVersion so we don't read one here.
if (protocolVersion == null) {
if (buf.length > 1024) {
_this.emit('transport-error', 'Parse error (version identification too long), dropping connection');
_this.close();
return;
}
for (i = 0, n = buf.length; i < n; i++) {
if (buf[i] == 0x0a) {
tmpbuf = new Buffer(i);
buf.copy(tmpbuf, 0, 0, i);
consume(i + 1);
verstr = tmpbuf.toString('utf-8');
t = verstr.split(' ');
protocolVersion = Number(t[0]);
versionIdentification = verstr;
_this.emit('protocol-version', {
protocolVersion: protocolVersion,
versionIdentification: versionIdentification
});
break;
}
}
if (protocolVersion == null) {
// Still waiting for version identification to complete.
return;
}
}
// Parse complete dvalues (quite inefficient now) by trial parsing.
// Consume a value only when it's fully present in 'buf'.
// See doc/debugger.rst for format description.
while (buf.length > 0) {
x = buf[0];
v = undefined;
gotValue = false; // used to flag special values like undefined
if (x >= 0xc0) {
// 0xc0...0xff: integers 0-16383
if (buf.length >= 2) {
v = ((x - 0xc0) << 8) + buf[1];
consume(2);
}
} else if (x >= 0x80) {
// 0x80...0xbf: integers 0-63
v = x - 0x80;
consume(1);
} else if (x >= 0x60) {
// 0x60...0x7f: strings with length 0-31
len = x - 0x60;
if (buf.length >= 1 + len) {
v = new Buffer(len);
buf.copy(v, 0, 1, 1 + len);
v = bufferToDebugString(v);
consume(1 + len);
}
} else {
switch (x) {
case 0x00: v = DVAL_EOM; consume(1); break;
case 0x01: v = DVAL_REQ; consume(1); break;
case 0x02: v = DVAL_REP; consume(1); break;
case 0x03: v = DVAL_ERR; consume(1); break;
case 0x04: v = DVAL_NFY; consume(1); break;
case 0x10: // 4-byte signed integer
if (buf.length >= 5) {
v = buf.readInt32BE(1);
consume(5);
}
break;
case 0x11: // 4-byte string
if (buf.length >= 5) {
len = buf.readUInt32BE(1);
if (buf.length >= 5 + len) {
v = new Buffer(len);
buf.copy(v, 0, 5, 5 + len);
v = bufferToDebugString(v);
consume(5 + len);
}
}
break;
case 0x12: // 2-byte string
if (buf.length >= 3) {
len = buf.readUInt16BE(1);
if (buf.length >= 3 + len) {
v = new Buffer(len);
buf.copy(v, 0, 3, 3 + len);
v = bufferToDebugString(v);
consume(3 + len);
}
}
break;
case 0x13: // 4-byte buffer
if (buf.length >= 5) {
len = buf.readUInt32BE(1);
if (buf.length >= 5 + len) {
v = new Buffer(len);
buf.copy(v, 0, 5, 5 + len);
v = { type: 'buffer', data: v.toString('hex') };
consume(5 + len);
// Value could be a Node.js buffer directly, but
// we prefer all dvalues to be JSON compatible
}
}
break;
case 0x14: // 2-byte buffer
if (buf.length >= 3) {
len = buf.readUInt16BE(1);
if (buf.length >= 3 + len) {
v = new Buffer(len);
buf.copy(v, 0, 3, 3 + len);
v = { type: 'buffer', data: v.toString('hex') };
consume(3 + len);
// Value could be a Node.js buffer directly, but
// we prefer all dvalues to be JSON compatible
}
}
break;
case 0x15: // unused/none
v = { type: 'unused' };
consume(1);
break;
case 0x16: // undefined
v = { type: 'undefined' };
gotValue = true; // indicate 'v' is actually set
consume(1);
break;
case 0x17: // null
v = null;
gotValue = true; // indicate 'v' is actually set
consume(1);
break;
case 0x18: // true
v = true;
consume(1);
break;
case 0x19: // false
v = false;
consume(1);
break;
case 0x1a: // number (IEEE double), big endian
if (buf.length >= 9) {
v = new Buffer(8);
buf.copy(v, 0, 1, 9);
v = { type: 'number', data: v.toString('hex') };
if (_this.readableNumberValue) {
// The value key should not be used programmatically,
// it is just there to make the dumps more readable.
v.value = buf.readDoubleBE(1);
}
consume(9);
}
break;
case 0x1b: // object
if (buf.length >= 3) {
len = buf[2];
if (buf.length >= 3 + len) {
v = new Buffer(len);
buf.copy(v, 0, 3, 3 + len);
v = { type: 'object', 'class': buf[1], pointer: v.toString('hex') };
consume(3 + len);
}
}
break;
case 0x1c: // pointer
if (buf.length >= 2) {
len = buf[1];
if (buf.length >= 2 + len) {
v = new Buffer(len);
buf.copy(v, 0, 2, 2 + len);
v = { type: 'pointer', pointer: v.toString('hex') };
consume(2 + len);
}
}
break;
case 0x1d: // lightfunc
if (buf.length >= 4) {
len = buf[3];
if (buf.length >= 4 + len) {
v = new Buffer(len);
buf.copy(v, 0, 4, 4 + len);
v = { type: 'lightfunc', flags: buf.readUInt16BE(1), pointer: v.toString('hex') };
consume(4 + len);
}
}
break;
case 0x1e: // heapptr
if (buf.length >= 2) {
len = buf[1];
if (buf.length >= 2 + len) {
v = new Buffer(len);
buf.copy(v, 0, 2, 2 + len);
v = { type: 'heapptr', pointer: v.toString('hex') };
consume(2 + len);
}
}
break;
default:
_this.emit('transport-error', 'Parse error, dropping connection');
_this.close();
}
}
if (typeof v === 'undefined' && !gotValue) {
break;
}
msg.push(v);
_this.dvalues++;
// Could emit a 'debug-value' event here, but that's not necessary
// because the receiver will just collect statistics which can also
// be done using the finished message.
if (v === DVAL_EOM) {
_this.messages++;
if (textDumpFileName || textDumpConsolePrefix) {
prettyMsg = prettyDebugMessage(msg);
if (textDumpFileName) {
fs.appendFileSync(textDumpFileName, (textDumpFilePrefix || '') + prettyMsg + '\n');
}
if (textDumpConsolePrefix) {
console.log(textDumpConsolePrefix + prettyMsg);
}
}
_this.emit('debug-message', msg);
msg = []; // new object, old may be in circulation for a while
}
}
});
// Not all streams will emit this.
inputStream.on('error', function (err) {
_this.emit('transport-error', err);
_this.close();
});
// Not all streams will emit this.
inputStream.on('close', function () {
_this.close();
});
}
DebugProtocolParser.prototype = Object.create(events.EventEmitter.prototype);
DebugProtocolParser.prototype.close = function () {
// Although the underlying transport may not have a close() or destroy()
// method or even a 'close' event, this method is always available and
// will generate a 'transport-close'.
//
// The caller is responsible for closing the underlying stream if that
// is necessary.
if (this.closed) { return; }
this.closed = true;
if (this.statsTimer) {
clearInterval(this.statsTimer);
this.statsTimer = null;
}
this.emit('transport-close');
};
/*
* Debugger output formatting
*/
function formatDebugValue(v) {
var buf, dec, len;
// See doc/debugger.rst for format description.
if (typeof v === 'object' && v !== null) {
// Note: typeof null === 'object', so null special case explicitly
if (v.type === 'eom') {
return new Buffer([ 0x00 ]);
} else if (v.type === 'req') {
return new Buffer([ 0x01 ]);
} else if (v.type === 'rep') {
return new Buffer([ 0x02 ]);
} else if (v.type === 'err') {
return new Buffer([ 0x03 ]);
} else if (v.type === 'nfy') {
return new Buffer([ 0x04 ]);
} else if (v.type === 'unused') {
return new Buffer([ 0x15 ]);
} else if (v.type === 'undefined') {
return new Buffer([ 0x16 ]);
} else if (v.type === 'number') {
dec = new Buffer(v.data, 'hex');
len = dec.length;
if (len !== 8) {
throw new TypeError('value cannot be converted to dvalue: ' + JSON.stringify(v));
}
buf = new Buffer(1 + len);
buf[0] = 0x1a;
dec.copy(buf, 1);
return buf;
} else if (v.type === 'buffer') {
dec = new Buffer(v.data, 'hex');
len = dec.length;
if (len <= 0xffff) {
buf = new Buffer(3 + len);
buf[0] = 0x14;
buf[1] = (len >> 8) & 0xff;
buf[2] = (len >> 0) & 0xff;
dec.copy(buf, 3);
return buf;
} else {
buf = new Buffer(5 + len);
buf[0] = 0x13;
buf[1] = (len >> 24) & 0xff;
buf[2] = (len >> 16) & 0xff;
buf[3] = (len >> 8) & 0xff;
buf[4] = (len >> 0) & 0xff;
dec.copy(buf, 5);
return buf;
}
} else if (v.type === 'object') {
dec = new Buffer(v.pointer, 'hex');
len = dec.length;
buf = new Buffer(3 + len);
buf[0] = 0x1b;
buf[1] = v.class;
buf[2] = len;
dec.copy(buf, 3);
return buf;
} else if (v.type === 'pointer') {
dec = new Buffer(v.pointer, 'hex');
len = dec.length;
buf = new Buffer(2 + len);
buf[0] = 0x1c;
buf[1] = len;
dec.copy(buf, 2);
return buf;
} else if (v.type === 'lightfunc') {
dec = new Buffer(v.pointer, 'hex');
len = dec.length;
buf = new Buffer(4 + len);
buf[0] = 0x1d;
buf[1] = (v.flags >> 8) & 0xff;
buf[2] = v.flags & 0xff;
buf[3] = len;
dec.copy(buf, 4);
return buf;
} else if (v.type === 'heapptr') {
dec = new Buffer(v.pointer, 'hex');
len = dec.length;
buf = new Buffer(2 + len);
buf[0] = 0x1e;
buf[1] = len;
dec.copy(buf, 2);
return buf;
}
} else if (v === null) {
return new Buffer([ 0x17 ]);
} else if (typeof v === 'boolean') {
return new Buffer([ v ? 0x18 : 0x19 ]);
} else if (typeof v === 'number') {
if (Math.floor(v) === v && /* whole */
(v !== 0 || 1 / v > 0) && /* not negative zero */
v >= -0x80000000 && v <= 0x7fffffff) {
// Represented signed 32-bit integers as plain integers.
// Debugger code expects this for all fields that are not
// duk_tval representations (e.g. command numbers and such).
if (v >= 0x00 && v <= 0x3f) {
return new Buffer([ 0x80 + v ]);
} else if (v >= 0x0000 && v <= 0x3fff) {
return new Buffer([ 0xc0 + (v >> 8), v & 0xff ]);
} else if (v >= -0x80000000 && v <= 0x7fffffff) {
return new Buffer([ 0x10,
(v >> 24) & 0xff,
(v >> 16) & 0xff,
(v >> 8) & 0xff,
(v >> 0) & 0xff ]);
} else {
throw new Error('internal error when encoding integer to dvalue: ' + v);
}
} else {
// Represent non-integers as IEEE double dvalues
buf = new Buffer(1 + 8);
buf[0] = 0x1a;
buf.writeDoubleBE(v, 1);
return buf;
}
} else if (typeof v === 'string') {
if (v.length < 0 || v.length > 0xffffffff) {
// Not possible in practice.
throw new TypeError('cannot convert to dvalue, invalid string length: ' + v.length);
}
if (v.length <= 0x1f) {
buf = new Buffer(1 + v.length);
buf[0] = 0x60 + v.length;
writeDebugStringToBuffer(v, buf, 1);
return buf;
} else if (v.length <= 0xffff) {
buf = new Buffer(3 + v.length);
buf[0] = 0x12;
buf[1] = (v.length >> 8) & 0xff;
buf[2] = (v.length >> 0) & 0xff;
writeDebugStringToBuffer(v, buf, 3);
return buf;
} else {
buf = new Buffer(5 + v.length);
buf[0] = 0x11;
buf[1] = (v.length >> 24) & 0xff;
buf[2] = (v.length >> 16) & 0xff;
buf[3] = (v.length >> 8) & 0xff;