launch.h revision 58537e28ecd584eab876aee8be7156509866d23a
1// Copyright (c) 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 <set>
11#include <string>
12#include <utility>
13#include <vector>
14
15#include "base/base_export.h"
16#include "base/basictypes.h"
17#include "base/environment.h"
18#include "base/process/process_handle.h"
19
20#if defined(OS_POSIX)
21#include "base/posix/file_descriptor_shuffle.h"
22#elif defined(OS_WIN)
23#include <windows.h>
24#endif
25
26class CommandLine;
27
28namespace base {
29
30typedef std::vector<std::pair<int, int> > FileHandleMappingVector;
31
32// Options for launching a subprocess that are passed to LaunchProcess().
33// The default constructor constructs the object with default options.
34struct BASE_EXPORT LaunchOptions {
35  LaunchOptions();
36  ~LaunchOptions();
37
38  // If true, wait for the process to complete.
39  bool wait;
40
41#if defined(OS_WIN)
42  bool start_hidden;
43
44  // If true, the new process inherits handles from the parent. In production
45  // code this flag should be used only when running short-lived, trusted
46  // binaries, because open handles from other libraries and subsystems will
47  // leak to the child process, causing errors such as open socket hangs.
48  bool inherit_handles;
49
50  // If non-NULL, runs as if the user represented by the token had launched it.
51  // Whether the application is visible on the interactive desktop depends on
52  // the token belonging to an interactive logon session.
53  //
54  // To avoid hard to diagnose problems, when specified this loads the
55  // environment variables associated with the user and if this operation fails
56  // the entire call fails as well.
57  UserTokenHandle as_user;
58
59  // If true, use an empty string for the desktop name.
60  bool empty_desktop_name;
61
62  // If non-NULL, launches the application in that job object. The process will
63  // be terminated immediately and LaunchProcess() will fail if assignment to
64  // the job object fails.
65  HANDLE job_handle;
66
67  // Handles for the redirection of stdin, stdout and stderr. The handles must
68  // be inheritable. Caller should either set all three of them or none (i.e.
69  // there is no way to redirect stderr without redirecting stdin). The
70  // |inherit_handles| flag must be set to true when redirecting stdio stream.
71  HANDLE stdin_handle;
72  HANDLE stdout_handle;
73  HANDLE stderr_handle;
74
75  // If set to true, ensures that the child process is launched with the
76  // CREATE_BREAKAWAY_FROM_JOB flag which allows it to breakout of the parent
77  // job if any.
78  bool force_breakaway_from_job_;
79#else
80  // Set/unset environment variables. Empty (the default) means to inherit
81  // the same environment. See AlterEnvironment().
82  EnvironmentMap environ;
83
84  // If non-NULL, remap file descriptors according to the mapping of
85  // src fd->dest fd to propagate FDs into the child process.
86  // This pointer is owned by the caller and must live through the
87  // call to LaunchProcess().
88  const FileHandleMappingVector* fds_to_remap;
89
90  // Each element is an RLIMIT_* constant that should be raised to its
91  // rlim_max.  This pointer is owned by the caller and must live through
92  // the call to LaunchProcess().
93  const std::set<int>* maximize_rlimits;
94
95  // If true, start the process in a new process group, instead of
96  // inheriting the parent's process group.  The pgid of the child process
97  // will be the same as its pid.
98  bool new_process_group;
99
100#if defined(OS_LINUX)
101  // If non-zero, start the process using clone(), using flags as provided.
102  int clone_flags;
103#endif  // defined(OS_LINUX)
104
105#if defined(OS_CHROMEOS)
106  // If non-negative, the specified file descriptor will be set as the launched
107  // process' controlling terminal.
108  int ctrl_terminal_fd;
109#endif  // defined(OS_CHROMEOS)
110
111#endif  // !defined(OS_WIN)
112};
113
114// Launch a process via the command line |cmdline|.
115// See the documentation of LaunchOptions for details on |options|.
116//
117// Returns true upon success.
118//
119// Upon success, if |process_handle| is non-NULL, it will be filled in with the
120// handle of the launched process.  NOTE: In this case, the caller is
121// responsible for closing the handle so that it doesn't leak!
122// Otherwise, the process handle will be implicitly closed.
123//
124// Unix-specific notes:
125// - All file descriptors open in the parent process will be closed in the
126//   child process except for any preserved by options::fds_to_remap, and
127//   stdin, stdout, and stderr. If not remapped by options::fds_to_remap,
128//   stdin is reopened as /dev/null, and the child is allowed to inherit its
129//   parent's stdout and stderr.
130// - If the first argument on the command line does not contain a slash,
131//   PATH will be searched.  (See man execvp.)
132BASE_EXPORT bool LaunchProcess(const CommandLine& cmdline,
133                               const LaunchOptions& options,
134                               ProcessHandle* process_handle);
135
136#if defined(OS_WIN)
137// Windows-specific LaunchProcess that takes the command line as a
138// string.  Useful for situations where you need to control the
139// command line arguments directly, but prefer the CommandLine version
140// if launching Chrome itself.
141//
142// The first command line argument should be the path to the process,
143// and don't forget to quote it.
144//
145// Example (including literal quotes)
146//  cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
147BASE_EXPORT bool LaunchProcess(const string16& cmdline,
148                               const LaunchOptions& options,
149                               ProcessHandle* process_handle);
150
151#elif defined(OS_POSIX)
152// A POSIX-specific version of LaunchProcess that takes an argv array
153// instead of a CommandLine.  Useful for situations where you need to
154// control the command line arguments directly, but prefer the
155// CommandLine version if launching Chrome itself.
156BASE_EXPORT bool LaunchProcess(const std::vector<std::string>& argv,
157                               const LaunchOptions& options,
158                               ProcessHandle* process_handle);
159
160// Close all file descriptors, except those which are a destination in the
161// given multimap. Only call this function in a child process where you know
162// that there aren't any other threads.
163BASE_EXPORT void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
164#endif  // defined(OS_POSIX)
165
166#if defined(OS_WIN)
167// Set JOBOBJECT_EXTENDED_LIMIT_INFORMATION to JobObject |job_object|.
168// As its limit_info.BasicLimitInformation.LimitFlags has
169// JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.
170// When the provide JobObject |job_object| is closed, the binded process will
171// be terminated.
172BASE_EXPORT bool SetJobObjectAsKillOnJobClose(HANDLE job_object);
173
174// Output multi-process printf, cout, cerr, etc to the cmd.exe console that ran
175// chrome. This is not thread-safe: only call from main thread.
176BASE_EXPORT void RouteStdioToConsole();
177#endif  // defined(OS_WIN)
178
179// Executes the application specified by |cl| and wait for it to exit. Stores
180// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
181// on success (application launched and exited cleanly, with exit code
182// indicating success).
183BASE_EXPORT bool GetAppOutput(const CommandLine& cl, std::string* output);
184
185#if defined(OS_POSIX)
186// A POSIX-specific version of GetAppOutput that takes an argv array
187// instead of a CommandLine.  Useful for situations where you need to
188// control the command line arguments directly.
189BASE_EXPORT bool GetAppOutput(const std::vector<std::string>& argv,
190                              std::string* output);
191
192// A restricted version of |GetAppOutput()| which (a) clears the environment,
193// and (b) stores at most |max_output| bytes; also, it doesn't search the path
194// for the command.
195BASE_EXPORT bool GetAppOutputRestricted(const CommandLine& cl,
196                                        std::string* output, size_t max_output);
197
198// A version of |GetAppOutput()| which also returns the exit code of the
199// executed command. Returns true if the application runs and exits cleanly. If
200// this is the case the exit code of the application is available in
201// |*exit_code|.
202BASE_EXPORT bool GetAppOutputWithExitCode(const CommandLine& cl,
203                                          std::string* output, int* exit_code);
204#endif  // defined(OS_POSIX)
205
206// If supported on the platform, and the user has sufficent rights, increase
207// the current process's scheduling priority to a high priority.
208BASE_EXPORT void RaiseProcessToHighPriority();
209
210#if defined(OS_MACOSX)
211// Restore the default exception handler, setting it to Apple Crash Reporter
212// (ReportCrash).  When forking and execing a new process, the child will
213// inherit the parent's exception ports, which may be set to the Breakpad
214// instance running inside the parent.  The parent's Breakpad instance should
215// not handle the child's exceptions.  Calling RestoreDefaultExceptionHandler
216// in the child after forking will restore the standard exception handler.
217// See http://crbug.com/20371/ for more details.
218void RestoreDefaultExceptionHandler();
219#endif  // defined(OS_MACOSX)
220
221}  // namespace base
222
223#endif  // BASE_PROCESS_LAUNCH_H_
224