process_win.cc 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright (c) 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. #include "base/process/process.h"
  5. #include "base/clang_profiling_buildflags.h"
  6. #include "base/debug/activity_tracker.h"
  7. #include "base/logging.h"
  8. #include "base/numerics/safe_conversions.h"
  9. #include "base/process/kill.h"
  10. #include "base/threading/thread_restrictions.h"
  11. #include "base/trace_event/base_tracing.h"
  12. #include "third_party/abseil-cpp/absl/types/optional.h"
  13. #include <windows.h>
  14. #if BUILDFLAG(CLANG_PROFILING)
  15. #include "base/test/clang_profiling.h"
  16. #endif
  17. namespace {
  18. DWORD kBasicProcessAccess =
  19. PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION | SYNCHRONIZE;
  20. } // namespace
  21. namespace base {
  22. Process::Process(ProcessHandle handle)
  23. : process_(handle), is_current_process_(false) {
  24. CHECK_NE(handle, ::GetCurrentProcess());
  25. }
  26. Process::Process(Process&& other)
  27. : process_(other.process_.release()),
  28. is_current_process_(other.is_current_process_) {
  29. other.Close();
  30. }
  31. Process::~Process() {
  32. }
  33. Process& Process::operator=(Process&& other) {
  34. DCHECK_NE(this, &other);
  35. process_.Set(other.process_.release());
  36. is_current_process_ = other.is_current_process_;
  37. other.Close();
  38. return *this;
  39. }
  40. // static
  41. Process Process::Current() {
  42. Process process;
  43. process.is_current_process_ = true;
  44. return process;
  45. }
  46. // static
  47. Process Process::Open(ProcessId pid) {
  48. return Process(::OpenProcess(kBasicProcessAccess, FALSE, pid));
  49. }
  50. // static
  51. Process Process::OpenWithExtraPrivileges(ProcessId pid) {
  52. DWORD access = kBasicProcessAccess | PROCESS_DUP_HANDLE | PROCESS_VM_READ;
  53. return Process(::OpenProcess(access, FALSE, pid));
  54. }
  55. // static
  56. Process Process::OpenWithAccess(ProcessId pid, DWORD desired_access) {
  57. return Process(::OpenProcess(desired_access, FALSE, pid));
  58. }
  59. // static
  60. bool Process::CanBackgroundProcesses() {
  61. return true;
  62. }
  63. // static
  64. void Process::TerminateCurrentProcessImmediately(int exit_code) {
  65. #if BUILDFLAG(CLANG_PROFILING)
  66. WriteClangProfilingProfile();
  67. #endif
  68. ::TerminateProcess(GetCurrentProcess(), static_cast<UINT>(exit_code));
  69. // There is some ambiguity over whether the call above can return. Rather than
  70. // hitting confusing crashes later on we should crash right here.
  71. IMMEDIATE_CRASH();
  72. }
  73. bool Process::IsValid() const {
  74. return process_.is_valid() || is_current();
  75. }
  76. ProcessHandle Process::Handle() const {
  77. return is_current_process_ ? GetCurrentProcess() : process_.get();
  78. }
  79. Process Process::Duplicate() const {
  80. if (is_current())
  81. return Current();
  82. ProcessHandle out_handle;
  83. if (!IsValid() || !::DuplicateHandle(GetCurrentProcess(),
  84. Handle(),
  85. GetCurrentProcess(),
  86. &out_handle,
  87. 0,
  88. FALSE,
  89. DUPLICATE_SAME_ACCESS)) {
  90. return Process();
  91. }
  92. return Process(out_handle);
  93. }
  94. ProcessHandle Process::Release() {
  95. if (is_current())
  96. return ::GetCurrentProcess();
  97. return process_.release();
  98. }
  99. ProcessId Process::Pid() const {
  100. DCHECK(IsValid());
  101. return GetProcId(Handle());
  102. }
  103. Time Process::CreationTime() const {
  104. FILETIME creation_time = {};
  105. FILETIME ignore1 = {};
  106. FILETIME ignore2 = {};
  107. FILETIME ignore3 = {};
  108. if (!::GetProcessTimes(Handle(), &creation_time, &ignore1, &ignore2,
  109. &ignore3)) {
  110. return Time();
  111. }
  112. return Time::FromFileTime(creation_time);
  113. }
  114. bool Process::is_current() const {
  115. return is_current_process_;
  116. }
  117. void Process::Close() {
  118. is_current_process_ = false;
  119. if (!process_.is_valid())
  120. return;
  121. process_.Close();
  122. }
  123. bool Process::Terminate(int exit_code, bool wait) const {
  124. constexpr DWORD kWaitMs = 60 * 1000;
  125. DCHECK(IsValid());
  126. bool result =
  127. ::TerminateProcess(Handle(), static_cast<UINT>(exit_code)) != FALSE;
  128. if (result) {
  129. // The process may not end immediately due to pending I/O
  130. if (wait && ::WaitForSingleObject(Handle(), kWaitMs) != WAIT_OBJECT_0)
  131. DPLOG(ERROR) << "Error waiting for process exit";
  132. Exited(exit_code);
  133. } else {
  134. // The process can't be terminated, perhaps because it has already exited or
  135. // is in the process of exiting. An error code of ERROR_ACCESS_DENIED is the
  136. // undocumented-but-expected result if the process has already exited or
  137. // started exiting when TerminateProcess is called, so don't print an error
  138. // message in that case.
  139. if (GetLastError() != ERROR_ACCESS_DENIED)
  140. DPLOG(ERROR) << "Unable to terminate process";
  141. // A non-zero timeout is necessary here for the same reasons as above.
  142. if (::WaitForSingleObject(Handle(), kWaitMs) == WAIT_OBJECT_0) {
  143. DWORD actual_exit;
  144. Exited(::GetExitCodeProcess(Handle(), &actual_exit)
  145. ? static_cast<int>(actual_exit)
  146. : exit_code);
  147. result = true;
  148. }
  149. }
  150. return result;
  151. }
  152. Process::WaitExitStatus Process::WaitForExitOrEvent(
  153. const base::win::ScopedHandle& stop_event_handle,
  154. int* exit_code) const {
  155. // Record the event that this thread is blocking upon (for hang diagnosis).
  156. base::debug::ScopedProcessWaitActivity process_activity(this);
  157. HANDLE events[] = {Handle(), stop_event_handle.get()};
  158. DWORD wait_result =
  159. ::WaitForMultipleObjects(std::size(events), events, FALSE, INFINITE);
  160. if (wait_result == WAIT_OBJECT_0) {
  161. DWORD temp_code; // Don't clobber out-parameters in case of failure.
  162. if (!::GetExitCodeProcess(Handle(), &temp_code))
  163. return Process::WaitExitStatus::FAILED;
  164. if (exit_code)
  165. *exit_code = static_cast<int>(temp_code);
  166. Exited(static_cast<int>(temp_code));
  167. return Process::WaitExitStatus::PROCESS_EXITED;
  168. }
  169. if (wait_result == WAIT_OBJECT_0 + 1) {
  170. return Process::WaitExitStatus::STOP_EVENT_SIGNALED;
  171. }
  172. return Process::WaitExitStatus::FAILED;
  173. }
  174. bool Process::WaitForExit(int* exit_code) const {
  175. return WaitForExitWithTimeout(TimeDelta::Max(), exit_code);
  176. }
  177. bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
  178. TRACE_EVENT0("base", "Process::WaitForExitWithTimeout");
  179. // Record the event that this thread is blocking upon (for hang diagnosis).
  180. absl::optional<debug::ScopedProcessWaitActivity> process_activity;
  181. if (!timeout.is_zero()) {
  182. process_activity.emplace(this);
  183. // Assert that this thread is allowed to wait below. This intentionally
  184. // doesn't use ScopedBlockingCallWithBaseSyncPrimitives because the process
  185. // being waited upon tends to itself be using the CPU and considering this
  186. // thread non-busy causes more issue than it fixes: http://crbug.com/905788
  187. internal::AssertBaseSyncPrimitivesAllowed();
  188. }
  189. // Limit timeout to INFINITE.
  190. DWORD timeout_ms = saturated_cast<DWORD>(timeout.InMilliseconds());
  191. if (::WaitForSingleObject(Handle(), timeout_ms) != WAIT_OBJECT_0)
  192. return false;
  193. DWORD temp_code; // Don't clobber out-parameters in case of failure.
  194. if (!::GetExitCodeProcess(Handle(), &temp_code))
  195. return false;
  196. if (exit_code)
  197. *exit_code = static_cast<int>(temp_code);
  198. Exited(static_cast<int>(temp_code));
  199. return true;
  200. }
  201. void Process::Exited(int exit_code) const {
  202. base::debug::GlobalActivityTracker::RecordProcessExitIfEnabled(Pid(),
  203. exit_code);
  204. }
  205. bool Process::IsProcessBackgrounded() const {
  206. DCHECK(IsValid());
  207. int priority = GetPriority();
  208. if (priority == 0)
  209. return false; // Failure case.
  210. return ((priority == BELOW_NORMAL_PRIORITY_CLASS) ||
  211. (priority == IDLE_PRIORITY_CLASS));
  212. }
  213. bool Process::SetProcessBackgrounded(bool value) {
  214. DCHECK(IsValid());
  215. // Vista and above introduce a real background mode, which not only
  216. // sets the priority class on the threads but also on the IO generated
  217. // by it. Unfortunately it can only be set for the calling process.
  218. DWORD priority;
  219. if (is_current()) {
  220. priority = value ? PROCESS_MODE_BACKGROUND_BEGIN :
  221. PROCESS_MODE_BACKGROUND_END;
  222. } else {
  223. priority = value ? IDLE_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS;
  224. }
  225. return (::SetPriorityClass(Handle(), priority) != 0);
  226. }
  227. int Process::GetPriority() const {
  228. DCHECK(IsValid());
  229. return static_cast<int>(::GetPriorityClass(Handle()));
  230. }
  231. } // namespace base