MemoryPressureHandler shouldn't know how to release WebCore memory
authorcarlosgc@webkit.org <carlosgc@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Thu, 10 Nov 2016 14:24:26 +0000 (14:24 +0000)
committercarlosgc@webkit.org <carlosgc@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Thu, 10 Nov 2016 14:24:26 +0000 (14:24 +0000)
https://bugs.webkit.org/show_bug.cgi?id=160497

Reviewed by Michael Catanzaro.

Source/WebCore:

All processes should set their own low memory handler, instead of leaving the web process using the default one
that needs to access APIs that are not in platform layer. This patch fixes all the layering violations in the
MemoryPressureHandler. Since the default implementation, that releases the WebCore memory, is shared by the
WebProcess in WebKit2 and WebKit1 ports, it has been moved to its own file to the WebCore layer.

* CMakeLists.txt: Add new files to compilation.
* PlatformMac.cmake: Ditto.
* WebCore.xcodeproj/project.pbxproj: Ditto.
* loader/FrameLoader.cpp:
(WebCore::FrameLoader::commitProvisionalLoad): Use WebCore::jettisonExpensiveObjectsOnTopLevelNavigation().
* page/MemoryRelease.cpp: Added.
(WebCore::releaseNoncriticalMemory):
(WebCore::releaseCriticalMemory):
(WebCore::releaseMemory):
(WebCore::platformReleaseMemory):
(WebCore::jettisonExpensiveObjectsOnTopLevelNavigation):
(WebCore::registerMemoryReleaseNotifyCallbacks):
* page/MemoryRelease.h: Added.
* page/cocoa/MemoryReleaseCocoa.mm: Added.
(WebCore::platformReleaseMemory):
(WebCore::jettisonExpensiveObjectsOnTopLevelNavigation):
(WebCore::registerMemoryReleaseNotifyCallbacks):
* platform/MemoryPressureHandler.cpp:
(WebCore::MemoryPressureHandler::MemoryPressureHandler):
(WebCore::MemoryPressureHandler::beginSimulatedMemoryPressure):
(WebCore::MemoryPressureHandler::releaseMemory): Use the current handler if it has been set.
(WebCore::MemoryPressureHandler::platformReleaseMemory): Deleted.
* platform/MemoryPressureHandler.h:
(WebCore::MemoryPressureHandler::setLowMemoryHandler):
(WebCore::MemoryPressureHandler::m_releaseMemoryBlock):
* platform/cocoa/MemoryPressureHandlerCocoa.mm:
(WebCore::MemoryPressureHandler::respondToMemoryPressure): Call releaseMemory() instead of using the handler directly.
(WebCore::MemoryPressureHandler::platformReleaseMemory): Deleted.
* platform/linux/MemoryPressureHandlerLinux.cpp:
* platform/win/MemoryPressureHandlerWin.cpp:
(WebCore::MemoryPressureHandler::respondToMemoryPressure): Call releaseMemory() instead of using the handler directly.

Source/WebKit/mac:

Set the low memory handler before installing the memory pressure handler.

* WebView/WebView.mm:
(-[WebView _commonInitializationWithFrameName:groupName:]):

Source/WebKit/win:

Set the low memory handler before installing the memory pressure handler.

* WebView.cpp:
(WebView::initWithFrame):

Source/WebKit2:

Set the low memory handler before installing the memory pressure handler.

* WebProcess/WebProcess.cpp:
(WebKit::WebProcess::initializeWebProcess):
* WebProcess/cocoa/WebProcessCocoa.mm:
(WebKit::WebProcess::platformInitializeWebProcess):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@208534 268f45cc-cd09-0410-ab3c-d52691b4dbfc

20 files changed:
Source/WebCore/CMakeLists.txt
Source/WebCore/ChangeLog
Source/WebCore/PlatformMac.cmake
Source/WebCore/WebCore.xcodeproj/project.pbxproj
Source/WebCore/loader/FrameLoader.cpp
Source/WebCore/page/MemoryRelease.cpp [new file with mode: 0644]
Source/WebCore/page/MemoryRelease.h [new file with mode: 0644]
Source/WebCore/page/cocoa/MemoryReleaseCocoa.mm [new file with mode: 0644]
Source/WebCore/platform/MemoryPressureHandler.cpp
Source/WebCore/platform/MemoryPressureHandler.h
Source/WebCore/platform/cocoa/MemoryPressureHandlerCocoa.mm
Source/WebCore/platform/linux/MemoryPressureHandlerLinux.cpp
Source/WebCore/platform/win/MemoryPressureHandlerWin.cpp
Source/WebKit/mac/ChangeLog
Source/WebKit/mac/WebView/WebView.mm
Source/WebKit/win/ChangeLog
Source/WebKit/win/WebView.cpp
Source/WebKit2/ChangeLog
Source/WebKit2/WebProcess/WebProcess.cpp
Source/WebKit2/WebProcess/cocoa/WebProcessCocoa.mm

