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
|
/**
* @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 <setjmp.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#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).
*/
#if defined(__GNUC__)
#define NODISCARD __attribute__((warn_unused_result))
#else
#define NODISCARD
#endif
/**
* @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`.
*/
#if defined(__GNUC__)
#define FALLTHROUGH __attribute__((fallthrough))
#else
#define FALLTHROUGH ((void)0)
#endif
/**
* @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 <unistd.h> /* 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 = NULL;
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 <ctype.h> 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
|