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_WIN) 25 #include <windows.h> 26 #elif defined(OS_FUCHSIA) 27 #include <lib/fdio/spawn.h> 28 #include <zircon/types.h> 29 #endif 30 31 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 32 #include "base/posix/file_descriptor_shuffle.h" 33 #endif 34 35 namespace base { 36 37 class CommandLine; 38 39 #if defined(OS_WIN) 40 typedef std::vector<HANDLE> HandlesToInheritVector; 41 #elif defined(OS_FUCHSIA) 42 struct PathToTransfer { 43 base::FilePath path; 44 zx_handle_t handle; 45 }; 46 struct HandleToTransfer { 47 uint32_t id; 48 zx_handle_t handle; 49 }; 50 typedef std::vector<HandleToTransfer> HandlesToTransferVector; 51 typedef std::vector<std::pair<int, int>> FileHandleMappingVector; 52 #elif defined(OS_POSIX) 53 typedef std::vector<std::pair<int, int>> FileHandleMappingVector; 54 #endif // defined(OS_WIN) 55 56 // Options for launching a subprocess that are passed to LaunchProcess(). 57 // The default constructor constructs the object with default options. 58 struct BASE_EXPORT LaunchOptions { 59 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 60 // Delegate to be run in between fork and exec in the subprocess (see 61 // pre_exec_delegate below) 62 class BASE_EXPORT PreExecDelegate { 63 public: 64 PreExecDelegate() = default; 65 virtual ~PreExecDelegate() = default; 66 67 // Since this is to be run between fork and exec, and fork may have happened 68 // while multiple threads were running, this function needs to be async 69 // safe. 70 virtual void RunAsyncSafe() = 0; 71 72 private: 73 DISALLOW_COPY_AND_ASSIGN(PreExecDelegate); 74 }; 75 #endif // defined(OS_POSIX) 76 77 LaunchOptions(); 78 LaunchOptions(const LaunchOptions&); 79 ~LaunchOptions(); 80 81 // If true, wait for the process to complete. 82 bool wait = false; 83 84 // If not empty, change to this directory before executing the new process. 85 base::FilePath current_directory; 86 87 #if defined(OS_WIN) 88 bool start_hidden = false; 89 90 // Windows can inherit handles when it launches child processes. 91 // See https://blogs.msdn.microsoft.com/oldnewthing/20111216-00/?p=8873 92 // for a good overview of Windows handle inheritance. 93 // 94 // Implementation note: it might be nice to implement in terms of 95 // base::Optional<>, but then the natural default state (vector not present) 96 // would be "all inheritable handles" while we want "no inheritance." 97 enum class Inherit { 98 // Only those handles in |handles_to_inherit| vector are inherited. If the 99 // vector is empty, no handles are inherited. The handles in the vector must 100 // all be inheritable. 101 kSpecific, 102 103 // All handles in the current process which are inheritable are inherited. 104 // In production code this flag should be used only when running 105 // short-lived, trusted binaries, because open handles from other libraries 106 // and subsystems will leak to the child process, causing errors such as 107 // open socket hangs. There are also race conditions that can cause handle 108 // over-sharing. 109 // 110 // |handles_to_inherit| must be null. 111 // 112 // DEPRECATED. THIS SHOULD NOT BE USED. Explicitly map all handles that 113 // need to be shared in new code. 114 // TODO(brettw) bug 748258: remove this. 115 kAll 116 }; 117 Inherit inherit_mode = Inherit::kSpecific; 118 HandlesToInheritVector handles_to_inherit; 119 120 // If non-null, runs as if the user represented by the token had launched it. 121 // Whether the application is visible on the interactive desktop depends on 122 // the token belonging to an interactive logon session. 123 // 124 // To avoid hard to diagnose problems, when specified this loads the 125 // environment variables associated with the user and if this operation fails 126 // the entire call fails as well. 127 UserTokenHandle as_user = nullptr; 128 129 // If true, use an empty string for the desktop name. 130 bool empty_desktop_name = false; 131 132 // If non-null, launches the application in that job object. The process will 133 // be terminated immediately and LaunchProcess() will fail if assignment to 134 // the job object fails. 135 HANDLE job_handle = nullptr; 136 137 // Handles for the redirection of stdin, stdout and stderr. The caller should 138 // either set all three of them or none (i.e. there is no way to redirect 139 // stderr without redirecting stdin). 140 // 141 // The handles must be inheritable. Pseudo handles are used when stdout and 142 // stderr redirect to the console. In that case, GetFileType() will return 143 // FILE_TYPE_CHAR and they're automatically inherited by child processes. See 144 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682075.aspx 145 // Otherwise, the caller must ensure that the |inherit_mode| and/or 146 // |handles_to_inherit| set so that the handles are inherited. 147 HANDLE stdin_handle = nullptr; 148 HANDLE stdout_handle = nullptr; 149 HANDLE stderr_handle = nullptr; 150 151 // If set to true, ensures that the child process is launched with the 152 // CREATE_BREAKAWAY_FROM_JOB flag which allows it to breakout of the parent 153 // job if any. 154 bool force_breakaway_from_job_ = false; 155 156 // If set to true, permission to bring windows to the foreground is passed to 157 // the launched process if the current process has such permission. 158 bool grant_foreground_privilege = false; 159 #elif defined(OS_POSIX) || defined(OS_FUCHSIA) 160 // Set/unset environment variables. These are applied on top of the parent 161 // process environment. Empty (the default) means to inherit the same 162 // environment. See AlterEnvironment(). 163 EnvironmentMap environ; 164 165 // Clear the environment for the new process before processing changes from 166 // |environ|. 167 bool clear_environ = false; 168 169 // Remap file descriptors according to the mapping of src_fd->dest_fd to 170 // propagate FDs into the child process. 171 FileHandleMappingVector fds_to_remap; 172 #endif // defined(OS_WIN) 173 174 #if defined(OS_LINUX) 175 // If non-zero, start the process using clone(), using flags as provided. 176 // Unlike in clone, clone_flags may not contain a custom termination signal 177 // that is sent to the parent when the child dies. The termination signal will 178 // always be set to SIGCHLD. 179 int clone_flags = 0; 180 181 // By default, child processes will have the PR_SET_NO_NEW_PRIVS bit set. If 182 // true, then this bit will not be set in the new child process. 183 bool allow_new_privs = false; 184 185 // Sets parent process death signal to SIGKILL. 186 bool kill_on_parent_death = false; 187 #endif // defined(OS_LINUX) 188 189 #if defined(OS_FUCHSIA) 190 // If valid, launches the application in that job object. 191 zx_handle_t job_handle = ZX_HANDLE_INVALID; 192 193 // Specifies additional handles to transfer (not duplicate) to the child 194 // process. Each entry is an <id,handle> pair, with an |id| created using the 195 // PA_HND() macro. The child retrieves the handle 196 // |zx_take_startup_handle(id)|. The supplied handles are consumed by 197 // LaunchProcess() even on failure. 198 HandlesToTransferVector handles_to_transfer; 199 200 // Specifies which basic capabilities to grant to the child process. 201 // By default the child process will receive the caller's complete namespace, 202 // access to the current base::fuchsia::DefaultJob(), handles for stdio and 203 // access to the dynamic library loader. 204 // Note that the child is always provided access to the loader service. 205 uint32_t spawn_flags = FDIO_SPAWN_CLONE_NAMESPACE | FDIO_SPAWN_CLONE_STDIO | 206 FDIO_SPAWN_CLONE_JOB; 207 208 // Specifies paths to clone from the calling process' namespace into that of 209 // the child process. If |paths_to_clone| is empty then the process will 210 // receive either a full copy of the parent's namespace, or an empty one, 211 // depending on whether FDIO_SPAWN_CLONE_NAMESPACE is set. 212 std::vector<FilePath> paths_to_clone; 213 214 // Specifies handles which will be installed as files or directories in the 215 // child process' namespace. Paths installed by |paths_to_clone| will be 216 // overridden by these entries. 217 std::vector<PathToTransfer> paths_to_transfer; 218 #endif // defined(OS_FUCHSIA) 219 220 #if defined(OS_POSIX) 221 // If not empty, launch the specified executable instead of 222 // cmdline.GetProgram(). This is useful when it is necessary to pass a custom 223 // argv[0]. 224 base::FilePath real_path; 225 226 // If non-null, a delegate to be run immediately prior to executing the new 227 // program in the child process. 228 // 229 // WARNING: If LaunchProcess is called in the presence of multiple threads, 230 // code running in this delegate essentially needs to be async-signal safe 231 // (see man 7 signal for a list of allowed functions). 232 PreExecDelegate* pre_exec_delegate = nullptr; 233 234 // Each element is an RLIMIT_* constant that should be raised to its 235 // rlim_max. This pointer is owned by the caller and must live through 236 // the call to LaunchProcess(). 237 const std::vector<int>* maximize_rlimits = nullptr; 238 239 // If true, start the process in a new process group, instead of 240 // inheriting the parent's process group. The pgid of the child process 241 // will be the same as its pid. 242 bool new_process_group = false; 243 #endif // defined(OS_POSIX) 244 245 #if defined(OS_CHROMEOS) 246 // If non-negative, the specified file descriptor will be set as the launched 247 // process' controlling terminal. 248 int ctrl_terminal_fd = -1; 249 #endif // defined(OS_CHROMEOS) 250 }; 251 252 // Launch a process via the command line |cmdline|. 253 // See the documentation of LaunchOptions for details on |options|. 254 // 255 // Returns a valid Process upon success. 256 // 257 // Unix-specific notes: 258 // - All file descriptors open in the parent process will be closed in the 259 // child process except for any preserved by options::fds_to_remap, and 260 // stdin, stdout, and stderr. If not remapped by options::fds_to_remap, 261 // stdin is reopened as /dev/null, and the child is allowed to inherit its 262 // parent's stdout and stderr. 263 // - If the first argument on the command line does not contain a slash, 264 // PATH will be searched. (See man execvp.) 265 BASE_EXPORT Process LaunchProcess(const CommandLine& cmdline, 266 const LaunchOptions& options); 267 268 #if defined(OS_WIN) 269 // Windows-specific LaunchProcess that takes the command line as a 270 // string. Useful for situations where you need to control the 271 // command line arguments directly, but prefer the CommandLine version 272 // if launching Chrome itself. 273 // 274 // The first command line argument should be the path to the process, 275 // and don't forget to quote it. 276 // 277 // Example (including literal quotes) 278 // cmdline = "c:\windows\explorer.exe" -foo "c:\bar\" 279 BASE_EXPORT Process LaunchProcess(const string16& cmdline, 280 const LaunchOptions& options); 281 282 // Launches a process with elevated privileges. This does not behave exactly 283 // like LaunchProcess as it uses ShellExecuteEx instead of CreateProcess to 284 // create the process. This means the process will have elevated privileges 285 // and thus some common operations like OpenProcess will fail. Currently the 286 // only supported LaunchOptions are |start_hidden| and |wait|. 287 BASE_EXPORT Process LaunchElevatedProcess(const CommandLine& cmdline, 288 const LaunchOptions& options); 289 290 #elif defined(OS_POSIX) || defined(OS_FUCHSIA) 291 // A POSIX-specific version of LaunchProcess that takes an argv array 292 // instead of a CommandLine. Useful for situations where you need to 293 // control the command line arguments directly, but prefer the 294 // CommandLine version if launching Chrome itself. 295 BASE_EXPORT Process LaunchProcess(const std::vector<std::string>& argv, 296 const LaunchOptions& options); 297 298 // Close all file descriptors, except those which are a destination in the 299 // given multimap. Only call this function in a child process where you know 300 // that there aren't any other threads. 301 BASE_EXPORT void CloseSuperfluousFds(const InjectiveMultimap& saved_map); 302 #endif // defined(OS_WIN) 303 304 #if defined(OS_WIN) 305 // Set |job_object|'s JOBOBJECT_EXTENDED_LIMIT_INFORMATION 306 // BasicLimitInformation.LimitFlags to |limit_flags|. 307 BASE_EXPORT bool SetJobObjectLimitFlags(HANDLE job_object, DWORD limit_flags); 308 309 // Output multi-process printf, cout, cerr, etc to the cmd.exe console that ran 310 // chrome. This is not thread-safe: only call from main thread. 311 BASE_EXPORT void RouteStdioToConsole(bool create_console_if_not_found); 312 #endif // defined(OS_WIN) 313 314 // Executes the application specified by |cl| and wait for it to exit. Stores 315 // the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true 316 // on success (application launched and exited cleanly, with exit code 317 // indicating success). 318 BASE_EXPORT bool GetAppOutput(const CommandLine& cl, std::string* output); 319 320 // Like GetAppOutput, but also includes stderr. 321 BASE_EXPORT bool GetAppOutputAndError(const CommandLine& cl, 322 std::string* output); 323 324 // A version of |GetAppOutput()| which also returns the exit code of the 325 // executed command. Returns true if the application runs and exits cleanly. If 326 // this is the case the exit code of the application is available in 327 // |*exit_code|. 328 BASE_EXPORT bool GetAppOutputWithExitCode(const CommandLine& cl, 329 std::string* output, int* exit_code); 330 331 #if defined(OS_WIN) 332 // A Windows-specific version of GetAppOutput that takes a command line string 333 // instead of a CommandLine object. Useful for situations where you need to 334 // control the command line arguments directly. 335 BASE_EXPORT bool GetAppOutput(const StringPiece16& cl, std::string* output); 336 #elif defined(OS_POSIX) || defined(OS_FUCHSIA) 337 // A POSIX-specific version of GetAppOutput that takes an argv array 338 // instead of a CommandLine. Useful for situations where you need to 339 // control the command line arguments directly. 340 BASE_EXPORT bool GetAppOutput(const std::vector<std::string>& argv, 341 std::string* output); 342 343 // Like the above POSIX-specific version of GetAppOutput, but also includes 344 // stderr. 345 BASE_EXPORT bool GetAppOutputAndError(const std::vector<std::string>& argv, 346 std::string* output); 347 #endif // defined(OS_WIN) 348 349 // If supported on the platform, and the user has sufficent rights, increase 350 // the current process's scheduling priority to a high priority. 351 BASE_EXPORT void RaiseProcessToHighPriority(); 352 353 #if defined(OS_MACOSX) 354 // An implementation of LaunchProcess() that uses posix_spawn() instead of 355 // fork()+exec(). This does not support the |pre_exec_delegate| and 356 // |current_directory| options. 357 Process LaunchProcessPosixSpawn(const std::vector<std::string>& argv, 358 const LaunchOptions& options); 359 360 // Restore the default exception handler, setting it to Apple Crash Reporter 361 // (ReportCrash). When forking and execing a new process, the child will 362 // inherit the parent's exception ports, which may be set to the Breakpad 363 // instance running inside the parent. The parent's Breakpad instance should 364 // not handle the child's exceptions. Calling RestoreDefaultExceptionHandler 365 // in the child after forking will restore the standard exception handler. 366 // See http://crbug.com/20371/ for more details. 367 void RestoreDefaultExceptionHandler(); 368 #endif // defined(OS_MACOSX) 369 370 // Creates a LaunchOptions object suitable for launching processes in a test 371 // binary. This should not be called in production/released code. 372 BASE_EXPORT LaunchOptions LaunchOptionsForTest(); 373 374 #if defined(OS_LINUX) || defined(OS_NACL_NONSFI) 375 // A wrapper for clone with fork-like behavior, meaning that it returns the 376 // child's pid in the parent and 0 in the child. |flags|, |ptid|, and |ctid| are 377 // as in the clone system call (the CLONE_VM flag is not supported). 378 // 379 // This function uses the libc clone wrapper (which updates libc's pid cache) 380 // internally, so callers may expect things like getpid() to work correctly 381 // after in both the child and parent. 382 // 383 // As with fork(), callers should be extremely careful when calling this while 384 // multiple threads are running, since at the time the fork happened, the 385 // threads could have been in any state (potentially holding locks, etc.). 386 // Callers should most likely call execve() in the child soon after calling 387 // this. 388 // 389 // It is unsafe to use any pthread APIs after ForkWithFlags(). 390 // However, performing an exec() will lift this restriction. 391 BASE_EXPORT pid_t ForkWithFlags(unsigned long flags, pid_t* ptid, pid_t* ctid); 392 #endif 393 394 } // namespace base 395 396 #endif // BASE_PROCESS_LAUNCH_H_ 397