/** * @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 #include #include #include #include #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); }