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