xref: /aosp_15_r20/system/core/init/sigchld_handler.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "sigchld_handler.h"
18 
19 #include <signal.h>
20 #include <string.h>
21 #include <sys/signalfd.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26 
27 #include <android-base/chrono_utils.h>
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/scopeguard.h>
31 #include <android-base/stringprintf.h>
32 
33 #include <thread>
34 
35 #include "epoll.h"
36 #include "init.h"
37 #include "service.h"
38 #include "service_list.h"
39 
40 using android::base::boot_clock;
41 using android::base::make_scope_guard;
42 using android::base::ReadFileToString;
43 using android::base::StringPrintf;
44 using android::base::Timer;
45 
46 namespace android {
47 namespace init {
48 
ReapOneProcess()49 static pid_t ReapOneProcess() {
50     siginfo_t siginfo = {};
51     // This returns a zombie pid or informs us that there are no zombies left to be reaped.
52     // It does NOT reap the pid; that is done below.
53     if (TEMP_FAILURE_RETRY(waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG | WNOWAIT)) != 0) {
54         PLOG(ERROR) << "waitid failed";
55         return 0;
56     }
57 
58     const pid_t pid = siginfo.si_pid;
59     if (pid == 0) {
60         DCHECK_EQ(siginfo.si_signo, 0);
61         return 0;
62     }
63 
64     DCHECK_EQ(siginfo.si_signo, SIGCHLD);
65 
66     // At this point we know we have a zombie pid, so we use this scopeguard to reap the pid
67     // whenever the function returns from this point forward.
68     // We do NOT want to reap the zombie earlier as in Service::Reap(), we kill(-pid, ...) and we
69     // want the pid to remain valid throughout that (and potentially future) usages.
70     auto reaper = make_scope_guard([pid] { TEMP_FAILURE_RETRY(waitpid(pid, nullptr, WNOHANG)); });
71 
72     std::string name;
73     std::string wait_string;
74     Service* service = nullptr;
75 
76     if (SubcontextChildReap(pid)) {
77         name = "Subcontext";
78     } else {
79         service = ServiceList::GetInstance().FindService(pid, &Service::pid);
80 
81         if (service) {
82             name = StringPrintf("Service '%s' (pid %d)", service->name().c_str(), pid);
83             if (service->flags() & SVC_EXEC) {
84                 auto exec_duration = boot_clock::now() - service->time_started();
85                 auto exec_duration_ms =
86                     std::chrono::duration_cast<std::chrono::milliseconds>(exec_duration).count();
87                 wait_string = StringPrintf(" waiting took %f seconds", exec_duration_ms / 1000.0f);
88             } else if (service->flags() & SVC_ONESHOT) {
89                 auto exec_duration = boot_clock::now() - service->time_started();
90                 auto exec_duration_ms =
91                         std::chrono::duration_cast<std::chrono::milliseconds>(exec_duration)
92                                 .count();
93                 wait_string = StringPrintf(" oneshot service took %f seconds in background",
94                                            exec_duration_ms / 1000.0f);
95             }
96         } else {
97             name = StringPrintf("Untracked pid %d", pid);
98         }
99     }
100 
101     if (siginfo.si_code == CLD_EXITED) {
102         LOG(INFO) << name << " exited with status " << siginfo.si_status << wait_string;
103     } else {
104         LOG(INFO) << name << " received signal " << siginfo.si_status << wait_string;
105     }
106 
107     if (!service) {
108         LOG(INFO) << name << " did not have an associated service entry and will not be reaped";
109         return pid;
110     }
111 
112     service->Reap(siginfo);
113 
114     if (service->flags() & SVC_TEMPORARY) {
115         ServiceList::GetInstance().RemoveService(*service);
116     }
117 
118     return pid;
119 }
120 
ReapAnyOutstandingChildren()121 std::set<pid_t> ReapAnyOutstandingChildren() {
122     std::set<pid_t> reaped_pids;
123     for (;;) {
124         const pid_t pid = ReapOneProcess();
125         if (pid <= 0) {
126             return reaped_pids;
127         }
128         reaped_pids.emplace(pid);
129     }
130 }
131 
ReapAndRemove(std::vector<pid_t> & alive_pids)132 static void ReapAndRemove(std::vector<pid_t>& alive_pids) {
133     for (auto pid : ReapAnyOutstandingChildren()) {
134         const auto it = std::find(alive_pids.begin(), alive_pids.end(), pid);
135         if (it != alive_pids.end()) {
136             alive_pids.erase(it);
137         }
138     }
139 }
140 
HandleSignal(int signal_fd)141 static void HandleSignal(int signal_fd) {
142     signalfd_siginfo siginfo;
143     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));
144     if (bytes_read != sizeof(siginfo)) {
145         LOG(WARNING) << "Unexpected: " << __func__ << " read " << bytes_read << " bytes instead of "
146                      << sizeof(siginfo);
147     }
148 }
149 
WaitToBeReaped(int sigchld_fd,const std::vector<pid_t> & pids,std::chrono::milliseconds timeout)150 void WaitToBeReaped(int sigchld_fd, const std::vector<pid_t>& pids,
151                     std::chrono::milliseconds timeout) {
152     Timer t;
153     Epoll epoll;
154     if (sigchld_fd >= 0) {
155         if (auto result = epoll.Open(); result.ok()) {
156             result =
157                     epoll.RegisterHandler(sigchld_fd, [sigchld_fd]() { HandleSignal(sigchld_fd); });
158             if (!result.ok()) {
159                 LOG(WARNING) << __func__
160                              << " RegisterHandler() failed. Falling back to sleep_for(): "
161                              << result.error();
162                 sigchld_fd = -1;
163             }
164         } else {
165             LOG(WARNING) << __func__ << " Epoll::Open() failed. Falling back to sleep_for(): "
166                          << result.error();
167             sigchld_fd = -1;
168         }
169     }
170     std::vector<pid_t> alive_pids(pids);
171     ReapAndRemove(alive_pids);
172     while (!alive_pids.empty() && t.duration() < timeout) {
173         if (sigchld_fd >= 0) {
174             auto result = epoll.Wait(std::max(timeout - t.duration(), 0ms));
175             if (result.ok()) {
176                 ReapAndRemove(alive_pids);
177                 continue;
178             } else {
179                 LOG(WARNING) << "Epoll::Wait() failed " << result.error();
180             }
181         }
182         std::this_thread::sleep_for(50ms);
183         ReapAndRemove(alive_pids);
184     }
185     LOG(INFO) << "Waiting for " << pids.size() << " pids to be reaped took " << t << " with "
186               << alive_pids.size() << " of them still running";
187     for (pid_t pid : alive_pids) {
188         std::string status = "(no-such-pid)";
189         ReadFileToString(StringPrintf("/proc/%d/status", pid), &status);
190         LOG(INFO) << "Still running: " << pid << '\n' << status;
191     }
192 }
193 
194 }  // namespace init
195 }  // namespace android
196