stacktrace.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. // Copyright 2009 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Tools for parsing and pretty printing error stack traces.
  16. *
  17. */
  18. goog.setTestOnly('goog.testing.stacktrace');
  19. goog.provide('goog.testing.stacktrace');
  20. goog.provide('goog.testing.stacktrace.Frame');
  21. /**
  22. * Class representing one stack frame.
  23. * @param {string} context Context object, empty in case of global functions or
  24. * if the browser doesn't provide this information.
  25. * @param {string} name Function name, empty in case of anonymous functions.
  26. * @param {string} alias Alias of the function if available. For example the
  27. * function name will be 'c' and the alias will be 'b' if the function is
  28. * defined as <code>a.b = function c() {};</code>.
  29. * @param {string} path File path or URL including line number and optionally
  30. * column number separated by colons.
  31. * @constructor
  32. * @final
  33. */
  34. goog.testing.stacktrace.Frame = function(context, name, alias, path) {
  35. this.context_ = context;
  36. this.name_ = name;
  37. this.alias_ = alias;
  38. this.path_ = path;
  39. };
  40. /**
  41. * @return {string} The function name or empty string if the function is
  42. * anonymous and the object field which it's assigned to is unknown.
  43. */
  44. goog.testing.stacktrace.Frame.prototype.getName = function() {
  45. return this.name_;
  46. };
  47. /**
  48. * @return {boolean} Whether the stack frame contains an anonymous function.
  49. */
  50. goog.testing.stacktrace.Frame.prototype.isAnonymous = function() {
  51. return !this.name_ || this.context_ == '[object Object]';
  52. };
  53. /**
  54. * Brings one frame of the stack trace into a common format across browsers.
  55. * @return {string} Pretty printed stack frame.
  56. */
  57. goog.testing.stacktrace.Frame.prototype.toCanonicalString = function() {
  58. var htmlEscape = goog.testing.stacktrace.htmlEscape_;
  59. var deobfuscate = goog.testing.stacktrace.maybeDeobfuscateFunctionName_;
  60. var canonical = [
  61. this.context_ ? htmlEscape(this.context_) + '.' : '',
  62. this.name_ ? htmlEscape(deobfuscate(this.name_)) : 'anonymous',
  63. this.alias_ ? ' [as ' + htmlEscape(deobfuscate(this.alias_)) + ']' : ''
  64. ];
  65. if (this.path_) {
  66. canonical.push(' at ');
  67. canonical.push(htmlEscape(this.path_));
  68. }
  69. return canonical.join('');
  70. };
  71. /**
  72. * Maximum number of steps while the call chain is followed.
  73. * @private {number}
  74. * @const
  75. */
  76. goog.testing.stacktrace.MAX_DEPTH_ = 20;
  77. /**
  78. * Maximum length of a string that can be matched with a RegExp on
  79. * Firefox 3x. Exceeding this approximate length will cause string.match
  80. * to exceed Firefox's stack quota. This situation can be encountered
  81. * when goog.globalEval is invoked with a long argument; such as
  82. * when loading a module.
  83. * @private {number}
  84. * @const
  85. */
  86. goog.testing.stacktrace.MAX_FIREFOX_FRAMESTRING_LENGTH_ = 500000;
  87. /**
  88. * RegExp pattern for JavaScript identifiers. We don't support Unicode
  89. * identifiers defined in ECMAScript v3.
  90. * @private {string}
  91. * @const
  92. */
  93. goog.testing.stacktrace.IDENTIFIER_PATTERN_ = '[a-zA-Z_$][\\w$]*';
  94. /**
  95. * RegExp pattern for function name alias in the V8 stack trace.
  96. * @private {string}
  97. * @const
  98. */
  99. goog.testing.stacktrace.V8_ALIAS_PATTERN_ =
  100. '(?: \\[as (' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')\\])?';
  101. /**
  102. * RegExp pattern for the context of a function call in a V8 stack trace.
  103. * Creates an optional submatch for the namespace identifier including the
  104. * "new" keyword for constructor calls (e.g. "new foo.Bar").
  105. * @private {string}
  106. * @const
  107. */
  108. goog.testing.stacktrace.V8_CONTEXT_PATTERN_ =
  109. '(?:((?:new )?(?:\\[object Object\\]|' +
  110. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '(?:\\.' +
  111. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')*))\\.)?';
  112. /**
  113. * RegExp pattern for function names and constructor calls in the V8 stack
  114. * trace.
  115. * @private {string}
  116. * @const
  117. */
  118. goog.testing.stacktrace.V8_FUNCTION_NAME_PATTERN_ = '(?:new )?(?:' +
  119. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '|<anonymous>)';
  120. /**
  121. * RegExp pattern for function call in the V8 stack trace. Creates 3 submatches
  122. * with context object (optional), function name and function alias (optional).
  123. * @private {string}
  124. * @const
  125. */
  126. goog.testing.stacktrace.V8_FUNCTION_CALL_PATTERN_ = ' ' +
  127. goog.testing.stacktrace.V8_CONTEXT_PATTERN_ + '(' +
  128. goog.testing.stacktrace.V8_FUNCTION_NAME_PATTERN_ + ')' +
  129. goog.testing.stacktrace.V8_ALIAS_PATTERN_;
  130. /**
  131. * RegExp pattern for an URL + position inside the file.
  132. * @private {string}
  133. * @const
  134. */
  135. goog.testing.stacktrace.URL_PATTERN_ =
  136. '((?:http|https|file)://[^\\s)]+|javascript:.*)';
  137. /**
  138. * RegExp pattern for an URL + line number + column number in V8.
  139. * The URL is either in submatch 1 or submatch 2.
  140. * @private {string}
  141. * @const
  142. */
  143. goog.testing.stacktrace.CHROME_URL_PATTERN_ = ' (?:' +
  144. '\\(unknown source\\)' +
  145. '|' +
  146. '\\(native\\)' +
  147. '|' +
  148. '\\((.+)\\)|(.+))';
  149. /**
  150. * Regular expression for parsing one stack frame in V8. For more information
  151. * on V8 stack frame formats, see
  152. * https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi.
  153. * @private {!RegExp}
  154. * @const
  155. */
  156. goog.testing.stacktrace.V8_STACK_FRAME_REGEXP_ = new RegExp(
  157. '^ at' +
  158. '(?:' + goog.testing.stacktrace.V8_FUNCTION_CALL_PATTERN_ + ')?' +
  159. goog.testing.stacktrace.CHROME_URL_PATTERN_ + '$');
  160. /**
  161. * RegExp pattern for function call in the Firefox stack trace.
  162. * Creates 2 submatches with function name (optional) and arguments.
  163. *
  164. * Modern FF produces stack traces like:
  165. * foo@url:1:2
  166. * a.b.foo@url:3:4
  167. *
  168. * @private {string}
  169. * @const
  170. */
  171. goog.testing.stacktrace.FIREFOX_FUNCTION_CALL_PATTERN_ = '(' +
  172. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '(?:\\.' +
  173. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')*' +
  174. ')?' +
  175. '(\\(.*\\))?@';
  176. /**
  177. * Regular expression for parsing one stack frame in Firefox.
  178. * @private {!RegExp}
  179. * @const
  180. */
  181. goog.testing.stacktrace.FIREFOX_STACK_FRAME_REGEXP_ = new RegExp(
  182. '^' + goog.testing.stacktrace.FIREFOX_FUNCTION_CALL_PATTERN_ + '(?::0|' +
  183. goog.testing.stacktrace.URL_PATTERN_ + ')$');
  184. /**
  185. * RegExp pattern for an anonymous function call in an Opera stack frame.
  186. * Creates 2 (optional) submatches: the context object and function name.
  187. * @private {string}
  188. * @const
  189. */
  190. goog.testing.stacktrace.OPERA_ANONYMOUS_FUNCTION_NAME_PATTERN_ =
  191. '<anonymous function(?:\\: ' +
  192. '(?:(' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '(?:\\.' +
  193. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')*)\\.)?' +
  194. '(' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '))?>';
  195. /**
  196. * RegExp pattern for a function call in an Opera stack frame.
  197. * Creates 4 (optional) submatches: the function name (if not anonymous),
  198. * the aliased context object and function name (if anonymous), and the
  199. * function call arguments.
  200. * @private {string}
  201. * @const
  202. */
  203. goog.testing.stacktrace.OPERA_FUNCTION_CALL_PATTERN_ = '(?:(?:(' +
  204. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')|' +
  205. goog.testing.stacktrace.OPERA_ANONYMOUS_FUNCTION_NAME_PATTERN_ +
  206. ')(\\(.*\\)))?@';
  207. /**
  208. * Regular expression for parsing on stack frame in Opera 11.68 - 12.17.
  209. * Newer versions of Opera use V8 and stack frames should match against
  210. * goog.testing.stacktrace.V8_STACK_FRAME_REGEXP_.
  211. * @private {!RegExp}
  212. * @const
  213. */
  214. goog.testing.stacktrace.OPERA_STACK_FRAME_REGEXP_ = new RegExp(
  215. '^' + goog.testing.stacktrace.OPERA_FUNCTION_CALL_PATTERN_ +
  216. goog.testing.stacktrace.URL_PATTERN_ + '?$');
  217. /**
  218. * Regular expression for finding the function name in its source.
  219. * @private {!RegExp}
  220. * @const
  221. */
  222. goog.testing.stacktrace.FUNCTION_SOURCE_REGEXP_ = new RegExp(
  223. '^function (' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')');
  224. /**
  225. * RegExp pattern for function call in a IE stack trace. This expression allows
  226. * for identifiers like 'Anonymous function', 'eval code', and 'Global code'.
  227. * @private {string}
  228. * @const
  229. */
  230. goog.testing.stacktrace.IE_FUNCTION_CALL_PATTERN_ = '(' +
  231. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '(?:\\.' +
  232. goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')*' +
  233. '(?:\\s+\\w+)*)';
  234. /**
  235. * Regular expression for parsing a stack frame in IE.
  236. * @private {!RegExp}
  237. * @const
  238. */
  239. goog.testing.stacktrace.IE_STACK_FRAME_REGEXP_ = new RegExp(
  240. '^ at ' + goog.testing.stacktrace.IE_FUNCTION_CALL_PATTERN_ + '\\s*\\(' +
  241. '(' +
  242. 'eval code:[^)]*' +
  243. '|' +
  244. 'Unknown script code:[^)]*' +
  245. '|' + goog.testing.stacktrace.URL_PATTERN_ + ')\\)?$');
  246. /**
  247. * Creates a stack trace by following the call chain. Based on
  248. * {@link goog.debug.getStacktrace}.
  249. * @return {!Array<!goog.testing.stacktrace.Frame>} Stack frames.
  250. * @private
  251. * @suppress {es5Strict}
  252. */
  253. goog.testing.stacktrace.followCallChain_ = function() {
  254. var frames = [];
  255. var fn = arguments.callee.caller;
  256. var depth = 0;
  257. while (fn && depth < goog.testing.stacktrace.MAX_DEPTH_) {
  258. var fnString = Function.prototype.toString.call(fn);
  259. var match = fnString.match(goog.testing.stacktrace.FUNCTION_SOURCE_REGEXP_);
  260. var functionName = match ? match[1] : '';
  261. frames.push(new goog.testing.stacktrace.Frame('', functionName, '', ''));
  262. try {
  263. fn = fn.caller;
  264. } catch (e) {
  265. break;
  266. }
  267. depth++;
  268. }
  269. return frames;
  270. };
  271. /**
  272. * Parses one stack frame.
  273. * @param {string} frameStr The stack frame as string.
  274. * @return {goog.testing.stacktrace.Frame} Stack frame object or null if the
  275. * parsing failed.
  276. * @private
  277. */
  278. goog.testing.stacktrace.parseStackFrame_ = function(frameStr) {
  279. // This match includes newer versions of Opera (15+).
  280. var m = frameStr.match(goog.testing.stacktrace.V8_STACK_FRAME_REGEXP_);
  281. if (m) {
  282. return new goog.testing.stacktrace.Frame(
  283. m[1] || '', m[2] || '', m[3] || '', m[4] || m[5] || m[6] || '');
  284. }
  285. // TODO(johnlenz): remove this. It seems like if this was useful it would
  286. // need to be before the V8 check.
  287. if (frameStr.length >
  288. goog.testing.stacktrace.MAX_FIREFOX_FRAMESTRING_LENGTH_) {
  289. return null;
  290. }
  291. m = frameStr.match(goog.testing.stacktrace.FIREFOX_STACK_FRAME_REGEXP_);
  292. if (m) {
  293. return new goog.testing.stacktrace.Frame('', m[1] || '', '', m[3] || '');
  294. }
  295. // Match against Presto Opera 11.68 - 12.17.
  296. m = frameStr.match(goog.testing.stacktrace.OPERA_STACK_FRAME_REGEXP_);
  297. if (m) {
  298. return new goog.testing.stacktrace.Frame(
  299. m[2] || '', m[1] || m[3] || '', '', m[5] || '');
  300. }
  301. m = frameStr.match(goog.testing.stacktrace.IE_STACK_FRAME_REGEXP_);
  302. if (m) {
  303. return new goog.testing.stacktrace.Frame('', m[1] || '', '', m[2] || '');
  304. }
  305. return null;
  306. };
  307. /**
  308. * Function to deobfuscate function names.
  309. * @type {function(string): string}
  310. * @private
  311. */
  312. goog.testing.stacktrace.deobfuscateFunctionName_;
  313. /**
  314. * Sets function to deobfuscate function names.
  315. * @param {function(string): string} fn function to deobfuscate function names.
  316. */
  317. goog.testing.stacktrace.setDeobfuscateFunctionName = function(fn) {
  318. goog.testing.stacktrace.deobfuscateFunctionName_ = fn;
  319. };
  320. /**
  321. * Deobfuscates a compiled function name with the function passed to
  322. * {@link #setDeobfuscateFunctionName}. Returns the original function name if
  323. * the deobfuscator hasn't been set.
  324. * @param {string} name The function name to deobfuscate.
  325. * @return {string} The deobfuscated function name.
  326. * @private
  327. */
  328. goog.testing.stacktrace.maybeDeobfuscateFunctionName_ = function(name) {
  329. return goog.testing.stacktrace.deobfuscateFunctionName_ ?
  330. goog.testing.stacktrace.deobfuscateFunctionName_(name) :
  331. name;
  332. };
  333. /**
  334. * Escapes the special character in HTML.
  335. * @param {string} text Plain text.
  336. * @return {string} Escaped text.
  337. * @private
  338. */
  339. goog.testing.stacktrace.htmlEscape_ = function(text) {
  340. return text.replace(/&/g, '&amp;')
  341. .replace(/</g, '&lt;')
  342. .replace(/>/g, '&gt;')
  343. .replace(/"/g, '&quot;');
  344. };
  345. /**
  346. * Converts the stack frames into canonical format. Chops the beginning and the
  347. * end of it which come from the testing environment, not from the test itself.
  348. * @param {!Array<goog.testing.stacktrace.Frame>} frames The frames.
  349. * @return {string} Canonical, pretty printed stack trace.
  350. * @private
  351. */
  352. goog.testing.stacktrace.framesToString_ = function(frames) {
  353. // Removes the anonymous calls from the end of the stack trace (they come
  354. // from testrunner.js, testcase.js and asserts.js), so the stack trace will
  355. // end with the test... method.
  356. var lastIndex = frames.length - 1;
  357. while (frames[lastIndex] && frames[lastIndex].isAnonymous()) {
  358. lastIndex--;
  359. }
  360. // Removes the beginning of the stack trace until the call of the private
  361. // _assert function (inclusive), so the stack trace will begin with a public
  362. // asserter. Does nothing if _assert is not present in the stack trace.
  363. var privateAssertIndex = -1;
  364. for (var i = 0; i < frames.length; i++) {
  365. if (frames[i] && frames[i].getName() == '_assert') {
  366. privateAssertIndex = i;
  367. break;
  368. }
  369. }
  370. var canonical = [];
  371. for (var i = privateAssertIndex + 1; i <= lastIndex; i++) {
  372. canonical.push('> ');
  373. if (frames[i]) {
  374. canonical.push(frames[i].toCanonicalString());
  375. } else {
  376. canonical.push('(unknown)');
  377. }
  378. canonical.push('\n');
  379. }
  380. return canonical.join('');
  381. };
  382. /**
  383. * Parses the browser's native stack trace.
  384. * @param {string} stack Stack trace.
  385. * @return {!Array<goog.testing.stacktrace.Frame>} Stack frames. The
  386. * unrecognized frames will be nulled out.
  387. * @private
  388. */
  389. goog.testing.stacktrace.parse_ = function(stack) {
  390. var lines = stack.replace(/\s*$/, '').split('\n');
  391. var frames = [];
  392. for (var i = 0; i < lines.length; i++) {
  393. frames.push(goog.testing.stacktrace.parseStackFrame_(lines[i]));
  394. }
  395. return frames;
  396. };
  397. /**
  398. * Brings the stack trace into a common format across browsers.
  399. * @param {string} stack Browser-specific stack trace.
  400. * @return {string} Same stack trace in common format.
  401. */
  402. goog.testing.stacktrace.canonicalize = function(stack) {
  403. var frames = goog.testing.stacktrace.parse_(stack);
  404. return goog.testing.stacktrace.framesToString_(frames);
  405. };
  406. /**
  407. * Returns the native stack trace.
  408. * @return {string|!Array<!CallSite>}
  409. * @private
  410. */
  411. goog.testing.stacktrace.getNativeStack_ = function() {
  412. var tmpError = new Error();
  413. if (tmpError.stack) {
  414. return tmpError.stack;
  415. }
  416. // IE10 will only create a stack trace when the Error is thrown.
  417. // We use null.x() to throw an exception because the closure compiler may
  418. // replace "throw" with a function call in an attempt to minimize the binary
  419. // size, which in turn has the side effect of adding an unwanted stack frame.
  420. try {
  421. null.x();
  422. } catch (e) {
  423. return e.stack;
  424. }
  425. return '';
  426. };
  427. /**
  428. * Gets the native stack trace if available otherwise follows the call chain.
  429. * @return {string} The stack trace in canonical format.
  430. */
  431. goog.testing.stacktrace.get = function() {
  432. var stack = goog.testing.stacktrace.getNativeStack_();
  433. var frames;
  434. if (!stack) {
  435. frames = goog.testing.stacktrace.followCallChain_();
  436. } else if (goog.isArray(stack)) {
  437. frames = goog.testing.stacktrace.callSitesToFrames_(stack);
  438. } else {
  439. frames = goog.testing.stacktrace.parse_(stack);
  440. }
  441. return goog.testing.stacktrace.framesToString_(frames);
  442. };
  443. /**
  444. * Converts an array of CallSite (elements of a stack trace in V8) to an array
  445. * of Frames.
  446. * @param {!Array<!CallSite>} stack The stack as an array of CallSites.
  447. * @return {!Array<!goog.testing.stacktrace.Frame>} The stack as an array of
  448. * Frames.
  449. * @private
  450. */
  451. goog.testing.stacktrace.callSitesToFrames_ = function(stack) {
  452. var frames = [];
  453. for (var i = 0; i < stack.length; i++) {
  454. var callSite = stack[i];
  455. var functionName = callSite.getFunctionName() || 'unknown';
  456. var fileName = callSite.getFileName();
  457. var path = fileName ?
  458. fileName + ':' + callSite.getLineNumber() + ':' +
  459. callSite.getColumnNumber() :
  460. 'unknown';
  461. frames.push(new goog.testing.stacktrace.Frame('', functionName, '', path));
  462. }
  463. return frames;
  464. };
  465. goog.exportSymbol(
  466. 'setDeobfuscateFunctionName',
  467. goog.testing.stacktrace.setDeobfuscateFunctionName);