message loading never finishes in Mail
authorandersca@apple.com <andersca@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 12 Aug 2016 18:50:02 +0000 (18:50 +0000)
committerandersca@apple.com <andersca@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 12 Aug 2016 18:50:02 +0000 (18:50 +0000)
https://bugs.webkit.org/show_bug.cgi?id=160806
rdar://problem/27624095

Reviewed by Dan Bernstein.

Add more checks for when a process goes away before we've established a proper connection to it.

* Platform/IPC/mac/ConnectionMac.mm:
(IPC::Connection::receiveSourceEventHandler):
Handle the MACH_NOTIFY_NO_SENDERS and MACH_NOTIFY_SEND_ONCE messages here. Also, once we receive a send
right from the other side, stop listening for the MACH_NOTIFY_NO_SENDERS notification.

* UIProcess/ChildProcessProxy.cpp:
(WebKit::ChildProcessProxy::didFinishLaunching):
Null check the connection identifier.

* UIProcess/Launcher/ProcessLauncher.cpp:
(WebKit::ProcessLauncher::ProcessLauncher):
(WebKit::processLauncherWorkQueue): Deleted.
Get rid of the process launcher queue - we're not doing any blocking work here.

* UIProcess/Launcher/ProcessLauncher.h:
Add a weak factory.

* UIProcess/Launcher/mac/ProcessLauncherMac.mm:
(WebKit::systemDirectoryPath):
Move this before launchProcess().

(WebKit::ProcessLauncher::launchProcess):
Merge createService and connectToService into launchProcess. Also make the following changes:
- Use mach_port_request_notification to get a notification for when our receive right loses all its senders.
This lets us listen for the other process going away before we have a send right for it.
- Use xpc_connection_set_event_handler to listen for errors, so we can detect the process going away before
we've sent a message to it.

(WebKit::connectToService): Deleted.
(WebKit::createService): Deleted.

* UIProcess/Network/NetworkProcessProxy.cpp:
(WebKit::NetworkProcessProxy::didFinishLaunching):
If we failed to launch, call networkProcessCrashedOrFailedToLaunch so we'll unblock any waiting web processes.

* UIProcess/WebProcessProxy.cpp:
(WebKit::WebProcessProxy::didFinishLaunching):
Null check the connection and XPC connection before trying to get its pid.

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

Source/WebKit2/ChangeLog
Source/WebKit2/Platform/IPC/mac/ConnectionMac.mm
Source/WebKit2/UIProcess/ChildProcessProxy.cpp
Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp
Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h
Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm
Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp
Source/WebKit2/UIProcess/WebProcessProxy.cpp

index 394cbcf..fffc9ca 100644 (file)
@@ -1,3 +1,52 @@
+2016-08-12  Anders Carlsson  <andersca@apple.com>
+
+        message loading never finishes in Mail
+        https://bugs.webkit.org/show_bug.cgi?id=160806
+        rdar://problem/27624095
+
+        Reviewed by Dan Bernstein.
+
+        Add more checks for when a process goes away before we've established a proper connection to it.
+
+        * Platform/IPC/mac/ConnectionMac.mm:
+        (IPC::Connection::receiveSourceEventHandler):
+        Handle the MACH_NOTIFY_NO_SENDERS and MACH_NOTIFY_SEND_ONCE messages here. Also, once we receive a send
+        right from the other side, stop listening for the MACH_NOTIFY_NO_SENDERS notification.
+
+        * UIProcess/ChildProcessProxy.cpp:
+        (WebKit::ChildProcessProxy::didFinishLaunching):
+        Null check the connection identifier.
+
+        * UIProcess/Launcher/ProcessLauncher.cpp:
+        (WebKit::ProcessLauncher::ProcessLauncher):
+        (WebKit::processLauncherWorkQueue): Deleted.
+        Get rid of the process launcher queue - we're not doing any blocking work here.
+
+        * UIProcess/Launcher/ProcessLauncher.h:
+        Add a weak factory.
+
+        * UIProcess/Launcher/mac/ProcessLauncherMac.mm:
+        (WebKit::systemDirectoryPath):
+        Move this before launchProcess().
+
+        (WebKit::ProcessLauncher::launchProcess):
+        Merge createService and connectToService into launchProcess. Also make the following changes:
+        - Use mach_port_request_notification to get a notification for when our receive right loses all its senders.
+        This lets us listen for the other process going away before we have a send right for it.
+        - Use xpc_connection_set_event_handler to listen for errors, so we can detect the process going away before
+        we've sent a message to it.
+        
+        (WebKit::connectToService): Deleted.
+        (WebKit::createService): Deleted.
+
+        * UIProcess/Network/NetworkProcessProxy.cpp:
+        (WebKit::NetworkProcessProxy::didFinishLaunching):
+        If we failed to launch, call networkProcessCrashedOrFailedToLaunch so we'll unblock any waiting web processes.
+
+        * UIProcess/WebProcessProxy.cpp:
+        (WebKit::WebProcessProxy::didFinishLaunching):
+        Null check the connection and XPC connection before trying to get its pid.
+
 2016-08-11  Brady Eidson  <beidson@apple.com>
 
         [WK2] Don't monitor gamepads at all unless an interested WebPageProxy is in the active window.
