DbgController.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. var TRACE_NONE = 0x0000;
  7. var TRACE_COMMANDS = 0x001;
  8. var TRACE_DIAG_OUTPUT = 0x002;
  9. var TRACE_INTERNAL_FUNCTIONS = 0x004;
  10. var TRACE_DEBUG_EVENTS = 0x008;
  11. var TRACE_ALL = TRACE_COMMANDS | TRACE_DIAG_OUTPUT | TRACE_INTERNAL_FUNCTIONS | TRACE_DEBUG_EVENTS;
  12. // Have all JsDiag* functions installed on it by Debugger.cpp
  13. var hostDebugObject = {};
  14. var controllerObj = (function () {
  15. var _commandList = [];
  16. var _commandCompletions = [];
  17. var _wasResumed = false;
  18. var _currentStackFrameIndex = 0;
  19. var _trace = TRACE_NONE;
  20. var _eventLog = [];
  21. var _baseline = undefined;
  22. var _exceptionCommands = undefined;
  23. var _onasyncbreakCommands = undefined;
  24. var _inspectMaxStringLength = 16;
  25. function internalPrint(str) {
  26. WScript.Echo(str);
  27. }
  28. function isTracing(traceFlag) {
  29. return _trace & traceFlag;
  30. }
  31. function internalTrace(traceFlag, ...varArgs) {
  32. if (isTracing(traceFlag)) {
  33. var str = "";
  34. varArgs.map(function (element) {
  35. str += (typeof element != "string") ? JSON.stringify(element, undefined, " ") : element;
  36. });
  37. internalPrint(str);
  38. }
  39. }
  40. function printError(str) {
  41. internalPrint("Error: " + str);
  42. }
  43. function callHostFunction(fn) {
  44. var result = fn.apply(undefined, [].slice.call(arguments, 1));
  45. var obj = {};
  46. obj[fn.name] = result;
  47. internalTrace(TRACE_DIAG_OUTPUT, obj);
  48. return result;
  49. }
  50. filterLog = (function () {
  51. var parentFilter = { "this": 1, "locals": 1, "globals": 1 };
  52. var filter = {};
  53. // Discard all known globals to reduce baseline noise.
  54. [
  55. "#__proto__",
  56. "globalThis",
  57. "AggregateError",
  58. "Array",
  59. "ArrayBuffer",
  60. "Atomics",
  61. "Boolean",
  62. "chWriteTraceEvent",
  63. "CollectGarbage",
  64. "console",
  65. "DataView",
  66. "Date",
  67. "decodeURI",
  68. "decodeURIComponent",
  69. "encodeURI",
  70. "encodeURIComponent",
  71. "Error",
  72. "escape",
  73. "eval",
  74. "EvalError",
  75. "Float32Array",
  76. "Float64Array",
  77. "Function",
  78. "Infinity",
  79. "Int16Array",
  80. "Int32Array",
  81. "Int8Array",
  82. "Intl",
  83. "isFinite",
  84. "isNaN",
  85. "JSON",
  86. "Map",
  87. "Math",
  88. "NaN",
  89. "Number",
  90. "Object",
  91. "parseFloat",
  92. "parseInt",
  93. "print",
  94. "Promise",
  95. "Proxy",
  96. "RangeError",
  97. "read",
  98. "readbuffer",
  99. "readline",
  100. "ReferenceError",
  101. "Reflect",
  102. "RegExp",
  103. "Set",
  104. "SharedArrayBuffer",
  105. "String",
  106. "Symbol",
  107. "SyntaxError",
  108. "TypeError",
  109. "Uint16Array",
  110. "Uint32Array",
  111. "Uint8Array",
  112. "Uint8ClampedArray",
  113. "undefined",
  114. "unescape",
  115. "URIError",
  116. "WeakMap",
  117. "WeakSet",
  118. "WebAssembly",
  119. "WScript",
  120. ].forEach(function (name) {
  121. filter[name] = 1;
  122. });
  123. function filterInternal(parentName, obj, depth) {
  124. for (var p in obj) {
  125. if (parentFilter[parentName] == 1 && filter[p] == 1) {
  126. delete obj[p];
  127. } else if (typeof obj[p] == "object") {
  128. filterInternal(p.trim(), obj[p], depth + 1);
  129. }
  130. }
  131. }
  132. return function (obj) {
  133. try {
  134. filterInternal("this"/*filter root*/, obj, 0);
  135. } catch (ex) {
  136. printError("exception during filter: " + ex);
  137. }
  138. };
  139. })();
  140. function recordEvent(json) {
  141. filterLog(json);
  142. _eventLog.push(json);
  143. }
  144. // remove path from file name and just have the filename with extension
  145. function filterFileName(fileName) {
  146. try {
  147. var index = fileName.lastIndexOf("\\");
  148. if (index === -1) {
  149. index = fileName.lastIndexOf("/");
  150. }
  151. return fileName.substring(index + 1);
  152. } catch (ex) { }
  153. return "";
  154. }
  155. var bpManager = (function () {
  156. var _bpMap = [];
  157. var _locBpId = -1;
  158. function getBpFromName(name) {
  159. for (var i in _bpMap) {
  160. if (_bpMap[i].name === name) {
  161. return _bpMap[i];
  162. }
  163. }
  164. printError("Breakpoint named '" + name + "' was not found");
  165. }
  166. function internalSetBp(name, scriptId, line, column, execStr) {
  167. var bpObject = callHostFunction(hostDebugObject.JsDiagSetBreakpoint, scriptId, line, column);
  168. return {
  169. id: bpObject.breakpointId,
  170. scriptId: scriptId,
  171. name: name,
  172. line: bpObject.line,
  173. column: bpObject.column,
  174. execStr: execStr,
  175. enabled: true
  176. };
  177. }
  178. function addBpObject(bpObj) {
  179. internalTrace(TRACE_INTERNAL_FUNCTIONS, "addBpObject: ", bpObj);
  180. _bpMap[bpObj.id] = bpObj;
  181. }
  182. return {
  183. setBreakpoint: function (name, scriptId, line, column, execStr) {
  184. var bpObj = internalSetBp(name, scriptId, line, column, execStr);
  185. addBpObject(bpObj);
  186. },
  187. setLocationBreakpoint: function (name, scriptId, line, column, execStr) {
  188. var bpObj = {
  189. id: _locBpId--,
  190. scriptId: scriptId,
  191. name: name,
  192. line: line,
  193. column: column,
  194. execStr: execStr,
  195. enabled: false
  196. }
  197. addBpObject(bpObj);
  198. },
  199. enableBreakpoint: function (name) {
  200. var bpObj = getBpFromName(name);
  201. if (bpObj) {
  202. delete _bpMap[bpObj.id];
  203. internalTrace(TRACE_INTERNAL_FUNCTIONS, "enableBreakpoint: ", name, " bpObj: ", bpObj);
  204. bpObj = internalSetBp(bpObj.name, bpObj.scriptId, bpObj.line, bpObj.column, bpObj.execStr);
  205. addBpObject(bpObj);
  206. }
  207. },
  208. deleteBreakpoint: function (name) {
  209. var bpObj = getBpFromName(name);
  210. if (bpObj && bpObj.enabled) {
  211. internalTrace(TRACE_INTERNAL_FUNCTIONS, "deleteBreakpoint: ", name, " bpObj: ", bpObj);
  212. callHostFunction(hostDebugObject.JsDiagRemoveBreakpoint, bpObj.id);
  213. delete _bpMap[bpObj.id];
  214. }
  215. },
  216. disableBreakpoint: function (name) {
  217. var bpObj = getBpFromName(name);
  218. if (bpObj && bpObj.enabled) {
  219. internalTrace(TRACE_INTERNAL_FUNCTIONS, "disableBreakpoint: ", name, " bpObj: ", bpObj);
  220. callHostFunction(hostDebugObject.JsDiagRemoveBreakpoint, bpObj.id);
  221. _bpMap[bpObj.id].enabled = false;
  222. }
  223. },
  224. getExecStr: function (id) {
  225. for (var i in _bpMap) {
  226. if (_bpMap[i].id === id) {
  227. return _bpMap[i].execStr;
  228. }
  229. }
  230. printError("Breakpoint '" + id + "' was not found");
  231. },
  232. setExecStr: function (id, newExecStr) {
  233. for (var i in _bpMap) {
  234. if (_bpMap[i].id === id) {
  235. _bpMap[i].execStr = newExecStr;
  236. }
  237. }
  238. },
  239. clearAllBreakpoints: function () {
  240. _bpMap = [];
  241. _locBpId = -1;
  242. }
  243. }
  244. })();
  245. function addSourceFile(text, srcId) {
  246. try {
  247. // Split the text into lines. Note this doesn't take into account block comments, but that's probably okay.
  248. var lines = text.split(/\n/);
  249. // /**bp <-- a breakpoint
  250. // /**loc <-- a named source location used for enabling bp at later stage
  251. // /**exception <-- set exception handling, catch all or only uncaught exception
  252. // /**onasyncbreak <-- set what happens on async break
  253. var bpStartToken = "/**";
  254. var bpStartStrings = ["bp", "loc", "exception", "onasyncbreak"];
  255. var bpEnd = "**/";
  256. // Iterate through each source line, setting any breakpoints.
  257. for (var i = 0; i < lines.length; ++i) {
  258. var line = lines[i];
  259. for (var startString in bpStartStrings) {
  260. var bpStart = bpStartToken + bpStartStrings[startString];
  261. var isLocationBreakpoint = (bpStart.indexOf("loc") != -1);
  262. var isExceptionBreakpoint = (bpStart.indexOf("exception") != -1);
  263. var isOnAsyncBreak = (bpStart.indexOf("onasyncbreak") != -1);
  264. var startIdx = -1;
  265. while ((startIdx = line.indexOf(bpStart, startIdx + 1)) != -1) {
  266. var endIdx;
  267. var currLine = i;
  268. var bpLine = i;
  269. var currBpLineString = "";
  270. // Gather up any lines within the breakpoint comment.
  271. do {
  272. var currentStartIdx = 0;
  273. if (currLine == i) {
  274. currentStartIdx = startIdx;
  275. }
  276. currBpLineString += lines[currLine++];
  277. endIdx = currBpLineString.indexOf(bpEnd, currentStartIdx);
  278. } while (endIdx == -1 && currLine < lines.length && lines[currLine].indexOf(bpStartToken) == -1);
  279. // Move the line cursor forward, allowing the current line to be re-checked
  280. i = currLine - 1;
  281. // Do some checking
  282. if (endIdx == -1) {
  283. printError("Unterminated breakpoint expression");
  284. return;
  285. }
  286. var bpStrStartIdx = startIdx + bpStart.length;
  287. var bpStr = currBpLineString.substring(bpStrStartIdx, endIdx);
  288. var bpFullStr = currBpLineString.substring(startIdx, endIdx);
  289. // Quick check to make sure the breakpoint is not within a
  290. // quoted string (such as an eval). If it is within an eval, the
  291. // eval will cause a separate call to have its breakpoints parsed.
  292. // This check can be defeated, but it should cover the useful scenarios.
  293. var quoteCount = 0;
  294. var escapeCount = 0;
  295. for (var j = 0; j < bpStrStartIdx; ++j) {
  296. switch (currBpLineString[j]) {
  297. case '\\':
  298. escapeCount++;
  299. continue;
  300. case '"':
  301. case '\'':
  302. if (escapeCount % 2 == 0)
  303. quoteCount++;
  304. /* fall through */
  305. default:
  306. escapeCount = 0;
  307. }
  308. }
  309. if (quoteCount % 2 == 1) {
  310. // The breakpoint was in a quoted string.
  311. continue;
  312. }
  313. // Only support strings like:
  314. // /**bp**/
  315. // /**bp(name)**/
  316. // /**bp(columnoffset)**/ takes an integer
  317. // /**bp:locals();stack()**/
  318. // /**bp(name):locals();stack()**/
  319. // /**loc(name)**/
  320. // /**loc(name):locals();stack()**/
  321. //
  322. // Parse the breakpoint name (if it exists)
  323. var bpName = undefined;
  324. var bpColumnOffset = 0;
  325. var bpExecStr = undefined;
  326. var parseIdx = 0;
  327. if (bpStr[parseIdx] == '(') {
  328. // The name and offset is overloaded with the same parameter.
  329. // if that is int (determined by parseInt), then it is column offset otherwise left as name.
  330. bpName = bpStr.match(/\(([\w,]+?)\)/)[1];
  331. parseIdx = bpName.length + 2;
  332. bpColumnOffset = parseInt(bpName);
  333. if (isNaN(bpColumnOffset)) {
  334. bpColumnOffset = 0;
  335. } else {
  336. bpName = undefined;
  337. if (bpColumnOffset > line.length) {
  338. bpColumnOffset = line.length - 1;
  339. } else if (bpColumnOffset < 0) {
  340. bpColumnOffset = 0;
  341. }
  342. }
  343. } else if (isLocationBreakpoint) {
  344. printError("'loc' sites require a label, for example /**loc(myFunc)**/");
  345. return;
  346. }
  347. // Process the exception label:
  348. // exception(none)
  349. // exception(uncaught)
  350. // exception(all)
  351. if (isExceptionBreakpoint) {
  352. var exceptionAttributes = -1;
  353. if (bpName !== undefined) {
  354. if (bpName == "none") {
  355. exceptionAttributes = 0; // JsDiagBreakOnExceptionAttributeNone
  356. } else if (bpName == "uncaught") {
  357. exceptionAttributes = 0x1; // JsDiagBreakOnExceptionAttributeUncaught
  358. } else if (bpName == "firstchance") {
  359. exceptionAttributes = 0x2; // JsDiagBreakOnExceptionAttributeFirstChance
  360. } else if (bpName == "all") {
  361. exceptionAttributes = 0x1 | 0x2; // JsDiagBreakOnExceptionAttributeUncaught | JsDiagBreakOnExceptionAttributeFirstChance
  362. }
  363. } else {
  364. // throw "No exception type specified";
  365. }
  366. callHostFunction(hostDebugObject.JsDiagSetBreakOnException, exceptionAttributes);
  367. }
  368. // Parse the breakpoint execution string
  369. if (bpStr[parseIdx] == ':') {
  370. bpExecStr = bpStr.substring(parseIdx + 1);
  371. } else if (parseIdx != bpStr.length) {
  372. printError("Invalid breakpoint string: " + bpStr);
  373. return;
  374. }
  375. // Insert the breakpoint.
  376. if (isExceptionBreakpoint) {
  377. if (_exceptionCommands != undefined) {
  378. printError("More than one 'exception' annotation found");
  379. return;
  380. }
  381. _exceptionCommands = bpExecStr;
  382. }
  383. if (isOnAsyncBreak) {
  384. if (_onasyncbreakCommands != undefined) {
  385. printError("More than one 'onasyncbreak' annotation found");
  386. return;
  387. }
  388. _onasyncbreakCommands = bpExecStr;
  389. }
  390. if (!isExceptionBreakpoint && !isOnAsyncBreak) {
  391. if (!isLocationBreakpoint) {
  392. bpManager.setBreakpoint(bpName, srcId, bpLine, bpColumnOffset, bpExecStr);
  393. } else {
  394. bpManager.setLocationBreakpoint(bpName, srcId, bpLine, bpColumnOffset, bpExecStr);
  395. }
  396. }
  397. }
  398. }
  399. }
  400. } catch (ex) {
  401. printError(ex);
  402. }
  403. }
  404. function handleBreakpoint(id) {
  405. internalTrace(TRACE_INTERNAL_FUNCTIONS, "handleBreakpoint id: ", id)
  406. _wasResumed = false;
  407. if (id != -1) {
  408. try {
  409. var execStr = "";
  410. if (id === "exception") {
  411. execStr = _exceptionCommands;
  412. if (execStr && execStr.toString().search("removeExpr()") != -1) {
  413. _exceptionCommands = undefined;
  414. }
  415. } else if (id === "asyncbreak") {
  416. execStr = _onasyncbreakCommands;
  417. if (execStr && execStr.toString().search("removeExpr()") != -1) {
  418. _onasyncbreakCommands = undefined;
  419. }
  420. } else if (id === "debuggerStatement") {
  421. execStr = "dumpBreak();locals();stack();"
  422. } else {
  423. // Retrieve this breakpoint's execution string
  424. execStr = bpManager.getExecStr(id);
  425. if (execStr.toString().search("removeExpr()") != -1) {
  426. // A hack to remove entire expression, so that it will not run again.
  427. bpManager.setExecStr(id, null);
  428. }
  429. }
  430. internalTrace(TRACE_INTERNAL_FUNCTIONS, "handleBreakpoint execStr: ", execStr)
  431. if (execStr != null) {
  432. eval(execStr);
  433. }
  434. } catch (ex) {
  435. printError(ex);
  436. }
  437. }
  438. internalTrace(TRACE_INTERNAL_FUNCTIONS, "_commandList length: ", _commandList.length, " _wasResumed: ", _wasResumed);
  439. // Continue processing the command list.
  440. while (_commandList.length > 0 && !_wasResumed) {
  441. var cmd = _commandList.shift();
  442. internalTrace(TRACE_INTERNAL_FUNCTIONS, "cmd: ", cmd);
  443. var completion = cmd.fn.apply(this, cmd.args);
  444. if (typeof completion === "function") {
  445. _commandCompletions.push(completion);
  446. }
  447. }
  448. while (_commandCompletions.length > 0) {
  449. var completion = _commandCompletions.shift();
  450. completion();
  451. }
  452. if (!_wasResumed) {
  453. _currentStackFrameIndex = 0;
  454. _wasResumed = true;
  455. }
  456. }
  457. function GetObjectDisplay(obj) {
  458. var objectDisplay = ("className" in obj) ? obj["className"] : obj["type"];
  459. var value = ("value" in obj) ? obj["value"] : obj["display"];
  460. if (value && value.length > _inspectMaxStringLength) {
  461. objectDisplay += " <large string>";
  462. } else {
  463. objectDisplay += " " + value;
  464. }
  465. return objectDisplay;
  466. }
  467. var stringToArrayBuffer = function stringToArrayBuffer(str) {
  468. var arr = [];
  469. for (var i = 0, len = str.length; i < len; i++) {
  470. arr[i] = str.charCodeAt(i) & 0xFF;
  471. }
  472. return new Uint8Array(arr).buffer;
  473. }
  474. function GetChild(obj, level) {
  475. function GetChildrens(obj, level) {
  476. var retArray = {};
  477. for (var i = 0; i < obj.length; ++i) {
  478. var propName = (obj[i].name == "__proto__") ? "#__proto__" : obj[i].name;
  479. retArray[propName] = GetChild(obj[i], level);
  480. }
  481. return retArray;
  482. }
  483. var retValue = {};
  484. if ("handle" in obj) {
  485. if (level >= 0) {
  486. var childProps = callHostFunction(hostDebugObject.JsDiagGetProperties, obj["handle"], 0, 1000);
  487. var properties = childProps["properties"];
  488. var debuggerOnlyProperties = childProps["debuggerOnlyProperties"];
  489. Array.prototype.push.apply(properties, debuggerOnlyProperties);
  490. if (properties.length > 0) {
  491. retValue = GetChildrens(properties, level - 1);
  492. } else {
  493. retValue = GetObjectDisplay(obj);
  494. }
  495. } else {
  496. retValue = GetObjectDisplay(obj);
  497. }
  498. delete obj["handle"];
  499. }
  500. if ("propertyAttributes" in obj) {
  501. delete obj["propertyAttributes"];
  502. }
  503. return retValue;
  504. }
  505. function compareWithBaseline() {
  506. function compareObjects(a, b, obj_namespace) {
  507. var objectsEqual = true;
  508. // This is a basic object comparison function, primarily to be used for JSON data.
  509. // It doesn't handle cyclical objects.
  510. function fail(step, message) {
  511. if (message == undefined) {
  512. message = "diff baselines for details";
  513. }
  514. printError("Step " + step + "; on: " + obj_namespace + ": " + message);
  515. objectsEqual = false;
  516. }
  517. function failNonObj(step, a, b, message) {
  518. if (message == undefined) {
  519. message = "";
  520. }
  521. printError("Step " + step + "; Local Diff on: " + obj_namespace + ": " + message);
  522. printError("Value 1:" + JSON.stringify(a));
  523. printError("Value 2:" + JSON.stringify(b));
  524. print("");
  525. objectsEqual = false;
  526. }
  527. // (1) Check strict equality.
  528. if (a === b)
  529. return true;
  530. // (2) non-Objects must have passed the strict equality comparison in (1)
  531. if ((typeof a != "object") || (typeof b != "object")) {
  532. failNonObj(2, a, b);
  533. return false;
  534. }
  535. // (3) check all properties
  536. for (var p in a) {
  537. // (4) check the property
  538. if (a[p] === b[p])
  539. continue;
  540. // (5) non-Objects must have passed the strict equality comparison in (4)
  541. if (typeof (a[p]) != "object") {
  542. failNonObj(5, a[p], b[p], "Property " + p);
  543. continue;
  544. }
  545. // (6) recursively check objects or arrays
  546. if (!compareObjects(a[p], b[p], obj_namespace + "." + p)) {
  547. // Don't need to report error message as it'll be reported inside nested call
  548. objectsEqual = false;
  549. continue;
  550. }
  551. }
  552. // (7) check any properties not in the previous enumeration
  553. var hasOwnProperty = Object.prototype.hasOwnProperty;
  554. for (var p in b) {
  555. if (hasOwnProperty.call(b, p) && !hasOwnProperty.call(a, p)) {
  556. fail(7, "Property missing: " + p + ", value: " + JSON.stringify(b[p]));
  557. continue;
  558. }
  559. }
  560. return objectsEqual;
  561. }
  562. var PASSED = 0;
  563. var FAILED = 1;
  564. if (_baseline == undefined) {
  565. return PASSED;
  566. }
  567. try {
  568. if (compareObjects(_baseline, _eventLog, "baseline")) {
  569. return PASSED;
  570. }
  571. }
  572. catch (ex) {
  573. printError("EXCEPTION: " + ex);
  574. }
  575. printError("TEST FAILED");
  576. return FAILED;
  577. }
  578. return {
  579. pushCommand: function pushCommand(fn, args) {
  580. _commandList.push({
  581. fn: fn,
  582. args: args
  583. });
  584. },
  585. debuggerCommands: {
  586. log: function (str) {
  587. internalPrint("LOG: " + str);
  588. },
  589. logJson: function (str) {
  590. recordEvent({ log: str });
  591. },
  592. resume: function (kind) {
  593. if (_wasResumed) {
  594. printError("Breakpoint resumed twice");
  595. } else {
  596. var stepType = -1;
  597. if (kind == "step_into") {
  598. stepType = 0;
  599. } else if (kind == "step_out") {
  600. stepType = 1;
  601. } else if (kind == "step_over") {
  602. stepType = 2;
  603. } else if (kind == "step_document") {
  604. stepType = 0;
  605. }
  606. if (stepType != -1) {
  607. callHostFunction(hostDebugObject.JsDiagSetStepType, stepType);
  608. } else if (kind != "continue") {
  609. throw new Error("Unhandled step type - " + kind);
  610. }
  611. _wasResumed = true;
  612. _currentStackFrameIndex = 0;
  613. }
  614. },
  615. locals: function (expandLevel, flags) {
  616. if (expandLevel == undefined || expandLevel < 0) {
  617. expandLevel = 0;
  618. }
  619. var stackProperties = callHostFunction(hostDebugObject.JsDiagGetStackProperties, _currentStackFrameIndex);
  620. if (expandLevel >= 0) {
  621. var localsJSON = {};
  622. ["thisObject", "exception", "arguments", "returnValue"].forEach(function (name) {
  623. if (name in stackProperties) {
  624. var stackObject = stackProperties[name];
  625. localsJSON[stackObject.name] = GetChild(stackObject, expandLevel - 1);
  626. }
  627. });
  628. ["functionCallsReturn", "locals"].forEach(function (name) {
  629. if (name in stackProperties) {
  630. var stackObject = stackProperties[name];
  631. if (stackObject.length > 0) {
  632. localsJSON[name] = {};
  633. for (var i = 0; i < stackObject.length; ++i) {
  634. localsJSON[name][stackObject[i].name] = GetChild(stackObject[i], expandLevel - 1);
  635. }
  636. }
  637. }
  638. });
  639. if ("scopes" in stackProperties) {
  640. var scopesArray = stackProperties["scopes"];
  641. for (var i = 0; i < scopesArray.length; ++i) {
  642. localsJSON["scopes" + i] = GetChild(scopesArray[i], expandLevel - 1);
  643. }
  644. }
  645. if ("globals" in stackProperties && expandLevel > 0) {
  646. localsJSON["globals"] = GetChild(stackProperties["globals"], expandLevel - 1);
  647. }
  648. recordEvent(localsJSON);
  649. }
  650. },
  651. stack: function (flags) {
  652. if (flags === undefined) {
  653. flags = 0;
  654. }
  655. var stackTrace = callHostFunction(hostDebugObject.JsDiagGetStackTrace);
  656. var stackTraceArray = [];
  657. for (var i = 0; i < stackTrace.length; ++i) {
  658. var stack = {};
  659. stack["line"] = stackTrace[i].line;
  660. stack["column"] = stackTrace[i].column;
  661. stack["sourceText"] = stackTrace[i].sourceText;
  662. var functionObject = callHostFunction(hostDebugObject.JsDiagGetObjectFromHandle, stackTrace[i].functionHandle);
  663. stack["function"] = functionObject.name;
  664. stackTraceArray.push(stack);
  665. }
  666. recordEvent({
  667. 'callStack': stackTraceArray
  668. });
  669. },
  670. evaluate: function (expression, expandLevel, flags) {
  671. if (expression != undefined) {
  672. if (typeof expandLevel != "number" || expandLevel <= 0) {
  673. expandLevel = 0;
  674. }
  675. if (WScript && typeof expression == 'string' && WScript.forceDebugArrayBuffer)
  676. expression = stringToArrayBuffer(expression);
  677. var evalResult = callHostFunction(hostDebugObject.JsDiagEvaluate, _currentStackFrameIndex, expression);
  678. var evaluateOutput = {};
  679. evaluateOutput[evalResult.name] = GetChild(evalResult, expandLevel - 1);
  680. recordEvent({
  681. 'evaluate': evaluateOutput
  682. });
  683. }
  684. },
  685. enableBp: function (name) {
  686. bpManager.enableBreakpoint(name);
  687. },
  688. disableBp: function (name) {
  689. bpManager.disableBreakpoint(name);
  690. },
  691. deleteBp: function (name) {
  692. bpManager.deleteBreakpoint(name);
  693. },
  694. setFrame: function (depth) {
  695. var stackTrace = callHostFunction(hostDebugObject.JsDiagGetStackTrace);
  696. for (var i = 0; i < stackTrace.length; ++i) {
  697. if (stackTrace[i].index == depth) {
  698. _currentStackFrameIndex = depth;
  699. break;
  700. }
  701. }
  702. },
  703. dumpBreak: function () {
  704. var breakpoints = callHostFunction(hostDebugObject.JsDiagGetBreakpoints);
  705. recordEvent({
  706. 'breakpoints': breakpoints
  707. });
  708. },
  709. dumpSourceList: function () {
  710. var sources = callHostFunction(hostDebugObject.JsDiagGetScripts);
  711. sources.forEach(function (source) {
  712. if ("fileName" in source) {
  713. source["fileName"] = filterFileName(source["fileName"]);
  714. }
  715. });
  716. recordEvent({
  717. 'sources': sources
  718. });
  719. },
  720. dumpFunctionProperties: function (frameIdOrArrayOfIds = [0], expandLevel = 0) {
  721. if (typeof frameIdOrArrayOfIds != "number" && !(frameIdOrArrayOfIds instanceof Array)) {
  722. frameIdOrArrayOfIds = [0];
  723. }
  724. if (typeof expandLevel != "number" || expandLevel < 0) {
  725. expandLevel = 0;
  726. }
  727. let stackTrace = callHostFunction(hostDebugObject.JsDiagGetStackTrace);
  728. let functionHandles = [];
  729. let requestedFrameIndexes = [];
  730. if (typeof frameIdOrArrayOfIds === "number") {
  731. requestedFrameIndexes.push(frameIdOrArrayOfIds);
  732. } else if (frameIdOrArrayOfIds instanceof Array) {
  733. frameIdOrArrayOfIds.forEach((s) => {
  734. if (typeof s === "number") {
  735. requestedFrameIndexes.push(s);
  736. }
  737. });
  738. }
  739. if (requestedFrameIndexes.length == 0) {
  740. requestedFrameIndexes.push(0);
  741. }
  742. stackTrace.forEach((stackFrame) => {
  743. let stackFrameIndex = stackFrame.index;
  744. if (requestedFrameIndexes.includes(stackFrameIndex) && !functionHandles.includes(stackFrame.functionHandle)) {
  745. functionHandles.push(stackFrame.functionHandle);
  746. }
  747. });
  748. let functionProperties = [];
  749. functionHandles.forEach((handle) => {
  750. functionProperties.push(GetChild({ handle: handle }, expandLevel));
  751. });
  752. recordEvent({
  753. 'functionProperties': functionProperties
  754. });
  755. },
  756. trace: function (traceFlag) {
  757. _trace |= traceFlag;
  758. }
  759. },
  760. setBaseline: function (baseline) {
  761. try {
  762. _baseline = JSON.parse(baseline);
  763. } catch (ex) {
  764. printError("Invalid JSON passed to setBaseline: " + ex);
  765. internalPrint(baseline);
  766. }
  767. },
  768. dumpFunctionPosition: function (functionPosition) {
  769. if (!functionPosition) {
  770. functionPosition = {};
  771. }
  772. else {
  773. functionPosition["fileName"] = filterFileName(functionPosition["fileName"]);
  774. }
  775. recordEvent({
  776. 'functionPosition': functionPosition
  777. });
  778. },
  779. setInspectMaxStringLength: function (value) {
  780. _inspectMaxStringLength = value;
  781. },
  782. getOutputJson: function () {
  783. return JSON.stringify(_eventLog, undefined, " ");
  784. },
  785. verify: function () {
  786. return compareWithBaseline();
  787. },
  788. handleDebugEvent: function (debugEvent, eventData) {
  789. function debugEventToString(debugEvent) {
  790. switch (debugEvent) {
  791. case 0:
  792. return "JsDiagDebugEventSourceCompile";
  793. case 1:
  794. return "JsDiagDebugEventCompileError";
  795. case 2:
  796. return "JsDiagDebugEventBreakpoint";
  797. case 3:
  798. return "JsDiagDebugEventStepComplete";
  799. case 4:
  800. return "JsDiagDebugEventDebuggerStatement";
  801. case 5:
  802. return "JsDiagDebugEventAsyncBreak";
  803. case 6:
  804. return "JsDiagDebugEventRuntimeException";
  805. default:
  806. return "UnKnown";
  807. }
  808. }
  809. internalTrace(TRACE_DEBUG_EVENTS, {
  810. 'debugEvent': debugEventToString(debugEvent),
  811. 'eventData': eventData
  812. });
  813. switch (debugEvent) {
  814. case 0:
  815. /*JsDiagDebugEventSourceCompile*/
  816. var source = callHostFunction(hostDebugObject.JsDiagGetSource, eventData.scriptId);
  817. addSourceFile(source.source, source.scriptId);
  818. break;
  819. case 1:
  820. /*JsDiagDebugEventCompileError*/
  821. var stackTrace = callHostFunction(hostDebugObject.JsDiagGetScripts);
  822. break;
  823. case 2:
  824. /*JsDiagDebugEventBreakpoint*/
  825. case 3:
  826. /*JsDiagDebugEventStepComplete*/
  827. handleBreakpoint(("breakpointId" in eventData) ? eventData.breakpointId : -1);
  828. break;
  829. case 4:
  830. /*JsDiagDebugEventDebuggerStatement*/
  831. handleBreakpoint("debuggerStatement");
  832. break;
  833. case 5:
  834. /*JsDiagDebugEventAsyncBreak*/
  835. handleBreakpoint("asyncbreak");
  836. break;
  837. case 6:
  838. /*JsDiagDebugEventRuntimeException*/
  839. handleBreakpoint("exception");
  840. break;
  841. default:
  842. throw "Unhandled JsDiagDebugEvent value " + debugEvent;
  843. break;
  844. }
  845. },
  846. handleSourceRunDown: function (sources) {
  847. bpManager.clearAllBreakpoints();
  848. for (var len = 0; len < sources.length; ++len) {
  849. var source = callHostFunction(hostDebugObject.JsDiagGetSource, sources[len].scriptId);
  850. addSourceFile(source.source, source.scriptId);
  851. };
  852. },
  853. }
  854. })();
  855. // Commands for use from the breakpoint execution string in test files
  856. function log(str) {
  857. // Prints given string as 'LOG: <given string>' on console
  858. controllerObj.pushCommand(controllerObj.debuggerCommands.log, arguments);
  859. }
  860. function logJson(str) {
  861. // Prints given string on console
  862. controllerObj.pushCommand(controllerObj.debuggerCommands.logJson, arguments);
  863. }
  864. function resume(kind) {
  865. // Resume exceution after a break, kinds - step_into, step_out, step_over
  866. controllerObj.pushCommand(controllerObj.debuggerCommands.resume, arguments);
  867. }
  868. function locals(expandLevel, flags) {
  869. // Dumps locals tree, expand till expandLevel with given flags
  870. controllerObj.pushCommand(controllerObj.debuggerCommands.locals, arguments);
  871. }
  872. function stack() {
  873. controllerObj.pushCommand(controllerObj.debuggerCommands.stack, arguments);
  874. }
  875. function removeExpr(bpId) {
  876. // A workaround to remove the current expression
  877. }
  878. function evaluate(expression, expandLevel, flags) {
  879. controllerObj.pushCommand(controllerObj.debuggerCommands.evaluate, arguments);
  880. }
  881. function enableBp(name) {
  882. controllerObj.pushCommand(controllerObj.debuggerCommands.enableBp, arguments);
  883. }
  884. function disableBp(name) {
  885. controllerObj.pushCommand(controllerObj.debuggerCommands.disableBp, arguments);
  886. }
  887. function deleteBp(name) {
  888. controllerObj.pushCommand(controllerObj.debuggerCommands.deleteBp, arguments);
  889. }
  890. function setFrame(name) {
  891. controllerObj.pushCommand(controllerObj.debuggerCommands.setFrame, arguments);
  892. }
  893. function dumpBreak() {
  894. controllerObj.pushCommand(controllerObj.debuggerCommands.dumpBreak, arguments);
  895. }
  896. function dumpSourceList() {
  897. controllerObj.pushCommand(controllerObj.debuggerCommands.dumpSourceList, arguments);
  898. }
  899. function dumpFunctionProperties() {
  900. controllerObj.pushCommand(controllerObj.debuggerCommands.dumpFunctionProperties, arguments);
  901. }
  902. // Start internal tracing. E.g.: /**bp:trace(TRACE_COMMANDS)**/
  903. function trace() {
  904. controllerObj.pushCommand(controllerObj.debuggerCommands.trace, arguments);
  905. }
  906. // Non Supported - TO BE REMOVED
  907. function setExceptionResume() { }
  908. function setnext() { }
  909. function evaluateAsync() { }
  910. function trackProjectionCall() { }
  911. function mbp() { }
  912. function deleteMbp() { }
  913. // APIs exposed to Debugger.cpp
  914. function GetOutputJson() {
  915. return controllerObj.getOutputJson.apply(controllerObj, arguments);
  916. }
  917. function Verify() {
  918. return controllerObj.verify.apply(controllerObj, arguments);
  919. }
  920. function SetBaseline() {
  921. return controllerObj.setBaseline.apply(controllerObj, arguments);
  922. }
  923. function SetInspectMaxStringLength() {
  924. return controllerObj.setInspectMaxStringLength.apply(controllerObj, arguments);
  925. }
  926. function DumpFunctionPosition() {
  927. return controllerObj.dumpFunctionPosition.apply(controllerObj, arguments);
  928. }
  929. // Called from Debugger.cpp to handle JsDiagDebugEvent
  930. function HandleDebugEvent() {
  931. return controllerObj.handleDebugEvent.apply(controllerObj, arguments);
  932. }
  933. // Called from Debugger.cpp when debugger is attached using WScript.Attach
  934. function HandleSourceRunDown() {
  935. return controllerObj.handleSourceRunDown.apply(controllerObj, arguments);
  936. }