1 // Copyright 2014 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.
5 #include "sandbox/linux/services/scoped_process.h"
10 #include <sys/syscall.h>
11 #include <sys/types.h>
15 #include "base/basictypes.h"
16 #include "base/callback.h"
17 #include "base/logging.h"
18 #include "base/posix/eintr_wrapper.h"
19 #include "build/build_config.h"
20 #include "sandbox/linux/services/syscall_wrappers.h"
21 #include "sandbox/linux/services/thread_helpers.h"
27 const char kSynchronisationChar
[] = "D";
37 ScopedProcess::ScopedProcess(const base::Closure
& child_callback
)
38 : child_process_id_(-1), process_id_(getpid()) {
39 PCHECK(0 == pipe(pipe_fds_
));
40 #if !defined(THREAD_SANITIZER)
41 // Make sure that we can safely fork().
42 CHECK(ThreadHelpers::IsSingleThreaded());
44 child_process_id_
= fork();
45 PCHECK(0 <= child_process_id_
);
47 if (0 == child_process_id_
) {
48 PCHECK(0 == IGNORE_EINTR(close(pipe_fds_
[0])));
51 // Notify the parent that the closure has run.
52 CHECK_EQ(1, HANDLE_EINTR(write(pipe_fds_
[1], kSynchronisationChar
, 1)));
58 PCHECK(0 == IGNORE_EINTR(close(pipe_fds_
[1])));
62 ScopedProcess::~ScopedProcess() {
63 CHECK(IsOriginalProcess());
64 if (child_process_id_
>= 0) {
65 PCHECK(0 == kill(child_process_id_
, SIGKILL
));
66 siginfo_t process_info
;
68 PCHECK(0 == HANDLE_EINTR(
69 waitid(P_PID
, child_process_id_
, &process_info
, WEXITED
)));
71 if (pipe_fds_
[0] >= 0) {
72 PCHECK(0 == IGNORE_EINTR(close(pipe_fds_
[0])));
74 if (pipe_fds_
[1] >= 0) {
75 PCHECK(0 == IGNORE_EINTR(close(pipe_fds_
[1])));
79 int ScopedProcess::WaitForExit(bool* got_signaled
) {
81 CHECK(IsOriginalProcess());
82 siginfo_t process_info
;
83 // WNOWAIT to make sure that the destructor can wait on the child.
84 int ret
= HANDLE_EINTR(
85 waitid(P_PID
, child_process_id_
, &process_info
, WEXITED
| WNOWAIT
));
86 PCHECK(0 == ret
) << "Did something else wait on the child?";
88 if (process_info
.si_code
== CLD_EXITED
) {
89 *got_signaled
= false;
90 } else if (process_info
.si_code
== CLD_KILLED
||
91 process_info
.si_code
== CLD_DUMPED
) {
94 CHECK(false) << "ScopedProcess needs to be extended for si_code "
95 << process_info
.si_code
;
97 return process_info
.si_status
;
100 bool ScopedProcess::WaitForClosureToRun() {
102 int ret
= HANDLE_EINTR(read(pipe_fds_
[0], &c
, 1));
107 CHECK_EQ(c
, kSynchronisationChar
[0]);
111 // It would be problematic if after a fork(), another process would start using
113 // This method allows to assert it is not happening.
114 bool ScopedProcess::IsOriginalProcess() {
115 // Make a direct syscall to bypass glibc caching of PIDs.
116 pid_t pid
= sys_getpid();
117 return pid
== process_id_
;
120 } // namespace sandbox