index fc96566..47ecdb9 100644 (file)
@@ -479,6 +479,20 @@ void Connection::receiveSourceEventHandler()
     if (!header)
         return;
 
+    switch (header->msgh_id) {
+    case MACH_NOTIFY_NO_SENDERS:
+        ASSERT(m_isServer);
+        if (!m_sendPort)
+            connectionDidClose();
+        return;
+
+    case MACH_NOTIFY_SEND_ONCE:
+        return;
+
+    default:
+        break;
+    }
+
     std::unique_ptr<MessageDecoder> decoder = createMessageDecoder(header);
     ASSERT(decoder);
 
@@ -500,6 +514,12 @@ void Connection::receiveSourceEventHandler()
         m_sendPort = port.port();
         
         if (m_sendPort) {
+            mach_port_t previousNotificationPort;
+            mach_port_request_notification(mach_task_self(), m_receivePort, MACH_NOTIFY_NO_SENDERS, 0, MACH_PORT_NULL, MACH_MSG_TYPE_MOVE_SEND_ONCE, &previousNotificationPort);
+
+            if (previousNotificationPort != MACH_PORT_NULL)
+                mach_port_deallocate(mach_task_self(), previousNotificationPort);
+
             initializeDeadNameSource();
             dispatch_resume(m_deadNameSource);
         }
