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/socket.h>
22#include <sys/types.h>
23#include <sys/wait.h>
24#include <unistd.h>
25
26#include <android-base/chrono_utils.h>
27#include <android-base/logging.h>
28#include <android-base/scopeguard.h>
29#include <android-base/stringprintf.h>
30
31#include "init.h"
32#include "property_service.h"
33#include "service.h"
34
35using android::base::StringPrintf;
36using android::base::boot_clock;
37using android::base::make_scope_guard;
38
39namespace android {
40namespace init {
41
42static int signal_write_fd = -1;
43static int signal_read_fd = -1;
44
45static bool ReapOneProcess() {
46    siginfo_t siginfo = {};
47    // This returns a zombie pid or informs us that there are no zombies left to be reaped.
48    // It does NOT reap the pid; that is done below.
49    if (TEMP_FAILURE_RETRY(waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG | WNOWAIT)) != 0) {
50        PLOG(ERROR) << "waitid failed";
51        return false;
52    }
53
54    auto pid = siginfo.si_pid;
55    if (pid == 0) return false;
56
57    // At this point we know we have a zombie pid, so we use this scopeguard to reap the pid
58    // whenever the function returns from this point forward.
59    // We do NOT want to reap the zombie earlier as in Service::Reap(), we kill(-pid, ...) and we
60    // want the pid to remain valid throughout that (and potentially future) usages.
61    auto reaper = make_scope_guard([pid] { TEMP_FAILURE_RETRY(waitpid(pid, nullptr, WNOHANG)); });
62
63    std::string name;
64    std::string wait_string;
65    Service* service = nullptr;
66
67    if (PropertyChildReap(pid)) {
68        name = "Async property child";
69    } else if (SubcontextChildReap(pid)) {
70        name = "Subcontext";
71    } else {
72        service = ServiceList::GetInstance().FindService(pid, &Service::pid);
73
74        if (service) {
75            name = StringPrintf("Service '%s' (pid %d)", service->name().c_str(), pid);
76            if (service->flags() & SVC_EXEC) {
77                auto exec_duration = boot_clock::now() - service->time_started();
78                auto exec_duration_ms =
79                    std::chrono::duration_cast<std::chrono::milliseconds>(exec_duration).count();
80                wait_string = StringPrintf(" waiting took %f seconds", exec_duration_ms / 1000.0f);
81            }
82        } else {
83            name = StringPrintf("Untracked pid %d", pid);
84        }
85    }
86
87    if (siginfo.si_code == CLD_EXITED) {
88        LOG(INFO) << name << " exited with status " << siginfo.si_status << wait_string;
89    } else {
90        LOG(INFO) << name << " received signal " << siginfo.si_status << wait_string;
91    }
92
93    if (!service) return true;
94
95    service->Reap(siginfo);
96
97    if (service->flags() & SVC_TEMPORARY) {
98        ServiceList::GetInstance().RemoveService(*service);
99    }
100
101    return true;
102}
103
104static void handle_signal() {
105    // Clear outstanding requests.
106    char buf[32];
107    read(signal_read_fd, buf, sizeof(buf));
108
109    ReapAnyOutstandingChildren();
110}
111
112static void SIGCHLD_handler(int) {
113    if (TEMP_FAILURE_RETRY(write(signal_write_fd, "1", 1)) == -1) {
114        PLOG(ERROR) << "write(signal_write_fd) failed";
115    }
116}
117
118void ReapAnyOutstandingChildren() {
119    while (ReapOneProcess()) {
120    }
121}
122
123void sigchld_handler_init() {
124    // Create a signalling mechanism for SIGCHLD.
125    int s[2];
126    if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, s) == -1) {
127        PLOG(FATAL) << "socketpair failed in sigchld_handler_init";
128    }
129
130    signal_write_fd = s[0];
131    signal_read_fd = s[1];
132
133    // Write to signal_write_fd if we catch SIGCHLD.
134    struct sigaction act;
135    memset(&act, 0, sizeof(act));
136    act.sa_handler = SIGCHLD_handler;
137    act.sa_flags = SA_NOCLDSTOP;
138    sigaction(SIGCHLD, &act, 0);
139
140    ReapAnyOutstandingChildren();
141
142    register_epoll_handler(signal_read_fd, handle_signal);
143}
144
145}  // namespace init
146}  // namespace android
147