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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
|
/**
* @file expand.c
* @brief Word expansion.
*
* A word's parts are expanded in one pass. In field mode each output
* byte is recorded as quoted or unquoted in a parallel mask, which is all
* that field splitting and pathname expansion need to know. The text
* itself never carries quoting marks, so it is safe in any character set.
*/
#include "expand.h"
#include <inttypes.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "exec.h"
#include "shell.h"
#include "var.h"
/**
* @brief What an expansion is producing.
*/
typedef enum xmode {
X_FIELDS, /**< command arguments: split and glob */
X_SINGLE, /**< one string, quotes removed */
X_PATTERN /**< one string, quoted characters backslash-escaped */
} xmode;
/**
* @brief What ended the previous field, which decides whether a following IFS
* delimiter creates an empty field.
*/
typedef enum sepstate { SEP_NONE, SEP_SPACE, SEP_HARD } sepstate;
/**
* @brief State of one expansion.
*/
typedef struct expansion {
xmode mode;
strbuf text;
strbuf mask; /**< X_FIELDS: 1 where the byte is unquoted */
bool have; /**< a field is in progress (it may be empty) */
bool glob; /**< ... and contains an unquoted * ? or [ */
sepstate sep; /**< what ended the previous field */
int arg_depth; /**< inside the word of an unquoted ${x-word} */
char **argv;
int argc;
int cap;
} expansion;
static void expand_parts(expansion *x, const wpart *p);
/**
* @brief The empty field, shared.
*/
static const char empty_string[] = "";
/**
* @brief Append a finished field to the argument vector.
* @param x Expansion state.
* @param s The field (scratch memory), or NULL to terminate the vector.
*/
static void field_add(expansion *x, const char *s) {
if (x->argc + 1 >= x->cap) {
int cap = x->cap ? x->cap * 2 : 16;
x->argv =
arena_grow(&scratch, x->argv, (size_t)x->cap * sizeof *x->argv,
(size_t)cap * sizeof *x->argv);
x->cap = cap;
}
x->argv[x->argc++] = (char *)s;
}
/**
* @brief glob_expand() callback: add one matching path as a field.
*/
static void glob_add(void *ctx, const char *path) {
field_add(ctx, arena_strndup(&scratch, path, strlen(path)));
}
/**
* @brief qsort() comparison of two strings.
*/
static int cmp_str(const void *a, const void *b) {
return strcmp(*(char *const *)a, *(char *const *)b);
}
/**
* @brief Is `c` special in a pattern, so that a quoted one must be escaped?
*/
static bool is_pattern_char(char c) {
return c == '*' || c == '?' || c == '[' || c == ']' || c == '\\' ||
c == '!' || c == '^' || c == '-';
}
/**
* @brief Pathname-expand a finished field, or keep it if nothing matches.
*
* Quoted bytes are backslash-escaped first so that only unquoted pattern
* characters are active. Matches are sorted.
*
* @param x Expansion state.
* @param s The field's text.
*/
static void glob_field(expansion *x, const char *s) {
strbuf pat;
sb_init(&pat, &scratch);
for (size_t i = 0; i < x->text.len; i++) {
if (!x->mask.s[i] && is_pattern_char(s[i]))
sb_putc(&pat, '\\');
sb_putc(&pat, s[i]);
}
int before = x->argc;
glob_expand(sb_cstr(&pat), glob_add, x);
if (x->argc == before)
field_add(x, s);
else
qsort(x->argv + before, (size_t)(x->argc - before), sizeof *x->argv,
cmp_str);
}
/**
* @brief Is the field really a pattern?
*
* An unquoted `[` only starts a bracket expression if an unquoted `]`
* follows, so the test command `[` and words like `a[1` are spared a
* pointless directory scan.
*/
static bool worth_globbing(const expansion *x) {
const char *s = x->text.s;
const char *m = x->mask.s;
bool open = false;
for (size_t i = 0; i < x->text.len; i++) {
if (!m[i])
continue;
if (s[i] == '*' || s[i] == '?' || (open && s[i] == ']'))
return true;
open |= s[i] == '[';
}
return false;
}
/**
* @brief Finish the field in progress: glob it if it is a pattern, add it to
* the result, and start a new one.
*/
static void field_end(expansion *x) {
const char *s = sb_cstr(&x->text);
if (x->glob && !opt.noglob && worth_globbing(x))
glob_field(x, s);
else
field_add(x, s);
sb_init(&x->text, &scratch);
sb_init(&x->mask, &scratch);
x->have = false;
x->glob = false;
}
/**
* @brief Append bytes to the field in progress, recording whether they are
* quoted.
* @param x Expansion state.
* @param s Bytes.
* @param n How many.
* @param unquoted Whether they take part in splitting and globbing.
*/
static void put_field_bytes(expansion *x, const char *s, size_t n,
bool unquoted) {
sb_put(&x->text, s, n);
sb_reserve(&x->mask, n);
memset(x->mask.s + x->mask.len, unquoted, n);
x->mask.len += n;
x->have = true;
x->sep = SEP_NONE;
if (unquoted && !x->glob) {
for (size_t i = 0; i < n; i++) {
if (s[i] == '*' || s[i] == '?' || s[i] == '[') {
x->glob = true;
break;
}
}
}
}
/**
* @brief Emit text that came from inside quotes: never split or globbed.
*
* In pattern mode its pattern characters are escaped so that they match
* themselves.
*/
static void emit_quoted(expansion *x, const char *s, size_t n) {
switch (x->mode) {
case X_FIELDS:
put_field_bytes(x, s, n, false);
break;
case X_SINGLE:
sb_put(&x->text, s, n);
break;
case X_PATTERN:
for (size_t i = 0; i < n; i++) {
if (is_pattern_char(s[i]))
sb_putc(&x->text, '\\');
sb_putc(&x->text, s[i]);
}
break;
}
}
/**
* @brief Emit the unquoted result of an expansion.
*
* In field mode it is split at IFS characters as it goes: white-space
* delimiters merge, and other delimiters each end a field.
*/
static void emit_split(expansion *x, const char *s, size_t n) {
if (x->mode != X_FIELDS) {
sb_put(&x->text, s, n);
return;
}
size_t i = 0;
while (i < n) {
unsigned char cls = ifs_class[(unsigned char)s[i]];
if (cls == IFS_NONE) {
size_t j = i + 1;
while (j < n && ifs_class[(unsigned char)s[j]] == IFS_NONE)
j++;
put_field_bytes(x, s + i, j - i, true);
i = j;
continue;
}
if (x->have) {
field_end(x);
x->sep = cls == IFS_SPACE ? SEP_SPACE : SEP_HARD;
} else if (cls == IFS_HARD) {
/* A second delimiter in a row makes an empty field, unless
* the first was only white space. */
if (x->sep != SEP_SPACE)
field_add(x, empty_string);
x->sep = SEP_HARD;
}
i++;
}
}
/**
* @brief Emit unquoted text that was written literally in the script.
*
* Literal text is not field-split, except inside the word of an unquoted
* `${x-word}`.
*/
static void emit_lit(expansion *x, const char *s, size_t n) {
if (x->mode != X_FIELDS)
sb_put(&x->text, s, n);
else if (x->arg_depth)
emit_split(x, s, n);
else
put_field_bytes(x, s, n, true);
}
/**
* @brief Emit text as quoted or unquoted.
*/
static void emit(expansion *x, const char *s, size_t n, bool quoted) {
if (quoted)
emit_quoted(x, s, n);
else
emit_split(x, s, n);
}
/* ---- tilde ----------------------------------------------------------- */
/**
* @brief Expand a tilde-prefix.
*
* @param x Expansion state.
* @param s Text starting with `~`.
* @param n Length of `s`.
* @param assign In an assignment, where `:` also ends the prefix.
* @param last No more parts follow, so the prefix may run to the end.
* @return How many bytes of `s` were replaced, or 0 if there is nothing to
* expand (unknown user, or the prefix is cut short by a quote).
*/
static size_t expand_tilde(expansion *x, const char *s, size_t n, bool assign,
bool last) {
size_t e = 1;
while (e < n && s[e] != '/' && !(assign && s[e] == ':'))
e++;
if (e == n && !last)
return 0;
const char *home;
if (e == 1) {
home = var_get("HOME");
} else {
const struct passwd *pw =
getpwnam(arena_strndup(&scratch, s + 1, e - 1));
home = pw ? pw->pw_dir : NULL;
}
if (!home)
return 0;
emit_quoted(x, home, strlen(home));
return e;
}
/**
* @brief Emit an unquoted literal of an assignment value, expanding `~` after
* the `=` and after each `:` (as in `PATH=~/bin:~/sbin`).
* @param x Expansion state.
* @param s The literal.
* @param n Its length.
* @param at_start It directly follows the `=`.
* @param last It is the last part of the word.
*/
static void emit_assign_lit(expansion *x, const char *s, size_t n,
bool at_start, bool last) {
size_t i = 0;
bool may_start = at_start;
while (i < n) {
if (may_start && s[i] == '~') {
size_t used = expand_tilde(x, s + i, n - i, true, last);
if (used) {
i += used;
may_start = false;
continue;
}
}
size_t j = i;
while (j < n && s[j] != ':')
j++;
if (j < n)
j++; /* include the colon */
sb_put(&x->text, s + i, j - i);
may_start = j > i && s[j - 1] == ':';
i = j;
}
}
/* ---- parameters ------------------------------------------------------ */
/**
* @brief Join the positional parameters into one string.
* @param sep Separator, or NUL for none.
* @return The joined string, in scratch memory.
*/
static const char *join_params(char sep) {
strbuf sb;
sb_init(&sb, &scratch);
for (int i = 0; i < shellparam.n; i++) {
if (i && sep)
sb_putc(&sb, sep);
sb_puts(&sb, shellparam.p[i]);
}
return sb_cstr(&sb);
}
/**
* @brief Expand `$@` or `$*` with no operator.
*
* `"$@"` gives one field per parameter, even an empty one. `"$*"` gives
* one field joined with the first character of IFS. Unquoted, both are
* split.
* @param x Expansion state.
* @param which `@` or `*`.
* @param quoted Whether the expansion is inside double quotes.
*/
static void expand_all_params(expansion *x, char which, bool quoted) {
int n = shellparam.n;
char **p = shellparam.p;
if (x->mode != X_FIELDS) {
const char *s = join_params(which == '*' ? ifs_first : ' ');
emit(x, s, strlen(s), quoted);
return;
}
if (quoted && which == '*') {
const char *s = join_params(ifs_first);
emit_quoted(x, s, strlen(s));
return;
}
for (int i = 0; i < n; i++) {
if (quoted) { /* "$@": one field per parameter, even if empty */
emit_quoted(x, p[i], strlen(p[i]));
if (i < n - 1)
field_end(x);
} else {
emit_split(x, p[i], strlen(p[i]));
if (i < n - 1 && x->have) {
field_end(x);
x->sep = SEP_SPACE;
}
}
}
}
/**
* @brief Value of a special parameter (`$?`, `$$`, `$#`, `$!`, `$-`).
* @param c The parameter character.
* @param buf Work space for numbers.
* @param size Size of `buf`.
* @return The value, or NULL if it is unset (`$!` before any `&`).
*/
static const char *special_value(char c, char *buf, size_t size) {
switch (c) {
case '?':
return fmt_int(exitstatus, buf);
case '$':
snprintf(buf, size, "%ld", (long)shell_pid());
return buf;
case '#':
return fmt_int(shellparam.n, buf);
case '!':
if (!last_bg_pid)
return NULL;
snprintf(buf, size, "%ld", (long)last_bg_pid);
return buf;
case '-':
return option_letters();
default:
return NULL;
}
}
/**
* @brief Current value of a parameter of any kind.
* @return The value, or NULL if the parameter is unset.
*/
static const char *param_value(const param *pm, char *buf, size_t size) {
switch (pm->type) {
case PT_VAR:
return var_get_n(pm->name, pm->nlen);
case PT_POS:
if (pm->pos == 0)
return arg0;
return pm->pos <= shellparam.n ? shellparam.p[pm->pos - 1] : NULL;
case PT_SPECIAL:
return special_value(pm->special, buf, size);
}
return NULL;
}
/**
* @brief Remove the prefix or suffix of a value that matches a pattern
* (`${x#p}`, `${x##p}`, `${x%p}`, `${x%%p}`).
* @param val The value.
* @param pat The pattern.
* @param op Which of the four operators.
* @param lenp Receives the length of the result.
* @return Start of the result within `val`.
*/
static const char *trim(const char *val, const char *pat, param_op op,
size_t *lenp) {
size_t n = strlen(val);
const char *end = val + n;
*lenp = n;
switch (op) {
case PS_TRIML:
for (size_t i = 0; i <= n; i++) {
if (pat_match(pat, val, val + i)) {
*lenp = n - i;
return val + i;
}
}
break;
case PS_TRIMLL:
for (size_t i = n + 1; i-- > 0;) {
if (pat_match(pat, val, val + i)) {
*lenp = n - i;
return val + i;
}
}
break;
case PS_TRIMR:
for (size_t i = n + 1; i-- > 0;) {
if (pat_match(pat, val + i, end)) {
*lenp = i;
return val;
}
}
break;
case PS_TRIMRR:
for (size_t i = 0; i <= n; i++) {
if (pat_match(pat, val + i, end)) {
*lenp = i;
return val;
}
}
break;
default:
break;
}
return val;
}
/**
* @brief Expand the word of `${x-word}` and friends.
*
* When the expansion is unquoted, literal text in the word is subject to
* field splitting, which `arg_depth` tells emit_lit().
*/
static void expand_arg(expansion *x, const param *pm, bool quoted) {
if (!quoted)
x->arg_depth++;
expand_parts(x, pm->arg);
if (!quoted)
x->arg_depth--;
}
/**
* @brief Expand one parameter expansion, with its operator.
* @param x Expansion state.
* @param pm The parameter.
* @param quoted Whether it is inside double quotes.
*/
static void expand_param(expansion *x, const param *pm, bool quoted) {
char buf[32];
const char *val;
bool all =
pm->type == PT_SPECIAL && (pm->special == '@' || pm->special == '*');
if (all) {
if (pm->op == PS_NORMAL) {
expand_all_params(x, pm->special, quoted);
return;
}
val = shellparam.n ? join_params(pm->special == '*' ? ifs_first : ' ')
: NULL;
} else {
val = param_value(pm, buf, sizeof buf);
}
bool missing = !val || (pm->colon && !*val);
switch (pm->op) {
case PS_MINUS:
if (missing) {
expand_arg(x, pm, quoted);
if (quoted)
emit_quoted(x, "", 0); /* "${x-}" is still a field */
return;
}
break;
case PS_PLUS:
if (!missing)
expand_arg(x, pm, quoted);
if (quoted)
emit_quoted(x, "", 0);
return;
case PS_EQUAL:
if (missing) {
if (pm->type != PT_VAR)
sh_error("%s: cannot assign in this way", pm->name);
var_set_n(pm->name, pm->nlen, expand_string(pm->arg, 0), 0);
val = var_get_n(pm->name, pm->nlen);
}
break;
case PS_QUESTION:
if (missing) {
const char *msg = pm->arg ? expand_string(pm->arg, 0) : "";
sh_error("%s: %s", pm->name,
*msg ? msg
: pm->colon ? "parameter null or not set"
: "parameter not set");
}
break;
default:
break;
}
if (all && !missing && pm->op != PS_LENGTH && pm->op < PS_TRIML) {
/* "${@-word}" with parameters set is just "$@". */
expand_all_params(x, pm->special, quoted);
return;
}
if (!val) {
if (opt.nounset && !all)
sh_error("%s: parameter not set", pm->name);
val = "";
if (pm->op == PS_NORMAL || pm->op == PS_MINUS) {
if (quoted)
emit_quoted(x, val, 0);
return;
}
}
size_t len;
switch (pm->op) {
case PS_LENGTH:
snprintf(buf, sizeof buf, "%zu", strlen(val));
val = buf;
len = strlen(buf);
break;
case PS_TRIML:
case PS_TRIMLL:
case PS_TRIMR:
case PS_TRIMRR:
val = trim(val, expand_pattern(pm->arg), pm->op, &len);
break;
default:
len = strlen(val);
break;
}
emit(x, val, len, quoted);
}
/* ---- parts ----------------------------------------------------------- */
/**
* @brief Expand `$((...))`: expand the expression text, evaluate it, emit the
* number.
*/
static void expand_arith(expansion *x, const wpart *p) {
char buf[INT_BUFSZ];
const char *s = fmt_int(arith_eval(expand_string(p->u.arith, 0)), buf);
emit(x, s, (size_t)(buf + INT_BUFSZ - 1 - s), p->quoted);
}
/**
* @brief Expand a list of word parts into the current field or string.
*/
static void expand_parts(expansion *x, const wpart *p) {
for (; p; p = p->next) {
switch (p->kind) {
case P_LIT:
if (p->quoted)
emit_quoted(x, p->u.lit.s, p->u.lit.len);
else
emit_lit(x, p->u.lit.s, p->u.lit.len);
break;
case P_PARAM:
expand_param(x, p->u.param, p->quoted);
break;
case P_CMDSUB: {
size_t len;
const char *s = cmdsub_run(p->u.cmd, &len);
emit(x, s, len, p->quoted);
break;
}
case P_ARITH:
expand_arith(x, p);
break;
}
}
}
/**
* @brief Expand a word, handling a leading tilde-prefix.
*/
static void expand_word(expansion *x, const wpart *p) {
if (p && p->kind == P_LIT && !p->quoted && p->u.lit.s[0] == '~') {
size_t used =
expand_tilde(x, p->u.lit.s, p->u.lit.len, false, !p->next);
if (used) {
emit_lit(x, p->u.lit.s + used, p->u.lit.len - used);
p = p->next;
}
}
expand_parts(x, p);
}
/* ---- entry points ---------------------------------------------------- */
/**
* @brief Expand command words into an argument vector.
*
* This is the full treatment: parameter, command and arithmetic
* expansion, field splitting, pathname expansion and quote removal. A
* word marked `plain` by the parser needs none of it and is used as is.
*
* @param list The words.
* @param argc Receives the number of fields.
* @return A NULL-terminated vector in scratch memory.
*/
char **expand_words(const word *list, int *argc) {
expansion x = {.mode = X_FIELDS};
sb_init(&x.text, &scratch);
sb_init(&x.mask, &scratch);
for (const word *w = list; w; w = w->next) {
if (w->plain) {
field_add(&x, w->plain);
continue;
}
expand_word(&x, w->parts);
if (x.have)
field_end(&x);
x.sep = SEP_NONE;
}
field_add(&x, NULL);
*argc = x.argc - 1;
return x.argv;
}
/**
* @brief Expand word parts to a single string: no splitting, no globbing.
* @param parts The parts.
* @param flags XS_TILDE to expand a leading `~`.
* @return The string, in scratch memory.
*/
char *expand_string(const wpart *parts, unsigned flags) {
expansion x = {.mode = X_SINGLE};
sb_init(&x.text, &scratch);
if (flags & XS_TILDE)
expand_word(&x, parts);
else
expand_parts(&x, parts);
return sb_cstr(&x.text);
}
/**
* @brief Expand word parts to a pattern for pat_match(): characters that were
* quoted are backslash-escaped so that they match literally.
*/
char *expand_pattern(const wpart *parts) {
expansion x = {.mode = X_PATTERN};
sb_init(&x.text, &scratch);
expand_parts(&x, parts);
return sb_cstr(&x.text);
}
/**
* @brief Expand an assignment word to `name=value`.
*/
char *expand_assign(const word *w) {
expansion x = {.mode = X_SINGLE};
sb_init(&x.text, &scratch);
const wpart *p = w->parts;
size_t skip = w->assign_len + 1;
sb_put(&x.text, p->u.lit.s, skip);
emit_assign_lit(&x, p->u.lit.s + skip, p->u.lit.len - skip, true, !p->next);
for (p = p->next; p; p = p->next) {
if (p->kind == P_LIT && !p->quoted) {
emit_assign_lit(&x, p->u.lit.s, p->u.lit.len, false, !p->next);
} else {
wpart one = *p;
one.next = NULL;
expand_parts(&x, &one);
}
}
return sb_cstr(&x.text);
}
|