~emersion/mrsh

ref: 37e7c073c6f0365ed8255c83168835503c5e1921 mrsh/shell/task/word.c -rw-r--r-- 10.4 KiB
37e7c073Simon Ser shell/task/word: refuse to apply string param ops on $# 1 year, 10 days ago
                                                                                
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#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,
		const char *name) {
	static char value[16];
	char *end;
	long lvalue = strtol(name, &end, 10);
	// Special cases
	if (strcmp(name, "@") == 0 || strcmp(name, "*") == 0) {
		// These are handled separately, because they evaluate to a word, not
		// a raw string.
		return NULL;
	} 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' && end != name) {
		if (lvalue >= state->frame->argc) {
			return NULL;
		}
		return state->frame->argv[lvalue];
	}
	// User-set cases
	return mrsh_env_get(state, name, NULL);
}

static struct mrsh_word *create_word_string(const char *str) {
	struct mrsh_word_string *ws = mrsh_word_string_create(strdup(str), false);
	return &ws->word;
}

static struct mrsh_word *copy_word_or_null(struct mrsh_word *word) {
	if (word != NULL) {
		return mrsh_word_copy(word);
	} else {
		return create_word_string("");
	}
}

static bool is_null_word(const struct mrsh_word *word) {
	switch (word->type) {
	case MRSH_WORD_STRING:;
		const struct mrsh_word_string *ws = mrsh_word_get_string(word);
		return ws->str[0] == '\0';
	case MRSH_WORD_LIST:;
		const struct mrsh_word_list *wl = mrsh_word_get_list(word);
		for (size_t i = 0; i < wl->children.len; i++) {
			const struct mrsh_word *child = wl->children.data[i];
			if (!is_null_word(child)) {
				return false;
			}
		}
		return true;
	default:
		assert(false);
	}
}

static int apply_parameter_cond_op(struct context *ctx,
		struct mrsh_word_parameter *wp, struct mrsh_word *value,
		struct mrsh_word **result) {
	switch (wp->op) {
	case MRSH_PARAM_NONE:
		*result = value;
		return 0;
	case MRSH_PARAM_MINUS: // Use Default Values
		if (value == NULL || (wp->colon && is_null_word(value))) {
			mrsh_word_destroy(value);
			*result = copy_word_or_null(wp->arg);
		} else {
			*result = value;
		}
		return 0;
	case MRSH_PARAM_EQUAL: // Assign Default Values
		if (value == NULL || (wp->colon && is_null_word(value))) {
			mrsh_word_destroy(value);
			*result = copy_word_or_null(wp->arg);
			int ret = run_word(ctx, result);
			if (ret < 0) {
				return ret;
			}
			char *str = mrsh_word_str(*result);
			mrsh_env_set(ctx->state, wp->name, str, 0);
			free(str);
		} else {
			*result = value;
		}
		return 0;
	case MRSH_PARAM_QMARK: // Indicate Error if Null or Unset
		if (value == NULL || (wp->colon && is_null_word(value))) {
			mrsh_word_destroy(value);
			char *err_msg;
			if (wp->arg != NULL) {
				struct mrsh_word *err_msg_word = mrsh_word_copy(wp->arg);
				int ret = run_word(ctx, &err_msg_word);
				if (ret < 0) {
					return ret;
				}
				err_msg = mrsh_word_str(err_msg_word);
				mrsh_word_destroy(err_msg_word);
			} else {
				err_msg = strdup("parameter not set or null");
			}
			fprintf(stderr, "%s: %s: %s\n", ctx->state->frame->argv[0],
				wp->name, err_msg);
			free(err_msg);
			// TODO: make the shell exit if non-interactive
			return TASK_STATUS_ERROR;
		} else {
			*result = value;
		}
		return 0;
	case MRSH_PARAM_PLUS: // Use Alternative Value
		if (value == NULL || (wp->colon && is_null_word(value))) {
			*result = create_word_string("");
		} else {
			*result = copy_word_or_null(wp->arg);
		}
		mrsh_word_destroy(value);
		return 0;
	default:
		assert(false); // unreachable
	}
}

static int apply_parameter_str_op(struct context *ctx,
		struct mrsh_word_parameter *wp, const char *str,
		struct mrsh_word **result) {
	switch (wp->op) {
	case MRSH_PARAM_LEADING_HASH: // String Length
		if (str == NULL && (ctx->state->options & MRSH_OPT_NOUNSET)) {
			*result = NULL;
			return 0;
		}

		int len = 0;
		if (str != NULL) {
			len = strlen(str);
		}
		char len_str[32];
		snprintf(len_str, sizeof(len_str), "%d", len);
		*result = create_word_string(len_str);
		return 0;
	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
	default:
		assert(false);
	}
}

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

	int ret;
	switch (word->type) {
	case MRSH_WORD_STRING:;
		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;
		}

		struct mrsh_word *result = NULL;
		switch (wp->op) {
		case MRSH_PARAM_NONE:
		case MRSH_PARAM_MINUS:
		case MRSH_PARAM_EQUAL:
		case MRSH_PARAM_QMARK:
		case MRSH_PARAM_PLUS:;
			struct mrsh_word *value_word;
			if (strcmp(wp->name, "@") == 0 || strcmp(wp->name, "*") == 0) {
				assert(false); // TODO
			} else if (value != NULL) {
				value_word = create_word_string(value);
			} else {
				value_word = NULL;
			}

			ret = apply_parameter_cond_op(ctx, wp, value_word, &result);
			if (ret < 0) {
				return ret;
			}
			break;
		case MRSH_PARAM_LEADING_HASH:
		case MRSH_PARAM_PERCENT:
		case MRSH_PARAM_DPERCENT:
		case MRSH_PARAM_HASH:
		case MRSH_PARAM_DHASH:
			if (strcmp(wp->name, "@") == 0 || strcmp(wp->name, "*") == 0 ||
					(wp->op != MRSH_PARAM_LEADING_HASH &&
					strcmp(wp->name, "#") == 0)) {
				fprintf(stderr, "%s: using this parameter operator on $%s "
					"is undefined behaviour\n",
					ctx->state->frame->argv[0], wp->name);
				return TASK_STATUS_ERROR;
			}

			ret = apply_parameter_str_op(ctx, wp, value, &result);
			if (ret < 0) {
				return ret;
			}
			break;
		}

		if (result == 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 = create_word_string("");
		}
		if (result->type != MRSH_WORD_STRING) {
			ret = run_word(ctx, &result);
			if (ret < 0) {
				return ret;
			}
		}
		swap_words(word_ptr, result);
		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);
		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];
			ret = run_word(ctx, child_ptr);
			if (ret < 0) {
				return ret;
			}
		}
		return 0;
	}
	assert(false);
}