/** * @file util.c * @brief Heap and arena allocation, string building, buffered output, error * reporting and a few small helpers used everywhere. */ #include "shell.h" #include #include #include #include #include #include #include #include #include #include "parser.h" /* ---- heap ------------------------------------------------------------ */ /** * @brief Report that memory has run out and end the process. * * Uses write() directly: buffered output could itself need memory. */ static _Noreturn void out_of_memory(void) { static const char msg[] = "zash: out of memory\n"; (void)!write(2, msg, sizeof msg - 1); _exit(2); } /** * @brief Allocate memory. Never returns NULL. * @param n Bytes wanted (0 is treated as 1). * @return The block. The shell exits if memory is exhausted. */ void *xmalloc(size_t n) { void *p = malloc(n ? n : 1); if (!p) out_of_memory(); return p; } /** * @brief Resize a heap block. Never returns NULL. * @param p Block from xmalloc(), or NULL. * @param n New size in bytes. * @return The resized block. The shell exits if memory is exhausted. */ void *xrealloc(void *p, size_t n) { p = realloc(p, n ? n : 1); if (!p) out_of_memory(); return p; } /** * @brief Copy a string to the heap. * @param s NUL-terminated string. * @return A copy the caller frees. */ char *xstrdup(const char *s) { size_t n = strlen(s) + 1; return memcpy(xmalloc(n), s, n); } /* ---- stack depth ----------------------------------------------------- */ /** * @brief Address of a local variable in main(): where the stack starts. */ uintptr_t stack_base; /** * @brief How much stack recursion may use before stack_low() says stop. */ size_t stack_budget; /** * @brief Record where the stack starts and how much of it may be used. * * Call early in main(). The budget is half of the stack size the system * allows (RLIMIT_STACK), capped at 32 MB, so that the "nested too deeply" * error is raised long before the real limit. */ void stack_init(void) { const size_t fallback = (size_t)8 << 20; const size_t most = (size_t)64 << 20; struct rlimit rl; size_t limit = fallback; if (getrlimit(RLIMIT_STACK, &rl) == 0 && rl.rlim_cur != RLIM_INFINITY && rl.rlim_cur > 0) limit = (size_t)rl.rlim_cur; if (limit > most) limit = most; stack_base = (uintptr_t)__builtin_frame_address(0); stack_budget = limit / 2; } /* ---- arenas ---------------------------------------------------------- */ /** * @brief Alignment of every arena allocation. */ #define ARENA_ALIGN ((size_t)8) /** * @brief Size of an ordinary arena chunk, header included. */ #define ARENA_CHUNK ((size_t)4096) /** * @brief Header of one block of arena memory. The usable bytes follow it. */ typedef struct arena_chunk { struct arena_chunk *prev; char *end; } arena_chunk; /** * @brief The scratch arena: per-command temporaries, used as a stack. */ arena scratch; /** * @brief Round a size up to the arena alignment. */ static size_t align_up(size_t n) { return (n + ARENA_ALIGN - 1) & ~(size_t)(ARENA_ALIGN - 1); } /** * @brief Release a chunk the arena no longer needs. * * One ordinary-sized chunk is kept in `a->spare` instead of being freed. * Without it, a loop whose body happens to straddle a chunk boundary would * malloc() and free() a chunk on every iteration. * * @param a The arena. * @param c The chunk, already unlinked from the arena. */ static void arena_drop_chunk(arena *a, arena_chunk *c) { if (!a->spare && c->end - (char *)c == (ptrdiff_t)ARENA_CHUNK) a->spare = c; else free(c); } /** * @brief Start a new chunk with room for at least `need` bytes. * @param a The arena. * @param need Bytes the caller is about to allocate. */ static void arena_add_chunk(arena *a, size_t need) { size_t size = ARENA_CHUNK - sizeof(arena_chunk); arena_chunk *c; if (need <= size && a->spare) { c = a->spare; a->spare = NULL; } else { if (size < need) size = need; c = xmalloc(sizeof *c + size); } c->prev = a->head; c->end = (char *)(c + 1) + size; a->head = c; a->next = (char *)(c + 1); a->end = c->end; } /** * @brief Allocate from an arena. * * This is a pointer bump in the common case. Memory is not freed * individually: it goes away with arena_release(), arena_reset() or * arena_unref(). * * @param a The arena. * @param n Bytes wanted. * @return Uninitialised memory aligned for any object. */ void *arena_alloc(arena *a, size_t n) { n = align_up(n); if ((size_t)(a->end - a->next) < n) arena_add_chunk(a, n); void *p = a->next; a->next += n; return p; } /** * @brief Resize an arena allocation. * * If `p` is the most recent allocation and the chunk has room, it grows in * place. This is what makes appending to a strbuf cheap. Otherwise a new * block is allocated and the old contents copied. * * @param a The arena. * @param p Existing block, or NULL. * @param oldn Its size. * @param newn Size wanted. * @return The block, possibly moved. */ void *arena_grow(arena *a, void *p, size_t oldn, size_t newn) { size_t olda = align_up(oldn); size_t newa = align_up(newn); if (p && (char *)p + olda == a->next && newa - olda <= (size_t)(a->end - a->next)) { a->next += newa - olda; return p; } void *q = arena_alloc(a, newn); if (oldn) memcpy(q, p, oldn); return q; } /** * @brief Copy `n` bytes of a string into an arena and NUL-terminate the copy. * @param a The arena. * @param s Source bytes. * @param n How many to copy. * @return The copy. */ char *arena_strndup(arena *a, const char *s, size_t n) { char *p = arena_alloc(a, n + 1); memcpy(p, s, n); p[n] = '\0'; return p; } /** * @brief Free everything allocated since a mark was taken. * * This is how `scratch` works as a stack: take arena_mark(), allocate * freely, release. * * @param a The arena. * @param m A mark from arena_mark() on the same arena. */ void arena_release(arena *a, arena_marker m) { while (a->head != m.chunk) { arena_chunk *c = a->head; a->head = c->prev; arena_drop_chunk(a, c); } a->next = m.next; a->end = a->head ? a->head->end : NULL; } /** * @brief Create an empty arena with one reference. * @return The arena. Drop it with arena_unref(). */ arena *arena_new(void) { arena *a = xmalloc(sizeof *a); *a = (arena){.refs = 1}; return a; } /** * @brief Empty an arena but keep its first chunk for reuse. * @param a The arena. */ void arena_reset(arena *a) { if (!a->head) return; while (a->head->prev) { arena_chunk *c = a->head; a->head = c->prev; arena_drop_chunk(a, c); } a->next = (char *)(a->head + 1); a->end = a->head->end; } /** * @brief Drop a reference to an arena and free it when none remain. * * Parse trees are reference counted this way: a function definition takes * a reference to the arena that holds its body. * * @param a The arena. */ void arena_unref(arena *a) { if (--a->refs > 0) return; arena_release(a, (arena_marker){NULL, NULL}); free(a->spare); free(a); } /* ---- string builder -------------------------------------------------- */ /** * @brief Make room in a string builder. * @param b The builder. * @param extra Bytes about to be appended. Room for a NUL is added. */ void sb_reserve(strbuf *b, size_t extra) { size_t need = b->len + extra + 1; if (need <= b->cap) return; size_t cap = b->cap ? b->cap * 2 : 32; if (cap < need) cap = need; b->s = arena_grow(b->a, b->s, b->cap, cap); b->cap = cap; } /** * @brief Append bytes to a string builder. * @param b The builder. * @param s Bytes to append. May be NULL when `n` is 0. * @param n How many. */ void sb_put(strbuf *b, const char *s, size_t n) { if (!n) return; /* `s` may be null: memcpy(p, NULL, 0) is undefined */ sb_reserve(b, n); memcpy(b->s + b->len, s, n); b->len += n; } /** * @brief Append a NUL-terminated string to a string builder. * @param b The builder. * @param s The string. */ void sb_puts(strbuf *b, const char *s) { sb_put(b, s, strlen(s)); } /* ---- output ---------------------------------------------------------- */ /** * @brief Buffer behind standard output. */ static char out1_buf[4096]; /** * @brief Buffer behind standard error (flushed after every message). */ static char out2_buf[512]; /** * @brief Where builtins write their output. Normally descriptor 1. */ output out1 = {out1_buf, 0, sizeof out1_buf, 1, 0}; /** * @brief Where messages and prompts go. Normally descriptor 2. */ output out2 = {out2_buf, 0, sizeof out2_buf, 2, 0}; /** * @brief Write out whatever an output has buffered. * * A write error is remembered in `o->err` (the first one wins) rather than * reported here. The caller decides whether it matters. Does nothing for * an in-memory output. * * @param o The output. */ void out_flush(output *o) { if (o->fd == OUT_MEM) return; const char *p = o->buf; size_t left = o->len; o->len = 0; while (left) { ssize_t n = write(o->fd, p, left); if (n < 0) { if (errno == EINTR) continue; if (!o->err) o->err = errno; return; } p += n; left -= (size_t)n; } } /** * @brief Append bytes to an output. * * For an in-memory output (`fd == OUT_MEM`) the heap buffer grows. For a * descriptor the bytes are buffered, and a block larger than the buffer is * written directly. * * @param o The output. * @param s Bytes to write. * @param n How many. */ void out_write(output *o, const char *s, size_t n) { if (!n) return; if (o->fd == OUT_MEM) { if (o->cap - o->len < n) { size_t cap = o->cap ? o->cap * 2 : 256; if (cap < o->len + n) cap = o->len + n; o->buf = xrealloc(o->buf, cap); o->cap = cap; } } else if (o->cap - o->len < n) { out_flush(o); if (n >= o->cap) { /* too big to buffer: write it straight out */ output direct = {(char *)s, n, n, o->fd, o->err}; out_flush(&direct); o->err = direct.err; return; } } memcpy(o->buf + o->len, s, n); o->len += n; } /** * @brief Append a NUL-terminated string to an output. * @param o The output. * @param s The string. */ void out_puts(output *o, const char *s) { out_write(o, s, strlen(s)); } /** * @brief Formatted output to an output, `vprintf` style. * @param o The output. * @param fmt printf() format. * @param ap Arguments. */ static void out_vprintf(output *o, const char *fmt, va_list ap) { char small[256]; va_list ap2; va_copy(ap2, ap); int n = vsnprintf(small, sizeof small, fmt, ap); if (n < 0) { va_end(ap2); return; } if ((size_t)n < sizeof small) { out_write(o, small, (size_t)n); } else { char *big = xmalloc((size_t)n + 1); vsnprintf(big, (size_t)n + 1, fmt, ap2); out_write(o, big, (size_t)n); free(big); } va_end(ap2); } /** * @brief Formatted output to an output, `printf` style. * @param o The output. * @param fmt printf() format. */ void out_printf(output *o, const char *fmt, ...) { va_list ap; va_start(ap, fmt); out_vprintf(o, fmt, ap); va_end(ap); } /** * @brief Write a string so that the shell would read it back as one word. * * Text made only of safe characters is written as is. Anything else is * wrapped in single quotes. * * @param o The output. * @param s The string. */ void out_quote(output *o, const char *s) { const char *p = s; while (isalnum((unsigned char)*p) || (*p && strchr("_/.-+,:=@%", *p))) p++; if (*s && !*p) { out_puts(o, s); return; } out_putc(o, '\''); for (; *s; s++) { if (*s == '\'') out_puts(o, "'\\''"); else out_putc(o, *s); } out_putc(o, '\''); } /** * @brief Flush standard output and standard error. * * Called before anything that creates a process or replaces the shell, so * that buffered text is not lost or written twice. */ void flush_all(void) { out_flush(&out1); out_flush(&out2); } /* ---- errors ---------------------------------------------------------- */ /** * @brief Where exc_raise() jumps to: the innermost active handler. */ jmploc *exc_handler; /** * @brief The exception being propagated (EXC_ERROR or EXC_EXIT). */ int exc_code; /** * @brief `$?`: exit status of the last command. */ int exitstatus; /** * @brief Raise a shell exception. * * Control passes to the innermost handler installed in #exc_handler. With * no handler the shell exits. * * @param exc EXC_ERROR or EXC_EXIT. */ void exc_raise(int exc) { if (!exc_handler) exit_shell(exitstatus); exc_code = exc; longjmp(exc_handler->buf, exc); } /** * @brief Derive a message number from a message's format string. * * `set -o msgid` puts an identifier such as `ZSH4711E` in front of every * diagnostic, which is what automation and SYSLOG filters on z/OS key * on. The number is a hash of the format string, so no table has to be * kept in step with the messages. It changes only if the wording does. * Characters are hashed by their position in the portable character set * (not by code point), so ASCII and EBCDIC builds give the same number. * * @param fmt The printf() format of the message. * @return A number from 1000 to 9999. */ static unsigned message_number(const char *fmt) { static const char alphabet[] = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" "abcdefghijklmnopqrstuvwxyz{|}~"; unsigned h = 2166136261u; for (; *fmt; fmt++) { const char *at = strchr(alphabet, *fmt); h = (h ^ (at ? (unsigned)(at - alphabet) + 1 : 0)) * 16777619u; } return 1000 + h % 9000; } /** * @brief Print a message on standard error, prefixed with the shell's name and, * in a script, the current line number. * @param fmt printf() format. * @param ap Arguments. * @param severity 'W' for a warning, 'E' for an error. */ static void vwarn(const char *fmt, va_list ap, char severity) { out_flush(&out1); if (opt.msgid) out_printf(&out2, "ZSH%u%c ", message_number(fmt), severity); out_puts(&out2, arg0 ? arg0 : "zash"); if (!opt.interactive && cur_lineno > 0) out_printf(&out2, ": line %d", cur_lineno); out_puts(&out2, ": "); out_vprintf(&out2, fmt, ap); out_putc(&out2, '\n'); out_flush(&out2); } /** * @brief Report a problem and carry on. * * Regular builtins use this and return a non-zero status. * * @param fmt printf() format. */ void sh_warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarn(fmt, ap, 'W'); va_end(ap); } /** * @brief Report an error that aborts the current command. * * Sets `$?` to 2 and raises EXC_ERROR: a non-interactive shell exits, an * interactive one returns to the prompt. * * @param fmt printf() format. */ void sh_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarn(fmt, ap, 'E'); va_end(ap); exitstatus = 2; exc_raise(EXC_ERROR); } /* ---- miscellany ------------------------------------------------------ */ /** * @brief Length of the variable name at the start of a string. * @param s Text. * @return Number of bytes that form a valid name. 0 if there is none. */ size_t name_len(const char *s) { const char *p = s; if (!isalpha((unsigned char)*p) && *p != '_') return 0; while (isalnum((unsigned char)*p) || *p == '_') p++; return (size_t)(p - s); } /** * @brief Is the whole string a valid variable name? */ bool is_name(const char *s) { size_t n = name_len(s); return n && !s[n]; } /** * @brief Convert a decimal string to a number, strictly. * @param s Text. The whole of it must be a number. * @param out Receives the value. * @return false if `s` is not a number or does not fit. */ bool parse_long(const char *s, long *out) { char *end; errno = 0; long v = strtol(s, &end, 10); if (end == s || *end || errno) return false; *out = v; return true; } /** * @brief Format an integer in decimal. * * Hand-written because snprintf("%jd") costs more than the arithmetic * whose result it prints, and the shell formats numbers constantly. * * @param v The value. * @param buf Work space. The digits are written at its end. * @return Pointer to the first character, inside `buf`. */ char *fmt_int(intmax_t v, char buf[static INT_BUFSZ]) { char *p = buf + INT_BUFSZ - 1; uintmax_t u = v < 0 ? -(uintmax_t)v : (uintmax_t)v; *p = '\0'; do { *--p = (char)('0' + u % 10); u /= 10; } while (u); if (v < 0) *--p = '-'; return p; }