index e59da3d..4c7ee06 100644 (file)
@@ -2040,6 +2040,7 @@ set(WebCore_SOURCES
     page/IntersectionObserverEntry.cpp
     page/Location.cpp
     page/MainFrame.cpp
+    page/MemoryRelease.cpp
     page/MouseEventWithHitTestResults.cpp
     page/Navigator.cpp
     page/NavigatorBase.cpp
index e244891..6444060 100644 (file)
@@ -1,3 +1,47 @@
+2016-10-14  Carlos Garcia Campos  <cgarcia@igalia.com>
+
+        MemoryPressureHandler shouldn't know how to release WebCore memory
+        https://bugs.webkit.org/show_bug.cgi?id=160497
+
+        Reviewed by Michael Catanzaro.
+
+        All processes should set their own low memory handler, instead of leaving the web process using the default one
+        that needs to access APIs that are not in platform layer. This patch fixes all the layering violations in the
+        MemoryPressureHandler. Since the default implementation, that releases the WebCore memory, is shared by the
+        WebProcess in WebKit2 and WebKit1 ports, it has been moved to its own file to the WebCore layer.
+
+        * CMakeLists.txt: Add new files to compilation.
+        * PlatformMac.cmake: Ditto.
+        * WebCore.xcodeproj/project.pbxproj: Ditto.
+        * loader/FrameLoader.cpp:
+        (WebCore::FrameLoader::commitProvisionalLoad): Use WebCore::jettisonExpensiveObjectsOnTopLevelNavigation().
+        * page/MemoryRelease.cpp: Added.
+        (WebCore::releaseNoncriticalMemory):
+        (WebCore::releaseCriticalMemory):
+        (WebCore::releaseMemory):
+        (WebCore::platformReleaseMemory):
+        (WebCore::jettisonExpensiveObjectsOnTopLevelNavigation):
+        (WebCore::registerMemoryReleaseNotifyCallbacks):
+        * page/MemoryRelease.h: Added.
+        * page/cocoa/MemoryReleaseCocoa.mm: Added.
+        (WebCore::platformReleaseMemory):
+        (WebCore::jettisonExpensiveObjectsOnTopLevelNavigation):
+        (WebCore::registerMemoryReleaseNotifyCallbacks):
+        * platform/MemoryPressureHandler.cpp:
+        (WebCore::MemoryPressureHandler::MemoryPressureHandler):
+        (WebCore::MemoryPressureHandler::beginSimulatedMemoryPressure):
+        (WebCore::MemoryPressureHandler::releaseMemory): Use the current handler if it has been set.
+        (WebCore::MemoryPressureHandler::platformReleaseMemory): Deleted.
+        * platform/MemoryPressureHandler.h:
+        (WebCore::MemoryPressureHandler::setLowMemoryHandler):
+        (WebCore::MemoryPressureHandler::m_releaseMemoryBlock):
+        * platform/cocoa/MemoryPressureHandlerCocoa.mm:
+        (WebCore::MemoryPressureHandler::respondToMemoryPressure): Call releaseMemory() instead of using the handler directly.
+        (WebCore::MemoryPressureHandler::platformReleaseMemory): Deleted.
+        * platform/linux/MemoryPressureHandlerLinux.cpp:
+        * platform/win/MemoryPressureHandlerWin.cpp:
+        (WebCore::MemoryPressureHandler::respondToMemoryPressure): Call releaseMemory() instead of using the handler directly.
+
 2016-11-08  Sergio Villar Senin  <svillar@igalia.com>
 
         [css-grid] Fix fr tracks sizing under min|max-size constraints
index 1155090..659023d 100644 (file)
@@ -260,6 +260,7 @@ list(APPEND WebCore_SOURCES
     page/CaptionUserPreferencesMediaAF.cpp
     page/PageDebuggable.cpp
 
+    page/cocoa/MemoryReleaseCocoa.mm
     page/cocoa/UserAgent.mm
     page/cocoa/ResourceUsageOverlayCocoa.mm
     page/cocoa/ResourceUsageThreadCocoa.mm
index 8537a2b..06ff7ab 100644 (file)
                4138F8571D253F08001CB61E /* JSDOMIterator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4138F8551D253EEE001CB61E /* JSDOMIterator.cpp */; };
                4138F8581D253F0E001CB61E /* JSDOMIterator.h in Headers */ = {isa = PBXBuildFile; fileRef = 4138F8561D253EEE001CB61E /* JSDOMIterator.h */; settings = {ATTRIBUTES = (Private, ); }; };
                413C2C341BC29A8F0075204C /* JSDOMConstructor.h in Headers */ = {isa = PBXBuildFile; fileRef = 413C2C331BC29A7B0075204C /* JSDOMConstructor.h */; };
+               413E00791DB0E4F2002341D2 /* MemoryRelease.h in Headers */ = {isa = PBXBuildFile; fileRef = 413E00781DB0E4DE002341D2 /* MemoryRelease.h */; settings = {ATTRIBUTES = (Private, ); }; };
+               413E007A1DB0E4F9002341D2 /* MemoryRelease.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 413E00771DB0E4DE002341D2 /* MemoryRelease.cpp */; };
+               413E007C1DB0E70A002341D2 /* MemoryReleaseCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 413E007B1DB0E707002341D2 /* MemoryReleaseCocoa.mm */; };
                4147E2B71C89912C00A7E715 /* FetchLoader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4147E2B41C89912600A7E715 /* FetchLoader.cpp */; };
                4147E2B81C89912F00A7E715 /* FetchBodyOwner.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4147E2B31C89912600A7E715 /* FetchBodyOwner.cpp */; };
                414B82041D6DF0DF0077EBE3 /* StructuredClone.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 414B82021D6DF0D90077EBE3 /* StructuredClone.cpp */; };
                4138F8551D253EEE001CB61E /* JSDOMIterator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSDOMIterator.cpp; sourceTree = "<group>"; };
                4138F8561D253EEE001CB61E /* JSDOMIterator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSDOMIterator.h; sourceTree = "<group>"; };
                413C2C331BC29A7B0075204C /* JSDOMConstructor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSDOMConstructor.h; sourceTree = "<group>"; };
+               413E00771DB0E4DE002341D2 /* MemoryRelease.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MemoryRelease.cpp; sourceTree = "<group>"; };
+               413E00781DB0E4DE002341D2 /* MemoryRelease.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MemoryRelease.h; sourceTree = "<group>"; };
+               413E007B1DB0E707002341D2 /* MemoryReleaseCocoa.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MemoryReleaseCocoa.mm; sourceTree = "<group>"; };
                4147E2B21C88337F00A7E715 /* FetchBodyOwner.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FetchBodyOwner.h; sourceTree = "<group>"; };
                4147E2B31C89912600A7E715 /* FetchBodyOwner.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FetchBodyOwner.cpp; sourceTree = "<group>"; };
                4147E2B41C89912600A7E715 /* FetchLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FetchLoader.cpp; sourceTree = "<group>"; };
                5D5975B5196362BE00D00878 /* cocoa */ = {
                        isa = PBXGroup;
                        children = (
+                               413E007B1DB0E707002341D2 /* MemoryReleaseCocoa.mm */,
                                ADFE2B541BD5F41200DAB457 /* ResourceUsageOverlayCocoa.mm */,
                                A5071E881C56D4FA009951BE /* ResourceUsageThreadCocoa.mm */,
                                A182D5B61BE722620087A7CC /* SettingsCocoa.mm */,
                                BC59DEFA169DEDD80016AC34 /* make_settings.pl */,
                                931BCC601124DFCB00BE70DD /* MediaCanStartListener.h */,
                                52E2CAFB19FF0207001EEB4F /* MediaProducer.h */,
+                               413E00771DB0E4DE002341D2 /* MemoryRelease.cpp */,
+                               413E00781DB0E4DE002341D2 /* MemoryRelease.h */,
                                93EB355E09E37FD600F43799 /* MouseEventWithHitTestResults.cpp */,
                                935C476209AC4CE600A6AAB4 /* MouseEventWithHitTestResults.h */,
                                A9C6E5A30D746458006442E9 /* Navigator.cpp */,
                                84730D891248F0B300D3A9C9 /* FESpecularLighting.h in Headers */,
                                416E6FE81BBD12DF000A6023 /* FetchInternalsBuiltins.h in Headers */,
                                41AD753A1CEF6BD100A31486 /* FetchOptions.h in Headers */,
+                               413E00791DB0E4F2002341D2 /* MemoryRelease.h in Headers */,
                                84730D8B1248F0B300D3A9C9 /* FETile.h in Headers */,
                                84730D8D1248F0B300D3A9C9 /* FETurbulence.h in Headers */,
                                FD31609512B026F700C1A359 /* FFTConvolver.h in Headers */,
                                CDE8B5EC1A69777300B4B66A /* CDMPrivateClearKey.cpp in Sources */,
                                CDCA98EB18B2C8EB00C12FF9 /* CDMPrivateMediaPlayer.cpp in Sources */,
                                CD318622199F1E2A0030A0F7 /* CDMPrivateMediaSourceAVFObjC.mm in Sources */,
+                               413E007C1DB0E70A002341D2 /* MemoryReleaseCocoa.mm in Sources */,
                                CDE595951BF16DF300A1CBE8 /* CDMSessionAVContentKeySession.mm in Sources */,
                                CDDE02ED18B3ED6D00CF7FF1 /* CDMSessionAVFoundationObjC.mm in Sources */,
                                CDDE02F018B5651300CF7FF1 /* CDMSessionAVStreamSession.mm in Sources */,
                                078E090317D14CEE00420AA1 /* MediaStreamTrackEvent.cpp in Sources */,
                                07FFDE68181AED420072D409 /* MediaStreamTrackPrivate.cpp in Sources */,
                                CD641EBF1819B36000EE4C41 /* MediaTimeAVFoundation.cpp in Sources */,
+                               413E007A1DB0E4F9002341D2 /* MemoryRelease.cpp in Sources */,
                                CD60C0C6193E87C7003C656B /* MediaTimeQTKit.mm in Sources */,
                                0705853A17FE0770005F2BCB /* MediaTrackConstraint.cpp in Sources */,
                                0705852317FDC140005F2BCB /* MediaTrackConstraints.cpp in Sources */,
index ff9c21d..01946c6 100644 (file)
@@ -85,6 +85,7 @@
 #include "MIMETypeRegistry.h"
 #include "MainFrame.h"
 #include "MemoryCache.h"
+#include "MemoryRelease.h"
 #include "Page.h"
 #include "PageCache.h"
 #include "PageTransitionEvent.h"
 
 #if PLATFORM(IOS)
 #include "DocumentType.h"
-#include "MemoryPressureHandler.h"
 #include "ResourceLoader.h"
 #include "RuntimeApplicationChecks.h"
 #include "SystemMemory.h"
@@ -1775,7 +1775,7 @@ void FrameLoader::commitProvisionalLoad()
         // We are doing this here because we know for sure that a new page is about to be loaded.
         PageCache::singleton().addIfCacheable(*history().currentItem(), m_frame.page());
         
-        MemoryPressureHandler::singleton().jettisonExpensiveObjectsOnTopLevelNavigation();
+        WebCore::jettisonExpensiveObjectsOnTopLevelNavigation();
     }
 
     if (m_loadType != FrameLoadType::Replace)
diff --git a/Source/WebCore/page/MemoryRelease.cpp b/Source/WebCore/page/MemoryRelease.cpp
new file mode 100644 (file)
index 0000000..3f8b5c9
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2011, 2014 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "MemoryRelease.h"
+
+#include "CSSValuePool.h"
+#include "Chrome.h"
+#include "ChromeClient.h"
+#include "Document.h"
+#include "FontCache.h"
+#include "GCController.h"
+#include "HTMLMediaElement.h"
+#include "InlineStyleSheetOwner.h"
+#include "InspectorInstrumentation.h"
+#include "MemoryCache.h"
+#include "Page.h"
+#include "PageCache.h"
+#include "ScrollingThread.h"
+#include "StyleScope.h"
+#include "StyledElement.h"
+#include "WorkerThread.h"
+#include <wtf/FastMalloc.h>
+
+namespace WebCore {
+
+static void releaseNoncriticalMemory()
+{
+    {
+        MemoryPressureHandler::ReliefLogger log("Purge inactive FontData");
+        FontCache::singleton().purgeInactiveFontData();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Clear WidthCaches");
+        clearWidthCaches();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Discard Selector Query Cache");
+        for (auto* document : Document::allDocuments())
+            document->clearSelectorQueryCache();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Prune MemoryCache dead resources");
+        MemoryCache::singleton().pruneDeadResourcesToSize(0);
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Prune presentation attribute cache");
+        StyledElement::clearPresentationAttributeCache();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Clear inline stylesheet cache");
+        InlineStyleSheetOwner::clearCache();
+    }
+}
+
+static void releaseCriticalMemory(Synchronous synchronous)
+{
+    {
+        MemoryPressureHandler::ReliefLogger log("Empty the PageCache");
+        // Right now, the only reason we call release critical memory while not under memory pressure is if the process is about to be suspended.
+        PruningReason pruningReason = MemoryPressureHandler::singleton().isUnderMemoryPressure() ? PruningReason::MemoryPressure : PruningReason::ProcessSuspended;
+        PageCache::singleton().pruneToSizeNow(0, pruningReason);
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Prune MemoryCache live resources");
+        MemoryCache::singleton().pruneLiveResourcesToSize(0, /*shouldDestroyDecodedDataForAllLiveResources*/ true);
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Drain CSSValuePool");
+        CSSValuePool::singleton().drain();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Discard StyleResolvers");
+        Vector<RefPtr<Document>> documents;
+        copyToVector(Document::allDocuments(), documents);
+        for (auto& document : documents)
+            document->styleScope().clearResolver();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Discard all JIT-compiled code");
+        GCController::singleton().deleteAllCode();
+    }
+
+#if ENABLE(VIDEO)
+    {
+        MemoryPressureHandler::ReliefLogger log("Dropping buffered data from paused media elements");
+        for (auto* mediaElement : HTMLMediaElement::allMediaElements()) {
+            if (mediaElement->paused())
+                mediaElement->purgeBufferedDataIfPossible();
+        }
+    }
+#endif
+
+    if (synchronous == Synchronous::Yes) {
+        MemoryPressureHandler::ReliefLogger log("Collecting JavaScript garbage");
+        GCController::singleton().garbageCollectNow();
+    } else
+        GCController::singleton().garbageCollectNowIfNotDoneRecently();
+
+    // We reduce tiling coverage while under memory pressure, so make sure to drop excess tiles ASAP.
+    Page::forEachPage([](Page& page) {
+        page.chrome().client().scheduleCompositingLayerFlush();
+    });
+}
+
+void releaseMemory(Critical critical, Synchronous synchronous)
+{
+    if (critical == Critical::Yes)
+        releaseCriticalMemory(synchronous);
+
+    releaseNoncriticalMemory();
+
+    platformReleaseMemory(critical);
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Release free FastMalloc memory");
+        // FastMalloc has lock-free thread specific caches that can only be cleared from the thread itself.
+        WorkerThread::releaseFastMallocFreeMemoryInAllThreads();
+#if ENABLE(ASYNC_SCROLLING) && !PLATFORM(IOS)
+        ScrollingThread::dispatch([]() {
+            WTF::releaseFastMallocFreeMemory();
+        });
+#endif
+        WTF::releaseFastMallocFreeMemory();
+    }
+
+#if ENABLE(RESOURCE_USAGE)
+    Page::forEachPage([&](Page& page) {
+        InspectorInstrumentation::didHandleMemoryPressure(page, critical);
+    });
+#endif
+}
+
+#if !PLATFORM(COCOA)
+void platformReleaseMemory(Critical) { }
+void jettisonExpensiveObjectsOnTopLevelNavigation() { }
+void registerMemoryReleaseNotifyCallbacks() { }
+#endif
+
+} // namespace WebCore
diff --git a/Source/WebCore/page/MemoryRelease.h b/Source/WebCore/page/MemoryRelease.h
new file mode 100644 (file)
index 0000000..1d99372
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2016 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include "MemoryPressureHandler.h"
+
+namespace WebCore {
+
+WEBCORE_EXPORT void releaseMemory(Critical, Synchronous);
+void platformReleaseMemory(Critical);
+void jettisonExpensiveObjectsOnTopLevelNavigation();
+WEBCORE_EXPORT void registerMemoryReleaseNotifyCallbacks();
+
+} // namespace WebCore
diff --git a/Source/WebCore/page/cocoa/MemoryReleaseCocoa.mm b/Source/WebCore/page/cocoa/MemoryReleaseCocoa.mm
new file mode 100644 (file)
index 0000000..2135b72
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2011-2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "MemoryRelease.h"
+
+#import "GCController.h"
+#import "IOSurfacePool.h"
+#import "LayerPool.h"
+#import <notify.h>
+
+extern "C" void _sqlite3_purgeEligiblePagerCacheMemory(void);
+
+namespace WebCore {
+
+void platformReleaseMemory(Critical)
+{
+    {
+        MemoryPressureHandler::ReliefLogger log("Purging SQLite caches");
+        _sqlite3_purgeEligiblePagerCacheMemory();
+    }
+
+    {
+        MemoryPressureHandler::ReliefLogger log("Drain LayerPools");
+        for (auto& pool : LayerPool::allLayerPools())
+            pool->drain();
+    }
+#if USE(IOSURFACE)
+    {
+        MemoryPressureHandler::ReliefLogger log("Drain IOSurfacePool");
+        IOSurfacePool::sharedPool().discardAllSurfaces();
+    }
+#endif
+}
+
+void jettisonExpensiveObjectsOnTopLevelNavigation()
+{
+#if PLATFORM(IOS)
+    // Protect against doing excessive jettisoning during repeated navigations.
+    const auto minimumTimeSinceNavigation = 2s;
+
+    static auto timeOfLastNavigation = std::chrono::steady_clock::now();
+    auto now = std::chrono::steady_clock::now();
+    bool shouldJettison = now - timeOfLastNavigation >= minimumTimeSinceNavigation;
+    timeOfLastNavigation = now;
+
+    if (!shouldJettison)
+        return;
+
+    // Throw away linked JS code. Linked code is tied to a global object and is not reusable.
+    // The immediate memory savings outweigh the cost of recompilation in case we go back again.
+    GCController::singleton().deleteAllLinkedCode();
+#endif
+}
+
+void registerMemoryReleaseNotifyCallbacks()
+{
+    static std::once_flag onceFlag;
+    std::call_once(onceFlag, [] {
+        int dummy;
+        notify_register_dispatch("com.apple.WebKit.fullGC", &dummy, dispatch_get_main_queue(), ^(int) {
+            GCController::singleton().garbageCollectNow();
+        });
+        notify_register_dispatch("com.apple.WebKit.deleteAllCode", &dummy, dispatch_get_main_queue(), ^(int) {
+            GCController::singleton().deleteAllCode();
+            GCController::singleton().garbageCollectNow();
+        });
+    });
+}
+
+} // namespace WebCore
index ad7f7f6..95ac3f2 100644 (file)
 #include "config.h"
 #include "MemoryPressureHandler.h"
 
