Title: [208534] trunk/Source
Revision
208534
Author
carlo...@webkit.org
Date
2016-11-10 06:24:26 -0800 (Thu, 10 Nov 2016)

Log Message

MemoryPressureHandler shouldn't know how to release WebCore memory
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):

Modified Paths

Added Paths

Diff

Modified: trunk/Source/WebCore/CMakeLists.txt (208533 => 208534)


--- trunk/Source/WebCore/CMakeLists.txt	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/CMakeLists.txt	2016-11-10 14:24:26 UTC (rev 208534)
@@ -2040,6 +2040,7 @@
     page/IntersectionObserverEntry.cpp
     page/Location.cpp
     page/MainFrame.cpp
+    page/MemoryRelease.cpp
     page/MouseEventWithHitTestResults.cpp
     page/Navigator.cpp
     page/NavigatorBase.cpp

Modified: trunk/Source/WebCore/ChangeLog (208533 => 208534)


--- trunk/Source/WebCore/ChangeLog	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/ChangeLog	2016-11-10 14:24:26 UTC (rev 208534)
@@ -1,3 +1,47 @@
+2016-10-14  Carlos Garcia Campos  <cgar...@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  <svil...@igalia.com>
 
         [css-grid] Fix fr tracks sizing under min|max-size constraints

Modified: trunk/Source/WebCore/PlatformMac.cmake (208533 => 208534)


--- trunk/Source/WebCore/PlatformMac.cmake	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/PlatformMac.cmake	2016-11-10 14:24:26 UTC (rev 208534)
@@ -260,6 +260,7 @@
     page/CaptionUserPreferencesMediaAF.cpp
     page/PageDebuggable.cpp
 
+    page/cocoa/MemoryReleaseCocoa.mm
     page/cocoa/UserAgent.mm
     page/cocoa/ResourceUsageOverlayCocoa.mm
     page/cocoa/ResourceUsageThreadCocoa.mm

Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (208533 => 208534)


--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2016-11-10 14:24:26 UTC (rev 208534)
@@ -1545,6 +1545,9 @@
 		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 */; };
@@ -8604,6 +8607,9 @@
 		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>"; };
@@ -17182,6 +17188,7 @@
 		5D5975B5196362BE00D00878 /* cocoa */ = {
 			isa = PBXGroup;
 			children = (
+				413E007B1DB0E707002341D2 /* MemoryReleaseCocoa.mm */,
 				ADFE2B541BD5F41200DAB457 /* ResourceUsageOverlayCocoa.mm */,
 				A5071E881C56D4FA009951BE /* ResourceUsageThreadCocoa.mm */,
 				A182D5B61BE722620087A7CC /* SettingsCocoa.mm */,
@@ -17738,6 +17745,8 @@
 				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 */,
@@ -25229,6 +25238,7 @@
 				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 */,
@@ -28540,6 +28550,7 @@
 				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 */,
@@ -30274,6 +30285,7 @@
 				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 */,

Modified: trunk/Source/WebCore/loader/FrameLoader.cpp (208533 => 208534)


--- trunk/Source/WebCore/loader/FrameLoader.cpp	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/loader/FrameLoader.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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"
@@ -133,7 +134,6 @@
 
 #if PLATFORM(IOS)
 #include "DocumentType.h"
-#include "MemoryPressureHandler.h"
 #include "ResourceLoader.h"
 #include "RuntimeApplicationChecks.h"
 #include "SystemMemory.h"
@@ -1775,7 +1775,7 @@
         // 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)

Added: trunk/Source/WebCore/page/MemoryRelease.cpp (0 => 208534)


--- trunk/Source/WebCore/page/MemoryRelease.cpp	                        (rev 0)
+++ trunk/Source/WebCore/page/MemoryRelease.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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

Added: trunk/Source/WebCore/page/MemoryRelease.h (0 => 208534)


--- trunk/Source/WebCore/page/MemoryRelease.h	                        (rev 0)
+++ trunk/Source/WebCore/page/MemoryRelease.h	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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

Added: trunk/Source/WebCore/page/cocoa/MemoryReleaseCocoa.mm (0 => 208534)


--- trunk/Source/WebCore/page/cocoa/MemoryReleaseCocoa.mm	                        (rev 0)
+++ trunk/Source/WebCore/page/cocoa/MemoryReleaseCocoa.mm	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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

Modified: trunk/Source/WebCore/platform/MemoryPressureHandler.cpp (208533 => 208534)


--- trunk/Source/WebCore/platform/MemoryPressureHandler.cpp	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/platform/MemoryPressureHandler.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -26,28 +26,7 @@
 #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 <_javascript_Core/IncrementalSweeper.h>
-#include <chrono>
-#include <wtf/CurrentTime.h>
-#include <wtf/FastMalloc.h>
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
@@ -59,136 +38,17 @@
     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::releaseMemory(Critical critical, Synchronous synchronous)
 {
-    if (critical == Critical::Yes)
-        releaseCriticalMemory(synchronous);
+    if (!m_lowMemoryHandler)
+        return;
 
-    releaseNoncriticalMemory();
-
+    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 @@
         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() { }

Modified: trunk/Source/WebCore/platform/MemoryPressureHandler.h (208533 => 208534)


--- trunk/Source/WebCore/platform/MemoryPressureHandler.h	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/platform/MemoryPressureHandler.h	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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 @@
 
     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 @@
     WEBCORE_EXPORT void endSimulatedMemoryPressure();
 
 private:
-    void platformInitialize();
-    void releaseNoncriticalMemory();
-    void releaseCriticalMemory(Synchronous);
-
     void uninstall();
 
     void holdOff(unsigned);
@@ -164,8 +159,8 @@
     };
 #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;
@@ -172,10 +167,11 @@
     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;

Modified: trunk/Source/WebCore/platform/cocoa/MemoryPressureHandlerCocoa.mm (208533 => 208534)


--- trunk/Source/WebCore/platform/cocoa/MemoryPressureHandlerCocoa.mm	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/platform/cocoa/MemoryPressureHandlerCocoa.mm	2016-11-10 14:24:26 UTC (rev 208534)
@@ -26,15 +26,12 @@
 #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"
@@ -44,41 +41,11 @@
 #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 @@
     double startTime = monotonicallyIncreasingTime();
 #endif
 
-    m_lowMemoryHandler(critical, synchronous);
+    releaseMemory(critical, synchronous);
 
 #if !PLATFORM(IOS)
     unsigned holdOffTime = (monotonicallyIncreasingTime() - startTime) * s_holdOffMultiplier;

Modified: trunk/Source/WebCore/platform/linux/MemoryPressureHandlerLinux.cpp (208533 => 208534)


--- trunk/Source/WebCore/platform/linux/MemoryPressureHandlerLinux.cpp	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/platform/linux/MemoryPressureHandlerLinux.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -298,7 +298,7 @@
     uninstall();
 
     double startTime = monotonicallyIncreasingTime();
-    m_lowMemoryHandler(critical, synchronous);
+    releaseMemory(critical, synchronous);
     unsigned holdOffTime = (monotonicallyIncreasingTime() - startTime) * s_holdOffMultiplier;
     holdOff(std::max(holdOffTime, s_minimumHoldOffTime));
 }

Modified: trunk/Source/WebCore/platform/win/MemoryPressureHandlerWin.cpp (208533 => 208534)


--- trunk/Source/WebCore/platform/win/MemoryPressureHandlerWin.cpp	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebCore/platform/win/MemoryPressureHandlerWin.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -120,7 +120,7 @@
 {
     uninstall();
 
-    m_lowMemoryHandler(critical, synchronous);
+    releaseMemory(critical, synchronous);
 }
 
 size_t MemoryPressureHandler::ReliefLogger::platformMemoryUsage()

Modified: trunk/Source/WebKit/mac/ChangeLog (208533 => 208534)


--- trunk/Source/WebKit/mac/ChangeLog	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit/mac/ChangeLog	2016-11-10 14:24:26 UTC (rev 208534)
@@ -1,3 +1,15 @@
+2016-10-14  Carlos Garcia Campos  <cgar...@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  <rn...@webkit.org>
 
         WebHTMLView's _attributeStringFromDOMRange should use HTMLConverter instead of NSAttributedString's _initWithDOMRange

Modified: trunk/Source/WebKit/mac/WebView/WebView.mm (208533 => 208534)


--- trunk/Source/WebKit/mac/WebView/WebView.mm	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit/mac/WebView/WebView.mm	2016-11-10 14:24:26 UTC (rev 208534)
@@ -161,7 +161,7 @@
 #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,9 +1430,19 @@
     _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.
         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);

