Backed out 7 changesets (bug 1845150) for causing dt failures on browser_screenshot_b...
[gecko.git] / browser / modules / ProcessHangMonitor.sys.mjs
blob4acf1ddce580b8f9306f9a961436fde1f81814ef
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";
8 /**
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
11  * clusters.
12  */
13 function elideMiddleOfString(str, threshold) {
14   const searchDistance = 5;
15   const stubLength = threshold / 2 - searchDistance;
16   if (str.length <= threshold || stubLength < searchDistance) {
17     return str;
18   }
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])) {
24         return position + i;
25       }
27       if (!unsplittableCharacter(str[position - i])) {
28         return position - i;
29       }
30     }
31     return position;
32   }
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);
38   }
39   return str;
42 /**
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.
46  */
48 export var ProcessHangMonitor = {
49   /**
50    * This timeout is the wait period applied after a user selects "Wait" in
51    * an existing notification.
52    */
53   get WAIT_EXPIRATION_TIME() {
54     try {
55       return Services.prefs.getIntPref("browser.hangNotification.waitPeriod");
56     } catch (ex) {
57       return 10000;
58     }
59   },
61   /**
62    * Should only be set to true once the quit-application-granted notification
63    * has been fired.
64    */
65   _shuttingDown: false,
67   /**
68    * Collection of hang reports that haven't expired or been dismissed
69    * by the user. These are nsIHangReports. They are mapped to objects
70    * containing:
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
74    *   child.
75    */
76   _activeReports: new Map(),
78   /**
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
82    * expires.
83    */
84   _pausedReports: new Map(),
86   /**
87    * Initialize hang reporting. Called once in the parent process.
88    */
89   init() {
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);
96   },
98   /**
99    * Terminate JavaScript associated with the hang being reported for
100    * the selected browser in |win|.
101    */
102   terminateScript(win) {
103     this.handleUserInput(win, report => report.terminateScript());
104   },
106   /**
107    * Start devtools debugger for JavaScript associated with the hang
108    * being reported for the selected browser in |win|.
109    */
110   debugScript(win) {
111     this.handleUserInput(win, report => {
112       function callback() {
113         report.endStartingDebugger();
114       }
116       this._recordTelemetryForReport(report, "debugging");
117       report.beginStartingDebugger();
119       let svc = Cc["@mozilla.org/dom/slow-script-debug;1"].getService(
120         Ci.nsISlowScriptDebug
121       );
122       let handler = svc.remoteActivationHandler;
123       handler.handleSlowScriptDebug(report.scriptBrowser, callback);
124     });
125   },
127   /**
128    * Dismiss the browser notification and invoke an appropriate action based on
129    * the hang type.
130    */
131   stopIt(win) {
132     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
133     if (!report) {
134       return;
135     }
137     this._recordTelemetryForReport(report, "user-aborted");
138     this.terminateScript(win);
139   },
141   /**
142    * Terminate the script causing this report. This is done without
143    * updating any report notifications.
144    */
145   stopHang(report, endReason, backupInfo) {
146     this._recordTelemetryForReport(report, endReason, backupInfo);
147     report.terminateScript();
148   },
150   /**
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.
153    */
154   waitLonger(win) {
155     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
156     if (!report) {
157       return;
158     }
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(
174       () => {
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();
183             break;
184           }
185         }
186       },
187       this.WAIT_EXPIRATION_TIME,
188       timer.TYPE_ONE_SHOT
189     );
191     reportInfo.timer = timer;
192     this._pausedReports.set(report, reportInfo);
194     // remove the browser notification associated with this hang
195     this.updateWindows();
196   },
198   /**
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
201    * about it.
202    */
203   handleUserInput(win, func) {
204     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
205     if (!report) {
206       return null;
207     }
208     this.removeActiveReport(report);
210     return func(report);
211   },
213   observe(subject, topic, data) {
214     switch (topic) {
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);
221         break;
222       }
224       case "quit-application-granted": {
225         this.onQuitApplicationGranted();
226         break;
227       }
229       case "process-hang-report": {
230         this.reportHang(subject.QueryInterface(Ci.nsIHangReport));
231         break;
232       }
234       case "clear-hang-report": {
235         this.clearHang(subject.QueryInterface(Ci.nsIHangReport));
236         break;
237       }
239       case "domwindowopened": {
240         // Install event listeners on the new window in case one of
241         // its tabs is already hung.
242         let win = subject;
243         let listener = ev => {
244           win.removeEventListener("load", listener, true);
245           this.updateWindows();
246         };
247         win.addEventListener("load", listener, true);
248         break;
249       }
251       case "domwindowclosed": {
252         let win = subject;
253         this.onWindowClosed(win);
254         break;
255       }
256     }
257   },
259   /**
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.
264    */
265   onQuitApplicationGranted() {
266     this._shuttingDown = true;
267     this.stopAllHangs("quit-application-granted");
268     this.updateWindows();
269   },
271   onWindowClosed(win) {
272     let maybeStopHang = report => {
273       let hungBrowserWindow = null;
274       try {
275         hungBrowserWindow = report.scriptBrowser.ownerGlobal;
276       } catch (e) {
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
280         // the hang.
281       }
282       if (!hungBrowserWindow || hungBrowserWindow == win) {
283         this.stopHang(report, "window-closed");
284         return true;
285       }
286       return false;
287     };
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);
294       }
295     }
297     for (let [pausedReport] of this._pausedReports) {
298       if (maybeStopHang(pausedReport)) {
299         this.removePausedReport(pausedReport);
300       }
301     }
303     this.updateWindows();
304   },
306   stopAllHangs(endReason) {
307     for (let [report] of this._activeReports) {
308       this.stopHang(report, endReason);
309     }
311     this._activeReports = new Map();
313     for (let [pausedReport] of this._pausedReports) {
314       this.stopHang(pausedReport, endReason);
315       this.removePausedReport(pausedReport);
316     }
317   },
319   /**
320    * Find a active hang report for the given <browser> element.
321    */
322   findActiveReport(browser) {
323     let frameLoader = browser.frameLoader;
324     for (let report of this._activeReports.keys()) {
325       if (report.isReportForBrowserOrChildren(frameLoader)) {
326         return report;
327       }
328     }
329     return null;
330   },
332   /**
333    * Find a paused hang report for the given <browser> element.
334    */
335   findPausedReport(browser) {
336     let frameLoader = browser.frameLoader;
337     for (let [report] of this._pausedReports) {
338       if (report.isReportForBrowserOrChildren(frameLoader)) {
339         return report;
340       }
341     }
342     return null;
343   },
345   /**
346    * Tell telemetry about the report.
347    */
348   _recordTelemetryForReport(report, endReason, backupInfo) {
349     let info =
350       this._activeReports.get(report) ||
351       this._pausedReports.get(report) ||
352       backupInfo;
353     if (!info) {
354       return;
355     }
356     try {
357       let uri_type;
358       if (report.addonId) {
359         uri_type = "extension";
360       } else if (report.scriptFileName?.startsWith("debugger")) {
361         uri_type = "devtools";
362       } else {
363         try {
364           let url = new URL(report.scriptFileName);
365           if (url.protocol == "chrome:" || url.protocol == "resource:") {
366             uri_type = "browser";
367           } else {
368             uri_type = "content";
369           }
370         } catch (ex) {
371           console.error(ex);
372           uri_type = "unknown";
373         }
374       }
375       let uptime = 0;
376       if (info.notificationTime) {
377         uptime = Cu.now() - info.notificationTime;
378       }
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
385       // use. :-(
386       let hangDuration =
387         report.hangDuration + Cu.now() - info.lastReportFromChild;
388       Services.telemetry.recordEvent(
389         "slow_script_warning",
390         "shown",
391         "content",
392         null,
393         {
394           end_reason: endReason,
395           hang_duration: "" + hangDuration,
396           n_tab_deselect: "" + info.deselectCount,
397           uri_type,
398           uptime,
399           wait_count: "" + info.waitCount,
400         }
401       );
402     } catch (ex) {
403       console.error(ex);
404     }
405   },
407   /**
408    * Remove an active hang report from the active list and cancel the timer
409    * associated with it.
410    */
411   removeActiveReport(report) {
412     this._activeReports.delete(report);
413     this.updateWindows();
414   },
416   /**
417    * Remove a paused hang report from the paused list and cancel the timer
418    * associated with it.
419    */
420   removePausedReport(report) {
421     let info = this._pausedReports.get(report);
422     info?.timer?.cancel();
423     this._pausedReports.delete(report);
424   },
426   /**
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.
431    */
432   updateWindows() {
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");
440       return;
441     }
443     for (let win of e) {
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);
449       } else {
450         this.untrackWindow(win);
451       }
452     }
453   },
455   /**
456    * If there is a hang report for the current tab in |win|, display it.
457    */
458   updateWindow(win) {
459     let report = this.findActiveReport(win.gBrowser.selectedBrowser);
461     if (report) {
462       let info = this._activeReports.get(report);
463       if (info && !info.notificationTime) {
464         info.notificationTime = Cu.now();
465       }
466       this.showNotification(win, report);
467     } else {
468       this.hideNotification(win);
469     }
470   },
472   /**
473    * Show the notification for a hang.
474    */
475   showNotification(win, report) {
476     let bundle = win.gNavigatorBundle;
478     let buttons = [
479       {
480         label: bundle.getString("processHang.button_stop2.label"),
481         accessKey: bundle.getString("processHang.button_stop2.accessKey"),
482         callback() {
483           ProcessHangMonitor.stopIt(win);
484         },
485       },
486     ];
488     let message;
489     let doc = win.document;
490     let brandShortName = doc
491       .getElementById("bundle_brand")
492       .getString("brandShortName");
493     let notificationTag;
494     if (report.addonId) {
495       notificationTag = report.addonId;
496       let aps = Cc["@mozilla.org/addons/policy-service;1"].getService(
497         Ci.nsIAddonPolicyService
498       );
500       let addonName = aps.getExtensionName(report.addonId);
502       message = bundle.getFormattedString("processHang.add-on.label2", [
503         addonName,
504         brandShortName,
505       ]);
507       buttons.unshift({
508         label: bundle.getString("processHang.add-on.learn-more.text"),
509         link: "https://support.mozilla.org/kb/warning-unresponsive-script#w_other-causes",
510       });
511     } else {
512       let scriptBrowser = report.scriptBrowser;
513       if (scriptBrowser == win.gBrowser?.selectedBrowser) {
514         notificationTag = "selected-tab";
515         message = bundle.getFormattedString("processHang.selected_tab.label", [
516           brandShortName,
517         ]);
518       } else {
519         let tab =
520           scriptBrowser?.ownerGlobal.gBrowser?.getTabForBrowser(scriptBrowser);
521         if (!tab) {
522           notificationTag = "nonspecific_tab";
523           message = bundle.getFormattedString(
524             "processHang.nonspecific_tab.label",
525             [brandShortName]
526           );
527         } else {
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]
534           );
535         }
536       }
537     }
539     let notification =
540       win.gNotificationBox.getNotificationWithValue("process-hang");
541     if (notificationTag == notification?.getAttribute("notification-tag")) {
542       return;
543     }
545     if (notification) {
546       notification.label = message;
547       notification.setAttribute("notification-tag", notificationTag);
548       return;
549     }
551     // Show the "debug script" button unconditionally if we are in Developer edition,
552     // or, if DevTools are opened on the slow tab.
553     if (
554       AppConstants.MOZ_DEV_EDITION ||
555       report.scriptBrowser.browsingContext.watchedByDevTools
556     ) {
557       buttons.push({
558         label: bundle.getString("processHang.button_debug.label"),
559         accessKey: bundle.getString("processHang.button_debug.accessKey"),
560         callback() {
561           ProcessHangMonitor.debugScript(win);
562         },
563       });
564     }
566     win.gNotificationBox
567       .appendNotification(
568         "process-hang",
569         {
570           label: message,
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);
576             }
577           },
578         },
579         buttons
580       )
581       .setAttribute("notification-tag", notificationTag);
582   },
584   /**
585    * Ensure that no hang notifications are visible in |win|.
586    */
587   hideNotification(win) {
588     let notification =
589       win.gNotificationBox.getNotificationWithValue("process-hang");
590     if (notification) {
591       win.gNotificationBox.removeNotification(notification);
592     }
593   },
595   /**
596    * Install event handlers on |win| to watch for events that would
597    * cause a different hang report to be displayed.
598    */
599   trackWindow(win) {
600     win.gBrowser.tabContainer.addEventListener("TabSelect", this, true);
601     win.gBrowser.tabContainer.addEventListener(
602       "TabRemotenessChange",
603       this,
604       true
605     );
606   },
608   untrackWindow(win) {
609     win.gBrowser.tabContainer.removeEventListener("TabSelect", this, true);
610     win.gBrowser.tabContainer.removeEventListener(
611       "TabRemotenessChange",
612       this,
613       true
614     );
615   },
617   handleEvent(event) {
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.
626         let r =
627           this.findActiveReport(event.detail.previousTab.linkedBrowser) ||
628           this.findPausedReport(event.detail.previousTab.linkedBrowser);
629         if (r) {
630           let info = this._activeReports.get(r) || this._pausedReports.get(r);
631           info.deselectCount++;
632         }
633       }
634       this.updateWindow(win);
635     }
636   },
638   /**
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.
641    */
642   reportHang(report) {
643     let now = Cu.now();
644     if (this._shuttingDown) {
645       this.stopHang(report, "shutdown-in-progress", {
646         lastReportFromChild: now,
647         waitCount: 0,
648         deselectCount: 0,
649       });
650       return;
651     }
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();
659       return;
660     }
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;
665       return;
666     }
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, {
673       deselectCount: 0,
674       lastReportFromChild: now,
675       waitCount: 0,
676     });
677     this.updateWindows();
678   },
680   clearHang(report) {
681     this._recordTelemetryForReport(report, "cleared");
683     this.removeActiveReport(report);
684     this.removePausedReport(report);
685     report.userCanceled();
686   },