Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / mac / relauncher.cc
blob5d8357fc5dcbe428d13a75b38044b7c7ae14b256
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/mac/relauncher.h"
7 #include <ApplicationServices/ApplicationServices.h>
8 #include <AvailabilityMacros.h>
9 #include <crt_externs.h>
10 #include <dlfcn.h>
11 #include <string.h>
12 #include <sys/event.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <unistd.h>
17 #include <string>
18 #include <vector>
20 #include "base/basictypes.h"
21 #include "base/file_util.h"
22 #include "base/logging.h"
23 #include "base/mac/mac_logging.h"
24 #include "base/mac/mac_util.h"
25 #include "base/mac/scoped_cftyperef.h"
26 #include "base/path_service.h"
27 #include "base/posix/eintr_wrapper.h"
28 #include "base/process/launch.h"
29 #include "base/strings/stringprintf.h"
30 #include "base/strings/sys_string_conversions.h"
31 #include "chrome/browser/mac/install_from_dmg.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "content/public/common/content_paths.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/main_function_params.h"
37 namespace mac_relauncher {
39 const char* const kRelauncherDMGDeviceArg = "--dmg-device=";
41 namespace {
43 // The "magic" file descriptor that the relauncher process' write side of the
44 // pipe shows up on. Chosen to avoid conflicting with stdin, stdout, and
45 // stderr.
46 const int kRelauncherSyncFD = STDERR_FILENO + 1;
48 // The argument separating arguments intended for the relauncher process from
49 // those intended for the relaunched process. "---" is chosen instead of "--"
50 // because CommandLine interprets "--" as meaning "end of switches", but
51 // for many purposes, the relauncher process' CommandLine ought to interpret
52 // arguments intended for the relaunched process, to get the correct settings
53 // for such things as logging and the user-data-dir in case it affects crash
54 // reporting.
55 const char kRelauncherArgSeparator[] = "---";
57 // When this argument is supplied to the relauncher process, it will launch
58 // the relaunched process without bringing it to the foreground.
59 const char kRelauncherBackgroundArg[] = "--background";
61 // The beginning of the "process serial number" argument that Launch Services
62 // sometimes inserts into command lines. A process serial number is only valid
63 // for a single process, so any PSN arguments will be stripped from command
64 // lines during relaunch to avoid confusion.
65 const char kPSNArg[] = "-psn_";
67 // Returns the "type" argument identifying a relauncher process
68 // ("--type=relauncher").
69 std::string RelauncherTypeArg() {
70 return base::StringPrintf("--%s=%s",
71 switches::kProcessType,
72 switches::kRelauncherProcess);
75 } // namespace
77 bool RelaunchApp(const std::vector<std::string>& args) {
78 // Use the currently-running application's helper process. The automatic
79 // update feature is careful to leave the currently-running version alone,
80 // so this is safe even if the relaunch is the result of an update having
81 // been applied. In fact, it's safer than using the updated version of the
82 // helper process, because there's no guarantee that the updated version's
83 // relauncher implementation will be compatible with the running version's.
84 base::FilePath child_path;
85 if (!PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) {
86 LOG(ERROR) << "No CHILD_PROCESS_EXE";
87 return false;
90 std::vector<std::string> relauncher_args;
91 return RelaunchAppWithHelper(child_path.value(), relauncher_args, args);
94 bool RelaunchAppWithHelper(const std::string& helper,
95 const std::vector<std::string>& relauncher_args,
96 const std::vector<std::string>& args) {
97 std::vector<std::string> relaunch_args;
98 relaunch_args.push_back(helper);
99 relaunch_args.push_back(RelauncherTypeArg());
101 // If this application isn't in the foreground, the relaunched one shouldn't
102 // be either.
103 if (!base::mac::AmIForeground()) {
104 relaunch_args.push_back(kRelauncherBackgroundArg);
107 relaunch_args.insert(relaunch_args.end(),
108 relauncher_args.begin(), relauncher_args.end());
110 relaunch_args.push_back(kRelauncherArgSeparator);
112 // When using the CommandLine interface, -psn_ may have been rewritten as
113 // --psn_. Look for both.
114 const char alt_psn_arg[] = "--psn_";
115 for (size_t index = 0; index < args.size(); ++index) {
116 // Strip any -psn_ arguments, as they apply to a specific process.
117 if (args[index].compare(0, strlen(kPSNArg), kPSNArg) != 0 &&
118 args[index].compare(0, strlen(alt_psn_arg), alt_psn_arg) != 0) {
119 relaunch_args.push_back(args[index]);
123 int pipe_fds[2];
124 if (HANDLE_EINTR(pipe(pipe_fds)) != 0) {
125 PLOG(ERROR) << "pipe";
126 return false;
129 // The parent process will only use pipe_read_fd as the read side of the
130 // pipe. It can close the write side as soon as the relauncher process has
131 // forked off. The relauncher process will only use pipe_write_fd as the
132 // write side of the pipe. In that process, the read side will be closed by
133 // base::LaunchApp because it won't be present in fd_map, and the write side
134 // will be remapped to kRelauncherSyncFD by fd_map.
135 file_util::ScopedFD pipe_read_fd(&pipe_fds[0]);
136 file_util::ScopedFD pipe_write_fd(&pipe_fds[1]);
138 // Make sure kRelauncherSyncFD is a safe value. base::LaunchProcess will
139 // preserve these three FDs in forked processes, so kRelauncherSyncFD should
140 // not conflict with them.
141 COMPILE_ASSERT(kRelauncherSyncFD != STDIN_FILENO &&
142 kRelauncherSyncFD != STDOUT_FILENO &&
143 kRelauncherSyncFD != STDERR_FILENO,
144 kRelauncherSyncFD_must_not_conflict_with_stdio_fds);
146 base::FileHandleMappingVector fd_map;
147 fd_map.push_back(std::make_pair(*pipe_write_fd, kRelauncherSyncFD));
149 base::LaunchOptions options;
150 options.fds_to_remap = &fd_map;
151 if (!base::LaunchProcess(relaunch_args, options, NULL)) {
152 LOG(ERROR) << "base::LaunchProcess failed";
153 return false;
156 // The relauncher process is now starting up, or has started up. The
157 // original parent process continues.
159 pipe_write_fd.reset(); // close(pipe_fds[1]);
161 // Synchronize with the relauncher process.
162 char read_char;
163 int read_result = HANDLE_EINTR(read(*pipe_read_fd, &read_char, 1));
164 if (read_result != 1) {
165 if (read_result < 0) {
166 PLOG(ERROR) << "read";
167 } else {
168 LOG(ERROR) << "read: unexpected result " << read_result;
170 return false;
173 // Since a byte has been successfully read from the relauncher process, it's
174 // guaranteed to have set up its kqueue monitoring this process for exit.
175 // It's safe to exit now.
176 return true;
179 namespace {
181 // In the relauncher process, performs the necessary synchronization steps
182 // with the parent by setting up a kqueue to watch for it to exit, writing a
183 // byte to the pipe, and then waiting for the exit notification on the kqueue.
184 // If anything fails, this logs a message and returns immediately. In those
185 // situations, it can be assumed that something went wrong with the parent
186 // process and the best recovery approach is to attempt relaunch anyway.
187 void RelauncherSynchronizeWithParent() {
188 // file_util::ScopedFD needs something non-const to operate on.
189 int relauncher_sync_fd = kRelauncherSyncFD;
190 file_util::ScopedFD relauncher_sync_fd_closer(&relauncher_sync_fd);
192 int parent_pid = getppid();
194 // PID 1 identifies init. launchd, that is. launchd never starts the
195 // relauncher process directly, having this parent_pid means that the parent
196 // already exited and launchd "inherited" the relauncher as its child.
197 // There's no reason to synchronize with launchd.
198 if (parent_pid == 1) {
199 LOG(ERROR) << "unexpected parent_pid";
200 return;
203 // Set up a kqueue to monitor the parent process for exit.
204 int kq = kqueue();
205 if (kq < 0) {
206 PLOG(ERROR) << "kqueue";
207 return;
209 file_util::ScopedFD kq_closer(&kq);
211 struct kevent change = { 0 };
212 EV_SET(&change, parent_pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
213 if (kevent(kq, &change, 1, NULL, 0, NULL) == -1) {
214 PLOG(ERROR) << "kevent (add)";
215 return;
218 // Write a '\0' character to the pipe.
219 if (HANDLE_EINTR(write(relauncher_sync_fd, "", 1)) != 1) {
220 PLOG(ERROR) << "write";
221 return;
224 // Up until now, the parent process was blocked in a read waiting for the
225 // write above to complete. The parent process is now free to exit. Wait for
226 // that to happen.
227 struct kevent event;
228 int events = kevent(kq, NULL, 0, &event, 1, NULL);
229 if (events != 1) {
230 if (events < 0) {
231 PLOG(ERROR) << "kevent (monitor)";
232 } else {
233 LOG(ERROR) << "kevent (monitor): unexpected result " << events;
235 return;
238 if (event.filter != EVFILT_PROC ||
239 event.fflags != NOTE_EXIT ||
240 event.ident != static_cast<uintptr_t>(parent_pid)) {
241 LOG(ERROR) << "kevent (monitor): unexpected event, filter " << event.filter
242 << ", fflags " << event.fflags << ", ident " << event.ident;
243 return;
247 } // namespace
249 namespace internal {
251 int RelauncherMain(const content::MainFunctionParams& main_parameters) {
252 // CommandLine rearranges the order of the arguments returned by
253 // main_parameters.argv(), rendering it impossible to determine which
254 // arguments originally came before kRelauncherArgSeparator and which came
255 // after. It's crucial to distinguish between these because only those
256 // after the separator should be given to the relaunched process; it's also
257 // important to not treat the path to the relaunched process as a "loose"
258 // argument. NXArgc and NXArgv are pointers to the original argc and argv as
259 // passed to main(), so use those. Access them through _NSGetArgc and
260 // _NSGetArgv because NXArgc and NXArgv are normally only available to a
261 // main executable via crt1.o and this code will run from a dylib, and
262 // because of http://crbug.com/139902.
263 const int* argcp = _NSGetArgc();
264 if (!argcp) {
265 NOTREACHED();
266 return 1;
268 int argc = *argcp;
270 const char* const* const* argvp = _NSGetArgv();
271 if (!argvp) {
272 NOTREACHED();
273 return 1;
275 const char* const* argv = *argvp;
277 if (argc < 4 || RelauncherTypeArg() != argv[1]) {
278 LOG(ERROR) << "relauncher process invoked with unexpected arguments";
279 return 1;
282 RelauncherSynchronizeWithParent();
284 // The capacity for relaunch_args is 4 less than argc, because it
285 // won't contain the argv[0] of the relauncher process, the
286 // RelauncherTypeArg() at argv[1], kRelauncherArgSeparator, or the
287 // executable path of the process to be launched.
288 base::ScopedCFTypeRef<CFMutableArrayRef> relaunch_args(
289 CFArrayCreateMutable(NULL, argc - 4, &kCFTypeArrayCallBacks));
290 if (!relaunch_args) {
291 LOG(ERROR) << "CFArrayCreateMutable";
292 return 1;
295 // Figure out what to execute, what arguments to pass it, and whether to
296 // start it in the background.
297 bool background = false;
298 bool in_relaunch_args = false;
299 std::string dmg_bsd_device_name;
300 bool seen_relaunch_executable = false;
301 std::string relaunch_executable;
302 const std::string relauncher_arg_separator(kRelauncherArgSeparator);
303 for (int argv_index = 2; argv_index < argc; ++argv_index) {
304 const std::string arg(argv[argv_index]);
306 // Strip any -psn_ arguments, as they apply to a specific process.
307 if (arg.compare(0, strlen(kPSNArg), kPSNArg) == 0) {
308 continue;
311 if (!in_relaunch_args) {
312 if (arg == relauncher_arg_separator) {
313 in_relaunch_args = true;
314 } else if (arg == kRelauncherBackgroundArg) {
315 background = true;
316 } else if (arg.compare(0, strlen(kRelauncherDMGDeviceArg),
317 kRelauncherDMGDeviceArg) == 0) {
318 dmg_bsd_device_name.assign(arg.substr(strlen(kRelauncherDMGDeviceArg)));
320 } else {
321 if (!seen_relaunch_executable) {
322 // The first argument after kRelauncherBackgroundArg is the path to
323 // the executable file or .app bundle directory. The Launch Services
324 // interface wants this separate from the rest of the arguments. In
325 // the relaunched process, this path will still be visible at argv[0].
326 relaunch_executable.assign(arg);
327 seen_relaunch_executable = true;
328 } else {
329 base::ScopedCFTypeRef<CFStringRef> arg_cf(
330 base::SysUTF8ToCFStringRef(arg));
331 if (!arg_cf) {
332 LOG(ERROR) << "base::SysUTF8ToCFStringRef failed for " << arg;
333 return 1;
335 CFArrayAppendValue(relaunch_args, arg_cf);
340 if (!seen_relaunch_executable) {
341 LOG(ERROR) << "nothing to relaunch";
342 return 1;
345 FSRef app_fsref;
346 if (!base::mac::FSRefFromPath(relaunch_executable, &app_fsref)) {
347 LOG(ERROR) << "base::mac::FSRefFromPath failed for " << relaunch_executable;
348 return 1;
351 LSApplicationParameters ls_parameters = {
352 0, // version
353 kLSLaunchDefaults | kLSLaunchAndDisplayErrors | kLSLaunchNewInstance |
354 (background ? kLSLaunchDontSwitch : 0),
355 &app_fsref,
356 NULL, // asyncLaunchRefCon
357 NULL, // environment
358 relaunch_args,
359 NULL // initialEvent
362 OSStatus status = LSOpenApplication(&ls_parameters, NULL);
363 if (status != noErr) {
364 OSSTATUS_LOG(ERROR, status) << "LSOpenApplication";
365 return 1;
368 // The application should have relaunched (or is in the process of
369 // relaunching). From this point on, only clean-up tasks should occur, and
370 // failures are tolerable.
372 if (!dmg_bsd_device_name.empty()) {
373 EjectAndTrashDiskImage(dmg_bsd_device_name);
376 return 0;
379 } // namespace internal
381 } // namespace mac_relauncher