-#include "CSSValuePool.h"
-#include "Chrome.h"
-#include "ChromeClient.h"
-#include "Document.h"
-#include "FontCache.h"
-#include "GCController.h"
-#include "HTMLMediaElement.h"
-#include "InlineStyleSheetOwner.h"
-#include "InspectorInstrumentation.h"
 #include "Logging.h"
-#include "MemoryCache.h"
-#include "Page.h"
-#include "PageCache.h"
-#include "ScrollingThread.h"
-#include "StyleScope.h"
-#include "StyledElement.h"
-#include "WorkerThread.h"
-#include <JavaScriptCore/IncrementalSweeper.h>
-#include <chrono>
-#include <wtf/CurrentTime.h>
-#include <wtf/FastMalloc.h>
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
@@ -59,136 +38,17 @@ MemoryPressureHandler& MemoryPressureHandler::singleton()
     return memoryPressureHandler;
 }
 
-MemoryPressureHandler::MemoryPressureHandler() 
-    : m_installed(false)
-    , m_lastRespondTime(0)
-    , m_lowMemoryHandler([this] (Critical critical, Synchronous synchronous) { releaseMemory(critical, synchronous); })
-    , m_underMemoryPressure(false)
-#if PLATFORM(IOS)
-    // FIXME: Can we share more of this with OpenSource?
-    , m_memoryPressureReason(MemoryPressureReasonNone)
-    , m_clearPressureOnMemoryRelease(true)
-    , m_releaseMemoryBlock(0)
-    , m_observer(0)
-#elif OS(LINUX)
-    , m_holdOffTimer(RunLoop::main(), this, &MemoryPressureHandler::holdOffTimerFired)
+MemoryPressureHandler::MemoryPressureHandler()
+#if OS(LINUX)
+    : m_holdOffTimer(RunLoop::main(), this, &MemoryPressureHandler::holdOffTimerFired)
 #endif
 {
-    platformInitialize();
-}
-
-void MemoryPressureHandler::releaseNoncriticalMemory()
-{
-    {
-        ReliefLogger log("Purge inactive FontData");
-        FontCache::singleton().purgeInactiveFontData();
-    }
-
-    {
-        ReliefLogger log("Clear WidthCaches");
-        clearWidthCaches();
-    }
-
-    {
-        ReliefLogger log("Discard Selector Query Cache");
-        for (auto* document : Document::allDocuments())
-            document->clearSelectorQueryCache();
-    }
-
-    {
-        ReliefLogger log("Prune MemoryCache dead resources");
-        MemoryCache::singleton().pruneDeadResourcesToSize(0);
-    }
-
-    {
-        ReliefLogger log("Prune presentation attribute cache");
-        StyledElement::clearPresentationAttributeCache();
-    }
-
-    {
-        ReliefLogger log("Clear inline stylesheet cache");
-        InlineStyleSheetOwner::clearCache();
-    }
-}
-
-void MemoryPressureHandler::releaseCriticalMemory(Synchronous synchronous)
-{
-    {
-        ReliefLogger log("Empty the PageCache");
-        // Right now, the only reason we call release critical memory while not under memory pressure is if the process is about to be suspended.
-        PruningReason pruningReason = isUnderMemoryPressure() ? PruningReason::MemoryPressure : PruningReason::ProcessSuspended;
-        PageCache::singleton().pruneToSizeNow(0, pruningReason);
-    }
-
-    {
-        ReliefLogger log("Prune MemoryCache live resources");
-        MemoryCache::singleton().pruneLiveResourcesToSize(0, /*shouldDestroyDecodedDataForAllLiveResources*/ true);
-    }
-
-    {
-        ReliefLogger log("Drain CSSValuePool");
-        CSSValuePool::singleton().drain();
-    }
-
-    {
-        ReliefLogger log("Discard StyleResolvers");
-        Vector<RefPtr<Document>> documents;
-        copyToVector(Document::allDocuments(), documents);
-        for (auto& document : documents)
-            document->styleScope().clearResolver();
-    }
-
-    {
-        ReliefLogger log("Discard all JIT-compiled code");
-        GCController::singleton().deleteAllCode();
-    }
-
-#if ENABLE(VIDEO)
-    {
-        ReliefLogger log("Dropping buffered data from paused media elements");
-        for (auto* mediaElement: HTMLMediaElement::allMediaElements()) {
-            if (mediaElement->paused())
-                mediaElement->purgeBufferedDataIfPossible();
-        }
-    }
-#endif
-
-    if (synchronous == Synchronous::Yes) {
-        ReliefLogger log("Collecting JavaScript garbage");
-        GCController::singleton().garbageCollectNow();
-    } else
-        GCController::singleton().garbageCollectNowIfNotDoneRecently();
-
-    // We reduce tiling coverage while under memory pressure, so make sure to drop excess tiles ASAP.
-    Page::forEachPage([](Page& page) {
-        page.chrome().client().scheduleCompositingLayerFlush();
-    });
-}
-
-void MemoryPressureHandler::jettisonExpensiveObjectsOnTopLevelNavigation()
-{
-#if PLATFORM(IOS)
-    // Protect against doing excessive jettisoning during repeated navigations.
-    const auto minimumTimeSinceNavigation = 2s;
-
-    static auto timeOfLastNavigation = std::chrono::steady_clock::now();
-    auto now = std::chrono::steady_clock::now();
-    bool shouldJettison = now - timeOfLastNavigation >= minimumTimeSinceNavigation;
-    timeOfLastNavigation = now;
-
-    if (!shouldJettison)
-        return;
-
-    // Throw away linked JS code. Linked code is tied to a global object and is not reusable.
-    // The immediate memory savings outweigh the cost of recompilation in case we go back again.
-    GCController::singleton().deleteAllLinkedCode();
-#endif
 }
 
 void MemoryPressureHandler::beginSimulatedMemoryPressure()
 {
     m_isSimulatingMemoryPressure = true;
-    MemoryPressureHandler::singleton().respondToMemoryPressure(Critical::Yes, Synchronous::Yes);
+    respondToMemoryPressure(Critical::Yes, Synchronous::Yes);
 }
 
 void MemoryPressureHandler::endSimulatedMemoryPressure()
