launch.h 19 KB

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