Bug 1667155 [wpt PR 25777] - [AspectRatio] Fix bug in flex-aspect-ratio-024 test...
[gecko.git] / browser / modules / ProcessHangMonitor.jsm
blobf2b5126e31b6a1d8ac447ea6bd19d259080219c7
1 /* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 "use strict";
8 var EXPORTED_SYMBOLS = ["ProcessHangMonitor"];
10 const { AppConstants } = ChromeUtils.import(
11   "resource://gre/modules/AppConstants.jsm"
13 const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
15 /**
16  * This JSM is responsible for observing content process hang reports
17  * and asking the user what to do about them. See nsIHangReport for
18  * the platform interface.
19  */
21 var ProcessHangMonitor = {
22   /**
23    * This timeout is the wait period applied after a user selects "Wait" in
24    * an existing notification.
25    */
26   get WAIT_EXPIRATION_TIME() {
27     try {
28       return Services.prefs.getIntPref("browser.hangNotification.waitPeriod");
29     } catch (ex) {
30       return 10000;
31     }
32   },
34   /**
35    * Should only be set to true once the quit-application-granted notification
36    * has been fired.
37    */
38   _shuttingDown: false,
40   /**
41    * Collection of hang reports that haven't expired or been dismissed
42    * by the user. These are nsIHangReports. They are mapped to objects
43    * containing:
44    * - notificationTime: when (Cu.now()) we first showed a notification
45    * - waitCount: how often the user asked to wait for the script to finish
46    * - lastReportFromChild: when (Cu.now()) we last got hang info from the
47    *   child.
48    */
49   _activeReports: new Map(),
51   /**
52    * Collection of hang reports that have been suppressed for a short
53    * period of time. Value is an object like in _activeReports, but also
54    * including a `timer` prop, which is an nsITimer for when the wait time
55    * expires.
56    */
57   _pausedReports: new Map(),
59   /**
60    * Initialize hang reporting. Called once in the parent process.
61    */
62   init() {
63     Services.obs.addObserver(this, "process-hang-report");
64     Services.obs.addObserver(this, "clear-hang-report");
65     Services.obs.addObserver(this, "quit-application-granted");
66     Services.obs.addObserver(this, "xpcom-shutdown");
67     Services.ww.registerNotification(this);
68     Services.telemetry.setEventRecordingEnabled("slow_script_warning", true);
69   },
71   /**
72    * Terminate JavaScript associated with the hang being reported for
73    * the selected browser in |win|.
74    */
75   terminateScript(win) {
76     this.handleUserInput(win, report => report.terminateScript());
77   },
79   /**
80    * Terminate Sandbox globals associated with the hang being reported
81    * for the selected browser in |win|.
82    */
83   terminateGlobal(win) {
84     this.handleUserInput(win, report => report.terminateGlobal());
85   },
87   /**
88    * Start devtools debugger for JavaScript associated with the hang
89    * being reported for the selected browser in |win|.
90    */
91   debugScript(win) {
92     this.handleUserInput(win, report => {
93       function callback() {
94         report.endStartingDebugger();
95       }
97       this._recordTelemetryForReport(report, "debugging");
98       report.beginStartingDebugger();
100       let svc = Cc["@mozilla.org/dom/slow-script-debug;1"].getService(
101         Ci.nsISlowScriptDebug
102       );
103       let handler = svc.remoteActivationHandler;
104       handler.handleSlowScriptDebug(report.scriptBrowser, callback);
105     });
106   },
108   /**
109    * Terminate the plugin process associated with a hang being reported
110    * for the selected browser in |win|. Will attempt to generate a combined
111    * crash report for all processes.
112    */
113   terminatePlugin(win) {
114     this.handleUserInput(win, report => report.terminatePlugin());
115   },
117   /**
118    * Dismiss the browser notification and invoke an appropriate action based on
119    * the hang type.
120    */
121   stopIt(win) {
122     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
123     if (!report) {
124       return;
125     }
127     switch (report.hangType) {
128       case report.SLOW_SCRIPT:
129         this._recordTelemetryForReport(report, "user-aborted");
130         this.terminateScript(win);
131         break;
132       case report.PLUGIN_HANG:
133         this.terminatePlugin(win);
134         break;
135     }
136   },
138   /**
139    * Stop all scripts from running in the Sandbox global attached to
140    * this window.
141    */
142   stopGlobal(win) {
143     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
144     if (!report) {
145       return;
146     }
148     switch (report.hangType) {
149       case report.SLOW_SCRIPT:
150         this._recordTelemetryForReport(report, "user-aborted");
151         this.terminateGlobal(win);
152         break;
153     }
154   },
156   /**
157    * Terminate whatever is causing this report, be it an add-on, page script,
158    * or plug-in. This is done without updating any report notifications.
159    */
160   stopHang(report, endReason, backupInfo) {
161     switch (report.hangType) {
162       case report.SLOW_SCRIPT: {
163         this._recordTelemetryForReport(report, endReason, backupInfo);
164         if (report.addonId) {
165           report.terminateGlobal();
166         } else {
167           report.terminateScript();
168         }
169         break;
170       }
171       case report.PLUGIN_HANG: {
172         report.terminatePlugin();
173         break;
174       }
175     }
176   },
178   /**
179    * Dismiss the notification, clear the report from the active list and set up
180    * a new timer to track a wait period during which we won't notify.
181    */
182   waitLonger(win) {
183     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
184     if (!report) {
185       return;
186     }
187     // Update the other info we keep.
188     let reportInfo = this._activeReports.get(report);
189     reportInfo.waitCount++;
191     // Remove the report from the active list.
192     this.removeActiveReport(report);
194     // NOTE, we didn't call userCanceled on nsIHangReport here. This insures
195     // we don't repeatedly generate and cache crash report data for this hang
196     // in the process hang reporter. It already has one report for the browser
197     // process we want it hold onto.
199     // Create a new wait timer with notify callback
200     let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
201     timer.initWithCallback(
202       () => {
203         for (let [stashedReport, pausedInfo] of this._pausedReports) {
204           if (pausedInfo.timer === timer) {
205             this.removePausedReport(stashedReport);
207             // We're still hung, so move the report back to the active
208             // list and update the UI.
209             this._activeReports.set(report, pausedInfo);
210             this.updateWindows();
211             break;
212           }
213         }
214       },
215       this.WAIT_EXPIRATION_TIME,
216       timer.TYPE_ONE_SHOT
217     );
219     reportInfo.timer = timer;
220     this._pausedReports.set(report, reportInfo);
222     // remove the browser notification associated with this hang
223     this.updateWindows();
224   },
226   /**
227    * If there is a hang report associated with the selected browser in
228    * |win|, invoke |func| on that report and stop notifying the user
229    * about it.
230    */
231   handleUserInput(win, func) {
232     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
233     if (!report) {
234       return null;
235     }
236     this.removeActiveReport(report);
238     return func(report);
239   },
241   observe(subject, topic, data) {
242     switch (topic) {
243       case "xpcom-shutdown": {
244         Services.obs.removeObserver(this, "xpcom-shutdown");
245         Services.obs.removeObserver(this, "process-hang-report");
246         Services.obs.removeObserver(this, "clear-hang-report");
247         Services.obs.removeObserver(this, "quit-application-granted");
248         Services.ww.unregisterNotification(this);
249         break;
250       }
252       case "quit-application-granted": {
253         this.onQuitApplicationGranted();
254         break;
255       }
257       case "process-hang-report": {
258         this.reportHang(subject.QueryInterface(Ci.nsIHangReport));
259         break;
260       }
262       case "clear-hang-report": {
263         this.clearHang(subject.QueryInterface(Ci.nsIHangReport));
264         break;
265       }
267       case "domwindowopened": {
268         // Install event listeners on the new window in case one of
269         // its tabs is already hung.
270         let win = subject;
271         let listener = ev => {
272           win.removeEventListener("load", listener, true);
273           this.updateWindows();
274         };
275         win.addEventListener("load", listener, true);
276         break;
277       }
279       case "domwindowclosed": {
280         let win = subject;
281         this.onWindowClosed(win);
282         break;
283       }
284     }
285   },
287   /**
288    * Called early on in the shutdown sequence. We take this opportunity to
289    * take any pre-existing hang reports, and terminate them. We also put
290    * ourselves in a state so that if any more hang reports show up while
291    * we're shutting down, we terminate them immediately.
292    */
293   onQuitApplicationGranted() {
294     this._shuttingDown = true;
295     this.stopAllHangs("quit-application-granted");
296     this.updateWindows();
297   },
299   onWindowClosed(win) {
300     let maybeStopHang = report => {
301       if (report.hangType == report.SLOW_SCRIPT) {
302         let hungBrowserWindow = null;
303         try {
304           hungBrowserWindow = report.scriptBrowser.ownerGlobal;
305         } catch (e) {
306           // Ignore failures to get the script browser - we'll be
307           // conservative, and assume that if we cannot access the
308           // window that belongs to this report that we should stop
309           // the hang.
310         }
311         if (!hungBrowserWindow || hungBrowserWindow == win) {
312           this.stopHang(report, "window-closed");
313           return true;
314         }
315       } else if (report.hangType == report.PLUGIN_HANG) {
316         // If any window has closed during a plug-in hang, we'll
317         // do the conservative thing and terminate the plug-in.
318         this.stopHang(report);
319         return true;
320       }
321       return false;
322     };
324     // If there are any script hangs for browsers that are in this window
325     // that is closing, we can stop them now.
326     for (let [report] of this._activeReports) {
327       if (maybeStopHang(report)) {
328         this._activeReports.delete(report);
329       }
330     }
332     for (let [pausedReport] of this._pausedReports) {
333       if (maybeStopHang(pausedReport)) {
334         this.removePausedReport(pausedReport);
335       }
336     }
338     this.updateWindows();
339   },
341   stopAllHangs(endReason) {
342     for (let [report] of this._activeReports) {
343       this.stopHang(report, endReason);
344     }
346     this._activeReports = new Map();
348     for (let [pausedReport] of this._pausedReports) {
349       this.stopHang(pausedReport, endReason);
350       this.removePausedReport(pausedReport);
351     }
352   },
354   /**
355    * Find a active hang report for the given <browser> element.
356    */
357   findActiveReport(browser) {
358     let frameLoader = browser.frameLoader;
359     for (let report of this._activeReports.keys()) {
360       if (report.isReportForBrowser(frameLoader)) {
361         return report;
362       }
363     }
364     return null;
365   },
367   /**
368    * Find a paused hang report for the given <browser> element.
369    */
370   findPausedReport(browser) {
371     let frameLoader = browser.frameLoader;
372     for (let [report] of this._pausedReports) {
373       if (report.isReportForBrowser(frameLoader)) {
374         return report;
375       }
376     }
377     return null;
378   },
380   /**
381    * Tell telemetry about the report.
382    */
383   _recordTelemetryForReport(report, endReason, backupInfo) {
384     let info =
385       this._activeReports.get(report) ||
386       this._pausedReports.get(report) ||
387       backupInfo;
388     if (!info) {
389       return;
390     }
391     try {
392       // Only report slow script hangs.
393       if (report.hangType != report.SLOW_SCRIPT) {
394         return;
395       }
396       let uri_type;
397       if (report.addonId) {
398         uri_type = "extension";
399       } else if (report.scriptFileName?.startsWith("debugger")) {
400         uri_type = "devtools";
401       } else {
402         try {
403           let url = new URL(report.scriptFileName);
404           if (url.protocol == "chrome:" || url.protocol == "resource:") {
405             uri_type = "browser";
406           } else {
407             uri_type = "content";
408           }
409         } catch (ex) {
410           Cu.reportError(ex);
411           uri_type = "unknown";
412         }
413       }
414       let uptime = 0;
415       if (info.notificationTime) {
416         uptime = Cu.now() - info.notificationTime;
417       }
418       uptime = "" + uptime;
419       // We combine the duration of the hang in the content process with the
420       // time since we were last told about the hang in the parent. This is
421       // not the same as the time we showed a notification, as we only do that
422       // for the currently selected browser. It's as messy as it is because
423       // there is no cross-process monotonically increasing timestamp we can
424       // use. :-(
425       let hangDuration =
426         report.hangDuration + Cu.now() - info.lastReportFromChild;
427       Services.telemetry.recordEvent(
428         "slow_script_warning",
429         "shown",
430         "content",
431         null,
432         {
433           end_reason: endReason,
434           hang_duration: "" + hangDuration,
435           n_tab_deselect: "" + info.deselectCount,
436           uri_type,
437           uptime,
438           wait_count: "" + info.waitCount,
439         }
440       );
441     } catch (ex) {
442       Cu.reportError(ex);
443     }
444   },
446   /**
447    * Remove an active hang report from the active list and cancel the timer
448    * associated with it.
449    */
450   removeActiveReport(report) {
451     this._activeReports.delete(report);
452     this.updateWindows();
453   },
455   /**
456    * Remove a paused hang report from the paused list and cancel the timer
457    * associated with it.
458    */
459   removePausedReport(report) {
460     let info = this._pausedReports.get(report);
461     info?.timer?.cancel();
462     this._pausedReports.delete(report);
463   },
465   /**
466    * Iterate over all XUL windows and ensure that the proper hang
467    * reports are shown for each one. Also install event handlers in
468    * each window to watch for events that would cause a different hang
469    * report to be displayed.
470    */
471   updateWindows() {
472     let e = Services.wm.getEnumerator("navigator:browser");
474     // If it turns out we have no windows (this can happen on macOS),
475     // we have no opportunity to ask the user whether or not they want
476     // to stop the hang or wait, so we'll opt for stopping the hang.
477     if (!e.hasMoreElements()) {
478       this.stopAllHangs("no-windows-left");
479       return;
480     }
482     for (let win of e) {
483       this.updateWindow(win);
485       // Only listen for these events if there are active hang reports.
486       if (this._activeReports.size) {
487         this.trackWindow(win);
488       } else {
489         this.untrackWindow(win);
490       }
491     }
492   },
494   /**
495    * If there is a hang report for the current tab in |win|, display it.
496    */
497   updateWindow(win) {
498     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
500     if (report) {
501       let info = this._activeReports.get(report);
502       if (info && !info.notificationTime) {
503         info.notificationTime = Cu.now();
504       }
505       this.showNotification(win, report);
506     } else {
507       this.hideNotification(win);
508     }
509   },
511   /**
512    * Show the notification for a hang.
513    */
514   showNotification(win, report) {
515     let notification = win.gHighPriorityNotificationBox.getNotificationWithValue(
516       "process-hang"
517     );
518     if (notification) {
519       return;
520     }
522     let bundle = win.gNavigatorBundle;
524     let buttons = [
525       {
526         label: bundle.getString("processHang.button_stop.label"),
527         accessKey: bundle.getString("processHang.button_stop.accessKey"),
528         callback() {
529           ProcessHangMonitor.stopIt(win);
530         },
531       },
532       {
533         label: bundle.getString("processHang.button_wait.label"),
534         accessKey: bundle.getString("processHang.button_wait.accessKey"),
535         callback() {
536           ProcessHangMonitor.waitLonger(win);
537         },
538       },
539     ];
541     let message = bundle.getString("processHang.label");
542     if (report.addonId) {
543       let aps = Cc["@mozilla.org/addons/policy-service;1"].getService(
544         Ci.nsIAddonPolicyService
545       );
547       let doc = win.document;
548       let brandBundle = doc.getElementById("bundle_brand");
550       let addonName = aps.getExtensionName(report.addonId);
552       let label = bundle.getFormattedString("processHang.add-on.label", [
553         addonName,
554         brandBundle.getString("brandShortName"),
555       ]);
557       let linkText = bundle.getString("processHang.add-on.learn-more.text");
558       let linkURL =
559         "https://support.mozilla.org/kb/warning-unresponsive-script#w_other-causes";
561       let link = doc.createXULElement("label", { is: "text-link" });
562       link.setAttribute("role", "link");
563       link.setAttribute(
564         "onclick",
565         `openTrustedLinkIn(${JSON.stringify(linkURL)}, "tab")`
566       );
567       link.setAttribute("value", linkText);
569       message = doc.createDocumentFragment();
570       message.appendChild(doc.createTextNode(label + " "));
571       message.appendChild(link);
573       buttons.unshift({
574         label: bundle.getString("processHang.button_stop_sandbox.label"),
575         accessKey: bundle.getString(
576           "processHang.button_stop_sandbox.accessKey"
577         ),
578         callback() {
579           ProcessHangMonitor.stopGlobal(win);
580         },
581       });
582     }
584     if (AppConstants.MOZ_DEV_EDITION && report.hangType == report.SLOW_SCRIPT) {
585       buttons.push({
586         label: bundle.getString("processHang.button_debug.label"),
587         accessKey: bundle.getString("processHang.button_debug.accessKey"),
588         callback() {
589           ProcessHangMonitor.debugScript(win);
590         },
591       });
592     }
594     win.gHighPriorityNotificationBox.appendNotification(
595       message,
596       "process-hang",
597       "chrome://browser/content/aboutRobots-icon.png",
598       win.gHighPriorityNotificationBox.PRIORITY_WARNING_HIGH,
599       buttons
600     );
601   },
603   /**
604    * Ensure that no hang notifications are visible in |win|.
605    */
606   hideNotification(win) {
607     let notification = win.gHighPriorityNotificationBox.getNotificationWithValue(
608       "process-hang"
609     );
610     if (notification) {
611       win.gHighPriorityNotificationBox.removeNotification(notification);
612     }
613   },
615   /**
616    * Install event handlers on |win| to watch for events that would
617    * cause a different hang report to be displayed.
618    */
619   trackWindow(win) {
620     win.gBrowser.tabContainer.addEventListener("TabSelect", this, true);
621     win.gBrowser.tabContainer.addEventListener(
622       "TabRemotenessChange",
623       this,
624       true
625     );
626   },
628   untrackWindow(win) {
629     win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true);
630     win.gBrowser.tabContainer.removeEventListener(
631       "TabRemotenessChange",
632       this,
633       true
634     );
635   },
637   handleEvent(event) {
638     let win = event.target.ownerGlobal;
640     // If a new tab is selected or if a tab changes remoteness, then
641     // we may need to show or hide a hang notification.
642     if (event.type == "TabSelect" || event.type == "TabRemotenessChange") {
643       if (event.type == "TabSelect" && event.detail.previousTab) {
644         // If we've got a notification, check the previous tab's report and
645         // indicate the user switched tabs while the notification was up.
646         let r =
647           this.findActiveReport(event.detail.previousTab.linkedBrowser) ||
648           this.findPausedReport(event.detail.previousTab.linkedBrowser);
649         if (r) {
650           let info = this._activeReports.get(r) || this._pausedReports.get(r);
651           info.deselectCount++;
652         }
653       }
654       this.updateWindow(win);
655     }
656   },
658   /**
659    * Handle a potentially new hang report. If it hasn't been seen
660    * before, show a notification for it in all open XUL windows.
661    */
662   reportHang(report) {
663     let now = Cu.now();
664     if (this._shuttingDown) {
665       this.stopHang(report, "shutdown-in-progress", {
666         lastReportFromChild: now,
667       });
668       return;
669     }
671     // If this hang was already reported reset the timer for it.
672     if (this._activeReports.has(report)) {
673       this._activeReports.get(report).lastReportFromChild = now;
674       // if this report is in active but doesn't have a notification associated
675       // with it, display a notification.
676       this.updateWindows();
677       return;
678     }
680     // If this hang was already reported and paused by the user ignore it.
681     if (this._pausedReports.has(report)) {
682       this._pausedReports.get(report).lastReportFromChild = now;
683       return;
684     }
686     // On e10s this counts slow-script/hanged-plugin notice only once.
687     // This code is not reached on non-e10s.
688     if (report.hangType == report.SLOW_SCRIPT) {
689       // On non-e10s, SLOW_SCRIPT_NOTICE_COUNT is probed at nsGlobalWindow.cpp
690       Services.telemetry.getHistogramById("SLOW_SCRIPT_NOTICE_COUNT").add();
691     } else if (report.hangType == report.PLUGIN_HANG) {
692       // On non-e10s we have sufficient plugin telemetry probes,
693       // so PLUGIN_HANG_NOTICE_COUNT is only probed on e10s.
694       Services.telemetry.getHistogramById("PLUGIN_HANG_NOTICE_COUNT").add();
695     }
697     this._activeReports.set(report, {
698       deselectCount: 0,
699       lastReportFromChild: now,
700       waitCount: 0,
701     });
702     this.updateWindows();
703   },
705   clearHang(report) {
706     this._recordTelemetryForReport(report, "cleared");
708     this.removeActiveReport(report);
709     this.removePausedReport(report);
710     report.userCanceled();
711   },