@@ -198,30 +58,11 @@ void MemoryPressureHandler::endSimulatedMemoryPressure()
 
 void MemoryPressureHandler::releaseMemory(Critical critical, Synchronous synchronous)
 {
-    if (critical == Critical::Yes)
-        releaseCriticalMemory(synchronous);
-
-    releaseNoncriticalMemory();
+    if (!m_lowMemoryHandler)
+        return;
 
+    m_lowMemoryHandler(critical, synchronous);
     platformReleaseMemory(critical);
-
-    {
-        ReliefLogger log("Release free FastMalloc memory");
-        // FastMalloc has lock-free thread specific caches that can only be cleared from the thread itself.
-        WorkerThread::releaseFastMallocFreeMemoryInAllThreads();
-#if ENABLE(ASYNC_SCROLLING) && !PLATFORM(IOS)
-        ScrollingThread::dispatch([]() {
-            WTF::releaseFastMallocFreeMemory();
-        });
-#endif
-        WTF::releaseFastMallocFreeMemory();
-    }
-
-#if ENABLE(RESOURCE_USAGE)
-    Page::forEachPage([&](Page& page) {
-        InspectorInstrumentation::didHandleMemoryPressure(page, critical);
-    });
-#endif
 }
 
 void MemoryPressureHandler::ReliefLogger::logMemoryUsageChange()
