duk_debug.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477
  1. /*
  2. * Minimal debug web console for Duktape command line tool
  3. *
  4. * See debugger/README.rst.
  5. *
  6. * The web UI socket.io communication can easily become a bottleneck and
  7. * it's important to ensure that the web UI remains responsive. Basic rate
  8. * limiting mechanisms (token buckets, suppressing identical messages, etc)
  9. * are used here now. Ideally the web UI would pull data on its own terms
  10. * which would provide natural rate limiting.
  11. *
  12. * Promises are used to structure callback chains.
  13. *
  14. * https://github.com/petkaantonov/bluebird
  15. * https://github.com/petkaantonov/bluebird/blob/master/API.md
  16. * https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns
  17. */
  18. var Promise = require('bluebird');
  19. var events = require('events');
  20. var stream = require('stream');
  21. var path = require('path');
  22. var fs = require('fs');
  23. var net = require('net');
  24. var byline = require('byline');
  25. var util = require('util');
  26. var readline = require('readline');
  27. var sprintf = require('sprintf').sprintf;
  28. var utf8 = require('utf8');
  29. var yaml = require('yamljs');
  30. var recursiveReadSync = require('recursive-readdir-sync');
  31. // Command line options (defaults here, overwritten if necessary)
  32. var optTargetHost = '127.0.0.1';
  33. var optTargetPort = 9091;
  34. var optHttpPort = 9092;
  35. var optJsonProxyPort = 9093;
  36. var optJsonProxy = false;
  37. var optSourceSearchDirs = [ '../tests/ecmascript' ];
  38. var optDumpDebugRead = null;
  39. var optDumpDebugWrite = null;
  40. var optDumpDebugPretty = null;
  41. var optLogMessages = false;
  42. // Constants
  43. var UI_MESSAGE_CLIPLEN = 128;
  44. var LOCALS_CLIPLEN = 64;
  45. var EVAL_CLIPLEN = 4096;
  46. var GETVAR_CLIPLEN = 4096;
  47. var SUPPORTED_DEBUG_PROTOCOL_VERSION = 2;
  48. // Commands initiated by Duktape
  49. var CMD_STATUS = 0x01;
  50. var CMD_UNUSED_2 = 0x02; // Duktape 1.x: print notify
  51. var CMD_UNUSED_3 = 0x03; // Duktape 1.x: alert notify
  52. var CMD_UNUSED_4 = 0x04; // Duktape 1.x: log notify
  53. var CMD_THROW = 0x05;
  54. var CMD_DETACHING = 0x06;
  55. // Commands initiated by the debug client (= us)
  56. var CMD_BASICINFO = 0x10;
  57. var CMD_TRIGGERSTATUS = 0x11;
  58. var CMD_PAUSE = 0x12;
  59. var CMD_RESUME = 0x13;
  60. var CMD_STEPINTO = 0x14;
  61. var CMD_STEPOVER = 0x15;
  62. var CMD_STEPOUT = 0x16;
  63. var CMD_LISTBREAK = 0x17;
  64. var CMD_ADDBREAK = 0x18;
  65. var CMD_DELBREAK = 0x19;
  66. var CMD_GETVAR = 0x1a;
  67. var CMD_PUTVAR = 0x1b;
  68. var CMD_GETCALLSTACK = 0x1c;
  69. var CMD_GETLOCALS = 0x1d;
  70. var CMD_EVAL = 0x1e;
  71. var CMD_DETACH = 0x1f;
  72. var CMD_DUMPHEAP = 0x20;
  73. var CMD_GETBYTECODE = 0x21;
  74. // Errors
  75. var ERR_UNKNOWN = 0x00;
  76. var ERR_UNSUPPORTED = 0x01;
  77. var ERR_TOOMANY = 0x02;
  78. var ERR_NOTFOUND = 0x03;
  79. // Marker objects for special protocol values
  80. var DVAL_EOM = { type: 'eom' };
  81. var DVAL_REQ = { type: 'req' };
  82. var DVAL_REP = { type: 'rep' };
  83. var DVAL_ERR = { type: 'err' };
  84. var DVAL_NFY = { type: 'nfy' };
  85. // String map for commands (debug dumping). A single map works (instead of
  86. // separate maps for each direction) because command numbers don't currently
  87. // overlap. So merge the YAML metadata.
  88. var debugCommandMeta = yaml.load('duk_debugcommands.yaml');
  89. var debugCommandNames = []; // list of command names, merged client/target
  90. debugCommandMeta.target_commands.forEach(function (k, i) {
  91. debugCommandNames[i] = k;
  92. });
  93. debugCommandMeta.client_commands.forEach(function (k, i) { // override
  94. debugCommandNames[i] = k;
  95. });
  96. var debugCommandNumbers = {}; // map from (merged) command name to number
  97. debugCommandNames.forEach(function (k, i) {
  98. debugCommandNumbers[k] = i;
  99. });
  100. // Duktape heaphdr type constants, must match C headers
  101. var DUK_HTYPE_STRING = 0;
  102. var DUK_HTYPE_OBJECT = 1;
  103. var DUK_HTYPE_BUFFER = 2;
  104. // Duktape internal class numbers, must match C headers
  105. var dukClassNameMeta = yaml.load('duk_classnames.yaml');
  106. var dukClassNames = dukClassNameMeta.class_names;
  107. // Bytecode opcode/extraop metadata
  108. var dukOpcodes = yaml.load('duk_opcodes.yaml');
  109. if (dukOpcodes.opcodes.length != 256) {
  110. throw new Error('opcode metadata length incorrect');
  111. }
  112. /*
  113. * Miscellaneous helpers
  114. */
  115. var nybbles = '0123456789abcdef';
  116. /* Convert a buffer into a string using Unicode codepoints U+0000...U+00FF.
  117. * This is the NodeJS 'binary' encoding, but since it's being deprecated,
  118. * reimplement it here. We need to avoid parsing strings as e.g. UTF-8:
  119. * although Duktape strings are usually UTF-8/CESU-8 that's not always the
  120. * case, e.g. for internal strings. Buffer values are also represented as
  121. * strings in the debug protocol, so we must deal accurately with arbitrary
  122. * byte arrays.
  123. */
  124. function bufferToDebugString(buf) {
  125. var cp = [];
  126. var i, n;
  127. /*
  128. // This fails with "RangeError: Maximum call stack size exceeded" for some
  129. // reason, so use a much slower variant.
  130. for (i = 0, n = buf.length; i < n; i++) {
  131. cp[i] = buf[i];
  132. }
  133. return String.fromCharCode.apply(String, cp);
  134. */
  135. for (i = 0, n = buf.length; i < n; i++) {
  136. cp[i] = String.fromCharCode(buf[i]);
  137. }
  138. return cp.join('');
  139. }
  140. /* Write a string into a buffer interpreting codepoints U+0000...U+00FF
  141. * as bytes. Drop higher bits.
  142. */
  143. function writeDebugStringToBuffer(str, buf, off) {
  144. var i, n;
  145. for (i = 0, n = str.length; i < n; i++) {
  146. buf[off + i] = str.charCodeAt(i) & 0xff; // truncate higher bits
  147. }
  148. }
  149. /* Encode an ordinary Unicode string into a dvalue compatible format, i.e.
  150. * into a byte array represented as codepoints U+0000...U+00FF. Concretely,
  151. * encode with UTF-8 and then represent the bytes with U+0000...U+00FF.
  152. */
  153. function stringToDebugString(str) {
  154. return utf8.encode(str);
  155. }
  156. /* Pretty print a dvalue. Useful for dumping etc. */
  157. function prettyDebugValue(x) {
  158. if (typeof x === 'object' && x !== null) {
  159. if (x.type === 'eom') {
  160. return 'EOM';
  161. } else if (x.type === 'req') {
  162. return 'REQ';
  163. } else if (x.type === 'rep') {
  164. return 'REP';
  165. } else if (x.type === 'err') {
  166. return 'ERR';
  167. } else if (x.type === 'nfy') {
  168. return 'NFY';
  169. }
  170. }
  171. return JSON.stringify(x);
  172. }
  173. /* Pretty print a number for UI usage. Types and values should be easy to
  174. * read and typing should be obvious. For numbers, support Infinity, NaN,
  175. * and signed zeroes properly.
  176. */
  177. function prettyUiNumber(x) {
  178. if (x === 1 / 0) { return 'Infinity'; }
  179. if (x === -1 / 0) { return '-Infinity'; }
  180. if (Number.isNaN(x)) { return 'NaN'; }
  181. if (x === 0 && 1 / x > 0) { return '0'; }
  182. if (x === 0 && 1 / x < 0) { return '-0'; }
  183. return x.toString();
  184. }
  185. /* Pretty print a dvalue string (bytes represented as U+0000...U+00FF)
  186. * for UI usage. Try UTF-8 decoding to get a nice Unicode string (JSON
  187. * encoded) but if that fails, ensure that bytes are encoded transparently.
  188. * The result is a quoted string with a special quote marker for a "raw"
  189. * string when UTF-8 decoding fails. Very long strings are optionally
  190. * clipped.
  191. */
  192. function prettyUiString(x, cliplen) {
  193. var ret;
  194. if (typeof x !== 'string') {
  195. throw new Error('invalid input to prettyUiString: ' + typeof x);
  196. }
  197. try {
  198. // Here utf8.decode() is better than decoding using NodeJS buffer
  199. // operations because we want strict UTF-8 interpretation.
  200. ret = JSON.stringify(utf8.decode(x));
  201. } catch (e) {
  202. // When we fall back to representing bytes, indicate that the string
  203. // is "raw" with a 'r"' prefix (a somewhat arbitrary convention).
  204. // U+0022 = ", U+0027 = '
  205. ret = 'r"' + x.replace(/[\u0022\u0027\u0000-\u001f\u0080-\uffff]/g, function (match) {
  206. var cp = match.charCodeAt(0);
  207. return '\\x' + nybbles[(cp >> 4) & 0x0f] + nybbles[cp & 0x0f];
  208. }) + '"';
  209. }
  210. if (cliplen && ret.length > cliplen) {
  211. ret = ret.substring(0, cliplen) + '...'; // trailing '"' intentionally missing
  212. }
  213. return ret;
  214. }
  215. /* Pretty print a dvalue string (bytes represented as U+0000...U+00FF)
  216. * for UI usage without quotes.
  217. */
  218. function prettyUiStringUnquoted(x, cliplen) {
  219. var ret;
  220. if (typeof x !== 'string') {
  221. throw new Error('invalid input to prettyUiStringUnquoted: ' + typeof x);
  222. }
  223. try {
  224. // Here utf8.decode() is better than decoding using NodeJS buffer
  225. // operations because we want strict UTF-8 interpretation.
  226. // XXX: unprintable characters etc? In some UI cases we'd want to
  227. // e.g. escape newlines and in others not.
  228. ret = utf8.decode(x);
  229. } catch (e) {
  230. // For the unquoted version we don't need to escape single or double
  231. // quotes.
  232. ret = x.replace(/[\u0000-\u001f\u0080-\uffff]/g, function (match) {
  233. var cp = match.charCodeAt(0);
  234. return '\\x' + nybbles[(cp >> 4) & 0x0f] + nybbles[cp & 0x0f];
  235. });
  236. }
  237. if (cliplen && ret.length > cliplen) {
  238. ret = ret.substring(0, cliplen) + '...';
  239. }
  240. return ret;
  241. }
  242. /* Pretty print a dvalue for UI usage. Everything comes out as a ready-to-use
  243. * string.
  244. *
  245. * XXX: Currently the debug client formats all values for UI use. A better
  246. * solution would be to pass values in typed form and let the UI format them,
  247. * so that styling etc. could take typing into account.
  248. */
  249. function prettyUiDebugValue(x, cliplen) {
  250. if (typeof x === 'object' && x !== null) {
  251. // Note: typeof null === 'object', so null special case explicitly
  252. if (x.type === 'eom') {
  253. return 'EOM';
  254. } else if (x.type === 'req') {
  255. return 'REQ';
  256. } else if (x.type === 'rep') {
  257. return 'REP';
  258. } else if (x.type === 'err') {
  259. return 'ERR';
  260. } else if (x.type === 'nfy') {
  261. return 'NFY';
  262. } else if (x.type === 'unused') {
  263. return 'unused';
  264. } else if (x.type === 'undefined') {
  265. return 'undefined';
  266. } else if (x.type === 'buffer') {
  267. return '|' + x.data + '|';
  268. } else if (x.type === 'object') {
  269. return '[object ' + (dukClassNames[x.class] || ('class ' + x.class)) + ' ' + x.pointer + ']';
  270. } else if (x.type === 'pointer') {
  271. return '<pointer ' + x.pointer + '>';
  272. } else if (x.type === 'lightfunc') {
  273. return '<lightfunc 0x' + x.flags.toString(16) + ' ' + x.pointer + '>';
  274. } else if (x.type === 'number') {
  275. // duk_tval number, any IEEE double
  276. var tmp = new Buffer(x.data, 'hex'); // decode into hex
  277. var val = tmp.readDoubleBE(0); // big endian ieee double
  278. return prettyUiNumber(val);
  279. }
  280. } else if (x === null) {
  281. return 'null';
  282. } else if (typeof x === 'boolean') {
  283. return x ? 'true' : 'false';
  284. } else if (typeof x === 'string') {
  285. return prettyUiString(x, cliplen);
  286. } else if (typeof x === 'number') {
  287. // Debug protocol integer
  288. return prettyUiNumber(x);
  289. }
  290. // We shouldn't come here, but if we do, JSON is a reasonable default.
  291. return JSON.stringify(x);
  292. }
  293. /* Pretty print a debugger message given as an array of parsed dvalues.
  294. * Result should be a pure ASCII one-liner.
  295. */
  296. function prettyDebugMessage(msg) {
  297. return msg.map(prettyDebugValue).join(' ');
  298. }
  299. /* Pretty print a debugger command. */
  300. function prettyDebugCommand(cmd) {
  301. return debugCommandNames[cmd] || String(cmd);
  302. }
  303. /* Decode and normalize source file contents: UTF-8, tabs to 8,
  304. * CR LF to LF.
  305. */
  306. function decodeAndNormalizeSource(data) {
  307. var tmp;
  308. var lines, line, repl;
  309. var i, n;
  310. var j, m;
  311. try {
  312. tmp = data.toString('utf8');
  313. } catch (e) {
  314. console.log('Failed to UTF-8 decode source file, ignoring: ' + e);
  315. tmp = String(data);
  316. }
  317. lines = tmp.split(/\r?\n/);
  318. for (i = 0, n = lines.length; i < n; i++) {
  319. line = lines[i];
  320. if (/\t/.test(line)) {
  321. repl = '';
  322. for (j = 0, m = line.length; j < m; j++) {
  323. if (line.charAt(j) === '\t') {
  324. repl += ' ';
  325. while ((repl.length % 8) != 0) {
  326. repl += ' ';
  327. }
  328. } else {
  329. repl += line.charAt(j);
  330. }
  331. }
  332. lines[i] = repl;
  333. }
  334. }
  335. // XXX: normalize last newline (i.e. force a newline if contents don't
  336. // end with a newline)?
  337. return lines.join('\n');
  338. }
  339. /* Token bucket rate limiter for a given callback. Calling code calls
  340. * trigger() to request 'cb' to be called, and the rate limiter ensures
  341. * that 'cb' is not called too often.
  342. */
  343. function RateLimited(tokens, rate, cb) {
  344. var _this = this;
  345. this.maxTokens = tokens;
  346. this.tokens = this.maxTokens;
  347. this.rate = rate;
  348. this.cb = cb;
  349. this.delayedCb = false;
  350. // Right now the implementation is setInterval-based, but could also be
  351. // made timerless. There are so few rate limited resources that this
  352. // doesn't matter in practice.
  353. this.tokenAdder = setInterval(function () {
  354. if (_this.tokens < _this.maxTokens) {
  355. _this.tokens++;
  356. }
  357. if (_this.delayedCb) {
  358. _this.delayedCb = false;
  359. _this.tokens--;
  360. _this.cb();
  361. }
  362. }, this.rate);
  363. }
  364. RateLimited.prototype.trigger = function () {
  365. if (this.tokens > 0) {
  366. this.tokens--;
  367. this.cb();
  368. } else {
  369. this.delayedCb = true;
  370. }
  371. };
  372. /*
  373. * Source file manager
  374. *
  375. * Scan the list of search directories for Ecmascript source files and
  376. * build an index of them. Provides a mechanism to find a source file
  377. * based on a raw 'fileName' property provided by the debug target, and
  378. * to provide a file list for the web UI.
  379. *
  380. * NOTE: it's tempting to do loose matching for filenames, but this does
  381. * not work in practice. Filenames must match 1:1 with the debug target
  382. * so that e.g. breakpoints assigned based on filenames found from the
  383. * search paths will match 1:1 on the debug target. If this is not the
  384. * case, breakpoints won't work as expected.
  385. */
  386. function SourceFileManager(directories) {
  387. this.directories = directories;
  388. this.extensions = { '.js': true, '.jsm': true };
  389. this.files;
  390. }
  391. SourceFileManager.prototype.scan = function () {
  392. var _this = this;
  393. var fileMap = {}; // absFn -> true
  394. var files;
  395. this.directories.forEach(function (dir) {
  396. console.log('Scanning source files: ' + dir);
  397. try {
  398. recursiveReadSync(dir).forEach(function (fn) {
  399. var absFn = path.normalize(path.join(dir, fn)); // './foo/bar.js' -> 'foo/bar.js'
  400. var ent;
  401. if (fs.existsSync(absFn) &&
  402. fs.lstatSync(absFn).isFile() &&
  403. _this.extensions[path.extname(fn)]) {
  404. // We want the fileMap to contain the filename relative to
  405. // the search dir root.
  406. fileMap[fn] = true;
  407. }
  408. });
  409. } catch (e) {
  410. console.log('Failed to scan ' + dir + ': ' + e);
  411. }
  412. });
  413. files = Object.keys(fileMap);
  414. files.sort();
  415. this.files = files;
  416. console.log('Found ' + files.length + ' source files in ' + this.directories.length + ' search directories');
  417. };
  418. SourceFileManager.prototype.getFiles = function () {
  419. return this.files;
  420. };
  421. SourceFileManager.prototype.search = function (fileName) {
  422. var _this = this;
  423. // Loose matching is tempting but counterproductive: filenames must
  424. // match 1:1 between the debug client and the debug target for e.g.
  425. // breakpoints to work as expected. Note that a breakpoint may be
  426. // assigned by selecting a file from a dropdown populated by scanning
  427. // the filesystem for available sources and there's no way of knowing
  428. // if the debug target uses the exact same name.
  429. function tryLookup() {
  430. var i, fn, data;
  431. for (i = 0; i < _this.directories.length; i++) {
  432. fn = path.join(_this.directories[i], fileName);
  433. if (fs.existsSync(fn) && fs.lstatSync(fn).isFile()) {
  434. data = fs.readFileSync(fn); // Raw bytes
  435. return decodeAndNormalizeSource(data); // Unicode string
  436. }
  437. }
  438. return null;
  439. }
  440. return tryLookup(fileName);
  441. };
  442. /*
  443. * Debug protocol parser
  444. *
  445. * The debug protocol parser is an EventEmitter which parses debug messages
  446. * from an input stream and emits 'debug-message' events for completed
  447. * messages ending in an EOM. The parser also provides debug dumping, stream
  448. * logging functionality, and statistics gathering functionality.
  449. *
  450. * This parser is used to parse both incoming and outgoing messages. For
  451. * outgoing messages the only function is to validate and debug dump the
  452. * messages we're about to send. The downside of dumping at this low level
  453. * is that we can't match request and reply/error messages here.
  454. *
  455. * http://www.sitepoint.com/nodejs-events-and-eventemitter/
  456. */
  457. function DebugProtocolParser(inputStream,
  458. protocolVersion,
  459. rawDumpFileName,
  460. textDumpFileName,
  461. textDumpFilePrefix,
  462. hexDumpConsolePrefix,
  463. textDumpConsolePrefix) {
  464. var _this = this;
  465. this.inputStream = inputStream;
  466. this.closed = false; // stream is closed/broken, don't parse anymore
  467. this.bytes = 0;
  468. this.dvalues = 0;
  469. this.messages = 0;
  470. this.requests = 0;
  471. this.prevBytes = 0;
  472. this.bytesPerSec = 0;
  473. this.statsTimer = null;
  474. this.readableNumberValue = true;
  475. events.EventEmitter.call(this);
  476. var buf = new Buffer(0); // accumulate data
  477. var msg = []; // accumulated message until EOM
  478. var versionIdentification;
  479. var statsInterval = 2000;
  480. var statsIntervalSec = statsInterval / 1000;
  481. this.statsTimer = setInterval(function () {
  482. _this.bytesPerSec = (_this.bytes - _this.prevBytes) / statsIntervalSec;
  483. _this.prevBytes = _this.bytes;
  484. _this.emit('stats-update');
  485. }, statsInterval);
  486. function consume(n) {
  487. var tmp = new Buffer(buf.length - n);
  488. buf.copy(tmp, 0, n);
  489. buf = tmp;
  490. }
  491. inputStream.on('data', function (data) {
  492. var i, n, x, v, gotValue, len, t, tmpbuf, verstr;
  493. var prettyMsg;
  494. if (_this.closed || !_this.inputStream) {
  495. console.log('Ignoring incoming data from closed input stream, len ' + data.length);
  496. return;
  497. }
  498. _this.bytes += data.length;
  499. if (rawDumpFileName) {
  500. fs.appendFileSync(rawDumpFileName, data);
  501. }
  502. if (hexDumpConsolePrefix) {
  503. console.log(hexDumpConsolePrefix + data.toString('hex'));
  504. }
  505. buf = Buffer.concat([ buf, data ]);
  506. // Protocol version handling. When dumping an output stream, the
  507. // caller gives a non-null protocolVersion so we don't read one here.
  508. if (protocolVersion == null) {
  509. if (buf.length > 1024) {
  510. _this.emit('transport-error', 'Parse error (version identification too long), dropping connection');
  511. _this.close();
  512. return;
  513. }
  514. for (i = 0, n = buf.length; i < n; i++) {
  515. if (buf[i] == 0x0a) {
  516. tmpbuf = new Buffer(i);
  517. buf.copy(tmpbuf, 0, 0, i);
  518. consume(i + 1);
  519. verstr = tmpbuf.toString('utf-8');
  520. t = verstr.split(' ');
  521. protocolVersion = Number(t[0]);
  522. versionIdentification = verstr;
  523. _this.emit('protocol-version', {
  524. protocolVersion: protocolVersion,
  525. versionIdentification: versionIdentification
  526. });
  527. break;
  528. }
  529. }
  530. if (protocolVersion == null) {
  531. // Still waiting for version identification to complete.
  532. return;
  533. }
  534. }
  535. // Parse complete dvalues (quite inefficient now) by trial parsing.
  536. // Consume a value only when it's fully present in 'buf'.
  537. // See doc/debugger.rst for format description.
  538. while (buf.length > 0) {
  539. x = buf[0];
  540. v = undefined;
  541. gotValue = false; // used to flag special values like undefined
  542. if (x >= 0xc0) {
  543. // 0xc0...0xff: integers 0-16383
  544. if (buf.length >= 2) {
  545. v = ((x - 0xc0) << 8) + buf[1];
  546. consume(2);
  547. }
  548. } else if (x >= 0x80) {
  549. // 0x80...0xbf: integers 0-63
  550. v = x - 0x80;
  551. consume(1);
  552. } else if (x >= 0x60) {
  553. // 0x60...0x7f: strings with length 0-31
  554. len = x - 0x60;
  555. if (buf.length >= 1 + len) {
  556. v = new Buffer(len);
  557. buf.copy(v, 0, 1, 1 + len);
  558. v = bufferToDebugString(v);
  559. consume(1 + len);
  560. }
  561. } else {
  562. switch (x) {
  563. case 0x00: v = DVAL_EOM; consume(1); break;
  564. case 0x01: v = DVAL_REQ; consume(1); break;
  565. case 0x02: v = DVAL_REP; consume(1); break;
  566. case 0x03: v = DVAL_ERR; consume(1); break;
  567. case 0x04: v = DVAL_NFY; consume(1); break;
  568. case 0x10: // 4-byte signed integer
  569. if (buf.length >= 5) {
  570. v = buf.readInt32BE(1);
  571. consume(5);
  572. }
  573. break;
  574. case 0x11: // 4-byte string
  575. if (buf.length >= 5) {
  576. len = buf.readUInt32BE(1);
  577. if (buf.length >= 5 + len) {
  578. v = new Buffer(len);
  579. buf.copy(v, 0, 5, 5 + len);
  580. v = bufferToDebugString(v);
  581. consume(5 + len);
  582. }
  583. }
  584. break;
  585. case 0x12: // 2-byte string
  586. if (buf.length >= 3) {
  587. len = buf.readUInt16BE(1);
  588. if (buf.length >= 3 + len) {
  589. v = new Buffer(len);
  590. buf.copy(v, 0, 3, 3 + len);
  591. v = bufferToDebugString(v);
  592. consume(3 + len);
  593. }
  594. }
  595. break;
  596. case 0x13: // 4-byte buffer
  597. if (buf.length >= 5) {
  598. len = buf.readUInt32BE(1);
  599. if (buf.length >= 5 + len) {
  600. v = new Buffer(len);
  601. buf.copy(v, 0, 5, 5 + len);
  602. v = { type: 'buffer', data: v.toString('hex') };
  603. consume(5 + len);
  604. // Value could be a Node.js buffer directly, but
  605. // we prefer all dvalues to be JSON compatible
  606. }
  607. }
  608. break;
  609. case 0x14: // 2-byte buffer
  610. if (buf.length >= 3) {
  611. len = buf.readUInt16BE(1);
  612. if (buf.length >= 3 + len) {
  613. v = new Buffer(len);
  614. buf.copy(v, 0, 3, 3 + len);
  615. v = { type: 'buffer', data: v.toString('hex') };
  616. consume(3 + len);
  617. // Value could be a Node.js buffer directly, but
  618. // we prefer all dvalues to be JSON compatible
  619. }
  620. }
  621. break;
  622. case 0x15: // unused/none
  623. v = { type: 'unused' };
  624. consume(1);
  625. break;
  626. case 0x16: // undefined
  627. v = { type: 'undefined' };
  628. gotValue = true; // indicate 'v' is actually set
  629. consume(1);
  630. break;
  631. case 0x17: // null
  632. v = null;
  633. gotValue = true; // indicate 'v' is actually set
  634. consume(1);
  635. break;
  636. case 0x18: // true
  637. v = true;
  638. consume(1);
  639. break;
  640. case 0x19: // false
  641. v = false;
  642. consume(1);
  643. break;
  644. case 0x1a: // number (IEEE double), big endian
  645. if (buf.length >= 9) {
  646. v = new Buffer(8);
  647. buf.copy(v, 0, 1, 9);
  648. v = { type: 'number', data: v.toString('hex') };
  649. if (_this.readableNumberValue) {
  650. // The value key should not be used programmatically,
  651. // it is just there to make the dumps more readable.
  652. v.value = buf.readDoubleBE(1);
  653. }
  654. consume(9);
  655. }
  656. break;
  657. case 0x1b: // object
  658. if (buf.length >= 3) {
  659. len = buf[2];
  660. if (buf.length >= 3 + len) {
  661. v = new Buffer(len);
  662. buf.copy(v, 0, 3, 3 + len);
  663. v = { type: 'object', 'class': buf[1], pointer: v.toString('hex') };
  664. consume(3 + len);
  665. }
  666. }
  667. break;
  668. case 0x1c: // pointer
  669. if (buf.length >= 2) {
  670. len = buf[1];
  671. if (buf.length >= 2 + len) {
  672. v = new Buffer(len);
  673. buf.copy(v, 0, 2, 2 + len);
  674. v = { type: 'pointer', pointer: v.toString('hex') };
  675. consume(2 + len);
  676. }
  677. }
  678. break;
  679. case 0x1d: // lightfunc
  680. if (buf.length >= 4) {
  681. len = buf[3];
  682. if (buf.length >= 4 + len) {
  683. v = new Buffer(len);
  684. buf.copy(v, 0, 4, 4 + len);
  685. v = { type: 'lightfunc', flags: buf.readUInt16BE(1), pointer: v.toString('hex') };
  686. consume(4 + len);
  687. }
  688. }
  689. break;
  690. case 0x1e: // heapptr
  691. if (buf.length >= 2) {
  692. len = buf[1];
  693. if (buf.length >= 2 + len) {
  694. v = new Buffer(len);
  695. buf.copy(v, 0, 2, 2 + len);
  696. v = { type: 'heapptr', pointer: v.toString('hex') };
  697. consume(2 + len);
  698. }
  699. }
  700. break;
  701. default:
  702. _this.emit('transport-error', 'Parse error, dropping connection');
  703. _this.close();
  704. }
  705. }
  706. if (typeof v === 'undefined' && !gotValue) {
  707. break;
  708. }
  709. msg.push(v);
  710. _this.dvalues++;
  711. // Could emit a 'debug-value' event here, but that's not necessary
  712. // because the receiver will just collect statistics which can also
  713. // be done using the finished message.
  714. if (v === DVAL_EOM) {
  715. _this.messages++;
  716. if (textDumpFileName || textDumpConsolePrefix) {
  717. prettyMsg = prettyDebugMessage(msg);
  718. if (textDumpFileName) {
  719. fs.appendFileSync(textDumpFileName, (textDumpFilePrefix || '') + prettyMsg + '\n');
  720. }
  721. if (textDumpConsolePrefix) {
  722. console.log(textDumpConsolePrefix + prettyMsg);
  723. }
  724. }
  725. _this.emit('debug-message', msg);
  726. msg = []; // new object, old may be in circulation for a while
  727. }
  728. }
  729. });
  730. // Not all streams will emit this.
  731. inputStream.on('error', function (err) {
  732. _this.emit('transport-error', err);
  733. _this.close();
  734. });
  735. // Not all streams will emit this.
  736. inputStream.on('close', function () {
  737. _this.close();
  738. });
  739. }
  740. DebugProtocolParser.prototype = Object.create(events.EventEmitter.prototype);
  741. DebugProtocolParser.prototype.close = function () {
  742. // Although the underlying transport may not have a close() or destroy()
  743. // method or even a 'close' event, this method is always available and
  744. // will generate a 'transport-close'.
  745. //
  746. // The caller is responsible for closing the underlying stream if that
  747. // is necessary.
  748. if (this.closed) { return; }
  749. this.closed = true;
  750. if (this.statsTimer) {
  751. clearInterval(this.statsTimer);
  752. this.statsTimer = null;
  753. }
  754. this.emit('transport-close');
  755. };
  756. /*
  757. * Debugger output formatting
  758. */
  759. function formatDebugValue(v) {
  760. var buf, dec, len;
  761. // See doc/debugger.rst for format description.
  762. if (typeof v === 'object' && v !== null) {
  763. // Note: typeof null === 'object', so null special case explicitly
  764. if (v.type === 'eom') {
  765. return new Buffer([ 0x00 ]);
  766. } else if (v.type === 'req') {
  767. return new Buffer([ 0x01 ]);
  768. } else if (v.type === 'rep') {
  769. return new Buffer([ 0x02 ]);
  770. } else if (v.type === 'err') {
  771. return new Buffer([ 0x03 ]);
  772. } else if (v.type === 'nfy') {
  773. return new Buffer([ 0x04 ]);
  774. } else if (v.type === 'unused') {
  775. return new Buffer([ 0x15 ]);
  776. } else if (v.type === 'undefined') {
  777. return new Buffer([ 0x16 ]);
  778. } else if (v.type === 'number') {
  779. dec = new Buffer(v.data, 'hex');
  780. len = dec.length;
  781. if (len !== 8) {
  782. throw new TypeError('value cannot be converted to dvalue: ' + JSON.stringify(v));
  783. }
  784. buf = new Buffer(1 + len);
  785. buf[0] = 0x1a;
  786. dec.copy(buf, 1);
  787. return buf;
  788. } else if (v.type === 'buffer') {
  789. dec = new Buffer(v.data, 'hex');
  790. len = dec.length;
  791. if (len <= 0xffff) {
  792. buf = new Buffer(3 + len);
  793. buf[0] = 0x14;
  794. buf[1] = (len >> 8) & 0xff;
  795. buf[2] = (len >> 0) & 0xff;
  796. dec.copy(buf, 3);
  797. return buf;
  798. } else {
  799. buf = new Buffer(5 + len);
  800. buf[0] = 0x13;
  801. buf[1] = (len >> 24) & 0xff;
  802. buf[2] = (len >> 16) & 0xff;
  803. buf[3] = (len >> 8) & 0xff;
  804. buf[4] = (len >> 0) & 0xff;
  805. dec.copy(buf, 5);
  806. return buf;
  807. }
  808. } else if (v.type === 'object') {
  809. dec = new Buffer(v.pointer, 'hex');
  810. len = dec.length;
  811. buf = new Buffer(3 + len);
  812. buf[0] = 0x1b;
  813. buf[1] = v.class;
  814. buf[2] = len;
  815. dec.copy(buf, 3);
  816. return buf;
  817. } else if (v.type === 'pointer') {
  818. dec = new Buffer(v.pointer, 'hex');
  819. len = dec.length;
  820. buf = new Buffer(2 + len);
  821. buf[0] = 0x1c;
  822. buf[1] = len;
  823. dec.copy(buf, 2);
  824. return buf;
  825. } else if (v.type === 'lightfunc') {
  826. dec = new Buffer(v.pointer, 'hex');
  827. len = dec.length;
  828. buf = new Buffer(4 + len);
  829. buf[0] = 0x1d;
  830. buf[1] = (v.flags >> 8) & 0xff;
  831. buf[2] = v.flags & 0xff;
  832. buf[3] = len;
  833. dec.copy(buf, 4);
  834. return buf;
  835. } else if (v.type === 'heapptr') {
  836. dec = new Buffer(v.pointer, 'hex');
  837. len = dec.length;
  838. buf = new Buffer(2 + len);
  839. buf[0] = 0x1e;
  840. buf[1] = len;
  841. dec.copy(buf, 2);
  842. return buf;
  843. }
  844. } else if (v === null) {
  845. return new Buffer([ 0x17 ]);
  846. } else if (typeof v === 'boolean') {
  847. return new Buffer([ v ? 0x18 : 0x19 ]);
  848. } else if (typeof v === 'number') {
  849. if (Math.floor(v) === v && /* whole */
  850. (v !== 0 || 1 / v > 0) && /* not negative zero */
  851. v >= -0x80000000 && v <= 0x7fffffff) {
  852. // Represented signed 32-bit integers as plain integers.
  853. // Debugger code expects this for all fields that are not
  854. // duk_tval representations (e.g. command numbers and such).
  855. if (v >= 0x00 && v <= 0x3f) {
  856. return new Buffer([ 0x80 + v ]);
  857. } else if (v >= 0x0000 && v <= 0x3fff) {
  858. return new Buffer([ 0xc0 + (v >> 8), v & 0xff ]);
  859. } else if (v >= -0x80000000 && v <= 0x7fffffff) {
  860. return new Buffer([ 0x10,
  861. (v >> 24) & 0xff,
  862. (v >> 16) & 0xff,
  863. (v >> 8) & 0xff,
  864. (v >> 0) & 0xff ]);
  865. } else {
  866. throw new Error('internal error when encoding integer to dvalue: ' + v);
  867. }
  868. } else {
  869. // Represent non-integers as IEEE double dvalues
  870. buf = new Buffer(1 + 8);
  871. buf[0] = 0x1a;
  872. buf.writeDoubleBE(v, 1);
  873. return buf;
  874. }
  875. } else if (typeof v === 'string') {
  876. if (v.length < 0 || v.length > 0xffffffff) {
  877. // Not possible in practice.
  878. throw new TypeError('cannot convert to dvalue, invalid string length: ' + v.length);
  879. }
  880. if (v.length <= 0x1f) {
  881. buf = new Buffer(1 + v.length);
  882. buf[0] = 0x60 + v.length;
  883. writeDebugStringToBuffer(v, buf, 1);
  884. return buf;
  885. } else if (v.length <= 0xffff) {
  886. buf = new Buffer(3 + v.length);
  887. buf[0] = 0x12;
  888. buf[1] = (v.length >> 8) & 0xff;
  889. buf[2] = (v.length >> 0) & 0xff;
  890. writeDebugStringToBuffer(v, buf, 3);
  891. return buf;
  892. } else {
  893. buf = new Buffer(5 + v.length);
  894. buf[0] = 0x11;
  895. buf[1] = (v.length >> 24) & 0xff;
  896. buf[2] = (v.length >> 16) & 0xff;
  897. buf[3] = (v.length >> 8) & 0xff;
  898. buf[4] = (v.length >> 0) & 0xff;
  899. writeDebugStringToBuffer(v, buf, 5);
  900. return buf;
  901. }
  902. }
  903. // Shouldn't come here.
  904. throw new TypeError('value cannot be converted to dvalue: ' + JSON.stringify(v));
  905. }
  906. /*
  907. * Debugger implementation
  908. *
  909. * A debugger instance communicates with the debug target and maintains
  910. * persistent debug state so that the current state can be resent to the
  911. * socket.io client (web UI) if it reconnects. Whenever the debugger state
  912. * is changed an event is generated. The socket.io handler will listen to
  913. * state change events and push the necessary updates to the web UI, often
  914. * in a rate limited fashion or using a client pull to ensure the web UI
  915. * is not overloaded.
  916. *
  917. * The debugger instance assumes that if the debug protocol connection is
  918. * re-established, it is always to the same target. There is no separate
  919. * abstraction for a debugger session.
  920. */
  921. function Debugger() {
  922. events.EventEmitter.call(this);
  923. this.web = null; // web UI singleton
  924. this.targetStream = null; // transport connection to target
  925. this.outputPassThroughStream = null; // dummy passthrough for message dumping
  926. this.inputParser = null; // parser for incoming debug messages
  927. this.outputParser = null; // parser for outgoing debug messages (stats, dumping)
  928. this.protocolVersion = null;
  929. this.dukVersion = null;
  930. this.dukGitDescribe = null;
  931. this.targetInfo = null;
  932. this.attached = false;
  933. this.handshook = false;
  934. this.reqQueue = null;
  935. this.stats = { // stats for current debug connection
  936. rxBytes: 0, rxDvalues: 0, rxMessages: 0, rxBytesPerSec: 0,
  937. txBytes: 0, txDvalues: 0, txMessages: 0, txBytesPerSec: 0
  938. };
  939. this.execStatus = {
  940. attached: false,
  941. state: 'detached',
  942. fileName: '',
  943. funcName: '',
  944. line: 0,
  945. pc: 0
  946. };
  947. this.breakpoints = [];
  948. this.callstack = [];
  949. this.locals = [];
  950. this.messageLines = [];
  951. this.messageScrollBack = 100;
  952. }
  953. Debugger.prototype = events.EventEmitter.prototype;
  954. Debugger.prototype.decodeBytecodeFromBuffer = function (buf, consts, funcs) {
  955. var i, j, n, m, ins, pc;
  956. var res = [];
  957. var op, str, args, comments;
  958. // XXX: add constants inline to preformatted output (e.g. for strings,
  959. // add a short escaped snippet as a comment on the line after the
  960. // compact argument list).
  961. for (i = 0, n = buf.length; i < n; i += 4) {
  962. pc = i / 4;
  963. // shift forces unsigned
  964. if (this.endianness === 'little') {
  965. ins = buf.readInt32LE(i) >>> 0;
  966. } else {
  967. ins = buf.readInt32BE(i) >>> 0;
  968. }
  969. op = dukOpcodes.opcodes[ins & 0xff];
  970. args = [];
  971. comments = [];
  972. if (op.args) {
  973. for (j = 0, m = op.args.length; j < m; j++) {
  974. var A = (ins >>> 8) & 0xff;
  975. var B = (ins >>> 16) & 0xff;
  976. var C = (ins >>> 24) & 0xff;
  977. var BC = (ins >>> 16) & 0xffff;
  978. var ABC = (ins >>> 8) & 0xffffff;
  979. var Bconst = op & 0x01;
  980. var Cconst = op & 0x02;
  981. switch (op.args[j]) {
  982. case 'A_R': args.push('r' + A); break;
  983. case 'A_RI': args.push('r' + A + '(indirect)'); break;
  984. case 'A_C': args.push('c' + A); break;
  985. case 'A_H': args.push('0x' + A.toString(16)); break;
  986. case 'A_I': args.push(A.toString(10)); break;
  987. case 'A_B': args.push(A ? 'true' : 'false'); break;
  988. case 'B_RC': args.push((Bconst ? 'c' : 'r') + B); break;
  989. case 'B_R': args.push('r' + B); break;
  990. case 'B_RI': args.push('r' + B + '(indirect)'); break;
  991. case 'B_C': args.push('c' + B); break;
  992. case 'B_H': args.push('0x' + B.toString(16)); break;
  993. case 'B_I': args.push(B.toString(10)); break;
  994. case 'C_RC': args.push((Cconst ? 'c' : 'r') + C); break;
  995. case 'C_R': args.push('r' + C); break;
  996. case 'C_RI': args.push('r' + C + '(indirect)'); break;
  997. case 'C_C': args.push('c' + C); break;
  998. case 'C_H': args.push('0x' + C.toString(16)); break;
  999. case 'C_I': args.push(C.toString(10)); break;
  1000. case 'BC_R': args.push('r' + BC); break;
  1001. case 'BC_C': args.push('c' + BC); break;
  1002. case 'BC_H': args.push('0x' + BC.toString(16)); break;
  1003. case 'BC_I': args.push(BC.toString(10)); break;
  1004. case 'ABC_H': args.push(ABC.toString(16)); break;
  1005. case 'ABC_I': args.push(ABC.toString(10)); break;
  1006. case 'BC_LDINT': args.push(BC - (1 << 15)); break;
  1007. case 'BC_LDINTX': args.push(BC - 0); break; // no bias in LDINTX
  1008. case 'ABC_JUMP': {
  1009. var pc_add = ABC - (1 << 23) + 1; // pc is preincremented before adding
  1010. var pc_dst = pc + pc_add;
  1011. args.push(pc_dst + ' (' + (pc_add >= 0 ? '+' : '') + pc_add + ')');
  1012. break;
  1013. }
  1014. default: args.push('?'); break;
  1015. }
  1016. }
  1017. }
  1018. if (op.flags) {
  1019. for (j = 0, m = op.flags.length; j < m; j++) {
  1020. if (ins & op.flags[j].mask) {
  1021. comments.push(op.flags[j].name);
  1022. }
  1023. }
  1024. }
  1025. if (args.length > 0) {
  1026. str = sprintf('%05d %08x %-10s %s', pc, ins, op.name, args.join(', '));
  1027. } else {
  1028. str = sprintf('%05d %08x %-10s', pc, ins, op.name);
  1029. }
  1030. if (comments.length > 0) {
  1031. str = sprintf('%-44s ; %s', str, comments.join(', '));
  1032. }
  1033. res.push({
  1034. str: str,
  1035. ins: ins
  1036. });
  1037. }
  1038. return res;
  1039. };
  1040. Debugger.prototype.uiMessage = function (type, val) {
  1041. var msg;
  1042. if (typeof type === 'object') {
  1043. msg = type;
  1044. } else if (typeof type === 'string') {
  1045. msg = { type: type, message: val };
  1046. } else {
  1047. throw new TypeError('invalid ui message: ' + type);
  1048. }
  1049. this.messageLines.push(msg);
  1050. while (this.messageLines.length > this.messageScrollBack) {
  1051. this.messageLines.shift();
  1052. }
  1053. this.emit('ui-message-update'); // just trigger a sync, gets rate limited
  1054. };
  1055. Debugger.prototype.sendRequest = function (msg) {
  1056. var _this = this;
  1057. return new Promise(function (resolve, reject) {
  1058. var dvals = [];
  1059. var dval;
  1060. var data;
  1061. var i;
  1062. if (!_this.attached || !_this.handshook || !_this.reqQueue || !_this.targetStream) {
  1063. throw new Error('invalid state for sendRequest');
  1064. }
  1065. for (i = 0; i < msg.length; i++) {
  1066. try {
  1067. dval = formatDebugValue(msg[i]);
  1068. } catch (e) {
  1069. console.log('Failed to format dvalue, dropping connection: ' + e);
  1070. console.log(e.stack || e);
  1071. _this.targetStream.destroy();
  1072. throw new Error('failed to format dvalue');
  1073. }
  1074. dvals.push(dval);
  1075. }
  1076. data = Buffer.concat(dvals);
  1077. _this.targetStream.write(data);
  1078. _this.outputPassThroughStream.write(data); // stats and dumping
  1079. if (optLogMessages) {
  1080. console.log('Request ' + prettyDebugCommand(msg[1]) + ': ' + prettyDebugMessage(msg));
  1081. }
  1082. if (!_this.reqQueue) {
  1083. throw new Error('no reqQueue');
  1084. }
  1085. _this.reqQueue.push({
  1086. reqMsg: msg,
  1087. reqCmd: msg[1],
  1088. resolveCb: resolve,
  1089. rejectCb: reject
  1090. });
  1091. });
  1092. };
  1093. Debugger.prototype.sendBasicInfoRequest = function () {
  1094. var _this = this;
  1095. return this.sendRequest([ DVAL_REQ, CMD_BASICINFO, DVAL_EOM ]).then(function (msg) {
  1096. _this.dukVersion = msg[1];
  1097. _this.dukGitDescribe = msg[2];
  1098. _this.targetInfo = msg[3];
  1099. _this.endianness = { 1: 'little', 2: 'mixed', 3: 'big' }[msg[4]] || 'unknown';
  1100. _this.emit('basic-info-update');
  1101. return msg;
  1102. });
  1103. };
  1104. Debugger.prototype.sendGetVarRequest = function (varname, level) {
  1105. var _this = this;
  1106. return this.sendRequest([ DVAL_REQ, CMD_GETVAR, (typeof level === 'number' ? level : -1), varname, DVAL_EOM ]).then(function (msg) {
  1107. return { found: msg[1] === 1, value: msg[2] };
  1108. });
  1109. };
  1110. Debugger.prototype.sendPutVarRequest = function (varname, varvalue, level) {
  1111. var _this = this;
  1112. return this.sendRequest([ DVAL_REQ, CMD_PUTVAR, (typeof level === 'number' ? level : -1), varname, varvalue, DVAL_EOM ]);
  1113. };
  1114. Debugger.prototype.sendInvalidCommandTestRequest = function () {
  1115. // Intentional invalid command
  1116. var _this = this;
  1117. return this.sendRequest([ DVAL_REQ, 0xdeadbeef, DVAL_EOM ]);
  1118. };
  1119. Debugger.prototype.sendStatusRequest = function () {
  1120. // Send a status request to trigger a status notify, result is ignored:
  1121. // target sends a status notify instead of a meaningful reply
  1122. var _this = this;
  1123. return this.sendRequest([ DVAL_REQ, CMD_TRIGGERSTATUS, DVAL_EOM ]);
  1124. };
  1125. Debugger.prototype.sendBreakpointListRequest = function () {
  1126. var _this = this;
  1127. return this.sendRequest([ DVAL_REQ, CMD_LISTBREAK, DVAL_EOM ]).then(function (msg) {
  1128. var i, n;
  1129. var breakpts = [];
  1130. for (i = 1, n = msg.length - 1; i < n; i += 2) {
  1131. breakpts.push({ fileName: msg[i], lineNumber: msg[i + 1] });
  1132. }
  1133. _this.breakpoints = breakpts;
  1134. _this.emit('breakpoints-update');
  1135. return msg;
  1136. });
  1137. };
  1138. Debugger.prototype.sendGetLocalsRequest = function (level) {
  1139. var _this = this;
  1140. return this.sendRequest([ DVAL_REQ, CMD_GETLOCALS, (typeof level === 'number' ? level : -1), DVAL_EOM ]).then(function (msg) {
  1141. var i;
  1142. var locals = [];
  1143. for (i = 1; i <= msg.length - 2; i += 2) {
  1144. // XXX: do pretty printing in debug client for now
  1145. locals.push({ key: msg[i], value: prettyUiDebugValue(msg[i + 1], LOCALS_CLIPLEN) });
  1146. }
  1147. _this.locals = locals;
  1148. _this.emit('locals-update');
  1149. return msg;
  1150. });
  1151. };
  1152. Debugger.prototype.sendGetCallStackRequest = function () {
  1153. var _this = this;
  1154. return this.sendRequest([ DVAL_REQ, CMD_GETCALLSTACK, DVAL_EOM ]).then(function (msg) {
  1155. var i;
  1156. var stack = [];
  1157. for (i = 1; i + 3 <= msg.length - 1; i += 4) {
  1158. stack.push({
  1159. fileName: msg[i],
  1160. funcName: msg[i + 1],
  1161. lineNumber: msg[i + 2],
  1162. pc: msg[i + 3]
  1163. });
  1164. }
  1165. _this.callstack = stack;
  1166. _this.emit('callstack-update');
  1167. return msg;
  1168. });
  1169. };
  1170. Debugger.prototype.sendStepIntoRequest = function () {
  1171. var _this = this;
  1172. return this.sendRequest([ DVAL_REQ, CMD_STEPINTO, DVAL_EOM ]);
  1173. };
  1174. Debugger.prototype.sendStepOverRequest = function () {
  1175. var _this = this;
  1176. return this.sendRequest([ DVAL_REQ, CMD_STEPOVER, DVAL_EOM ]);
  1177. };
  1178. Debugger.prototype.sendStepOutRequest = function () {
  1179. var _this = this;
  1180. return this.sendRequest([ DVAL_REQ, CMD_STEPOUT, DVAL_EOM ]);
  1181. };
  1182. Debugger.prototype.sendPauseRequest = function () {
  1183. var _this = this;
  1184. return this.sendRequest([ DVAL_REQ, CMD_PAUSE, DVAL_EOM ]);
  1185. };
  1186. Debugger.prototype.sendResumeRequest = function () {
  1187. var _this = this;
  1188. return this.sendRequest([ DVAL_REQ, CMD_RESUME, DVAL_EOM ]);
  1189. };
  1190. Debugger.prototype.sendEvalRequest = function (evalInput, level) {
  1191. var _this = this;
  1192. // Use explicit level if given. If no level is given, use null if the call
  1193. // stack is empty, -1 otherwise. This works well when we're paused and the
  1194. // callstack information is not liable to change before we do an Eval.
  1195. if (typeof level !== 'number') {
  1196. level = this.callstack && this.callstack.length > 0 ? -1 : null;
  1197. }
  1198. return this.sendRequest([ DVAL_REQ, CMD_EVAL, level, evalInput, DVAL_EOM ]).then(function (msg) {
  1199. return { error: msg[1] === 1 /*error*/, value: msg[2] };
  1200. });
  1201. };
  1202. Debugger.prototype.sendDetachRequest = function () {
  1203. var _this = this;
  1204. return this.sendRequest([ DVAL_REQ, CMD_DETACH, DVAL_EOM ]);
  1205. };
  1206. Debugger.prototype.sendDumpHeapRequest = function () {
  1207. var _this = this;
  1208. return this.sendRequest([ DVAL_REQ, CMD_DUMPHEAP, DVAL_EOM ]).then(function (msg) {
  1209. var res = {};
  1210. var objs = [];
  1211. var i, j, n, m, o, prop;
  1212. res.type = 'heapDump';
  1213. res.heapObjects = objs;
  1214. for (i = 1, n = msg.length - 1; i < n; /*nop*/) {
  1215. o = {};
  1216. o.ptr = msg[i++];
  1217. o.type = msg[i++];
  1218. o.flags = msg[i++] >>> 0; /* unsigned */
  1219. o.refc = msg[i++];
  1220. if (o.type === DUK_HTYPE_STRING) {
  1221. o.blen = msg[i++];
  1222. o.clen = msg[i++];
  1223. o.hash = msg[i++] >>> 0; /* unsigned */
  1224. o.data = msg[i++];
  1225. } else if (o.type === DUK_HTYPE_BUFFER) {
  1226. o.len = msg[i++];
  1227. o.data = msg[i++];
  1228. } else if (o.type === DUK_HTYPE_OBJECT) {
  1229. o['class'] = msg[i++];
  1230. o.proto = msg[i++];
  1231. o.esize = msg[i++];
  1232. o.enext = msg[i++];
  1233. o.asize = msg[i++];
  1234. o.hsize = msg[i++];
  1235. o.props = [];
  1236. for (j = 0, m = o.enext; j < m; j++) {
  1237. prop = {};
  1238. prop.flags = msg[i++];
  1239. prop.key = msg[i++];
  1240. prop.accessor = (msg[i++] == 1);
  1241. if (prop.accessor) {
  1242. prop.getter = msg[i++];
  1243. prop.setter = msg[i++];
  1244. } else {
  1245. prop.value = msg[i++];
  1246. }
  1247. o.props.push(prop);
  1248. }
  1249. o.array = [];
  1250. for (j = 0, m = o.asize; j < m; j++) {
  1251. prop = {};
  1252. prop.value = msg[i++];
  1253. o.array.push(prop);
  1254. }
  1255. } else {
  1256. console.log('invalid htype: ' + o.type + ', disconnect');
  1257. _this.disconnectDebugger();
  1258. throw new Error('invalid htype');
  1259. return;
  1260. }
  1261. objs.push(o);
  1262. }
  1263. return res;
  1264. });
  1265. };
  1266. Debugger.prototype.sendGetBytecodeRequest = function () {
  1267. var _this = this;
  1268. return this.sendRequest([ DVAL_REQ, CMD_GETBYTECODE, -1 /* level; could be other than -1 too */, DVAL_EOM ]).then(function (msg) {
  1269. var idx = 1;
  1270. var nconst;
  1271. var nfunc;
  1272. var val;
  1273. var buf;
  1274. var i, n;
  1275. var consts = [];
  1276. var funcs = [];
  1277. var bcode;
  1278. var preformatted;
  1279. var ret;
  1280. var idxPreformattedInstructions;
  1281. //console.log(JSON.stringify(msg));
  1282. nconst = msg[idx++];
  1283. for (i = 0; i < nconst; i++) {
  1284. val = msg[idx++];
  1285. consts.push(val);
  1286. }
  1287. nfunc = msg[idx++];
  1288. for (i = 0; i < nfunc; i++) {
  1289. val = msg[idx++];
  1290. funcs.push(val);
  1291. }
  1292. val = msg[idx++];
  1293. // Right now bytecode is a string containing a direct dump of the
  1294. // bytecode in target endianness. Decode here so that the web UI
  1295. // doesn't need to.
  1296. buf = new Buffer(val.length);
  1297. writeDebugStringToBuffer(val, buf, 0);
  1298. bcode = _this.decodeBytecodeFromBuffer(buf, consts, funcs);
  1299. preformatted = [];
  1300. consts.forEach(function (v, i) {
  1301. preformatted.push('; c' + i + ' ' + JSON.stringify(v));
  1302. });
  1303. preformatted.push('');
  1304. idxPreformattedInstructions = preformatted.length;
  1305. bcode.forEach(function (v) {
  1306. preformatted.push(v.str);
  1307. });
  1308. preformatted = preformatted.join('\n') + '\n';
  1309. ret = {
  1310. constants: consts,
  1311. functions: funcs,
  1312. bytecode: bcode,
  1313. preformatted: preformatted,
  1314. idxPreformattedInstructions: idxPreformattedInstructions
  1315. };
  1316. return ret;
  1317. });
  1318. };
  1319. Debugger.prototype.changeBreakpoint = function (fileName, lineNumber, mode) {
  1320. var _this = this;
  1321. return this.sendRequest([ DVAL_REQ, CMD_LISTBREAK, DVAL_EOM ]).then(function (msg) {
  1322. var i, n;
  1323. var breakpts = [];
  1324. var deleted = false;
  1325. // Up-to-date list of breakpoints on target
  1326. for (i = 1, n = msg.length - 1; i < n; i += 2) {
  1327. breakpts.push({ fileName: msg[i], lineNumber: msg[i + 1] });
  1328. }
  1329. // Delete matching breakpoints in reverse order so that indices
  1330. // remain valid. We do this for all operations so that duplicates
  1331. // are eliminated if present.
  1332. for (i = breakpts.length - 1; i >= 0; i--) {
  1333. var bp = breakpts[i];
  1334. if (mode === 'deleteall' || (bp.fileName === fileName && bp.lineNumber === lineNumber)) {
  1335. deleted = true;
  1336. _this.sendRequest([ DVAL_REQ, CMD_DELBREAK, i, DVAL_EOM ], function (msg) {
  1337. // nop
  1338. }, function (err) {
  1339. // nop
  1340. });
  1341. }
  1342. }
  1343. // Technically we should wait for each delbreak reply but because
  1344. // target processes the requests in order, it doesn't matter.
  1345. if ((mode === 'add') || (mode === 'toggle' && !deleted)) {
  1346. _this.sendRequest([ DVAL_REQ, CMD_ADDBREAK, fileName, lineNumber, DVAL_EOM ], function (msg) {
  1347. // nop
  1348. }, function (err) {
  1349. _this.uiMessage('debugger-info', 'Failed to add breakpoint: ' + err);
  1350. });
  1351. }
  1352. // Read final, effective breakpoints from the target
  1353. _this.sendBreakpointListRequest();
  1354. });
  1355. };
  1356. Debugger.prototype.disconnectDebugger = function () {
  1357. if (this.targetStream) {
  1358. // We require a destroy() method from the actual target stream
  1359. this.targetStream.destroy();
  1360. this.targetStream = null;
  1361. }
  1362. if (this.inputParser) {
  1363. this.inputParser.close();
  1364. this.inputParser = null;
  1365. }
  1366. if (this.outputPassThroughStream) {
  1367. // There is no close() or destroy() for a passthrough stream, so just
  1368. // close the outputParser which will cancel timers etc.
  1369. }
  1370. if (this.outputParser) {
  1371. this.outputParser.close();
  1372. this.outputParser = null;
  1373. }
  1374. this.attached = false;
  1375. this.handshook = false;
  1376. this.reqQueue = null;
  1377. this.execStatus = {
  1378. attached: false,
  1379. state: 'detached',
  1380. fileName: '',
  1381. funcName: '',
  1382. line: 0,
  1383. pc: 0
  1384. };
  1385. };
  1386. Debugger.prototype.connectDebugger = function () {
  1387. var _this = this;
  1388. this.disconnectDebugger(); // close previous target connection
  1389. // CUSTOMTRANSPORT: to use a custom transport, change this.targetStream to
  1390. // use your custom transport.
  1391. console.log('Connecting to ' + optTargetHost + ':' + optTargetPort + '...');
  1392. this.targetStream = new net.Socket();
  1393. this.targetStream.connect(optTargetPort, optTargetHost, function () {
  1394. console.log('Debug transport connected');
  1395. _this.attached = true;
  1396. _this.reqQueue = [];
  1397. _this.uiMessage('debugger-info', 'Debug transport connected');
  1398. });
  1399. this.inputParser = new DebugProtocolParser(
  1400. this.targetStream,
  1401. null,
  1402. optDumpDebugRead,
  1403. optDumpDebugPretty,
  1404. optDumpDebugPretty ? 'Recv: ' : null,
  1405. null,
  1406. null // console logging is done at a higher level to match request/response
  1407. );
  1408. // Use a PassThrough stream to debug dump and get stats for output messages.
  1409. // Simply write outgoing data to both the targetStream and this passthrough
  1410. // separately.
  1411. this.outputPassThroughStream = stream.PassThrough();
  1412. this.outputParser = new DebugProtocolParser(
  1413. this.outputPassThroughStream,
  1414. 1,
  1415. optDumpDebugWrite,
  1416. optDumpDebugPretty,
  1417. optDumpDebugPretty ? 'Send: ' : null,
  1418. null,
  1419. null // console logging is done at a higher level to match request/response
  1420. );
  1421. this.inputParser.on('transport-close', function () {
  1422. _this.uiMessage('debugger-info', 'Debug transport closed');
  1423. _this.disconnectDebugger();
  1424. _this.emit('exec-status-update');
  1425. _this.emit('detached');
  1426. });
  1427. this.inputParser.on('transport-error', function (err) {
  1428. _this.uiMessage('debugger-info', 'Debug transport error: ' + err);
  1429. _this.disconnectDebugger();
  1430. });
  1431. this.inputParser.on('protocol-version', function (msg) {
  1432. var ver = msg.protocolVersion;
  1433. console.log('Debug version identification:', msg.versionIdentification);
  1434. _this.protocolVersion = ver;
  1435. _this.uiMessage('debugger-info', 'Debug version identification: ' + msg.versionIdentification);
  1436. if (ver !== SUPPORTED_DEBUG_PROTOCOL_VERSION) {
  1437. console.log('Unsupported debug protocol version (got ' + ver + ', support ' + SUPPORTED_DEBUG_PROTOCOL_VERSION + ')');
  1438. _this.uiMessage('debugger-info', 'Protocol version ' + ver + ' unsupported, dropping connection');
  1439. _this.targetStream.destroy();
  1440. } else {
  1441. _this.uiMessage('debugger-info', 'Debug protocol version: ' + ver);
  1442. _this.handshook = true;
  1443. _this.execStatus = {
  1444. attached: true,
  1445. state: 'attached',
  1446. fileName: '',
  1447. funcName: '',
  1448. line: 0,
  1449. pc: 0
  1450. };
  1451. _this.emit('exec-status-update');
  1452. _this.emit('attached'); // inform web UI
  1453. // Fetch basic info right away
  1454. _this.sendBasicInfoRequest();
  1455. }
  1456. });
  1457. this.inputParser.on('debug-message', function (msg) {
  1458. _this.processDebugMessage(msg);
  1459. });
  1460. this.inputParser.on('stats-update', function () {
  1461. _this.stats.rxBytes = this.bytes;
  1462. _this.stats.rxDvalues = this.dvalues;
  1463. _this.stats.rxMessages = this.messages;
  1464. _this.stats.rxBytesPerSec = this.bytesPerSec;
  1465. _this.emit('debug-stats-update');
  1466. });
  1467. this.outputParser.on('stats-update', function () {
  1468. _this.stats.txBytes = this.bytes;
  1469. _this.stats.txDvalues = this.dvalues;
  1470. _this.stats.txMessages = this.messages;
  1471. _this.stats.txBytesPerSec = this.bytesPerSec;
  1472. _this.emit('debug-stats-update');
  1473. });
  1474. };
  1475. Debugger.prototype.processDebugMessage = function (msg) {
  1476. var req;
  1477. var prevState, newState;
  1478. var err;
  1479. if (msg[0] === DVAL_REQ) {
  1480. // No actual requests sent by the target right now (just notifys).
  1481. console.log('Unsolicited reply message, dropping connection: ' + prettyDebugMessage(msg));
  1482. } else if (msg[0] === DVAL_REP) {
  1483. if (this.reqQueue.length <= 0) {
  1484. console.log('Unsolicited reply message, dropping connection: ' + prettyDebugMessage(msg));
  1485. this.targetStream.destroy();
  1486. }
  1487. req = this.reqQueue.shift();
  1488. if (optLogMessages) {
  1489. console.log('Reply for ' + prettyDebugCommand(req.reqCmd) + ': ' + prettyDebugMessage(msg));
  1490. }
  1491. if (req.resolveCb) {
  1492. req.resolveCb(msg);
  1493. } else {
  1494. // nop: no callback
  1495. }
  1496. } else if (msg[0] === DVAL_ERR) {
  1497. if (this.reqQueue.length <= 0) {
  1498. console.log('Unsolicited error message, dropping connection: ' + prettyDebugMessage(msg));
  1499. this.targetStream.destroy();
  1500. }
  1501. err = new Error(String(msg[2]) + ' (code ' + String(msg[1]) + ')');
  1502. err.errorCode = msg[1] || 0;
  1503. req = this.reqQueue.shift();
  1504. if (optLogMessages) {
  1505. console.log('Error for ' + prettyDebugCommand(req.reqCmd) + ': ' + prettyDebugMessage(msg));
  1506. }
  1507. if (req.rejectCb) {
  1508. req.rejectCb(err);
  1509. } else {
  1510. // nop: no callback
  1511. }
  1512. } else if (msg[0] === DVAL_NFY) {
  1513. if (optLogMessages) {
  1514. console.log('Notify ' + prettyDebugCommand(msg[1]) + ': ' + prettyDebugMessage(msg));
  1515. }
  1516. if (msg[1] === CMD_STATUS) {
  1517. prevState = this.execStatus.state;
  1518. newState = msg[2] === 0 ? 'running' : 'paused';
  1519. this.execStatus = {
  1520. attached: true,
  1521. state: newState,
  1522. fileName: msg[3],
  1523. funcName: msg[4],
  1524. line: msg[5],
  1525. pc: msg[6]
  1526. };
  1527. if (prevState !== newState && newState === 'paused') {
  1528. // update run state now that we're paused
  1529. this.sendBreakpointListRequest();
  1530. this.sendGetLocalsRequest();
  1531. this.sendGetCallStackRequest();
  1532. }
  1533. this.emit('exec-status-update');
  1534. } else if (msg[1] === CMD_THROW) {
  1535. this.uiMessage({ type: 'throw', fatal: msg[2], message: (msg[2] ? 'UNCAUGHT: ' : 'THROW: ') + prettyUiStringUnquoted(msg[3], UI_MESSAGE_CLIPLEN), fileName: msg[4], lineNumber: msg[5] });
  1536. } else if (msg[1] === CMD_DETACHING) {
  1537. this.uiMessage({ type: 'detaching', reason: msg[2], message: 'DETACH: ' + (msg.length >= 5 ? prettyUiStringUnquoted(msg[3]) : 'detaching') });
  1538. } else {
  1539. // Ignore unknown notify messages
  1540. console.log('Unknown notify, ignoring: ' + prettyDebugMessage(msg));
  1541. //this.targetStream.destroy();
  1542. }
  1543. } else {
  1544. console.log('Invalid initial dvalue, dropping connection: ' + prettyDebugMessage(msg));
  1545. this.targetStream.destroy();
  1546. }
  1547. };
  1548. Debugger.prototype.run = function () {
  1549. var _this = this;
  1550. // Initial debugger connection
  1551. this.connectDebugger();
  1552. // Poll various state items when running
  1553. var sendRound = 0;
  1554. var statusPending = false;
  1555. var bplistPending = false;
  1556. var localsPending = false;
  1557. var callStackPending = false;
  1558. setInterval(function () {
  1559. if (_this.execStatus.state !== 'running') {
  1560. return;
  1561. }
  1562. // Could also check for an empty request queue, but that's probably
  1563. // too strict?
  1564. // Pending flags are used to avoid requesting the same thing twice
  1565. // while a previous request is pending. The flag-based approach is
  1566. // quite awkward. Rework to use promises.
  1567. switch (sendRound) {
  1568. case 0:
  1569. if (!statusPending) {
  1570. statusPending = true;
  1571. _this.sendStatusRequest().finally(function () { statusPending = false; });
  1572. }
  1573. break;
  1574. case 1:
  1575. if (!bplistPending) {
  1576. bplistPending = true;
  1577. _this.sendBreakpointListRequest().finally(function () { bplistPending = false; });
  1578. }
  1579. break;
  1580. case 2:
  1581. if (!localsPending) {
  1582. localsPending = true;
  1583. _this.sendGetLocalsRequest().finally(function () { localsPending = false; });
  1584. }
  1585. break;
  1586. case 3:
  1587. if (!callStackPending) {
  1588. callStackPending = true;
  1589. _this.sendGetCallStackRequest().finally(function () { callStackPending = false; });
  1590. }
  1591. break;
  1592. }
  1593. sendRound = (sendRound + 1) % 4;
  1594. }, 500);
  1595. };
  1596. /*
  1597. * Express setup and socket.io
  1598. */
  1599. function DebugWebServer() {
  1600. this.dbg = null; // debugger singleton
  1601. this.socket = null; // current socket (or null)
  1602. this.keepaliveTimer = null;
  1603. this.uiMessageLimiter = null;
  1604. this.cachedJson = {}; // cache to avoid resending identical data
  1605. this.sourceFileManager = new SourceFileManager(optSourceSearchDirs);
  1606. this.sourceFileManager.scan();
  1607. }
  1608. DebugWebServer.prototype.handleSourcePost = function (req, res) {
  1609. var fileName = req.body && req.body.fileName;
  1610. var fileData;
  1611. console.log('Source request: ' + fileName);
  1612. if (typeof fileName !== 'string') {
  1613. res.status(500).send('invalid request');
  1614. return;
  1615. }
  1616. fileData = this.sourceFileManager.search(fileName, optSourceSearchDirs);
  1617. if (typeof fileData !== 'string') {
  1618. res.status(404).send('not found');
  1619. return;
  1620. }
  1621. res.status(200).send(fileData); // UTF-8
  1622. };
  1623. DebugWebServer.prototype.handleSourceListPost = function (req, res) {
  1624. console.log('Source list request');
  1625. var files = this.sourceFileManager.getFiles();
  1626. res.header('Content-Type', 'application/json');
  1627. res.status(200).json(files);
  1628. };
  1629. DebugWebServer.prototype.handleHeapDumpGet = function (req, res) {
  1630. console.log('Heap dump get');
  1631. this.dbg.sendDumpHeapRequest().then(function (val) {
  1632. res.header('Content-Type', 'application/json');
  1633. //res.status(200).json(val);
  1634. res.status(200).send(JSON.stringify(val, null, 4));
  1635. }).catch(function (err) {
  1636. res.status(500).send('Failed to get heap dump: ' + (err.stack || err));
  1637. });
  1638. };
  1639. DebugWebServer.prototype.run = function () {
  1640. var _this = this;
  1641. var express = require('express');
  1642. var bodyParser = require('body-parser');
  1643. var app = express();
  1644. var http = require('http').Server(app);
  1645. var io = require('socket.io')(http);
  1646. app.use(bodyParser.json());
  1647. app.post('/source', this.handleSourcePost.bind(this));
  1648. app.post('/sourceList', this.handleSourceListPost.bind(this));
  1649. app.get('/heapDump.json', this.handleHeapDumpGet.bind(this));
  1650. app.use('/', express.static(__dirname + '/static'));
  1651. http.listen(optHttpPort, function () {
  1652. console.log('Listening on *:' + optHttpPort);
  1653. });
  1654. io.on('connection', this.handleNewSocketIoConnection.bind(this));
  1655. this.dbg.on('attached', function () {
  1656. console.log('Debugger attached');
  1657. });
  1658. this.dbg.on('detached', function () {
  1659. console.log('Debugger detached');
  1660. });
  1661. this.dbg.on('debug-stats-update', function () {
  1662. _this.debugStatsLimiter.trigger();
  1663. });
  1664. this.dbg.on('ui-message-update', function () {
  1665. // Explicit rate limiter because this is a source of a lot of traffic.
  1666. _this.uiMessageLimiter.trigger();
  1667. });
  1668. this.dbg.on('basic-info-update', function () {
  1669. _this.emitBasicInfo();
  1670. });
  1671. this.dbg.on('breakpoints-update', function () {
  1672. _this.emitBreakpoints();
  1673. });
  1674. this.dbg.on('exec-status-update', function () {
  1675. // Explicit rate limiter because this is a source of a lot of traffic.
  1676. _this.execStatusLimiter.trigger();
  1677. });
  1678. this.dbg.on('locals-update', function () {
  1679. _this.emitLocals();
  1680. });
  1681. this.dbg.on('callstack-update', function () {
  1682. _this.emitCallStack();
  1683. });
  1684. this.uiMessageLimiter = new RateLimited(10, 1000, this.uiMessageLimiterCallback.bind(this));
  1685. this.execStatusLimiter = new RateLimited(50, 500, this.execStatusLimiterCallback.bind(this));
  1686. this.debugStatsLimiter = new RateLimited(1, 2000, this.debugStatsLimiterCallback.bind(this));
  1687. this.keepaliveTimer = setInterval(this.emitKeepalive.bind(this), 30000);
  1688. };
  1689. DebugWebServer.prototype.handleNewSocketIoConnection = function (socket) {
  1690. var _this = this;
  1691. console.log('Socket.io connected');
  1692. if (this.socket) {
  1693. console.log('Closing previous socket.io socket');
  1694. this.socket.emit('replaced');
  1695. }
  1696. this.socket = socket;
  1697. this.emitKeepalive();
  1698. socket.on('disconnect', function () {
  1699. console.log('Socket.io disconnected');
  1700. if (_this.socket === socket) {
  1701. _this.socket = null;
  1702. }
  1703. });
  1704. socket.on('keepalive', function (msg) {
  1705. // nop
  1706. });
  1707. socket.on('attach', function (msg) {
  1708. if (_this.dbg.targetStream) {
  1709. console.log('Attach request when debugger already has a connection, ignoring');
  1710. } else {
  1711. _this.dbg.connectDebugger();
  1712. }
  1713. });
  1714. socket.on('detach', function (msg) {
  1715. // Try to detach cleanly, timeout if no response
  1716. Promise.any([
  1717. _this.dbg.sendDetachRequest(),
  1718. Promise.delay(3000)
  1719. ]).finally(function () {
  1720. _this.dbg.disconnectDebugger();
  1721. });
  1722. });
  1723. socket.on('stepinto', function (msg) {
  1724. _this.dbg.sendStepIntoRequest();
  1725. });
  1726. socket.on('stepover', function (msg) {
  1727. _this.dbg.sendStepOverRequest();
  1728. });
  1729. socket.on('stepout', function (msg) {
  1730. _this.dbg.sendStepOutRequest();
  1731. });
  1732. socket.on('pause', function (msg) {
  1733. _this.dbg.sendPauseRequest();
  1734. });
  1735. socket.on('resume', function (msg) {
  1736. _this.dbg.sendResumeRequest();
  1737. });
  1738. socket.on('eval', function (msg) {
  1739. // msg.input is a proper Unicode strings here, and needs to be
  1740. // converted into a protocol string (U+0000...U+00FF).
  1741. var input = stringToDebugString(msg.input);
  1742. _this.dbg.sendEvalRequest(input, msg.level).then(function (v) {
  1743. socket.emit('eval-result', { error: v.error, result: prettyUiDebugValue(v.value, EVAL_CLIPLEN) });
  1744. });
  1745. // An eval call quite possibly changes the local variables so always
  1746. // re-read locals afterwards. We don't need to wait for Eval to
  1747. // complete here; the requests will pipeline automatically and be
  1748. // executed in order.
  1749. // XXX: move this to the web UI so that the UI can control what
  1750. // locals are listed (or perhaps show locals for all levels with
  1751. // an expandable tree view).
  1752. _this.dbg.sendGetLocalsRequest();
  1753. });
  1754. socket.on('getvar', function (msg) {
  1755. // msg.varname is a proper Unicode strings here, and needs to be
  1756. // converted into a protocol string (U+0000...U+00FF).
  1757. var varname = stringToDebugString(msg.varname);
  1758. _this.dbg.sendGetVarRequest(varname, msg.level)
  1759. .then(function (v) {
  1760. socket.emit('getvar-result', { found: v.found, result: prettyUiDebugValue(v.value, GETVAR_CLIPLEN) });
  1761. });
  1762. });
  1763. socket.on('putvar', function (msg) {
  1764. // msg.varname and msg.varvalue are proper Unicode strings here, they
  1765. // need to be converted into protocol strings (U+0000...U+00FF).
  1766. var varname = stringToDebugString(msg.varname);
  1767. var varvalue = msg.varvalue;
  1768. // varvalue is JSON parsed by the web UI for now, need special string
  1769. // encoding here.
  1770. if (typeof varvalue === 'string') {
  1771. varvalue = stringToDebugString(msg.varvalue);
  1772. }
  1773. _this.dbg.sendPutVarRequest(varname, varvalue, msg.level)
  1774. .then(function (v) {
  1775. console.log('putvar done'); // XXX: signal success to UI?
  1776. });
  1777. // A PutVar call quite possibly changes the local variables so always
  1778. // re-read locals afterwards. We don't need to wait for PutVar to
  1779. // complete here; the requests will pipeline automatically and be
  1780. // executed in order.
  1781. // XXX: make the client do this?
  1782. _this.dbg.sendGetLocalsRequest();
  1783. });
  1784. socket.on('add-breakpoint', function (msg) {
  1785. _this.dbg.changeBreakpoint(msg.fileName, msg.lineNumber, 'add');
  1786. });
  1787. socket.on('delete-breakpoint', function (msg) {
  1788. _this.dbg.changeBreakpoint(msg.fileName, msg.lineNumber, 'delete');
  1789. });
  1790. socket.on('toggle-breakpoint', function (msg) {
  1791. _this.dbg.changeBreakpoint(msg.fileName, msg.lineNumber, 'toggle');
  1792. });
  1793. socket.on('delete-all-breakpoints', function (msg) {
  1794. _this.dbg.changeBreakpoint(null, null, 'deleteall');
  1795. });
  1796. socket.on('get-bytecode', function (msg) {
  1797. _this.dbg.sendGetBytecodeRequest().then(function (res) {
  1798. socket.emit('bytecode', res);
  1799. });
  1800. });
  1801. // Resend all debugger state for new client
  1802. this.cachedJson = {}; // clear client state cache
  1803. this.emitBasicInfo();
  1804. this.emitStats();
  1805. this.emitExecStatus();
  1806. this.emitUiMessages();
  1807. this.emitBreakpoints();
  1808. this.emitCallStack();
  1809. this.emitLocals();
  1810. };
  1811. // Check if 'msg' would encode to the same JSON which was previously sent
  1812. // to the web client. The caller then avoid resending unnecessary stuff.
  1813. DebugWebServer.prototype.cachedJsonCheck = function (cacheKey, msg) {
  1814. var newJson = JSON.stringify(msg);
  1815. if (this.cachedJson[cacheKey] === newJson) {
  1816. return true; // cached
  1817. }
  1818. this.cachedJson[cacheKey] = newJson;
  1819. return false; // not cached, send (cache already updated)
  1820. };
  1821. DebugWebServer.prototype.uiMessageLimiterCallback = function () {
  1822. this.emitUiMessages();
  1823. };
  1824. DebugWebServer.prototype.execStatusLimiterCallback = function () {
  1825. this.emitExecStatus();
  1826. };
  1827. DebugWebServer.prototype.debugStatsLimiterCallback = function () {
  1828. this.emitStats();
  1829. };
  1830. DebugWebServer.prototype.emitKeepalive = function () {
  1831. if (!this.socket) { return; }
  1832. this.socket.emit('keepalive', { nodeVersion: process.version });
  1833. };
  1834. DebugWebServer.prototype.emitBasicInfo = function () {
  1835. if (!this.socket) { return; }
  1836. var newMsg = {
  1837. duk_version: this.dbg.dukVersion,
  1838. duk_git_describe: this.dbg.dukGitDescribe,
  1839. target_info: this.dbg.targetInfo,
  1840. endianness: this.dbg.endianness
  1841. };
  1842. if (this.cachedJsonCheck('basic-info', newMsg)) {
  1843. return;
  1844. }
  1845. this.socket.emit('basic-info', newMsg);
  1846. };
  1847. DebugWebServer.prototype.emitStats = function () {
  1848. if (!this.socket) { return; }
  1849. this.socket.emit('debug-stats', this.dbg.stats);
  1850. };
  1851. DebugWebServer.prototype.emitExecStatus = function () {
  1852. if (!this.socket) { return; }
  1853. var newMsg = this.dbg.execStatus;
  1854. if (this.cachedJsonCheck('exec-status', newMsg)) {
  1855. return;
  1856. }
  1857. this.socket.emit('exec-status', newMsg);
  1858. };
  1859. DebugWebServer.prototype.emitUiMessages = function () {
  1860. if (!this.socket) { return; }
  1861. var newMsg = this.dbg.messageLines;
  1862. if (this.cachedJsonCheck('output-lines', newMsg)) {
  1863. return;
  1864. }
  1865. this.socket.emit('output-lines', newMsg);
  1866. };
  1867. DebugWebServer.prototype.emitBreakpoints = function () {
  1868. if (!this.socket) { return; }
  1869. var newMsg = { breakpoints: this.dbg.breakpoints };
  1870. if (this.cachedJsonCheck('breakpoints', newMsg)) {
  1871. return;
  1872. }
  1873. this.socket.emit('breakpoints', newMsg);
  1874. };
  1875. DebugWebServer.prototype.emitCallStack = function () {
  1876. if (!this.socket) { return; }
  1877. var newMsg = { callstack: this.dbg.callstack };
  1878. if (this.cachedJsonCheck('callstack', newMsg)) {
  1879. return;
  1880. }
  1881. this.socket.emit('callstack', newMsg);
  1882. };
  1883. DebugWebServer.prototype.emitLocals = function () {
  1884. if (!this.socket) { return; }
  1885. var newMsg = { locals: this.dbg.locals };
  1886. if (this.cachedJsonCheck('locals', newMsg)) {
  1887. return;
  1888. }
  1889. this.socket.emit('locals', newMsg);
  1890. };
  1891. /*
  1892. * JSON debug proxy
  1893. */
  1894. function DebugProxy(serverPort) {
  1895. this.serverPort = serverPort;
  1896. this.server = null;
  1897. this.socket = null;
  1898. this.targetStream = null;
  1899. this.inputParser = null;
  1900. // preformatted dvalues
  1901. this.dval_eom = formatDebugValue(DVAL_EOM);
  1902. this.dval_req = formatDebugValue(DVAL_REQ);
  1903. this.dval_rep = formatDebugValue(DVAL_REP);
  1904. this.dval_nfy = formatDebugValue(DVAL_NFY);
  1905. this.dval_err = formatDebugValue(DVAL_ERR);
  1906. }
  1907. DebugProxy.prototype.determineCommandNumber = function (cmdName, cmdNumber) {
  1908. var ret;
  1909. if (typeof cmdName === 'string') {
  1910. ret = debugCommandNumbers[cmdName];
  1911. } else if (typeof cmdName === 'number') {
  1912. ret = cmdName;
  1913. }
  1914. ret = ret || cmdNumber;
  1915. if (typeof ret !== 'number') {
  1916. throw Error('cannot figure out command number for "' + cmdName + '" (' + cmdNumber + ')');
  1917. }
  1918. return ret;
  1919. };
  1920. DebugProxy.prototype.commandNumberToString = function (id) {
  1921. return debugCommandNames[id] || String(id);
  1922. };
  1923. DebugProxy.prototype.formatDvalues = function (args) {
  1924. if (!args) {
  1925. return [];
  1926. }
  1927. return args.map(function (v) {
  1928. return formatDebugValue(v);
  1929. });
  1930. };
  1931. DebugProxy.prototype.writeJson = function (val) {
  1932. this.socket.write(JSON.stringify(val) + '\n');
  1933. };
  1934. DebugProxy.prototype.writeJsonSafe = function (val) {
  1935. try {
  1936. this.writeJson(val);
  1937. } catch (e) {
  1938. console.log('Failed to write JSON in writeJsonSafe, ignoring: ' + e);
  1939. }
  1940. };
  1941. DebugProxy.prototype.disconnectJsonClient = function () {
  1942. if (this.socket) {
  1943. this.socket.destroy();
  1944. this.socket = null;
  1945. }
  1946. };
  1947. DebugProxy.prototype.disconnectTarget = function () {
  1948. if (this.inputParser) {
  1949. this.inputParser.close();
  1950. this.inputParser = null;
  1951. }
  1952. if (this.targetStream) {
  1953. this.targetStream.destroy();
  1954. this.targetStream = null;
  1955. }
  1956. };
  1957. DebugProxy.prototype.run = function () {
  1958. var _this = this;
  1959. console.log('Waiting for client connections on port ' + this.serverPort);
  1960. this.server = net.createServer(function (socket) {
  1961. console.log('JSON proxy client connected');
  1962. _this.disconnectJsonClient();
  1963. _this.disconnectTarget();
  1964. // A byline-parser is simple and good enough for now (assume
  1965. // compact JSON with no newlines).
  1966. var socketByline = byline(socket);
  1967. _this.socket = socket;
  1968. socketByline.on('data', function (line) {
  1969. try {
  1970. // console.log('Received json proxy input line: ' + line.toString('utf8'));
  1971. var msg = JSON.parse(line.toString('utf8'));
  1972. var first_dval;
  1973. var args_dvalues = _this.formatDvalues(msg.args);
  1974. var last_dval = _this.dval_eom;
  1975. var cmd;
  1976. if (msg.request) {
  1977. // "request" can be a string or "true"
  1978. first_dval = _this.dval_req;
  1979. cmd = _this.determineCommandNumber(msg.request, msg.command);
  1980. } else if (msg.reply) {
  1981. first_dval = _this.dval_rep;
  1982. } else if (msg.notify) {
  1983. // "notify" can be a string or "true"
  1984. first_dval = _this.dval_nfy;
  1985. cmd = _this.determineCommandNumber(msg.notify, msg.command);
  1986. } else if (msg.error) {
  1987. first_dval = _this.dval_err;
  1988. } else {
  1989. throw new Error('Invalid input JSON message: ' + JSON.stringify(msg));
  1990. }
  1991. _this.targetStream.write(first_dval);
  1992. if (cmd) {
  1993. _this.targetStream.write(formatDebugValue(cmd));
  1994. }
  1995. args_dvalues.forEach(function (v) {
  1996. _this.targetStream.write(v);
  1997. });
  1998. _this.targetStream.write(last_dval);
  1999. } catch (e) {
  2000. console.log(e);
  2001. _this.writeJsonSafe({
  2002. notify: '_Error',
  2003. args: [ 'Failed to handle input json message: ' + e ]
  2004. });
  2005. _this.disconnectJsonClient();
  2006. _this.disconnectTarget();
  2007. }
  2008. });
  2009. _this.connectToTarget();
  2010. }).listen(this.serverPort);
  2011. };
  2012. DebugProxy.prototype.connectToTarget = function () {
  2013. var _this = this;
  2014. console.log('Connecting to ' + optTargetHost + ':' + optTargetPort + '...');
  2015. this.targetStream = new net.Socket();
  2016. this.targetStream.connect(optTargetPort, optTargetHost, function () {
  2017. console.log('Debug transport connected');
  2018. });
  2019. this.inputParser = new DebugProtocolParser(
  2020. this.targetStream,
  2021. null,
  2022. optDumpDebugRead,
  2023. optDumpDebugPretty,
  2024. optDumpDebugPretty ? 'Recv: ' : null,
  2025. null,
  2026. null // console logging is done at a higher level to match request/response
  2027. );
  2028. // Don't add a 'value' key to numbers.
  2029. this.inputParser.readableNumberValue = false;
  2030. this.inputParser.on('transport-close', function () {
  2031. console.log('Debug transport closed');
  2032. _this.writeJsonSafe({
  2033. notify: '_Disconnecting'
  2034. });
  2035. _this.disconnectJsonClient();
  2036. _this.disconnectTarget();
  2037. });
  2038. this.inputParser.on('transport-error', function (err) {
  2039. console.log('Debug transport error', err);
  2040. _this.writeJsonSafe({
  2041. notify: '_Error',
  2042. args: [ String(err) ]
  2043. });
  2044. });
  2045. this.inputParser.on('protocol-version', function (msg) {
  2046. var ver = msg.protocolVersion;
  2047. console.log('Debug version identification:', msg.versionIdentification);
  2048. _this.writeJson({
  2049. notify: '_TargetConnected',
  2050. args: [ msg.versionIdentification ] // raw identification string
  2051. });
  2052. if (ver !== 1) {
  2053. console.log('Protocol version ' + ver + ' unsupported, dropping connection');
  2054. }
  2055. });
  2056. this.inputParser.on('debug-message', function (msg) {
  2057. var t;
  2058. //console.log(msg);
  2059. if (typeof msg[0] !== 'object' || msg[0] === null) {
  2060. throw new Error('unexpected initial dvalue: ' + msg[0]);
  2061. } else if (msg[0].type === 'eom') {
  2062. throw new Error('unexpected initial dvalue: ' + msg[0]);
  2063. } else if (msg[0].type === 'req') {
  2064. if (typeof msg[1] !== 'number') {
  2065. throw new Error('unexpected request command number: ' + msg[1]);
  2066. }
  2067. t = {
  2068. request: _this.commandNumberToString(msg[1]),
  2069. command: msg[1],
  2070. args: msg.slice(2, msg.length - 1)
  2071. };
  2072. _this.writeJson(t);
  2073. } else if (msg[0].type === 'rep') {
  2074. t = {
  2075. reply: true,
  2076. args: msg.slice(1, msg.length - 1)
  2077. };
  2078. _this.writeJson(t);
  2079. } else if (msg[0].type === 'err') {
  2080. t = {
  2081. error: true,
  2082. args: msg.slice(1, msg.length - 1)
  2083. };
  2084. _this.writeJson(t);
  2085. } else if (msg[0].type === 'nfy') {
  2086. if (typeof msg[1] !== 'number') {
  2087. throw new Error('unexpected notify command number: ' + msg[1]);
  2088. }
  2089. t = {
  2090. notify: _this.commandNumberToString(msg[1]),
  2091. command: msg[1],
  2092. args: msg.slice(2, msg.length - 1)
  2093. };
  2094. _this.writeJson(t);
  2095. } else {
  2096. throw new Error('unexpected initial dvalue: ' + msg[0]);
  2097. }
  2098. });
  2099. this.inputParser.on('stats-update', function () {
  2100. });
  2101. };
  2102. /*
  2103. * Command line parsing and initialization
  2104. */
  2105. function main() {
  2106. console.log('((o) Duktape debugger');
  2107. // Parse arguments.
  2108. var argv = require('minimist')(process.argv.slice(2));
  2109. //console.dir(argv);
  2110. if (argv['target-host']) {
  2111. optTargetHost = argv['target-host'];
  2112. }
  2113. if (argv['target-port']) {
  2114. optTargetPort = argv['target-port'];
  2115. }
  2116. if (argv['http-port']) {
  2117. optHttpPort = argv['http-port'];
  2118. }
  2119. if (argv['json-proxy-port']) {
  2120. optJsonProxyPort = argv['json-proxy-port'];
  2121. }
  2122. if (argv['json-proxy']) {
  2123. optJsonProxy = argv['json-proxy'];
  2124. }
  2125. if (argv['source-dirs']) {
  2126. optSourceSearchDirs = argv['source-dirs'].split(path.delimiter);
  2127. }
  2128. if (argv['dump-debug-read']) {
  2129. optDumpDebugRead = argv['dump-debug-read'];
  2130. }
  2131. if (argv['dump-debug-write']) {
  2132. optDumpDebugWrite = argv['dump-debug-write'];
  2133. }
  2134. if (argv['dump-debug-pretty']) {
  2135. optDumpDebugPretty = argv['dump-debug-pretty'];
  2136. }
  2137. if (argv['log-messages']) {
  2138. optLogMessages = true;
  2139. }
  2140. // Dump effective options. Also provides a list of option names.
  2141. console.log('');
  2142. console.log('Effective options:');
  2143. console.log(' --target-host: ' + optTargetHost);
  2144. console.log(' --target-port: ' + optTargetPort);
  2145. console.log(' --http-port: ' + optHttpPort);
  2146. console.log(' --json-proxy-port: ' + optJsonProxyPort);
  2147. console.log(' --json-proxy: ' + optJsonProxy);
  2148. console.log(' --source-dirs: ' + optSourceSearchDirs.join(' '));
  2149. console.log(' --dump-debug-read: ' + optDumpDebugRead);
  2150. console.log(' --dump-debug-write: ' + optDumpDebugWrite);
  2151. console.log(' --dump-debug-pretty: ' + optDumpDebugPretty);
  2152. console.log(' --log-messages: ' + optLogMessages);
  2153. console.log('');
  2154. // Create debugger and web UI singletons, tie them together and
  2155. // start them.
  2156. if (optJsonProxy) {
  2157. console.log('Starting in JSON proxy mode, JSON port: ' + optJsonProxyPort);
  2158. var prx = new DebugProxy(optJsonProxyPort);
  2159. prx.run();
  2160. } else {
  2161. var dbg = new Debugger();
  2162. var web = new DebugWebServer();
  2163. dbg.web = web;
  2164. web.dbg = dbg;
  2165. dbg.run();
  2166. web.run();
  2167. }
  2168. }
  2169. main();