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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
|
/**
* @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 <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>
#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;
}
|