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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
|
/**
* @file main.c
* @brief Options, startup and exit.
*/
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "exec.h"
#include "interact.h"
#include "parser.h"
#ifndef environ /* z/OS <stdlib.h> defines it as a macro */
extern char **environ;
#endif
/**
* @brief Current option settings.
*/
options opt;
/**
* @brief `$0`.
*/
const char *arg0;
/**
* @brief Line of the command being executed, for messages and `$LINENO`.
*/
int cur_lineno;
/**
* @brief argv[0] as given.
*/
static const char *invoked_as; /**< argv[0] */
/**
* @brief Working directory at startup, kept if argv[0] is a relative path.
*/
static char *start_dir; /**< cwd at startup, if invoked_as is relative */
/**
* @brief The shell's own command line is being parsed.
*/
static bool startup; /**< parsing the shell's own command line */
/**
* @brief `-c` was given.
*/
static bool opt_command; /**< -c */
/**
* @brief `-l` was given, or argv[0] starts with `-`.
*/
static bool opt_login; /**< -l */
/* ---- options --------------------------------------------------------- */
/**
* @brief The options: letter, long name and where the value lives.
*/
static const struct {
char letter; /**< '\0' if the option only has a name */
const char *name;
bool *value;
bool startup_only;
} option_table[] = {
{'a', "allexport", &opt.allexport, false},
{'C', "noclobber", &opt.noclobber, false},
{'e', "errexit", &opt.errexit, false},
{'f', "noglob", &opt.noglob, false},
{'i', "interactive", &opt.interactive, true},
{'m', "monitor", &opt.monitor, false},
{'n', "noexec", &opt.noexec, false},
{'s', "stdin", &opt.stdin_cmds, true},
{'u', "nounset", &opt.nounset, false},
{'v', "verbose", &opt.verbose, false},
{'x', "xtrace", &opt.xtrace, false},
{'\0', "pipefail", &opt.pipefail, false},
{'\0', "jobnames", &opt.jobnames, false},
{'\0', "shareas", &opt.shareas, false},
{'\0', "msgid", &opt.msgid, false},
{'\0', "pipetag", &opt.pipetag, false},
{'b', "notify", &opt.notify, false},
{'h', "trackall", &opt.trackall, false},
{'\0', "ignoreeof", &opt.ignoreeof, false},
{'\0', "nolog", &opt.nolog, false},
{'E', "emacs", &opt.emacs, false},
{'V', "vi", &opt.vi, false},
};
/**
* @brief `-m` or `+m` appeared on the command line.
*/
static bool monitor_given; /**< -m or +m appeared on the command line */
/**
* @brief Apply the side effects of changing one option.
* @param value The option's storage.
* @param on Its new value.
*/
static void option_changed(const bool *value, bool on) {
/* The two editing modes exclude each other. */
if (value == &opt.emacs && on)
opt.vi = false;
else if (value == &opt.vi && on)
opt.emacs = false;
else if (value == &opt.monitor && startup)
monitor_given = true;
}
/**
* @brief Set or clear an option by its letter.
* @return false if there is no such option.
*/
bool option_set_letter(int letter, bool on) {
if (startup && letter == 'c') {
opt_command = on;
return true;
}
if (startup && letter == 'l') {
opt_login = on;
return true;
}
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
if (option_table[i].letter == letter &&
(startup || !option_table[i].startup_only)) {
*option_table[i].value = on;
option_changed(option_table[i].value, on);
return true;
}
}
return false;
}
/**
* @brief Set or clear an option by its `-o` name.
* @return false if there is no such option.
*/
bool option_set_name(const char *name, bool on) {
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
if (!strcmp(option_table[i].name, name) &&
(startup || !option_table[i].startup_only)) {
*option_table[i].value = on;
option_changed(option_table[i].value, on);
return true;
}
}
return false;
}
/**
* @brief Is a shell option on? (`[[ -o name ]]`.)
* @param name The option's long name.
* @return 1 if it is on, 0 if off, -1 if there is no such option.
*/
int option_is_set(const char *name) {
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
if (!strcmp(option_table[i].name, name))
return *option_table[i].value;
}
return -1;
}
/**
* @brief Print every option (`set -o`), or as commands that restore them
* (`set +o`).
*/
void options_print(bool as_commands) {
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
bool on = *option_table[i].value;
if (as_commands)
out_printf(&out1, "set %co %s\n", on ? '-' : '+',
option_table[i].name);
else
out_printf(&out1, "%-12s %s\n", option_table[i].name,
on ? "on" : "off");
}
}
/**
* @brief The value of `$-`.
*/
const char *option_letters(void) {
static char buf[ARRAY_LEN(option_table) + 1];
size_t n = 0;
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
if (option_table[i].letter && *option_table[i].value)
buf[n++] = option_table[i].letter;
}
buf[n] = '\0';
return buf;
}
/**
* @brief Process option arguments as `set` does.
* @param argc Argument count.
* @param argv Arguments. Argv[0] is skipped.
* @param set_params Set when the operands (even if there are none) are
* meant to replace the positional parameters.
* @return Index of the first operand.
*/
int parse_set_options(int argc, char **argv, bool *set_params) {
int i = 1;
for (; i < argc; i++) {
const char *a = argv[i];
if (!strcmp(a, "--") || !strcmp(a, "-")) {
i++;
*set_params = true;
break;
}
if ((a[0] != '-' && a[0] != '+') || !a[1])
break;
bool on = a[0] == '-';
for (const char *p = a + 1; *p; p++) {
if (*p == 'o') {
if (i + 1 >= argc) {
options_print(!on);
continue;
}
if (!option_set_name(argv[++i], on))
sh_error("%s: bad option name", argv[i]);
} else if (!option_set_letter(*p, on)) {
sh_error("%c%c: bad option", a[0], *p);
}
}
}
if (i < argc)
*set_params = true;
return i;
}
/* ---- identity -------------------------------------------------------- */
/**
* @brief `$$`: process ID of the original shell, also in subshells.
*/
pid_t shell_pid(void) {
static pid_t pid;
if (!pid)
pid = getpid();
return pid;
}
/**
* @brief The path of this shell, for running scripts that have no `#!` line.
*
* Worked out the first time it is needed.
*/
const char *shell_path(void) {
static const char *path;
if (path)
return path;
const char *name = invoked_as;
if (name[0] == '-')
name++;
if (name[0] == '/') {
path = name;
} else if (strchr(name, '/')) {
size_t len = strlen(start_dir) + strlen(name) + 2;
char *full = xmalloc(len);
snprintf(full, len, "%s/%s", start_dir, name);
path = full;
} else {
const char *search = var_get("PATH");
char *found = search ? path_search(name, search, true) : nullptr;
path = found ? xstrdup(found) : "/bin/sh";
}
return path;
}
/* ---- exit ------------------------------------------------------------ */
/**
* @brief Leave the shell: run the EXIT trap, save history, hand back the
* terminal, flush output.
* @param status Exit status (the EXIT trap may change it by calling exit).
*/
void exit_shell(int status) {
static bool exiting;
volatile int code = status; /* survives the longjmp below */
if (!exiting) {
exiting = true;
exitstatus = status;
jmploc jl;
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
trap_run_exit();
} else if (exc_code == EXC_EXIT) {
code = exitstatus; /* the trap called exit itself */
}
}
exc_handler = nullptr;
if (!in_subshell) {
interact_exit();
jc_exit();
}
if (!in_subshell && var_get("ZASH_PROCSTAT"))
out_printf(&out2, "zash: spawns=%ld forks=%ld\n", stat_spawns,
stat_forks);
flush_all();
_exit(code);
}
/* ---- startup --------------------------------------------------------- */
/**
* @brief Open a script on a descriptor above the ones scripts can name.
*/
static int open_script(const char *path) {
int fd = sys_open(path, O_RDONLY, 0);
if (fd < 0)
return -1;
int high = sys_dupfd(fd, SYS_NFD);
close(fd);
return high;
}
/**
* @brief Run the commands in a file, if it exists (profile and ENV files).
*
* A failure in a startup file is reported and the shell carries on: these
* files are only read by an interactive shell, and an interactive shell
* does not exit for a command that fails (a `.kshrc` full of another
* shell's builtins must not lock the user out). `exit` in the file still
* exits. Parsing errors do not produce a prompt line, because there is
* no interactive input here.
*/
static void source_file(const char *path) {
int fd = open_script(path);
if (fd < 0)
return;
input_push_fd(fd, false);
run_input(RI_RECOVER);
input_pop();
}
/**
* @brief A login shell reads /etc/profile and ~/.profile.
*/
static void read_profiles(void) {
source_file("/etc/profile");
const char *home = var_get("HOME");
if (home) {
char path[PATH_MAX];
int n = snprintf(path, sizeof path, "%s/.profile", home);
if (n > 0 && (size_t)n < sizeof path) /* truncated: another file */
source_file(path);
}
}
/**
* @brief Print the command-line synopsis.
*
* The option letters come from option_table, so the synopsis cannot fall
* out of step with what the shell accepts.
*
* @param o Where to write it.
* @param full Also list the `-o` option names (for `--help`).
*/
static void usage_print(output *o, bool full) {
/* Every table letter but s, plus l; sorted. c and s get their own
synopsis lines. */
char letters[ARRAY_LEN(option_table) + 2];
size_t n = 0;
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
if (option_table[i].letter && option_table[i].letter != 's')
letters[n++] = option_table[i].letter;
}
letters[n++] = 'l';
for (size_t i = 1; i < n; i++) { /* insertion sort, ~15 letters */
char c = letters[i];
size_t j = i;
for (; j > 0 && letters[j - 1] > c; j--)
letters[j] = letters[j - 1];
letters[j] = c;
}
letters[n] = '\0';
const char *name = arg0 ? arg0 : "zash";
out_printf(o, "usage: %s [-+%s] [-+o option]... [script [arg...]]\n", name,
letters);
out_printf(o,
" %s [-+%s] [-+o option]... -c command [name [arg...]]\n",
name, letters);
out_printf(o, " %s [-+%s] [-+o option]... -s [arg...]\n", name,
letters);
if (!full)
return;
out_puts(o, "options:");
size_t col = 8;
for (size_t i = 0; i < ARRAY_LEN(option_table); i++) {
size_t len = strlen(option_table[i].name);
if (col + 1 + len > 72) {
out_puts(o, "\n ");
col = 7;
}
out_putc(o, ' ');
out_puts(o, option_table[i].name);
col += 1 + len;
}
out_putc(o, '\n');
}
/**
* @brief Start the shell.
*
* Order: stack guard, variables, command table, options, signals, job
* control, profiles and ENV, then commands from `-c`, a script, or stdin.
*/
int main(int argc, char **argv) {
jmploc jl;
const char *volatile script = nullptr;
const char *volatile command = nullptr;
volatile bool in_args = false; /* read after longjmp: must be volatile */
bool ignored = false;
stack_init();
invoked_as = argv[0] ? argv[0] : "zash";
arg0 = invoked_as[0] == '-' ? invoked_as + 1 : invoked_as;
if (arg0[0] != '/' && strchr(arg0, '/')) {
char buf[PATH_MAX];
start_dir = xstrdup(getcwd(buf, sizeof buf) ? buf : ".");
}
if (invoked_as[0] == '-')
opt_login = true;
var_init(environ);
/* POSIX: the shell sets and exports PWD even when the parent had none. */
char cwd[PATH_MAX];
if (!var_get("PWD") && getcwd(cwd, sizeof cwd))
var_set("PWD", cwd, V_EXPORT);
exec_init();
fd_open_mask = sys_init();
if (setjmp(jl.buf)) {
if (in_args) /* the error was in the command line */
usage_print(&out2, false);
exit_shell(exitstatus);
}
exc_handler = &jl;
/* Only as the first argument, so that it cannot be an operand. */
if (argc > 1 && !strcmp(argv[1], "--help")) {
usage_print(&out1, true);
exit_shell(0);
}
in_args = true;
startup = true;
int i = parse_set_options(argc, argv, &ignored);
startup = false;
if (opt_command) {
if (i >= argc)
sh_error("-c requires an argument");
command = argv[i++];
if (i < argc)
arg0 = argv[i++];
} else if (i < argc && !opt.stdin_cmds) {
script = argv[i++];
arg0 = script;
}
in_args = false;
shellparam = (shparam){argc - i, argv + i, nullptr};
if (!command && !script) {
opt.stdin_cmds = true;
if (isatty(0) && isatty(2))
opt.interactive = true;
}
trap_init();
if (opt.interactive && !monitor_given)
opt.monitor = true; /* job control is the interactive default */
jc_sync();
if (opt.interactive)
interact_init();
if (opt_login)
read_profiles();
/*
* POSIX: ENV is parameter-expanded, and is not used when the real
* and effective user or group IDs differ (a set-ID shell must not
* run a file the invoking user chose).
*/
if (opt.interactive && getuid() == geteuid() && getgid() == getegid()) {
const char *env = var_get("ENV");
if (env && *env) {
arena_marker mark = arena_mark(&scratch);
const char *path = expand_quietly(env, false);
if (*path)
source_file(path);
arena_release(&scratch, mark);
}
}
if (command) {
input_push_string(command, strlen(command));
run_input(RI_TOP | RI_EXEC_LAST);
} else if (script) {
int fd = open_script(script);
if (fd < 0) {
sh_warn("cannot open %s", script);
exit_shell(127);
}
input_push_fd(fd, false);
run_input(RI_TOP);
} else {
input_push_fd(0, true);
run_input(RI_TOP);
}
exit_shell(exitstatus);
}
|