michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=8 sts=2 et sw=2 tw=80: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "amIAddonManager.h" michael@0: #include "nsWindowMemoryReporter.h" michael@0: #include "nsGlobalWindow.h" michael@0: #include "nsIDocument.h" michael@0: #include "nsIDOMWindowCollection.h" michael@0: #include "nsIEffectiveTLDService.h" michael@0: #include "mozilla/ClearOnShutdown.h" michael@0: #include "mozilla/Preferences.h" michael@0: #include "mozilla/Services.h" michael@0: #include "mozilla/StaticPtr.h" michael@0: #include "nsNetCID.h" michael@0: #include "nsPrintfCString.h" michael@0: #include "XPCJSMemoryReporter.h" michael@0: #include "js/MemoryMetrics.h" michael@0: #include "nsServiceManagerUtils.h" michael@0: michael@0: using namespace mozilla; michael@0: michael@0: StaticRefPtr sWindowReporter; michael@0: michael@0: /** michael@0: * Don't trigger a ghost window check when a DOM window is detached if we've michael@0: * run it this recently. michael@0: */ michael@0: const int32_t kTimeBetweenChecks = 45; /* seconds */ michael@0: michael@0: nsWindowMemoryReporter::nsWindowMemoryReporter() michael@0: : mLastCheckForGhostWindows(TimeStamp::NowLoRes()), michael@0: mCycleCollectorIsRunning(false), michael@0: mCheckTimerWaitingForCCEnd(false) michael@0: { michael@0: } michael@0: michael@0: nsWindowMemoryReporter::~nsWindowMemoryReporter() michael@0: { michael@0: KillCheckTimer(); michael@0: } michael@0: michael@0: NS_IMPL_ISUPPORTS(nsWindowMemoryReporter, nsIMemoryReporter, nsIObserver, michael@0: nsISupportsWeakReference) michael@0: michael@0: static nsresult michael@0: AddNonJSSizeOfWindowAndItsDescendents(nsGlobalWindow* aWindow, michael@0: nsTabSizes* aSizes) michael@0: { michael@0: // Measure the window. michael@0: nsWindowSizes windowSizes(moz_malloc_size_of); michael@0: aWindow->AddSizeOfIncludingThis(&windowSizes); michael@0: windowSizes.addToTabSizes(aSizes); michael@0: michael@0: // Measure the inner window, if there is one. michael@0: nsWindowSizes innerWindowSizes(moz_malloc_size_of); michael@0: nsGlobalWindow* inner = aWindow->GetCurrentInnerWindowInternal(); michael@0: if (inner) { michael@0: inner->AddSizeOfIncludingThis(&innerWindowSizes); michael@0: innerWindowSizes.addToTabSizes(aSizes); michael@0: } michael@0: michael@0: nsCOMPtr frames; michael@0: nsresult rv = aWindow->GetFrames(getter_AddRefs(frames)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: uint32_t length; michael@0: rv = frames->GetLength(&length); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: // Measure this window's descendents. michael@0: for (uint32_t i = 0; i < length; i++) { michael@0: nsCOMPtr child; michael@0: rv = frames->Item(i, getter_AddRefs(child)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: NS_ENSURE_STATE(child); michael@0: michael@0: nsGlobalWindow* childWin = michael@0: static_cast(static_cast(child.get())); michael@0: michael@0: rv = AddNonJSSizeOfWindowAndItsDescendents(childWin, aSizes); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: static nsresult michael@0: NonJSSizeOfTab(nsPIDOMWindow* aWindow, size_t* aDomSize, size_t* aStyleSize, size_t* aOtherSize) michael@0: { michael@0: nsGlobalWindow* window = static_cast(aWindow); michael@0: michael@0: nsTabSizes sizes; michael@0: nsresult rv = AddNonJSSizeOfWindowAndItsDescendents(window, &sizes); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: *aDomSize = sizes.mDom; michael@0: *aStyleSize = sizes.mStyle; michael@0: *aOtherSize = sizes.mOther; michael@0: return NS_OK; michael@0: } michael@0: michael@0: /* static */ void michael@0: nsWindowMemoryReporter::Init() michael@0: { michael@0: MOZ_ASSERT(!sWindowReporter); michael@0: sWindowReporter = new nsWindowMemoryReporter(); michael@0: ClearOnShutdown(&sWindowReporter); michael@0: RegisterStrongMemoryReporter(sWindowReporter); michael@0: RegisterNonJSSizeOfTab(NonJSSizeOfTab); michael@0: michael@0: nsCOMPtr os = services::GetObserverService(); michael@0: if (os) { michael@0: // DOM_WINDOW_DESTROYED_TOPIC announces what we call window "detachment", michael@0: // when a window's docshell is set to nullptr. michael@0: os->AddObserver(sWindowReporter, DOM_WINDOW_DESTROYED_TOPIC, michael@0: /* weakRef = */ true); michael@0: os->AddObserver(sWindowReporter, "after-minimize-memory-usage", michael@0: /* weakRef = */ true); michael@0: os->AddObserver(sWindowReporter, "cycle-collector-begin", michael@0: /* weakRef = */ true); michael@0: os->AddObserver(sWindowReporter, "cycle-collector-end", michael@0: /* weakRef = */ true); michael@0: } michael@0: michael@0: RegisterStrongMemoryReporter(new GhostWindowsReporter()); michael@0: RegisterGhostWindowsDistinguishedAmount(GhostWindowsReporter::DistinguishedAmount); michael@0: } michael@0: michael@0: static already_AddRefed michael@0: GetWindowURI(nsIDOMWindow *aWindow) michael@0: { michael@0: nsCOMPtr pWindow = do_QueryInterface(aWindow); michael@0: NS_ENSURE_TRUE(pWindow, nullptr); michael@0: michael@0: nsCOMPtr doc = pWindow->GetExtantDoc(); michael@0: nsCOMPtr uri; michael@0: michael@0: if (doc) { michael@0: uri = doc->GetDocumentURI(); michael@0: } michael@0: michael@0: if (!uri) { michael@0: nsCOMPtr scriptObjPrincipal = michael@0: do_QueryInterface(aWindow); michael@0: NS_ENSURE_TRUE(scriptObjPrincipal, nullptr); michael@0: michael@0: // GetPrincipal() will print a warning if the window does not have an outer michael@0: // window, so check here for an outer window first. This code is michael@0: // functionally correct if we leave out the GetOuterWindow() check, but we michael@0: // end up printing a lot of warnings during debug mochitests. michael@0: if (pWindow->GetOuterWindow()) { michael@0: nsIPrincipal* principal = scriptObjPrincipal->GetPrincipal(); michael@0: if (principal) { michael@0: principal->GetURI(getter_AddRefs(uri)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: return uri.forget(); michael@0: } michael@0: michael@0: static void michael@0: AppendWindowURI(nsGlobalWindow *aWindow, nsACString& aStr) michael@0: { michael@0: nsCOMPtr uri = GetWindowURI(aWindow); michael@0: michael@0: if (uri) { michael@0: nsCString spec; michael@0: uri->GetSpec(spec); michael@0: michael@0: // A hack: replace forward slashes with '\\' so they aren't michael@0: // treated as path separators. Users of the reporters michael@0: // (such as about:memory) have to undo this change. michael@0: spec.ReplaceChar('/', '\\'); michael@0: michael@0: aStr += spec; michael@0: } else { michael@0: // If we're unable to find a URI, we're dealing with a chrome window with michael@0: // no document in it (or somesuch), so we call this a "system window". michael@0: aStr += NS_LITERAL_CSTRING("[system]"); michael@0: } michael@0: } michael@0: michael@0: MOZ_DEFINE_MALLOC_SIZE_OF(WindowsMallocSizeOf) michael@0: michael@0: // The key is the window ID. michael@0: typedef nsDataHashtable WindowPaths; michael@0: michael@0: static nsresult michael@0: ReportAmount(const nsCString& aBasePath, const char* aPathTail, michael@0: size_t aAmount, const nsCString& aDescription, michael@0: uint32_t aKind, uint32_t aUnits, michael@0: nsIMemoryReporterCallback* aCb, michael@0: nsISupports* aClosure) michael@0: { michael@0: if (aAmount == 0) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsAutoCString path(aBasePath); michael@0: path += aPathTail; michael@0: michael@0: return aCb->Callback(EmptyCString(), path, aKind, aUnits, michael@0: aAmount, aDescription, aClosure); michael@0: } michael@0: michael@0: static nsresult michael@0: ReportSize(const nsCString& aBasePath, const char* aPathTail, michael@0: size_t aAmount, const nsCString& aDescription, michael@0: nsIMemoryReporterCallback* aCb, michael@0: nsISupports* aClosure) michael@0: { michael@0: return ReportAmount(aBasePath, aPathTail, aAmount, aDescription, michael@0: nsIMemoryReporter::KIND_HEAP, michael@0: nsIMemoryReporter::UNITS_BYTES, aCb, aClosure); michael@0: } michael@0: michael@0: static nsresult michael@0: ReportCount(const nsCString& aBasePath, const char* aPathTail, michael@0: size_t aAmount, const nsCString& aDescription, michael@0: nsIMemoryReporterCallback* aCb, michael@0: nsISupports* aClosure) michael@0: { michael@0: return ReportAmount(aBasePath, aPathTail, aAmount, aDescription, michael@0: nsIMemoryReporter::KIND_OTHER, michael@0: nsIMemoryReporter::UNITS_COUNT, aCb, aClosure); michael@0: } michael@0: michael@0: static nsresult michael@0: CollectWindowReports(nsGlobalWindow *aWindow, michael@0: amIAddonManager *addonManager, michael@0: nsWindowSizes *aWindowTotalSizes, michael@0: nsTHashtable *aGhostWindowIDs, michael@0: WindowPaths *aWindowPaths, michael@0: WindowPaths *aTopWindowPaths, michael@0: nsIMemoryReporterCallback *aCb, michael@0: nsISupports *aClosure) michael@0: { michael@0: nsAutoCString windowPath("explicit/"); michael@0: michael@0: // Avoid calling aWindow->GetTop() if there's no outer window. It will work michael@0: // just fine, but will spew a lot of warnings. michael@0: nsGlobalWindow *top = nullptr; michael@0: nsCOMPtr location; michael@0: if (aWindow->GetOuterWindow()) { michael@0: // Our window should have a null top iff it has a null docshell. michael@0: MOZ_ASSERT(!!aWindow->GetTop() == !!aWindow->GetDocShell()); michael@0: top = aWindow->GetTop(); michael@0: if (top) { michael@0: location = GetWindowURI(top); michael@0: } michael@0: } michael@0: if (!location) { michael@0: location = GetWindowURI(aWindow); michael@0: } michael@0: michael@0: if (addonManager && location) { michael@0: bool ok; michael@0: nsAutoCString id; michael@0: if (NS_SUCCEEDED(addonManager->MapURIToAddonID(location, id, &ok)) && ok) { michael@0: windowPath += NS_LITERAL_CSTRING("add-ons/") + id + michael@0: NS_LITERAL_CSTRING("/"); michael@0: } michael@0: } michael@0: michael@0: windowPath += NS_LITERAL_CSTRING("window-objects/"); michael@0: michael@0: if (top) { michael@0: windowPath += NS_LITERAL_CSTRING("top("); michael@0: AppendWindowURI(top, windowPath); michael@0: windowPath += NS_LITERAL_CSTRING(", id="); michael@0: windowPath.AppendInt(top->WindowID()); michael@0: windowPath += NS_LITERAL_CSTRING(")"); michael@0: michael@0: aTopWindowPaths->Put(aWindow->WindowID(), windowPath); michael@0: michael@0: windowPath += aWindow->IsFrozen() ? NS_LITERAL_CSTRING("/cached/") michael@0: : NS_LITERAL_CSTRING("/active/"); michael@0: } else { michael@0: if (aGhostWindowIDs->Contains(aWindow->WindowID())) { michael@0: windowPath += NS_LITERAL_CSTRING("top(none)/ghost/"); michael@0: } else { michael@0: windowPath += NS_LITERAL_CSTRING("top(none)/detached/"); michael@0: } michael@0: } michael@0: michael@0: windowPath += NS_LITERAL_CSTRING("window("); michael@0: AppendWindowURI(aWindow, windowPath); michael@0: windowPath += NS_LITERAL_CSTRING(")"); michael@0: michael@0: // Use |windowPath|, but replace "explicit/" with "event-counts/". michael@0: nsCString censusWindowPath(windowPath); michael@0: censusWindowPath.Replace(0, strlen("explicit"), "event-counts"); michael@0: michael@0: // Remember the path for later. michael@0: aWindowPaths->Put(aWindow->WindowID(), windowPath); michael@0: michael@0: #define REPORT_SIZE(_pathTail, _amount, _desc) \ michael@0: do { \ michael@0: nsresult rv = ReportSize(windowPath, _pathTail, _amount, \ michael@0: NS_LITERAL_CSTRING(_desc), aCb, aClosure); \ michael@0: NS_ENSURE_SUCCESS(rv, rv); \ michael@0: } while (0) michael@0: michael@0: #define REPORT_COUNT(_pathTail, _amount, _desc) \ michael@0: do { \ michael@0: nsresult rv = ReportCount(censusWindowPath, _pathTail, _amount, \ michael@0: NS_LITERAL_CSTRING(_desc), aCb, aClosure); \ michael@0: NS_ENSURE_SUCCESS(rv, rv); \ michael@0: } while (0) michael@0: michael@0: nsWindowSizes windowSizes(WindowsMallocSizeOf); michael@0: aWindow->AddSizeOfIncludingThis(&windowSizes); michael@0: michael@0: REPORT_SIZE("/dom/element-nodes", windowSizes.mDOMElementNodesSize, michael@0: "Memory used by the element nodes in a window's DOM."); michael@0: aWindowTotalSizes->mDOMElementNodesSize += windowSizes.mDOMElementNodesSize; michael@0: michael@0: REPORT_SIZE("/dom/text-nodes", windowSizes.mDOMTextNodesSize, michael@0: "Memory used by the text nodes in a window's DOM."); michael@0: aWindowTotalSizes->mDOMTextNodesSize += windowSizes.mDOMTextNodesSize; michael@0: michael@0: REPORT_SIZE("/dom/cdata-nodes", windowSizes.mDOMCDATANodesSize, michael@0: "Memory used by the CDATA nodes in a window's DOM."); michael@0: aWindowTotalSizes->mDOMCDATANodesSize += windowSizes.mDOMCDATANodesSize; michael@0: michael@0: REPORT_SIZE("/dom/comment-nodes", windowSizes.mDOMCommentNodesSize, michael@0: "Memory used by the comment nodes in a window's DOM."); michael@0: aWindowTotalSizes->mDOMCommentNodesSize += windowSizes.mDOMCommentNodesSize; michael@0: michael@0: REPORT_SIZE("/dom/event-targets", windowSizes.mDOMEventTargetsSize, michael@0: "Memory used by the event targets table in a window's DOM, and " michael@0: "the objects it points to, which include XHRs."); michael@0: aWindowTotalSizes->mDOMEventTargetsSize += windowSizes.mDOMEventTargetsSize; michael@0: michael@0: REPORT_COUNT("/dom/event-targets", windowSizes.mDOMEventTargetsCount, michael@0: "Number of non-node event targets in the event targets table " michael@0: "in a window's DOM, such as XHRs."); michael@0: aWindowTotalSizes->mDOMEventTargetsCount += michael@0: windowSizes.mDOMEventTargetsCount; michael@0: michael@0: REPORT_COUNT("/dom/event-listeners", windowSizes.mDOMEventListenersCount, michael@0: "Number of event listeners in a window, including event " michael@0: "listeners on nodes and other event targets."); michael@0: aWindowTotalSizes->mDOMEventListenersCount += michael@0: windowSizes.mDOMEventListenersCount; michael@0: michael@0: REPORT_SIZE("/dom/other", windowSizes.mDOMOtherSize, michael@0: "Memory used by a window's DOM that isn't measured by the " michael@0: "other 'dom/' numbers."); michael@0: aWindowTotalSizes->mDOMOtherSize += windowSizes.mDOMOtherSize; michael@0: michael@0: REPORT_SIZE("/property-tables", michael@0: windowSizes.mPropertyTablesSize, michael@0: "Memory used for the property tables within a window."); michael@0: aWindowTotalSizes->mPropertyTablesSize += windowSizes.mPropertyTablesSize; michael@0: michael@0: REPORT_SIZE("/style-sheets", windowSizes.mStyleSheetsSize, michael@0: "Memory used by style sheets within a window."); michael@0: aWindowTotalSizes->mStyleSheetsSize += windowSizes.mStyleSheetsSize; michael@0: michael@0: REPORT_SIZE("/layout/pres-shell", windowSizes.mLayoutPresShellSize, michael@0: "Memory used by layout's PresShell, along with any structures " michael@0: "allocated in its arena and not measured elsewhere, " michael@0: "within a window."); michael@0: aWindowTotalSizes->mLayoutPresShellSize += windowSizes.mLayoutPresShellSize; michael@0: michael@0: REPORT_SIZE("/layout/line-boxes", windowSizes.mArenaStats.mLineBoxes, michael@0: "Memory used by line boxes within a window."); michael@0: aWindowTotalSizes->mArenaStats.mLineBoxes michael@0: += windowSizes.mArenaStats.mLineBoxes; michael@0: michael@0: REPORT_SIZE("/layout/rule-nodes", windowSizes.mArenaStats.mRuleNodes, michael@0: "Memory used by CSS rule nodes within a window."); michael@0: aWindowTotalSizes->mArenaStats.mRuleNodes michael@0: += windowSizes.mArenaStats.mRuleNodes; michael@0: michael@0: REPORT_SIZE("/layout/style-contexts", windowSizes.mArenaStats.mStyleContexts, michael@0: "Memory used by style contexts within a window."); michael@0: aWindowTotalSizes->mArenaStats.mStyleContexts michael@0: += windowSizes.mArenaStats.mStyleContexts; michael@0: michael@0: REPORT_SIZE("/layout/style-sets", windowSizes.mLayoutStyleSetsSize, michael@0: "Memory used by style sets within a window."); michael@0: aWindowTotalSizes->mLayoutStyleSetsSize += windowSizes.mLayoutStyleSetsSize; michael@0: michael@0: REPORT_SIZE("/layout/text-runs", windowSizes.mLayoutTextRunsSize, michael@0: "Memory used for text-runs (glyph layout) in the PresShell's " michael@0: "frame tree, within a window."); michael@0: aWindowTotalSizes->mLayoutTextRunsSize += windowSizes.mLayoutTextRunsSize; michael@0: michael@0: REPORT_SIZE("/layout/pres-contexts", windowSizes.mLayoutPresContextSize, michael@0: "Memory used for the PresContext in the PresShell's frame " michael@0: "within a window."); michael@0: aWindowTotalSizes->mLayoutPresContextSize += michael@0: windowSizes.mLayoutPresContextSize; michael@0: michael@0: // There are many different kinds of frames, but it is very likely michael@0: // that only a few matter. Implement a cutoff so we don't bloat michael@0: // about:memory with many uninteresting entries. michael@0: const size_t FRAME_SUNDRIES_THRESHOLD = michael@0: js::MemoryReportingSundriesThreshold(); michael@0: michael@0: size_t frameSundriesSize = 0; michael@0: #define FRAME_ID(classname) \ michael@0: { \ michael@0: size_t frameSize \ michael@0: = windowSizes.mArenaStats.FRAME_ID_STAT_FIELD(classname); \ michael@0: if (frameSize < FRAME_SUNDRIES_THRESHOLD) { \ michael@0: frameSundriesSize += frameSize; \ michael@0: } else { \ michael@0: REPORT_SIZE("/layout/frames/" # classname, frameSize, \ michael@0: "Memory used by frames of " \ michael@0: "type " #classname " within a window."); \ michael@0: } \ michael@0: aWindowTotalSizes->mArenaStats.FRAME_ID_STAT_FIELD(classname) \ michael@0: += frameSize; \ michael@0: } michael@0: #include "nsFrameIdList.h" michael@0: #undef FRAME_ID michael@0: michael@0: if (frameSundriesSize > 0) { michael@0: REPORT_SIZE("/layout/frames/sundries", frameSundriesSize, michael@0: "The sum of all memory used by frames which were too small " michael@0: "to be shown individually."); michael@0: } michael@0: michael@0: #undef REPORT_SIZE michael@0: #undef REPORT_COUNT michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: typedef nsTArray< nsRefPtr > WindowArray; michael@0: michael@0: static michael@0: PLDHashOperator michael@0: GetWindows(const uint64_t& aId, nsGlobalWindow*& aWindow, void* aClosure) michael@0: { michael@0: ((WindowArray *)aClosure)->AppendElement(aWindow); michael@0: michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: struct ReportGhostWindowsEnumeratorData michael@0: { michael@0: nsIMemoryReporterCallback* callback; michael@0: nsISupports* closure; michael@0: nsresult rv; michael@0: }; michael@0: michael@0: static PLDHashOperator michael@0: ReportGhostWindowsEnumerator(nsUint64HashKey* aIDHashKey, void* aClosure) michael@0: { michael@0: ReportGhostWindowsEnumeratorData *data = michael@0: static_cast(aClosure); michael@0: michael@0: nsGlobalWindow::WindowByIdTable* windowsById = michael@0: nsGlobalWindow::GetWindowsTable(); michael@0: if (!windowsById) { michael@0: NS_WARNING("Couldn't get window-by-id hashtable?"); michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: nsGlobalWindow* window = windowsById->Get(aIDHashKey->GetKey()); michael@0: if (!window) { michael@0: NS_WARNING("Could not look up window?"); michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: nsAutoCString path; michael@0: path.AppendLiteral("ghost-windows/"); michael@0: AppendWindowURI(window, path); michael@0: michael@0: nsresult rv = data->callback->Callback( michael@0: /* process = */ EmptyCString(), michael@0: path, michael@0: nsIMemoryReporter::KIND_OTHER, michael@0: nsIMemoryReporter::UNITS_COUNT, michael@0: /* amount = */ 1, michael@0: /* description = */ NS_LITERAL_CSTRING("A ghost window."), michael@0: data->closure); michael@0: michael@0: if (NS_FAILED(rv) && NS_SUCCEEDED(data->rv)) { michael@0: data->rv = rv; michael@0: } michael@0: michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsWindowMemoryReporter::CollectReports(nsIMemoryReporterCallback* aCb, michael@0: nsISupports* aClosure) michael@0: { michael@0: nsGlobalWindow::WindowByIdTable* windowsById = michael@0: nsGlobalWindow::GetWindowsTable(); michael@0: NS_ENSURE_TRUE(windowsById, NS_OK); michael@0: michael@0: // Hold on to every window in memory so that window objects can't be michael@0: // destroyed while we're calling the memory reporter callback. michael@0: WindowArray windows; michael@0: windowsById->Enumerate(GetWindows, &windows); michael@0: michael@0: // Get the IDs of all the "ghost" windows, and call aCb->Callback() for each michael@0: // one. michael@0: nsTHashtable ghostWindows; michael@0: CheckForGhostWindows(&ghostWindows); michael@0: ReportGhostWindowsEnumeratorData reportGhostWindowsEnumData = michael@0: { aCb, aClosure, NS_OK }; michael@0: ghostWindows.EnumerateEntries(ReportGhostWindowsEnumerator, michael@0: &reportGhostWindowsEnumData); michael@0: nsresult rv = reportGhostWindowsEnumData.rv; michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: WindowPaths windowPaths; michael@0: WindowPaths topWindowPaths; michael@0: michael@0: // Collect window memory usage. michael@0: nsWindowSizes windowTotalSizes(nullptr); michael@0: nsCOMPtr addonManager; michael@0: if (XRE_GetProcessType() == GeckoProcessType_Default) { michael@0: // Only try to access the service from the main process. michael@0: addonManager = do_GetService("@mozilla.org/addons/integration;1"); michael@0: } michael@0: for (uint32_t i = 0; i < windows.Length(); i++) { michael@0: rv = CollectWindowReports(windows[i], addonManager, michael@0: &windowTotalSizes, &ghostWindows, michael@0: &windowPaths, &topWindowPaths, aCb, michael@0: aClosure); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: // Report JS memory usage. We do this from here because the JS memory michael@0: // reporter needs to be passed |windowPaths|. michael@0: rv = xpc::JSReporter::CollectReports(&windowPaths, &topWindowPaths, michael@0: aCb, aClosure); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: #define REPORT(_path, _amount, _desc) \ michael@0: do { \ michael@0: nsresult rv; \ michael@0: rv = aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ michael@0: KIND_OTHER, UNITS_BYTES, _amount, \ michael@0: NS_LITERAL_CSTRING(_desc), aClosure); \ michael@0: NS_ENSURE_SUCCESS(rv, rv); \ michael@0: } while (0) michael@0: michael@0: REPORT("window-objects/dom/element-nodes", windowTotalSizes.mDOMElementNodesSize, michael@0: "This is the sum of all windows' 'dom/element-nodes' numbers."); michael@0: michael@0: REPORT("window-objects/dom/text-nodes", windowTotalSizes.mDOMTextNodesSize, michael@0: "This is the sum of all windows' 'dom/text-nodes' numbers."); michael@0: michael@0: REPORT("window-objects/dom/cdata-nodes", windowTotalSizes.mDOMCDATANodesSize, michael@0: "This is the sum of all windows' 'dom/cdata-nodes' numbers."); michael@0: michael@0: REPORT("window-objects/dom/comment-nodes", windowTotalSizes.mDOMCommentNodesSize, michael@0: "This is the sum of all windows' 'dom/comment-nodes' numbers."); michael@0: michael@0: REPORT("window-objects/dom/event-targets", windowTotalSizes.mDOMEventTargetsSize, michael@0: "This is the sum of all windows' 'dom/event-targets' numbers."); michael@0: michael@0: REPORT("window-objects/dom/other", windowTotalSizes.mDOMOtherSize, michael@0: "This is the sum of all windows' 'dom/other' numbers."); michael@0: michael@0: REPORT("window-objects/property-tables", michael@0: windowTotalSizes.mPropertyTablesSize, michael@0: "This is the sum of all windows' 'property-tables' numbers."); michael@0: michael@0: REPORT("window-objects/style-sheets", windowTotalSizes.mStyleSheetsSize, michael@0: "This is the sum of all windows' 'style-sheets' numbers."); michael@0: michael@0: REPORT("window-objects/layout/pres-shell", windowTotalSizes.mLayoutPresShellSize, michael@0: "This is the sum of all windows' 'layout/arenas' numbers."); michael@0: michael@0: REPORT("window-objects/layout/line-boxes", michael@0: windowTotalSizes.mArenaStats.mLineBoxes, michael@0: "This is the sum of all windows' 'layout/line-boxes' numbers."); michael@0: michael@0: REPORT("window-objects/layout/rule-nodes", michael@0: windowTotalSizes.mArenaStats.mRuleNodes, michael@0: "This is the sum of all windows' 'layout/rule-nodes' numbers."); michael@0: michael@0: REPORT("window-objects/layout/style-contexts", michael@0: windowTotalSizes.mArenaStats.mStyleContexts, michael@0: "This is the sum of all windows' 'layout/style-contexts' numbers."); michael@0: michael@0: REPORT("window-objects/layout/style-sets", windowTotalSizes.mLayoutStyleSetsSize, michael@0: "This is the sum of all windows' 'layout/style-sets' numbers."); michael@0: michael@0: REPORT("window-objects/layout/text-runs", windowTotalSizes.mLayoutTextRunsSize, michael@0: "This is the sum of all windows' 'layout/text-runs' numbers."); michael@0: michael@0: REPORT("window-objects/layout/pres-contexts", windowTotalSizes.mLayoutPresContextSize, michael@0: "This is the sum of all windows' 'layout/pres-contexts' numbers."); michael@0: michael@0: size_t frameTotal = 0; michael@0: #define FRAME_ID(classname) \ michael@0: frameTotal += windowTotalSizes.mArenaStats.FRAME_ID_STAT_FIELD(classname); michael@0: #include "nsFrameIdList.h" michael@0: #undef FRAME_ID michael@0: michael@0: REPORT("window-objects/layout/frames", frameTotal, michael@0: "Memory used for layout frames within windows. " michael@0: "This is the sum of all windows' 'layout/frames/' numbers."); michael@0: michael@0: #undef REPORT michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: uint32_t michael@0: nsWindowMemoryReporter::GetGhostTimeout() michael@0: { michael@0: return Preferences::GetUint("memory.ghost_window_timeout_seconds", 60); michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsWindowMemoryReporter::Observe(nsISupports *aSubject, const char *aTopic, michael@0: const char16_t *aData) michael@0: { michael@0: if (!strcmp(aTopic, DOM_WINDOW_DESTROYED_TOPIC)) { michael@0: ObserveDOMWindowDetached(aSubject); michael@0: } else if (!strcmp(aTopic, "after-minimize-memory-usage")) { michael@0: ObserveAfterMinimizeMemoryUsage(); michael@0: } else if (!strcmp(aTopic, "cycle-collector-begin")) { michael@0: if (mCheckTimer) { michael@0: mCheckTimerWaitingForCCEnd = true; michael@0: KillCheckTimer(); michael@0: } michael@0: mCycleCollectorIsRunning = true; michael@0: } else if (!strcmp(aTopic, "cycle-collector-end")) { michael@0: mCycleCollectorIsRunning = false; michael@0: if (mCheckTimerWaitingForCCEnd) { michael@0: mCheckTimerWaitingForCCEnd = false; michael@0: AsyncCheckForGhostWindows(); michael@0: } michael@0: } else { michael@0: MOZ_ASSERT(false); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: void michael@0: nsWindowMemoryReporter::ObserveDOMWindowDetached(nsISupports* aWindow) michael@0: { michael@0: nsWeakPtr weakWindow = do_GetWeakReference(aWindow); michael@0: if (!weakWindow) { michael@0: NS_WARNING("Couldn't take weak reference to a window?"); michael@0: return; michael@0: } michael@0: michael@0: mDetachedWindows.Put(weakWindow, TimeStamp()); michael@0: michael@0: AsyncCheckForGhostWindows(); michael@0: } michael@0: michael@0: // static michael@0: void michael@0: nsWindowMemoryReporter::CheckTimerFired(nsITimer* aTimer, void* aClosure) michael@0: { michael@0: if (sWindowReporter) { michael@0: MOZ_ASSERT(!sWindowReporter->mCycleCollectorIsRunning); michael@0: sWindowReporter->CheckForGhostWindows(); michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsWindowMemoryReporter::AsyncCheckForGhostWindows() michael@0: { michael@0: if (mCheckTimer) { michael@0: return; michael@0: } michael@0: michael@0: if (mCycleCollectorIsRunning) { michael@0: mCheckTimerWaitingForCCEnd = true; michael@0: return; michael@0: } michael@0: michael@0: // If more than kTimeBetweenChecks seconds have elapsed since the last check, michael@0: // timerDelay is 0. Otherwise, it is kTimeBetweenChecks, reduced by the time michael@0: // since the last check. Reducing the delay by the time since the last check michael@0: // prevents the timer from being completely starved if it is repeatedly killed michael@0: // and restarted. michael@0: int32_t timeSinceLastCheck = (TimeStamp::NowLoRes() - mLastCheckForGhostWindows).ToSeconds(); michael@0: int32_t timerDelay = (kTimeBetweenChecks - std::min(timeSinceLastCheck, kTimeBetweenChecks)) * PR_MSEC_PER_SEC; michael@0: michael@0: CallCreateInstance("@mozilla.org/timer;1", getter_AddRefs(mCheckTimer)); michael@0: michael@0: if (mCheckTimer) { michael@0: mCheckTimer->InitWithFuncCallback(CheckTimerFired, nullptr, michael@0: timerDelay, nsITimer::TYPE_ONE_SHOT); michael@0: } michael@0: } michael@0: michael@0: static PLDHashOperator michael@0: BackdateTimeStampsEnumerator(nsISupports *aKey, TimeStamp &aTimeStamp, michael@0: void* aClosure) michael@0: { michael@0: TimeStamp *minTimeStamp = static_cast(aClosure); michael@0: michael@0: if (!aTimeStamp.IsNull() && aTimeStamp > *minTimeStamp) { michael@0: aTimeStamp = *minTimeStamp; michael@0: } michael@0: michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: void michael@0: nsWindowMemoryReporter::ObserveAfterMinimizeMemoryUsage() michael@0: { michael@0: // Someone claims they've done enough GC/CCs so that all eligible windows michael@0: // have been free'd. So we deem that any windows which satisfy ghost michael@0: // criteria (1) and (2) now satisfy criterion (3) as well. michael@0: // michael@0: // To effect this change, we'll backdate some of our timestamps. michael@0: michael@0: TimeStamp minTimeStamp = TimeStamp::Now() - michael@0: TimeDuration::FromSeconds(GetGhostTimeout()); michael@0: michael@0: mDetachedWindows.Enumerate(BackdateTimeStampsEnumerator, michael@0: &minTimeStamp); michael@0: } michael@0: michael@0: struct CheckForGhostWindowsEnumeratorData michael@0: { michael@0: nsTHashtable *nonDetachedDomains; michael@0: nsTHashtable *ghostWindowIDs; michael@0: nsIEffectiveTLDService *tldService; michael@0: uint32_t ghostTimeout; michael@0: TimeStamp now; michael@0: }; michael@0: michael@0: static PLDHashOperator michael@0: CheckForGhostWindowsEnumerator(nsISupports *aKey, TimeStamp& aTimeStamp, michael@0: void* aClosure) michael@0: { michael@0: CheckForGhostWindowsEnumeratorData *data = michael@0: static_cast(aClosure); michael@0: michael@0: nsWeakPtr weakKey = do_QueryInterface(aKey); michael@0: nsCOMPtr window = do_QueryReferent(weakKey); michael@0: if (!window) { michael@0: // The window object has been destroyed. Stop tracking its weak ref in our michael@0: // hashtable. michael@0: return PL_DHASH_REMOVE; michael@0: } michael@0: michael@0: // Avoid calling GetTop() if we have no outer window. Nothing will break if michael@0: // we do, but it will spew debug output, which can cause our test logs to michael@0: // overflow. michael@0: nsCOMPtr top; michael@0: if (window->GetOuterWindow()) { michael@0: window->GetTop(getter_AddRefs(top)); michael@0: } michael@0: michael@0: if (top) { michael@0: // The window is no longer detached, so we no longer want to track it. michael@0: return PL_DHASH_REMOVE; michael@0: } michael@0: michael@0: nsCOMPtr uri = GetWindowURI(window); michael@0: michael@0: nsAutoCString domain; michael@0: if (uri) { michael@0: // GetBaseDomain works fine if |uri| is null, but it outputs a warning michael@0: // which ends up overrunning the mochitest logs. michael@0: data->tldService->GetBaseDomain(uri, 0, domain); michael@0: } michael@0: michael@0: if (data->nonDetachedDomains->Contains(domain)) { michael@0: // This window shares a domain with a non-detached window, so reset its michael@0: // clock. michael@0: aTimeStamp = TimeStamp(); michael@0: } else { michael@0: // This window does not share a domain with a non-detached window, so it michael@0: // meets ghost criterion (2). michael@0: if (aTimeStamp.IsNull()) { michael@0: // This may become a ghost window later; start its clock. michael@0: aTimeStamp = data->now; michael@0: } else if ((data->now - aTimeStamp).ToSeconds() > data->ghostTimeout) { michael@0: // This definitely is a ghost window, so add it to ghostWindowIDs, if michael@0: // that is not null. michael@0: if (data->ghostWindowIDs) { michael@0: nsCOMPtr pWindow = do_QueryInterface(window); michael@0: if (pWindow) { michael@0: data->ghostWindowIDs->PutEntry(pWindow->WindowID()); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: struct GetNonDetachedWindowDomainsEnumeratorData michael@0: { michael@0: nsTHashtable *nonDetachedDomains; michael@0: nsIEffectiveTLDService *tldService; michael@0: }; michael@0: michael@0: static PLDHashOperator michael@0: GetNonDetachedWindowDomainsEnumerator(const uint64_t& aId, nsGlobalWindow* aWindow, michael@0: void* aClosure) michael@0: { michael@0: GetNonDetachedWindowDomainsEnumeratorData *data = michael@0: static_cast(aClosure); michael@0: michael@0: // Null outer window implies null top, but calling GetTop() when there's no michael@0: // outer window causes us to spew debug warnings. michael@0: if (!aWindow->GetOuterWindow() || !aWindow->GetTop()) { michael@0: // This window is detached, so we don't care about its domain. michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: nsCOMPtr uri = GetWindowURI(aWindow); michael@0: michael@0: nsAutoCString domain; michael@0: if (uri) { michael@0: data->tldService->GetBaseDomain(uri, 0, domain); michael@0: } michael@0: michael@0: data->nonDetachedDomains->PutEntry(domain); michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: /** michael@0: * Iterate over mDetachedWindows and update it to reflect the current state of michael@0: * the world. In particular: michael@0: * michael@0: * - Remove weak refs to windows which no longer exist. michael@0: * michael@0: * - Remove references to windows which are no longer detached. michael@0: * michael@0: * - Reset the timestamp on detached windows which share a domain with a michael@0: * non-detached window (they no longer meet ghost criterion (2)). michael@0: * michael@0: * - If a window now meets ghost criterion (2) but didn't before, set its michael@0: * timestamp to now. michael@0: * michael@0: * Additionally, if aOutGhostIDs is not null, fill it with the window IDs of michael@0: * all ghost windows we found. michael@0: */ michael@0: void michael@0: nsWindowMemoryReporter::CheckForGhostWindows( michael@0: nsTHashtable *aOutGhostIDs /* = nullptr */) michael@0: { michael@0: nsCOMPtr tldService = do_GetService( michael@0: NS_EFFECTIVETLDSERVICE_CONTRACTID); michael@0: if (!tldService) { michael@0: NS_WARNING("Couldn't get TLDService."); michael@0: return; michael@0: } michael@0: michael@0: nsGlobalWindow::WindowByIdTable *windowsById = michael@0: nsGlobalWindow::GetWindowsTable(); michael@0: if (!windowsById) { michael@0: NS_WARNING("GetWindowsTable returned null"); michael@0: return; michael@0: } michael@0: michael@0: mLastCheckForGhostWindows = TimeStamp::NowLoRes(); michael@0: KillCheckTimer(); michael@0: michael@0: nsTHashtable nonDetachedWindowDomains; michael@0: michael@0: // Populate nonDetachedWindowDomains. michael@0: GetNonDetachedWindowDomainsEnumeratorData nonDetachedEnumData = michael@0: { &nonDetachedWindowDomains, tldService }; michael@0: windowsById->EnumerateRead(GetNonDetachedWindowDomainsEnumerator, michael@0: &nonDetachedEnumData); michael@0: michael@0: // Update mDetachedWindows and write the ghost window IDs into aOutGhostIDs, michael@0: // if it's not null. michael@0: CheckForGhostWindowsEnumeratorData ghostEnumData = michael@0: { &nonDetachedWindowDomains, aOutGhostIDs, tldService, michael@0: GetGhostTimeout(), mLastCheckForGhostWindows }; michael@0: mDetachedWindows.Enumerate(CheckForGhostWindowsEnumerator, michael@0: &ghostEnumData); michael@0: } michael@0: michael@0: NS_IMPL_ISUPPORTS(nsWindowMemoryReporter::GhostWindowsReporter, michael@0: nsIMemoryReporter) michael@0: michael@0: /* static */ int64_t michael@0: nsWindowMemoryReporter::GhostWindowsReporter::DistinguishedAmount() michael@0: { michael@0: nsTHashtable ghostWindows; michael@0: sWindowReporter->CheckForGhostWindows(&ghostWindows); michael@0: return ghostWindows.Count(); michael@0: } michael@0: michael@0: void michael@0: nsWindowMemoryReporter::KillCheckTimer() michael@0: { michael@0: if (mCheckTimer) { michael@0: mCheckTimer->Cancel(); michael@0: mCheckTimer = nullptr; michael@0: } michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: static PLDHashOperator michael@0: UnlinkGhostWindowsEnumerator(nsUint64HashKey* aIDHashKey, void *) michael@0: { michael@0: nsGlobalWindow::WindowByIdTable* windowsById = michael@0: nsGlobalWindow::GetWindowsTable(); michael@0: if (!windowsById) { michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: nsRefPtr window = windowsById->Get(aIDHashKey->GetKey()); michael@0: if (window) { michael@0: window->RiskyUnlink(); michael@0: } michael@0: michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: /* static */ void michael@0: nsWindowMemoryReporter::UnlinkGhostWindows() michael@0: { michael@0: if (!sWindowReporter) { michael@0: return; michael@0: } michael@0: michael@0: nsGlobalWindow::WindowByIdTable* windowsById = michael@0: nsGlobalWindow::GetWindowsTable(); michael@0: if (!windowsById) { michael@0: return; michael@0: } michael@0: michael@0: // Hold on to every window in memory so that window objects can't be michael@0: // destroyed while we're calling the UnlinkGhostWindows callback. michael@0: WindowArray windows; michael@0: windowsById->Enumerate(GetWindows, &windows); michael@0: michael@0: // Get the IDs of all the "ghost" windows, and unlink them all. michael@0: nsTHashtable ghostWindows; michael@0: sWindowReporter->CheckForGhostWindows(&ghostWindows); michael@0: ghostWindows.EnumerateEntries(UnlinkGhostWindowsEnumerator, nullptr); michael@0: } michael@0: #endif