summaryrefslogtreecommitdiffstats
path: root/browser/modules/test/browser/browser_ProcessHangNotifications.js
blob: fd8116abfe786a892035c7999b9e4e0afa842782 (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
/* globals ProcessHangMonitor */

const { WebExtensionPolicy } = Cu.getGlobalForObject(Services);

function promiseNotificationShown(aWindow, aName) {
  return new Promise(resolve => {
    let notificationBox = aWindow.gNotificationBox;
    notificationBox.stack.addEventListener(
      "AlertActive",
      function () {
        is(
          notificationBox.allNotifications.length,
          1,
          "Notification Displayed."
        );
        resolve(notificationBox);
      },
      { once: true }
    );
  });
}

function pushPrefs(...aPrefs) {
  return SpecialPowers.pushPrefEnv({ set: aPrefs });
}

function popPrefs() {
  return SpecialPowers.popPrefEnv();
}

const TEST_ACTION_UNKNOWN = 0;
const TEST_ACTION_CANCELLED = 1;
const TEST_ACTION_TERMSCRIPT = 2;
const TEST_ACTION_TERMGLOBAL = 3;
const SLOW_SCRIPT = 1;
const ADDON_HANG = 3;
const ADDON_ID = "fake-addon";

/**
 * A mock nsIHangReport that we can pass through nsIObserverService
 * to trigger notifications.
 *
 * @param hangType
 *        One of SLOW_SCRIPT, ADDON_HANG.
 * @param browser (optional)
 *        The <xul:browser> that this hang should be associated with.
 *        If not supplied, the hang will be associated with every browser,
 *        but the nsIHangReport.scriptBrowser attribute will return the
 *        currently selected browser in this window's gBrowser.
 */
let TestHangReport = function (
  hangType = SLOW_SCRIPT,
  browser = gBrowser.selectedBrowser
) {
  this.promise = new Promise((resolve, reject) => {
    this._resolver = resolve;
  });

  if (hangType == ADDON_HANG) {
    // Add-on hangs need an associated add-on ID for us to blame.
    this._addonId = ADDON_ID;
  }

  this._browser = browser;
};

TestHangReport.prototype = {
  get addonId() {
    return this._addonId;
  },

  QueryInterface: ChromeUtils.generateQI(["nsIHangReport"]),

  userCanceled() {
    this._resolver(TEST_ACTION_CANCELLED);
  },

  terminateScript() {
    this._resolver(TEST_ACTION_TERMSCRIPT);
  },

  isReportForBrowserOrChildren(aFrameLoader) {
    if (this._browser) {
      return this._browser.frameLoader === aFrameLoader;
    }

    return true;
  },

  get scriptBrowser() {
    return this._browser;
  },

  // Shut up warnings about this property missing:
  get scriptFileName() {
    return "chrome://browser/content/browser.js";
  },
};

// on dev edition we add a button for js debugging of hung scripts.
let buttonCount = AppConstants.MOZ_DEV_EDITION ? 2 : 1;

add_setup(async function () {
  // Create a fake WebExtensionPolicy that we can use for
  // the add-on hang notification.
  const uuidGen = Services.uuid;
  const uuid = uuidGen.generateUUID().number.slice(1, -1);
  let policy = new WebExtensionPolicy({
    name: "Scapegoat",
    id: ADDON_ID,
    mozExtensionHostname: uuid,
    baseURL: "file:///",
    allowedOrigins: new MatchPatternSet([]),
    localizeCallback() {},
  });
  policy.active = true;

  registerCleanupFunction(() => {
    policy.active = false;
  });
});

/**
 * Test if hang reports receive a terminate script callback when the user selects
 * stop in response to a script hang.
 */
add_task(async function terminateScriptTest() {
  let promise = promiseNotificationShown(window, "process-hang");
  let hangReport = new TestHangReport();
  Services.obs.notifyObservers(hangReport, "process-hang-report");
  let notification = await promise;

  let buttons =
    notification.currentNotification.buttonContainer.getElementsByTagName(
      "button"
    );
  is(buttons.length, buttonCount, "proper number of buttons");

  // Click the "Stop" button, we should get a terminate script callback
  buttons[0].click();
  let action = await hangReport.promise;
  is(
    action,
    TEST_ACTION_TERMSCRIPT,
    "Clicking 'Stop' should have terminated the script."
  );
});

/**
 * Test if hang reports receive user canceled callbacks after a user selects wait
 * and the browser frees up from a script hang on its own.
 */
add_task(async function waitForScriptTest() {
  let hangReport = new TestHangReport();
  let promise = promiseNotificationShown(window, "process-hang");
  Services.obs.notifyObservers(hangReport, "process-hang-report");
  let notification = await promise;

  let buttons =
    notification.currentNotification.buttonContainer.getElementsByTagName(
      "button"
    );
  is(buttons.length, buttonCount, "proper number of buttons");

  await pushPrefs(["browser.hangNotification.waitPeriod", 1000]);

  let ignoringReport = true;

  hangReport.promise.then(action => {
    if (ignoringReport) {
      ok(
        false,
        "Hang report was somehow dealt with when it " +
          "should have been ignored."
      );
    } else {
      is(
        action,
        TEST_ACTION_CANCELLED,
        "Hang report should have been cancelled."
      );
    }
  });

  // Click the "Close" button this time, we shouldn't get a callback at all.
  notification.currentNotification.closeButton.click();

  // send another hang pulse, we should not get a notification here
  Services.obs.notifyObservers(hangReport, "process-hang-report");
  is(
    notification.currentNotification,
    null,
    "no notification should be visible"
  );

  // Make sure that any queued Promises have run to give our report-ignoring
  // then() a chance to fire.
  await Promise.resolve();

  ignoringReport = false;
  Services.obs.notifyObservers(hangReport, "clear-hang-report");

  await popPrefs();
});

/**
 * Test if hang reports receive user canceled callbacks after the content
 * process stops sending hang notifications.
 */
add_task(async function hangGoesAwayTest() {
  await pushPrefs(["browser.hangNotification.expiration", 1000]);

  let hangReport = new TestHangReport();
  let promise = promiseNotificationShown(window, "process-hang");
  Services.obs.notifyObservers(hangReport, "process-hang-report");
  await promise;

  Services.obs.notifyObservers(hangReport, "clear-hang-report");
  let action = await hangReport.promise;
  is(action, TEST_ACTION_CANCELLED, "Hang report should have been cancelled.");

  await popPrefs();
});

/**
 * Tests that if we're shutting down, any pre-existing hang reports will
 * be terminated appropriately.
 */
add_task(async function terminateAtShutdown() {
  let pausedHang = new TestHangReport(SLOW_SCRIPT);
  Services.obs.notifyObservers(pausedHang, "process-hang-report");
  ProcessHangMonitor.waitLonger(window);
  ok(
    ProcessHangMonitor.findPausedReport(gBrowser.selectedBrowser),
    "There should be a paused report for the selected browser."
  );

  let scriptHang = new TestHangReport(SLOW_SCRIPT);
  let addonHang = new TestHangReport(ADDON_HANG);

  [scriptHang, addonHang].forEach(hangReport => {
    Services.obs.notifyObservers(hangReport, "process-hang-report");
  });

  // Simulate the browser being told to shutdown. This should cause
  // hangs to terminate scripts.
  ProcessHangMonitor.onQuitApplicationGranted();

  // In case this test happens to throw before it can finish, make
  // sure to reset the shutting-down state.
  registerCleanupFunction(() => {
    ProcessHangMonitor._shuttingDown = false;
  });

  let pausedAction = await pausedHang.promise;
  let scriptAction = await scriptHang.promise;
  let addonAction = await addonHang.promise;

  is(
    pausedAction,
    TEST_ACTION_TERMSCRIPT,
    "On shutdown, should have terminated script for paused script hang."
  );
  is(
    scriptAction,
    TEST_ACTION_TERMSCRIPT,
    "On shutdown, should have terminated script for script hang."
  );
  is(
    addonAction,
    TEST_ACTION_TERMSCRIPT,
    "On shutdown, should have terminated script for add-on hang."
  );

  // ProcessHangMonitor should now be in the "shutting down" state,
  // meaning that any further hangs should be handled immediately
  // without user interaction.
  let scriptHang2 = new TestHangReport(SLOW_SCRIPT);
  let addonHang2 = new TestHangReport(ADDON_HANG);

  [scriptHang2, addonHang2].forEach(hangReport => {
    Services.obs.notifyObservers(hangReport, "process-hang-report");
  });

  let scriptAction2 = await scriptHang.promise;
  let addonAction2 = await addonHang.promise;

  is(
    scriptAction2,
    TEST_ACTION_TERMSCRIPT,
    "On shutdown, should have terminated script for script hang."
  );
  is(
    addonAction2,
    TEST_ACTION_TERMSCRIPT,
    "On shutdown, should have terminated script for add-on hang."
  );

  ProcessHangMonitor._shuttingDown = false;
});

/**
 * Test that if there happens to be no open browser windows, that any
 * hang reports that exist or appear while in this state will be handled
 * automatically.
 */
add_task(async function terminateNoWindows() {
  let testWin = await BrowserTestUtils.openNewBrowserWindow();

  let pausedHang = new TestHangReport(
    SLOW_SCRIPT,
    testWin.gBrowser.selectedBrowser
  );
  Services.obs.notifyObservers(pausedHang, "process-hang-report");
  ProcessHangMonitor.waitLonger(testWin);
  ok(
    ProcessHangMonitor.findPausedReport(testWin.gBrowser.selectedBrowser),
    "There should be a paused report for the selected browser."
  );

  let scriptHang = new TestHangReport(SLOW_SCRIPT);
  let addonHang = new TestHangReport(ADDON_HANG);

  [scriptHang, addonHang].forEach(hangReport => {
    Services.obs.notifyObservers(hangReport, "process-hang-report");
  });

  // Quick and dirty hack to trick the window mediator into thinking there
  // are no browser windows without actually closing all browser windows.
  document.documentElement.setAttribute(
    "windowtype",
    "navigator:browsertestdummy"
  );

  // In case this test happens to throw before it can finish, make
  // sure to reset this.
  registerCleanupFunction(() => {
    document.documentElement.setAttribute("windowtype", "navigator:browser");
  });

  await BrowserTestUtils.closeWindow(testWin);

  let pausedAction = await pausedHang.promise;
  let scriptAction = await scriptHang.promise;
  let addonAction = await addonHang.promise;

  is(
    pausedAction,
    TEST_ACTION_TERMSCRIPT,
    "With no open windows, should have terminated script for paused script hang."
  );
  is(
    scriptAction,
    TEST_ACTION_TERMSCRIPT,
    "With no open windows, should have terminated script for script hang."
  );
  is(
    addonAction,
    TEST_ACTION_TERMSCRIPT,
    "With no open windows, should have terminated script for add-on hang."
  );

  // ProcessHangMonitor should notice we're in the "no windows" state,
  // so any further hangs should be handled immediately without user
  // interaction.
  let scriptHang2 = new TestHangReport(SLOW_SCRIPT);
  let addonHang2 = new TestHangReport(ADDON_HANG);

  [scriptHang2, addonHang2].forEach(hangReport => {
    Services.obs.notifyObservers(hangReport, "process-hang-report");
  });

  let scriptAction2 = await scriptHang.promise;
  let addonAction2 = await addonHang.promise;

  is(
    scriptAction2,
    TEST_ACTION_TERMSCRIPT,
    "With no open windows, should have terminated script for script hang."
  );
  is(
    addonAction2,
    TEST_ACTION_TERMSCRIPT,
    "With no open windows, should have terminated script for add-on hang."
  );

  document.documentElement.setAttribute("windowtype", "navigator:browser");
});

/**
 * Test that if a script hang occurs in one browser window, and that
 * browser window goes away, that we clear the hang. For plug-in hangs,
 * we do the conservative thing and terminate any plug-in hangs when a
 * window closes, even though we don't exactly know which window it
 * belongs to.
 */
add_task(async function terminateClosedWindow() {
  let testWin = await BrowserTestUtils.openNewBrowserWindow();
  let testBrowser = testWin.gBrowser.selectedBrowser;

  let pausedHang = new TestHangReport(SLOW_SCRIPT, testBrowser);
  Services.obs.notifyObservers(pausedHang, "process-hang-report");
  ProcessHangMonitor.waitLonger(testWin);
  ok(
    ProcessHangMonitor.findPausedReport(testWin.gBrowser.selectedBrowser),
    "There should be a paused report for the selected browser."
  );

  let scriptHang = new TestHangReport(SLOW_SCRIPT, testBrowser);
  let addonHang = new TestHangReport(ADDON_HANG, testBrowser);

  [scriptHang, addonHang].forEach(hangReport => {
    Services.obs.notifyObservers(hangReport, "process-hang-report");
  });

  await BrowserTestUtils.closeWindow(testWin);

  let pausedAction = await pausedHang.promise;
  let scriptAction = await scriptHang.promise;
  let addonAction = await addonHang.promise;

  is(
    pausedAction,
    TEST_ACTION_TERMSCRIPT,
    "When closing window, should have terminated script for a paused script hang."
  );
  is(
    scriptAction,
    TEST_ACTION_TERMSCRIPT,
    "When closing window, should have terminated script for script hang."
  );
  is(
    addonAction,
    TEST_ACTION_TERMSCRIPT,
    "When closing window, should have terminated script for add-on hang."
  );
});

/**
 * Test that permitUnload (used for closing or discarding tabs) does not
 * try to talk to the hung child
 */
add_task(async function permitUnload() {
  let testWin = await BrowserTestUtils.openNewBrowserWindow();
  let testTab = testWin.gBrowser.selectedTab;

  // Ensure we don't close the window:
  BrowserTestUtils.addTab(testWin.gBrowser, "about:blank");

  // Set up the test tab and another tab so we can check what happens when
  // they are closed:
  let otherTab = BrowserTestUtils.addTab(testWin.gBrowser, "about:blank");
  let permitUnloadCount = 0;
  for (let tab of [testTab, otherTab]) {
    let browser = tab.linkedBrowser;
    // Fake before unload state:
    Object.defineProperty(browser, "hasBeforeUnload", { value: true });
    // Increment permitUnloadCount if we ask for unload permission:
    browser.asyncPermitUnload = () => {
      permitUnloadCount++;
      return Promise.resolve({ permitUnload: true });
    };
  }

  // Set up a hang for the selected tab:
  let testBrowser = testTab.linkedBrowser;
  let pausedHang = new TestHangReport(SLOW_SCRIPT, testBrowser);
  Services.obs.notifyObservers(pausedHang, "process-hang-report");
  ProcessHangMonitor.waitLonger(testWin);
  ok(
    ProcessHangMonitor.findPausedReport(testWin.gBrowser.selectedBrowser),
    "There should be a paused report for the browser we're about to remove."
  );

  BrowserTestUtils.removeTab(otherTab);
  BrowserTestUtils.removeTab(testWin.gBrowser.getTabForBrowser(testBrowser));
  is(
    permitUnloadCount,
    1,
    "Should have called asyncPermitUnload once (not for the hung tab)."
  );

  await BrowserTestUtils.closeWindow(testWin);
});