launch.h 18 KB

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