summaryrefslogtreecommitdiff
path: root/exec.c
blob: 318638e206300952f9435339cc7e65eebc75df09 (plain)
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/wait.h>

#include "utils.h"
#include "exec.h"
#include "preproc.h"


char* get_var(char* varname, ShellState* shstate) {
    MaybeStr maybe_varval = get_map_value(&shstate->shell_vars, varname); 
    if (maybe_varval.some == true) return maybe_varval.value;
    return getenv(varname);
}

typedef struct {
    QuotationMode qmode;  
    char* content;
} ExpandedChunk;


ExpandedChunk expand_chunk(Chunk chunk, ShellState* shstate) {
    char* content;
    if (chunk.qmode == SINGLE_Q || chunk.kind == LITERAL) {
        if (chunk.qmode == SINGLE_Q && chunk.kind != LITERAL) exit(69);
        content = chunk.as.literal_str;
    } else if (chunk.kind == VAR_EXP) {
        content = get_var(chunk.as.varname, shstate);
    } else if (chunk.kind == REGION_EXP) {
        exit(7); // Not supported yet; arithm
    }
    return (ExpandedChunk){.qmode = chunk.qmode, .content = content};
}


typedef struct {
    StrVec complete_strs;
    String active_str;
} WordSplittingGerm;

void add_expchunk(char* next_str, WordSplittingGerm* curr_res) {
     for (int pos = 0; pos < strlen(next_str); pos++) {
        if (next_str[pos] == ' ') {
            push_to_StrVec(&curr_res->complete_strs, inner(&curr_res->active_str));
            curr_res->active_str = make_String(256);
        } else {
            push_to_String(&curr_res->active_str, next_str[pos]);
        }
    }
}

StrVec expand_word(Word word, ShellState* state) {
    WordSplittingGerm curr_res = {.complete_strs = make_StrVec(256), .active_str = make_String(25)};
    for (int i = 0; i < word.count; i++) {
        Chunk curr_cunk = **get_from_Word(&word, i);
        ExpandedChunk curr_exp = expand_chunk(curr_cunk, state);
        switch (curr_exp.qmode) {
            case UN_Q:
                add_expchunk(curr_exp.content, &curr_res);
                break;
            case SINGLE_Q:
                append_str_to_String(&curr_res.active_str, curr_exp.content);
                break;
            case DOUBLE_Q:
                append_str_to_String(&curr_res.active_str, curr_exp.content);
        }
    }

    if (curr_res.active_str.count > 0) {
        push_to_StrVec(&curr_res.complete_strs, inner(&curr_res.active_str));
    }

    return curr_res.complete_strs;
}


void merge_strvecs(StrVec* target, StrVec* source) {
    for (int i = 0; i < source->count; i++) {
        push_to_StrVec(target, *get_from_StrVec(source, i));
    }
}


char** make_cmd_args(Command command, ShellState* shstate) {
    StrVec arg_str_vec = make_StrVec(256);
    for (int i = 0; i < command.args.count; i++) {
        Token arg_i = *get_from_TokenVec(&command.args, i);
        StrVec expanded_i;
        switch (arg_i.kind) {
            case TOK_WORD:
                expanded_i = expand_word(arg_i.as.word, shstate);
                merge_strvecs(&arg_str_vec, &expanded_i);
                break;
            default:
                exit(67);
        }
    }
    int argcount = arg_str_vec.count;
    char** arg_str_arr = malloc(sizeof(char*) * (argcount + 1));
    for (int j = 0; j < argcount; j++) {
        arg_str_arr[j] = *get_from_StrVec(&arg_str_vec, j);
    }
    arg_str_arr[argcount] = NULL;
    return arg_str_arr;
}



