blob: 920420ee1262e519a951794f16d64e8479a2c66c [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"
[email protected]76bea672013-07-19 16:48:5611#include "base/process/process_handle.h"
rvargas126fd5822014-12-12 00:25:1412#include "base/time/time.h"
Dave Tapuskaed322d02023-03-07 23:33:3313#include "build/blink_buildflags.h"
[email protected]76bea672013-07-19 16:48:5614#include "build/build_config.h"
Hidehiko Abe7c68f582020-09-03 15:47:2515#include "build/chromeos_buildflags.h"
[email protected]76bea672013-07-19 16:48:5616
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
48class ProcessPriorityDelegate;
Youssef Esmatc732bf82022-05-27 00:47:1949#endif
50
Zheda Chen2808be72022-12-19 06:26:5551#if BUILDFLAG(IS_WIN)
52BASE_EXPORT BASE_DECLARE_FEATURE(kUseEcoQoSForBackgroundProcess);
Zheda Chene7421f32024-08-29 03:05:3953
54BASE_EXPORT BASE_DECLARE_FEATURE(kEnableIntermediatePriority);
Zheda Chen2808be72022-12-19 06:26:5555#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.
143 const std::string& unique_token() const { return unique_token_; }
144#endif
145
[email protected]76bea672013-07-19 16:48:56146 // Close the process handle. This will not terminate the process.
147 void Close();
148
Zijie He4dd88ae422017-09-20 01:30:18149 // Returns true if this process is still running. This is only safe on Windows
150 // (and maybe Fuchsia?), because the ProcessHandle will keep the zombie
151 // process information available until itself has been released. But on Posix,
152 // the OS may reuse the ProcessId.
Xiaohan Wang37e81612022-01-15 18:27:00153#if BUILDFLAG(IS_WIN)
Zijie He4dd88ae422017-09-20 01:30:18154 bool IsRunning() const {
155 return !WaitForExitWithTimeout(base::TimeDelta(), nullptr);
156 }
157#endif
158
rvargas02ad7832015-04-02 01:36:06159 // Terminates the process with extreme prejudice. The given |exit_code| will
rvargaseedb763e2015-03-09 23:53:45160 // be the exit code of the process. If |wait| is true, this method will wait
161 // for up to one minute for the process to actually terminate.
162 // Returns true if the process terminates within the allowed time.
Johann30f94472021-04-07 23:54:24163 // NOTE: |exit_code| is only used on OS_WIN.
rvargas02ad7832015-04-02 01:36:06164 bool Terminate(int exit_code, bool wait) const;
[email protected]76bea672013-07-19 16:48:56165
Xiaohan Wang37e81612022-01-15 18:27:00166#if BUILDFLAG(IS_WIN)
Mike Rorkef36971b2020-03-06 17:56:29167 enum class WaitExitStatus {
168 PROCESS_EXITED,
169 STOP_EVENT_SIGNALED,
170 FAILED,
171 };
172
173 // Waits for the process to exit, or the specified |stop_event_handle| to be
174 // set. Returns value indicating which event was set. The given |exit_code|
175 // will be the exit code of the process.
176 WaitExitStatus WaitForExitOrEvent(
177 const base::win::ScopedHandle& stop_event_handle,
178 int* exit_code) const;
Xiaohan Wang37e81612022-01-15 18:27:00179#endif // BUILDFLAG(IS_WIN)
Mike Rorkef36971b2020-03-06 17:56:29180
rvargas126fd5822014-12-12 00:25:14181 // Waits for the process to exit. Returns true on success.
182 // On POSIX, if the process has been signaled then |exit_code| is set to -1.
rvargas2f70a152015-02-24 00:28:11183 // On Linux this must be a child process, however on Mac and Windows it can be
184 // any process.
g.mehndirattfd19e232015-05-29 08:17:14185 // NOTE: |exit_code| is optional, nullptr can be passed if the exit code is
186 // not required.
jcivellif4462a352017-01-10 04:45:59187 bool WaitForExit(int* exit_code) const;
rvargas126fd5822014-12-12 00:25:14188
189 // Same as WaitForExit() but only waits for up to |timeout|.
g.mehndirattfd19e232015-05-29 08:17:14190 // NOTE: |exit_code| is optional, nullptr can be passed if the exit code
191 // is not required.
jcivellif4462a352017-01-10 04:45:59192 bool WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const;
rvargas126fd5822014-12-12 00:25:14193
Brian Whiteae2a8b9a2017-11-02 19:10:36194 // Indicates that the process has exited with the specified |exit_code|.
195 // This should be called if process exit is observed outside of this class.
196 // (i.e. Not because Terminate or WaitForExit, above, was called.)
197 // Note that nothing prevents this being called multiple times for a dead
198 // process though that should be avoided.
199 void Exited(int exit_code) const;
200
Patrick Monette5d1ba7ca2023-08-02 22:05:27201 // The different priorities that a process can have.
202 // TODO(pmonette): Consider merging with base::TaskPriority when the API is
203 // stable.
204 enum class Priority {
205 // The process does not contribute to content that is currently important
206 // to the user. Lowest priority.
207 kBestEffort,
208
Zheda Chene7421f32024-08-29 03:05:39209 // The process contributes to content that is visible to the user, but the
210 // work don't have significant performance or latency requirement, so it can
211 // run in energy efficient manner. Moderate priority.
Patrick Monette5d1ba7ca2023-08-02 22:05:27212 kUserVisible,
213
214 // The process contributes to content that is of the utmost importance to
215 // the user, like producing audible content, or visible content in the
Zheda Chene7421f32024-08-29 03:05:39216 // main frame. High priority.
Patrick Monette5d1ba7ca2023-08-02 22:05:27217 kUserBlocking,
218 };
219
Dave Tapuskaed322d02023-03-07 23:33:33220#if BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK))
lgrey0d2bafc2016-11-07 16:28:33221 // The Mac needs a Mach port in order to manipulate a process's priority,
222 // and there's no good way to get that from base given the pid. These Mac
Patrick Monette5d1ba7ca2023-08-02 22:05:27223 // variants of the `GetPriority()` and `SetPriority()` API take a port
224 // provider for this reason. See crbug.com/460102.
lgrey0d2bafc2016-11-07 16:28:33225
Patrick Monette5d1ba7ca2023-08-02 22:05:27226 // Retrieves the priority of the process. Defaults to Priority::kUserBlocking
227 // if the priority could not be retrieved, or if `port_provider` is null.
228 Priority GetPriority(PortProvider* port_provider) const;
229
230 // Sets the priority of the process process. Returns true if the priority was
231 // changed, false otherwise. If `port_provider` is null, this is a no-op and
232 // it returns false.
233 bool SetPriority(PortProvider* port_provider, Priority priority);
lgrey0d2bafc2016-11-07 16:28:33234#else
Patrick Monette5d1ba7ca2023-08-02 22:05:27235 // Retrieves the priority of the process. Defaults to Priority::kUserBlocking
236 // if the priority could not be retrieved.
237 Priority GetPriority() const;
[email protected]76bea672013-07-19 16:48:56238
Patrick Monette5d1ba7ca2023-08-02 22:05:27239 // Sets the priority of the process process. Returns true if the priority was
240 // changed, false otherwise.
241 bool SetPriority(Priority priority);
Dave Tapuskaed322d02023-03-07 23:33:33242#endif // BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK))
243
[email protected]76bea672013-07-19 16:48:56244 // Returns an integer representing the priority of a process. The meaning
245 // of this value is OS dependent.
Patrick Monette740b81b2023-07-21 21:09:09246 int GetOSPriority() const;
[email protected]76bea672013-07-19 16:48:56247
Yuta Hijikata000df18f2020-11-18 06:55:58248#if BUILDFLAG(IS_CHROMEOS_ASH)
nyad2c548b2015-12-09 03:22:32249 // Get the PID in its PID namespace.
250 // If the process is not in a PID namespace or /proc/<pid>/status does not
251 // report NSpid, kNullProcessId is returned.
252 ProcessId GetPidInNamespace() const;
253#endif
254
Matthew Dentonf969883422023-08-08 01:44:34255#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
256 // Returns true if the process has any seccomp policy applied.
257 bool IsSeccompSandboxed();
258#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
259
Youssef Esmatc732bf82022-05-27 00:47:19260#if BUILDFLAG(IS_CHROMEOS)
Shintaro Kawamuraf29c8fdf2024-03-28 03:40:08261 // Sets a delegate which handles process priority changes. This
262 // must be externally synchronized with any call to base::Process methods.
263 static void SetProcessPriorityDelegate(ProcessPriorityDelegate* delegate);
264
Youssef Esmat10aa75d2022-06-10 11:58:46265 // Exposes OneGroupPerRendererEnabled() to unit tests.
266 static bool OneGroupPerRendererEnabledForTesting();
Youssef Esmatc732bf82022-05-27 00:47:19267
268 // If OneGroupPerRenderer is enabled, runs at process startup to clean up
269 // any stale cgroups that were left behind from any unclean exits of the
270 // browser process.
271 static void CleanUpStaleProcessStates();
272
Shintaro Kawamuraf726c1292024-03-28 03:40:08273 // Initializes the process's priority.
274 //
275 // This should be called before SetPriority().
276 //
277 // If SchedQoSOnResourcedForChrome is enabled, this creates a cache entry for
278 // the process priority. The returned `base::Process::PriorityEntry` should be
279 // freed when the process is terminated so that the cached entry is freed from
280 // the internal map.
281 //
282 // If OneGroupPerRenderer is enabled, it also creates a unique cgroup for the
283 // process.
284 // This is a no-op if the Process is not valid or if it has already been
285 // called.
Youssef Esmatc732bf82022-05-27 00:47:19286 void InitializePriority();
Shintaro Kawamuraf726c1292024-03-28 03:40:08287
288 // Clears the entities initialized by InitializePriority().
289 //
290 // This is no-op if SchedQoSOnResourcedForChrome is disabled.
291 void ForgetPriority();
Youssef Esmatc732bf82022-05-27 00:47:19292#endif // BUILDFLAG(IS_CHROMEOS)
293
Dave Tapuskaed322d02023-03-07 23:33:33294#if BUILDFLAG(IS_APPLE)
Patrick Monette209f31da2023-08-31 21:25:33295 // Sets the priority of the current process to its default value.
Patrick Monetteee7f72f2023-01-23 22:59:45296 static void SetCurrentTaskDefaultRole();
297#endif // BUILDFLAG(IS_MAC)
298
Dave Tapuska31c385c2024-04-12 18:43:11299#if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK)
300 using TerminateCallback = bool (*)(ProcessHandle handle);
301 using WaitForExitCallback = bool (*)(ProcessHandle handle,
302 int* exit_code,
303 base::TimeDelta timeout);
304 // Function ptrs to implement termination without polluting //base with
305 // BrowserEngineKit APIs.
306 static void SetTerminationHooks(TerminateCallback terminate_callback,
307 WaitForExitCallback wait_callback);
308#if TARGET_OS_SIMULATOR
309 // Methods for supporting both "content processes" and traditional
310 // forked processes. For non-simulator builds on iOS every process would
311 // be a "content process" so we don't need the conditionals.
312 void SetIsContentProcess();
313 bool IsContentProcess() const;
314#endif
315#endif
316
[email protected]76bea672013-07-19 16:48:56317 private:
Youssef Esmatc732bf82022-05-27 00:47:19318#if BUILDFLAG(IS_CHROMEOS)
319 // Cleans up process state. If OneGroupPerRenderer is enabled, it cleans up
320 // the cgroup created by InitializePriority(). If the process has not
321 // fully terminated yet, it will post a background task to try again.
322 void CleanUpProcess(int remaining_retries) const;
323
324 // Calls CleanUpProcess() on a background thread.
325 void CleanUpProcessAsync() const;
326
327 // Used to call CleanUpProcess() on a background thread because Process is not
328 // refcounted.
329 static void CleanUpProcessScheduled(Process process, int remaining_retries);
330#endif // BUILDFLAG(IS_CHROMEOS)
331
Dave Tapuska31c385c2024-04-12 18:43:11332#if !BUILDFLAG(IS_IOS) || (BUILDFLAG(IS_IOS) && TARGET_OS_SIMULATOR)
333 bool TerminateInternal(int exit_code, bool wait) const;
334 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
335 int* exit_code,
336 base::TimeDelta timeout) const;
337#endif
338
Xiaohan Wang37e81612022-01-15 18:27:00339#if BUILDFLAG(IS_WIN)
rvargas079d1842014-10-17 22:32:16340 win::ScopedHandle process_;
Xiaohan Wang37e81612022-01-15 18:27:00341#elif BUILDFLAG(IS_FUCHSIA)
Wez157707d62018-07-10 22:48:47342 zx::process process_;
rvargas079d1842014-10-17 22:32:16343#else
[email protected]76bea672013-07-19 16:48:56344 ProcessHandle process_;
rvargas079d1842014-10-17 22:32:16345#endif
dcheng1a2fd6cd2016-06-07 21:39:12346
Xiaohan Wang37e81612022-01-15 18:27:00347#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
scottmg297cc932017-05-24 03:45:58348 bool is_current_process_;
349#endif
Youssef Esmatc732bf82022-05-27 00:47:19350
Dave Tapuska31c385c2024-04-12 18:43:11351#if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR
352 // A flag indicating that this is a "content process". iOS does not support
353 // generic process invocation but it does support some types of well defined
354 // processes. These types of processes are defined at the //content layer so
355 // for termination we defer to some globally initialized callbacks.
356 bool content_process_ = false;
357#endif
358
Youssef Esmatc732bf82022-05-27 00:47:19359#if BUILDFLAG(IS_CHROMEOS)
360 // A unique token per process not per class instance (`base::Process`). This
361 // is similar to the PID of a process but should not be reused after the
362 // process's termination. The token will be copied during Duplicate()
363 // and move semantics as is the PID/ProcessHandle.
364 std::string unique_token_;
365#endif
[email protected]76bea672013-07-19 16:48:56366};
367
Eric Willigers611cf542022-04-28 02:22:14368#if BUILDFLAG(IS_CHROMEOS)
afakhry8b4796b2015-11-16 18:41:44369// Exposed for testing.
370// Given the contents of the /proc/<pid>/cgroup file, determine whether the
371// process is backgrounded or not.
Patrick Monette5d1ba7ca2023-08-02 22:05:27372BASE_EXPORT Process::Priority GetProcessPriorityCGroup(
Helmut Januschkabfa62f72024-04-04 15:18:31373 std::string_view cgroup_contents);
Eric Willigers611cf542022-04-28 02:22:14374#endif // BUILDFLAG(IS_CHROMEOS)
afakhry8b4796b2015-11-16 18:41:44375
[email protected]76bea672013-07-19 16:48:56376} // namespace base
377
danakj0a448602015-03-10 00:31:16378#endif // BASE_PROCESS_PROCESS_H_