Constant crashes under WebPage::isThrottleable() after r245299
https://bugs.webkit.org/show_bug.cgi?id=197902
<rdar://problem/50793796>

Reviewed by Alex Christensen.

Source/WebKit:

Update throttle state after a run loop iteration when page state changes to make sure the pageMap does not have null pages.
Add appNapEnabled preference that is used by added API test.

* WebProcess/WebPage/WebPage.cpp:
(WebKit::WebPage::updateThrottleState):
* UIProcess/API/Cocoa/WKPreferences.mm:
(-[WKPreferences _setAppNapEnabled:]):
(-[WKPreferences _appNapEnabled]):
* UIProcess/API/Cocoa/WKPreferencesPrivate.h:

Tools:

* TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm:


git-svn-id: http://svn.webkit.org/repository/webkit/trunk@245327 268f45cc-cd09-0410-ab3c-d52691b4dbfc
diff --git a/Source/WebKit/ChangeLog b/Source/WebKit/ChangeLog
index b25a8b54..b2ee925 100644
--- a/Source/WebKit/ChangeLog
+++ b/Source/WebKit/ChangeLog
@@ -1,3 +1,21 @@
+2019-05-15  Youenn Fablet  <youenn@apple.com>
+
+        Constant crashes under WebPage::isThrottleable() after r245299
+        https://bugs.webkit.org/show_bug.cgi?id=197902
+        <rdar://problem/50793796>
+
+        Reviewed by Alex Christensen.
+
+        Update throttle state after a run loop iteration when page state changes to make sure the pageMap does not have null pages.
+        Add appNapEnabled preference that is used by added API test.
+
+        * WebProcess/WebPage/WebPage.cpp:
+        (WebKit::WebPage::updateThrottleState):
+        * UIProcess/API/Cocoa/WKPreferences.mm:
+        (-[WKPreferences _setAppNapEnabled:]):
+        (-[WKPreferences _appNapEnabled]):
+        * UIProcess/API/Cocoa/WKPreferencesPrivate.h:
+
 2019-05-15  Alex Christensen  <achristensen@webkit.org>
 
         Allow NSFileCoordinator to be called from WebContent process
diff --git a/Source/WebKit/UIProcess/API/Cocoa/WKPreferences.mm b/Source/WebKit/UIProcess/API/Cocoa/WKPreferences.mm
index c3befce..65384ec 100644
--- a/Source/WebKit/UIProcess/API/Cocoa/WKPreferences.mm
+++ b/Source/WebKit/UIProcess/API/Cocoa/WKPreferences.mm
@@ -1265,6 +1265,16 @@
     return _preferences->aggressiveTileRetentionEnabled();
 }
 
+- (void)_setAppNapEnabled:(BOOL)enabled
+{
+    _preferences->setPageVisibilityBasedProcessSuppressionEnabled(enabled);
+}
+
+- (BOOL)_appNapEnabled
+{
+    return _preferences->pageVisibilityBasedProcessSuppressionEnabled();
+}
+
 #endif // PLATFORM(MAC)
 
 - (BOOL)_javaScriptCanAccessClipboard
diff --git a/Source/WebKit/UIProcess/API/Cocoa/WKPreferencesPrivate.h b/Source/WebKit/UIProcess/API/Cocoa/WKPreferencesPrivate.h
index e2b96c7..077a393 100644
--- a/Source/WebKit/UIProcess/API/Cocoa/WKPreferencesPrivate.h
+++ b/Source/WebKit/UIProcess/API/Cocoa/WKPreferencesPrivate.h
@@ -200,6 +200,7 @@
 @property (nonatomic, setter=_setWantsBalancedSetDefersLoadingBehavior:) BOOL _wantsBalancedSetDefersLoadingBehavior WK_API_AVAILABLE(macos(10.14));
 @property (nonatomic, setter=_setWebAudioEnabled:) BOOL _webAudioEnabled WK_API_AVAILABLE(macos(10.14));
 @property (nonatomic, setter=_setAggressiveTileRetentionEnabled:) BOOL _aggressiveTileRetentionEnabled WK_API_AVAILABLE(macos(10.14));
+@property (nonatomic, setter=_setAppNapEnabled:) BOOL _appNapEnabled WK_API_AVAILABLE(macos(WK_MAC_TBA));
 #endif
 
 @end
diff --git a/Source/WebKit/WebProcess/WebPage/WebPage.cpp b/Source/WebKit/WebProcess/WebPage/WebPage.cpp
index 0ed89d0..140cd6a 100644
--- a/Source/WebKit/WebProcess/WebPage/WebPage.cpp
+++ b/Source/WebKit/WebProcess/WebPage/WebPage.cpp
@@ -776,10 +776,12 @@
         m_userActivity.start();
 
 #if ENABLE(SERVICE_WORKER)