@@ -249,10 +90,6 @@ void MemoryPressureHandler::ReliefLogger::logMemoryUsageChange()
         MEMORYPRESSURE_LOG("Memory pressure relief: " STRING_SPECIFICATION ": =dirty (at %zu bytes)", m_logString, currentMemory);
 }
 
-#if !PLATFORM(COCOA)
-void MemoryPressureHandler::platformInitialize() { }
-#endif
-
 #if !PLATFORM(COCOA) && !OS(LINUX) && !PLATFORM(WIN)
 void MemoryPressureHandler::install() { }
 void MemoryPressureHandler::uninstall() { }
index 64608de..b2ecef4 100644 (file)
@@ -32,6 +32,7 @@
 #include <functional>
 #include <wtf/FastMalloc.h>
 #include <wtf/Forward.h>
+#include <wtf/NeverDestroyed.h>
 
 #if PLATFORM(IOS)
 #include <wtf/Lock.h>
@@ -66,14 +67,12 @@ public:
 
     WEBCORE_EXPORT void install();
 
-    void setLowMemoryHandler(LowMemoryHandler handler)
+    void setLowMemoryHandler(LowMemoryHandler&& handler)
     {
         ASSERT(!m_installed);
-        m_lowMemoryHandler = handler;
+        m_lowMemoryHandler = WTFMove(handler);
     }
 
