process.h 11 KB

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