summaryrefslogtreecommitdiffstats
path: root/devtools/server/tracer/tests/xpcshell/test_tracer.js
blob: 0f38052ba569d3e4e3cf06557b96802cce9188e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { addTracingListener, removeTracingListener, startTracing, stopTracing } =
  ChromeUtils.import("resource://devtools/server/tracer/tracer.jsm");

add_task(async function () {
  // Because this test uses evalInSandbox, we need to tweak the following prefs
  Services.prefs.setBoolPref(
    "security.allow_parent_unrestricted_js_loads",
    true
  );
  registerCleanupFunction(() => {
    Services.prefs.clearUserPref("security.allow_parent_unrestricted_js_loads");
  });
});

add_task(async function testTracingContentGlobal() {
  const toggles = [];
  const frames = [];
  const listener = {
    onTracingToggled(state) {
      toggles.push(state);
    },
    onTracingFrame(frameInfo) {
      frames.push(frameInfo);
    },
  };

  info("Register a tracing listener");
  addTracingListener(listener);

  const sandbox = Cu.Sandbox("https://example.com");
  Cu.evalInSandbox("function bar() {}; function foo() {bar()};", sandbox);

  info("Start tracing");
  startTracing({ global: sandbox, prefix: "testContentPrefix" });
  Assert.equal(toggles.length, 1);
  Assert.equal(toggles[0], true);

  info("Call some code");
  sandbox.foo();

  Assert.equal(frames.length, 2);
  const lastFrame = frames.pop();
  const beforeLastFrame = frames.pop();
  Assert.equal(beforeLastFrame.depth, 0);
  Assert.equal(beforeLastFrame.formatedDisplayName, "λ foo");
  Assert.equal(beforeLastFrame.prefix, "testContentPrefix: ");
  Assert.ok(beforeLastFrame.frame);
  Assert.equal(lastFrame.depth, 1);
  Assert.equal(lastFrame.formatedDisplayName, "λ bar");
  Assert.equal(lastFrame.prefix, "testContentPrefix: ");
  Assert.ok(lastFrame.frame);

  info("Stop tracing");
  stopTracing();
  Assert.equal(toggles.length, 2);
  Assert.equal(toggles[1], false);

  info("Recall code after stop, no more traces are logged");
  sandbox.foo();
  Assert.equal(frames.length, 0);

  info("Start tracing again, and recall code");
  startTracing({ global: sandbox, prefix: "testContentPrefix" });
  sandbox.foo();
  info("New traces are logged");
  Assert.equal(frames.length, 2);

  info("Unregister the listener and recall code");
  removeTracingListener(listener);
  sandbox.foo();
  info("No more traces are logged");
  Assert.equal(frames.length, 2);

  info("Stop tracing");
  stopTracing();
});

add_task(async function testTracingJSMGlobal() {
  // We have to register the listener code in a sandbox, i.e. in a distinct global
  // so that we aren't creating traces when tracer calls it. (and cause infinite loops)
  const systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
  const listenerSandbox = Cu.Sandbox(systemPrincipal);
  Cu.evalInSandbox(
    "new " +
      function () {
        globalThis.toggles = [];
        globalThis.frames = [];
        globalThis.listener = {
          onTracingToggled(state) {
            globalThis.toggles.push(state);
          },
          onTracingFrame(frameInfo) {
            globalThis.frames.push(frameInfo);
          },
        };
      },
    listenerSandbox
  );

  info("Register a tracing listener");
  addTracingListener(listenerSandbox.listener);

  info("Start tracing");
  startTracing({ global: null, prefix: "testPrefix" });
  Assert.equal(listenerSandbox.toggles.length, 1);
  Assert.equal(listenerSandbox.toggles[0], true);

  info("Call some code");
  function bar() {}
  function foo() {
    bar();
  }
  foo();

  // Note that the tracer will record the two Assert.equal and the info calls.
  // So only assert the last two frames.
  const lastFrame = listenerSandbox.frames.at(-1);
  const beforeLastFrame = listenerSandbox.frames.at(-2);
  Assert.equal(beforeLastFrame.depth, 7);
  Assert.equal(beforeLastFrame.formatedDisplayName, "λ foo");
  Assert.equal(beforeLastFrame.prefix, "testPrefix: ");
  Assert.ok(beforeLastFrame.frame);
  Assert.equal(lastFrame.depth, 8);
  Assert.equal(lastFrame.formatedDisplayName, "λ bar");
  Assert.equal(lastFrame.prefix, "testPrefix: ");
  Assert.ok(lastFrame.frame);

  info("Stop tracing");
  stopTracing();
  Assert.equal(listenerSandbox.toggles.length, 2);
  Assert.equal(listenerSandbox.toggles[1], false);

  removeTracingListener(listenerSandbox.listener);
});

