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