WeakPtrFactory should populate m_ref lazily.
[WebKit-https.git] / Source / WebKit / UIProcess / Launcher / mac / ProcessLauncherMac.mm
1 /*
2  * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "ProcessLauncher.h"
28
29 #import <WebCore/WebCoreNSStringExtras.h>
30 #import <crt_externs.h>
31 #import <mach-o/dyld.h>
32 #import <mach/machine.h>
33 #import <pal/spi/cocoa/ServersSPI.h>
34 #import <spawn.h>
35 #import <sys/param.h>
36 #import <sys/stat.h>
37 #import <wtf/RunLoop.h>
38 #import <wtf/SoftLinking.h>
39 #import <wtf/Threading.h>
40 #import <wtf/spi/cf/CFBundleSPI.h>
41 #import <wtf/spi/darwin/XPCSPI.h>
42 #import <wtf/text/CString.h>
43 #import <wtf/text/WTFString.h>
44
45 #if PLATFORM(MAC)
46 #import "CodeSigning.h"
47 #endif
48
49 namespace WebKit {
50
51 static const char* serviceName(const ProcessLauncher::LaunchOptions& launchOptions)
52 {
53     switch (launchOptions.processType) {
54     case ProcessLauncher::ProcessType::Web:
55         return "com.apple.WebKit.WebContent";
56     case ProcessLauncher::ProcessType::Network:
57         return "com.apple.WebKit.Networking";
58     case ProcessLauncher::ProcessType::Storage:
59 #if PLATFORM(MAC) || PLATFORM(IOS_SIMULATOR)
60         return "com.apple.WebKit.Storage";
61 #else
62         return "com.apple.WebKit.Databases";
63 #endif
64 #if ENABLE(NETSCAPE_PLUGIN_API)
65     case ProcessLauncher::ProcessType::Plugin32:
66         return "com.apple.WebKit.Plugin.32";
67     case ProcessLauncher::ProcessType::Plugin64:
68         return "com.apple.WebKit.Plugin.64";
69 #endif
70     }
71 }
72     
73 static bool shouldLeakBoost(const ProcessLauncher::LaunchOptions& launchOptions)
74 {
75 #if PLATFORM(IOS)
76     // On iOS, leak a boost onto all child processes
77     UNUSED_PARAM(launchOptions);
78     return true;
79 #else
80     // On Mac, leak a boost onto the NetworkProcess.
81     return launchOptions.processType == ProcessLauncher::ProcessType::Network;
82 #endif
83 }
84
85 static NSString *systemDirectoryPath()
86 {
87     static NSString *path = [^{
88 #if PLATFORM(IOS_SIMULATOR)
89         char *simulatorRoot = getenv("SIMULATOR_ROOT");
90         return simulatorRoot ? [NSString stringWithFormat:@"%s/System/", simulatorRoot] : @"/System/";
91 #else
92         return @"/System/";
93 #endif
94     }() copy];
95
96     return path;
97 }
98
99 void ProcessLauncher::launchProcess()
100 {
101     ASSERT(!m_xpcConnection);
102
103     m_xpcConnection = adoptOSObject(xpc_connection_create(serviceName(m_launchOptions), dispatch_get_main_queue()));
104
105     uuid_t uuid;
106     uuid_generate(uuid);
107     xpc_connection_set_oneshot_instance(m_xpcConnection.get(), uuid);
108
109     // Inherit UI process localization. It can be different from child process default localization:
110     // 1. When the application and system frameworks simply have different localized resources available, we should match the application.
111     // 1.1. An important case is WebKitTestRunner, where we should use English localizations for all system frameworks.
112     // 2. When AppleLanguages is passed as command line argument for UI process, or set in its preferences, we should respect it in child processes.
113     auto initializationMessage = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
114     _CFBundleSetupXPCBootstrap(initializationMessage.get());
115 #if PLATFORM(IOS)
116     // Clients that set these environment variables explicitly do not have the values automatically forwarded by libxpc.
117     auto containerEnvironmentVariables = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
118     if (const char* environmentHOME = getenv("HOME"))
119         xpc_dictionary_set_string(containerEnvironmentVariables.get(), "HOME", environmentHOME);
120     if (const char* environmentCFFIXED_USER_HOME = getenv("CFFIXED_USER_HOME"))
121         xpc_dictionary_set_string(containerEnvironmentVariables.get(), "CFFIXED_USER_HOME", environmentCFFIXED_USER_HOME);
122     if (const char* environmentTMPDIR = getenv("TMPDIR"))
123         xpc_dictionary_set_string(containerEnvironmentVariables.get(), "TMPDIR", environmentTMPDIR);
124     xpc_dictionary_set_value(initializationMessage.get(), "ContainerEnvironmentVariables", containerEnvironmentVariables.get());
125 #endif
126
127     auto languagesIterator = m_launchOptions.extraInitializationData.find("OverrideLanguages");
128     if (languagesIterator != m_launchOptions.extraInitializationData.end()) {
129         auto languages = adoptOSObject(xpc_array_create(nullptr, 0));
130         Vector<String> languageVector;
131         languagesIterator->value.split(",", false, languageVector);
132         for (auto& language : languageVector)
133             xpc_array_set_string(languages.get(), XPC_ARRAY_APPEND, language.utf8().data());
134         xpc_dictionary_set_value(initializationMessage.get(), "OverrideLanguages", languages.get());
135     }
136
137 #if PLATFORM(MAC)
138     xpc_dictionary_set_string(initializationMessage.get(), "WebKitBundleVersion", [[NSBundle bundleWithIdentifier:@"com.apple.WebKit"].infoDictionary[(__bridge NSString *)kCFBundleVersionKey] UTF8String]);
139 #endif
140     xpc_connection_set_bootstrap(m_xpcConnection.get(), initializationMessage.get());
141
142     if (shouldLeakBoost(m_launchOptions)) {
143         auto preBootstrapMessage = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
144         xpc_dictionary_set_string(preBootstrapMessage.get(), "message-name", "pre-bootstrap");
145         xpc_connection_send_message(m_xpcConnection.get(), preBootstrapMessage.get());
146     }
147     
148     // Create the listening port.
149     mach_port_t listeningPort;
150     mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
151     
152     // Insert a send right so we can send to it.
153     mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND);
154
155     mach_port_t previousNotificationPort;
156     mach_port_request_notification(mach_task_self(), listeningPort, MACH_NOTIFY_NO_SENDERS, 0, listeningPort, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previousNotificationPort);
157     ASSERT(!previousNotificationPort);
158
159     String clientIdentifier;
160 #if PLATFORM(MAC)
161     clientIdentifier = codeSigningIdentifierForCurrentProcess();
162 #endif
163     if (clientIdentifier.isNull())
164         clientIdentifier = [[NSBundle mainBundle] bundleIdentifier];
165
166     // FIXME: Switch to xpc_connection_set_bootstrap once it's available everywhere we need.
167     auto bootstrapMessage = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
168     xpc_dictionary_set_string(bootstrapMessage.get(), "message-name", "bootstrap");
169
170     xpc_dictionary_set_mach_send(bootstrapMessage.get(), "server-port", listeningPort);
171     mach_port_deallocate(mach_task_self(), listeningPort);
172
173     xpc_dictionary_set_string(bootstrapMessage.get(), "client-identifier", !clientIdentifier.isEmpty() ? clientIdentifier.utf8().data() : *_NSGetProgname());
174     xpc_dictionary_set_string(bootstrapMessage.get(), "ui-process-name", [[[NSProcessInfo processInfo] processName] UTF8String]);
175
176     bool isWebKitDevelopmentBuild = ![[[[NSBundle bundleWithIdentifier:@"com.apple.WebKit"] bundlePath] stringByDeletingLastPathComponent] hasPrefix:systemDirectoryPath()];
177     if (isWebKitDevelopmentBuild) {
178         xpc_dictionary_set_fd(bootstrapMessage.get(), "stdout", STDOUT_FILENO);
179         xpc_dictionary_set_fd(bootstrapMessage.get(), "stderr", STDERR_FILENO);
180     }
181
182     auto extraInitializationData = adoptOSObject(xpc_dictionary_create(nullptr, nullptr, 0));
183
184     for (const auto& keyValuePair : m_launchOptions.extraInitializationData)
185         xpc_dictionary_set_string(extraInitializationData.get(), keyValuePair.key.utf8().data(), keyValuePair.value.utf8().data());
186
187     xpc_dictionary_set_value(bootstrapMessage.get(), "extra-initialization-data", extraInitializationData.get());
188
189     auto weakProcessLauncher = m_weakPtrFactory.createWeakPtr(*this);
190     xpc_connection_set_event_handler(m_xpcConnection.get(), [weakProcessLauncher, listeningPort](xpc_object_t event) {
191         ASSERT(xpc_get_type(event) == XPC_TYPE_ERROR);
192
193         auto processLauncher = weakProcessLauncher.get();
194         if (!processLauncher)
195             return;
196
197         if (!processLauncher->isLaunching())
198             return;
199
200         // We failed to launch. Release the send right.
201         mach_port_deallocate(mach_task_self(), listeningPort);
202
203         // And the receive right.
204         mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1);
205
206         if (processLauncher->m_xpcConnection)
207             xpc_connection_cancel(processLauncher->m_xpcConnection.get());
208         processLauncher->m_xpcConnection = nullptr;
209
210         processLauncher->didFinishLaunchingProcess(0, IPC::Connection::Identifier());
211     });
212
213     xpc_connection_resume(m_xpcConnection.get());
214
215     ref();
216     xpc_connection_send_message_with_reply(m_xpcConnection.get(), bootstrapMessage.get(), dispatch_get_main_queue(), ^(xpc_object_t reply) {
217         // Errors are handled in the event handler.
218         if (xpc_get_type(reply) != XPC_TYPE_ERROR) {
219             ASSERT(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);
220             ASSERT(!strcmp(xpc_dictionary_get_string(reply, "message-name"), "process-finished-launching"));
221
222             if (!m_xpcConnection) {
223                 // The process was terminated.
224                 didFinishLaunchingProcess(0, IPC::Connection::Identifier());
225                 return;
226             }
227
228             // The process has finished launching, grab the pid from the connection.
229             pid_t processIdentifier = xpc_connection_get_pid(m_xpcConnection.get());
230
231             didFinishLaunchingProcess(processIdentifier, IPC::Connection::Identifier(listeningPort, m_xpcConnection));
232             m_xpcConnection = nullptr;
233         }
234
235         deref();
236     });
237 }
238
239 void ProcessLauncher::terminateProcess()
240 {
241     if (m_isLaunching) {
242         invalidate();
243         return;
244     }
245
246     if (!m_processIdentifier)
247         return;
248     
249     kill(m_processIdentifier, SIGKILL);
250     m_processIdentifier = 0;
251 }
252     
253 void ProcessLauncher::platformInvalidate()
254 {
255     if (!m_xpcConnection)
256         return;
257
258     xpc_connection_cancel(m_xpcConnection.get());
259     xpc_connection_kill(m_xpcConnection.get(), SIGKILL);
260     m_xpcConnection = nullptr;
261 }
262
263 } // namespace WebKit