Modified: trunk/Source/WebKit/win/ChangeLog (208533 => 208534)


--- trunk/Source/WebKit/win/ChangeLog	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit/win/ChangeLog	2016-11-10 14:24:26 UTC (rev 208534)
@@ -1,3 +1,15 @@
+2016-10-14  Carlos Garcia Campos  <cgar...@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  <achristen...@webkit.org>
 
         Fix Windows build after r208499

Modified: trunk/Source/WebKit/win/WebView.cpp (208533 => 208534)


--- trunk/Source/WebKit/win/WebView.cpp	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit/win/WebView.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -127,7 +127,7 @@
 #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 @@
 
         WebKitInitializeWebDatabasesIfNecessary();
 
-        MemoryPressureHandler::singleton().install();
+        auto& memoryPressureHandler = MemoryPressureHandler::singleton();
+        memoryPressureHandler.setLowMemoryHandler([] (Critical critical, Synchronous synchronous) {
+            WebCore::releaseMemory(critical, synchronous);
+        });
+        memoryPressureHandler.install();
 
         didOneTimeInitialization = true;
      }

Modified: trunk/Source/WebKit2/ChangeLog (208533 => 208534)


--- trunk/Source/WebKit2/ChangeLog	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit2/ChangeLog	2016-11-10 14:24:26 UTC (rev 208534)
@@ -1,3 +1,17 @@
+2016-10-14  Carlos Garcia Campos  <cgar...@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  <svil...@igalia.com>
 
         [GTK] New API to notify about dynamically added forms

Modified: trunk/Source/WebKit2/WebProcess/WebProcess.cpp (208533 => 208534)


--- trunk/Source/WebKit2/WebProcess/WebProcess.cpp	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit2/WebProcess/WebProcess.cpp	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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 @@
     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());

Modified: trunk/Source/WebKit2/WebProcess/cocoa/WebProcessCocoa.mm (208533 => 208534)


--- trunk/Source/WebKit2/WebProcess/cocoa/WebProcessCocoa.mm	2016-11-10 13:37:38 UTC (rev 208533)
+++ trunk/Source/WebKit2/WebProcess/cocoa/WebProcessCocoa.mm	2016-11-10 14:24:26 UTC (rev 208534)
@@ -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 @@
     m_compositingRenderServerPort = WTFMove(parameters.acceleratedCompositingPort);
     m_presenterApplicationPid = parameters.presenterApplicationPid;
 
+    WebCore::registerMemoryReleaseNotifyCallbacks();
     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
 
 #if PLATFORM(IOS)
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to