ref: f1342b124da2cf87e57f70bd8f1a9c221bca47fe mrsh/shell/task/word.c -rw-r--r-- 7.6 KiB View raw
                                                                                
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <mrsh/buffer.h>
#include <mrsh/parser.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "builtin.h"
#include "shell/process.h"
#include "shell/task.h"
#include "shell/word.h"

#define READ_SIZE 1024

static bool buffer_read_from(struct mrsh_buffer *buf, int fd) {
	while (true) {
		char *dst = mrsh_buffer_reserve(buf, READ_SIZE);

		ssize_t n = read(fd, dst, READ_SIZE);
		if (n < 0 && errno == EINTR) {
			continue;
		} else if (n < 0) {
			perror("read");
			return false;
		} else if (n == 0) {
			break;
		}

		buf->len += n;
	}

	return true;
}

static void swap_words(struct mrsh_word **word_ptr, struct mrsh_word *new_word) {
	mrsh_word_destroy(*word_ptr);
	*word_ptr = new_word;
}

static int run_word_command(struct context *ctx, struct mrsh_word **word_ptr) {
	struct mrsh_word_command *wc = mrsh_word_get_command(*word_ptr);

	int fds[2];
	if (pipe(fds) != 0) {
		perror("pipe");
		return TASK_STATUS_ERROR;
	}

	pid_t pid = fork();
	if (pid < 0) {
		perror("fork");
		close(fds[0]);
		close(fds[1]);
		return TASK_STATUS_ERROR;
	} else if (pid == 0) {
		close(fds[0]);

		dup2(fds[1], STDOUT_FILENO);
		close(fds[1]);

		if (wc->program != NULL) {
			mrsh_run_program(ctx->state, wc->program);
		}

		exit(ctx->state->exit >= 0 ? ctx->state->exit : 0);
	}

	struct process *process = process_create(ctx->state, pid);

	close(fds[1]);
	int child_fd = fds[0];

	struct mrsh_buffer buf = {0};
	if (!buffer_read_from(&buf, child_fd)) {
		mrsh_buffer_finish(&buf);
		close(child_fd);
		return TASK_STATUS_ERROR;
	}
	mrsh_buffer_append_char(&buf, '\0');
	close(child_fd);

	// Trim newlines at the end
	ssize_t i = buf.len - 2;
	while (i >= 0 && buf.data[i] == '\n') {
		buf.data[i] = '\0';
		--i;
	}

	struct mrsh_word_string *ws =
		mrsh_word_string_create(mrsh_buffer_steal(&buf), false);
	swap_words(word_ptr, &ws->word);
	return job_wait_process(process);
}

static const char *parameter_get_value(struct mrsh_state *state, char *name) {
	static char value[16];
	char *end;
	long lvalue = strtol(name, &end, 10);
	// Special cases
	if (strcmp(name, "@") == 0) {
		// TODO
	} else if (strcmp(name, "*") == 0) {
		// TODO
	} else if (strcmp(name, "#") == 0) {
		sprintf(value, "%d", state->frame->argc - 1);
		return value;
	} else if (strcmp(name, "?") == 0) {
		sprintf(value, "%d", state->last_status);
		return value;
	} else if (strcmp(name, "-") == 0) {
		return state_get_options(state);
	} else if (strcmp(name, "$") == 0) {
		sprintf(value, "%d", (int)getpid());
		return value;
	} else if (strcmp(name, "!") == 0) {
		for (ssize_t i = state->jobs.len - 1; i >= 0; i--) {
			struct mrsh_job *job = state->jobs.data[i];
			if (job->processes.len == 0) {
				continue;
			}
			struct process *process =
				job->processes.data[job->processes.len - 1];
			sprintf(value, "%d", process->pid);
			return value;
		}
		/* Standard is unclear on what to do in this case, mimic dash */
		return "";
	} else if (end[0] == '\0') {
		if (lvalue >= state->frame->argc) {
			return NULL;
		}
		return state->frame->argv[lvalue];
	}
	// User-set cases
	return mrsh_env_get(state, name, NULL);
}

/* Fill either result_str or result_word */
static int apply_parameter_op(struct mrsh_word_parameter *wp, const char *str,
		char **result_str, struct mrsh_word **result_word) {
	switch (wp->op) {
	case MRSH_PARAM_NONE:
		*result_str = str != NULL ? strdup(str) : NULL;
		return 0;
	case MRSH_PARAM_MINUS: // Use Default Values
		if (str == NULL || (str[0] == '\0' && wp->colon)) {
			*result_word = wp->arg;
		} else {
			*result_str = strdup(str);
		}
		return 0;
	case MRSH_PARAM_EQUAL: // Assign Default Values
	case MRSH_PARAM_QMARK: // Indicate Error if Null or Unset
	case MRSH_PARAM_PLUS: // Use Alternative Value
	case MRSH_PARAM_LEADING_HASH: // String Length
	case MRSH_PARAM_PERCENT: // Remove Smallest Suffix Pattern
	case MRSH_PARAM_DPERCENT: // Remove Largest Suffix Pattern
	case MRSH_PARAM_HASH: // Remove Smallest Prefix Pattern
	case MRSH_PARAM_DHASH: // Remove Largest Prefix Pattern
		assert(false); // TODO
	}
	assert(false);
}

