UI↔Web deadlock when printing with a JavaScript alert visible
authortimothy_horton@apple.com <timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 17 Apr 2019 20:20:40 +0000 (20:20 +0000)
committertimothy_horton@apple.com <timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 17 Apr 2019 20:20:40 +0000 (20:20 +0000)
https://bugs.webkit.org/show_bug.cgi?id=196839
<rdar://problem/49157642>

Reviewed by Andy Estes.

Source/WebKit:

* Platform/IPC/Connection.cpp:
(IPC::Connection::dispatchWorkQueueMessageReceiverMessage):
(IPC::Connection::sendSyncReply):
(IPC::Connection::dispatchSyncMessage):
* Platform/IPC/Connection.h:
(IPC::Connection::hasOutstandingOutgoingSynchronousReplies const):
Keep track of whether we owe the other side of the connection any
delayed sync replies.

* UIProcess/API/Cocoa/WKWebView.mm:
(-[WKWebView _webViewPrintFormatter]):
Most actions one can take with a _WKWebViewPrintFormatter involve
synchronously messaging the Web Content process with an infinite timeout.
Doing so while the Web Content process is awaiting a reply to a deferred-reply
synchronous message (like, say, an alert()) results in an app-destroying deadlock.
Instead of that, return a nil _WKWebViewPrintFormatter, indicating to the client
that we can't print right now.

* UIProcess/ios/WKContentView.mm:
(-[WKContentView _wk_pageCountForPrintFormatter:]):
(-[WKContentView _wk_printedDocument]):
The above isn't sufficient, though, because a sync message could arrive and
be handled between creation and use of the _WKWebViewPrintFormatter.
So, we also bail with a zero page count and null CGPDFDocument immediately
before we would send a sync message to the Web Content process. Clients
handle this less gracefully (e.g. showing a zero page PDF), but it is
very rare compared to the above case.

Tools:

* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WebKitCocoa/WKWebViewPrintFormatter.mm: Added.
(-[PrintOnAlertUIDelegate webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:]):
(TEST):

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

Source/WebKit/ChangeLog
Source/WebKit/Platform/IPC/Connection.cpp
Source/WebKit/Platform/IPC/Connection.h
Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm
Source/WebKit/UIProcess/ios/WKContentView.mm
Tools/ChangeLog
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/WebKitCocoa/WKWebViewPrintFormatter.mm [new file with mode: 0644]

index bcee55c..f544207 100644 (file)
@@ -1,3 +1,39 @@
+2019-04-17  Tim Horton  <timothy_horton@apple.com>
+
+        UI↔Web deadlock when printing with a JavaScript alert visible
+        https://bugs.webkit.org/show_bug.cgi?id=196839
+        <rdar://problem/49157642>
+
+        Reviewed by Andy Estes.
+
+        * Platform/IPC/Connection.cpp:
+        (IPC::Connection::dispatchWorkQueueMessageReceiverMessage):
+        (IPC::Connection::sendSyncReply):
+        (IPC::Connection::dispatchSyncMessage):
+        * Platform/IPC/Connection.h:
+        (IPC::Connection::hasOutstandingOutgoingSynchronousReplies const):
+        Keep track of whether we owe the other side of the connection any
+        delayed sync replies.
+
+        * UIProcess/API/Cocoa/WKWebView.mm:
+        (-[WKWebView _webViewPrintFormatter]):
+        Most actions one can take with a _WKWebViewPrintFormatter involve
+        synchronously messaging the Web Content process with an infinite timeout.
+        Doing so while the Web Content process is awaiting a reply to a deferred-reply
+        synchronous message (like, say, an alert()) results in an app-destroying deadlock.
+        Instead of that, return a nil _WKWebViewPrintFormatter, indicating to the client
+        that we can't print right now.
+
+        * UIProcess/ios/WKContentView.mm:
+        (-[WKContentView _wk_pageCountForPrintFormatter:]):
+        (-[WKContentView _wk_printedDocument]):
+        The above isn't sufficient, though, because a sync message could arrive and
+        be handled between creation and use of the _WKWebViewPrintFormatter.
+        So, we also bail with a zero page count and null CGPDFDocument immediately
+        before we would send a sync message to the Web Content process. Clients
+        handle this less gracefully (e.g. showing a zero page PDF), but it is
+        very rare compared to the above case.
+
 2019-04-17  Zalan Bujtas  <zalan@apple.com>
 
         [ContentChangeObserver] Use aria role as a hint whether a tap should result in a synthetic click
index e2ee148..7f736c6 100644 (file)
@@ -341,6 +341,8 @@ void Connection::dispatchWorkQueueMessageReceiverMessage(WorkQueueMessageReceive
         return;
     }
 
+    m_outstandingOutgoingSynchronousReplyCount++;
+
     auto replyEncoder = std::make_unique<Encoder>("IPC", "SyncMessageReply", syncRequestID);
 
     // Hand off both the decoder and encoder to the work queue message receiver.
