summaryrefslogtreecommitdiffhomepage
path: root/src
diff options
context:
space:
mode:
authorSean Kurtz <seankurtz75@gmail.com>2026-11-28 14:16:41 -0600
committerGitHub <noreply@github.com>2026-11-28 14:16:41 -0600
commit95d31d2d7d5fd7de81d6d5e2caedcdc369ca0fcf (patch)
tree4959b8d43268945543be4061b8fccd95d04592b1 /src
parent625908ab56c7c554506d61c83c7001bca19a05f6 (diff)
parent6fe2aff8d6611bf45704ba86120efa23950bfa80 (diff)
downloadzash-95d31d2d7d5fd7de81d6d5e2caedcdc369ca0fcf.tar.gz
Merge pull request #46 from skurtz97/fix/review-2026-11-28
Fixes from the 2026-11-28 code review
Diffstat (limited to 'src')
-rw-r--r--src/arith.c34
-rw-r--r--src/builtin.c5
-rw-r--r--src/builtin_ext.c23
-rw-r--r--src/edit_builtin.c259
-rw-r--r--src/exec.c42
-rw-r--r--src/exec.h3
-rw-r--r--src/expand.c56
-rw-r--r--src/history.c31
-rw-r--r--src/main.c2
-rw-r--r--src/parser.c11
-rw-r--r--src/pattern.c12
-rw-r--r--src/printf.c24
-rw-r--r--src/redir.c5
-rw-r--r--src/trap.c24
-rw-r--r--src/util.c4
15 files changed, 475 insertions, 60 deletions
diff --git a/src/arith.c b/src/arith.c
index c7c410f..5097134 100644
--- a/src/arith.c
+++ b/src/arith.c
@@ -266,16 +266,36 @@ static intmax_t apply(const arith *a, binop op, intmax_t x, intmax_t y) {
*/
static intmax_t parse_based(arith *a, const char *p, const char *hash) {
int base = 0;
- for (const char *q = p; q < hash; q++)
+ for (const char *q = p; q < hash; q++) {
base = base * 10 + (*q - '0');
- if (base < 2 || base > 36)
+ if (base > 64)
+ arith_error(a, "bad number base");
+ }
+ if (base < 2)
arith_error(a, "bad number base");
- char *end;
- errno = 0;
- uintmax_t v = strtoumax(hash + 1, &end, base);
- if (errno || end == hash + 1 || isalnum((unsigned char)*end) || *end == '_')
+ /*
+ * The digit set of ksh and bash. Spelling it out beats arithmetic on
+ * character codes: the letters are not contiguous in EBCDIC.
+ */
+ static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ@_";
+ uintmax_t v = 0;
+ const char *q = hash + 1;
+ for (; *q; q++) {
+ const char *d = strchr(digits, *q);
+ if (!d)
+ break;
+ uintmax_t dv = (uintmax_t)(d - digits);
+ if (dv >= (uintmax_t)base)
+ break;
+ if (v > (UINTMAX_MAX - dv) / (uintmax_t)base)
+ arith_error(a, "bad number");
+ v = v * base + dv;
+ }
+ /* No digits, or a digit the base does not have (16#0x10, 16# f). */
+ if (q == hash + 1 || (*q && strchr(digits, *q)))
arith_error(a, "bad number");
- a->p = end;
+ a->p = q;
return (intmax_t)v;
}
diff --git a/src/builtin.c b/src/builtin.c
index 2aa198f..ac7aa45 100644
--- a/src/builtin.c
+++ b/src/builtin.c
@@ -672,6 +672,11 @@ static const char *get_curdir(void) {
return curdir;
}
+void curdir_invalidate(void) {
+ free(curdir);
+ curdir = nullptr;
+}
+
/**
* @brief Remove `.`, `..` and repeated slashes from an absolute path, textually
* (the logical view `cd -L` uses).
diff --git a/src/builtin_ext.c b/src/builtin_ext.c
index 2f0271a..8983e5a 100644
--- a/src/builtin_ext.c
+++ b/src/builtin_ext.c
@@ -377,16 +377,12 @@ int builtin_ulimit(int argc, char **argv) {
}
if (all) {
for (size_t k = 0; k < ARRAY_LEN(limits); k++) {
- char label[64];
const limit *e = &limits[k];
- size_t n = 0;
- for (const char *s = e->name; *s; s++)
- label[n++] = *s;
- label[n] = '\0';
if (e->unit)
- out_printf(&out1, "%-20s (%s, -%c) ", label, e->unit, e->opt);
+ out_printf(&out1, "%-20s (%s, -%c) ", e->name, e->unit,
+ e->opt);
else
- out_printf(&out1, "%-20s (-%c) ", label, e->opt);
+ out_printf(&out1, "%-20s (-%c) ", e->name, e->opt);
limit_print(e, hard && !soft);
}
return 0;
@@ -397,6 +393,11 @@ int builtin_ulimit(int argc, char **argv) {
l = &limits[k];
}
}
+ if (!l) {
+ /* Built without RLIMIT_FSIZE: there is no default resource. */
+ sh_warn("ulimit: -f: not supported here");
+ return 1;
+ }
if (i >= argc) {
limit_print(l, hard && !soft);
return 0;
@@ -417,7 +418,13 @@ int builtin_ulimit(int argc, char **argv) {
sh_warn("ulimit: %s: bad limit", argv[i]);
return 2;
}
- v = (rlim_t)n * l->scale;
+ /* n * scale may not wrap, and may not quietly mean "unlimited". */
+ if (n > RLIM_INFINITY / l->scale ||
+ n * l->scale == RLIM_INFINITY) {
+ sh_warn("ulimit: %s: limit out of range", argv[i]);
+ return 1;
+ }
+ v = (rlim_t)n * (rlim_t)l->scale;
}
if (hard || !soft)
rl.rlim_max = v;
diff --git a/src/edit_builtin.c b/src/edit_builtin.c
index 14ad8ac..bc66b5a 100644
--- a/src/edit_builtin.c
+++ b/src/edit_builtin.c
@@ -33,6 +33,7 @@
*/
#include <ctype.h>
#include <errno.h>
+#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
@@ -90,6 +91,17 @@ typedef struct editor {
size_t undo_len; /**< Its length. */
size_t undo_pos; /**< Cursor position to restore with it. */
char search[128]; /**< vi mode: last `/` or `?` pattern. */
+
+ int rec[512]; /**< vi mode: the keys of the change being made. */
+ size_t rec_len; /**< Keys in `rec`. */
+ int last[512]; /**< vi mode: the last change, for `.` and count. */
+ size_t last_len; /**< Keys in `last`. */
+ bool changed; /**< vi mode: the command under way moved the line. */
+ bool recording; /**< vi mode: keys are being recorded into `rec`. */
+ int replay[512]; /**< vi mode: keys `.` is replaying, one pass. */
+ size_t replay_len; /**< Keys in `replay`. */
+ size_t replay_pos; /**< Next key to hand out. */
+ size_t replay_left; /**< Keys still to hand out, passes included. */
} editor;
/**
@@ -358,6 +370,8 @@ static void reserve(size_t extra) {
* @param n How many.
*/
static void insert(const char *s, size_t n) {
+ if (!n) /* `y` over an empty range has no kill buffer to paste */
+ return;
reserve(n);
memmove(ed.buf + ed.pos + n, ed.buf + ed.pos, ed.len - ed.pos);
memcpy(ed.buf + ed.pos, s, n);
@@ -365,6 +379,16 @@ static void insert(const char *s, size_t n) {
ed.pos += n;
}
+/** @brief Make the bytes in [from, to) the kill buffer. */
+static void kill_set(size_t from, size_t to) {
+ if (from >= to)
+ return;
+ free(ed.kill);
+ ed.kill_len = to - from;
+ ed.kill = xmalloc(ed.kill_len);
+ memcpy(ed.kill, ed.buf + from, ed.kill_len);
+}
+
/**
* @brief Remove the bytes in [from, to) and put the cursor at `from`.
* @param from First byte to remove.
@@ -374,12 +398,8 @@ static void insert(const char *s, size_t n) {
static void remove_range(size_t from, size_t to, bool save) {
if (from >= to)
return;
- if (save) {
- free(ed.kill);
- ed.kill_len = to - from;
- ed.kill = xmalloc(ed.kill_len);
- memcpy(ed.kill, ed.buf + from, ed.kill_len);
- }
+ if (save)
+ kill_set(from, to);
memmove(ed.buf + from, ed.buf + to, ed.len - to);
ed.len -= to - from;
ed.pos = from;
@@ -579,7 +599,7 @@ static int read_byte(void) {
*
* @return A byte value, one of the K_ codes, or K_META plus a byte.
*/
-static int read_key(void) {
+static int read_key_raw(void) {
if (ed.unread) {
int k = ed.unread;
ed.unread = 0;
@@ -671,6 +691,47 @@ static int read_key(void) {
return bind_key(k, seq, n);
}
+/**
+ * @brief Record a key for vi mode's `.`, or give up on this change.
+ *
+ * A change longer than the record cannot be repeated, and a partial one
+ * would repeat the wrong thing, so recording stops instead.
+ *
+ * @param k The key, or a negative value at end of input.
+ * @return true while recording continues.
+ */
+static bool rec_add(int k) {
+ if (ed.rec_len == sizeof ed.rec / sizeof ed.rec[0]) {
+ ed.recording = false;
+ ed.rec_len = 0;
+ return false;
+ }
+ if (k >= 0)
+ ed.rec[ed.rec_len++] = k;
+ return true;
+}
+
+/**
+ * @brief Read one key: from `.`'s replay, or from the terminal.
+ *
+ * Replaying through here means a repeated change is dispatched exactly
+ * like a typed one, insert mode and all. Every key read while a change
+ * is being made is recorded for the next `.`.
+ */
+static int read_key(void) {
+ if (ed.replay_left) {
+ int k = ed.replay[ed.replay_pos];
+ if (++ed.replay_pos >= ed.replay_len)
+ ed.replay_pos = 0;
+ ed.replay_left--;
+ return k;
+ }
+ int k = read_key_raw();
+ if (ed.recording)
+ rec_add(k);
+ return k;
+}
+
/* ---- completion ------------------------------------------------------ */
/**
@@ -842,6 +903,145 @@ static void vi_save_undo(void) {
memcpy(ed.undo, ed.buf, ed.len);
ed.undo_len = ed.len;
ed.undo_pos = ed.pos;
+ ed.changed = true;
+}
+
+/**
+ * @brief vi: start recording the keys of a change.
+ *
+ * A change runs from its command key through the text typed in insert
+ * mode, which the main loop records while `vi_cmd` is false. Keys that
+ * `.` hands back are not recorded: `.` keeps the change it repeated.
+ */
+static void vi_record_start(void) {
+ if (ed.replay_left) {
+ ed.recording = false;
+ return;
+ }
+ ed.rec_len = 0;
+ ed.changed = false;
+ ed.recording = true;
+}
+
+/**
+ * @brief vi: keep the keys of the change just made, for `.`.
+ */
+static void vi_record_done(void) {
+ if (!ed.recording)
+ return;
+ ed.recording = false;
+ if (!ed.changed || !ed.rec_len)
+ return;
+ memcpy(ed.last, ed.rec, ed.rec_len * sizeof ed.last[0]);
+ ed.last_len = ed.rec_len;
+}
+
+/** @brief vi: stop recording and forget the change (the line was taken). */
+static void vi_record_stop(void) {
+ ed.recording = false;
+ ed.changed = false;
+}
+
+/**
+ * @brief vi: hand the last change's keys back, `times` times (`3.`).
+ * @param times Repeat count; 0 and 1 both mean once.
+ */
+static void vi_replay(int times) {
+ if (!ed.last_len)
+ return;
+ memcpy(ed.replay, ed.last, ed.last_len * sizeof ed.replay[0]);
+ ed.replay_len = ed.last_len;
+ ed.replay_pos = 0;
+ ed.replay_left = ed.last_len * (size_t)(times > 0 ? times : 1);
+}
+
+/**
+ * @brief vi: edit the line in `$VISUAL` or `$EDITOR` (the `v` key).
+ *
+ * The line goes to a temporary file and the editor is run through the
+ * shell, so an editor given with arguments (`emacs -nw`) works. The
+ * terminal is handed back while it runs. A successful exit puts the
+ * file's first line in the buffer with the cursor at its start, ready
+ * for the next command-mode key.
+ */
+static void edit_external(void) {
+ const char *tmpdir = var_get("TMPDIR");
+ char file[4096];
+ int n = snprintf(file, sizeof file, "%s/zash-vi.XXXXXX",
+ tmpdir && *tmpdir ? tmpdir : "/tmp");
+ if (n < 0 || (size_t)n >= sizeof file) {
+ ob_puts("zash: TMPDIR is too long for `v`\n");
+ ob_flush();
+ return;
+ }
+ int fd = mkstemp(file);
+ if (fd < 0) {
+ ob_puts("zash: `v`: cannot create a temporary file\n");
+ ob_flush();
+ return;
+ }
+ size_t off = 0;
+ while (off < ed.len) {
+ ssize_t w = write(fd, ed.buf + off, ed.len - off);
+ if (w <= 0)
+ break;
+ off += (size_t)w;
+ }
+ bool wrote = off == ed.len && write(fd, "\n", 1) == 1;
+ close(fd);
+ const char *editor = var_get("VISUAL");
+ if (!editor || !*editor)
+ editor = var_get("EDITOR");
+ if (!editor || !*editor)
+ editor = "vi";
+ /* The editor is a shell command, the file name is a word: quote it, so
+ * a TMPDIR with a space or a `$` in it still names the file. */
+ output cmd = {.fd = OUT_MEM};
+ out_puts(&cmd, editor);
+ out_putc(&cmd, ' ');
+ out_quote(&cmd, file);
+ out_write(&cmd, "", 1); /* the NUL */
+ raw_off();
+ ob_flush();
+ jmploc jl;
+ jmploc *prev = exc_handler;
+ int status;
+ if (setjmp(jl.buf)) {
+ /* The editor command raised: the file must not be left behind. */
+ exc_handler = prev;
+ raw_on();
+ free(cmd.buf);
+ unlink(file);
+ exc_raise(exc_code);
+ }
+ exc_catch(&jl);
+ status = eval_string(cmd.buf, 0);
+ exc_handler = prev;
+ raw_on();
+ free(cmd.buf);
+ char *text = nullptr;
+ size_t nread = 0;
+ if (status == 0 && wrote && (fd = open(file, O_RDONLY)) >= 0) {
+ text = xmalloc(256);
+ size_t cap = 256;
+ ssize_t r;
+ while (nread + 1 < cap &&
+ (r = read(fd, text + nread, cap - nread - 1)) > 0) {
+ nread += (size_t)r;
+ if (nread + 1 == cap) {
+ cap *= 2;
+ text = xrealloc(text, cap);
+ }
+ }
+ close(fd);
+ text[nread] = '\0';
+ text[strcspn(text, "\n")] = '\0';
+ vi_save_undo();
+ set_line(text);
+ ed.pos = 0;
+ }
+ free(text);
+ unlink(file);
}
/** @brief vi: is this byte blank? */
@@ -961,11 +1161,14 @@ static bool vi_search(bool backwards) {
* @return false if the user gave up with ESC or an interrupt.
*/
static bool vi_read_pattern(char lead) {
+ /* Read into a buffer of its own: typing over the old pattern and then
+ * backspacing past it would otherwise leave a mix of two patterns. */
+ char pat[sizeof ed.search];
size_t n = 0;
for (;;) {
ob_putc('\r');
ob_putc(lead);
- ob_put(ed.search, n);
+ ob_put(pat, n);
ob_csi(0, 'K');
ob_flush();
int k = read_key();
@@ -979,12 +1182,14 @@ static bool vi_read_pattern(char lead) {
if (k == CH_DEL || k == CH_CTRL_H) {
if (n)
n--;
- } else if (k < 0x100 && !iscntrl(k) && n + 1 < sizeof ed.search) {
- ed.search[n++] = (char)k;
+ } else if (k < 0x100 && !iscntrl(k) && n + 1 < sizeof pat) {
+ pat[n++] = (char)k;
}
}
- if (n) /* an empty pattern repeats the previous search */
+ if (n) { /* an empty pattern repeats the previous search */
+ memcpy(ed.search, pat, n);
ed.search[n] = '\0';
+ }
return ed.search[0] != '\0';
}
@@ -1107,11 +1312,11 @@ static bool vi_command(int key) {
}
}
if (key == 'y') {
- size_t keep = ed.pos;
- vi_save_undo();
- remove_range(from, to, true);
- insert(ed.kill, ed.kill_len);
- ed.pos = keep < from ? keep : from;
+ /* Yank: the text becomes the kill buffer and stays put. Going
+ * through remove_range() and inserting it back pasted an older
+ * kill buffer when the range was empty (`y0` at column 0). */
+ kill_set(from, to);
+ ed.pos = from;
break;
}
vi_save_undo();
@@ -1130,6 +1335,12 @@ static bool vi_command(int key) {
ed.pos = prev_char(ed.pos);
}
break;
+ case '.':
+ vi_replay(count);
+ break;
+ case 'v':
+ edit_external();
+ break;
case 'u':
if (ed.undo) {
char *now = xmalloc(ed.len + 1);
@@ -1419,12 +1630,17 @@ char *edit_readline(const char *prompt, size_t *len) {
ed.hidx = hist_count();
ed.unread = 0;
ed.vi_cmd = false;
+ ed.recording = false;
+ ed.replay_left = 0;
reserve(64);
raw_on();
bool eof = false;
for (;;) {
refresh();
+ /* A change is recorded from its command key: `.` repeats it. */
+ if (opt.vi && ed.vi_cmd)
+ vi_record_start();
int k = read_key();
if (k == K_INTR) {
interrupted();
@@ -1436,19 +1652,26 @@ char *edit_readline(const char *prompt, size_t *len) {
}
if (opt.vi) {
if (ed.vi_cmd) {
- if (k == '\r' || k == '\n' || vi_command(k))
+ if (k == '\r' || k == '\n' || vi_command(k)) {
+ vi_record_stop();
break;
+ }
+ if (ed.vi_cmd)
+ vi_record_done();
continue;
}
if (k == CH_ESC) {
ed.vi_cmd = true;
ed.pos = prev_char(ed.pos);
+ vi_record_done();
continue;
}
/* In insert mode the basic editing keys still work. */
}
- if (edit_key(k))
+ if (edit_key(k)) {
+ vi_record_stop();
break;
+ }
}
ed.pos = ed.len;
if (!eof)
diff --git a/src/exec.c b/src/exec.c
index 1b04b25..e7365ba 100644
--- a/src/exec.c
+++ b/src/exec.c
@@ -957,7 +957,7 @@ static int run_external(simple_cmd *sc, unsigned flags, int in, int out,
plan_close(&plan);
return 2;
}
- if ((flags & EV_EXIT) && !async && !trap_has_exit()) {
+ if ((flags & EV_EXIT) && !async && !trap_after_last()) {
/* Nothing comes after this command: become it. */
plan_apply(&plan);
exec_path(sc->cmd.path, sc->argv, envp);
@@ -1248,7 +1248,12 @@ static bool subshell_in_process(const node *n) {
return false;
cmdinfo ci;
find_command(b->u.simple.args->plain, &ci, 0);
- return ci.kind == C_BUILTIN && (ci.bi->flags & BI_PURE);
+ if (ci.kind != C_BUILTIN)
+ return false;
+ if (ci.bi->flags & BI_PURE)
+ return true;
+ /* cd / chdir: can run in-process if the cwd is saved and restored */
+ return !strcmp(ci.bi->name, "cd") || !strcmp(ci.bi->name, "chdir");
}
/* ---- pipelines ------------------------------------------------------- */
@@ -1367,7 +1372,7 @@ static void run_deferred(stage *st, int nc, int i, bool stream) {
s->out = -1;
for (int j = 0; j < nc; j++)
close_stage(&st[j]); /* or we would never see EPIPE */
- signal(SIGPIPE, SIG_DFL);
+ trap_sig_default(SIGPIPE);
output direct = {o.buf, o.len, o.len, out, 0};
out_flush(&direct);
_exit(0);
@@ -1903,7 +1908,7 @@ static int eval_case(node *n, unsigned flags) {
* the shell was about to exit anyway.
*/
static int eval_subshell(node *n, unsigned flags) {
- if (!(flags & EV_EXIT) || trap_has_exit()) {
+ if (!(flags & EV_EXIT) || trap_after_last()) {
if (!job_launching && !opt.errexit && subshell_in_process(n)) {
simple_cmd sc;
varscope vs;
@@ -1915,6 +1920,23 @@ static int eval_subshell(node *n, unsigned flags) {
scope_pop();
return status;
}
+ /* cd / chdir: save cwd, run in-process, restore */
+ if (ok && sc.cmd.kind == C_BUILTIN &&
+ (!strcmp(sc.cmd.bi->name, "cd") ||
+ !strcmp(sc.cmd.bi->name, "chdir"))) {
+ int cwd_fd = open(".", O_RDONLY | O_CLOEXEC);
+ if (cwd_fd < 0) {
+ scope_pop();
+ return 1;
+ }
+ int status = sc.cmd.bi->fn(sc.argc, sc.argv);
+ if (fchdir(cwd_fd) < 0)
+ sh_error("cannot restore working directory");
+ close(cwd_fd);
+ scope_pop();
+ curdir_invalidate();
+ return status;
+ }
scope_pop();
if (!ok)
return exitstatus;
@@ -2088,6 +2110,7 @@ int eval_node(node *n, unsigned flags) {
* @return The status of the last command.
*/
int run_input(unsigned flags) {
+ alignas(max_align_t) char pstate[PARSER_STATE_SIZE];
arena *volatile pa = arena_new();
arena_marker mark = arena_mark(&scratch);
jmploc jl;
@@ -2100,6 +2123,14 @@ int run_input(unsigned flags) {
arena_unref(pa);
sh_error("eval nested too deeply");
}
+ /*
+ * A trap, or the vi `v` command, runs eval_string() while the outer
+ * parse is half way through a command; its parse_command() moves the
+ * static arena pointer and parser_reset() drops the pending tokens.
+ * Every way out of this function restores what the caller was in the
+ * middle of, so no nested eval can leave it parsing a freed arena.
+ */
+ parser_save(pstate);
if (!recover) {
/*
* An error or exit unwinding through here drops this level's
@@ -2110,6 +2141,7 @@ int run_input(unsigned flags) {
if (setjmp(jl.buf)) {
exc_handler = prev;
arena_unref(pa);
+ parser_restore(pstate);
exc_raise(exc_code);
}
exc_catch(&jl);
@@ -2121,6 +2153,7 @@ int run_input(unsigned flags) {
if (exc_code == EXC_EXIT) {
exc_handler = prev;
arena_unref(pa);
+ parser_restore(pstate);
exc_raise(EXC_EXIT);
}
arena_release(&scratch, mark);
@@ -2160,6 +2193,7 @@ int run_input(unsigned flags) {
}
exc_handler = prev;
arena_unref(pa);
+ parser_restore(pstate);
return exitstatus;
}
diff --git a/src/exec.h b/src/exec.h
index 90bc8c9..6bbe6f6 100644
--- a/src/exec.h
+++ b/src/exec.h
@@ -110,6 +110,7 @@ enum {
};
void find_command(const char *name, cmdinfo *ci, unsigned flags);
+void curdir_invalidate(void);
void func_define(const char *name, node *body, arena *owner);
bool func_unset(const char *name);
void func_each(void (*fn)(const char *name, void *arg), void *arg);
@@ -214,6 +215,8 @@ void trap_poll(void);
void trap_reset_child(void);
void trap_reset_exec(void);
bool trap_has_exit(void);
+void trap_sig_default(int sig);
+bool trap_after_last(void);
void trap_run_exit(void);
const sigset_t *trap_spawn_defaults(void);
int builtin_trap(int argc, char **argv);
diff --git a/src/expand.c b/src/expand.c
index 89106ad..1699fb8 100644
--- a/src/expand.c
+++ b/src/expand.c
@@ -338,6 +338,9 @@ static void emit_assign_lit(expansion *x, const char *s, size_t n,
/* ---- parameters ------------------------------------------------------ */
+static const char *trim(const char *val, const char *pat, param_op op,
+ size_t *lenp);
+
/**
* @brief Join the positional parameters into one string.
* @param sep Separator, or NUL for none.
@@ -355,6 +358,27 @@ static const char *join_params(char sep) {
}
/**
+ * @brief Join the positional parameters after trimming each one.
+ * @param sep Separator, or NUL for none.
+ * @param pat Pattern for trim().
+ * @param op Which trim.
+ * @return The joined string, in scratch memory.
+ */
+static const char *join_params_trimmed(char sep, const char *pat,
+ param_op op) {
+ strbuf sb;
+ sb_init(&sb, &scratch);
+ for (int i = 0; i < shellparam.n; i++) {
+ if (i && sep)
+ sb_putc(&sb, sep);
+ size_t len;
+ const char *s = trim(shellparam.p[i], pat, op, &len);
+ sb_put(&sb, s, len);
+ }
+ return sb_cstr(&sb);
+}
+
+/**
* @brief Expand `$@` or `$*` with no operator.
*
* `"$@"` gives one field per parameter, even an empty one. `"$*"` gives
@@ -363,27 +387,38 @@ static const char *join_params(char sep) {
* @param x Expansion state.
* @param which `@` or `*`.
* @param quoted Whether the expansion is inside double quotes.
+ * @param pat Pattern for `${@#pat}`, or nullptr for plain `$@`.
+ * @param op Which trim, when `pat` is not nullptr.
*/
-static void expand_all_params(expansion *x, char which, bool quoted) {
+static void expand_all_params(expansion *x, char which, bool quoted,
+ const char *pat, param_op op) {
int n = shellparam.n;
char **p = shellparam.p;
if (x->mode != X_FIELDS) {
- const char *s = join_params(which == '*' ? ifs_first : ' ');
+ const char *s =
+ pat ? join_params_trimmed(which == '*' ? ifs_first : ' ', pat, op)
+ : join_params(which == '*' ? ifs_first : ' ');
emit(x, s, strlen(s), quoted);
return;
}
if (quoted && which == '*') {
- const char *s = join_params(ifs_first);
+ const char *s =
+ pat ? join_params_trimmed(ifs_first, pat, op)
+ : join_params(ifs_first);
emit_quoted(x, s, strlen(s));
return;
}
for (int i = 0; i < n; i++) {
+ const char *s = p[i];
+ size_t len = strlen(s);
+ if (pat)
+ s = trim(s, pat, op, &len);
if (quoted) { /* "$@": one field per parameter, even if empty */
- emit_quoted(x, p[i], strlen(p[i]));
+ emit_quoted(x, s, len);
if (i < n - 1)
field_end(x);
} else {
- emit_split(x, p[i], strlen(p[i]));
+ emit_split(x, s, len);
if (i < n - 1 && x->have) {
field_end(x);
x->sep = SEP_SPACE;
@@ -521,7 +556,7 @@ static void expand_param(expansion *x, const param *pm, bool quoted) {
if (all) {
if (pm->op == PS_NORMAL) {
- expand_all_params(x, pm->special, quoted);
+ expand_all_params(x, pm->special, quoted, nullptr, PS_NORMAL);
return;
}
val = shellparam.n ? join_params(pm->special == '*' ? ifs_first : ' ')
@@ -569,7 +604,7 @@ static void expand_param(expansion *x, const param *pm, bool quoted) {
if (all && !missing && pm->op != PS_LENGTH && pm->op < PS_TRIML) {
/* "${@-word}" with parameters set is just "$@". */
- expand_all_params(x, pm->special, quoted);
+ expand_all_params(x, pm->special, quoted, nullptr, PS_NORMAL);
return;
}
@@ -580,6 +615,13 @@ static void expand_param(expansion *x, const param *pm, bool quoted) {
return;
}
+ if (all && pm->op >= PS_TRIML) {
+ /* "${@#pat}" trims each parameter; "$@" / "$*" rules follow. */
+ expand_all_params(x, pm->special, quoted, expand_pattern(pm->arg),
+ pm->op);
+ return;
+ }
+
if (!val) {
if (opt.nounset && !all)
sh_error("%s: parameter not set", pm->name);
diff --git a/src/history.c b/src/history.c
index 011e0db..b15d6b8 100644
--- a/src/history.c
+++ b/src/history.c
@@ -291,14 +291,33 @@ static int fc_edit(const char *editor, int lo, int hi) {
break;
}
out_flush(&o);
+ if (o.err) {
+ close(fd);
+ unlink(file);
+ sh_warn("fc: write error: %s", strerror(o.err));
+ return 1;
+ }
close(fd);
- strbuf cmd;
- sb_init(&cmd, &scratch);
- sb_puts(&cmd, editor);
- sb_putc(&cmd, ' ');
- sb_puts(&cmd, file);
- int status = eval_string(sb_cstr(&cmd), 0);
+ output cmd = {.fd = OUT_MEM};
+ out_puts(&cmd, editor);
+ out_putc(&cmd, ' ');
+ out_quote(&cmd, file); /* TMPDIR may hold a space or a `$` */
+ out_write(&cmd, "", 1);
+ jmploc jl;
+ jmploc *prev = exc_handler;
+ int status;
+ if (setjmp(jl.buf)) {
+ /* The editor command raised: the file must not be left behind. */
+ exc_handler = prev;
+ free(cmd.buf);
+ unlink(file);
+ exc_raise(exc_code);
+ }
+ exc_catch(&jl);
+ status = eval_string(cmd.buf, 0);
+ exc_handler = prev;
+ free(cmd.buf);
size_t len = 0;
char *text = status == 0 ? read_file(file, &len) : nullptr;
unlink(file);
diff --git a/src/main.c b/src/main.c
index 518dc45..8b4b516 100644
--- a/src/main.c
+++ b/src/main.c
@@ -426,7 +426,7 @@ int main(int argc, char **argv) {
stack_init();
/* A parent may leave SIGCHLD ignored, and then waitpid fails with ECHILD
* for every child: reset it before anything is spawned. */
- signal(SIGCHLD, SIG_DFL);
+ trap_sig_default(SIGCHLD);
invoked_as = argv[0] ? argv[0] : "zash";
arg0 = invoked_as[0] == '-' ? invoked_as + 1 : invoked_as;
if (arg0[0] != '/' && strchr(arg0, '/')) {
diff --git a/src/parser.c b/src/parser.c
index 70bc96a..98d4c0b 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -112,14 +112,14 @@ static heredoc *here_head;
/**
* @brief Where the next pending here-document is linked.
*/
+static heredoc **here_tail = &here_head;
+
/**
* @brief The lexer is inside `[[ ]]`, where `<` and `>` are comparison
* operators, not redirections.
*/
static bool in_cond;
-static heredoc **here_tail = &here_head;
-
/**
* @brief Set by input_fill() when an alias whose value ends in a blank runs
* out: the next word is then subject to alias substitution too.
@@ -2139,6 +2139,8 @@ typedef struct parser_state {
bool tok_pushed;
heredoc *here_head;
heredoc **here_tail;
+ bool in_cond;
+ bool alias_ended_blank;
} parser_state;
static_assert(sizeof(parser_state) <= PARSER_STATE_SIZE,
@@ -2150,7 +2152,8 @@ static_assert(sizeof(parser_state) <= PARSER_STATE_SIZE,
*/
void parser_save(void *state) {
parser_state *ps = state;
- *ps = (parser_state){pa, tok, tok_pushed, here_head, here_tail};
+ *ps = (parser_state){pa, tok, tok_pushed, here_head, here_tail, in_cond,
+ alias_ended_blank};
if (here_tail == &here_head)
ps->here_tail = nullptr;
parser_reset();
@@ -2166,4 +2169,6 @@ void parser_restore(const void *state) {
tok_pushed = ps->tok_pushed;
here_head = ps->here_head;
here_tail = ps->here_tail ? ps->here_tail : &here_head;
+ in_cond = ps->in_cond;
+ alias_ended_blank = ps->alias_ended_blank;
}
diff --git a/src/pattern.c b/src/pattern.c
index 0dabc15..dded417 100644
--- a/src/pattern.c
+++ b/src/pattern.c
@@ -30,6 +30,10 @@ static int index_in(const char *set, unsigned char c) {
* alphabet. Any other range is by character code.
*/
static bool in_range(unsigned char lo, unsigned char hi, unsigned char c) {
+#if ZASH_ASCII
+ /* Code order is alphabet order here: one comparison, no table. */
+ return lo <= c && c <= hi;
+#else
static const char *const sets[] = {
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
@@ -44,6 +48,7 @@ static bool in_range(unsigned char lo, unsigned char hi, unsigned char c) {
}
}
return lo <= c && c <= hi;
+#endif
}
/**
@@ -255,7 +260,12 @@ static void glob_from(globber *g, const char *pat) {
continue;
g->path.len = dirlen;
sb_puts(&g->path, name);
- glob_from(g, rest);
+ /* readdir() already named this entry: the last component needs
+ * no lstat(), only a literal tail or a trailing `/` does. */
+ if (!*rest)
+ g->add(g->ctx, sb_cstr(&g->path));
+ else
+ glob_from(g, rest);
}
closedir(dir);
}
diff --git a/src/printf.c b/src/printf.c
index 3e33c53..fabc0b3 100644
--- a/src/printf.c
+++ b/src/printf.c
@@ -150,12 +150,23 @@ static double arg_double(printf_state *pf) {
* @param f Position in the format.
* @param spec Specification being built.
* @param n Receives the new length of `spec`.
+ * @param dot Length of `spec` before the '.' that starts this precision,
+ * or 0 when this is the width.
* @return Position in the format after the number.
*/
static const char *copy_number(printf_state *pf, const char *f, char *spec,
- size_t *n) {
+ size_t *n, size_t dot) {
if (*f == '*') {
- *n += (size_t)snprintf(spec + *n, 16, "%d", (int)arg_int(pf));
+ intmax_t v = arg_int(pf);
+ /*
+ * C99: a negative precision is as if the precision were omitted,
+ * so drop the '.' as well; a negative width is a '-' flag, which
+ * snprintf() reads from the "%*d" this writes.
+ */
+ if (dot && v < 0)
+ *n = dot;
+ else
+ *n += (size_t)snprintf(spec + *n, 24, "%jd", v);
return f + 1;
}
int digits = 0;
@@ -184,10 +195,11 @@ static const char *convert(printf_state *pf, const char *f) {
spec[n++] = *f;
f++;
}
- f = copy_number(pf, f, spec, &n);
+ f = copy_number(pf, f, spec, &n, 0);
if (*f == '.') {
+ size_t dot = n;
spec[n++] = '.';
- f = copy_number(pf, f + 1, spec, &n);
+ f = copy_number(pf, f + 1, spec, &n, dot);
}
switch (*f) {
case 'd':
@@ -228,6 +240,10 @@ static const char *convert(printf_state *pf, const char *f) {
}
case 's': {
const char *s = next_arg(pf);
+ if (n == 1) { /* a bare "%s": there is nothing to pad or truncate */
+ out_puts(&out1, s ? s : "");
+ break;
+ }
spec[n++] = 's';
spec[n] = '\0';
out_printf(&out1, spec, s ? s : "");
diff --git a/src/redir.c b/src/redir.c
index 2d328a9..edfc212 100644
--- a/src/redir.c
+++ b/src/redir.c
@@ -109,7 +109,10 @@ static int heredoc_open(const redir *r) {
}
const char *dir = var_get("TMPDIR");
char path[PATH_MAX];
- snprintf(path, sizeof path, "%s/zashXXXXXX", dir && *dir ? dir : "/tmp");
+ int n = snprintf(path, sizeof path, "%s/zashXXXXXX",
+ dir && *dir ? dir : "/tmp");
+ if (n < 0 || (size_t)n >= sizeof path) /* a TMPDIR longer than PATH_MAX */
+ return -1;
int fd = mkstemp(path);
if (fd < 0)
return -1;
diff --git a/src/trap.c b/src/trap.c
index b72c552..4e57d7c 100644
--- a/src/trap.c
+++ b/src/trap.c
@@ -132,6 +132,17 @@ static void set_handler(int sig, void (*handler)(int)) {
}
/**
+ * @brief Put a signal back to SIG_DFL.
+ *
+ * For the two places that must not inherit or keep a handler: a parent's
+ * ignored SIGCHLD (waitpid then fails with ECHILD for every child) and a
+ * pipeline child that must die on SIGPIPE.
+ *
+ * @param sig The signal.
+ */
+void trap_sig_default(int sig) { set_handler(sig, SIG_DFL); }
+
+/**
* @brief What a signal does in this shell when no trap is set for it.
*/
static void (*default_handler(int sig))(int) {
@@ -398,6 +409,19 @@ bool trap_has_exit(void) {
}
/**
+ * @brief Must something run after the last command?
+ *
+ * The EXIT trap and the ERR trap both run after the command that ends the
+ * shell, so when either is set the last command may not replace the
+ * shell: the process would be gone before the trap could run.
+ *
+ * @return true if the EXIT or the ERR trap is set.
+ */
+bool trap_after_last(void) {
+ return trap_has_exit() || trap_err_set;
+}
+
+/**
* @brief Run the EXIT trap, once.
*/
void trap_run_exit(void) {
diff --git a/src/util.c b/src/util.c
index c671d77..bdb5431 100644
--- a/src/util.c
+++ b/src/util.c
@@ -156,6 +156,8 @@ static void arena_drop_chunk(arena *a, arena_chunk *c) {
static void arena_add_chunk(arena *a, size_t need) {
size_t size = ARENA_CHUNK - sizeof(arena_chunk);
arena_chunk *c;
+ if (need > SIZE_MAX / 2) /* sizeof *c + size must not wrap */
+ out_of_memory();
if (need <= size && a->spare) {
c = a->spare;
a->spare = nullptr;
@@ -183,6 +185,8 @@ static void arena_add_chunk(arena *a, size_t need) {
* @return Uninitialised memory aligned for any object.
*/
void *arena_alloc(arena *a, size_t n) {
+ if (n > SIZE_MAX / 2) /* align_up() must not wrap */
+ out_of_memory();
n = align_up(n);
if ((size_t)(a->end - a->next) < n)
arena_add_chunk(a, n);