63758bb77dbb78b4df3fc7985c73114e546cf5cc
[WebKit-https.git] / Source / WebKit2 / UIProcess / Launcher / mac / ProcessLauncherMac.mm
1 /*
2  * Copyright (C) 2010, 2011, 2012 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 "DynamicLinkerEnvironmentExtractor.h"
30 #import "EnvironmentVariables.h"
31 #import "WebKitSystemInterface.h"
32 #import <WebCore/RunLoop.h>
33 #import <crt_externs.h>
34 #import <mach-o/dyld.h>
35 #import <mach/machine.h>
36 #import <runtime/InitializeThreading.h>
37 #import <servers/bootstrap.h>
38 #import <spawn.h>
39 #import <sys/param.h>
40 #import <sys/stat.h>
41 #import <wtf/PassRefPtr.h>
42 #import <wtf/RetainPtr.h>
43 #import <wtf/Threading.h>
44 #import <wtf/text/CString.h>
45 #import <wtf/text/WTFString.h>
46
47 #if HAVE(XPC)
48 #import <xpc/xpc.h>
49 #endif
50
51 using namespace WebCore;
52
53 // FIXME: We should be doing this another way.
54 extern "C" kern_return_t bootstrap_register2(mach_port_t, name_t, mach_port_t, uint64_t);
55
56 #if HAVE(XPC)
57 extern "C" void xpc_connection_set_instance(xpc_connection_t, uuid_t);
58 extern "C" void xpc_dictionary_set_mach_send(xpc_object_t, const char*, mach_port_t);
59 #endif
60
61 namespace WebKit {
62
63 namespace {
64
65 struct UUIDHolder : public RefCounted<UUIDHolder> {
66     static PassRefPtr<UUIDHolder> create()
67     {
68         return adoptRef(new UUIDHolder);
69     }
70
71     UUIDHolder()
72     {
73         uuid_generate(uuid);
74     }
75
76     uuid_t uuid;
77 };
78
79 }
80
81 static void setUpTerminationNotificationHandler(pid_t pid)
82 {
83 #if HAVE(DISPATCH_H)
84     dispatch_source_t processDiedSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, pid, DISPATCH_PROC_EXIT, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
85     dispatch_source_set_event_handler(processDiedSource, ^{
86         int status;
87         waitpid(dispatch_source_get_handle(processDiedSource), &status, 0);
88         dispatch_source_cancel(processDiedSource);
89     });
90     dispatch_source_set_cancel_handler(processDiedSource, ^{
91         dispatch_release(processDiedSource);
92     });
93     dispatch_resume(processDiedSource);
94 #endif
95 }
96
97 static void addDYLDEnvironmentAdditions(const ProcessLauncher::LaunchOptions& launchOptions, bool isWebKitDevelopmentBuild, EnvironmentVariables& environmentVariables)
98 {
99     DynamicLinkerEnvironmentExtractor environmentExtractor([[NSBundle mainBundle] executablePath], _NSGetMachExecuteHeader()->cputype);
100     environmentExtractor.getExtractedEnvironmentVariables(environmentVariables);
101
102     NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"];
103     NSString *frameworksPath = [[webKit2Bundle bundlePath] stringByDeletingLastPathComponent];
104
105     // To make engineering builds work, if the path is outside of /System set up
106     // DYLD_FRAMEWORK_PATH to pick up other frameworks, but don't do it for the
107     // production configuration because it involves extra file system access.
108     if (isWebKitDevelopmentBuild)
109         environmentVariables.appendValue("DYLD_FRAMEWORK_PATH", [frameworksPath fileSystemRepresentation], ':');
110
111     NSString *processShimPathNSString = nil;
112 #if ENABLE(PLUGIN_PROCESS)
113     if (launchOptions.processType == ProcessLauncher::PluginProcess) {
114         NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"PluginProcess.app"];
115         NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath];
116
117         processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"PluginProcessShim.dylib"];
118     } else
119 #endif // ENABLE(PLUGIN_PROCESS)
120     if (launchOptions.processType == ProcessLauncher::WebProcess) {
121         NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"WebProcess.app"];
122         NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath];
123
124         processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"SecItemShim.dylib"];
125     } else if (launchOptions.processType == ProcessLauncher::NetworkProcess) {
126         NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"NetworkProcess.app"];
127         NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath];
128
129         processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"SecItemShim.dylib"];
130     }
131
132     // Make sure that the shim library file exists and insert it.
133     if (processShimPathNSString) {
134         const char* processShimPath = [processShimPathNSString fileSystemRepresentation];
135         struct stat statBuf;
136         if (stat(processShimPath, &statBuf) == 0 && (statBuf.st_mode & S_IFMT) == S_IFREG)
137             environmentVariables.appendValue("DYLD_INSERT_LIBRARIES", processShimPath, ':');
138     }
139
140 }
141
142 typedef void (ProcessLauncher::*DidFinishLaunchingProcessFunction)(PlatformProcessIdentifier, CoreIPC::Connection::Identifier);
143
144 #if HAVE(XPC)
145
146 static const char* serviceName(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment)
147 {
148     switch (launchOptions.processType) {
149     case ProcessLauncher::WebProcess:
150         if (forDevelopment)
151             return "com.apple.WebKit.WebContent.Development";
152         return "com.apple.WebKit.WebContent";
153 #if ENABLE(NETWORK_PROCESS)
154     case ProcessLauncher::NetworkProcess:
155         if (forDevelopment)
156             return "com.apple.WebKit.Networking.Development";
157         return "com.apple.WebKit.Networking";
158 #endif
159 #if ENABLE(PLUGIN_PROCESS)
160     case ProcessLauncher::PluginProcess:
161         if (forDevelopment)
162             return "com.apple.WebKit.Plugin.Development";
163
164         // FIXME: Support plugins that require an executable heap.
165         if (launchOptions.architecture == CPU_TYPE_X86)
166             return "com.apple.WebKit.Plugin.32";
167         if (launchOptions.architecture == CPU_TYPE_X86_64)
168             return "com.apple.WebKit.Plugin.64";
169
170         ASSERT_NOT_REACHED();
171         return 0;
172 #endif
173 #if ENABLE(SHARED_WORKER_PROCESS)
174     case ProcessLauncher::SharedWorkerProcess:
175         ASSERT_NOT_REACHED();
176         return 0;
177 #endif
178     }
179 }
180
181 static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction, UUIDHolder* instanceUUID)
182 {
183     // Create a connection to the WebKit2 XPC service.
184     xpc_connection_t connection = xpc_connection_create(serviceName(launchOptions, forDevelopment), 0);
185     xpc_connection_set_instance(connection, instanceUUID->uuid);
186
187     // XPC requires having an event handler, even if it is not used.
188     xpc_connection_set_event_handler(connection, ^(xpc_object_t event) { });
189     xpc_connection_resume(connection);
190
191     // Create the listening port.
192     mach_port_t listeningPort;
193     mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
194     
195     // Insert a send right so we can send to it.
196     mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND);
197
198     NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
199     CString clientIdentifier = bundleIdentifier ? String([[NSBundle mainBundle] bundleIdentifier]).utf8() : *_NSGetProgname();
200
201     xpc_object_t bootstrapMessage = xpc_dictionary_create(0, 0, 0);
202     xpc_dictionary_set_string(bootstrapMessage, "message-name", "bootstrap");
203     xpc_dictionary_set_string(bootstrapMessage, "framework-executable-path", [[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] executablePath] fileSystemRepresentation]);
204     xpc_dictionary_set_mach_send(bootstrapMessage, "server-port", listeningPort);
205     xpc_dictionary_set_string(bootstrapMessage, "client-identifier", clientIdentifier.data());
206     xpc_dictionary_set_string(bootstrapMessage, "ui-process-name", [[[NSProcessInfo processInfo] processName] UTF8String]);
207
208     if (forDevelopment) {
209         xpc_dictionary_set_fd(bootstrapMessage, "stdout", STDOUT_FILENO);
210         xpc_dictionary_set_fd(bootstrapMessage, "stderr", STDERR_FILENO);
211     }
212
213     xpc_object_t extraInitializationData = xpc_dictionary_create(0, 0, 0);
214     HashMap<String, String>::const_iterator it = launchOptions.extraInitializationData.begin();
215     HashMap<String, String>::const_iterator end = launchOptions.extraInitializationData.end();
216     for (; it != end; ++it)
217         xpc_dictionary_set_string(extraInitializationData, it->key.utf8().data(), it->value.utf8().data());
218     xpc_dictionary_set_value(bootstrapMessage, "extra-initialization-data", extraInitializationData);
219     xpc_release(extraInitializationData);
220
221     that->ref();
222
223     xpc_connection_send_message_with_reply(connection, bootstrapMessage, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t reply) {
224         xpc_type_t type = xpc_get_type(reply);
225         if (type == XPC_TYPE_ERROR) {
226             // We failed to launch. Release the send right.
227             mach_port_deallocate(mach_task_self(), listeningPort);
228
229             // And the receive right.
230             mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1);
231
232             RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, 0, CoreIPC::Connection::Identifier()));
233         } else {
234             ASSERT(type == XPC_TYPE_DICTIONARY);
235             ASSERT(!strcmp(xpc_dictionary_get_string(reply, "message-name"), "process-finished-launching"));
236
237             // The process has finished launching, grab the pid from the connection.
238             pid_t processIdentifier = xpc_connection_get_pid(connection);
239
240             // We've finished launching the process, message back to the main run loop.
241             RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort, connection)));
242         }
243
244         that->deref();
245     });
246     xpc_release(bootstrapMessage);
247 }
248
249 static void connectToReExecService(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction)
250 {
251     EnvironmentVariables environmentVariables;
252     addDYLDEnvironmentAdditions(launchOptions, true, environmentVariables);
253
254     // Generate the uuid for the service instance we are about to create.
255     // FIXME: This UUID should be stored on the ChildProcessProxy.
256     RefPtr<UUIDHolder> instanceUUID = UUIDHolder::create();
257
258     xpc_connection_t reExecConnection = xpc_connection_create(serviceName(launchOptions, true), 0);
259     xpc_connection_set_instance(reExecConnection, instanceUUID->uuid);
260
261     // Keep the ProcessLauncher alive while we do the re-execing (balanced in event handler).
262     that->ref();
263
264     // We wait for the connection to tear itself down (indicated via an error event)
265     // to indicate that the service instance re-execed itself, and is now ready to be
266     // connected to.
267     xpc_connection_set_event_handler(reExecConnection, ^(xpc_object_t event) {
268         ASSERT(xpc_get_type(event) == XPC_TYPE_ERROR);
269
270         connectToService(launchOptions, true, that, didFinishLaunchingProcessFunction, instanceUUID.get());
271
272         // Release the connection.
273         xpc_release(reExecConnection);
274
275         // Other end of ref called before we setup the event handler.
276         that->deref();
277     });
278     xpc_connection_resume(reExecConnection);
279
280     xpc_object_t reExecMessage = xpc_dictionary_create(0, 0, 0);
281     xpc_dictionary_set_string(reExecMessage, "message-name", "re-exec");
282
283     cpu_type_t architecture = launchOptions.architecture == ProcessLauncher::LaunchOptions::MatchCurrentArchitecture ? _NSGetMachExecuteHeader()->cputype : launchOptions.architecture;
284     xpc_dictionary_set_uint64(reExecMessage, "architecture", (uint64_t)architecture);
285     
286     xpc_object_t environment = xpc_array_create(0, 0);
287     char** environmentPointer = environmentVariables.environmentPointer();
288     Vector<CString> temps;
289     for (size_t i = 0; environmentPointer[i]; ++i) {
290         CString temp(environmentPointer[i], strlen(environmentPointer[i]));
291         temps.append(temp);
292
293         xpc_array_set_string(environment, XPC_ARRAY_APPEND, temp.data());
294     }
295     xpc_dictionary_set_value(reExecMessage, "environment", environment);
296     xpc_release(environment);
297
298     xpc_dictionary_set_bool(reExecMessage, "executable-heap", launchOptions.executableHeap);
299
300     xpc_connection_send_message(reExecConnection, reExecMessage);
301     xpc_release(reExecMessage);
302 }
303
304 static void createService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction)
305 {
306     if (forDevelopment) {
307         connectToReExecService(launchOptions, that, didFinishLaunchingProcessFunction);
308         return;
309     }
310
311     // Generate the uuid for the service instance we are about to create.
312     // FIXME: This UUID should be stored on the ChildProcessProxy.
313     RefPtr<UUIDHolder> instanceUUID = UUIDHolder::create();
314     connectToService(launchOptions, false, that, didFinishLaunchingProcessFunction, instanceUUID.get());
315 }
316
317 #endif
318
319 static bool tryPreexistingProcess(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction)
320 {
321     EnvironmentVariables environmentVariables;
322     static const char* preexistingProcessServiceName = environmentVariables.get(EnvironmentVariables::preexistingProcessServiceNameKey());
323
324     ProcessLauncher::ProcessType preexistingProcessType;
325     if (preexistingProcessServiceName)
326         ProcessLauncher::getProcessTypeFromString(environmentVariables.get(EnvironmentVariables::preexistingProcessTypeKey()), preexistingProcessType);
327
328     bool usePreexistingProcess = preexistingProcessServiceName && preexistingProcessType == launchOptions.processType;
329     if (!usePreexistingProcess)
330         return false;
331
332     // Create the listening port.
333     mach_port_t listeningPort;
334     mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
335     
336     // Insert a send right so we can send to it.
337     mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND);
338
339     pid_t processIdentifier = 0;
340
341     mach_port_t lookupPort;
342     bootstrap_look_up(bootstrap_port, preexistingProcessServiceName, &lookupPort);
343
344     mach_msg_header_t header;
345     header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND);
346     header.msgh_id = 0;
347     header.msgh_local_port = listeningPort;
348     header.msgh_remote_port = lookupPort;
349     header.msgh_size = sizeof(header);
350     kern_return_t kr = mach_msg(&header, MACH_SEND_MSG, sizeof(header), 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
351
352     mach_port_deallocate(mach_task_self(), lookupPort);
353     preexistingProcessServiceName = 0;
354
355     if (kr) {
356         LOG_ERROR("Failed to pick up preexisting process at %s (%x). Launching a new process of type %s instead.", preexistingProcessServiceName, kr, ProcessLauncher::processTypeAsString(launchOptions.processType));
357         return false;
358     }
359     
360     // We've finished launching the process, message back to the main run loop.
361     RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort)));
362     return true;
363 }
364
365 static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, bool isWebKitDevelopmentBuild, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction)
366 {
367     EnvironmentVariables environmentVariables;
368     addDYLDEnvironmentAdditions(launchOptions, isWebKitDevelopmentBuild, environmentVariables);
369
370     // Create the listening port.
371     mach_port_t listeningPort;
372     mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
373
374     // Insert a send right so we can send to it.
375     mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND);
376
377     RetainPtr<CFStringRef> cfLocalization(AdoptCF, WKCopyCFLocalizationPreferredName(NULL));
378     CString localization = String(cfLocalization.get()).utf8();
379
380     NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"];
381
382     NSString *processPath = nil;
383     switch (launchOptions.processType) {
384     case ProcessLauncher::WebProcess:
385         processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"WebProcess.app"];
386         break;
387 #if ENABLE(PLUGIN_PROCESS)
388     case ProcessLauncher::PluginProcess:
389         processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"PluginProcess.app"];
390         break;
391 #endif
392 #if ENABLE(NETWORK_PROCESS)
393     case ProcessLauncher::NetworkProcess:
394         processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"NetworkProcess.app"];
395         break;
396 #endif
397 #if ENABLE(SHARED_WORKER_PROCESS)
398     case ProcessLauncher::SharedWorkerProcess:
399         processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"SharedWorkerProcess.app"];
400         break;
401 #endif
402     }
403
404     NSString *frameworkExecutablePath = [webKit2Bundle executablePath];
405     NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath];
406
407     NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
408     CString clientIdentifier = bundleIdentifier ? String([[NSBundle mainBundle] bundleIdentifier]).utf8() : *_NSGetProgname();
409
410     // Make a unique, per pid, per process launcher web process service name.
411     CString serviceName = String::format("com.apple.WebKit.WebProcess-%d-%p", getpid(), that).utf8();
412
413     Vector<const char*> args;
414     args.append([processAppExecutablePath fileSystemRepresentation]);
415     args.append([frameworkExecutablePath fileSystemRepresentation]);
416     args.append("-type");
417     args.append(ProcessLauncher::processTypeAsString(launchOptions.processType));
418     args.append("-servicename");
419     args.append(serviceName.data());
420     args.append("-localization");
421     args.append(localization.data());
422     args.append("-client-identifier");
423     args.append(clientIdentifier.data());
424     args.append("-ui-process-name");
425     args.append([[[NSProcessInfo processInfo] processName] UTF8String]);
426
427     HashMap<String, String>::const_iterator it = launchOptions.extraInitializationData.begin();
428     HashMap<String, String>::const_iterator end = launchOptions.extraInitializationData.end();
429     Vector<CString> temps;
430     for (; it != end; ++it) {
431         String keyPlusDash = "-" + it->key;
432         CString key(keyPlusDash.utf8().data());
433         temps.append(key);
434         args.append(key.data());
435
436         CString value(it->value.utf8().data());
437         temps.append(value);
438         args.append(value.data());
439     }
440
441     args.append(nullptr);
442
443     // Register ourselves.
444     kern_return_t kr = bootstrap_register2(bootstrap_port, const_cast<char*>(serviceName.data()), listeningPort, 0);
445     ASSERT_UNUSED(kr, kr == KERN_SUCCESS);
446
447     posix_spawnattr_t attr;
448     posix_spawnattr_init(&attr);
449
450     short flags = 0;
451
452     // We want our process to receive all signals.
453     sigset_t signalMaskSet;
454     sigemptyset(&signalMaskSet);
455
456     posix_spawnattr_setsigmask(&attr, &signalMaskSet);
457     flags |= POSIX_SPAWN_SETSIGMASK;
458
459     // Determine the architecture to use.
460     cpu_type_t architecture = launchOptions.architecture;
461     if (architecture == ProcessLauncher::LaunchOptions::MatchCurrentArchitecture)
462         architecture = _NSGetMachExecuteHeader()->cputype;
463
464     cpu_type_t cpuTypes[] = { architecture };
465     size_t outCount = 0;
466     posix_spawnattr_setbinpref_np(&attr, 1, cpuTypes, &outCount);
467
468     // Start suspended so we can set up the termination notification handler.
469     flags |= POSIX_SPAWN_START_SUSPENDED;
470
471     static const int allowExecutableHeapFlag = 0x2000;
472     if (launchOptions.executableHeap)
473         flags |= allowExecutableHeapFlag;
474
475     posix_spawnattr_setflags(&attr, flags);
476
477     pid_t processIdentifier = 0;
478     int result = posix_spawn(&processIdentifier, args[0], 0, &attr, const_cast<char**>(args.data()), environmentVariables.environmentPointer());
479
480     posix_spawnattr_destroy(&attr);
481
482     if (!result) {
483         // Set up the termination notification handler and then ask the child process to continue.
484         setUpTerminationNotificationHandler(processIdentifier);
485         kill(processIdentifier, SIGCONT);
486     } else {
487         // We failed to launch. Release the send right.
488         mach_port_deallocate(mach_task_self(), listeningPort);
489
490         // And the receive right.
491         mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1);
492     
493         listeningPort = MACH_PORT_NULL;
494         processIdentifier = 0;
495     }
496
497     // We've finished launching the process, message back to the main run loop.
498     RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort)));
499 }
500
501 void ProcessLauncher::launchProcess()
502 {
503     if (tryPreexistingProcess(m_launchOptions, this, &ProcessLauncher::didFinishLaunchingProcess))
504         return;
505
506     bool isWebKitDevelopmentBuild = ![[[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] bundlePath] stringByDeletingLastPathComponent] hasPrefix:@"/System/"];
507
508 #if HAVE(XPC)
509     if (m_launchOptions.useXPC) {
510         createService(m_launchOptions, isWebKitDevelopmentBuild, this, &ProcessLauncher::didFinishLaunchingProcess);
511         return;
512     }
513 #endif
514
515     createProcess(m_launchOptions, isWebKitDevelopmentBuild, this, &ProcessLauncher::didFinishLaunchingProcess);
516 }
517
518 void ProcessLauncher::terminateProcess()
519 {    
520     if (!m_processIdentifier)
521         return;
522     
523     kill(m_processIdentifier, SIGKILL);
524 }
525     
526 void ProcessLauncher::platformInvalidate()
527 {
528 }
529
530 } // namespace WebKit