1 // Copyright 2024 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 #include "base/process/process.h"
6
7 #include "base/threading/thread_restrictions.h"
8
9 namespace base {
10
11 namespace {
12
13 static Process::TerminateCallback g_terminate_callback = nullptr;
14 static Process::WaitForExitCallback g_wait_for_exit_callback = nullptr;
15
16 } // namespace
17
18 bool WaitForExitWithTimeoutImpl(base::ProcessHandle handle,
19 int* exit_code,
20 base::TimeDelta timeout);
21
SetTerminationHooks(TerminateCallback terminate_callback,WaitForExitCallback wait_callback)22 void Process::SetTerminationHooks(TerminateCallback terminate_callback,
23 WaitForExitCallback wait_callback) {
24 CHECK(!g_terminate_callback);
25 CHECK(!g_wait_for_exit_callback);
26 g_terminate_callback = terminate_callback;
27 g_wait_for_exit_callback = wait_callback;
28 }
29
30 #if TARGET_OS_SIMULATOR
SetIsContentProcess()31 void Process::SetIsContentProcess() {
32 content_process_ = true;
33 }
34
IsContentProcess() const35 bool Process::IsContentProcess() const {
36 return content_process_;
37 }
38 #endif
39
Terminate(int exit_code,bool wait) const40 bool Process::Terminate(int exit_code, bool wait) const {
41 // exit_code isn't supportable.
42 DCHECK(IsValid());
43 CHECK_GT(process_, 0);
44 #if TARGET_OS_SIMULATOR
45 if (!content_process_) {
46 return TerminateInternal(exit_code, wait);
47 }
48 #endif
49 CHECK(g_terminate_callback);
50 return (*g_terminate_callback)(process_);
51 }
52
WaitForExitWithTimeout(TimeDelta timeout,int * exit_code) const53 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
54 if (!timeout.is_zero()) {
55 // Assert that this thread is allowed to wait below. This intentionally
56 // doesn't use ScopedBlockingCallWithBaseSyncPrimitives because the process
57 // being waited upon tends to itself be using the CPU and considering this
58 // thread non-busy causes more issue than it fixes: http://crbug.com/905788
59 internal::AssertBaseSyncPrimitivesAllowed();
60 }
61
62 #if TARGET_OS_SIMULATOR
63 if (!content_process_) {
64 return WaitForExitWithTimeoutImpl(Handle(), exit_code, timeout);
65 }
66 #endif
67 return (*g_wait_for_exit_callback)(process_, exit_code, timeout);
68 }
69
70 } // namespace base
71