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