blob: aa41efa307403758e2cd38a7ef3f3bff2a816bf6 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2011 The Chromium Authors
[email protected]76bea672013-07-19 16:48:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
danakj0a448602015-03-10 00:31:165#ifndef BASE_PROCESS_PROCESS_H_
6#define BASE_PROCESS_PROCESS_H_
[email protected]76bea672013-07-19 16:48:567
Helmut Januschkabfa62f72024-04-04 15:18:318#include <string_view>
9
[email protected]76bea672013-07-19 16:48:5610#include "base/base_export.h"
Tom Sepez1705e3f02024-10-25 01:39:1811#include "base/compiler_specific.h"
[email protected]76bea672013-07-19 16:48:5612#include "base/process/process_handle.h"
rvargas126fd5822014-12-12 00:25:1413#include "base/time/time.h"
Dave Tapuskaed322d02023-03-07 23:33:3314#include "build/blink_buildflags.h"
[email protected]76bea672013-07-19 16:48:5615#include "build/build_config.h"
16
Xiaohan Wang37e81612022-01-15 18:27:0017#if BUILDFLAG(IS_WIN)
rvargas079d1842014-10-17 22:32:1618#include "base/win/scoped_handle.h"
19#endif
20
Xiaohan Wang37e81612022-01-15 18:27:0021#if BUILDFLAG(IS_FUCHSIA)
Wez157707d62018-07-10 22:48:4722#include <lib/zx/process.h>
Wez78b733132017-08-09 18:41:5923#endif
24
Zheda Chen2808be72022-12-19 06:26:5525#if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN)
lgrey0d2bafc2016-11-07 16:28:3326#include "base/feature_list.h"
Zheda Chen2808be72022-12-19 06:26:5527#endif // BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN)
Youssef Esmatc732bf82022-05-27 00:47:1928
29#if BUILDFLAG(IS_APPLE)
lgrey0d2bafc2016-11-07 16:28:3330#include "base/process/port_provider_mac.h"
Youssef Esmatc732bf82022-05-27 00:47:1931#endif // BUILDFLAG(IS_APPLE)
lgrey0d2bafc2016-11-07 16:28:3332
[email protected]76bea672013-07-19 16:48:5633namespace base {
34
Youssef Esmatc732bf82022-05-27 00:47:1935#if BUILDFLAG(IS_CHROMEOS)
36// OneGroupPerRenderer feature places each foreground renderer process into
37// its own cgroup. This will cause the scheduler to use the aggregate runtime
38// of all threads in the process when deciding on the next thread to schedule.
39// It will help guarantee fairness between renderers.
Daniel Cheng0fff5c232022-09-21 17:43:3440BASE_EXPORT BASE_DECLARE_FEATURE(kOneGroupPerRenderer);
Joel Fernandesf3f294f2023-09-22 17:29:4541
42// Set all threads of a background process as backgrounded, which changes the
43// thread attributes including c-group, latency sensitivity. But the nice value
44// is unchanged, since background process is under the spell of the background
45// CPU c-group (via cgroup.procs).
46BASE_EXPORT BASE_DECLARE_FEATURE(kSetThreadBgForBgProcess);
Shintaro Kawamuraf29c8fdf2024-03-28 03:40:0847
Shintaro Kawamuradb0ae3e2024-12-26 07:41:3348// FlattenCpuCgroups feature uses /sys/fs/cgroup/cpu/chrome_renderers and
49// /sys/fs/cgroup/cpu/chrome_renderers_background cpu cgroups for renderer
50// processes instead of nested cpu cgroups. Nested cpu cgroups has an overhead
51// on task scheduling.
52BASE_EXPORT BASE_DECLARE_FEATURE(kFlattenCpuCgroups);
53
Shintaro Kawamuraf29c8fdf2024-03-28 03:40:0854class ProcessPriorityDelegate;
Youssef Esmatc732bf82022-05-27 00:47:1955#endif
56
rvargas079d1842014-10-17 22:32:1657// Provides a move-only encapsulation of a process.
58//
59// This object is not tied to the lifetime of the underlying process: the
60// process may be killed and this object may still around, and it will still
61// claim to be valid. The actual behavior in that case is OS dependent like so:
62//
63// Windows: The underlying ProcessHandle will be valid after the process dies
64// and can be used to gather some information about that process, but most
65// methods will obviously fail.
66//
Wez6fcf59f2017-08-02 21:09:0567// POSIX: The underlying ProcessHandle is not guaranteed to remain valid after
rvargas079d1842014-10-17 22:32:1668// the process dies, and it may be reused by the system, which means that it may
69// end up pointing to the wrong process.
[email protected]76bea672013-07-19 16:48:5670class BASE_EXPORT Process {
71 public:
erikchen7cef7d262017-09-11 22:56:5772 // On Windows, this takes ownership of |handle|. On POSIX, this does not take
73 // ownership of |handle|.
rvargas079d1842014-10-17 22:32:1674 explicit Process(ProcessHandle handle = kNullProcessHandle);
[email protected]76bea672013-07-19 16:48:5675
dchenge1b0277c2015-12-01 12:09:5276 Process(Process&& other);
[email protected]76bea672013-07-19 16:48:5677
Peter Boström7319bbd2021-09-15 22:59:3878 Process(const Process&) = delete;
79 Process& operator=(const Process&) = delete;
80
rvargas079d1842014-10-17 22:32:1681 // The destructor does not terminate the process.
thakis3096dac2015-04-20 16:44:4882 ~Process();
rvargas079d1842014-10-17 22:32:1683
dchenge1b0277c2015-12-01 12:09:5284 Process& operator=(Process&& other);
rvargas079d1842014-10-17 22:32:1685
86 // Returns an object for the current process.
[email protected]76bea672013-07-19 16:48:5687 static Process Current();
88
rvargas6b039c372015-02-04 21:11:2989 // Returns a Process for the given |pid|.
90 static Process Open(ProcessId pid);
91
rvargas747ff242015-01-17 02:46:4792 // Returns a Process for the given |pid|. On Windows the handle is opened
93 // with more access rights and must only be used by trusted code (can read the
94 // address space and duplicate handles).
rvargas1c376a82015-03-16 23:03:5295 static Process OpenWithExtraPrivileges(ProcessId pid);
rvargas747ff242015-01-17 02:46:4796
Xiaohan Wang37e81612022-01-15 18:27:0097#if BUILDFLAG(IS_WIN)
rvargas17a407d2015-01-23 20:36:4498 // Returns a Process for the given |pid|, using some |desired_access|.
99 // See ::OpenProcess documentation for valid |desired_access|.
100 static Process OpenWithAccess(ProcessId pid, DWORD desired_access);
101#endif
102
Patrick Monette5d1ba7ca2023-08-02 22:05:27103 // Returns true if changing the priority of processes through `SetPriority()`
104 // is possible.
105 static bool CanSetPriority();
106
haraken940efb92017-02-08 05:58:15107 // Terminates the current process immediately with |exit_code|.
Wez5f117412018-02-07 04:17:47108 [[noreturn]] static void TerminateCurrentProcessImmediately(int exit_code);
haraken940efb92017-02-08 05:58:15109
rvargas079d1842014-10-17 22:32:16110 // Returns true if this objects represents a valid process.
111 bool IsValid() const;
112
113 // Returns a handle for this process. There is no guarantee about when that
114 // handle becomes invalid because this object retains ownership.
115 ProcessHandle Handle() const;
116
117 // Returns a second object that represents this process.
118 Process Duplicate() const;
[email protected]76bea672013-07-19 16:48:56119
Robert Sesek0e7f165a2020-11-20 21:31:45120 // Relinquishes ownership of the handle and sets this to kNullProcessHandle.
121 // The result may be a pseudo-handle, depending on the OS and value stored in
122 // this.
Daniel Cheng4455c9842022-01-13 23:26:37123 [[nodiscard]] ProcessHandle Release();
Robert Sesek0e7f165a2020-11-20 21:31:45124
[email protected]76bea672013-07-19 16:48:56125 // Get the PID for this process.
rvargas960db882015-01-24 00:27:25126 ProcessId Pid() const;
[email protected]76bea672013-07-19 16:48:56127
Francois Doray7d1315342018-10-21 03:54:47128 // Get the creation time for this process. Since the Pid can be reused after a
129 // process dies, it is useful to use both the Pid and the creation time to
130 // uniquely identify a process.
131 //
Benoit Lize8a544692020-08-31 15:43:42132 // On Android, works only if |this| is the current process, as security
133 // features prevent an application from getting data about other processes,
134 // even if they belong to us. Otherwise, returns Time().
Francois Doray7d1315342018-10-21 03:54:47135 Time CreationTime() const;
Francois Doray7d1315342018-10-21 03:54:47136
rvargas079d1842014-10-17 22:32:16137 // Returns true if this process is the current process.
[email protected]76bea672013-07-19 16:48:56138 bool is_current() const;
139
Youssef Esmatc732bf82022-05-27 00:47:19140#if BUILDFLAG(IS_CHROMEOS)
141 // A unique token generated for each process, this is used to create a unique
142 // cgroup for each renderer.
Tom Sepez1705e3f02024-10-25 01:39:18143 const std::string& unique_token() const LIFETIME_BOUND {
144 return unique_token_;
145 }
Youssef Esmatc732bf82022-05-27 00:47:19146#endif
147
[email protected]76bea672013-07-19 16:48:56148 // Close the process handle. This will not terminate the process.
149 void Close();
150
Zijie He4dd88ae422017-09-20 01:30:18151 // Returns true if this process is still running. This is only safe on Windows
152 // (and maybe Fuchsia?), because the ProcessHandle will keep the zombie
153 // process information available until itself has been released. But on Posix,
154 // the OS may reuse the ProcessId.
Xiaohan Wang37e81612022-01-15 18:27:00155#if BUILDFLAG(IS_WIN)
Zijie He4dd88ae422017-09-20 01:30:18156 bool IsRunning() const {
157 return !WaitForExitWithTimeout(base::TimeDelta(), nullptr);
158 }
159#endif
160
rvargas02ad7832015-04-02 01:36:06161 // Terminates the process with extreme prejudice. The given |exit_code| will
rvargaseedb7632015-03-09 23:53:45162 // be the exit code of the process. If |wait| is true, this method will wait
163 // for up to one minute for the process to actually terminate.
164 // Returns true if the process terminates within the allowed time.
Johann30f94472021-04-07 23:54:24165 // NOTE: |exit_code| is only used on OS_WIN.
rvargas02ad7832015-04-02 01:36:06166 bool Terminate(int exit_code, bool wait) const;
[email protected]76bea672013-07-19 16:48:56167
Xiaohan Wang37e81612022-01-15 18:27:00168#if BUILDFLAG(IS_WIN)
Mike Rorkef36971b2020-03-06 17:56:29169 enum class WaitExitStatus {
170 PROCESS_EXITED,
171 STOP_EVENT_SIGNALED,
172 FAILED,
173 };
174
175 // Waits for the process to exit, or the specified |stop_event_handle| to be
176 // set. Returns value indicating which event was set. The given |exit_code|
177 // will be the exit code of the process.
178 WaitExitStatus WaitForExitOrEvent(
179 const base::win::ScopedHandle& stop_event_handle,
180 int* exit_code) const;
Xiaohan Wang37e81612022-01-15 18:27:00181#endif // BUILDFLAG(IS_WIN)
Mike Rorkef36971b2020-03-06 17:56:29182
rvargas126fd5822014-12-12 00:25:14183 // Waits for the process to exit. Returns true on success.
184 // On POSIX, if the process has been signaled then |exit_code| is set to -1.
rvargas2f70a152015-02-24 00:28:11185 // On Linux this must be a child process, however on Mac and Windows it can be
186 // any process.
g.mehndirattfd19e232015-05-29 08:17:14187 // NOTE: |exit_code| is optional, nullptr can be passed if the exit code is
188 // not required.
jcivellif4462a352017-01-10 04:45:59189 bool WaitForExit(int* exit_code) const;
rvargas126fd5822014-12-12 00:25:14190
191 // Same as WaitForExit() but only waits for up to |timeout|.
g.mehndirattfd19e232015-05-29 08:17:14192 // NOTE: |exit_code| is optional, nullptr can be passed if the exit code
193 // is not required.
jcivellif4462a352017-01-10 04:45:59194 bool WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const;
rvargas126fd5822014-12-12 00:25:14195
Brian Whiteae2a8b9a2017-11-02 19:10:36196 // Indicates that the process has exited with the specified |exit_code|.
197 // This should be called if process exit is observed outside of this class.
198 // (i.e. Not because Terminate or WaitForExit, above, was called.)
199 // Note that nothing prevents this being called multiple times for a dead
200 // process though that should be avoided.
201 void Exited(int exit_code) const;
202
Patrick Monette5d1ba7ca2023-08-02 22:05:27203 // The different priorities that a process can have.
204 // TODO(pmonette): Consider merging with base::TaskPriority when the API is
205 // stable.
206 enum class Priority {
207 // The process does not contribute to content that is currently important
208 // to the user. Lowest priority.
209 kBestEffort,
210
Zheda Chene7421f32024-08-29 03:05:39211 // The process contributes to content that is visible to the user, but the
212 // work don't have significant performance or latency requirement, so it can
213 // run in energy efficient manner. Moderate priority.
Patrick Monette5d1ba7ca2023-08-02 22:05:27214 kUserVisible,
215
216 // The process contributes to content that is of the utmost importance to
217 // the user, like producing audible content, or visible content in the
Zheda Chene7421f32024-08-29 03:05:39218 // main frame. High priority.
Patrick Monette5d1ba7ca2023-08-02 22:05:27219 kUserBlocking,
Patrick Monette617db892024-09-24 17:29:19220
221 kMaxValue = kUserBlocking,
Patrick Monette5d1ba7ca2023-08-02 22:05:27222 };
223
Gyuyoung Kim9e4c3ef2025-02-12 01:17:57224#if (BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK))) && \
Raphael Kubo da Costac57d2df32025-03-01 00:51:43225 !BUILDFLAG(IS_IOS_TVOS)
lgrey0d2bafc2016-11-07 16:28:33226 // The Mac needs a Mach port in order to manipulate a process's priority,
227 // and there's no good way to get that from base given the pid. These Mac
Patrick Monette5d1ba7ca2023-08-02 22:05:27228 // variants of the `GetPriority()` and `SetPriority()` API take a port
229 // provider for this reason. See crbug.com/460102.
lgrey0d2bafc2016-11-07 16:28:33230
Patrick Monette5d1ba7ca2023-08-02 22:05:27231 // Retrieves the priority of the process. Defaults to Priority::kUserBlocking
232 // if the priority could not be retrieved, or if `port_provider` is null.
233 Priority GetPriority(PortProvider* port_provider) const;
234
235 // Sets the priority of the process process. Returns true if the priority was
236 // changed, false otherwise. If `port_provider` is null, this is a no-op and
237 // it returns false.
238 bool SetPriority(PortProvider* port_provider, Priority priority);
lgrey0d2bafc2016-11-07 16:28:33239#else
Patrick Monette5d1ba7ca2023-08-02 22:05:27240 // Retrieves the priority of the process. Defaults to Priority::kUserBlocking
241 // if the priority could not be retrieved.
242 Priority GetPriority() const;
[email protected]76bea672013-07-19 16:48:56243
Patrick Monette5d1ba7ca2023-08-02 22:05:27244 // Sets the priority of the process process. Returns true if the priority was
245 // changed, false otherwise.
246 bool SetPriority(Priority priority);
Dave Tapuskaed322d02023-03-07 23:33:33247#endif // BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK))
248
[email protected]76bea672013-07-19 16:48:56249 // Returns an integer representing the priority of a process. The meaning
250 // of this value is OS dependent.
Patrick Monette740b81b2023-07-21 21:09:09251 int GetOSPriority() const;
[email protected]76bea672013-07-19 16:48:56252
Georg Neisff37fb52025-02-05 09:05:26253#if BUILDFLAG(IS_CHROMEOS)
nyad2c548b2015-12-09 03:22:32254 // Get the PID in its PID namespace.
255 // If the process is not in a PID namespace or /proc/<pid>/status does not
256 // report NSpid, kNullProcessId is returned.
257 ProcessId GetPidInNamespace() const;
258#endif
259
Matthew Dentonf969883422023-08-08 01:44:34260#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
261 // Returns true if the process has any seccomp policy applied.
262 bool IsSeccompSandboxed();
263#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
264
Youssef Esmatc732bf82022-05-27 00:47:19265#if BUILDFLAG(IS_CHROMEOS)
Shintaro Kawamuraf29c8fdf2024-03-28 03:40:08266 // Sets a delegate which handles process priority changes. This
267 // must be externally synchronized with any call to base::Process methods.
268 static void SetProcessPriorityDelegate(ProcessPriorityDelegate* delegate);
269
Youssef Esmat10aa75d2022-06-10 11:58:46270 // Exposes OneGroupPerRendererEnabled() to unit tests.
271 static bool OneGroupPerRendererEnabledForTesting();
Youssef Esmatc732bf82022-05-27 00:47:19272
273 // If OneGroupPerRenderer is enabled, runs at process startup to clean up
274 // any stale cgroups that were left behind from any unclean exits of the
275 // browser process.
276 static void CleanUpStaleProcessStates();
277
Shintaro Kawamuraf726c1292024-03-28 03:40:08278 // Initializes the process's priority.
279 //
280 // This should be called before SetPriority().
281 //
282 // If SchedQoSOnResourcedForChrome is enabled, this creates a cache entry for
283 // the process priority. The returned `base::Process::PriorityEntry` should be
284 // freed when the process is terminated so that the cached entry is freed from
285 // the internal map.
286 //
287 // If OneGroupPerRenderer is enabled, it also creates a unique cgroup for the
288 // process.
289 // This is a no-op if the Process is not valid or if it has already been
290 // called.
Youssef Esmatc732bf82022-05-27 00:47:19291 void InitializePriority();
Shintaro Kawamuraf726c1292024-03-28 03:40:08292
293 // Clears the entities initialized by InitializePriority().
294 //
295 // This is no-op if SchedQoSOnResourcedForChrome is disabled.
296 void ForgetPriority();
Youssef Esmatc732bf82022-05-27 00:47:19297#endif // BUILDFLAG(IS_CHROMEOS)
298
Dave Tapuskaed322d02023-03-07 23:33:33299#if BUILDFLAG(IS_APPLE)
Patrick Monette209f31da2023-08-31 21:25:33300 // Sets the priority of the current process to its default value.
Gabriel Charette99c4dc962025-01-06 20:54:38301 // Ironically, non-App Nap compliant processes do not get this by default on
302 // Mac.
Patrick Monetteee7f72f2023-01-23 22:59:45303 static void SetCurrentTaskDefaultRole();
304#endif // BUILDFLAG(IS_MAC)
305
Dave Tapuska31c385c2024-04-12 18:43:11306#if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK)
Dave Tapuskab7422332025-05-22 22:10:39307 using TerminateCallback = bool (*)(ProcessHandle handle,
308 int exit_code,
309 bool wait);
Dave Tapuska31c385c2024-04-12 18:43:11310 using WaitForExitCallback = bool (*)(ProcessHandle handle,
311 int* exit_code,
312 base::TimeDelta timeout);
313 // Function ptrs to implement termination without polluting //base with
314 // BrowserEngineKit APIs.
315 static void SetTerminationHooks(TerminateCallback terminate_callback,
316 WaitForExitCallback wait_callback);
317#if TARGET_OS_SIMULATOR
318 // Methods for supporting both "content processes" and traditional
319 // forked processes. For non-simulator builds on iOS every process would
320 // be a "content process" so we don't need the conditionals.
321 void SetIsContentProcess();
322 bool IsContentProcess() const;
323#endif
324#endif
325
[email protected]76bea672013-07-19 16:48:56326 private:
Youssef Esmatc732bf82022-05-27 00:47:19327#if BUILDFLAG(IS_CHROMEOS)
328 // Cleans up process state. If OneGroupPerRenderer is enabled, it cleans up
329 // the cgroup created by InitializePriority(). If the process has not
330 // fully terminated yet, it will post a background task to try again.
331 void CleanUpProcess(int remaining_retries) const;
332
333 // Calls CleanUpProcess() on a background thread.
334 void CleanUpProcessAsync() const;
335
336 // Used to call CleanUpProcess() on a background thread because Process is not
337 // refcounted.
338 static void CleanUpProcessScheduled(Process process, int remaining_retries);
339#endif // BUILDFLAG(IS_CHROMEOS)
340
Dave Tapuska31c385c2024-04-12 18:43:11341#if !BUILDFLAG(IS_IOS) || (BUILDFLAG(IS_IOS) && TARGET_OS_SIMULATOR)
342 bool TerminateInternal(int exit_code, bool wait) const;
343 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
344 int* exit_code,
345 base::TimeDelta timeout) const;
346#endif
347
Xiaohan Wang37e81612022-01-15 18:27:00348#if BUILDFLAG(IS_WIN)
rvargas079d1842014-10-17 22:32:16349 win::ScopedHandle process_;
Xiaohan Wang37e81612022-01-15 18:27:00350#elif BUILDFLAG(IS_FUCHSIA)
Wez157707d62018-07-10 22:48:47351 zx::process process_;
rvargas079d1842014-10-17 22:32:16352#else
[email protected]76bea672013-07-19 16:48:56353 ProcessHandle process_;
rvargas079d1842014-10-17 22:32:16354#endif
dcheng1a2fd6cd2016-06-07 21:39:12355
Xiaohan Wang37e81612022-01-15 18:27:00356#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
scottmg297cc932017-05-24 03:45:58357 bool is_current_process_;
358#endif
Youssef Esmatc732bf82022-05-27 00:47:19359
Dave Tapuska31c385c2024-04-12 18:43:11360#if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
361 // A flag indicating that this is a "content process". iOS does not support
362 // generic process invocation but it does support some types of well defined
363 // processes. These types of processes are defined at the //content layer so
364 // for termination we defer to some globally initialized callbacks.
365 bool content_process_ = false;
366#endif
367
Youssef Esmatc732bf82022-05-27 00:47:19368#if BUILDFLAG(IS_CHROMEOS)
369 // A unique token per process not per class instance (`base::Process`). This
370 // is similar to the PID of a process but should not be reused after the
371 // process's termination. The token will be copied during Duplicate()
372 // and move semantics as is the PID/ProcessHandle.
373 std::string unique_token_;
374#endif
[email protected]76bea672013-07-19 16:48:56375};
376
Eric Willigers611cf542022-04-28 02:22:14377#if BUILDFLAG(IS_CHROMEOS)
afakhry8b4796b2015-11-16 18:41:44378// Exposed for testing.
379// Given the contents of the /proc/<pid>/cgroup file, determine whether the
380// process is backgrounded or not.
Patrick Monette5d1ba7ca2023-08-02 22:05:27381BASE_EXPORT Process::Priority GetProcessPriorityCGroup(
Helmut Januschkabfa62f72024-04-04 15:18:31382 std::string_view cgroup_contents);
Eric Willigers611cf542022-04-28 02:22:14383#endif // BUILDFLAG(IS_CHROMEOS)
afakhry8b4796b2015-11-16 18:41:44384
[email protected]76bea672013-07-19 16:48:56385} // namespace base
386
danakj0a448602015-03-10 00:31:16387#endif // BASE_PROCESS_PROCESS_H_