@@ -458,6 +460,9 @@ void Connection::sendMessageWithReply(uint64_t requestID, std::unique_ptr<Encode
 
 bool Connection::sendSyncReply(std::unique_ptr<Encoder> encoder)
 {
+    ASSERT(m_outstandingOutgoingSynchronousReplyCount);
+    m_outstandingOutgoingSynchronousReplyCount--;
+
     return sendMessage(WTFMove(encoder), { });
 }
 
@@ -888,6 +893,8 @@ void Connection::dispatchSyncMessage(Decoder& decoder)
         return;
     }
 
+    m_outstandingOutgoingSynchronousReplyCount++;
+
     auto replyEncoder = std::make_unique<Encoder>("IPC", "SyncMessageReply", syncRequestID);
 
     if (decoder.messageReceiverName() == "IPC" && decoder.messageName() == "WrappedAsyncMessageForTesting") {
index 36bd912..5167c95 100644 (file)
@@ -196,6 +196,8 @@ public:
 
     bool inSendSync() const { return m_inSendSyncCount; }
 
+    bool hasOutstandingOutgoingSynchronousReplies() const { return m_outstandingOutgoingSynchronousReplyCount; }
+
     Identifier identifier() const;
 
 #if PLATFORM(COCOA)
@@ -297,6 +299,7 @@ private:
     unsigned m_inDispatchMessageCount;
     unsigned m_inDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount;
     unsigned m_inDispatchMessageMarkedToUseFullySynchronousModeForTesting { 0 };
+    unsigned m_outstandingOutgoingSynchronousReplyCount { 0 };
     bool m_fullySynchronousModeIsAllowedForTesting { false };
     bool m_ignoreTimeoutsForTesting { false };
     bool m_didReceiveInvalidMessage;
index b9b1e80..58c6498 100644 (file)
@@ -6323,6 +6323,9 @@ static WTF::Optional<WebCore::ViewportArguments> viewportArgumentsFromDictionary
 - (_WKWebViewPrintFormatter *)_webViewPrintFormatter
 {
 #if !PLATFORM(IOSMAC)
+    if (_page->process().connection()->hasOutstandingOutgoingSynchronousReplies())
+        return nil;
+
     UIViewPrintFormatter *viewPrintFormatter = self.viewPrintFormatter;
     ASSERT([viewPrintFormatter isKindOfClass:[_WKWebViewPrintFormatter class]]);
     return (_WKWebViewPrintFormatter *)viewPrintFormatter;
index 6b2d9f9..d4f4ea7 100644 (file)
@@ -726,6 +726,9 @@ static void storeAccessibilityRemoteConnectionInformation(id element, pid_t pid,
     if (_isPrintingToPDF)
         return 0;
 
+    if (_page->process().connection()->hasOutstandingOutgoingSynchronousReplies())
+        return 0;
+
     uint64_t frameID;
     if (_WKFrameHandle *handle = printFormatter.frameToPrint)
         frameID = handle._frameID;
@@ -769,6 +772,9 @@ static void storeAccessibilityRemoteConnectionInformation(id element, pid_t pid,
 
 - (CGPDFDocumentRef)_wk_printedDocument
 {
+    if (_page->process().connection()->hasOutstandingOutgoingSynchronousReplies())
+        return nullptr;
+
     if (_isPrintingToPDF) {
         if (!_page->process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DrawToPDFCallback>(_page->pageID(), Seconds::infinity())) {
             ASSERT_NOT_REACHED();
index ade1054..72cf37a 100644 (file)
@@ -1,3 +1,16 @@
+2019-04-17  Tim Horton  <timothy_horton@apple.com>
+
+        UI↔Web deadlock when printing with a JavaScript alert visible
+        https://bugs.webkit.org/show_bug.cgi?id=196839
+        <rdar://problem/49157642>
+
+        Reviewed by Andy Estes.
+
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WebKitCocoa/WKWebViewPrintFormatter.mm: Added.
+        (-[PrintOnAlertUIDelegate webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:]):
+        (TEST):
+
 2019-04-17  Alex Christensen  <achristensen@webkit.org>
 
         WKRetainPtr's adoption constructor should be private
index 8f90a22..7b44d80 100644 (file)
@@ -94,6 +94,7 @@
                2D21FE591F04642900B58E7D /* WKPDFViewStablePresentationUpdateCallback.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D21FE581F04642800B58E7D /* WKPDFViewStablePresentationUpdateCallback.mm */; };
                2D2BEB2D22324E5F005544CA /* RequestTextInputContext.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D2BEB2C22324E5F005544CA /* RequestTextInputContext.mm */; };
                2D3CA3A8221DF4B40088E803 /* PageOverlayPlugin.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D3CA3A4221DF2390088E803 /* PageOverlayPlugin.mm */; };
+               2D41CFB92260014F00FFF335 /* WKWebViewPrintFormatter.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D41CFB82260014E00FFF335 /* WKWebViewPrintFormatter.mm */; };
                2D4CF8BD1D8360CC0001CE8D /* WKThumbnailView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D4CF8BC1D8360CC0001CE8D /* WKThumbnailView.mm */; };
                2D51A0C71C8BF00C00765C45 /* DOMHTMLVideoElementWrapper.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D51A0C51C8BF00400765C45 /* DOMHTMLVideoElementWrapper.mm */; };
                2D70059621EDA0C6003463CB /* TabOutOfWebView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2D70059521EDA0C6003463CB /* TabOutOfWebView.mm */; };
                2D21FE581F04642800B58E7D /* WKPDFViewStablePresentationUpdateCallback.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WKPDFViewStablePresentationUpdateCallback.mm; sourceTree = "<group>"; };
                2D2BEB2C22324E5F005544CA /* RequestTextInputContext.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RequestTextInputContext.mm; sourceTree = "<group>"; };
                2D3CA3A4221DF2390088E803 /* PageOverlayPlugin.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PageOverlayPlugin.mm; sourceTree = "<group>"; };
+               2D41CFB82260014E00FFF335 /* WKWebViewPrintFormatter.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WKWebViewPrintFormatter.mm; sourceTree = "<group>"; };
                2D4CF8BC1D8360CC0001CE8D /* WKThumbnailView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = WKThumbnailView.mm; path = WebKit/WKThumbnailView.mm; sourceTree = "<group>"; };
                2D51A0C51C8BF00400765C45 /* DOMHTMLVideoElementWrapper.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = DOMHTMLVideoElementWrapper.mm; sourceTree = "<group>"; };
                2D61EC3021B0B75C00A7D1CB /* PencilKitTestSPI.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PencilKitTestSPI.h; sourceTree = "<group>"; };
                                CE449E1021AE0F7200E7ADA1 /* WKWebViewFindString.mm */,
                                F4106C6821ACBF84004B89A1 /* WKWebViewFirstResponderTests.mm */,
                                D3BE5E341E4CE85E00FD563A /* WKWebViewGetContents.mm */,
