|
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
|
3 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
4 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
6 |
|
7 #include "amIAddonManager.h" |
|
8 #include "nsWindowMemoryReporter.h" |
|
9 #include "nsGlobalWindow.h" |
|
10 #include "nsIDocument.h" |
|
11 #include "nsIDOMWindowCollection.h" |
|
12 #include "nsIEffectiveTLDService.h" |
|
13 #include "mozilla/ClearOnShutdown.h" |
|
14 #include "mozilla/Preferences.h" |
|
15 #include "mozilla/Services.h" |
|
16 #include "mozilla/StaticPtr.h" |
|
17 #include "nsNetCID.h" |
|
18 #include "nsPrintfCString.h" |
|
19 #include "XPCJSMemoryReporter.h" |
|
20 #include "js/MemoryMetrics.h" |
|
21 #include "nsServiceManagerUtils.h" |
|
22 |
|
23 using namespace mozilla; |
|
24 |
|
25 StaticRefPtr<nsWindowMemoryReporter> sWindowReporter; |
|
26 |
|
27 /** |
|
28 * Don't trigger a ghost window check when a DOM window is detached if we've |
|
29 * run it this recently. |
|
30 */ |
|
31 const int32_t kTimeBetweenChecks = 45; /* seconds */ |
|
32 |
|
33 nsWindowMemoryReporter::nsWindowMemoryReporter() |
|
34 : mLastCheckForGhostWindows(TimeStamp::NowLoRes()), |
|
35 mCycleCollectorIsRunning(false), |
|
36 mCheckTimerWaitingForCCEnd(false) |
|
37 { |
|
38 } |
|
39 |
|
40 nsWindowMemoryReporter::~nsWindowMemoryReporter() |
|
41 { |
|
42 KillCheckTimer(); |
|
43 } |
|
44 |
|
45 NS_IMPL_ISUPPORTS(nsWindowMemoryReporter, nsIMemoryReporter, nsIObserver, |
|
46 nsISupportsWeakReference) |
|
47 |
|
48 static nsresult |
|
49 AddNonJSSizeOfWindowAndItsDescendents(nsGlobalWindow* aWindow, |
|
50 nsTabSizes* aSizes) |
|
51 { |
|
52 // Measure the window. |
|
53 nsWindowSizes windowSizes(moz_malloc_size_of); |
|
54 aWindow->AddSizeOfIncludingThis(&windowSizes); |
|
55 windowSizes.addToTabSizes(aSizes); |
|
56 |
|
57 // Measure the inner window, if there is one. |
|
58 nsWindowSizes innerWindowSizes(moz_malloc_size_of); |
|
59 nsGlobalWindow* inner = aWindow->GetCurrentInnerWindowInternal(); |
|
60 if (inner) { |
|
61 inner->AddSizeOfIncludingThis(&innerWindowSizes); |
|
62 innerWindowSizes.addToTabSizes(aSizes); |
|
63 } |
|
64 |
|
65 nsCOMPtr<nsIDOMWindowCollection> frames; |
|
66 nsresult rv = aWindow->GetFrames(getter_AddRefs(frames)); |
|
67 NS_ENSURE_SUCCESS(rv, rv); |
|
68 |
|
69 uint32_t length; |
|
70 rv = frames->GetLength(&length); |
|
71 NS_ENSURE_SUCCESS(rv, rv); |
|
72 |
|
73 // Measure this window's descendents. |
|
74 for (uint32_t i = 0; i < length; i++) { |
|
75 nsCOMPtr<nsIDOMWindow> child; |
|
76 rv = frames->Item(i, getter_AddRefs(child)); |
|
77 NS_ENSURE_SUCCESS(rv, rv); |
|
78 NS_ENSURE_STATE(child); |
|
79 |
|
80 nsGlobalWindow* childWin = |
|
81 static_cast<nsGlobalWindow*>(static_cast<nsIDOMWindow *>(child.get())); |
|
82 |
|
83 rv = AddNonJSSizeOfWindowAndItsDescendents(childWin, aSizes); |
|
84 NS_ENSURE_SUCCESS(rv, rv); |
|
85 } |
|
86 return NS_OK; |
|
87 } |
|
88 |
|
89 static nsresult |
|
90 NonJSSizeOfTab(nsPIDOMWindow* aWindow, size_t* aDomSize, size_t* aStyleSize, size_t* aOtherSize) |
|
91 { |
|
92 nsGlobalWindow* window = static_cast<nsGlobalWindow*>(aWindow); |
|
93 |
|
94 nsTabSizes sizes; |
|
95 nsresult rv = AddNonJSSizeOfWindowAndItsDescendents(window, &sizes); |
|
96 NS_ENSURE_SUCCESS(rv, rv); |
|
97 |
|
98 *aDomSize = sizes.mDom; |
|
99 *aStyleSize = sizes.mStyle; |
|
100 *aOtherSize = sizes.mOther; |
|
101 return NS_OK; |
|
102 } |
|
103 |
|
104 /* static */ void |
|
105 nsWindowMemoryReporter::Init() |
|
106 { |
|
107 MOZ_ASSERT(!sWindowReporter); |
|
108 sWindowReporter = new nsWindowMemoryReporter(); |
|
109 ClearOnShutdown(&sWindowReporter); |
|
110 RegisterStrongMemoryReporter(sWindowReporter); |
|
111 RegisterNonJSSizeOfTab(NonJSSizeOfTab); |
|
112 |
|
113 nsCOMPtr<nsIObserverService> os = services::GetObserverService(); |
|
114 if (os) { |
|
115 // DOM_WINDOW_DESTROYED_TOPIC announces what we call window "detachment", |
|
116 // when a window's docshell is set to nullptr. |
|
117 os->AddObserver(sWindowReporter, DOM_WINDOW_DESTROYED_TOPIC, |
|
118 /* weakRef = */ true); |
|
119 os->AddObserver(sWindowReporter, "after-minimize-memory-usage", |
|
120 /* weakRef = */ true); |
|
121 os->AddObserver(sWindowReporter, "cycle-collector-begin", |
|
122 /* weakRef = */ true); |
|
123 os->AddObserver(sWindowReporter, "cycle-collector-end", |
|
124 /* weakRef = */ true); |
|
125 } |
|
126 |
|
127 RegisterStrongMemoryReporter(new GhostWindowsReporter()); |
|
128 RegisterGhostWindowsDistinguishedAmount(GhostWindowsReporter::DistinguishedAmount); |
|
129 } |
|
130 |
|
131 static already_AddRefed<nsIURI> |
|
132 GetWindowURI(nsIDOMWindow *aWindow) |
|
133 { |
|
134 nsCOMPtr<nsPIDOMWindow> pWindow = do_QueryInterface(aWindow); |
|
135 NS_ENSURE_TRUE(pWindow, nullptr); |
|
136 |
|
137 nsCOMPtr<nsIDocument> doc = pWindow->GetExtantDoc(); |
|
138 nsCOMPtr<nsIURI> uri; |
|
139 |
|
140 if (doc) { |
|
141 uri = doc->GetDocumentURI(); |
|
142 } |
|
143 |
|
144 if (!uri) { |
|
145 nsCOMPtr<nsIScriptObjectPrincipal> scriptObjPrincipal = |
|
146 do_QueryInterface(aWindow); |
|
147 NS_ENSURE_TRUE(scriptObjPrincipal, nullptr); |
|
148 |
|
149 // GetPrincipal() will print a warning if the window does not have an outer |
|
150 // window, so check here for an outer window first. This code is |
|
151 // functionally correct if we leave out the GetOuterWindow() check, but we |
|
152 // end up printing a lot of warnings during debug mochitests. |
|
153 if (pWindow->GetOuterWindow()) { |
|
154 nsIPrincipal* principal = scriptObjPrincipal->GetPrincipal(); |
|
155 if (principal) { |
|
156 principal->GetURI(getter_AddRefs(uri)); |
|
157 } |
|
158 } |
|
159 } |
|
160 |
|
161 return uri.forget(); |
|
162 } |
|
163 |
|
164 static void |
|
165 AppendWindowURI(nsGlobalWindow *aWindow, nsACString& aStr) |
|
166 { |
|
167 nsCOMPtr<nsIURI> uri = GetWindowURI(aWindow); |
|
168 |
|
169 if (uri) { |
|
170 nsCString spec; |
|
171 uri->GetSpec(spec); |
|
172 |
|
173 // A hack: replace forward slashes with '\\' so they aren't |
|
174 // treated as path separators. Users of the reporters |
|
175 // (such as about:memory) have to undo this change. |
|
176 spec.ReplaceChar('/', '\\'); |
|
177 |
|
178 aStr += spec; |
|
179 } else { |
|
180 // If we're unable to find a URI, we're dealing with a chrome window with |
|
181 // no document in it (or somesuch), so we call this a "system window". |
|
182 aStr += NS_LITERAL_CSTRING("[system]"); |
|
183 } |
|
184 } |
|
185 |
|
186 MOZ_DEFINE_MALLOC_SIZE_OF(WindowsMallocSizeOf) |
|
187 |
|
188 // The key is the window ID. |
|
189 typedef nsDataHashtable<nsUint64HashKey, nsCString> WindowPaths; |
|
190 |
|
191 static nsresult |
|
192 ReportAmount(const nsCString& aBasePath, const char* aPathTail, |
|
193 size_t aAmount, const nsCString& aDescription, |
|
194 uint32_t aKind, uint32_t aUnits, |
|
195 nsIMemoryReporterCallback* aCb, |
|
196 nsISupports* aClosure) |
|
197 { |
|
198 if (aAmount == 0) { |
|
199 return NS_OK; |
|
200 } |
|
201 |
|
202 nsAutoCString path(aBasePath); |
|
203 path += aPathTail; |
|
204 |
|
205 return aCb->Callback(EmptyCString(), path, aKind, aUnits, |
|
206 aAmount, aDescription, aClosure); |
|
207 } |
|
208 |
|
209 static nsresult |
|
210 ReportSize(const nsCString& aBasePath, const char* aPathTail, |
|
211 size_t aAmount, const nsCString& aDescription, |
|
212 nsIMemoryReporterCallback* aCb, |
|
213 nsISupports* aClosure) |
|
214 { |
|
215 return ReportAmount(aBasePath, aPathTail, aAmount, aDescription, |
|
216 nsIMemoryReporter::KIND_HEAP, |
|
217 nsIMemoryReporter::UNITS_BYTES, aCb, aClosure); |
|
218 } |
|
219 |
|
220 static nsresult |
|
221 ReportCount(const nsCString& aBasePath, const char* aPathTail, |
|
222 size_t aAmount, const nsCString& aDescription, |
|
223 nsIMemoryReporterCallback* aCb, |
|
224 nsISupports* aClosure) |
|
225 { |
|
226 return ReportAmount(aBasePath, aPathTail, aAmount, aDescription, |
|
227 nsIMemoryReporter::KIND_OTHER, |
|
228 nsIMemoryReporter::UNITS_COUNT, aCb, aClosure); |
|
229 } |
|
230 |
|
231 static nsresult |
|
232 CollectWindowReports(nsGlobalWindow *aWindow, |
|
233 amIAddonManager *addonManager, |
|
234 nsWindowSizes *aWindowTotalSizes, |
|
235 nsTHashtable<nsUint64HashKey> *aGhostWindowIDs, |
|
236 WindowPaths *aWindowPaths, |
|
237 WindowPaths *aTopWindowPaths, |
|
238 nsIMemoryReporterCallback *aCb, |
|
239 nsISupports *aClosure) |
|
240 { |
|
241 nsAutoCString windowPath("explicit/"); |
|
242 |
|
243 // Avoid calling aWindow->GetTop() if there's no outer window. It will work |
|
244 // just fine, but will spew a lot of warnings. |
|
245 nsGlobalWindow *top = nullptr; |
|
246 nsCOMPtr<nsIURI> location; |
|
247 if (aWindow->GetOuterWindow()) { |
|
248 // Our window should have a null top iff it has a null docshell. |
|
249 MOZ_ASSERT(!!aWindow->GetTop() == !!aWindow->GetDocShell()); |
|
250 top = aWindow->GetTop(); |
|
251 if (top) { |
|
252 location = GetWindowURI(top); |
|
253 } |
|
254 } |
|
255 if (!location) { |
|
256 location = GetWindowURI(aWindow); |
|
257 } |
|
258 |
|
259 if (addonManager && location) { |
|
260 bool ok; |
|
261 nsAutoCString id; |
|
262 if (NS_SUCCEEDED(addonManager->MapURIToAddonID(location, id, &ok)) && ok) { |
|
263 windowPath += NS_LITERAL_CSTRING("add-ons/") + id + |
|
264 NS_LITERAL_CSTRING("/"); |
|
265 } |
|
266 } |
|
267 |
|
268 windowPath += NS_LITERAL_CSTRING("window-objects/"); |
|
269 |
|
270 if (top) { |
|
271 windowPath += NS_LITERAL_CSTRING("top("); |
|
272 AppendWindowURI(top, windowPath); |
|
273 windowPath += NS_LITERAL_CSTRING(", id="); |
|
274 windowPath.AppendInt(top->WindowID()); |
|
275 windowPath += NS_LITERAL_CSTRING(")"); |
|
276 |
|
277 aTopWindowPaths->Put(aWindow->WindowID(), windowPath); |
|
278 |
|
279 windowPath += aWindow->IsFrozen() ? NS_LITERAL_CSTRING("/cached/") |
|
280 : NS_LITERAL_CSTRING("/active/"); |
|
281 } else { |
|
282 if (aGhostWindowIDs->Contains(aWindow->WindowID())) { |
|
283 windowPath += NS_LITERAL_CSTRING("top(none)/ghost/"); |
|
284 } else { |
|
285 windowPath += NS_LITERAL_CSTRING("top(none)/detached/"); |
|
286 } |
|
287 } |
|
288 |
|
289 windowPath += NS_LITERAL_CSTRING("window("); |
|
290 AppendWindowURI(aWindow, windowPath); |
|
291 windowPath += NS_LITERAL_CSTRING(")"); |
|
292 |
|
293 // Use |windowPath|, but replace "explicit/" with "event-counts/". |
|
294 nsCString censusWindowPath(windowPath); |
|
295 censusWindowPath.Replace(0, strlen("explicit"), "event-counts"); |
|
296 |
|
297 // Remember the path for later. |
|
298 aWindowPaths->Put(aWindow->WindowID(), windowPath); |
|
299 |
|
300 #define REPORT_SIZE(_pathTail, _amount, _desc) \ |
|
301 do { \ |
|
302 nsresult rv = ReportSize(windowPath, _pathTail, _amount, \ |
|
303 NS_LITERAL_CSTRING(_desc), aCb, aClosure); \ |
|
304 NS_ENSURE_SUCCESS(rv, rv); \ |
|
305 } while (0) |
|
306 |
|
307 #define REPORT_COUNT(_pathTail, _amount, _desc) \ |
|
308 do { \ |
|
309 nsresult rv = ReportCount(censusWindowPath, _pathTail, _amount, \ |
|
310 NS_LITERAL_CSTRING(_desc), aCb, aClosure); \ |
|
311 NS_ENSURE_SUCCESS(rv, rv); \ |
|
312 } while (0) |
|
313 |
|
314 nsWindowSizes windowSizes(WindowsMallocSizeOf); |
|
315 aWindow->AddSizeOfIncludingThis(&windowSizes); |
|
316 |
|
317 REPORT_SIZE("/dom/element-nodes", windowSizes.mDOMElementNodesSize, |
|
318 "Memory used by the element nodes in a window's DOM."); |
|
319 aWindowTotalSizes->mDOMElementNodesSize += windowSizes.mDOMElementNodesSize; |
|
320 |
|
321 REPORT_SIZE("/dom/text-nodes", windowSizes.mDOMTextNodesSize, |
|
322 "Memory used by the text nodes in a window's DOM."); |
|
323 aWindowTotalSizes->mDOMTextNodesSize += windowSizes.mDOMTextNodesSize; |
|
324 |
|
325 REPORT_SIZE("/dom/cdata-nodes", windowSizes.mDOMCDATANodesSize, |
|
326 "Memory used by the CDATA nodes in a window's DOM."); |
|
327 aWindowTotalSizes->mDOMCDATANodesSize += windowSizes.mDOMCDATANodesSize; |
|
328 |
|
329 REPORT_SIZE("/dom/comment-nodes", windowSizes.mDOMCommentNodesSize, |
|
330 "Memory used by the comment nodes in a window's DOM."); |
|
331 aWindowTotalSizes->mDOMCommentNodesSize += windowSizes.mDOMCommentNodesSize; |
|
332 |
|
333 REPORT_SIZE("/dom/event-targets", windowSizes.mDOMEventTargetsSize, |
|
334 "Memory used by the event targets table in a window's DOM, and " |
|
335 "the objects it points to, which include XHRs."); |
|
336 aWindowTotalSizes->mDOMEventTargetsSize += windowSizes.mDOMEventTargetsSize; |
|
337 |
|
338 REPORT_COUNT("/dom/event-targets", windowSizes.mDOMEventTargetsCount, |
|
339 "Number of non-node event targets in the event targets table " |
|
340 "in a window's DOM, such as XHRs."); |
|
341 aWindowTotalSizes->mDOMEventTargetsCount += |
|
342 windowSizes.mDOMEventTargetsCount; |
|
343 |
|
344 REPORT_COUNT("/dom/event-listeners", windowSizes.mDOMEventListenersCount, |
|
345 "Number of event listeners in a window, including event " |
|
346 "listeners on nodes and other event targets."); |
|
347 aWindowTotalSizes->mDOMEventListenersCount += |
|
348 windowSizes.mDOMEventListenersCount; |
|
349 |
|
350 REPORT_SIZE("/dom/other", windowSizes.mDOMOtherSize, |
|
351 "Memory used by a window's DOM that isn't measured by the " |
|
352 "other 'dom/' numbers."); |
|
353 aWindowTotalSizes->mDOMOtherSize += windowSizes.mDOMOtherSize; |
|
354 |
|
355 REPORT_SIZE("/property-tables", |
|
356 windowSizes.mPropertyTablesSize, |
|
357 "Memory used for the property tables within a window."); |
|
358 aWindowTotalSizes->mPropertyTablesSize += windowSizes.mPropertyTablesSize; |
|
359 |
|
360 REPORT_SIZE("/style-sheets", windowSizes.mStyleSheetsSize, |
|
361 "Memory used by style sheets within a window."); |
|
362 aWindowTotalSizes->mStyleSheetsSize += windowSizes.mStyleSheetsSize; |
|
363 |
|
364 REPORT_SIZE("/layout/pres-shell", windowSizes.mLayoutPresShellSize, |
|
365 "Memory used by layout's PresShell, along with any structures " |
|
366 "allocated in its arena and not measured elsewhere, " |
|
367 "within a window."); |
|
368 aWindowTotalSizes->mLayoutPresShellSize += windowSizes.mLayoutPresShellSize; |
|
369 |
|
370 REPORT_SIZE("/layout/line-boxes", windowSizes.mArenaStats.mLineBoxes, |
|
371 "Memory used by line boxes within a window."); |
|
372 aWindowTotalSizes->mArenaStats.mLineBoxes |
|
373 += windowSizes.mArenaStats.mLineBoxes; |
|
374 |
|
375 REPORT_SIZE("/layout/rule-nodes", windowSizes.mArenaStats.mRuleNodes, |
|
376 "Memory used by CSS rule nodes within a window."); |
|
377 aWindowTotalSizes->mArenaStats.mRuleNodes |
|
378 += windowSizes.mArenaStats.mRuleNodes; |
|
379 |
|
380 REPORT_SIZE("/layout/style-contexts", windowSizes.mArenaStats.mStyleContexts, |
|
381 "Memory used by style contexts within a window."); |
|
382 aWindowTotalSizes->mArenaStats.mStyleContexts |
|
383 += windowSizes.mArenaStats.mStyleContexts; |
|
384 |
|
385 REPORT_SIZE("/layout/style-sets", windowSizes.mLayoutStyleSetsSize, |
|
386 "Memory used by style sets within a window."); |
|
387 aWindowTotalSizes->mLayoutStyleSetsSize += windowSizes.mLayoutStyleSetsSize; |
|
388 |
|
389 REPORT_SIZE("/layout/text-runs", windowSizes.mLayoutTextRunsSize, |
|
390 "Memory used for text-runs (glyph layout) in the PresShell's " |
|
391 "frame tree, within a window."); |
|
392 aWindowTotalSizes->mLayoutTextRunsSize += windowSizes.mLayoutTextRunsSize; |
|
393 |
|
394 REPORT_SIZE("/layout/pres-contexts", windowSizes.mLayoutPresContextSize, |
|
395 "Memory used for the PresContext in the PresShell's frame " |
|
396 "within a window."); |
|
397 aWindowTotalSizes->mLayoutPresContextSize += |
|
398 windowSizes.mLayoutPresContextSize; |
|
399 |
|
400 // There are many different kinds of frames, but it is very likely |
|
401 // that only a few matter. Implement a cutoff so we don't bloat |
|
402 // about:memory with many uninteresting entries. |
|
403 const size_t FRAME_SUNDRIES_THRESHOLD = |
|
404 js::MemoryReportingSundriesThreshold(); |
|
405 |
|
406 size_t frameSundriesSize = 0; |
|
407 #define FRAME_ID(classname) \ |
|
408 { \ |
|
409 size_t frameSize \ |
|
410 = windowSizes.mArenaStats.FRAME_ID_STAT_FIELD(classname); \ |
|
411 if (frameSize < FRAME_SUNDRIES_THRESHOLD) { \ |
|
412 frameSundriesSize += frameSize; \ |
|
413 } else { \ |
|
414 REPORT_SIZE("/layout/frames/" # classname, frameSize, \ |
|
415 "Memory used by frames of " \ |
|
416 "type " #classname " within a window."); \ |
|
417 } \ |
|
418 aWindowTotalSizes->mArenaStats.FRAME_ID_STAT_FIELD(classname) \ |
|
419 += frameSize; \ |
|
420 } |
|
421 #include "nsFrameIdList.h" |
|
422 #undef FRAME_ID |
|
423 |
|
424 if (frameSundriesSize > 0) { |
|
425 REPORT_SIZE("/layout/frames/sundries", frameSundriesSize, |
|
426 "The sum of all memory used by frames which were too small " |
|
427 "to be shown individually."); |
|
428 } |
|
429 |
|
430 #undef REPORT_SIZE |
|
431 #undef REPORT_COUNT |
|
432 |
|
433 return NS_OK; |
|
434 } |
|
435 |
|
436 typedef nsTArray< nsRefPtr<nsGlobalWindow> > WindowArray; |
|
437 |
|
438 static |
|
439 PLDHashOperator |
|
440 GetWindows(const uint64_t& aId, nsGlobalWindow*& aWindow, void* aClosure) |
|
441 { |
|
442 ((WindowArray *)aClosure)->AppendElement(aWindow); |
|
443 |
|
444 return PL_DHASH_NEXT; |
|
445 } |
|
446 |
|
447 struct ReportGhostWindowsEnumeratorData |
|
448 { |
|
449 nsIMemoryReporterCallback* callback; |
|
450 nsISupports* closure; |
|
451 nsresult rv; |
|
452 }; |
|
453 |
|
454 static PLDHashOperator |
|
455 ReportGhostWindowsEnumerator(nsUint64HashKey* aIDHashKey, void* aClosure) |
|
456 { |
|
457 ReportGhostWindowsEnumeratorData *data = |
|
458 static_cast<ReportGhostWindowsEnumeratorData*>(aClosure); |
|
459 |
|
460 nsGlobalWindow::WindowByIdTable* windowsById = |
|
461 nsGlobalWindow::GetWindowsTable(); |
|
462 if (!windowsById) { |
|
463 NS_WARNING("Couldn't get window-by-id hashtable?"); |
|
464 return PL_DHASH_NEXT; |
|
465 } |
|
466 |
|
467 nsGlobalWindow* window = windowsById->Get(aIDHashKey->GetKey()); |
|
468 if (!window) { |
|
469 NS_WARNING("Could not look up window?"); |
|
470 return PL_DHASH_NEXT; |
|
471 } |
|
472 |
|
473 nsAutoCString path; |
|
474 path.AppendLiteral("ghost-windows/"); |
|
475 AppendWindowURI(window, path); |
|
476 |
|
477 nsresult rv = data->callback->Callback( |
|
478 /* process = */ EmptyCString(), |
|
479 path, |
|
480 nsIMemoryReporter::KIND_OTHER, |
|
481 nsIMemoryReporter::UNITS_COUNT, |
|
482 /* amount = */ 1, |
|
483 /* description = */ NS_LITERAL_CSTRING("A ghost window."), |
|
484 data->closure); |
|
485 |
|
486 if (NS_FAILED(rv) && NS_SUCCEEDED(data->rv)) { |
|
487 data->rv = rv; |
|
488 } |
|
489 |
|
490 return PL_DHASH_NEXT; |
|
491 } |
|
492 |
|
493 NS_IMETHODIMP |
|
494 nsWindowMemoryReporter::CollectReports(nsIMemoryReporterCallback* aCb, |
|
495 nsISupports* aClosure) |
|
496 { |
|
497 nsGlobalWindow::WindowByIdTable* windowsById = |
|
498 nsGlobalWindow::GetWindowsTable(); |
|
499 NS_ENSURE_TRUE(windowsById, NS_OK); |
|
500 |
|
501 // Hold on to every window in memory so that window objects can't be |
|
502 // destroyed while we're calling the memory reporter callback. |
|
503 WindowArray windows; |
|
504 windowsById->Enumerate(GetWindows, &windows); |
|
505 |
|
506 // Get the IDs of all the "ghost" windows, and call aCb->Callback() for each |
|
507 // one. |
|
508 nsTHashtable<nsUint64HashKey> ghostWindows; |
|
509 CheckForGhostWindows(&ghostWindows); |
|
510 ReportGhostWindowsEnumeratorData reportGhostWindowsEnumData = |
|
511 { aCb, aClosure, NS_OK }; |
|
512 ghostWindows.EnumerateEntries(ReportGhostWindowsEnumerator, |
|
513 &reportGhostWindowsEnumData); |
|
514 nsresult rv = reportGhostWindowsEnumData.rv; |
|
515 NS_ENSURE_SUCCESS(rv, rv); |
|
516 |
|
517 WindowPaths windowPaths; |
|
518 WindowPaths topWindowPaths; |
|
519 |
|
520 // Collect window memory usage. |
|
521 nsWindowSizes windowTotalSizes(nullptr); |
|
522 nsCOMPtr<amIAddonManager> addonManager; |
|
523 if (XRE_GetProcessType() == GeckoProcessType_Default) { |
|
524 // Only try to access the service from the main process. |
|
525 addonManager = do_GetService("@mozilla.org/addons/integration;1"); |
|
526 } |
|
527 for (uint32_t i = 0; i < windows.Length(); i++) { |
|
528 rv = CollectWindowReports(windows[i], addonManager, |
|
529 &windowTotalSizes, &ghostWindows, |
|
530 &windowPaths, &topWindowPaths, aCb, |
|
531 aClosure); |
|
532 NS_ENSURE_SUCCESS(rv, rv); |
|
533 } |
|
534 |
|
535 // Report JS memory usage. We do this from here because the JS memory |
|
536 // reporter needs to be passed |windowPaths|. |
|
537 rv = xpc::JSReporter::CollectReports(&windowPaths, &topWindowPaths, |
|
538 aCb, aClosure); |
|
539 NS_ENSURE_SUCCESS(rv, rv); |
|
540 |
|
541 #define REPORT(_path, _amount, _desc) \ |
|
542 do { \ |
|
543 nsresult rv; \ |
|
544 rv = aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ |
|
545 KIND_OTHER, UNITS_BYTES, _amount, \ |
|
546 NS_LITERAL_CSTRING(_desc), aClosure); \ |
|
547 NS_ENSURE_SUCCESS(rv, rv); \ |
|
548 } while (0) |
|
549 |
|
550 REPORT("window-objects/dom/element-nodes", windowTotalSizes.mDOMElementNodesSize, |
|
551 "This is the sum of all windows' 'dom/element-nodes' numbers."); |
|
552 |
|
553 REPORT("window-objects/dom/text-nodes", windowTotalSizes.mDOMTextNodesSize, |
|
554 "This is the sum of all windows' 'dom/text-nodes' numbers."); |
|
555 |
|
556 REPORT("window-objects/dom/cdata-nodes", windowTotalSizes.mDOMCDATANodesSize, |
|
557 "This is the sum of all windows' 'dom/cdata-nodes' numbers."); |
|
558 |
|
559 REPORT("window-objects/dom/comment-nodes", windowTotalSizes.mDOMCommentNodesSize, |
|
560 "This is the sum of all windows' 'dom/comment-nodes' numbers."); |
|
561 |
|
562 REPORT("window-objects/dom/event-targets", windowTotalSizes.mDOMEventTargetsSize, |
|
563 "This is the sum of all windows' 'dom/event-targets' numbers."); |
|
564 |
|
565 REPORT("window-objects/dom/other", windowTotalSizes.mDOMOtherSize, |
|
566 "This is the sum of all windows' 'dom/other' numbers."); |
|
567 |
|
568 REPORT("window-objects/property-tables", |
|
569 windowTotalSizes.mPropertyTablesSize, |
|
570 "This is the sum of all windows' 'property-tables' numbers."); |
|
571 |
|
572 REPORT("window-objects/style-sheets", windowTotalSizes.mStyleSheetsSize, |
|
573 "This is the sum of all windows' 'style-sheets' numbers."); |
|
574 |
|
575 REPORT("window-objects/layout/pres-shell", windowTotalSizes.mLayoutPresShellSize, |
|
576 "This is the sum of all windows' 'layout/arenas' numbers."); |
|
577 |
|
578 REPORT("window-objects/layout/line-boxes", |
|
579 windowTotalSizes.mArenaStats.mLineBoxes, |
|
580 "This is the sum of all windows' 'layout/line-boxes' numbers."); |
|
581 |
|
582 REPORT("window-objects/layout/rule-nodes", |
|
583 windowTotalSizes.mArenaStats.mRuleNodes, |
|
584 "This is the sum of all windows' 'layout/rule-nodes' numbers."); |
|
585 |
|
586 REPORT("window-objects/layout/style-contexts", |
|
587 windowTotalSizes.mArenaStats.mStyleContexts, |
|
588 "This is the sum of all windows' 'layout/style-contexts' numbers."); |
|
589 |
|
590 REPORT("window-objects/layout/style-sets", windowTotalSizes.mLayoutStyleSetsSize, |
|
591 "This is the sum of all windows' 'layout/style-sets' numbers."); |
|
592 |
|
593 REPORT("window-objects/layout/text-runs", windowTotalSizes.mLayoutTextRunsSize, |
|
594 "This is the sum of all windows' 'layout/text-runs' numbers."); |
|
595 |
|
596 REPORT("window-objects/layout/pres-contexts", windowTotalSizes.mLayoutPresContextSize, |
|
597 "This is the sum of all windows' 'layout/pres-contexts' numbers."); |
|
598 |
|
599 size_t frameTotal = 0; |
|
600 #define FRAME_ID(classname) \ |
|
601 frameTotal += windowTotalSizes.mArenaStats.FRAME_ID_STAT_FIELD(classname); |
|
602 #include "nsFrameIdList.h" |
|
603 #undef FRAME_ID |
|
604 |
|
605 REPORT("window-objects/layout/frames", frameTotal, |
|
606 "Memory used for layout frames within windows. " |
|
607 "This is the sum of all windows' 'layout/frames/' numbers."); |
|
608 |
|
609 #undef REPORT |
|
610 |
|
611 return NS_OK; |
|
612 } |
|
613 |
|
614 uint32_t |
|
615 nsWindowMemoryReporter::GetGhostTimeout() |
|
616 { |
|
617 return Preferences::GetUint("memory.ghost_window_timeout_seconds", 60); |
|
618 } |
|
619 |
|
620 NS_IMETHODIMP |
|
621 nsWindowMemoryReporter::Observe(nsISupports *aSubject, const char *aTopic, |
|
622 const char16_t *aData) |
|
623 { |
|
624 if (!strcmp(aTopic, DOM_WINDOW_DESTROYED_TOPIC)) { |
|
625 ObserveDOMWindowDetached(aSubject); |
|
626 } else if (!strcmp(aTopic, "after-minimize-memory-usage")) { |
|
627 ObserveAfterMinimizeMemoryUsage(); |
|
628 } else if (!strcmp(aTopic, "cycle-collector-begin")) { |
|
629 if (mCheckTimer) { |
|
630 mCheckTimerWaitingForCCEnd = true; |
|
631 KillCheckTimer(); |
|
632 } |
|
633 mCycleCollectorIsRunning = true; |
|
634 } else if (!strcmp(aTopic, "cycle-collector-end")) { |
|
635 mCycleCollectorIsRunning = false; |
|
636 if (mCheckTimerWaitingForCCEnd) { |
|
637 mCheckTimerWaitingForCCEnd = false; |
|
638 AsyncCheckForGhostWindows(); |
|
639 } |
|
640 } else { |
|
641 MOZ_ASSERT(false); |
|
642 } |
|
643 |
|
644 return NS_OK; |
|
645 } |
|
646 |
|
647 void |
|
648 nsWindowMemoryReporter::ObserveDOMWindowDetached(nsISupports* aWindow) |
|
649 { |
|
650 nsWeakPtr weakWindow = do_GetWeakReference(aWindow); |
|
651 if (!weakWindow) { |
|
652 NS_WARNING("Couldn't take weak reference to a window?"); |
|
653 return; |
|
654 } |
|
655 |
|
656 mDetachedWindows.Put(weakWindow, TimeStamp()); |
|
657 |
|
658 AsyncCheckForGhostWindows(); |
|
659 } |
|
660 |
|
661 // static |
|
662 void |
|
663 nsWindowMemoryReporter::CheckTimerFired(nsITimer* aTimer, void* aClosure) |
|
664 { |
|
665 if (sWindowReporter) { |
|
666 MOZ_ASSERT(!sWindowReporter->mCycleCollectorIsRunning); |
|
667 sWindowReporter->CheckForGhostWindows(); |
|
668 } |
|
669 } |
|
670 |
|
671 void |
|
672 nsWindowMemoryReporter::AsyncCheckForGhostWindows() |
|
673 { |
|
674 if (mCheckTimer) { |
|
675 return; |
|
676 } |
|
677 |
|
678 if (mCycleCollectorIsRunning) { |
|
679 mCheckTimerWaitingForCCEnd = true; |
|
680 return; |
|
681 } |
|
682 |
|
683 // If more than kTimeBetweenChecks seconds have elapsed since the last check, |
|
684 // timerDelay is 0. Otherwise, it is kTimeBetweenChecks, reduced by the time |
|
685 // since the last check. Reducing the delay by the time since the last check |
|
686 // prevents the timer from being completely starved if it is repeatedly killed |
|
687 // and restarted. |
|
688 int32_t timeSinceLastCheck = (TimeStamp::NowLoRes() - mLastCheckForGhostWindows).ToSeconds(); |
|
689 int32_t timerDelay = (kTimeBetweenChecks - std::min(timeSinceLastCheck, kTimeBetweenChecks)) * PR_MSEC_PER_SEC; |
|
690 |
|
691 CallCreateInstance<nsITimer>("@mozilla.org/timer;1", getter_AddRefs(mCheckTimer)); |
|
692 |
|
693 if (mCheckTimer) { |
|
694 mCheckTimer->InitWithFuncCallback(CheckTimerFired, nullptr, |
|
695 timerDelay, nsITimer::TYPE_ONE_SHOT); |
|
696 } |
|
697 } |
|
698 |
|
699 static PLDHashOperator |
|
700 BackdateTimeStampsEnumerator(nsISupports *aKey, TimeStamp &aTimeStamp, |
|
701 void* aClosure) |
|
702 { |
|
703 TimeStamp *minTimeStamp = static_cast<TimeStamp*>(aClosure); |
|
704 |
|
705 if (!aTimeStamp.IsNull() && aTimeStamp > *minTimeStamp) { |
|
706 aTimeStamp = *minTimeStamp; |
|
707 } |
|
708 |
|
709 return PL_DHASH_NEXT; |
|
710 } |
|
711 |
|
712 void |
|
713 nsWindowMemoryReporter::ObserveAfterMinimizeMemoryUsage() |
|
714 { |
|
715 // Someone claims they've done enough GC/CCs so that all eligible windows |
|
716 // have been free'd. So we deem that any windows which satisfy ghost |
|
717 // criteria (1) and (2) now satisfy criterion (3) as well. |
|
718 // |
|
719 // To effect this change, we'll backdate some of our timestamps. |
|
720 |
|
721 TimeStamp minTimeStamp = TimeStamp::Now() - |
|
722 TimeDuration::FromSeconds(GetGhostTimeout()); |
|
723 |
|
724 mDetachedWindows.Enumerate(BackdateTimeStampsEnumerator, |
|
725 &minTimeStamp); |
|
726 } |
|
727 |
|
728 struct CheckForGhostWindowsEnumeratorData |
|
729 { |
|
730 nsTHashtable<nsCStringHashKey> *nonDetachedDomains; |
|
731 nsTHashtable<nsUint64HashKey> *ghostWindowIDs; |
|
732 nsIEffectiveTLDService *tldService; |
|
733 uint32_t ghostTimeout; |
|
734 TimeStamp now; |
|
735 }; |
|
736 |
|
737 static PLDHashOperator |
|
738 CheckForGhostWindowsEnumerator(nsISupports *aKey, TimeStamp& aTimeStamp, |
|
739 void* aClosure) |
|
740 { |
|
741 CheckForGhostWindowsEnumeratorData *data = |
|
742 static_cast<CheckForGhostWindowsEnumeratorData*>(aClosure); |
|
743 |
|
744 nsWeakPtr weakKey = do_QueryInterface(aKey); |
|
745 nsCOMPtr<nsPIDOMWindow> window = do_QueryReferent(weakKey); |
|
746 if (!window) { |
|
747 // The window object has been destroyed. Stop tracking its weak ref in our |
|
748 // hashtable. |
|
749 return PL_DHASH_REMOVE; |
|
750 } |
|
751 |
|
752 // Avoid calling GetTop() if we have no outer window. Nothing will break if |
|
753 // we do, but it will spew debug output, which can cause our test logs to |
|
754 // overflow. |
|
755 nsCOMPtr<nsIDOMWindow> top; |
|
756 if (window->GetOuterWindow()) { |
|
757 window->GetTop(getter_AddRefs(top)); |
|
758 } |
|
759 |
|
760 if (top) { |
|
761 // The window is no longer detached, so we no longer want to track it. |
|
762 return PL_DHASH_REMOVE; |
|
763 } |
|
764 |
|
765 nsCOMPtr<nsIURI> uri = GetWindowURI(window); |
|
766 |
|
767 nsAutoCString domain; |
|
768 if (uri) { |
|
769 // GetBaseDomain works fine if |uri| is null, but it outputs a warning |
|
770 // which ends up overrunning the mochitest logs. |
|
771 data->tldService->GetBaseDomain(uri, 0, domain); |
|
772 } |
|
773 |
|
774 if (data->nonDetachedDomains->Contains(domain)) { |
|
775 // This window shares a domain with a non-detached window, so reset its |
|
776 // clock. |
|
777 aTimeStamp = TimeStamp(); |
|
778 } else { |
|
779 // This window does not share a domain with a non-detached window, so it |
|
780 // meets ghost criterion (2). |
|
781 if (aTimeStamp.IsNull()) { |
|
782 // This may become a ghost window later; start its clock. |
|
783 aTimeStamp = data->now; |
|
784 } else if ((data->now - aTimeStamp).ToSeconds() > data->ghostTimeout) { |
|
785 // This definitely is a ghost window, so add it to ghostWindowIDs, if |
|
786 // that is not null. |
|
787 if (data->ghostWindowIDs) { |
|
788 nsCOMPtr<nsPIDOMWindow> pWindow = do_QueryInterface(window); |
|
789 if (pWindow) { |
|
790 data->ghostWindowIDs->PutEntry(pWindow->WindowID()); |
|
791 } |
|
792 } |
|
793 } |
|
794 } |
|
795 |
|
796 return PL_DHASH_NEXT; |
|
797 } |
|
798 |
|
799 struct GetNonDetachedWindowDomainsEnumeratorData |
|
800 { |
|
801 nsTHashtable<nsCStringHashKey> *nonDetachedDomains; |
|
802 nsIEffectiveTLDService *tldService; |
|
803 }; |
|
804 |
|
805 static PLDHashOperator |
|
806 GetNonDetachedWindowDomainsEnumerator(const uint64_t& aId, nsGlobalWindow* aWindow, |
|
807 void* aClosure) |
|
808 { |
|
809 GetNonDetachedWindowDomainsEnumeratorData *data = |
|
810 static_cast<GetNonDetachedWindowDomainsEnumeratorData*>(aClosure); |
|
811 |
|
812 // Null outer window implies null top, but calling GetTop() when there's no |
|
813 // outer window causes us to spew debug warnings. |
|
814 if (!aWindow->GetOuterWindow() || !aWindow->GetTop()) { |
|
815 // This window is detached, so we don't care about its domain. |
|
816 return PL_DHASH_NEXT; |
|
817 } |
|
818 |
|
819 nsCOMPtr<nsIURI> uri = GetWindowURI(aWindow); |
|
820 |
|
821 nsAutoCString domain; |
|
822 if (uri) { |
|
823 data->tldService->GetBaseDomain(uri, 0, domain); |
|
824 } |
|
825 |
|
826 data->nonDetachedDomains->PutEntry(domain); |
|
827 return PL_DHASH_NEXT; |
|
828 } |
|
829 |
|
830 /** |
|
831 * Iterate over mDetachedWindows and update it to reflect the current state of |
|
832 * the world. In particular: |
|
833 * |
|
834 * - Remove weak refs to windows which no longer exist. |
|
835 * |
|
836 * - Remove references to windows which are no longer detached. |
|
837 * |
|
838 * - Reset the timestamp on detached windows which share a domain with a |
|
839 * non-detached window (they no longer meet ghost criterion (2)). |
|
840 * |
|
841 * - If a window now meets ghost criterion (2) but didn't before, set its |
|
842 * timestamp to now. |
|
843 * |
|
844 * Additionally, if aOutGhostIDs is not null, fill it with the window IDs of |
|
845 * all ghost windows we found. |
|
846 */ |
|
847 void |
|
848 nsWindowMemoryReporter::CheckForGhostWindows( |
|
849 nsTHashtable<nsUint64HashKey> *aOutGhostIDs /* = nullptr */) |
|
850 { |
|
851 nsCOMPtr<nsIEffectiveTLDService> tldService = do_GetService( |
|
852 NS_EFFECTIVETLDSERVICE_CONTRACTID); |
|
853 if (!tldService) { |
|
854 NS_WARNING("Couldn't get TLDService."); |
|
855 return; |
|
856 } |
|
857 |
|
858 nsGlobalWindow::WindowByIdTable *windowsById = |
|
859 nsGlobalWindow::GetWindowsTable(); |
|
860 if (!windowsById) { |
|
861 NS_WARNING("GetWindowsTable returned null"); |
|
862 return; |
|
863 } |
|
864 |
|
865 mLastCheckForGhostWindows = TimeStamp::NowLoRes(); |
|
866 KillCheckTimer(); |
|
867 |
|
868 nsTHashtable<nsCStringHashKey> nonDetachedWindowDomains; |
|
869 |
|
870 // Populate nonDetachedWindowDomains. |
|
871 GetNonDetachedWindowDomainsEnumeratorData nonDetachedEnumData = |
|
872 { &nonDetachedWindowDomains, tldService }; |
|
873 windowsById->EnumerateRead(GetNonDetachedWindowDomainsEnumerator, |
|
874 &nonDetachedEnumData); |
|
875 |
|
876 // Update mDetachedWindows and write the ghost window IDs into aOutGhostIDs, |
|
877 // if it's not null. |
|
878 CheckForGhostWindowsEnumeratorData ghostEnumData = |
|
879 { &nonDetachedWindowDomains, aOutGhostIDs, tldService, |
|
880 GetGhostTimeout(), mLastCheckForGhostWindows }; |
|
881 mDetachedWindows.Enumerate(CheckForGhostWindowsEnumerator, |
|
882 &ghostEnumData); |
|
883 } |
|
884 |
|
885 NS_IMPL_ISUPPORTS(nsWindowMemoryReporter::GhostWindowsReporter, |
|
886 nsIMemoryReporter) |
|
887 |
|
888 /* static */ int64_t |
|
889 nsWindowMemoryReporter::GhostWindowsReporter::DistinguishedAmount() |
|
890 { |
|
891 nsTHashtable<nsUint64HashKey> ghostWindows; |
|
892 sWindowReporter->CheckForGhostWindows(&ghostWindows); |
|
893 return ghostWindows.Count(); |
|
894 } |
|
895 |
|
896 void |
|
897 nsWindowMemoryReporter::KillCheckTimer() |
|
898 { |
|
899 if (mCheckTimer) { |
|
900 mCheckTimer->Cancel(); |
|
901 mCheckTimer = nullptr; |
|
902 } |
|
903 } |
|
904 |
|
905 #ifdef DEBUG |
|
906 static PLDHashOperator |
|
907 UnlinkGhostWindowsEnumerator(nsUint64HashKey* aIDHashKey, void *) |
|
908 { |
|
909 nsGlobalWindow::WindowByIdTable* windowsById = |
|
910 nsGlobalWindow::GetWindowsTable(); |
|
911 if (!windowsById) { |
|
912 return PL_DHASH_NEXT; |
|
913 } |
|
914 |
|
915 nsRefPtr<nsGlobalWindow> window = windowsById->Get(aIDHashKey->GetKey()); |
|
916 if (window) { |
|
917 window->RiskyUnlink(); |
|
918 } |
|
919 |
|
920 return PL_DHASH_NEXT; |
|
921 } |
|
922 |
|
923 /* static */ void |
|
924 nsWindowMemoryReporter::UnlinkGhostWindows() |
|
925 { |
|
926 if (!sWindowReporter) { |
|
927 return; |
|
928 } |
|
929 |
|
930 nsGlobalWindow::WindowByIdTable* windowsById = |
|
931 nsGlobalWindow::GetWindowsTable(); |
|
932 if (!windowsById) { |
|
933 return; |
|
934 } |
|
935 |
|
936 // Hold on to every window in memory so that window objects can't be |
|
937 // destroyed while we're calling the UnlinkGhostWindows callback. |
|
938 WindowArray windows; |
|
939 windowsById->Enumerate(GetWindows, &windows); |
|
940 |
|
941 // Get the IDs of all the "ghost" windows, and unlink them all. |
|
942 nsTHashtable<nsUint64HashKey> ghostWindows; |
|
943 sWindowReporter->CheckForGhostWindows(&ghostWindows); |
|
944 ghostWindows.EnumerateEntries(UnlinkGhostWindowsEnumerator, nullptr); |
|
945 } |
|
946 #endif |