-    void jettisonExpensiveObjectsOnTopLevelNavigation();
-
     bool isUnderMemoryPressure() const { return m_underMemoryPressure || m_isSimulatingMemoryPressure; }
     void setUnderMemoryPressure(bool b) { m_underMemoryPressure = b; }
 
@@ -130,10 +129,6 @@ public:
     WEBCORE_EXPORT void endSimulatedMemoryPressure();
 
 private:
-    void platformInitialize();
-    void releaseNoncriticalMemory();
-    void releaseCriticalMemory(Synchronous);
-
     void uninstall();
 
     void holdOff(unsigned);
@@ -164,18 +159,19 @@ private:
     };
 #endif
 
-    bool m_installed;
-    time_t m_lastRespondTime;
+    bool m_installed { false };
+    time_t m_lastRespondTime { 0 };
     LowMemoryHandler m_lowMemoryHandler;
 
     std::atomic<bool> m_underMemoryPressure;
     bool m_isSimulatingMemoryPressure { false };
 
 #if PLATFORM(IOS)
-    uint32_t m_memoryPressureReason;
-    bool m_clearPressureOnMemoryRelease;
-    void (^m_releaseMemoryBlock)();
-    CFRunLoopObserverRef m_observer;
+    // FIXME: Can we share more of this with OpenSource?
+    uint32_t m_memoryPressureReason { MemoryPressureReasonNone };
+    bool m_clearPressureOnMemoryRelease { true };
+    void (^m_releaseMemoryBlock)() { nullptr };
+    CFRunLoopObserverRef m_observer { nullptr };
     Lock m_observerMutex;
 #elif OS(LINUX)
     Optional<int> m_eventFD;
