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 <string_view> 9 10 #include "base/base_export.h" 11 #include "base/compiler_specific.h" 12 #include "base/process/process_handle.h" 13 #include "base/time/time.h" 14 #include "build/blink_buildflags.h" 15 #include "build/build_config.h" 16 #include "build/chromeos_buildflags.h" 17 18 #if BUILDFLAG(IS_WIN) 19 #include "base/win/scoped_handle.h" 20 #endif 21 22 #if BUILDFLAG(IS_FUCHSIA) 23 #include <lib/zx/process.h> 24 #endif 25 26 #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN) 27 #include "base/feature_list.h" 28 #endif // BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN) 29 30 #if BUILDFLAG(IS_APPLE) 31 #include "base/process/port_provider_mac.h" 32 #endif // BUILDFLAG(IS_APPLE) 33 34 namespace base { 35 36 #if BUILDFLAG(IS_CHROMEOS) 37 // OneGroupPerRenderer feature places each foreground renderer process into 38 // its own cgroup. This will cause the scheduler to use the aggregate runtime 39 // of all threads in the process when deciding on the next thread to schedule. 40 // It will help guarantee fairness between renderers. 41 BASE_EXPORT BASE_DECLARE_FEATURE(kOneGroupPerRenderer); 42 43 // Set all threads of a background process as backgrounded, which changes the 44 // thread attributes including c-group, latency sensitivity. But the nice value 45 // is unchanged, since background process is under the spell of the background 46 // CPU c-group (via cgroup.procs). 47 BASE_EXPORT BASE_DECLARE_FEATURE(kSetThreadBgForBgProcess); 48 49 class ProcessPriorityDelegate; 50 #endif 51 52 // Provides a move-only encapsulation of a process. 53 // 54 // This object is not tied to the lifetime of the underlying process: the 55 // process may be killed and this object may still around, and it will still 56 // claim to be valid. The actual behavior in that case is OS dependent like so: 57 // 58 // Windows: The underlying ProcessHandle will be valid after the process dies 59 // and can be used to gather some information about that process, but most 60 // methods will obviously fail. 61 // 62 // POSIX: The underlying ProcessHandle is not guaranteed to remain valid after 63 // the process dies, and it may be reused by the system, which means that it may 64 // end up pointing to the wrong process. 65 class BASE_EXPORT Process { 66 public: 67 // On Windows, this takes ownership of |handle|. On POSIX, this does not take 68 // ownership of |handle|. 69 explicit Process(ProcessHandle handle = kNullProcessHandle); 70 71 Process(Process&& other); 72 73 Process(const Process&) = delete; 74 Process& operator=(const Process&) = delete; 75 76 // The destructor does not terminate the process. 77 ~Process(); 78 79 Process& operator=(Process&& other); 80 81 // Returns an object for the current process. 82 static Process Current(); 83 84 // Returns a Process for the given |pid|. 85 static Process Open(ProcessId pid); 86 87 // Returns a Process for the given |pid|. On Windows the handle is opened 88 // with more access rights and must only be used by trusted code (can read the 89 // address space and duplicate handles). 90 static Process OpenWithExtraPrivileges(ProcessId pid); 91 92 #if BUILDFLAG(IS_WIN) 93 // Returns a Process for the given |pid|, using some |desired_access|. 94 // See ::OpenProcess documentation for valid |desired_access|. 95 static Process OpenWithAccess(ProcessId pid, DWORD desired_access); 96 #endif 97 98 // Returns true if changing the priority of processes through `SetPriority()` 99 // is possible. 100 static bool CanSetPriority(); 101 102 // Terminates the current process immediately with |exit_code|. 103 [[noreturn]] static void TerminateCurrentProcessImmediately(int exit_code); 104 105 // Returns true if this objects represents a valid process. 106 bool IsValid() const; 107 108 // Returns a handle for this process. There is no guarantee about when that 109 // handle becomes invalid because this object retains ownership. 110 ProcessHandle Handle() const; 111 112 // Returns a second object that represents this process. 113 Process Duplicate() const; 114 115 // Relinquishes ownership of the handle and sets this to kNullProcessHandle. 116 // The result may be a pseudo-handle, depending on the OS and value stored in 117 // this. 118 [[nodiscard]] ProcessHandle Release(); 119 120 // Get the PID for this process. 121 ProcessId Pid() const; 122 123 // Get the creation time for this process. Since the Pid can be reused after a 124 // process dies, it is useful to use both the Pid and the creation time to 125 // uniquely identify a process. 126 // 127 // On Android, works only if |this| is the current process, as security 128 // features prevent an application from getting data about other processes, 129 // even if they belong to us. Otherwise, returns Time(). 130 Time CreationTime() const; 131 132 // Returns true if this process is the current process. 133 bool is_current() const; 134 135 #if BUILDFLAG(IS_CHROMEOS) 136 // A unique token generated for each process, this is used to create a unique 137 // cgroup for each renderer. unique_token()138 const std::string& unique_token() const LIFETIME_BOUND { 139 return unique_token_; 140 } 141 #endif 142 143 // Close the process handle. This will not terminate the process. 144 void Close(); 145 146 // Returns true if this process is still running. This is only safe on Windows 147 // (and maybe Fuchsia?), because the ProcessHandle will keep the zombie 148 // process information available until itself has been released. But on Posix, 149 // the OS may reuse the ProcessId. 150 #if BUILDFLAG(IS_WIN) IsRunning()151 bool IsRunning() const { 152 return !WaitForExitWithTimeout(base::TimeDelta(), nullptr); 153 } 154 #endif 155 156 // Terminates the process with extreme prejudice. The given |exit_code| will 157 // be the exit code of the process. If |wait| is true, this method will wait 158 // for up to one minute for the process to actually terminate. 159 // Returns true if the process terminates within the allowed time. 160 // NOTE: |exit_code| is only used on OS_WIN. 161 bool Terminate(int exit_code, bool wait) const; 162 163 #if BUILDFLAG(IS_WIN) 164 enum class WaitExitStatus { 165 PROCESS_EXITED, 166 STOP_EVENT_SIGNALED, 167 FAILED, 168 }; 169 170 // Waits for the process to exit, or the specified |stop_event_handle| to be 171 // set. Returns value indicating which event was set. The given |exit_code| 172 // will be the exit code of the process. 173 WaitExitStatus WaitForExitOrEvent( 174 const base::win::ScopedHandle& stop_event_handle, 175 int* exit_code) const; 176 #endif // BUILDFLAG(IS_WIN) 177 178 // Waits for the process to exit. Returns true on success. 179 // On POSIX, if the process has been signaled then |exit_code| is set to -1. 180 // On Linux this must be a child process, however on Mac and Windows it can be 181 // any process. 182 // NOTE: |exit_code| is optional, nullptr can be passed if the exit code is 183 // not required. 184 bool WaitForExit(int* exit_code) const; 185 186 // Same as WaitForExit() but only waits for up to |timeout|. 187 // NOTE: |exit_code| is optional, nullptr can be passed if the exit code 188 // is not required. 189 bool WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const; 190 191 // Indicates that the process has exited with the specified |exit_code|. 192 // This should be called if process exit is observed outside of this class. 193 // (i.e. Not because Terminate or WaitForExit, above, was called.) 194 // Note that nothing prevents this being called multiple times for a dead 195 // process though that should be avoided. 196 void Exited(int exit_code) const; 197 198 // The different priorities that a process can have. 199 // TODO(pmonette): Consider merging with base::TaskPriority when the API is 200 // stable. 201 enum class Priority { 202 // The process does not contribute to content that is currently important 203 // to the user. Lowest priority. 204 kBestEffort, 205 206 // The process contributes to content that is visible to the user, but the 207 // work don't have significant performance or latency requirement, so it can 208 // run in energy efficient manner. Moderate priority. 209 kUserVisible, 210 211 // The process contributes to content that is of the utmost importance to 212 // the user, like producing audible content, or visible content in the 213 // main frame. High priority. 214 kUserBlocking, 215 216 kMaxValue = kUserBlocking, 217 }; 218 219 #if BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK)) 220 // The Mac needs a Mach port in order to manipulate a process's priority, 221 // and there's no good way to get that from base given the pid. These Mac 222 // variants of the `GetPriority()` and `SetPriority()` API take a port 223 // provider for this reason. See crbug.com/460102. 224 225 // Retrieves the priority of the process. Defaults to Priority::kUserBlocking 226 // if the priority could not be retrieved, or if `port_provider` is null. 227 Priority GetPriority(PortProvider* port_provider) const; 228 229 // Sets the priority of the process process. Returns true if the priority was 230 // changed, false otherwise. If `port_provider` is null, this is a no-op and 231 // it returns false. 232 bool SetPriority(PortProvider* port_provider, Priority priority); 233 #else 234 // Retrieves the priority of the process. Defaults to Priority::kUserBlocking 235 // if the priority could not be retrieved. 236 Priority GetPriority() const; 237 238 // Sets the priority of the process process. Returns true if the priority was 239 // changed, false otherwise. 240 bool SetPriority(Priority priority); 241 #endif // BUILDFLAG(IS_MAC) || (BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK)) 242 243 // Returns an integer representing the priority of a process. The meaning 244 // of this value is OS dependent. 245 int GetOSPriority() const; 246 247 #if BUILDFLAG(IS_CHROMEOS_ASH) 248 // Get the PID in its PID namespace. 249 // If the process is not in a PID namespace or /proc/<pid>/status does not 250 // report NSpid, kNullProcessId is returned. 251 ProcessId GetPidInNamespace() const; 252 #endif 253 254 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 255 // Returns true if the process has any seccomp policy applied. 256 bool IsSeccompSandboxed(); 257 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) 258 259 #if BUILDFLAG(IS_CHROMEOS) 260 // Sets a delegate which handles process priority changes. This 261 // must be externally synchronized with any call to base::Process methods. 262 static void SetProcessPriorityDelegate(ProcessPriorityDelegate* delegate); 263 264 // Exposes OneGroupPerRendererEnabled() to unit tests. 265 static bool OneGroupPerRendererEnabledForTesting(); 266 267 // If OneGroupPerRenderer is enabled, runs at process startup to clean up 268 // any stale cgroups that were left behind from any unclean exits of the 269 // browser process. 270 static void CleanUpStaleProcessStates(); 271 272 // Initializes the process's priority. 273 // 274 // This should be called before SetPriority(). 275 // 276 // If SchedQoSOnResourcedForChrome is enabled, this creates a cache entry for 277 // the process priority. The returned `base::Process::PriorityEntry` should be 278 // freed when the process is terminated so that the cached entry is freed from 279 // the internal map. 280 // 281 // If OneGroupPerRenderer is enabled, it also creates a unique cgroup for the 282 // process. 283 // This is a no-op if the Process is not valid or if it has already been 284 // called. 285 void InitializePriority(); 286 287 // Clears the entities initialized by InitializePriority(). 288 // 289 // This is no-op if SchedQoSOnResourcedForChrome is disabled. 290 void ForgetPriority(); 291 #endif // BUILDFLAG(IS_CHROMEOS) 292 293 #if BUILDFLAG(IS_APPLE) 294 // Sets the priority of the current process to its default value. 295 static void SetCurrentTaskDefaultRole(); 296 #endif // BUILDFLAG(IS_MAC) 297 298 #if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) 299 using TerminateCallback = bool (*)(ProcessHandle handle); 300 using WaitForExitCallback = bool (*)(ProcessHandle handle, 301 int* exit_code, 302 base::TimeDelta timeout); 303 // Function ptrs to implement termination without polluting //base with 304 // BrowserEngineKit APIs. 305 static void SetTerminationHooks(TerminateCallback terminate_callback, 306 WaitForExitCallback wait_callback); 307 #if TARGET_OS_SIMULATOR 308 // Methods for supporting both "content processes" and traditional 309 // forked processes. For non-simulator builds on iOS every process would 310 // be a "content process" so we don't need the conditionals. 311 void SetIsContentProcess(); 312 bool IsContentProcess() const; 313 #endif 314 #endif 315 316 private: 317 #if BUILDFLAG(IS_CHROMEOS) 318 // Cleans up process state. If OneGroupPerRenderer is enabled, it cleans up 319 // the cgroup created by InitializePriority(). If the process has not 320 // fully terminated yet, it will post a background task to try again. 321 void CleanUpProcess(int remaining_retries) const; 322 323 // Calls CleanUpProcess() on a background thread. 324 void CleanUpProcessAsync() const; 325 326 // Used to call CleanUpProcess() on a background thread because Process is not 327 // refcounted. 328 static void CleanUpProcessScheduled(Process process, int remaining_retries); 329 #endif // BUILDFLAG(IS_CHROMEOS) 330 331 #if !BUILDFLAG(IS_IOS) || (BUILDFLAG(IS_IOS) && TARGET_OS_SIMULATOR) 332 bool TerminateInternal(int exit_code, bool wait) const; 333 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle, 334 int* exit_code, 335 base::TimeDelta timeout) const; 336 #endif 337 338 #if BUILDFLAG(IS_WIN) 339 win::ScopedHandle process_; 340 #elif BUILDFLAG(IS_FUCHSIA) 341 zx::process process_; 342 #else 343 ProcessHandle process_; 344 #endif 345 346 #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA) 347 bool is_current_process_; 348 #endif 349 350 #if BUILDFLAG(IS_IOS) && BUILDFLAG(USE_BLINK) && TARGET_OS_SIMULATOR 351 // A flag indicating that this is a "content process". iOS does not support 352 // generic process invocation but it does support some types of well defined 353 // processes. These types of processes are defined at the //content layer so 354 // for termination we defer to some globally initialized callbacks. 355 bool content_process_ = false; 356 #endif 357 358 #if BUILDFLAG(IS_CHROMEOS) 359 // A unique token per process not per class instance (`base::Process`). This 360 // is similar to the PID of a process but should not be reused after the 361 // process's termination. The token will be copied during Duplicate() 362 // and move semantics as is the PID/ProcessHandle. 363 std::string unique_token_; 364 #endif 365 }; 366 367 #if BUILDFLAG(IS_CHROMEOS) 368 // Exposed for testing. 369 // Given the contents of the /proc/<pid>/cgroup file, determine whether the 370 // process is backgrounded or not. 371 BASE_EXPORT Process::Priority GetProcessPriorityCGroup( 372 std::string_view cgroup_contents); 373 #endif // BUILDFLAG(IS_CHROMEOS) 374 375 } // namespace base 376 377 #endif // BASE_PROCESS_PROCESS_H_ 378