+/yash

git clone https://git.julia.blue/+/yash

Joseph RyanSubmission4587801

master
12.4 KiB416 linesraw
1#include <assert.h>
2#include <ctype.h>
3#include <setjmp.h>
4#include <signal.h>
5#include <stdbool.h>
6#include <stdint.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <stdnoreturn.h>
10#include <string.h>
11
12#include <fcntl.h>
13#include <readline/history.h>
14#include <readline/readline.h>
15#include <sys/stat.h>
16#include <sys/wait.h>
17#include <unistd.h>
18
19#define MAX_JOBS 32
20#define MAX_ARGS 1024
21#define DEBUG_ENABLE false
22#define DEBUG(format, args...)                                                 \
23    if (DEBUG_ENABLE)                                                          \
24    printf(format, ##args)
25
26#include <stdarg.h>
27
28typedef struct {
29    char* command;
30    pid_t group_id;
31    pid_t pipe_id;
32    bool running;
33    int8_t number;
34    int8_t next;
35    int8_t prev;
36    bool occupied;
37    bool main_exited;
38    bool do_pipe;
39    bool pipe_exited;
40} Job;
41
42static volatile Job jobs[MAX_JOBS];
43
44static sigjmp_buf jump_buf;
45static volatile sig_atomic_t first_job = -1;
46static volatile sig_atomic_t recent_job = -1;
47static volatile sig_atomic_t foreground_job = -1;
48
49static void push_job(int j) {
50    if (recent_job == -1) {
51        first_job = j;
52    } else {
53        jobs[recent_job].next = (int8_t)j;
54    }
55    jobs[j].prev = (int8_t)recent_job;
56    jobs[j].next = -1;
57    recent_job = j;
58}
59
60static void remove_job(int j) {
61    if (jobs[j].prev != -1) {
62        jobs[jobs[j].prev].next = jobs[j].next;
63    } else {
64        assert(first_job == j);
65        first_job = jobs[j].next;
66    }
67    if (jobs[j].next != -1) {
68        jobs[jobs[j].next].prev = jobs[j].prev;
69    } else {
70        assert(recent_job == j);
71        recent_job = jobs[j].prev;
72    }
73}
74
75static void handle_finished_jobs() {
76    DEBUG("going through finished stuff\n");
77    for (int i = 0; i < MAX_JOBS; ++i) {
78        if (jobs[i].occupied && jobs[i].main_exited && jobs[i].pipe_exited) {
79            printf("[%d]+  %-20s %s &\n", jobs[i].number, "Done",
80                   jobs[i].command);
81            free(jobs[i].command);
82            jobs[i].occupied = false;
83        }
84    }
85}
86
87static int max(int a, int b) {
88    return a > b ? a : b;
89}
90
91static char* next_token(char** line_ptr) {
92    char* line = *line_ptr;
93    while (*line && isspace(*line)) { ++line; }
94    if (!*line) {
95        return NULL;
96    }
97    char* start = line;
98    char c = *line;
99    if (c == '|' || c == '<' || c == '>' || c == '&') {
100        *line_ptr = line + 1;
101        return strndup(start, 1);
102    } else if (c == '2' && *(line + 1) == '>') {
103        *line_ptr = line + 2;
104        return strndup(start, 2);
105    }
106    do {
107        c = *++line;
108    } while (c && !isspace(c) && c != '|' && c != '<' && c != '>' && c != '&');
109    *line_ptr = line;
110    return strndup(start, (size_t)(line - start));
111}
112
113static char* main_args[MAX_ARGS];
114static char* pipe_args[MAX_ARGS];
115static int main_redir_in, main_redir_out, main_redir_err;
116static int pipe_redir_in, pipe_redir_out, pipe_redir_err;
117static pid_t main_pid;
118static pid_t pipe_pid;
119static bool launch_bg;
120static bool do_pipe;
121
122static bool parse_line(char* line, bool after_pipe) {
123    do_pipe = false;
124    launch_bg = false;
125    size_t arg_num = 0;
126    int redir_in = -1, redir_out = -1, redir_err = -1;
127    char** args = after_pipe ? pipe_args : main_args;
128    for (int i = 0; args[i]; ++i) { free(args[i]); }
129    char* current;
130    while ((current = next_token(&line))) {
131        if (!strcmp("<", current)) {
132            if (!(current = next_token(&line))) {
133                DEBUG("No file passed for redirection\n");
134                return false;
135            }
136            if ((redir_in = open(current, O_RDONLY)) == -1) {
137                printf("yash: %s: No such file or directory\n", current);
138                return false;
139            }
140        } else if (!strcmp(">", current)) {
141            if (!(current = next_token(&line))) {
142                DEBUG("No file passed for redirection\n");
143            }
144            (redir_out = open(current, O_CREAT | O_WRONLY,
145                              S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH));
146        } else if (!strcmp("2>", current)) {
147            if (!(current = next_token(&line))) {
148                DEBUG("No file passed for redirection\n");
149                return false;
150            }
151            redir_err = open(current, O_CREAT | O_WRONLY,
152                             S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
153        } else if (!strcmp("|", current)) {
154            if (!parse_line(line, true)) {
155                DEBUG("Error parsing pipe command\n");
156            }
157            do_pipe = true;
158            break;
159        } else if (!strcmp("&", current)) {
160            launch_bg = true;
161            break;
162        } else {
163            args[arg_num++] = current;
164        }
165    }
166    if (after_pipe) {
167        pipe_redir_err = redir_err;
168        pipe_redir_in = redir_in;
169        pipe_redir_out = redir_out;
170    } else {
171        main_redir_err = redir_err;
172        main_redir_in = redir_in;
173        main_redir_out = redir_out;
174    }
175    args[arg_num] = 0;
176    return true;
177}
178
179static void line(char* orig) {
180    char* line = orig;
181    if (!line) {
182        for (int i = first_job; i != -1; i = jobs[i].next) {
183            if (jobs[i].occupied) {
184                kill(-jobs[i].group_id, SIGKILL);
185            }
186        }
187        exit(0);
188    }
189    add_history(line);
190
191    char* command = next_token(&line);
192    if (!command) {
193        return;
194    } else if (!strcmp("fg", command)) {
195        if (recent_job != -1) {
196            foreground_job = recent_job;
197            puts(jobs[recent_job].command);
198            kill(-jobs[recent_job].group_id, SIGCONT);
199            remove_job(recent_job);
200        }
201        return;
202    } else if (!strcmp("bg", command)) {
203        int i = recent_job;
204        while (i != -1 && jobs[i].running) { i = jobs[i].prev; }
205        if (i != -1) {
206            jobs[i].running = true;
207            printf("[%d]+ %s &\n", jobs[i].number, jobs[i].command);
208            DEBUG("Sending SIGCONT to %d\n", jobs[i].group_id);
209            kill(-jobs[i].group_id, SIGCONT);
210        }
211        return;
212    } else if (!strcmp("jobs", command)) {
213        int i = first_job;
214        while (i != -1) {
215            printf("[%d]%c  %-20s %s%s\n", jobs[i].number,
216                   i == recent_job ? '+' : '-',
217                   jobs[i].running ? "Running" : "Stopped", jobs[i].command,
218                   jobs[i].running ? " &" : "");
219            i = jobs[i].next;
220        }
221        return;
222    }
223
224    if (!parse_line(orig, false)) {
225        return;
226    }
227    if (launch_bg) { // strip & and resulting trailing whitespace
228        char* end = strchr(orig, '&');
229        if (end) {
230            --end;
231            while (isspace(*end)) { --end; }
232            *++end = (char)'\0';
233        }
234    }
235
236    int pipe_ends[2];
237    if (do_pipe) {
238        pipe(pipe_ends);
239    }
240
241    if ((main_pid = fork())) {
242        if (do_pipe) {
243            if (!(pipe_pid = fork())) {
244                setpgid(0, main_pid);
245                signal(SIGINT, SIG_DFL);
246                signal(SIGTSTP, SIG_DFL);
247                signal(SIGCHLD, SIG_DFL);
248                dup2(pipe_ends[0], 0);
249                close(pipe_ends[1]);
250                if (pipe_redir_in != -1) {
251                    dup2(pipe_redir_in, 0);
252                }
253                if (pipe_redir_out != -1) {
254                    dup2(pipe_redir_out, 1);
255                }
256                if (pipe_redir_err != -1) {
257                    dup2(pipe_redir_err, 2);
258                }
259                if (execvp(pipe_args[0], pipe_args) == -1) {
260                    DEBUG("Error calling exec for pipe\n");
261                    exit(1);
262                }
263            }
264            close(pipe_ends[0]);
265            close(pipe_ends[1]);
266        }
267    } else {
268        setpgid(0, 0);
269        signal(SIGINT, SIG_DFL);
270        signal(SIGTSTP, SIG_DFL);
271        signal(SIGCHLD, SIG_DFL);
272        if (do_pipe) {
273            dup2(pipe_ends[1], 1);
274            close(pipe_ends[0]);
275        }
276        if (main_redir_in != -1) {
277            dup2(main_redir_in, 0);
278        }
279        if (main_redir_out != -1) {
280            dup2(main_redir_out, 1);
281        }
282        if (main_redir_err != -1) {
283            dup2(main_redir_err, 2);
284        }
285        if (execvp(main_args[0], main_args) == -1) {
286            DEBUG("Error calling exec\n");
287            exit(1);
288        }
289    }
290
291    int i;
292    for (i = 0; i < MAX_JOBS; ++i) {
293        if (!jobs[i].occupied) {
294            break;
295        }
296    }
297    jobs[i].occupied = true;
298    jobs[i].pipe_id = do_pipe ? pipe_pid : -1;
299    jobs[i].group_id = main_pid;
300    jobs[i].command = strdup(orig);
301    jobs[i].running = true;
302    jobs[i].running = true;
303    jobs[i].main_exited = false;
304    jobs[i].pipe_exited = !do_pipe;
305    int8_t biggest = 0;
306    int temp = first_job;
307    while (temp != -1) {
308        biggest = (int8_t)max(jobs[temp].number, biggest);
309        temp = jobs[temp].next;
310    }
311    jobs[i].number = biggest + 1;
312    if (launch_bg) {
313        push_job(i);
314    } else {
315        foreground_job = i;
316    }
317    DEBUG("Launching %d (%d) as job #%d\n", main_pid, pipe_pid, jobs[i].number);
318}
319
320static void handle_sigint(int sig) {
321    assert(sig == SIGINT);
322    if (foreground_job != -1) {
323        kill(-jobs[foreground_job].group_id, SIGINT);
324        jobs[foreground_job].occupied = false;
325        foreground_job = -1;
326        DEBUG("\nexited\n");
327    } else {
328        siglongjmp(jump_buf, 0);
329    }
330}
331
332static void handle_sigtstp(int sig) {
333    assert(sig == SIGTSTP);
334    if (foreground_job != -1) {
335        kill(-jobs[foreground_job].group_id, SIGTSTP);
336        jobs[foreground_job].running = false;
337        push_job(foreground_job);
338        foreground_job = -1;
339        return;
340    }
341    DEBUG("Attempted to stop shell process\n");
342}
343
344static void handle_sigchld(int sig) {
345    assert(sig == SIGCHLD);
346    pid_t pid;
347    int status;
348    while ((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) != -1) {
349        if (pid == 0) {
350            return;
351        }
352        if (WIFEXITED(status) || WIFSIGNALED(status)) {
353            DEBUG("Exited: %d(%d) %d(%d)\n", WIFEXITED(status),
354                  WEXITSTATUS(status), WIFSIGNALED(status), WTERMSIG(status));
355            if (jobs[foreground_job].group_id == pid) {
356                jobs[foreground_job].main_exited = true;
357                if (jobs[foreground_job].pipe_exited) {
358                    jobs[foreground_job].occupied = false;
359                    DEBUG("Removing foreground: %s\n",
360                          jobs[foreground_job].command);
361                    free(jobs[foreground_job].command);
362                    foreground_job = -1;
363                }
364            } else if (jobs[foreground_job].pipe_id == pid) {
365                jobs[foreground_job].pipe_exited = true;
366                if (jobs[foreground_job].main_exited) {
367                    jobs[foreground_job].occupied = false;
368                    DEBUG("Removing foreground: %s\n",
369                          jobs[foreground_job].command);
370                    free(jobs[foreground_job].command);
371                    foreground_job = -1;
372                }
373            } else {
374                for (int i = first_job; i != -1; i = jobs[i].next) {
375                    if (jobs[i].group_id == pid) {
376                        jobs[i].main_exited = true;
377                        if (jobs[i].pipe_exited) {
378                            DEBUG("Removing %d\n", jobs[i].number);
379                            remove_job(i);
380                        }
381                    } else if (!jobs[i].pipe_exited && jobs[i].pipe_id == pid) {
382                        jobs[i].pipe_exited = true;
383                        if (jobs[i].main_exited) {
384                            DEBUG("Removing %d\n", jobs[i].number);
385                            remove_job(i);
386                        }
387                    }
388                }
389            }
390        } else if (WIFSTOPPED(status)) {
391            DEBUG("stopped\n");
392        } else {
393            DEBUG("ERROR unexpected wait status\n");
394        }
395        DEBUG("PID: %d, status: %d\n", pid, status);
396    }
397}
398
399int main() {
400    signal(SIGINT, handle_sigint);
401    signal(SIGTSTP, handle_sigtstp);
402    signal(SIGCHLD, handle_sigchld);
403    for (int i = 0; i < MAX_JOBS; ++i) { jobs[i].occupied = false; }
404    while (true) {
405        // SIGINT during readline prints a new prompt
406        while (sigsetjmp(jump_buf, true)) { putchar('\n'); }
407        char* raw_input = readline("# ");
408        handle_finished_jobs();
409        line(raw_input);
410        free(raw_input);
411        while (foreground_job != -1) {
412            DEBUG("pausing...\n");
413            pause();
414        }
415    }
416}