-
Notifications
You must be signed in to change notification settings - Fork 9
/
init.c
102 lines (86 loc) · 2.19 KB
/
init.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* Copyright © 2020 Arista Networks, Inc. All rights reserved.
*
* Use of this source code is governed by the MIT license that can be found
* in the LICENSE file.
*/
#include <err.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <unistd.h>
#include "sig.h"
int main(int argc, char *argv[], char *envp[])
{
if (argc == 1) {
printf("usage: %s <program> [args...]\n", argv[0]);
return 2;
}
if (prctl(PR_SET_NAME, "bst-init") == -1) {
err(1, "prctl(PR_SET_NAME)");
}
sigset_t mask;
sigfillset(&mask);
if (sigprocmask(SIG_SETMASK, &mask, NULL) == -1) {
err(1, "sigprocmask");
}
pid_t main_child_pid = fork();
if (main_child_pid == -1) {
err(1, "fork");
}
if (!main_child_pid) {
sigemptyset(&mask);
if (sigprocmask(SIG_SETMASK, &mask, NULL) == -1) {
err(1, "sigprocmask");
}
execvpe(argv[1], argv + 1, envp);
err(1, "execvpe %s", argv[1]);
}
for (;;) {
siginfo_t info;
sig_wait(&mask, &info);
sig_forward(&info, main_child_pid);
if (info.si_signo != SIGCHLD) {
continue;
}
int rc;
while ((rc = waitid(P_ALL, 0, &info, WEXITED | WNOHANG)) != -1) {
if (info.si_signo != SIGCHLD) {
break;
}
switch (info.si_code) {
case CLD_EXITED:
case CLD_KILLED:
case CLD_DUMPED:
if (info.si_pid == main_child_pid) {
/* the main child died -- rather that trying to collect the rest,
just abort init, and the kernel will sweep the rest. */
if (info.si_code == CLD_EXITED) {
return info.si_status;
} else {
return info.si_status | 1 << 7;
}
}
break;
case CLD_TRAPPED:
/*
* Empirically, if a traced process's parent exits, the
* init process inherits the tracing of that process.
* If we notice an inherited child has stopped without
* explicitly asking for that notification, detach from
* it, forwarding the stopping signal in the status.
*/
if (ptrace(PTRACE_DETACH, info.si_pid, 0, info.si_status) == -1) {
warn("failed to detach from traced child %d, "
"status %d", info.si_pid, info.si_status);
}
break;
}
}
if (rc == -1) {
err(1, "waitid");
}
}
}