fork/fish-shell

git clone https://git.julia.blue/fork/fish-shell

Johannes Altmanningerclang-format fish_test_helper3c4243fdd

master
8.8 KiB284 linesraw
1// fish_test_helper is a little program with no fish dependencies that acts like certain other
2// programs, allowing fish to test its behavior.
3
4#include <fcntl.h>
5#include <signal.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <sys/wait.h>
11#include <unistd.h>
12
13static void abandon_tty() {
14    // The parent may get SIGSTOPed when it tries to call tcsetpgrp if the child has already done
15    // it. Prevent this by ignoring signals.
16    signal(SIGTTIN, SIG_IGN);
17    signal(SIGTTOU, SIG_IGN);
18    pid_t pid = fork();
19    if (pid < 0) {
20        perror("fork");
21        exit(EXIT_FAILURE);
22    }
23    // Both parent and child do the same thing.
24    pid_t child = pid ? pid : getpid();
25    if (setpgid(child, child)) {
26        perror("setpgid");
27        exit(EXIT_FAILURE);
28    }
29    // tcsetpgrp may fail in the parent if the child has already exited.
30    // This is the benign race.
31    (void)tcsetpgrp(STDIN_FILENO, child);
32    // Parent waits for child to exit.
33    if (pid > 0) {
34        waitpid(child, NULL, 0);
35    }
36}
37
38static void become_foreground_then_print_stderr() {
39    if (tcsetpgrp(STDOUT_FILENO, getpgrp()) < 0) {
40        perror("tcsetgrp");
41        exit(EXIT_FAILURE);
42    }
43    usleep(1000000 / 4);  //.25 secs
44    fprintf(stderr, "become_foreground_then_print_stderr done\n");
45}
46
47static void nohup_wait() {
48    pid_t init_parent = getppid();
49    if (signal(SIGHUP, SIG_IGN)) {
50        perror("tcsetgrp");
51        exit(EXIT_FAILURE);
52    }
53    // Note: these silly close() calls are necessary to prevent our parent process (presumably fish)
54    // from getting stuck in the "E" state ("Trying to exit"). This appears to be a (kernel?) bug on
55    // macOS: the process is no longer running but is not a zombie either, and so cannot be reaped.
56    // It is unclear why closing these fds successfully works around this issue.
57    close(STDIN_FILENO);
58    close(STDOUT_FILENO);
59    close(STDERR_FILENO);
60    // To avoid leaving fish_test_helpers around, we exit once our parent changes, meaning the fish
61    // instance exited.
62    while (getppid() == init_parent) {
63        usleep(1000000 / 4);
64    }
65}
66
67static void report_foreground_loop() {
68    int was_fg = -1;
69    const pid_t grp = getpgrp();
70    for (;;) {
71        int is_fg = (tcgetpgrp(STDIN_FILENO) == grp);
72        if (is_fg != was_fg) {
73            was_fg = is_fg;
74            if (fputs(is_fg ? "foreground\n" : "background\n", stderr) < 0) {
75                return;
76            }
77        }
78        usleep(1000000 / 2);
79    }
80}
81
82static void report_foreground() {
83    bool is_fg = (tcgetpgrp(STDIN_FILENO) == getpgrp());
84    fputs(is_fg ? "foreground\n" : "background\n", stderr);
85}
86
87static void sigint_parent() {
88    // SIGINT the parent after a time, then exit
89    int parent = getppid();
90    usleep(1000000 / 4);  //.25 secs
91    kill(parent, SIGINT);
92    fprintf(stderr, "Sent SIGINT to %d\n", parent);
93}
94
95static void print_stdout_stderr() {
96    fprintf(stdout, "stdout\n");
97    fprintf(stderr, "stderr\n");
98    fflush(NULL);
99}
100
101static void print_pid_then_sleep() {
102    // On some systems getpid is a long, on others it's an int, let's just cast it.
103    fprintf(stdout, "%ld\n", (long)getpid());
104    fflush(NULL);
105    usleep(1000000 / 2);  //.5 secs
106}
107
108static void print_pgrp() { fprintf(stdout, "%ld\n", (long)getpgrp()); }
109
110static void print_fds() {
111    bool needs_space = false;
112    for (int fd = 0; fd <= 100; fd++) {
113        if (fcntl(fd, F_GETFD) >= 0) {
114            fprintf(stdout, "%s%d", needs_space ? " " : "", fd);
115            needs_space = true;
116        }
117    }
118    fputc('\n', stdout);
119}
120
121static void print_signal(int sig) {
122    // Print a signal description to stderr.
123    const char *s = strsignal(sig);
124    if (s) {
125        fprintf(stderr, "%s", s);
126        if (strchr(s, ':') == NULL) {
127            fprintf(stderr, ": %d", sig);
128        }
129        fprintf(stderr, "\n");
130    }
131}
132
133static void print_blocked_signals() {
134    sigset_t sigs;
135    sigemptyset(&sigs);
136    if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
137        perror("sigprocmask");
138        exit(EXIT_FAILURE);
139    }
140    // There is no obviously portable way to get the maximum number of signals.
141    // POSIX says sigqueue(2) can be used with signo 0 to validate the pid and signo parameters,
142    // but it is missing from OpenBSD and returns ENOSYS (not implemented) under WSL.
143    // Here we limit it to 32 because strsignal on OpenBSD returns "Unknown signal" for anything
144    // above, while NetBSD taps out at 63, and Linux at 64.
145    for (int sig = 1; sig < 33; sig++) {
146        if (sigismember(&sigs, sig)) {
147            print_signal(sig);
148        }
149    }
150}
151
152static void print_ignored_signals() {
153    for (int sig = 1; sig < 33; sig++) {
154        struct sigaction act = {};
155        sigaction(sig, NULL, &act);
156        if (act.sa_handler == SIG_IGN) {
157            print_signal(sig);
158        }
159    }
160}
161
162static void sigtstp_handler(int x) {
163    (void)!write(STDOUT_FILENO, "SIGTSTP\n", strlen("SIGTSTP\n"));
164    kill(getpid(), SIGSTOP);
165}
166static void sigcont_handler(int x) {
167    (void)!write(STDOUT_FILENO, "SIGCONT\n", strlen("SIGCONT\n"));
168}
169static void print_stop_cont() {
170    signal(SIGTSTP, &sigtstp_handler);
171    signal(SIGCONT, &sigcont_handler);
172    char buff[1];
173    for (;;) {
174        if (read(STDIN_FILENO, buff, sizeof buff) >= 0) {
175            exit(0);
176        }
177    }
178}
179
180static void sigkill_self() {
181    kill(getpid(), SIGKILL);
182    usleep(20000000);  // 20 secs
183    abort();
184}
185
186static void sigint_self() {
187    kill(getpid(), SIGINT);
188    usleep(20000000);  // 20 secs
189    abort();
190}
191
192static void do_nothing(int x) {}
193static void stdin_make_nonblocking() {
194    const int fd = STDIN_FILENO;
195    // Catch SIGCONT so pause() wakes us up.
196    signal(SIGCONT, &do_nothing);
197
198    for (;;) {
199        int flags = fcntl(fd, F_GETFL, 0);
200        fprintf(stdout, "stdin was %sblocking\n", (flags & O_NONBLOCK) ? "non" : "");
201        if (fcntl(fd, F_SETFL, flags | O_NONBLOCK)) {
202            perror("fcntl");
203            exit(EXIT_FAILURE);
204        }
205        pause();
206    }
207}
208
209static void show_help();
210
211/// A thing that fish_test_helper can do.
212typedef struct {
213    /// The argument to match against.
214    const char *arg;
215
216    /// Function to invoke.
217    void (*func)();
218
219    /// Description of what this does.
220    const char *desc;
221} fth_command_t;
222
223static fth_command_t s_commands[] = {
224    {"abandon_tty", abandon_tty, "Create a new pgroup and transfer tty ownership to it"},
225    {"become_foreground_then_print_stderr", become_foreground_then_print_stderr,
226     "Claim the terminal (tcsetpgrp) and then print to stderr"},
227    {"nohup_wait", nohup_wait, "Ignore SIGHUP and just wait"},
228    {"report_foreground", report_foreground, "Report to stderr whether we own the terminal"},
229    {"report_foreground_loop", report_foreground_loop,
230     "Continually report to stderr whether we own the terminal"},
231    {"sigint_parent", sigint_parent, "Wait .25 seconds, then SIGINT the parent process"},
232    {"print_stdout_stderr", print_stdout_stderr, "Print 'stdout' to stdout and 'stderr' to stderr"},
233    {"print_pid_then_sleep", print_pid_then_sleep, "Print our pid, then sleep for .5 seconds"},
234    {"print_pgrp", print_pgrp, "Print our pgroup to stdout"},
235    {"print_fds", print_fds, "Print the list of active FDs to stdout"},
236    {"print_blocked_signals", print_blocked_signals,
237     "Print to stdout the name(s) of blocked signals"},
238    {"print_ignored_signals", print_ignored_signals,
239     "Print to stdout the name(s) of ignored signals"},
240    {"print_stop_cont", print_stop_cont, "Print when we get SIGTSTP and SIGCONT, exiting on input"},
241    {"sigint_self", sigint_self, "Send SIGINT to self"},
242    {"sigkill_self", sigkill_self, "Send SIGKILL to self"},
243    {"stdin_make_nonblocking", stdin_make_nonblocking,
244     "Print if stdin is blocking and then make it nonblocking"},
245    {"help", show_help, "Print list of fish_test_helper commands"},
246    {NULL, NULL, NULL},
247};
248
249static void show_help() {
250    printf("fish_test_helper: helper utility for fish\n\n");
251    printf("Commands\n");
252    printf("--------\n");
253    for (int i = 0; s_commands[i].arg; i++) {
254        printf("  %s:\n    %s\n\n", s_commands[i].arg, s_commands[i].desc);
255    }
256}
257
258int main(int argc, char *argv[]) {
259    if (argc <= 1) {
260        fprintf(stderr, "No commands given.\n");
261        return 0;
262    }
263    for (int i = 1; i < argc; i++) {
264        if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "help") || !strcmp(argv[i], "-h")) {
265            show_help();
266            return 0;
267        }
268
269        const fth_command_t *found = NULL;
270        for (int j = 0; s_commands[j].arg; j++) {
271            if (!strcmp(argv[i], s_commands[j].arg)) {
272                found = &s_commands[j];
273                break;
274            }
275        }
276        if (found) {
277            found->func();
278        } else {
279            fprintf(stderr, "%s: Unknown command: %s\n", argv[0], argv[i]);
280            return EXIT_FAILURE;
281        }
282    }
283    return 0;
284}