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/. */
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");
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.
21 var ProcessHangMonitor = {
23 * This timeout is the wait period applied after a user selects "Wait" in
24 * an existing notification.
26 get WAIT_EXPIRATION_TIME() {
28 return Services.prefs.getIntPref("browser.hangNotification.waitPeriod");
35 * Should only be set to true once the quit-application-granted notification
41 * Collection of hang reports that haven't expired or been dismissed
42 * by the user. These are nsIHangReports. They are mapped to objects
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
49 _activeReports: new Map(),
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
57 _pausedReports: new Map(),
60 * Initialize hang reporting. Called once in the parent process.
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);
72 * Terminate JavaScript associated with the hang being reported for
73 * the selected browser in |win|.
75 terminateScript(win) {
76 this.handleUserInput(win, report => report.terminateScript());
80 * Terminate Sandbox globals associated with the hang being reported
81 * for the selected browser in |win|.
83 terminateGlobal(win) {
84 this.handleUserInput(win, report => report.terminateGlobal());
88 * Start devtools debugger for JavaScript associated with the hang
89 * being reported for the selected browser in |win|.
92 this.handleUserInput(win, report => {
94 report.endStartingDebugger();
97 this._recordTelemetryForReport(report, "debugging");
98 report.beginStartingDebugger();
100 let svc = Cc["@mozilla.org/dom/slow-script-debug;1"].getService(
101 Ci.nsISlowScriptDebug
103 let handler = svc.remoteActivationHandler;
104 handler.handleSlowScriptDebug(report.scriptBrowser, callback);
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.
113 terminatePlugin(win) {
114 this.handleUserInput(win, report => report.terminatePlugin());
118 * Dismiss the browser notification and invoke an appropriate action based on
122 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
127 switch (report.hangType) {
128 case report.SLOW_SCRIPT:
129 this._recordTelemetryForReport(report, "user-aborted");
130 this.terminateScript(win);
132 case report.PLUGIN_HANG:
133 this.terminatePlugin(win);
139 * Stop all scripts from running in the Sandbox global attached to
143 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
148 switch (report.hangType) {
149 case report.SLOW_SCRIPT:
150 this._recordTelemetryForReport(report, "user-aborted");
151 this.terminateGlobal(win);
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.
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();
167 report.terminateScript();
171 case report.PLUGIN_HANG: {
172 report.terminatePlugin();
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.
183 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
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(
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();
215 this.WAIT_EXPIRATION_TIME,
219 reportInfo.timer = timer;
220 this._pausedReports.set(report, reportInfo);
222 // remove the browser notification associated with this hang
223 this.updateWindows();
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
231 handleUserInput(win, func) {
232 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
236 this.removeActiveReport(report);
241 observe(subject, topic, data) {
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);
252 case "quit-application-granted": {
253 this.onQuitApplicationGranted();
257 case "process-hang-report": {
258 this.reportHang(subject.QueryInterface(Ci.nsIHangReport));
262 case "clear-hang-report": {
263 this.clearHang(subject.QueryInterface(Ci.nsIHangReport));
267 case "domwindowopened": {
268 // Install event listeners on the new window in case one of
269 // its tabs is already hung.
271 let listener = ev => {
272 win.removeEventListener("load", listener, true);
273 this.updateWindows();
275 win.addEventListener("load", listener, true);
279 case "domwindowclosed": {
281 this.onWindowClosed(win);
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.
293 onQuitApplicationGranted() {
294 this._shuttingDown = true;
295 this.stopAllHangs("quit-application-granted");
296 this.updateWindows();
299 onWindowClosed(win) {
300 let maybeStopHang = report => {
301 if (report.hangType == report.SLOW_SCRIPT) {
302 let hungBrowserWindow = null;
304 hungBrowserWindow = report.scriptBrowser.ownerGlobal;
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
311 if (!hungBrowserWindow || hungBrowserWindow == win) {
312 this.stopHang(report, "window-closed");
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);
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);
332 for (let [pausedReport] of this._pausedReports) {
333 if (maybeStopHang(pausedReport)) {
334 this.removePausedReport(pausedReport);
338 this.updateWindows();
341 stopAllHangs(endReason) {
342 for (let [report] of this._activeReports) {
343 this.stopHang(report, endReason);
346 this._activeReports = new Map();
348 for (let [pausedReport] of this._pausedReports) {
349 this.stopHang(pausedReport, endReason);
350 this.removePausedReport(pausedReport);
355 * Find a active hang report for the given <browser> element.
357 findActiveReport(browser) {
358 let frameLoader = browser.frameLoader;
359 for (let report of this._activeReports.keys()) {
360 if (report.isReportForBrowser(frameLoader)) {
368 * Find a paused hang report for the given <browser> element.
370 findPausedReport(browser) {
371 let frameLoader = browser.frameLoader;
372 for (let [report] of this._pausedReports) {
373 if (report.isReportForBrowser(frameLoader)) {
381 * Tell telemetry about the report.
383 _recordTelemetryForReport(report, endReason, backupInfo) {
385 this._activeReports.get(report) ||
386 this._pausedReports.get(report) ||
392 // Only report slow script hangs.
393 if (report.hangType != report.SLOW_SCRIPT) {
397 if (report.addonId) {
398 uri_type = "extension";
399 } else if (report.scriptFileName?.startsWith("debugger")) {
400 uri_type = "devtools";
403 let url = new URL(report.scriptFileName);
404 if (url.protocol == "chrome:" || url.protocol == "resource:") {
405 uri_type = "browser";
407 uri_type = "content";
411 uri_type = "unknown";
415 if (info.notificationTime) {
416 uptime = Cu.now() - info.notificationTime;
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
426 report.hangDuration + Cu.now() - info.lastReportFromChild;
427 Services.telemetry.recordEvent(
428 "slow_script_warning",
433 end_reason: endReason,
434 hang_duration: "" + hangDuration,
435 n_tab_deselect: "" + info.deselectCount,
438 wait_count: "" + info.waitCount,
447 * Remove an active hang report from the active list and cancel the timer
448 * associated with it.
450 removeActiveReport(report) {
451 this._activeReports.delete(report);
452 this.updateWindows();
456 * Remove a paused hang report from the paused list and cancel the timer
457 * associated with it.
459 removePausedReport(report) {
460 let info = this._pausedReports.get(report);
461 info?.timer?.cancel();
462 this._pausedReports.delete(report);
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.
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");
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);
489 this.untrackWindow(win);
495 * If there is a hang report for the current tab in |win|, display it.
498 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
501 let info = this._activeReports.get(report);
502 if (info && !info.notificationTime) {
503 info.notificationTime = Cu.now();
505 this.showNotification(win, report);
507 this.hideNotification(win);
512 * Show the notification for a hang.
514 showNotification(win, report) {
515 let notification = win.gHighPriorityNotificationBox.getNotificationWithValue(
522 let bundle = win.gNavigatorBundle;
526 label: bundle.getString("processHang.button_stop.label"),
527 accessKey: bundle.getString("processHang.button_stop.accessKey"),
529 ProcessHangMonitor.stopIt(win);
533 label: bundle.getString("processHang.button_wait.label"),
534 accessKey: bundle.getString("processHang.button_wait.accessKey"),
536 ProcessHangMonitor.waitLonger(win);
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
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", [
554 brandBundle.getString("brandShortName"),
557 let linkText = bundle.getString("processHang.add-on.learn-more.text");
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");
565 `openTrustedLinkIn(${JSON.stringify(linkURL)}, "tab")`
567 link.setAttribute("value", linkText);
569 message = doc.createDocumentFragment();
570 message.appendChild(doc.createTextNode(label + " "));
571 message.appendChild(link);
574 label: bundle.getString("processHang.button_stop_sandbox.label"),
575 accessKey: bundle.getString(
576 "processHang.button_stop_sandbox.accessKey"
579 ProcessHangMonitor.stopGlobal(win);
584 if (AppConstants.MOZ_DEV_EDITION && report.hangType == report.SLOW_SCRIPT) {
586 label: bundle.getString("processHang.button_debug.label"),
587 accessKey: bundle.getString("processHang.button_debug.accessKey"),
589 ProcessHangMonitor.debugScript(win);
594 win.gHighPriorityNotificationBox.appendNotification(
597 "chrome://browser/content/aboutRobots-icon.png",
598 win.gHighPriorityNotificationBox.PRIORITY_WARNING_HIGH,
604 * Ensure that no hang notifications are visible in |win|.
606 hideNotification(win) {
607 let notification = win.gHighPriorityNotificationBox.getNotificationWithValue(
611 win.gHighPriorityNotificationBox.removeNotification(notification);
616 * Install event handlers on |win| to watch for events that would
617 * cause a different hang report to be displayed.
620 win.gBrowser.tabContainer.addEventListener("TabSelect", this, true);
621 win.gBrowser.tabContainer.addEventListener(
622 "TabRemotenessChange",
629 win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true);
630 win.gBrowser.tabContainer.removeEventListener(
631 "TabRemotenessChange",
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.
647 this.findActiveReport(event.detail.previousTab.linkedBrowser) ||
648 this.findPausedReport(event.detail.previousTab.linkedBrowser);
650 let info = this._activeReports.get(r) || this._pausedReports.get(r);
651 info.deselectCount++;
654 this.updateWindow(win);
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.
664 if (this._shuttingDown) {
665 this.stopHang(report, "shutdown-in-progress", {
666 lastReportFromChild: now,
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();
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;
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();
697 this._activeReports.set(report, {
699 lastReportFromChild: now,
702 this.updateWindows();
706 this._recordTelemetryForReport(report, "cleared");
708 this.removeActiveReport(report);
709 this.removePausedReport(report);
710 report.userCanceled();