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