int run_word(struct context *ctx, struct mrsh_word **word_ptr,
		enum tilde_expansion tilde_expansion) {
	struct mrsh_word *word = *word_ptr;

	int ret;
	switch (word->type) {
	case MRSH_WORD_STRING:;
		struct mrsh_word_string *ws = mrsh_word_get_string(word);
		if (!ws->single_quoted && tilde_expansion != TILDE_EXPANSION_NONE) {
			// TODO: TILDE_EXPANSION_ASSIGNMENT
			expand_tilde(ctx->state, &ws->str);
		}
		return 0;
	case MRSH_WORD_PARAMETER:;
		struct mrsh_word_parameter *wp = mrsh_word_get_parameter(word);
		const char *value = parameter_get_value(ctx->state, wp->name);
		char lineno[16];
		if (value == NULL && strcmp(wp->name, "LINENO") == 0) {
			struct mrsh_position pos;
			mrsh_word_range(word, &pos, NULL);

			snprintf(lineno, sizeof(lineno), "%d", pos.line);

			value = lineno;
		}
		char *result_str = NULL;
		struct mrsh_word *result_word = NULL;
		ret = apply_parameter_op(wp, value, &result_str, &result_word);
		if (ret < 0) {
			return ret;
		}
		assert(result_str == NULL || result_word == NULL);
		if (result_str == NULL && result_word == NULL) {
			if ((ctx->state->options & MRSH_OPT_NOUNSET)) {
				fprintf(stderr, "%s: %s: unbound variable\n",
						ctx->state->frame->argv[0], wp->name);
				return TASK_STATUS_ERROR;
			}
			result_str = strdup("");
		}
		if (result_word != NULL) {
			result_word = mrsh_word_copy(result_word);
			ret = run_word(ctx, &result_word, tilde_expansion);
			if (ret < 0) {
				return ret;
			}
		} else if (result_str != NULL) {
			struct mrsh_word_string *ws =
				mrsh_word_string_create(result_str, false);
			result_word = &ws->word;
		}
		swap_words(word_ptr, result_word);
		return 0;
	case MRSH_WORD_COMMAND:
		return run_word_command(ctx, word_ptr);
	case MRSH_WORD_ARITHMETIC:;
		// For arithmetic words, we need to expand the arithmetic expression
		// before parsing and evaluating it
		struct mrsh_word_arithmetic *wa = mrsh_word_get_arithmetic(word);
		ret = run_word(ctx, &wa->body, TILDE_EXPANSION_NONE);
		if (ret < 0) {
			return ret;
		}

		char *body_str = mrsh_word_str(wa->body);
		struct mrsh_parser *parser =
			mrsh_parser_with_data(body_str, strlen(body_str));
		free(body_str);
		struct mrsh_arithm_expr *expr = mrsh_parse_arithm_expr(parser);
		if (expr == NULL) {
			struct mrsh_position err_pos;
			const char *err_msg = mrsh_parser_error(parser, &err_pos);
			if (err_msg != NULL) {
				// TODO: improve error line/column
				fprintf(stderr, "%s (arithmetic %d:%d): %s\n",
					ctx->state->frame->argv[0], err_pos.line,
					err_pos.column, err_msg);
			} else {
				fprintf(stderr, "expected an arithmetic expression\n");
			}
			ret = TASK_STATUS_ERROR;
		} else {
			long result;
			if (!mrsh_run_arithm_expr(ctx->state, expr, &result)) {
				ret = TASK_STATUS_ERROR;
			} else {
				char buf[32];
				snprintf(buf, sizeof(buf), "%ld", result);

				struct mrsh_word_string *ws =
					mrsh_word_string_create(strdup(buf), false);
				swap_words(word_ptr, &ws->word);
				ret = 0;
			}
		}
		mrsh_arithm_expr_destroy(expr);
		mrsh_parser_destroy(parser);
		return ret;
	case MRSH_WORD_LIST:;
		// For word lists, we just need to expand each word
		struct mrsh_word_list *wl = mrsh_word_get_list(word);
		for (size_t i = 0; i < wl->children.len; ++i) {
			struct mrsh_word **child_ptr =
				(struct mrsh_word **)&wl->children.data[i];
			if (i > 0 || wl->double_quoted) {
				tilde_expansion = TILDE_EXPANSION_NONE;
			}
			ret = run_word(ctx, child_ptr, tilde_expansion);
			if (ret < 0) {
				return ret;
			}
		}
		return 0;
	}
	assert(false);
}