Add a pre-bootstrap message for NetworkProcess XPC service
[WebKit-https.git] / Source / WebKit2 / Shared / EntryPointUtilities / mac / XPCService / XPCServiceMain.Development.mm
1 /*
2  * Copyright (C) 2013 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 <crt_externs.h>
27 #import <dlfcn.h>
28 #import <mach-o/dyld.h>
29 #import <spawn.h> 
30 #import <stdio.h>
31 #import <stdlib.h>
32 #import <xpc/xpc.h>
33
34 namespace WebKit {
35
36 static void XPCServiceEventHandler(xpc_connection_t peer)
37 {
38     xpc_connection_set_target_queue(peer, dispatch_get_main_queue());
39     xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
40         xpc_type_t type = xpc_get_type(event);
41         if (type == XPC_TYPE_ERROR) {
42             if (event == XPC_ERROR_CONNECTION_INVALID || event == XPC_ERROR_TERMINATION_IMMINENT) {
43                 // FIXME: Handle this case more gracefully.
44                 exit(EXIT_FAILURE);
45             }
46         } else {
47             assert(type == XPC_TYPE_DICTIONARY);
48
49             if (!strcmp(xpc_dictionary_get_string(event, "message-name"), "re-exec")) {
50                 posix_spawnattr_t attr;
51                 posix_spawnattr_init(&attr);
52
53                 short flags = 0;
54
55                 // We just want to set the process state, not actually launch a new process,
56                 // so we are going to use the darwin extension to posix_spawn POSIX_SPAWN_SETEXEC
57                 // to act like a more full featured exec.
58                 flags |= POSIX_SPAWN_SETEXEC;
59
60                 sigset_t signalMaskSet;
61                 sigemptyset(&signalMaskSet);
62                 posix_spawnattr_setsigmask(&attr, &signalMaskSet);
63                 flags |= POSIX_SPAWN_SETSIGMASK;
64
65                 static const int allowExecutableHeapFlag = 0x2000;
66                 if (xpc_dictionary_get_bool(event, "executable-heap"))
67                     flags |= allowExecutableHeapFlag;
68
69                 posix_spawnattr_setflags(&attr, flags);
70
71                 cpu_type_t cpuTypes[] = { (cpu_type_t)xpc_dictionary_get_uint64(event, "architecture") };
72                 size_t outCount = 0;
73                 posix_spawnattr_setbinpref_np(&attr, 1, cpuTypes, &outCount);
74
75                 char path[4 * PATH_MAX];
76                 uint32_t pathLength = sizeof(path);
77                 _NSGetExecutablePath(path, &pathLength);
78
79                 char** argv = *_NSGetArgv();
80                 const char* programName = argv[0];
81                 const char* args[] = { programName, 0 };
82
83                 xpc_object_t environmentArray = xpc_dictionary_get_value(event, "environment");
84                 size_t numberOfEnvironmentVariables = xpc_array_get_count(environmentArray);
85
86                 const char** environment = (const char**)malloc(numberOfEnvironmentVariables * sizeof(char*) + 1);
87                 for (size_t i = 0; i < numberOfEnvironmentVariables; ++i)
88                     environment[i] = xpc_array_get_string(environmentArray, i);
89                 environment[numberOfEnvironmentVariables] = 0;
90
91                 pid_t processIdentifier = 0;
92                 posix_spawn(&processIdentifier, path, 0, &attr, const_cast<char**>(args), const_cast<char**>(environment));
93
94                 posix_spawnattr_destroy(&attr);
95
96                 NSLog(@"Unable to re-exec for path: %s", path);
97                 exit(EXIT_FAILURE);
98             }
99
100             if (!strcmp(xpc_dictionary_get_string(event, "message-name"), "bootstrap")) {
101                 static void* frameworkLibrary = dlopen(xpc_dictionary_get_string(event, "framework-executable-path"), RTLD_NOW);
102                 if (!frameworkLibrary) {
103                     NSLog(@"Unable to load WebKit2.framework at path: %s (Error: %s)", xpc_dictionary_get_string(event, "framework-executable-path"), dlerror());
104                     exit(EXIT_FAILURE);
105                 }
106
107                 CFBundleRef webKit2Bundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.WebKit2"));
108                 CFStringRef entryPointFunctionName = (CFStringRef)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("WebKitEntryPoint"));
109
110                 typedef void (*InitializerFunction)(xpc_connection_t, xpc_object_t);
111                 InitializerFunction initializerFunctionPtr = reinterpret_cast<InitializerFunction>(CFBundleGetFunctionPointerForName(webKit2Bundle, entryPointFunctionName));
112                 if (!initializerFunctionPtr) {
113                     NSLog(@"Unable to find entry point in WebKit2.framework with name: %@", (NSString *)entryPointFunctionName);
114                     exit(EXIT_FAILURE);
115                 }
116
117                 xpc_object_t reply = xpc_dictionary_create_reply(event);
118                 xpc_dictionary_set_string(reply, "message-name", "process-finished-launching");
119                 xpc_connection_send_message(xpc_dictionary_get_remote_connection(event), reply);
120                 xpc_release(reply);
121
122                 dup2(xpc_dictionary_dup_fd(event, "stdout"), STDOUT_FILENO);
123                 dup2(xpc_dictionary_dup_fd(event, "stderr"), STDERR_FILENO);
124
125                 initializerFunctionPtr(peer, event);
126             }
127
128             if (!strcmp(xpc_dictionary_get_string(event, "message-name"), "pre-bootstrap")) {
129                 // Hold on to the pre-bootstrap message.
130                 xpc_retain(event);
131             }
132         }
133     });
134
135     xpc_connection_resume(peer);
136 }
137
138 } // namespace WebKit;
139
140 using namespace WebKit;
141
142 int main(int argc, char** argv)
143 {
144     xpc_main(XPCServiceEventHandler);
145     return 0;
146 }