• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 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 #ifndef BASE_PROCESS_PROCESS_H_
6 #define BASE_PROCESS_PROCESS_H_
7 
8 #include "base/base_export.h"
9 #include "base/process/process_handle.h"
10 #include "base/strings/string_piece.h"
11 #include "base/time/time.h"
12 #include "build/blink_buildflags.h"
13 #include "build/build_config.h"
14 #include "build/chromeos_buildflags.h"
15 
16 #if BUILDFLAG(IS_WIN)
17 #include "base/win/scoped_handle.h"
18 #endif
19 
20 #if BUILDFLAG(IS_FUCHSIA)
21 #include <lib/zx/process.h>
22 #endif
23 
24 #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN)
25 #include "base/feature_list.h"
26 #endif  // BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN)
27 
28 #if BUILDFLAG(IS_APPLE)
29 #include "base/process/port_provider_mac.h"
30 #endif  // BUILDFLAG(IS_APPLE)
31 
32 namespace base {
33 
34 #if BUILDFLAG(IS_APPLE)
35 BASE_DECLARE_FEATURE(kMacAllowBackgroundingProcesses);
36 #endif
37 
38 #if BUILDFLAG(IS_CHROMEOS)
39 // OneGroupPerRenderer feature places each foreground renderer process into
40 // its own cgroup. This will cause the scheduler to use the aggregate runtime
41 // of all threads in the process when deciding on the next thread to schedule.
42 // It will help guarantee fairness between renderers.
43 BASE_EXPORT BASE_DECLARE_FEATURE(kOneGroupPerRenderer);
44 #endif
45 
46 #if BUILDFLAG(IS_WIN)
47 BASE_EXPORT BASE_DECLARE_FEATURE(kUseEcoQoSForBackgroundProcess);
48 #endif
49 
50 // Provides a move-only encapsulation of a process.
51 //
52 // This object is not tied to the lifetime of the underlying process: the
53 // process may be killed and this object may still around, and it will still
54 // claim to be valid. The actual behavior in that case is OS dependent like so:
55 //
56 // Windows: The underlying ProcessHandle will be valid after the process dies
57 // and can be used to gather some information about that process, but most
58 // methods will obviously fail.
59 //
60 // POSIX: The underlying ProcessHandle is not guaranteed to remain valid after
61 // the process dies, and it may be reused by the system, which means that it may
62 // end up pointing to the wrong process.
63 class BASE_EXPORT Process {
64  public:
65   // On Windows, this takes ownership of |handle|. On POSIX, this does not take
66   // ownership of |handle|.
67   explicit Process(ProcessHandle handle = kNullProcessHandle);
68 
69   Process(Process&& other);
70 
71   Process(const Process&) = delete;
72   Process& operator=(const Process&) = delete;
73 
74   // The destructor does not terminate the process.
75   ~Process();
76 
77   Process& operator=(Process&& other);
78 
79   // Returns an object for the current process.
80   static Process Current();
81 
82   // Returns a Process for the given |pid|.
83   static Process Open(ProcessId pid);
84 
85   // Returns a Process for the given |pid|. On Windows the handle is opened
86   // with more access rights and must only be used by trusted code (can read the
87   // address space and duplicate handles).
88   static Process OpenWithExtraPrivileges(ProcessId pid);
89 
90 #if BUILDFLAG(IS_WIN)
91   // Returns a Process for the given |pid|, using some |desired_access|.
92   // See ::OpenProcess documentation for valid |desired_access|.
93   static Process OpenWithAccess(ProcessId pid, DWORD desired_access);
94 #endif
95 
96   // Returns true if processes can be backgrounded.
97   static bool CanBackgroundProcesses();
98 
99   // Terminates the current process immediately with |exit_code|.
100   [[noreturn]] static void TerminateCurrentProcessImmediately(int exit_code);
101 
102   // Returns true if this objects represents a valid process.
103   bool IsValid() const;
104 
105   // Returns a handle for this process. There is no guarantee about when that
106   // handle becomes invalid because this object retains ownership.
107   ProcessHandle Handle() const;
108 
109   // Returns a second object that represents this process.
110   Process Duplicate() const;
111 
112   // Relinquishes ownership of the handle and sets this to kNullProcessHandle.
113   // The result may be a pseudo-handle, depending on the OS and value stored in
114   // this.
115   [[nodiscard]] ProcessHandle Release();
116 
117   // Get the PID for this process.
118   ProcessId Pid() const;
119 
120   // Get the creation time for this process. Since the Pid can be reused after a
121   // process dies, it is useful to use both the Pid and the creation time to
122   // uniquely identify a process.
123   //
124   // On Android, works only if |this| is the current process, as security
125   // features prevent an application from getting data about other processes,
126   // even if they belong to us. Otherwise, returns Time().
127   Time CreationTime() const;
128 
129   // Returns true if this process is the current process.
130   bool is_current() const;
131 
132 #if BUILDFLAG(IS_CHROMEOS)
133   // A unique token generated for each process, this is used to create a unique
134   // cgroup for each renderer.
unique_token()135   const std::string& unique_token() const { return unique_token_; }
136 #endif
137 
138   // Close the process handle. This will not terminate the process.
139   void Close();
140 
141   // Returns true if this process is still running. This is only safe on Windows
142   // (and maybe Fuchsia?), because the ProcessHandle will keep the zombie
143   // process information available until itself has been released. But on Posix,
144   // the OS may reuse the ProcessId.
145 #if BUILDFLAG(IS_WIN)
IsRunning()146   bool IsRunning() const {
147     return !WaitForExitWithTimeout(base::TimeDelta(), nullptr);
148   }
149 #endif
150 
151   // Terminates the process with extreme prejudice. The given |exit_code| will
152   // be the exit code of the process. If |wait| is true, this method will wait
153   // for up to one minute for the process to actually terminate.
154   // Returns true if the process terminates within the allowed time.
155   // NOTE: |exit_code| is only used on OS_WIN.
156   bool Terminate(int exit_code, bool wait) const;
157 
158 #if BUILDFLAG(IS_WIN)
159   enum class WaitExitStatus {
160     PROCESS_EXITED,
161     STOP_EVENT_SIGNALED,
162     FAILED,
163   };
164 
165   // Waits for the process to exit, or the specified |stop_event_handle| to be
166   // set. Returns value indicating which event was set. The given |exit_code|
167   // will be the exit code of the process.
168   WaitExitStatus WaitForExitOrEvent(
169       const base::win::ScopedHandle& stop_event_handle,
170       int* exit_code) const;
171 #endif  // BUILDFLAG(IS_WIN)
172 
173   // Waits for the process to exit. Returns true on success.
174   // On POSIX, if the process has been signaled then |exit_code| is set to -1.
175   // On Linux this must be a child process, however on Mac and Windows it can be
176   // any process.
177   // NOTE: |exit_code| is optional, nullptr can be passed if the exit code is
178   // not required.
179   bool WaitForExit(int* exit_code) const;
180 
181   // Same as WaitForExit() but only waits for up to |timeout|.
182   // NOTE: |exit_code| is optional, nullptr can be passed if the exit code
183   // is not required.
184   bool WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const;
185 
186   // Indicates that the process has exited with the specified |exit_code|.
187   // This should be called if process exit is observed outside of this class.
188   // (i.e. Not because Terminate or WaitForExit, above, was called.)
189   // Note that nothing prevents this being called multiple times for a dead
190   // process though that should be avoided.
191   void Exited(int exit_code) const;
192 
193 #if BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK))
194   // The Mac needs a Mach port in order to manipulate a process's priority,
195   // and there's no good way to get that from base given the pid. These Mac
196   // variants of the IsProcessBackgrounded() and SetProcessBackgrounded() API
197   // take a port provider for this reason. See crbug.com/460102
198   //
199   // A process is backgrounded when its task priority is
200   // |TASK_BACKGROUND_APPLICATION|.
201   //
202   // Returns true if the port_provider can locate a task port for the process
203   // and it is backgrounded. If port_provider is null, returns false.
204   bool IsProcessBackgrounded(PortProvider* port_provider) const;
205 
206   // Set the process as backgrounded. If value is
207   // true, the priority of the associated task will be set to
208   // TASK_BACKGROUND_APPLICATION. If value is false, the
209   // priority of the process will be set to TASK_FOREGROUND_APPLICATION.
210   //
211   // Returns true if the priority was changed, false otherwise. If
212   // |port_provider| is null, this is a no-op and it returns false.
213   bool SetProcessBackgrounded(PortProvider* port_provider, bool value);
214 #else
215   // A process is backgrounded when it's priority is lower than normal.
216   // Return true if this process is backgrounded, false otherwise.
217   bool IsProcessBackgrounded() const;
218 
219   // Set a process as backgrounded. If value is true, the priority of the
220   // process will be lowered. If value is false, the priority of the process
221   // will be made "normal" - equivalent to default process priority.
222   // Returns true if the priority was changed, false otherwise.
223   bool SetProcessBackgrounded(bool value);
224 #endif  // BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK))
225 
226   // Returns an integer representing the priority of a process. The meaning
227   // of this value is OS dependent.
228   int GetPriority() const;
229 
230 #if BUILDFLAG(IS_CHROMEOS_ASH)
231   // Get the PID in its PID namespace.
232   // If the process is not in a PID namespace or /proc/<pid>/status does not
233   // report NSpid, kNullProcessId is returned.
234   ProcessId GetPidInNamespace() const;
235 #endif
236 
237 #if BUILDFLAG(IS_CHROMEOS)
238   // Exposes OneGroupPerRendererEnabled() to unit tests.
239   static bool OneGroupPerRendererEnabledForTesting();
240 
241   // If OneGroupPerRenderer is enabled, runs at process startup to clean up
242   // any stale cgroups that were left behind from any unclean exits of the
243   // browser process.
244   static void CleanUpStaleProcessStates();
245 
246   // Initializes the process's priority. If OneGroupPerRenderer is enabled, it
247   // creates a unique cgroup for the process. This should be called before
248   // SetProcessBackgrounded(). This is a no-op if the Process is not valid
249   // or if it has already been called.
250   void InitializePriority();
251 #endif  // BUILDFLAG(IS_CHROMEOS)
252 
253 #if BUILDFLAG(IS_APPLE)
254   // Sets the `task_role_t` of the current task (the calling process) to
255   // TASK_DEFAULT_APPLICATION, if the MacSetDefaultTaskRole feature is
256   // enabled.
257   static void SetCurrentTaskDefaultRole();
258 #endif  // BUILDFLAG(IS_MAC)
259 
260  private:
261 #if BUILDFLAG(IS_CHROMEOS)
262   // Cleans up process state. If OneGroupPerRenderer is enabled, it cleans up
263   // the cgroup created by InitializePriority(). If the process has not
264   // fully terminated yet, it will post a background task to try again.
265   void CleanUpProcess(int remaining_retries) const;
266 
267   // Calls CleanUpProcess() on a background thread.
268   void CleanUpProcessAsync() const;
269 
270   // Used to call CleanUpProcess() on a background thread because Process is not
271   // refcounted.
272   static void CleanUpProcessScheduled(Process process, int remaining_retries);
273 #endif  // BUILDFLAG(IS_CHROMEOS)
274 
275 #if BUILDFLAG(IS_WIN)
276   win::ScopedHandle process_;
277 #elif BUILDFLAG(IS_FUCHSIA)
278   zx::process process_;
279 #else
280   ProcessHandle process_;
281 #endif
282 
283 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
284   bool is_current_process_;
285 #endif
286 
287 #if BUILDFLAG(IS_CHROMEOS)
288   // A unique token per process not per class instance (`base::Process`). This
289   // is similar to the PID of a process but should not be reused after the
290   // process's termination. The token will be copied during Duplicate()
291   // and move semantics as is the PID/ProcessHandle.
292   std::string unique_token_;
293 #endif
294 };
295 
296 #if BUILDFLAG(IS_CHROMEOS)
297 // Exposed for testing.
298 // Given the contents of the /proc/<pid>/cgroup file, determine whether the
299 // process is backgrounded or not.
300 BASE_EXPORT bool IsProcessBackgroundedCGroup(
301     const StringPiece& cgroup_contents);
302 #endif  // BUILDFLAG(IS_CHROMEOS)
303 
304 }  // namespace base
305 
306 #endif  // BASE_PROCESS_PROCESS_H_
307