add_task(async function testTracingValues() {
  // Test the `traceValues` flag
  const sandbox = Cu.Sandbox("https://example.com");
  Cu.evalInSandbox(
    `function foo() { bar(-0, 1, ["array"], { attribute: 3 }, "4", BigInt(5), Symbol("6"), Infinity, undefined, null, false, NaN, function foo() {}, function () {}, class MyClass {}); }; function bar(a, b, c) {}`,
    sandbox
  );

  // Pass an override method to catch all strings tentatively logged to stdout
  const logs = [];
  function loggingMethod(str) {
    logs.push(str);
  }

  info("Start tracing");
  startTracing({ global: sandbox, traceValues: true, loggingMethod });

  info("Call some code");
  sandbox.foo();

  Assert.equal(logs.length, 3);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ foo()");
  Assert.stringContains(
    logs[2],
    `λ bar(-0, 1, Array(1), [object Object], "4", BigInt(5), Symbol(6), Infinity, undefined, null, false, NaN, function foo(), function anonymous(), class MyClass)`
  );

  info("Stop tracing");
  stopTracing();
});

add_task(async function testTracingFunctionReturn() {
  // Test the `traceFunctionReturn` flag
  const sandbox = Cu.Sandbox("https://example.com");
  Cu.evalInSandbox(
    `function foo() { bar(); return 0 } function bar() { return "string" }; foo();`,
    sandbox
  );

  // Pass an override method to catch all strings tentatively logged to stdout
  const logs = [];
  function loggingMethod(str) {
    logs.push(str);
  }

  info("Start tracing");
  startTracing({ global: sandbox, traceFunctionReturn: true, loggingMethod });

  info("Call some code");
  sandbox.foo();

  Assert.equal(logs.length, 5);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ foo");
  Assert.stringContains(logs[2], "λ bar");
  Assert.stringContains(logs[3], `λ bar return`);
  Assert.stringContains(logs[4], "λ foo return");

  info("Stop tracing");
  stopTracing();
});

add_task(async function testTracingFunctionReturnAndValues() {
  // Test the `traceFunctionReturn` and `traceValues` flag
  const sandbox = Cu.Sandbox("https://example.com");
  Cu.evalInSandbox(
    `function foo() { bar(); second(); } function bar() { return "string" }; function second() { return null; }; foo();`,
    sandbox
  );

  // Pass an override method to catch all strings tentatively logged to stdout
  const logs = [];
  function loggingMethod(str) {
    logs.push(str);
  }

  info("Start tracing");
  startTracing({
    global: sandbox,
    traceFunctionReturn: true,
    traceValues: true,
    loggingMethod,
  });

  info("Call some code");
  sandbox.foo();

  Assert.equal(logs.length, 7);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ foo()");
  Assert.stringContains(logs[2], "λ bar()");
  Assert.stringContains(logs[3], `λ bar return "string"`);
  Assert.stringContains(logs[4], "λ second()");
  Assert.stringContains(logs[5], `λ second return null`);
  Assert.stringContains(logs[6], "λ foo return undefined");

  info("Stop tracing");
  stopTracing();
});

add_task(async function testTracingStep() {
  // Test the `traceStep` flag
  const sandbox = Cu.Sandbox("https://example.com");
  const source = `
function foo() {
  bar();            /* line 3 */
  second();         /* line 4 */
}
function bar() {
  let res;          /* line 7 */
  if (1 === 1) {    /* line 8 */
    res = "string"; /* line 9 */
  } else {
    res = "nope"
  }
  return res;       /* line 13 */
};
function second() {
  let x = 0;        /* line 16 */
  for (let i = 0; i < 2; i++) { /* line 17 */
    x++;            /* line 18 */
  }
  return null;      /* line 20 */
};
foo();`;
  Cu.evalInSandbox(source, sandbox, null, "file.js", 1);

  // Pass an override method to catch all strings tentatively logged to stdout
  const logs = [];
  function loggingMethod(str) {
    logs.push(str);
  }

  info("Start tracing");
  startTracing({
    global: sandbox,
    traceSteps: true,
    loggingMethod,
  });

  info("Call some code");
  sandbox.foo();

  Assert.equal(logs.length, 19);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ foo");
  Assert.stringContains(logs[1], "file.js:3:3");

  // Each "step" only prints the location and nothing more
  Assert.stringContains(logs[2], "file.js:3:3");

  Assert.stringContains(logs[3], "λ bar");
  Assert.stringContains(logs[3], "file.js:6:16");

  Assert.stringContains(logs[4], "file.js:8:7");

  Assert.stringContains(logs[5], "file.js:9:5");

  Assert.stringContains(logs[6], "file.js:13:3");

  Assert.stringContains(logs[7], "file.js:4:3");

  Assert.stringContains(logs[8], "λ second");
  Assert.stringContains(logs[8], "file.js:15:19");

  Assert.stringContains(logs[9], "file.js:16:11");

  // For loop
  Assert.stringContains(logs[10], "file.js:17:16");

  Assert.stringContains(logs[11], "file.js:17:19");

  Assert.stringContains(logs[12], "file.js:18:5");

  Assert.stringContains(logs[13], "file.js:17:26");

  Assert.stringContains(logs[14], "file.js:17:19");

  Assert.stringContains(logs[15], "file.js:18:5");

  Assert.stringContains(logs[16], "file.js:17:26");

  Assert.stringContains(logs[17], "file.js:17:19");
  // End of for loop

  Assert.stringContains(logs[18], "file.js:20:3");

  info("Stop tracing");
  stopTracing();
});

