/** * @file shell.h * @brief Things every module needs: memory, strings, output, errors, the stack * guard, options and shared globals. */ #ifndef ZASH_SHELL_H #define ZASH_SHELL_H #include #include #include #include #include #if defined(__GNUC__) || defined(__clang__) /** * @brief Mark a function as taking a printf() format, so the compiler checks * calls. `f` is the format's argument number and `a` the first value's. */ #define PRINTFLIKE(f, a) __attribute__((format(printf, f, a))) #else #define PRINTFLIKE(f, a) #endif /** * @brief Warn if a function's result is ignored (GCC and Clang). */ #define NODISCARD [[nodiscard]] /** * @brief Keep a function out of line (a cold path that would otherwise * be inlined into, and pessimise, a hot one). */ #if defined(__GNUC__) #define NOINLINE __attribute__((noinline)) #else #define NOINLINE #endif /** * @brief Mark a deliberate fall into the next `case`. */ #define FALLTHROUGH [[fallthrough]] /** * @brief Tell the compiler that control cannot reach this point. */ #if defined(__GNUC__) #define UNREACHABLE() __builtin_unreachable() #else #define UNREACHABLE() abort() #endif /** * @brief Write out coverage counters. A no-op in a normal build. * * The shell leaves through _exit() and execve(), which skip the atexit * handler that normally saves coverage data, so a coverage build * (`make coverage`) saves it explicitly at those points. */ #ifdef ZASH_COVERAGE #include /* declare the real _exit() before it is wrapped */ void __gcov_dump(void); #define COVERAGE_FLUSH() __gcov_dump() #define _exit(code) (__gcov_dump(), (_exit)(code)) #else #define COVERAGE_FLUSH() ((void)0) #endif /** * @brief Number of elements in an array. */ #define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) /* ---- heap ------------------------------------------------------------ */ void *xmalloc(size_t n); void *xrealloc(void *p, size_t n); char *xstrdup(const char *s); /* ---- arenas ---------------------------------------------------------- */ /* * A bump allocator. `scratch` holds expansion results and other per-command * temporaries and is used as a stack: take a mark, allocate, release. Parse * trees live in reference-counted arenas of their own so that a function * body can outlive the command that defined it without being copied. */ typedef struct arena_chunk arena_chunk; /** * @brief A bump allocator. * * Memory is handed out by advancing a pointer and is freed all at once. * `scratch` holds expansion results and other per-command temporaries and * is used as a stack: take a mark, allocate, release. Parse trees live in * reference-counted arenas of their own so that a function body can * outlive the command that defined it without being copied. */ typedef struct arena { arena_chunk *head; arena_chunk *spare; /**< one released chunk, kept for reuse */ char *next; char *end; int refs; } arena; /** * @brief A position in an arena, for arena_release(). */ typedef struct arena_marker { arena_chunk *chunk; char *next; } arena_marker; extern arena scratch; arena *arena_new(void); void arena_unref(arena *a); void arena_reset(arena *a); void *arena_alloc(arena *a, size_t n); void *arena_grow(arena *a, void *p, size_t oldn, size_t newn); char *arena_strndup(arena *a, const char *s, size_t n); void arena_release(arena *a, arena_marker m); /** * @brief Remember the current position of an arena. * @param a The arena. * @return A mark to pass to arena_release(). */ static inline arena_marker arena_mark(const arena *a) { return (arena_marker){a->head, a->next}; } /* ---- string builder (arena backed) ----------------------------------- */ /** * @brief A growing string whose storage comes from an arena. */ typedef struct strbuf { arena *a; char *s; size_t len; size_t cap; } strbuf; void sb_reserve(strbuf *b, size_t extra); void sb_put(strbuf *b, const char *s, size_t n); void sb_puts(strbuf *b, const char *s); /** * @brief Start an empty string builder. * @param b The builder. * @param a Arena its storage comes from. */ static inline void sb_init(strbuf *b, arena *a) { b->a = a; b->s = nullptr; b->len = b->cap = 0; } /** * @brief Append one byte to a string builder. */ static inline void sb_putc(strbuf *b, char c) { if (b->len + 1 >= b->cap) sb_reserve(b, 1); b->s[b->len++] = c; } /** * @brief NUL-terminate a string builder and return its text. * * The builder may still be appended to afterwards. */ static inline char *sb_cstr(strbuf *b) { if (b->len >= b->cap) sb_reserve(b, 0); b->s[b->len] = '\0'; return b->s; } /* ---- output ---------------------------------------------------------- */ /** * @brief Value of output::fd for an output that collects in memory. */ #define OUT_MEM (-2) /** * @brief A buffered output stream. * * Builtins never write to a file descriptor directly. They write to #out1 * and #out2. That lets a builtin's output be captured in memory or * pointed at a pipe without forking and without touching the real * descriptor table. */ typedef struct output { char *buf; size_t len; size_t cap; int fd; /**< OUT_MEM: grow `buf` on the heap instead of writing */ int err; /**< errno of the first failed write, or 0 */ } output; extern output out1; extern output out2; void out_write(output *o, const char *s, size_t n); void out_puts(output *o, const char *s); void out_printf(output *o, const char *fmt, ...) PRINTFLIKE(2, 3); void out_quote(output *o, const char *s); void out_flush(output *o); void flush_all(void); /** * @brief Append one byte to an output. */ static inline void out_putc(output *o, char c) { out_write(o, &c, 1); } /* ---- errors ---------------------------------------------------------- */ /** * @brief Kinds of shell exception: an error that aborts the current command, * and a request to exit the shell. */ enum { EXC_ERROR = 1, EXC_EXIT }; /** * @brief A place exc_raise() can jump to. Set with setjmp(jl.buf). */ typedef struct jmploc { jmp_buf buf; } jmploc; extern jmploc *exc_handler; extern int exc_code; /**< the exception being propagated */ extern int exitstatus; [[noreturn]] void exc_raise(int exc); [[noreturn]] void sh_error(const char *fmt, ...) PRINTFLIKE(1, 2); void sh_warn(const char *fmt, ...) PRINTFLIKE(1, 2); [[noreturn]] void exit_shell(int status); /* ---- stack depth ----------------------------------------------------- */ /* * Recursion (functions, eval, nested commands and expansions) is bounded * by how much stack is actually in use rather than by a count, because * frame sizes differ widely between platforms and build types. When * stack_low() is true the caller reports an error instead of recursing. */ extern uintptr_t stack_base; extern size_t stack_budget; void stack_init(void); /** * @brief Is the stack nearly used up? * * Recursion (functions, `eval`, nested commands and expansions) is bounded * by how much stack is actually in use rather than by a count, because * frame sizes differ widely between platforms and build types. When this * returns true the caller reports "nested too deeply" instead of recursing. */ static inline bool stack_low(void) { uintptr_t here = (uintptr_t)__builtin_frame_address(0); uintptr_t used = here < stack_base ? stack_base - here : here - stack_base; return used > stack_budget; } /* ---- options --------------------------------------------------------- */ /** * @brief The shell options (`set -o`, `$-`). */ typedef struct options { bool allexport; /**< -a */ bool noclobber; /**< -C */ bool errexit; /**< -e */ bool noglob; /**< -f */ bool interactive; /**< -i */ bool monitor; /**< -m: job control */ bool noexec; /**< -n */ bool stdin_cmds; /**< -s */ bool nounset; /**< -u */ bool verbose; /**< -v */ bool xtrace; /**< -x */ bool pipefail; /**< -o pipefail */ bool jobnames; /**< -o jobnames: _BPX_JOBNAME per command (z/OS) */ bool shareas; /**< -o shareas: foreground commands share the shell's address space (z/OS) */ bool msgid; /**< -o msgid: message IDs on diagnostics */ bool pipetag; /**< -o pipetag: tag pipes IBM-1047 (z/OS, ASCII) */ bool notify; /**< -b (accepted; jobs are reported at the prompt) */ bool trackall; /**< -h (accepted; command paths are always hashed) */ bool ignoreeof; /**< -o ignoreeof: ^D does not leave the shell */ bool nolog; /**< -o nolog (accepted) */ bool emacs; /**< -E, -o emacs: emacs-style line editing */ bool vi; /**< -V, -o vi: vi-style line editing */ } options; /** * @brief Current option settings. */ extern options opt; bool option_set_letter(int letter, bool on); bool option_set_name(const char *name, bool on); int option_is_set(const char *name); void options_print(bool as_commands); const char *option_letters(void); int parse_set_options(int argc, char **argv, bool *set_params); /* ---- miscellany ------------------------------------------------------ */ /** * @brief `$0`. */ extern const char *arg0; /**< $0 */ extern int cur_lineno; /**< line of the command being executed */ extern bool in_subshell; /**< running in a forked copy of the shell */ extern long stat_spawns; /**< processes created with spawn */ extern long stat_forks; /**< processes created with fork */ pid_t shell_pid(void); /* $$: pid of the original shell */ const char *shell_path(void); /* path used to re-run the shell on scripts */ /** * @brief Is `c` a decimal digit? * * Digits are contiguous in ASCII and in EBCDIC, so is not * needed. */ static inline bool is_digit(char c) { return c >= '0' && c <= '9'; } /** * @brief Buffer size that fmt_int() needs: any 64-bit number, sign and NUL. */ #define INT_BUFSZ ((size_t)24) char *fmt_int(intmax_t v, char buf[static INT_BUFSZ]); bool is_name(const char *s); size_t name_len(const char *s); bool parse_long(const char *s, long *out); #endif