-    if (auto* connection = ServiceWorkerProvider::singleton().existingServiceWorkerConnectionForSession(sessionID())) {
-        if (isThrottleable != connection->isThrottleable())
-            connection->updateThrottleState();
-    }
+    RunLoop::main().dispatch([isThrottleable, sessionID = sessionID()] {
+        if (auto* connection = ServiceWorkerProvider::singleton().existingServiceWorkerConnectionForSession(sessionID)) {
+            if (isThrottleable != connection->isThrottleable())
+                connection->updateThrottleState();
+        }
+    });
 #endif
 }
 
diff --git a/Tools/ChangeLog b/Tools/ChangeLog
index 06198de..df0cdd8 100644
--- a/Tools/ChangeLog
+++ b/Tools/ChangeLog
@@ -1,3 +1,13 @@
+2019-05-15  Youenn Fablet  <youenn@apple.com>
+
+        Constant crashes under WebPage::isThrottleable() after r245299
+        https://bugs.webkit.org/show_bug.cgi?id=197902
+        <rdar://problem/50793796>
+
+        Reviewed by Alex Christensen.
+
+        * TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm:
+
 2019-05-15  Philippe Normand  <pnormand@igalia.com>
 
         [GTK][jhbuild] misc cleanups and bumps
diff --git a/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm b/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm
index 3dd4d7b..8261e36 100644
--- a/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm
+++ b/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm
@@ -27,6 +27,8 @@
 
 #import "PlatformUtilities.h"
 #import "Test.h"
+#import "TestNavigationDelegate.h"
+#import "TestWKWebView.h"
 #import <WebKit/WKPreferencesPrivate.h>
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKURLSchemeHandler.h>
@@ -52,6 +54,7 @@
 };
 
 static bool done;
+static bool didFinishNavigation;
 
 static String expectedMessage;
 static String retrievedString;
@@ -1619,6 +1622,74 @@
     EXPECT_EQ(0U, processPool._serviceWorkerProcessCount);
 }
 
+TEST(ServiceWorkers, ThrottleCrash)
+{
+    ASSERT(mainBytes);
+    ASSERT(scriptBytes);
+
+    [WKWebsiteDataStore _allowWebsiteDataRecordsForAllOrigins];
+
+    // Start with a clean slate data store
+    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] modifiedSince:[NSDate distantPast] completionHandler:^() {
+        done = true;
+    }];
+    TestWebKitAPI::Util::run(&done);
+    done = false;
+
+    auto messageHandler = adoptNS([[SWMessageHandler alloc] init]);
+
+    auto handler = adoptNS([[SWSchemes alloc] init]);
+    handler->resources.set("sw1://host/main.html", ResourceInfo { @"text/html", mainBytes });
+    handler->resources.set("sw1://host/sw.js", ResourceInfo { @"application/javascript", scriptBytes });
+
+    auto navigationDelegate = adoptNS([[TestNavigationDelegate alloc] init]);
+    [navigationDelegate setDidFinishNavigation:^(WKWebView *, WKNavigation *) {
+        didFinishNavigation = true;
+    }];
+
+    auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
+#if PLATFORM(MAC)
+    [[configuration preferences] _setAppNapEnabled:YES];
+#endif
+    [[configuration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sw"];
+    [configuration setURLSchemeHandler:handler.get() forURLScheme:@"sw1"];
+
+    auto *processPool = configuration.get().processPool;
+    [processPool _registerURLSchemeServiceWorkersCanHandle:@"sw1"];
+
+    auto webView1 = adoptNS([[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get() addToWindow: YES]);
+    [webView1 setNavigationDelegate:navigationDelegate.get()];
+
+    // Let's make it so that webView1 be app nappable after loading is completed.
+    [webView1.get().window resignKeyWindow];
+#if PLATFORM(MAC)
+    [webView1.get().window orderOut:nil];
+#endif
+
+    auto *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:@"sw1://host/main.html"]];
+    [webView1 loadRequest:request1];
+
+    didFinishNavigation = false;
+    TestWebKitAPI::Util::run(&didFinishNavigation);
+
+    auto webView2Configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
+#if PLATFORM(MAC)
+    [[webView2Configuration preferences] _setAppNapEnabled:NO];
+#endif
+    [webView2Configuration setProcessPool:processPool];
+    [[webView2Configuration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sw"];
+    [webView2Configuration setURLSchemeHandler:handler.get() forURLScheme:@"sw1"];
+    webView2Configuration.get()._relatedWebView = webView1.get();
+
+    auto webView2 = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:webView2Configuration.get()]);
+    [webView2 setNavigationDelegate:navigationDelegate.get()];
+
+    [webView2 loadRequest:request1];
+
+    didFinishNavigation = false;
+    TestWebKitAPI::Util::run(&didFinishNavigation);
+}
+
 TEST(ServiceWorkers, LoadData)
 {
     ASSERT(mainBytes);