+                               2D41CFB82260014E00FFF335 /* WKWebViewPrintFormatter.mm */,
                                37A9DBE7213B4C9300D261A2 /* WKWebViewServerTrustKVC.mm */,
                                93F56DA81E5F9181003EDE84 /* WKWebViewSnapshot.mm */,
                                9984FACA1CFFAEEE008D198C /* WKWebViewTextInput.mm */,
                                F4106C6921ACBF84004B89A1 /* WKWebViewFirstResponderTests.mm in Sources */,
                                D34E08761E4E42E1005FF14A /* WKWebViewGetContents.mm in Sources */,
                                F4FA91811E61849B007B8C1D /* WKWebViewMacEditingTests.mm in Sources */,
+                               2D41CFB92260014F00FFF335 /* WKWebViewPrintFormatter.mm in Sources */,
                                37A9DBE9213B4C9300D261A2 /* WKWebViewServerTrustKVC.mm in Sources */,
                                93F56DA91E5F919D003EDE84 /* WKWebViewSnapshot.mm in Sources */,
                                9984FACC1CFFAF60008D198C /* WKWebViewTextInput.mm in Sources */,
diff --git a/Tools/TestWebKitAPI/Tests/WebKitCocoa/WKWebViewPrintFormatter.mm b/Tools/TestWebKitAPI/Tests/WebKitCocoa/WKWebViewPrintFormatter.mm
new file mode 100644 (file)
index 0000000..84bcdcc
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#import "config.h"
+
+#if PLATFORM(IOS_FAMILY)
+
+#import "PlatformUtilities.h"
+#import "Test.h"
+#import "TestNavigationDelegate.h"
+#import "TestWKWebView.h"
+#import <WebKit/WKPreferencesRefPrivate.h>
+#import <WebKit/WKWebViewPrivate.h>
+#import <WebKit/WebKit.h>
+#import <WebKit/_WKTextInputContext.h>
+#import <wtf/RetainPtr.h>
+
+static bool done;
+
+@interface PrintOnAlertUIDelegate : NSObject <WKUIDelegate>
+@end
+
+@implementation PrintOnAlertUIDelegate
+
+- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
+{
+    EXPECT_NULL([webView _webViewPrintFormatter]);
+
+    dispatch_async(dispatch_get_main_queue(), ^{
+        EXPECT_NULL([webView _webViewPrintFormatter]);
+        completionHandler();
+        done = true;
+    });
+}
+
+@end
+
+TEST(WebKit, WKWebViewPrintFormatterJavaScriptAlertDeadlock)
+{
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600)]);
+    auto delegate = adoptNS([[PrintOnAlertUIDelegate alloc] init]);
+    [webView setUIDelegate:delegate.get()];
+
+    [webView synchronouslyLoadHTMLString:@"The quick brown fox jumps over the lazy dog."];
+    EXPECT_NOT_NULL([webView _webViewPrintFormatter]);
+
+    [webView evaluateJavaScript:@"alert('hello')" completionHandler:nil];
+    TestWebKitAPI::Util::run(&done);
+
+    EXPECT_NOT_NULL([webView _webViewPrintFormatter]);
+}
+
+#endif // PLATFORM(IOS_FAMILY)