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 import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
9 * Elides the middle of a string by replacing it with an elipsis if it is
10 * longer than `threshold` characters. Does its best to not break up grapheme
13 function elideMiddleOfString(str, threshold) {
14 const searchDistance = 5;
15 const stubLength = threshold / 2 - searchDistance;
16 if (str.length <= threshold || stubLength < searchDistance) {
20 function searchElisionPoint(position) {
21 let unsplittableCharacter = c => /[\p{M}\uDC00-\uDFFF]/u.test(c);
22 for (let i = 0; i < searchDistance; i++) {
23 if (!unsplittableCharacter(str[position + i])) {
27 if (!unsplittableCharacter(str[position - i])) {
34 let elisionStart = searchElisionPoint(stubLength);
35 let elisionEnd = searchElisionPoint(str.length - stubLength);
36 if (elisionStart < elisionEnd) {
37 str = str.slice(0, elisionStart) + "\u2026" + str.slice(elisionEnd);
43 * This JSM is responsible for observing content process hang reports
44 * and asking the user what to do about them. See nsIHangReport for
45 * the platform interface.
48 export var ProcessHangMonitor = {
50 * This timeout is the wait period applied after a user selects "Wait" in
51 * an existing notification.
53 get WAIT_EXPIRATION_TIME() {
55 return Services.prefs.getIntPref("browser.hangNotification.waitPeriod");
62 * Should only be set to true once the quit-application-granted notification
68 * Collection of hang reports that haven't expired or been dismissed
69 * by the user. These are nsIHangReports. They are mapped to objects
71 * - notificationTime: when (Cu.now()) we first showed a notification
72 * - waitCount: how often the user asked to wait for the script to finish
73 * - lastReportFromChild: when (Cu.now()) we last got hang info from the
76 _activeReports: new Map(),
79 * Collection of hang reports that have been suppressed for a short
80 * period of time. Value is an object like in _activeReports, but also
81 * including a `timer` prop, which is an nsITimer for when the wait time
84 _pausedReports: new Map(),
87 * Initialize hang reporting. Called once in the parent process.
90 Services.obs.addObserver(this, "process-hang-report");
91 Services.obs.addObserver(this, "clear-hang-report");
92 Services.obs.addObserver(this, "quit-application-granted");
93 Services.obs.addObserver(this, "xpcom-shutdown");
94 Services.ww.registerNotification(this);
95 Services.telemetry.setEventRecordingEnabled("slow_script_warning", true);
99 * Terminate JavaScript associated with the hang being reported for
100 * the selected browser in |win|.
102 terminateScript(win) {
103 this.handleUserInput(win, report => report.terminateScript());
107 * Start devtools debugger for JavaScript associated with the hang
108 * being reported for the selected browser in |win|.
111 this.handleUserInput(win, report => {
112 function callback() {
113 report.endStartingDebugger();
116 this._recordTelemetryForReport(report, "debugging");
117 report.beginStartingDebugger();
119 let svc = Cc["@mozilla.org/dom/slow-script-debug;1"].getService(
120 Ci.nsISlowScriptDebug
122 let handler = svc.remoteActivationHandler;
123 handler.handleSlowScriptDebug(report.scriptBrowser, callback);
128 * Dismiss the browser notification and invoke an appropriate action based on
132 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
137 this._recordTelemetryForReport(report, "user-aborted");
138 this.terminateScript(win);
142 * Terminate the script causing this report. This is done without
143 * updating any report notifications.
145 stopHang(report, endReason, backupInfo) {
146 this._recordTelemetryForReport(report, endReason, backupInfo);
147 report.terminateScript();
151 * Dismiss the notification, clear the report from the active list and set up
152 * a new timer to track a wait period during which we won't notify.
155 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
159 // Update the other info we keep.
160 let reportInfo = this._activeReports.get(report);
161 reportInfo.waitCount++;
163 // Remove the report from the active list.
164 this.removeActiveReport(report);
166 // NOTE, we didn't call userCanceled on nsIHangReport here. This insures
167 // we don't repeatedly generate and cache crash report data for this hang
168 // in the process hang reporter. It already has one report for the browser
169 // process we want it hold onto.
171 // Create a new wait timer with notify callback
172 let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
173 timer.initWithCallback(
175 for (let [stashedReport, pausedInfo] of this._pausedReports) {
176 if (pausedInfo.timer === timer) {
177 this.removePausedReport(stashedReport);
179 // We're still hung, so move the report back to the active
180 // list and update the UI.
181 this._activeReports.set(report, pausedInfo);
182 this.updateWindows();
187 this.WAIT_EXPIRATION_TIME,
191 reportInfo.timer = timer;
192 this._pausedReports.set(report, reportInfo);
194 // remove the browser notification associated with this hang
195 this.updateWindows();
199 * If there is a hang report associated with the selected browser in
200 * |win|, invoke |func| on that report and stop notifying the user
203 handleUserInput(win, func) {
204 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
208 this.removeActiveReport(report);
213 observe(subject, topic, data) {
215 case "xpcom-shutdown": {
216 Services.obs.removeObserver(this, "xpcom-shutdown");
217 Services.obs.removeObserver(this, "process-hang-report");
218 Services.obs.removeObserver(this, "clear-hang-report");
219 Services.obs.removeObserver(this, "quit-application-granted");
220 Services.ww.unregisterNotification(this);
224 case "quit-application-granted": {
225 this.onQuitApplicationGranted();
229 case "process-hang-report": {
230 this.reportHang(subject.QueryInterface(Ci.nsIHangReport));
234 case "clear-hang-report": {
235 this.clearHang(subject.QueryInterface(Ci.nsIHangReport));
239 case "domwindowopened": {
240 // Install event listeners on the new window in case one of
241 // its tabs is already hung.
243 let listener = ev => {
244 win.removeEventListener("load", listener, true);
245 this.updateWindows();
247 win.addEventListener("load", listener, true);
251 case "domwindowclosed": {
253 this.onWindowClosed(win);
260 * Called early on in the shutdown sequence. We take this opportunity to
261 * take any pre-existing hang reports, and terminate them. We also put
262 * ourselves in a state so that if any more hang reports show up while
263 * we're shutting down, we terminate them immediately.
265 onQuitApplicationGranted() {
266 this._shuttingDown = true;
267 this.stopAllHangs("quit-application-granted");
268 this.updateWindows();
271 onWindowClosed(win) {
272 let maybeStopHang = report => {
273 let hungBrowserWindow = null;
275 hungBrowserWindow = report.scriptBrowser.ownerGlobal;
277 // Ignore failures to get the script browser - we'll be
278 // conservative, and assume that if we cannot access the
279 // window that belongs to this report that we should stop
282 if (!hungBrowserWindow || hungBrowserWindow == win) {
283 this.stopHang(report, "window-closed");
289 // If there are any script hangs for browsers that are in this window
290 // that is closing, we can stop them now.
291 for (let [report] of this._activeReports) {
292 if (maybeStopHang(report)) {
293 this._activeReports.delete(report);
297 for (let [pausedReport] of this._pausedReports) {
298 if (maybeStopHang(pausedReport)) {
299 this.removePausedReport(pausedReport);
303 this.updateWindows();
306 stopAllHangs(endReason) {
307 for (let [report] of this._activeReports) {
308 this.stopHang(report, endReason);
311 this._activeReports = new Map();
313 for (let [pausedReport] of this._pausedReports) {
314 this.stopHang(pausedReport, endReason);
315 this.removePausedReport(pausedReport);
320 * Find a active hang report for the given <browser> element.
322 findActiveReport(browser) {
323 let frameLoader = browser.frameLoader;
324 for (let report of this._activeReports.keys()) {
325 if (report.isReportForBrowserOrChildren(frameLoader)) {
333 * Find a paused hang report for the given <browser> element.
335 findPausedReport(browser) {
336 let frameLoader = browser.frameLoader;
337 for (let [report] of this._pausedReports) {
338 if (report.isReportForBrowserOrChildren(frameLoader)) {
346 * Tell telemetry about the report.
348 _recordTelemetryForReport(report, endReason, backupInfo) {
350 this._activeReports.get(report) ||
351 this._pausedReports.get(report) ||
358 if (report.addonId) {
359 uri_type = "extension";
360 } else if (report.scriptFileName?.startsWith("debugger")) {
361 uri_type = "devtools";
364 let url = new URL(report.scriptFileName);
365 if (url.protocol == "chrome:" || url.protocol == "resource:") {
366 uri_type = "browser";
368 uri_type = "content";
372 uri_type = "unknown";
376 if (info.notificationTime) {
377 uptime = Cu.now() - info.notificationTime;
379 uptime = "" + uptime;
380 // We combine the duration of the hang in the content process with the
381 // time since we were last told about the hang in the parent. This is
382 // not the same as the time we showed a notification, as we only do that
383 // for the currently selected browser. It's as messy as it is because
384 // there is no cross-process monotonically increasing timestamp we can
387 report.hangDuration + Cu.now() - info.lastReportFromChild;
388 Services.telemetry.recordEvent(
389 "slow_script_warning",
394 end_reason: endReason,
395 hang_duration: "" + hangDuration,
396 n_tab_deselect: "" + info.deselectCount,
399 wait_count: "" + info.waitCount,
408 * Remove an active hang report from the active list and cancel the timer
409 * associated with it.
411 removeActiveReport(report) {
412 this._activeReports.delete(report);
413 this.updateWindows();
417 * Remove a paused hang report from the paused list and cancel the timer
418 * associated with it.
420 removePausedReport(report) {
421 let info = this._pausedReports.get(report);
422 info?.timer?.cancel();
423 this._pausedReports.delete(report);
427 * Iterate over all XUL windows and ensure that the proper hang
428 * reports are shown for each one. Also install event handlers in
429 * each window to watch for events that would cause a different hang
430 * report to be displayed.
433 let e = Services.wm.getEnumerator("navigator:browser");
435 // If it turns out we have no windows (this can happen on macOS),
436 // we have no opportunity to ask the user whether or not they want
437 // to stop the hang or wait, so we'll opt for stopping the hang.
438 if (!e.hasMoreElements()) {
439 this.stopAllHangs("no-windows-left");
444 this.updateWindow(win);
446 // Only listen for these events if there are active hang reports.
447 if (this._activeReports.size) {
448 this.trackWindow(win);
450 this.untrackWindow(win);
456 * If there is a hang report for the current tab in |win|, display it.
459 let report = this.findActiveReport(win.gBrowser.selectedBrowser);
462 let info = this._activeReports.get(report);
463 if (info && !info.notificationTime) {
464 info.notificationTime = Cu.now();
466 this.showNotification(win, report);
468 this.hideNotification(win);
473 * Show the notification for a hang.
475 showNotification(win, report) {
476 let bundle = win.gNavigatorBundle;
480 label: bundle.getString("processHang.button_stop2.label"),
481 accessKey: bundle.getString("processHang.button_stop2.accessKey"),
483 ProcessHangMonitor.stopIt(win);
489 let doc = win.document;
490 let brandShortName = doc
491 .getElementById("bundle_brand")
492 .getString("brandShortName");
494 if (report.addonId) {
495 notificationTag = report.addonId;
496 let aps = Cc["@mozilla.org/addons/policy-service;1"].getService(
497 Ci.nsIAddonPolicyService
500 let addonName = aps.getExtensionName(report.addonId);
502 message = bundle.getFormattedString("processHang.add-on.label2", [
508 label: bundle.getString("processHang.add-on.learn-more.text"),
509 link: "https://support.mozilla.org/kb/warning-unresponsive-script#w_other-causes",
512 let scriptBrowser = report.scriptBrowser;
513 if (scriptBrowser == win.gBrowser?.selectedBrowser) {
514 notificationTag = "selected-tab";
515 message = bundle.getFormattedString("processHang.selected_tab.label", [
520 scriptBrowser?.ownerGlobal.gBrowser?.getTabForBrowser(scriptBrowser);
522 notificationTag = "nonspecific_tab";
523 message = bundle.getFormattedString(
524 "processHang.nonspecific_tab.label",
528 notificationTag = scriptBrowser.browserId.toString();
529 let title = tab.getAttribute("label");
530 title = elideMiddleOfString(title, 60);
531 message = bundle.getFormattedString(
532 "processHang.specific_tab.label",
533 [title, brandShortName]
540 win.gNotificationBox.getNotificationWithValue("process-hang");
541 if (notificationTag == notification?.getAttribute("notification-tag")) {
546 notification.label = message;
547 notification.setAttribute("notification-tag", notificationTag);
551 // Show the "debug script" button unconditionally if we are in Developer edition,
552 // or, if DevTools are opened on the slow tab.
554 AppConstants.MOZ_DEV_EDITION ||
555 report.scriptBrowser.browsingContext.watchedByDevTools
558 label: bundle.getString("processHang.button_debug.label"),
559 accessKey: bundle.getString("processHang.button_debug.accessKey"),
561 ProcessHangMonitor.debugScript(win);
571 image: "chrome://browser/content/aboutRobots-icon.png",
572 priority: win.gNotificationBox.PRIORITY_INFO_HIGH,
573 eventCallback: event => {
574 if (event == "dismissed") {
575 ProcessHangMonitor.waitLonger(win);
581 .setAttribute("notification-tag", notificationTag);
585 * Ensure that no hang notifications are visible in |win|.
587 hideNotification(win) {
589 win.gNotificationBox.getNotificationWithValue("process-hang");
591 win.gNotificationBox.removeNotification(notification);
596 * Install event handlers on |win| to watch for events that would
597 * cause a different hang report to be displayed.
600 win.gBrowser.tabContainer.addEventListener("TabSelect", this, true);
601 win.gBrowser.tabContainer.addEventListener(
602 "TabRemotenessChange",
609 win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true);
610 win.gBrowser.tabContainer.removeEventListener(
611 "TabRemotenessChange",
618 let win = event.target.ownerGlobal;
620 // If a new tab is selected or if a tab changes remoteness, then
621 // we may need to show or hide a hang notification.
622 if (event.type == "TabSelect" || event.type == "TabRemotenessChange") {
623 if (event.type == "TabSelect" && event.detail.previousTab) {
624 // If we've got a notification, check the previous tab's report and
625 // indicate the user switched tabs while the notification was up.
627 this.findActiveReport(event.detail.previousTab.linkedBrowser) ||
628 this.findPausedReport(event.detail.previousTab.linkedBrowser);
630 let info = this._activeReports.get(r) || this._pausedReports.get(r);
631 info.deselectCount++;
634 this.updateWindow(win);
639 * Handle a potentially new hang report. If it hasn't been seen
640 * before, show a notification for it in all open XUL windows.
644 if (this._shuttingDown) {
645 this.stopHang(report, "shutdown-in-progress", {
646 lastReportFromChild: now,
653 // If this hang was already reported reset the timer for it.
654 if (this._activeReports.has(report)) {
655 this._activeReports.get(report).lastReportFromChild = now;
656 // if this report is in active but doesn't have a notification associated
657 // with it, display a notification.
658 this.updateWindows();
662 // If this hang was already reported and paused by the user ignore it.
663 if (this._pausedReports.has(report)) {
664 this._pausedReports.get(report).lastReportFromChild = now;
668 // On e10s this counts slow-script notice only once.
669 // This code is not reached on non-e10s.
670 Services.telemetry.getHistogramById("SLOW_SCRIPT_NOTICE_COUNT").add();
672 this._activeReports.set(report, {
674 lastReportFromChild: now,
677 this.updateWindows();
681 this._recordTelemetryForReport(report, "cleared");
683 this.removeActiveReport(report);
684 this.removePausedReport(report);
685 report.userCanceled();