void execute_command(ExecutableCommand cmd, int* pgid) {
    pid_t pid = fork();
    
    if (pid == 0) {
        if (*pgid == -1) {
            setpgid(0, 0);
        } else {
            setpgid(0, *pgid);
        }
        
        dup2(cmd.stdin_fd, STDIN_FILENO);
        dup2(cmd.stdout_fd, STDOUT_FILENO);

        for (int j = 0; j < cmd.redirs.count; j++) {
            FdRedirect fd_rd = *get_from_FdRedirectVec(&cmd.redirs, j);
            dup2(fd_rd.old_fd, fd_rd.new_fd);
        }

        for (int i = 0; i < cmd.child_close_fds.count; i++) {
            close(*get_from_IntVec(&cmd.child_close_fds, i));
        }

        signal(SIGINT,  SIG_DFL);
        signal(SIGQUIT, SIG_DFL);
        signal(SIGTSTP, SIG_DFL);
        signal(SIGTTIN, SIG_DFL);
        signal(SIGTTOU, SIG_DFL);

        execvp(cmd.args[0], cmd.args);
        exit(67);
    }

    if (*pgid == -1) {
        setpgid(pid, pid);
        *pgid = pid;
    } else {
        setpgid(pid, *pgid);
    }
}




void run_pipeline(Pipeline pl, ShellState* shstate) {
    signal(SIGTTIN, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);

    int last_pipe_fd;
    int pgid = -1;
    for (int i = 0; i < pl.count; i++) {
        PipelineElement elem = *get_from_Pipeline(&pl, i);

        ExecutableCommand cmd = {
            .child_close_fds = make_IntVec(64), 
            .parent_close_fds = make_IntVec(64),
            .redirs = make_FdRedirectVec(32)
        };
        cmd.args = make_cmd_args(elem.cmd, shstate);

        if (i == 0) {
            cmd.stdin_fd = STDIN_FILENO;
        } else {
            cmd.stdin_fd = last_pipe_fd;
            push_to_IntVec(&cmd.child_close_fds, last_pipe_fd);
            push_to_IntVec(&cmd.parent_close_fds, last_pipe_fd);
        }

        if (elem.conn == CONN_PIPE) {
            int pipe_fds[2];
            pipe(pipe_fds);
            cmd.stdout_fd = pipe_fds[1];
            push_to_IntVec(&cmd.child_close_fds, pipe_fds[1]);
            push_to_IntVec(&cmd.parent_close_fds, pipe_fds[1]);
            last_pipe_fd = pipe_fds[0];
        } else {
            cmd.stdout_fd = STDOUT_FILENO;
        }

        for (int j = 0; j < elem.cmd.redirects.count; j++) {
            Redirect rd = *get_from_RedirectVec(&elem.cmd.redirects, j);
            switch (rd.kind) {
                case STDIN_REDIR: 
                    /*
                    int in_fd = open(rd.as.std_redir_filename, O_RDONLY, 0644);
                    push_to_FdRedirectVec(&cmd.redirs, (FdRedirect){.old_fd = STDIN_REDIR, .new_fd = in_fd});
                    push_to_IntVec(&cmd.child_close_fds, in_fd);
                    push_to_IntVec(&cmd.parent_close_fds, in_fd);
                    */
                    break;
                default:
                    exit(69);
            }
        }

        execute_command(cmd, &pgid);
        
        for (int j = 0; j < cmd.parent_close_fds.count; j++) {
            close(*get_from_IntVec(&cmd.parent_close_fds, j));
        }
    }
    tcsetpgrp(STDIN_FILENO, pgid); 
    while (waitpid(-pgid, NULL, 0) > 0); 
    tcsetpgrp(STDIN_FILENO, getpgrp());
}


void process_input_line(char* line, ShellState* shstate) {
    PreprocArena arena = {
        .tokens = make_TokenVec(256),
        .chunks = make_ChunkVec(256),
        .regions = make_RegionVec(256),
    };
    TokenPtrVec line_tok_ptrs = lex(line, &arena);
    Token* line_toks = malloc(sizeof(Token) * line_tok_ptrs.count);
    for (int i = 0; i < line_tok_ptrs.count; i++) {
        line_toks[i] = **get_from_TokenPtrVec(&line_tok_ptrs, i);
    }
    Pipeline pl = parse_tokstream(line_toks);
    run_pipeline(pl, shstate);
    free(line_toks);
}