index fe2a6de..b39a522 100644 (file)
@@ -171,6 +171,9 @@ void ChildProcessProxy::didFinishLaunching(ProcessLauncher*, IPC::Connection::Id
 {
     ASSERT(!m_connection);
 
+    if (IPC::Connection::identifierIsNull(connectionIdentifier))
+        return;
+
     m_connection = IPC::Connection::createServerConnection(connectionIdentifier, *this);
 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED <= 101000
     m_connection->setShouldCloseConnectionOnMachExceptions();
index f8584c9..089c17c 100644 (file)
 
 namespace WebKit {
 
-static WorkQueue& processLauncherWorkQueue()
-{
-
-    static WorkQueue& processLauncherWorkQueue = WorkQueue::create("com.apple.WebKit.ProcessLauncher").leakRef();
-    return processLauncherWorkQueue;
-}
-
 ProcessLauncher::ProcessLauncher(Client* client, const LaunchOptions& launchOptions)
     : m_client(client)
+    , m_weakPtrFactory(this)
     , m_launchOptions(launchOptions)
     , m_processIdentifier(0)
 {
     m_isLaunching = true;
-
-    processLauncherWorkQueue().dispatch([processLauncher = makeRef(*this)]() mutable {
-        processLauncher->launchProcess();
-    });
+    launchProcess();
 }
 
 void ProcessLauncher::didFinishLaunchingProcess(pid_t processIdentifier, IPC::Connection::Identifier identifier)
index 05e7947..a5f5a81 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef WebProcessLauncher_h
-#define WebProcessLauncher_h
+#pragma once
 
 #include "Connection.h"
 #include <wtf/HashMap.h>
 #include <wtf/RefPtr.h>
 #include <wtf/Threading.h>
+#include <wtf/WeakPtr.h>
 #include <wtf/text/StringHash.h>
 #include <wtf/text/WTFString.h>
 
@@ -86,11 +86,10 @@ private:
 
     Client* m_client;
 
+    WeakPtrFactory<ProcessLauncher> m_weakPtrFactory;
     const LaunchOptions m_launchOptions;
     bool m_isLaunching;
     pid_t m_processIdentifier;
 };
 
 } // namespace WebKit
-
-#endif // WebProcessLauncher_h
index 49eddbf..a7006af 100644 (file)
@@ -50,8 +50,6 @@
 
 namespace WebKit {
 
-typedef void (ProcessLauncher::*DidFinishLaunchingProcessFunction)(pid_t, IPC::Connection::Identifier);
-
 static const char* serviceName(const ProcessLauncher::LaunchOptions& launchOptions)
 {
     switch (launchOptions.processType) {
@@ -83,11 +81,24 @@ static bool shouldLeakBoost(const ProcessLauncher::LaunchOptions& launchOptions)
     return launchOptions.processType == ProcessLauncher::ProcessType::Network;
 #endif
 }
-    
-static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction)
+
+static NSString *systemDirectoryPath()
 {
-    // Create a connection to the WebKit XPC service.
-    auto connection = adoptOSObject(xpc_connection_create(serviceName(launchOptions), 0));
+    static NSString *path = [^{
+#if PLATFORM(IOS_SIMULATOR)
+        char *simulatorRoot = getenv("SIMULATOR_ROOT");
+        return simulatorRoot ? [NSString stringWithFormat:@"%s/System/", simulatorRoot] : @"/System/";
+#else
+        return @"/System/";
+#endif
+    }() copy];
+
+    return path;
+}
+
+void ProcessLauncher::launchProcess()
+{
+    auto connection = adoptOSObject(xpc_connection_create(serviceName(m_launchOptions), dispatch_get_main_queue()));
 
     uuid_t uuid;
     uuid_generate(uuid);
@@ -111,8 +122,8 @@ static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions
     xpc_dictionary_set_value(initializationMessage.get(), "ContainerEnvironmentVariables", containerEnvironmentVariables.get());
 #endif
 
-    auto languagesIterator = launchOptions.extraInitializationData.find("OverrideLanguages");
-    if (languagesIterator != launchOptions.extraInitializationData.end()) {
+    auto languagesIterator = m_launchOptions.extraInitializationData.find("OverrideLanguages");
+    if (languagesIterator != m_launchOptions.extraInitializationData.end()) {
         auto languages = adoptOSObject(xpc_array_create(nullptr, 0));
         Vector<String> languageVector;
         languagesIterator->value.split(",", false, languageVector);
@@ -123,11 +134,7 @@ static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions
 
     xpc_connection_set_bootstrap(connection.get(), initializationMessage.get());
 
-    // XPC requires having an event handler, even if it is not used.
-    xpc_connection_set_event_handler(connection.get(), ^(xpc_object_t event) { });
-    xpc_connection_resume(connection.get());
-    
-    if (shouldLeakBoost(launchOptions)) {
+    if (shouldLeakBoost(m_launchOptions)) {
         auto preBootstrapMessage = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
         xpc_dictionary_set_string(preBootstrapMessage.get(), "message-name", "pre-bootstrap");
         xpc_connection_send_message(connection.get(), preBootstrapMessage.get());
@@ -140,6 +147,10 @@ static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions
     // Insert a send right so we can send to it.
     mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND);
 
+    mach_port_t previousNotificationPort;
+    mach_port_request_notification(mach_task_self(), listeningPort, MACH_NOTIFY_NO_SENDERS, 0, listeningPort, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previousNotificationPort);
+    ASSERT(!previousNotificationPort);
+
     String clientIdentifier;
 #if PLATFORM(MAC)
     clientIdentifier = codeSigningIdentifierForCurrentProcess();
@@ -157,75 +168,57 @@ static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions
     xpc_dictionary_set_string(bootstrapMessage.get(), "client-identifier", !clientIdentifier.isEmpty() ? clientIdentifier.utf8().data() : *_NSGetProgname());
     xpc_dictionary_set_string(bootstrapMessage.get(), "ui-process-name", [[[NSProcessInfo processInfo] processName] UTF8String]);
 
-    if (forDevelopment) {
+    bool isWebKitDevelopmentBuild = ![[[[NSBundle bundleWithIdentifier:@"com.apple.WebKit"] bundlePath] stringByDeletingLastPathComponent] hasPrefix:systemDirectoryPath()];
+    if (isWebKitDevelopmentBuild) {
         xpc_dictionary_set_fd(bootstrapMessage.get(), "stdout", STDOUT_FILENO);
         xpc_dictionary_set_fd(bootstrapMessage.get(), "stderr", STDERR_FILENO);
     }
 
     auto extraInitializationData = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
 
-    for (const auto& keyValuePair : launchOptions.extraInitializationData)
+    for (const auto& keyValuePair : m_launchOptions.extraInitializationData)
         xpc_dictionary_set_string(extraInitializationData.get(), keyValuePair.key.utf8().data(), keyValuePair.value.utf8().data());
 
     xpc_dictionary_set_value(bootstrapMessage.get(), "extra-initialization-data", extraInitializationData.get());
 
-    that->ref();
+    auto weakProcessLauncher = m_weakPtrFactory.createWeakPtr();
+    xpc_connection_set_event_handler(connection.get(), [weakProcessLauncher, listeningPort](xpc_object_t event) {
+        ASSERT(xpc_get_type(event) == XPC_TYPE_ERROR);
+
+        auto processLauncher = weakProcessLauncher.get();
+        if (!processLauncher)
+            return;
+
+        if (!processLauncher->isLaunching())
+            return;
+
+        // We failed to launch. Release the send right.
+        mach_port_deallocate(mach_task_self(), listeningPort);
 
-    xpc_connection_send_message_with_reply(connection.get(), bootstrapMessage.get(), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t reply) {
-        xpc_type_t type = xpc_get_type(reply);
-        if (type == XPC_TYPE_ERROR) {
-            // We failed to launch. Release the send right.
-            mach_port_deallocate(mach_task_self(), listeningPort);
+        // And the receive right.
+        mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1);
+        processLauncher->didFinishLaunchingProcess(0, IPC::Connection::Identifier());
+    });
 
-            // And the receive right.
-            mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1);
+    xpc_connection_resume(connection.get());
 
-            RunLoop::main().dispatch([protectedThat = RefPtr<ProcessLauncher>(that), didFinishLaunchingProcessFunction]() mutable {
-                (*protectedThat.*didFinishLaunchingProcessFunction)(0, IPC::Connection::Identifier());
-            });
-        } else {
-            ASSERT(type == XPC_TYPE_DICTIONARY);
+    ref();
+    xpc_connection_send_message_with_reply(connection.get(), bootstrapMessage.get(), dispatch_get_main_queue(), ^(xpc_object_t reply) {
+        // Errors are handled in the event handler.
+        if (xpc_get_type(reply) != XPC_TYPE_ERROR) {
+            ASSERT(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);
             ASSERT(!strcmp(xpc_dictionary_get_string(reply, "message-name"), "process-finished-launching"));
 
             // The process has finished launching, grab the pid from the connection.
             pid_t processIdentifier = xpc_connection_get_pid(connection.get());
 
-            // We've finished launching the process, message back to the main run loop. This takes ownership of the connection.
-            RunLoop::main().dispatch([protectedThat = RefPtr<ProcessLauncher>(that), didFinishLaunchingProcessFunction, processIdentifier, listeningPort, connection] {
-                (*protectedThat.*didFinishLaunchingProcessFunction)(processIdentifier, IPC::Connection::Identifier(listeningPort, connection));
-            });
+            didFinishLaunchingProcess(processIdentifier, IPC::Connection::Identifier(listeningPort, connection));
         }
 
-        that->deref();
+        deref();
     });
 }
 
-static void createService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction)
-{
-    connectToService(launchOptions, forDevelopment, that, didFinishLaunchingProcessFunction);
-}
-
-static NSString *systemDirectoryPath()
-{
-    static NSString *path = [^{
-#if PLATFORM(IOS_SIMULATOR)
-        char *simulatorRoot = getenv("SIMULATOR_ROOT");
-        return simulatorRoot ? [NSString stringWithFormat:@"%s/System/", simulatorRoot] : @"/System/";
-#else
-        return @"/System/";
-#endif
-    }() copy];
-
-    return path;
-}
-
-void ProcessLauncher::launchProcess()
-{
-    bool isWebKitDevelopmentBuild = ![[[[NSBundle bundleWithIdentifier:@"com.apple.WebKit"] bundlePath] stringByDeletingLastPathComponent] hasPrefix:systemDirectoryPath()];
-
-    createService(m_launchOptions, isWebKitDevelopmentBuild, this, &ProcessLauncher::didFinishLaunchingProcess);
-}
-
 void ProcessLauncher::terminateProcess()
 {
     if (m_isLaunching) {
index 03bcb61..62e661d 100644 (file)
@@ -299,7 +299,7 @@ void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Con
     ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier);
 
     if (IPC::Connection::identifierIsNull(connectionIdentifier)) {
-        // FIXME: Do better cleanup here.
+        networkProcessCrashedOrFailedToLaunch();
         return;
     }
 
index b1c0f8b..c9f71f5 100644 (file)
@@ -613,9 +613,10 @@ void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connect
     m_processPool->processDidFinishLaunching(this);
 
 #if PLATFORM(IOS)
-    xpc_connection_t xpcConnection = connection()->xpcConnection();
-    ASSERT(xpcConnection);
-    m_throttler.didConnectToProcess(xpc_connection_get_pid(xpcConnection));
+    if (connection()) {
+        if (xpc_connection_t xpcConnection = connection()->xpcConnection())
+            m_throttler.didConnectToProcess(xpc_connection_get_pid(xpcConnection));
+    }
 #endif
 }