add_task(async function testTracingPauseOnStep() {
  // Test the `pauseOnStep` flag
  const sandbox = Cu.Sandbox("https://example.com");
  sandbox.dump = dump;
  const source = `var counter = 0; function incrementCounter() { let x = 0; dump("++\\n"); counter++; };`;
  Cu.evalInSandbox(source, sandbox);

  // Pass an override method to catch all strings tentatively logged to stdout
  const logs = [];
  let loggingMethodResolve;
  function loggingMethod(str) {
    logs.push(str);
    if (loggingMethodResolve) {
      loggingMethodResolve();
    }
  }

  info("Start tracing without pause");
  startTracing({
    global: sandbox,
    loggingMethod,
  });

  info("Call some code");
  sandbox.incrementCounter();

  Assert.equal(logs.length, 2);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ incrementCounter");

  info(
    "When pauseOnStep isn't used, the traced code runs synchronously to completion"
  );
  Assert.equal(sandbox.counter, 1);

  info("Stop tracing");
  stopTracing();

  logs.length = 0;
  sandbox.counter = 0;

  info("Start tracing with 0ms pause");
  startTracing({
    global: sandbox,
    pauseOnStep: 0,
    loggingMethod,
  });

  let onTraces = Promise.withResolvers();
  let onResumed = Promise.withResolvers();
  // This is used when receiving new traces in `loggingMethod()`
  loggingMethodResolve = onTraces.resolve;

  info(
    "Run the to-be-traced code in a distinct event loop as it would be paused synchronously and would prevent further test script execution"
  );
  Services.tm.dispatchToMainThread(() => {
    sandbox.incrementCounter();
    onResumed.resolve();
  });

  info("Wait for tracer to call the listener");
  await onTraces.promise;

  Assert.equal(logs.length, 2);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ incrementCounter");

  info(
    "When pauseInStep is used, the tracer listener is called, but the traced function is paused and doesn't run synchronously to completion"
  );
  Assert.equal(
    sandbox.counter,
    0,
    "The increment method was called but its execution flow was blocked and couldn't increment"
  );

  info("Wait for traced code to be resumed");
  await onResumed.promise;
  info(
    "If we release the event loop, we can see the traced function completion"
  );
  Assert.equal(sandbox.counter, 1);

  info("Stop tracing");
  stopTracing();

  logs.length = 0;
  sandbox.counter = 0;

  info("Start tracing with 250ms pause");
  startTracing({
    global: sandbox,
    pauseOnStep: 250,
    loggingMethod,
  });

  onTraces = Promise.withResolvers();
  onResumed = Promise.withResolvers();
  // This is used when receiving new traces in `loggingMethod()`
  loggingMethodResolve = onTraces.resolve;

  info(
    "Run the to-be-traced code in a distinct event loop as it would be paused synchronously and would prevent further test script execution"
  );
  const startTimestamp = Cu.now();
  Services.tm.dispatchToMainThread(() => {
    sandbox.incrementCounter();
    onResumed.resolve();
  });

  info("Wait for tracer to call the listener");
  await onTraces.promise;

  Assert.equal(logs.length, 2);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ incrementCounter");

  info(
    "When pauseInStep is used, the tracer lsitener is called, but the traced function is paused and doesn't run synchronously to completion"
  );
  Assert.equal(sandbox.counter, 0);

  info("Wait for traced code to be resumed");
  await onResumed.promise;
  info(
    "If we release the event loop, we can see the traced function completion"
  );
  Assert.equal(sandbox.counter, 1);
  info("The thread should have paused at least the pauseOnStep's duration");
  Assert.greater(Cu.now() - startTimestamp, 250);

  info("Stop tracing");
  stopTracing();
});

add_task(async function testTracingFilterSourceUrl() {
  // Test the `filterFrameSourceUrl` flag
  const sandbox = Cu.Sandbox("https://example.com");

  // Use a unique global (sandbox), but with two distinct scripts (first.js and second.js)
  const source1 = `function foo() { bar(); }`;
  Cu.evalInSandbox(source1, sandbox, null, "first.js", 1);

  // Only code running in that second source should be traced.
  const source2 = `function bar() { }`;
  Cu.evalInSandbox(source2, sandbox, null, "second.js", 1);

  // Pass an override method to catch all strings tentatively logged to stdout
  const logs = [];
  function loggingMethod(str) {
    logs.push(str);
  }

  info("Start tracing");
  startTracing({
    global: sandbox,
    filterFrameSourceUrl: "second",
    loggingMethod,
  });

  info("Call some code");
  sandbox.foo();

  Assert.equal(logs.length, 2);
  Assert.equal(logs[0], "Start tracing JavaScript\n");
  Assert.stringContains(logs[1], "λ bar");
  Assert.stringContains(logs[1], "second.js:1:18");

  info("Stop tracing");
  stopTracing();
});