1 // Copyright 2013 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 // This file contains functions for launching subprocesses.
7 #ifndef BASE_PROCESS_LAUNCH_H_
8 #define BASE_PROCESS_LAUNCH_H_
14 #include "base/base_export.h"
15 #include "base/basictypes.h"
16 #include "base/environment.h"
17 #include "base/process/process.h"
18 #include "base/process/process_handle.h"
19 #include "base/strings/string_piece.h"
22 #include "base/posix/file_descriptor_shuffle.h"
32 typedef std::vector
<HANDLE
> HandlesToInheritVector
;
34 // TODO(viettrungluu): Only define this on POSIX?
35 typedef std::vector
<std::pair
<int, int> > FileHandleMappingVector
;
37 // Options for launching a subprocess that are passed to LaunchProcess().
38 // The default constructor constructs the object with default options.
39 struct BASE_EXPORT LaunchOptions
{
41 // Delegate to be run in between fork and exec in the subprocess (see
42 // pre_exec_delegate below)
43 class BASE_EXPORT PreExecDelegate
{
46 virtual ~PreExecDelegate() {}
48 // Since this is to be run between fork and exec, and fork may have happened
49 // while multiple threads were running, this function needs to be async
51 virtual void RunAsyncSafe() = 0;
54 DISALLOW_COPY_AND_ASSIGN(PreExecDelegate
);
56 #endif // defined(OS_POSIX)
61 // If true, wait for the process to complete.
67 // If non-null, inherit exactly the list of handles in this vector (these
68 // handles must be inheritable). This is only supported on Vista and higher.
69 HandlesToInheritVector
* handles_to_inherit
;
71 // If true, the new process inherits handles from the parent. In production
72 // code this flag should be used only when running short-lived, trusted
73 // binaries, because open handles from other libraries and subsystems will
74 // leak to the child process, causing errors such as open socket hangs.
75 // Note: If |handles_to_inherit| is non-null, this flag is ignored and only
76 // those handles will be inherited (on Vista and higher).
79 // If non-null, runs as if the user represented by the token had launched it.
80 // Whether the application is visible on the interactive desktop depends on
81 // the token belonging to an interactive logon session.
83 // To avoid hard to diagnose problems, when specified this loads the
84 // environment variables associated with the user and if this operation fails
85 // the entire call fails as well.
86 UserTokenHandle as_user
;
88 // If true, use an empty string for the desktop name.
89 bool empty_desktop_name
;
91 // If non-null, launches the application in that job object. The process will
92 // be terminated immediately and LaunchProcess() will fail if assignment to
93 // the job object fails.
96 // Handles for the redirection of stdin, stdout and stderr. The handles must
97 // be inheritable. Caller should either set all three of them or none (i.e.
98 // there is no way to redirect stderr without redirecting stdin). The
99 // |inherit_handles| flag must be set to true when redirecting stdio stream.
101 HANDLE stdout_handle
;
102 HANDLE stderr_handle
;
104 // If set to true, ensures that the child process is launched with the
105 // CREATE_BREAKAWAY_FROM_JOB flag which allows it to breakout of the parent
107 bool force_breakaway_from_job_
;
109 // Set/unset environment variables. These are applied on top of the parent
110 // process environment. Empty (the default) means to inherit the same
111 // environment. See AlterEnvironment().
112 EnvironmentMap environ
;
114 // Clear the environment for the new process before processing changes from
118 // If non-null, remap file descriptors according to the mapping of
119 // src fd->dest fd to propagate FDs into the child process.
120 // This pointer is owned by the caller and must live through the
121 // call to LaunchProcess().
122 const FileHandleMappingVector
* fds_to_remap
;
124 // Each element is an RLIMIT_* constant that should be raised to its
125 // rlim_max. This pointer is owned by the caller and must live through
126 // the call to LaunchProcess().
127 const std::vector
<int>* maximize_rlimits
;
129 // If true, start the process in a new process group, instead of
130 // inheriting the parent's process group. The pgid of the child process
131 // will be the same as its pid.
132 bool new_process_group
;
134 #if defined(OS_LINUX)
135 // If non-zero, start the process using clone(), using flags as provided.
136 // Unlike in clone, clone_flags may not contain a custom termination signal
137 // that is sent to the parent when the child dies. The termination signal will
138 // always be set to SIGCHLD.
141 // By default, child processes will have the PR_SET_NO_NEW_PRIVS bit set. If
142 // true, then this bit will not be set in the new child process.
143 bool allow_new_privs
;
145 // Sets parent process death signal to SIGKILL.
146 bool kill_on_parent_death
;
147 #endif // defined(OS_LINUX)
149 #if defined(OS_POSIX)
150 // If not empty, change to this directory before execing the new process.
151 base::FilePath current_directory
;
153 // If non-null, a delegate to be run immediately prior to executing the new
154 // program in the child process.
156 // WARNING: If LaunchProcess is called in the presence of multiple threads,
157 // code running in this delegate essentially needs to be async-signal safe
158 // (see man 7 signal for a list of allowed functions).
159 PreExecDelegate
* pre_exec_delegate
;
160 #endif // defined(OS_POSIX)
162 #if defined(OS_CHROMEOS)
163 // If non-negative, the specified file descriptor will be set as the launched
164 // process' controlling terminal.
165 int ctrl_terminal_fd
;
166 #endif // defined(OS_CHROMEOS)
168 #if defined(OS_MACOSX)
169 // If this name is non-empty, the new child, after fork() but before exec(),
170 // will look up this server name in the bootstrap namespace. The resulting
171 // service port will be replaced as the bootstrap port in the child. Because
172 // the process's IPC space is cleared on exec(), any rights to the old
173 // bootstrap port will not be transferred to the new process.
174 std::string replacement_bootstrap_name
;
177 #endif // !defined(OS_WIN)
180 // Launch a process via the command line |cmdline|.
181 // See the documentation of LaunchOptions for details on |options|.
183 // Returns a valid Process upon success.
185 // Unix-specific notes:
186 // - All file descriptors open in the parent process will be closed in the
187 // child process except for any preserved by options::fds_to_remap, and
188 // stdin, stdout, and stderr. If not remapped by options::fds_to_remap,
189 // stdin is reopened as /dev/null, and the child is allowed to inherit its
190 // parent's stdout and stderr.
191 // - If the first argument on the command line does not contain a slash,
192 // PATH will be searched. (See man execvp.)
193 BASE_EXPORT Process
LaunchProcess(const CommandLine
& cmdline
,
194 const LaunchOptions
& options
);
197 // Windows-specific LaunchProcess that takes the command line as a
198 // string. Useful for situations where you need to control the
199 // command line arguments directly, but prefer the CommandLine version
200 // if launching Chrome itself.
202 // The first command line argument should be the path to the process,
203 // and don't forget to quote it.
205 // Example (including literal quotes)
206 // cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
207 BASE_EXPORT Process
LaunchProcess(const string16
& cmdline
,
208 const LaunchOptions
& options
);
210 // Launches a process with elevated privileges. This does not behave exactly
211 // like LaunchProcess as it uses ShellExecuteEx instead of CreateProcess to
212 // create the process. This means the process will have elevated privileges
213 // and thus some common operations like OpenProcess will fail. Currently the
214 // only supported LaunchOptions are |start_hidden| and |wait|.
215 BASE_EXPORT Process
LaunchElevatedProcess(const CommandLine
& cmdline
,
216 const LaunchOptions
& options
);
218 #elif defined(OS_POSIX)
219 // A POSIX-specific version of LaunchProcess that takes an argv array
220 // instead of a CommandLine. Useful for situations where you need to
221 // control the command line arguments directly, but prefer the
222 // CommandLine version if launching Chrome itself.
223 BASE_EXPORT Process
LaunchProcess(const std::vector
<std::string
>& argv
,
224 const LaunchOptions
& options
);
226 // Close all file descriptors, except those which are a destination in the
227 // given multimap. Only call this function in a child process where you know
228 // that there aren't any other threads.
229 BASE_EXPORT
void CloseSuperfluousFds(const InjectiveMultimap
& saved_map
);
230 #endif // defined(OS_POSIX)
233 // Set |job_object|'s JOBOBJECT_EXTENDED_LIMIT_INFORMATION
234 // BasicLimitInformation.LimitFlags to |limit_flags|.
235 BASE_EXPORT
bool SetJobObjectLimitFlags(HANDLE job_object
, DWORD limit_flags
);
237 // Output multi-process printf, cout, cerr, etc to the cmd.exe console that ran
238 // chrome. This is not thread-safe: only call from main thread.
239 BASE_EXPORT
void RouteStdioToConsole(bool create_console_if_not_found
);
240 #endif // defined(OS_WIN)
242 // Executes the application specified by |cl| and wait for it to exit. Stores
243 // the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
244 // on success (application launched and exited cleanly, with exit code
245 // indicating success).
246 BASE_EXPORT
bool GetAppOutput(const CommandLine
& cl
, std::string
* output
);
248 // Like GetAppOutput, but also includes stderr.
249 BASE_EXPORT
bool GetAppOutputAndError(const CommandLine
& cl
,
250 std::string
* output
);
253 // A Windows-specific version of GetAppOutput that takes a command line string
254 // instead of a CommandLine object. Useful for situations where you need to
255 // control the command line arguments directly.
256 BASE_EXPORT
bool GetAppOutput(const StringPiece16
& cl
, std::string
* output
);
259 #if defined(OS_POSIX)
260 // A POSIX-specific version of GetAppOutput that takes an argv array
261 // instead of a CommandLine. Useful for situations where you need to
262 // control the command line arguments directly.
263 BASE_EXPORT
bool GetAppOutput(const std::vector
<std::string
>& argv
,
264 std::string
* output
);
266 // A restricted version of |GetAppOutput()| which (a) clears the environment,
267 // and (b) stores at most |max_output| bytes; also, it doesn't search the path
269 BASE_EXPORT
bool GetAppOutputRestricted(const CommandLine
& cl
,
270 std::string
* output
, size_t max_output
);
272 // A version of |GetAppOutput()| which also returns the exit code of the
273 // executed command. Returns true if the application runs and exits cleanly. If
274 // this is the case the exit code of the application is available in
276 BASE_EXPORT
bool GetAppOutputWithExitCode(const CommandLine
& cl
,
277 std::string
* output
, int* exit_code
);
278 #endif // defined(OS_POSIX)
280 // If supported on the platform, and the user has sufficent rights, increase
281 // the current process's scheduling priority to a high priority.
282 BASE_EXPORT
void RaiseProcessToHighPriority();
284 #if defined(OS_MACOSX)
285 // Restore the default exception handler, setting it to Apple Crash Reporter
286 // (ReportCrash). When forking and execing a new process, the child will
287 // inherit the parent's exception ports, which may be set to the Breakpad
288 // instance running inside the parent. The parent's Breakpad instance should
289 // not handle the child's exceptions. Calling RestoreDefaultExceptionHandler
290 // in the child after forking will restore the standard exception handler.
291 // See http://crbug.com/20371/ for more details.
292 void RestoreDefaultExceptionHandler();
294 // Look up the bootstrap server named |replacement_bootstrap_name| via the
295 // current |bootstrap_port|. Then replace the task's bootstrap port with the
297 void ReplaceBootstrapPort(const std::string
& replacement_bootstrap_name
);
298 #endif // defined(OS_MACOSX)
300 // Creates a LaunchOptions object suitable for launching processes in a test
301 // binary. This should not be called in production/released code.
302 BASE_EXPORT LaunchOptions
LaunchOptionsForTest();
304 #if defined(OS_LINUX) || defined(OS_NACL_NONSFI)
305 // A wrapper for clone with fork-like behavior, meaning that it returns the
306 // child's pid in the parent and 0 in the child. |flags|, |ptid|, and |ctid| are
307 // as in the clone system call (the CLONE_VM flag is not supported).
309 // This function uses the libc clone wrapper (which updates libc's pid cache)
310 // internally, so callers may expect things like getpid() to work correctly
311 // after in both the child and parent. An exception is when this code is run
312 // under Valgrind. Valgrind does not support the libc clone wrapper, so the libc
313 // pid cache may be incorrect after this function is called under Valgrind.
315 // As with fork(), callers should be extremely careful when calling this while
316 // multiple threads are running, since at the time the fork happened, the
317 // threads could have been in any state (potentially holding locks, etc.).
318 // Callers should most likely call execve() in the child soon after calling
320 BASE_EXPORT pid_t
ForkWithFlags(unsigned long flags
, pid_t
* ptid
, pid_t
* ctid
);
325 #endif // BASE_PROCESS_LAUNCH_H_