index 2f2e005..252728b 100644 (file)
 #import "config.h"
 #import "MemoryPressureHandler.h"
 
-#import "GCController.h"
-#import "IOSurfacePool.h"
-#import "LayerPool.h"
 #import "Logging.h"
-#import "ResourceUsageThread.h"
 #import <mach/mach.h>
 #import <mach/task_info.h>
 #import <malloc/malloc.h>
 #import <notify.h>
+#import <wtf/CurrentTime.h>
 
 #if PLATFORM(IOS)
 #import "SystemMemory.h"
 #define ENABLE_FMW_FOOTPRINT_COMPARISON 0
 
 extern "C" void cache_simulate_memory_warning_event(uint64_t);
-extern "C" void _sqlite3_purgeEligiblePagerCacheMemory(void);
 
 namespace WebCore {
 
-void MemoryPressureHandler::platformInitialize()
-{
-    int dummy;
-    notify_register_dispatch("com.apple.WebKit.fullGC", &dummy, dispatch_get_main_queue(), ^(int) {
-        GCController::singleton().garbageCollectNow();
-    });
-    notify_register_dispatch("com.apple.WebKit.deleteAllCode", &dummy, dispatch_get_main_queue(), ^(int) {
-        GCController::singleton().deleteAllCode();
-        GCController::singleton().garbageCollectNow();
-    });
-}
-
 void MemoryPressureHandler::platformReleaseMemory(Critical critical)
 {
-    {
-        ReliefLogger log("Purging SQLite caches");
-        _sqlite3_purgeEligiblePagerCacheMemory();
-    }
-
-    {
-        ReliefLogger log("Drain LayerPools");
-        for (auto& pool : LayerPool::allLayerPools())
-            pool->drain();
-    }
-#if USE(IOSURFACE)
-    {
-        ReliefLogger log("Drain IOSurfacePool");
-        IOSurfacePool::sharedPool().discardAllSurfaces();
-    }
-#endif
-
     if (critical == Critical::Yes && (!isUnderMemoryPressure() || m_isSimulatingMemoryPressure)) {
         // libcache listens to OS memory notifications, but for process suspension
         // or memory pressure simulation, we need to prod it manually:
@@ -211,7 +178,7 @@ void MemoryPressureHandler::respondToMemoryPressure(Critical critical, Synchrono
     double startTime = monotonicallyIncreasingTime();
 #endif
 
-    m_lowMemoryHandler(critical, synchronous);
+    releaseMemory(critical, synchronous);
 
 #if !PLATFORM(IOS)
     unsigned holdOffTime = (monotonicallyIncreasingTime() - startTime) * s_holdOffMultiplier;
index 90cf640..c2d4929 100644 (file)
@@ -298,7 +298,7 @@ void MemoryPressureHandler::respondToMemoryPressure(Critical critical, Synchrono
     uninstall();
 
     double startTime = monotonicallyIncreasingTime();
-    m_lowMemoryHandler(critical, synchronous);
+    releaseMemory(critical, synchronous);
     unsigned holdOffTime = (monotonicallyIncreasingTime() - startTime) * s_holdOffMultiplier;
     holdOff(std::max(holdOffTime, s_minimumHoldOffTime));
 }
index dc97c73..78761a7 100644 (file)
@@ -120,7 +120,7 @@ void MemoryPressureHandler::respondToMemoryPressure(Critical critical, Synchrono
 {
     uninstall();
 
-    m_lowMemoryHandler(critical, synchronous);
+    releaseMemory(critical, synchronous);
 }
 
 size_t MemoryPressureHandler::ReliefLogger::platformMemoryUsage()
index 4686646..eced9e4 100644 (file)
@@ -1,3 +1,15 @@
+2016-10-14  Carlos Garcia Campos  <cgarcia@igalia.com>
+
+        MemoryPressureHandler shouldn't know how to release WebCore memory
+        https://bugs.webkit.org/show_bug.cgi?id=160497
+
+        Reviewed by Michael Catanzaro.
+
+        Set the low memory handler before installing the memory pressure handler.
+
+        * WebView/WebView.mm:
+        (-[WebView _commonInitializationWithFrameName:groupName:]):
+
 2016-11-09  Ryosuke Niwa  <rniwa@webkit.org>
 
         WebHTMLView's _attributeStringFromDOMRange should use HTMLConverter instead of NSAttributedString's _initWithDOMRange
index 7e09065..1f388a6 100644 (file)
 #import <WebCore/MIMETypeRegistry.h>
 #import <WebCore/MainFrame.h>
 #import <WebCore/MemoryCache.h>
-#import <WebCore/MemoryPressureHandler.h>
+#import <WebCore/MemoryRelease.h>
 #import <WebCore/NSSpellCheckerSPI.h>
 #import <WebCore/NSTouchBarSPI.h>
 #import <WebCore/NSURLFileTypeMappingsSPI.h>
@@ -1430,8 +1430,18 @@ static void WebKitInitializeGamepadProviderIfNecessary()
     _private->page->settings().setFontFallbackPrefersPictographs(true);
 #endif
 
-    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitSuppressMemoryPressureHandler"])
-        MemoryPressureHandler::singleton().install();
+    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitSuppressMemoryPressureHandler"]) {
+        WebCore::registerMemoryReleaseNotifyCallbacks();
+
+        static std::once_flag onceFlag;
+        std::call_once(onceFlag, [] {
+            auto& memoryPressureHandler = MemoryPressureHandler::singleton();
+            memoryPressureHandler.setLowMemoryHandler([] (Critical critical, Synchronous synchronous) {
+                WebCore::releaseMemory(critical, synchronous);
+            });
+            memoryPressureHandler.install();
+        });
+    }
 
     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
         // Originally, we allowed all local loads.
index 90adef8..8fdaaae 100644 (file)
@@ -1,3 +1,15 @@
+2016-10-14  Carlos Garcia Campos  <cgarcia@igalia.com>
+
+        MemoryPressureHandler shouldn't know how to release WebCore memory
+        https://bugs.webkit.org/show_bug.cgi?id=160497
+
+        Reviewed by Michael Catanzaro.
+
+        Set the low memory handler before installing the memory pressure handler.
+
+        * WebView.cpp:
+        (WebView::initWithFrame):
+
 2016-11-09  Alex Christensen  <achristensen@webkit.org>
 
         Fix Windows build after r208499
index dd4e353..8e8dc7e 100644 (file)
 #include <WebCore/MIMETypeRegistry.h>
 #include <WebCore/MainFrame.h>
 #include <WebCore/MemoryCache.h>
-#include <WebCore/MemoryPressureHandler.h>
+#include <WebCore/MemoryRelease.h>
 #include <WebCore/NotImplemented.h>
 #include <WebCore/Page.h>
 #include <WebCore/PageCache.h>
@@ -3084,7 +3084,11 @@ HRESULT WebView::initWithFrame(RECT frame, _In_ BSTR frameName, _In_ BSTR groupN
 
         WebKitInitializeWebDatabasesIfNecessary();
 
-        MemoryPressureHandler::singleton().install();
+        auto& memoryPressureHandler = MemoryPressureHandler::singleton();
+        memoryPressureHandler.setLowMemoryHandler([] (Critical critical, Synchronous synchronous) {
+            WebCore::releaseMemory(critical, synchronous);
+        });
+        memoryPressureHandler.install();
 
         didOneTimeInitialization = true;
      }
index 77dbb72..0bb5e29 100644 (file)
@@ -1,3 +1,17 @@
+2016-10-14  Carlos Garcia Campos  <cgarcia@igalia.com>
+
+        MemoryPressureHandler shouldn't know how to release WebCore memory
+        https://bugs.webkit.org/show_bug.cgi?id=160497
+
+        Reviewed by Michael Catanzaro.
+
+        Set the low memory handler before installing the memory pressure handler.
+
+        * WebProcess/WebProcess.cpp:
+        (WebKit::WebProcess::initializeWebProcess):
+        * WebProcess/cocoa/WebProcessCocoa.mm:
+        (WebKit::WebProcess::platformInitializeWebProcess):
+
 2016-10-27  Sergio Villar Senin  <svillar@igalia.com>
 
         [GTK] New API to notify about dynamically added forms
index 7ddd2f1..87c2c5d 100644 (file)
@@ -88,7 +88,7 @@
 #include <WebCore/Language.h>
 #include <WebCore/MainFrame.h>
 #include <WebCore/MemoryCache.h>
-#include <WebCore/MemoryPressureHandler.h>
+#include <WebCore/MemoryRelease.h>
 #include <WebCore/NetworkStorageSession.h>
 #include <WebCore/Page.h>
 #include <WebCore/PageCache.h>
@@ -273,8 +273,13 @@ void WebProcess::initializeWebProcess(WebProcessCreationParameters&& parameters)
     WTF::setCurrentThreadIsUserInteractive(-1);
 
     m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
-    if (!m_suppressMemoryPressureHandler)
-        MemoryPressureHandler::singleton().install();
+    if (!m_suppressMemoryPressureHandler) {
+        auto& memoryPressureHandler = MemoryPressureHandler::singleton();
+        memoryPressureHandler.setLowMemoryHandler([] (Critical critical, Synchronous synchronous) {
+            WebCore::releaseMemory(critical, synchronous);
+        });
+        memoryPressureHandler.install();
+    }
 
     if (!parameters.injectedBundlePath.isEmpty())
         m_injectedBundle = InjectedBundle::create(parameters, transformHandlesToObjects(parameters.initializationUserData.object()).get());
index 0a60493..a48a2f4 100644 (file)
@@ -49,7 +49,7 @@
 #import <WebCore/FontCache.h>
 #import <WebCore/FontCascade.h>
 #import <WebCore/LocalizedStrings.h>
-#import <WebCore/MemoryPressureHandler.h>
+#import <WebCore/MemoryRelease.h>
 #import <WebCore/NSAccessibilitySPI.h>
 #import <WebCore/RuntimeApplicationChecks.h>
 #import <WebCore/VNodeTracker.h>
@@ -120,6 +120,7 @@ void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& par
     m_compositingRenderServerPort = WTFMove(parameters.acceleratedCompositingPort);
     m_presenterApplicationPid = parameters.presenterApplicationPid;
 
+    WebCore::registerMemoryReleaseNotifyCallbacks();
     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
 
 #if PLATFORM(IOS)