1 /* $OpenBSD: eval.c,v 1.40 2013/09/14 20:09:30 millert Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015
6 * Thorsten Glaser <tg@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 __RCSID("$MirOS: src/bin/mksh/eval.c,v 1.158.2.4 2015/03/01 15:42:58 tg Exp $");
31 * first pass: quoting, IFS separation, ~, ${}, $() and $(()) substitution.
32 * second pass: alternation ({,}), filename expansion (*?[]).
35 /* expansion generator state */
37 /* not including an "int type;" member, see expand() */
47 /* variable in ${var...} */
49 /* split "$@" / call waitlast in $() */
53 #define XBASE 0 /* scanning original */
54 #define XSUB 1 /* expanding ${} string */
55 #define XARGSEP 2 /* ifs0 between "$*" */
56 #define XARG 3 /* expanding $*, $@ */
57 #define XCOM 4 /* expanding $() */
58 #define XNULLSUB 5 /* "$@" when $# is 0 (don't generate word) */
59 #define XSUBMID 6 /* middle of expanding ${} */
61 /* States used for field splitting */
62 #define IFS_WORD 0 /* word has chars (or quotes except "$@") */
63 #define IFS_WS 1 /* have seen IFS white-space */
64 #define IFS_NWS 2 /* have seen IFS non-white-space */
65 #define IFS_IWS 3 /* begin of word, ignore IFS WS */
66 #define IFS_QUOTE 4 /* beg.w/quote, become IFS_WORD unless "$@" */
68 static int varsub(Expand *, const char *, const char *, int *, int *);
69 static int comsub(Expand *, const char *, int);
70 static char *valsub(struct op *, Area *);
71 static char *trimsub(char *, char *, int);
72 static void glob(char *, XPtrV *, bool);
73 static void globit(XString *, char **, char *, XPtrV *, int);
74 static const char *maybe_expand_tilde(const char *, XString *, char **, bool);
76 static char *homedir(char *);
78 static void alt_expand(XPtrV *, char *, char *, char *, int);
79 static int utflen(const char *) MKSH_A_PURE;
80 static void utfincptr(const char *, mksh_ari_t *);
82 /* UTFMODE functions */
103 utfincptr(const char *s, mksh_ari_t *lp)
108 cp += utf_ptradj(cp);
112 /* compile and expand word */
114 substitute(const char *cp, int f)
116 struct source *s, *sold;
119 s = pushs(SWSTR, ATEMP);
120 s->start = s->str = cp;
122 if (yylex(ONEWORD) != LWORD)
123 internal_errorf("bad substitution");
126 return (evalstr(yylval.cp, f));
133 eval(const char **ap, int f)
138 union mksh_ccphack vap;
144 /* space for shell name */
147 expand(*ap++, &w, f);
149 return ((char **)XPclose(w) + 1);
156 evalstr(const char *cp, int f)
170 * expand string - return only one component
171 * used from iosetup to expand redirection files
174 evalonestr(const char *cp, int f)
186 rv = (char *) *XPptrv(w);
189 rv = evalstr(cp, f&~DOGLOB);
196 /* for nested substitution: ${var:=$var2} */
197 typedef struct SubType {
198 struct tbl *var; /* variable for ${var..} */
199 struct SubType *prev; /* old type */
200 struct SubType *next; /* poped type (to avoid re-allocating) */
201 size_t base; /* begin position of expanded word */
202 short stype; /* [=+-?%#] action after expanded word */
203 short f; /* saved value of f (DOPAT, etc) */
204 uint8_t quotep; /* saved value of quote (for ${..[%#]..}) */
205 uint8_t quotew; /* saved value of quote (for ${..[+-=]..}) */
222 /* destination string and live pointer */
227 /* second pass flags */
231 /* field splitting of parameter/command substitution */
233 /* expansion variables */
235 NULL, { NULL }, NULL, 0
237 SubType st_head, *st;
238 /* record number of trailing newlines in COMSUB */
240 bool saw_eq, make_magic;
241 unsigned int tilde_ok;
246 internal_errorf("expand(NULL)");
247 /* for alias, readonly, set, typeset commands */
248 if ((f & DOVACHECK) && is_wdvarassign(ccp)) {
249 f &= ~(DOVACHECK | DOBLANK | DOGLOB | DOTILDE);
250 f |= DOASNTILDE | DOSCALAR;
256 if (Flag(FBRACEEXPAND) && (f & DOGLOB))
259 /* init destination string */
260 Xinit(ds, dp, 128, ATEMP);
266 tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
269 word = (f&DOBLANK) ? IFS_WS : IFS_WORD;
270 /* clang doesn't know OSUBST comes before CSUBST */
271 memset(&st_head, 0, sizeof(st_head));
274 while (/* CONSTCOND */ 1) {
279 /* original prefixed string */
289 /* temporary quote */
315 if (f & DONTRUNCOMMAND) {
318 *dp++ = c == COMSUB ? '(' : '{';
320 *dp++ = c == FUNSUB ? ' ' : '|';
321 while (*sp != '\0') {
331 type = comsub(&x, sp, c);
332 if (type != XBASE && (f & DOBLANK))
340 if (f & DONTRUNCOMMAND) {
342 *dp++ = '$'; *dp++ = '('; *dp++ = '(';
343 while (*sp != '\0') {
347 *dp++ = ')'; *dp++ = ')';
351 v.flag = DEFINED|ISSET|INTEGER;
355 v_evaluate(&v, substitute(sp, 0),
356 KSH_UNWIND_ERROR, true);
365 /* ${{#}var{:}[=+-?#%]word} */
368 * OSUBST [{x] plain-variable-part \0
369 * compiled-word-part CSUBST [}x]
370 * This is where all syntax checking gets done...
372 /* skip the { or x (}) */
373 const char *varname = ++sp;
378 sp = cstrchr(sp, '\0') + 1;
379 type = varsub(&x, varname, sp, &stype, &slen);
381 char *beg, *end, *str;
385 end = (beg = wdcopy(sp, ATEMP)) +
386 (wdscan(sp, CSUBST) - sp);
387 /* ({) the } or x is already skipped */
388 if (end < wdscan(beg, EOS))
390 str = snptreef(NULL, 64, "%S", beg);
392 errorf("%s: %s", str, "bad substitution");
397 if (word == IFS_QUOTE && type != XNULLSUB)
404 newst = alloc(sizeof(SubType), ATEMP);
411 st->base = Xsavepos(ds, dp);
413 if (x.var == &vtemp) {
415 st->var->flag &= ~INTEGER;
416 /* can't fail here */
419 KSH_RETURN_ERROR | 0x4);
423 st->quotew = st->quotep = quote;
424 /* skip qualifier(s) */
427 switch (stype & 0x17F) {
429 x.str = shf_smprintf("%08X",
430 (unsigned int)hash(str_val(st->var)));
435 shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
436 print_value_quoted(&shf, str_val(st->var));
437 x.str = shf_sclose(&shf);
441 char *beg, *mid, *end, *stg;
442 mksh_ari_t from = 0, num = -1, flen, finc = 0;
444 beg = wdcopy(sp, ATEMP);
445 mid = beg + (wdscan(sp, ADELIM) - sp);
446 stg = beg + (wdscan(sp, CSUBST) - sp);
448 goto unwind_substsyn;
450 if (mid[-1] == /*{*/'}') {
455 (wdscan(mid, ADELIM) - mid);
457 /* more than max delimiters */
458 end[-1] != /*{*/ '}')
459 goto unwind_substsyn;
463 evaluate(substitute(stg = wdstrip(beg, 0), 0),
464 &from, KSH_UNWIND_ERROR, true);
467 evaluate(substitute(stg = wdstrip(mid, 0), 0),
468 &num, KSH_UNWIND_ERROR, true);
472 beg = str_val(st->var);
478 finc = from < flen ? from : flen;
480 utfincptr(beg, &finc);
483 if (num < 0 || num > flen)
486 utfincptr(beg, &num);
487 strndupx(x.str, beg, num, ATEMP);
491 char *s, *p, *d, *sbeg, *end;
493 char *tpat0, *tpat1, *tpat2;
495 s = wdcopy(sp, ATEMP);
496 p = s + (wdscan(sp, ADELIM) - sp);
497 d = s + (wdscan(sp, CSUBST) - sp);
499 goto unwind_substsyn;
501 if (p[-1] == /*{*/'}')
505 sp += (d ? d : p) - s - 1;
507 WDS_KEEPQ | WDS_MAGIC);
508 pat = substitute(tpat0, 0);
510 d = wdstrip(p, WDS_KEEPQ);
511 rrep = substitute(d, 0);
522 /* XXX really? */ s[1] == '\\' ||
530 /* check for special cases */
531 d = str_val(st->var);
534 /* anchor at begin */
551 tpat1 = tpat2 = NULL;
553 if (gmatchx(null, tpat0, false)) {
560 /* but is anchored */
561 s = shf_smprintf("%s%s",
566 /* prepare string on which to work */
567 strdupx(s, d, ATEMP);
570 /* first see if we have any match at all */
573 /* anchor at the beginning */
574 tpat1 = shf_smprintf("%s%c*", ++tpat0, MAGIC);
576 } else if (*pat == '%') {
577 /* anchor at the end */
578 tpat1 = shf_smprintf("%c*%s", MAGIC, ++tpat0);
582 tpat1 = shf_smprintf("%c*%s%c*", MAGIC, pat, MAGIC);
587 * this would not be necessary if gmatchx would return
588 * the start and end values of a match found, like re*
590 if (!gmatchx(sbeg, tpat1, false))
593 /* now anchor the beginning of the match */
595 while (sbeg <= end) {
596 if (gmatchx(sbeg, tpat2, false))
601 /* now anchor the end of the match */
609 gotmatch = tobool(gmatchx(sbeg, tpat0, false));
615 strndupx(end, s, sbeg - s, ATEMP);
616 d = shf_smprintf("%s%s%s", end, rrep, p);
618 sbeg = d + (sbeg - s) + strlen(rrep);
635 /* ! DOBLANK,DOBRACE,DOTILDE */
636 f = (f & DONTRUNCOMMAND) |
637 DOPAT | DOTEMP | DOSCALAR;
638 st->quotew = quote = 0;
640 * Prepend open pattern (so |
641 * in a trim will work as
651 * Enabling tilde expansion
653 * non-standard ksh, but is
654 * consistent with rules for
655 * other assignments. Not
656 * sure what POSIX thinks of
658 * Not doing tilde expansion
659 * for integer variables is a
660 * non-POSIX thing - makes
661 * sense though, since ~ is
662 * a arithmetic operator.
664 if (!(x.var->flag & INTEGER))
665 f |= DOASNTILDE | DOTILDE;
668 * These will be done after the
669 * value has been assigned.
671 f &= ~(DOBLANK|DOGLOB|DOBRACE);
682 else if (dp == Xstring(ds, dp))
684 /* Enable tilde expansion */
690 sp += wdscan(sp, CSUBST) - sp;
694 /* only get here if expanding word */
696 /* ({) skip the } or x */
698 /* in case of ${unset:-} */
705 switch (st->stype & 0x17F) {
709 /* Append end-pattern */
714 dp = Xrestpos(ds, dp, st->base);
716 * Must use st->var since calling
717 * global would break things
720 x.str = trimsub(str_val(st->var),
722 if (x.str[0] != '\0') {
729 if (dp == Xstring(ds, dp))
739 * Restore our position and substitute
740 * the value of st->var (may not be
741 * the assigned value in the presence
742 * of integer/right-adj/etc attributes).
744 dp = Xrestpos(ds, dp, st->base);
746 * Must use st->var since calling
747 * global would cause with things
748 * like x[i+=1] to be evaluated twice.
751 * Note: not exported by FEXPORT
755 * XXX POSIX says readonly is only
756 * fatal for special builtins (setstr
757 * does readonly check).
759 len = strlen(dp) + 1;
761 debunk(alloc(len, ATEMP),
762 dp, len), KSH_UNWIND_ERROR);
763 x.str = str_val(st->var);
768 word = quote || (!*x.str && (f & DOSCALAR)) ? IFS_WORD : IFS_IWS;
771 char *s = Xrestpos(ds, dp, st->base);
773 errorf("%s: %s", st->var->name,
775 "parameter null or not set" :
776 (debunk(s, s, strlen(s) + 1), s));
782 dp = Xrestpos(ds, dp, st->base);
784 word = quote || (!*x.str && (f & DOSCALAR)) ? IFS_WORD : IFS_IWS;
789 /* default: '-' '+' */
796 /* open pattern: *(foo|bar) */
797 /* Next char is the type of pattern */
803 /* pattern separator (|) */
818 * Special case for "$@" (and "${foo[@]}") - no
819 * word is generated if $# is 0 (unless there is
820 * other stuff inside the quotes).
825 if (dp == Xstring(ds, dp) && word != IFS_WORD)
832 if ((c = *x.str++) == 0) {
845 if ((c = *x.str++) == '\0') {
847 * force null words to be created so
848 * set -- "" 2 ""; echo "$@" will do
851 if (quote && x.split)
853 if ((x.str = *x.u.strv++) == NULL) {
860 if ((f & DOHEREDOC)) {
861 /* pseudo-field-split reliably */
866 if ((f & DOSCALAR)) {
867 /* do not field-split */
876 if (quote && !x.split)
878 if (!quote && word == IFS_WS)
880 /* this is so we don't terminate */
882 /* now force-emit a word */
885 if (quote && x.split) {
886 /* terminate word for "$@" */
894 if (x.u.shf == NULL) {
899 } else if (newlines) {
900 /* spit out saved NLs */
904 while ((c = shf_getc(x.u.shf)) == 0 || c == '\n')
908 if (newlines && c != -1) {
909 shf_ungetc(c, x.u.shf);
919 subst_exstat = waitlast();
928 /* check for end of word or IFS separation */
929 if (c == 0 || (!quote && (f & DOBLANK) && doblank &&
930 !make_magic && ctype(c, C_IFS))) {
932 * How words are broken up:
935 * -----------------------------------
936 * IFS_WORD w/WS w/NWS w
937 * IFS_WS -/WS -/NWS -
938 * IFS_NWS -/NWS w/NWS -
939 * IFS_IWS -/WS w/NWS -
940 * (w means generate a word)
942 if ((word == IFS_WORD) || (word == IFS_QUOTE) || (c &&
943 (word == IFS_IWS || word == IFS_NWS) &&
944 !ctype(c, C_IFSWS))) {
949 /* also does globbing */
950 alt_expand(wp, cp, cp,
951 cp + Xlength(ds, (dp - 1)),
952 fdo | (f & DOMARKDIRS));
953 else if (fdo & DOGLOB)
954 glob(cp, wp, tobool(f & DOMARKDIRS));
955 else if ((f & DOPAT) || !(fdo & DOMAGIC))
958 XPput(*wp, debunk(cp, cp,
963 tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
966 Xinit(ds, dp, 128, ATEMP);
969 } else if (type == XSUB && ctype(c, C_IFS) &&
970 !ctype(c, C_IFSWS) && Xlength(ds, dp) == 0) {
971 *(cp = alloc(1, ATEMP)) = '\0';
976 word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
979 if (word == IFS_NWS &&
980 Xlength(ds, dp) == 0) {
981 *(cp = alloc(1, ATEMP)) = '\0';
987 /* age tilde_ok info - ~ code tests second bit */
989 /* mark any special second pass chars */
997 * For character classes - doesn't hurt
998 * to have magic !,-,]s outside of
1001 if (f & (DOPAT | DOGLOB)) {
1010 if (f & (DOPAT | DOGLOB)) {
1011 fdo |= DOMAGIC | (f & DOGLOB);
1018 if ((f & DOBRACE) && (c == '{' /*}*/ ||
1020 fdo |= DOBRACE|DOMAGIC;
1025 /* Note first unquoted = for ~ */
1026 if (!(f & DOTEMP) && !saw_eq &&
1027 (Flag(FBRACEEXPAND) ||
1028 (f & DOASNTILDE))) {
1035 /* Note unquoted : for ~ */
1036 if (!(f & DOTEMP) && (f & DOASNTILDE))
1041 * tilde_ok is reset whenever
1042 * any of ' " $( $(( ${ } are seen.
1043 * Note that tilde_ok must be preserved
1044 * through the sequence ${A=a=}~
1046 if (type == XBASE &&
1047 (f & (DOTILDE | DOASNTILDE)) &&
1052 tcp = maybe_expand_tilde(sp,
1054 tobool(f & DOASNTILDE));
1066 /* undo temporary */
1071 fdo |= DOMAGIC | (f & DOGLOB);
1073 } else if (ISMAGIC(c)) {
1077 /* save output char */
1085 * Prepare to generate the string returned by ${} substitution.
1088 varsub(Expand *xp, const char *sp, const char *word,
1089 int *stypep, /* becomes qualifier type */
1090 int *slenp) /* " " len (=, :=, etc.) valid iff *stypep != 0 */
1093 int state; /* next state: XBASE, XARG, XSUB, XNULLSUB */
1094 int stype; /* substitution type */
1098 bool zero_ok = false;
1100 if ((stype = sp[0]) == '\0')
1101 /* Bad variable name */
1107 * ${#var}, string length (-U: characters, +U: octets) or array size
1108 * ${%var}, string width (-U: screen columns, +U: octets)
1111 if (stype == '%' && c == '\0')
1113 if ((stype == '#' || stype == '%') && c != '\0') {
1114 /* Can't have any modifiers for ${#...} or ${%...} */
1115 if (*word != CSUBST)
1118 /* Check for size of array */
1119 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1125 vp = global(arrayname(sp));
1126 if (vp->flag & (ISSET|ARRAY))
1128 for (; vp; vp = vp->u.array)
1129 if (vp->flag & ISSET)
1132 } else if (c == '*' || c == '@') {
1137 p = str_val(global(sp));
1138 zero_ok = p != null;
1142 /* partial utf_mbswidth reimplementation */
1150 if (!UTFMODE || (len = utf_mbtowc(&wc,
1152 /* not UTFMODE or not UTF-8 */
1153 wc = (unsigned char)(*s++);
1155 /* UTFMODE and UTF-8 */
1157 /* wc == char or wchar at s++ */
1158 if ((cw = utf_wcwidth(wc)) == -1) {
1159 /* 646, 8859-1, 10646 C0/C1 */
1167 if (Flag(FNOUNSET) && c == 0 && !zero_ok)
1168 errorf("%s: %s", sp, "parameter not set");
1169 /* unqualified variable/string substitution */
1171 xp->str = shf_smprintf("%d", c);
1175 /* Check for qualifiers in word part */
1177 c = word[slen = 0] == CHAR ? word[1] : 0;
1181 c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
1183 if (!stype && c == '/') {
1186 if (word[slen] == ADELIM) {
1190 } else if (stype == 0x80 && (c == ' ' || c == '0')) {
1192 } else if (ctype(c, C_SUBOP1)) {
1195 } else if (ctype(c, C_SUBOP2)) {
1196 /* Note: ksh88 allows :%, :%%, etc */
1199 if (word[slen + 0] == CHAR && c == word[slen + 1]) {
1203 } else if (c == '@') {
1204 /* @x where x is command char */
1207 if (word[slen] == CHAR) {
1208 stype |= word[slen + 1];
1214 if (!stype && *word != CSUBST)
1220 if (c == '*' || c == '@') {
1221 switch (stype & 0x17F) {
1222 /* can't assign to a vector */
1224 /* can't trim a vector (yet) */
1233 if (e->loc->argc == 0) {
1235 xp->var = global(sp);
1236 state = c == '@' ? XNULLSUB : XSUB;
1238 xp->u.strv = (const char **)e->loc->argv + 1;
1239 xp->str = *xp->u.strv++;
1241 xp->split = tobool(c == '@');
1247 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1251 switch (stype & 0x17F) {
1252 /* can't assign to a vector */
1254 /* can't trim a vector (yet) */
1265 if ((c = sp[0]) == '!')
1267 vp = global(arrayname(sp));
1268 for (; vp; vp = vp->u.array) {
1269 if (!(vp->flag&ISSET))
1271 XPput(wv, c == '!' ? shf_smprintf("%lu",
1275 if (XPsize(wv) == 0) {
1277 state = p[1] == '@' ? XNULLSUB : XSUB;
1281 xp->u.strv = (const char **)XPptrv(wv);
1282 xp->str = *xp->u.strv++;
1284 xp->split = tobool(p[1] == '@');
1288 /* Can't assign things like $! or $1 */
1289 if ((stype & 0x17F) == '=' &&
1290 ctype(*sp, C_VAR1 | C_DIGIT))
1292 if (*sp == '!' && sp[1]) {
1294 xp->var = global(sp);
1295 if (vstrchr(sp, '['))
1296 xp->str = shf_smprintf("%s[%lu]",
1298 arrayindex(xp->var));
1300 xp->str = xp->var->name;
1302 xp->var = global(sp);
1303 xp->str = str_val(xp->var);
1310 /* test the compiler's code generator */
1311 if (((stype < 0x100) && (ctype(c, C_SUBOP2) || c == '/' ||
1312 (((stype&0x80) ? *xp->str=='\0' : xp->str==null) ? /* undef? */
1313 c == '=' || c == '-' || c == '?' : c == '+'))) ||
1314 stype == (0x80 | '0') || stype == (0x100 | '#') ||
1315 stype == (0x100 | 'Q'))
1316 /* expand word instead of variable value */
1318 if (Flag(FNOUNSET) && xp->str == null && !zero_ok &&
1319 (ctype(c, C_SUBOP2) || (state != XBASE && c != '+')))
1320 errorf("%s: %s", sp, "parameter not set");
1325 * Run the command in $(...) and read its output.
1328 comsub(Expand *xp, const char *cp, int fn MKSH_A_UNUSED)
1333 uint8_t old_utfmode = UTFMODE;
1335 s = pushs(SSTRING, ATEMP);
1336 s->start = s->str = cp;
1338 t = compile(s, true);
1342 UTFMODE = old_utfmode;
1347 /* no waitlast() unless specifically enabled later */
1350 if (t->type == TCOM &&
1351 *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
1353 struct ioword *io = *t->ioact;
1356 if ((io->flag & IOTYPE) != IOREAD)
1357 errorf("%s: %s", "funny $() command",
1358 snptreef(NULL, 32, "%R", io));
1359 shf = shf_open(name = evalstr(io->name, DOTILDE), O_RDONLY, 0,
1360 SHF_MAPHI|SHF_CLEXEC);
1362 warningf(!Flag(FTALKING), "%s: %s %s: %s", name,
1363 "can't open", "$(<...) input", cstrerror(errno));
1364 } else if (fn == FUNSUB) {
1366 struct temp *tf = NULL;
1369 * create a temporary file, open for reading and writing,
1370 * with an shf open for reading (buffered) but yet unused
1372 maketemp(ATEMP, TT_FUNSUB, &tf);
1374 errorf("can't %s temporary file %s: %s",
1375 "create", tf->tffn, cstrerror(errno));
1377 /* extract shf from temporary file, unlink and free it */
1381 /* save stdout and let it point to the tempfile */
1383 ksh_dup2(shf_fileno(shf), 1, false);
1385 * run tree, with output thrown into the tempfile,
1386 * in a new function block
1389 subst_exstat = exstat & 0xFF;
1390 /* rewind the tempfile and restore regular stdout */
1391 lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
1393 } else if (fn == VALSUB) {
1394 xp->str = valsub(t, ATEMP);
1395 subst_exstat = exstat & 0xFF;
1401 shf = shf_fdopen(pv[0], SHF_RD, NULL);
1404 ksh_dup2(pv[1], 1, false);
1407 execute(t, XXCOM | XPIPEO | XFORK, NULL);
1419 * perform #pattern and %pattern substitution in ${}
1422 trimsub(char *str, char *pat, int how)
1424 char *end = strnul(str);
1427 switch (how & 0xFF) {
1429 /* shortest match at beginning */
1430 for (p = str; p <= end; p += utf_ptradj(p)) {
1432 if (gmatchx(str, pat, false)) {
1440 /* longest match at beginning */
1441 for (p = end; p >= str; p--) {
1443 if (gmatchx(str, pat, false)) {
1451 /* shortest match at end */
1454 if (gmatchx(p, pat, false))
1458 while ((p-- > str) && ((*p & 0xC0) == 0x80))
1460 if ((p < str) || (p + utf_ptradj(p) != op))
1467 /* longest match at end */
1468 for (p = str; p <= end; p++)
1469 if (gmatchx(p, pat, false)) {
1471 strndupx(end, str, p - str, ATEMP);
1477 /* no match, return string */
1483 * Name derived from V6's /etc/glob, the program that expanded filenames.
1486 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
1488 glob(char *cp, XPtrV *wp, bool markdirs)
1490 int oldsize = XPsize(*wp);
1492 if (glob_str(cp, wp, markdirs) == 0)
1493 XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
1495 qsort(XPptrv(*wp) + oldsize, XPsize(*wp) - oldsize,
1496 sizeof(void *), xstrcmp);
1500 #define GF_EXCHECK BIT(0) /* do existence check on file */
1501 #define GF_GLOBBED BIT(1) /* some globbing has been done */
1502 #define GF_MARKDIR BIT(2) /* add trailing / to directories */
1505 * Apply file globbing to cp and store the matching files in wp. Returns
1506 * the number of matches found.
1509 glob_str(char *cp, XPtrV *wp, bool markdirs)
1511 int oldsize = XPsize(*wp);
1515 Xinit(xs, xp, 256, ATEMP);
1516 globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
1519 return (XPsize(*wp) - oldsize);
1523 globit(XString *xs, /* dest string */
1524 char **xpp, /* ptr to dest end */
1525 char *sp, /* source path */
1526 XPtrV *wp, /* output list */
1527 int check) /* GF_* flags */
1529 char *np; /* next source component */
1534 /* This to allow long expansions to be interrupted */
1538 /* end of source path */
1540 * We only need to check if the file exists if a pattern
1541 * is followed by a non-pattern (eg, foo*x/bar; no check
1542 * is needed for foo* since the match must exist) or if
1543 * any patterns were expanded and the markdirs option is set.
1544 * Symlinks make things a bit tricky...
1546 if ((check & GF_EXCHECK) ||
1547 ((check & GF_MARKDIR) && (check & GF_GLOBBED))) {
1548 #define stat_check() (stat_done ? stat_done : (stat_done = \
1549 stat(Xstring(*xs, xp), &statb) < 0 ? -1 : 1))
1550 struct stat lstatb, statb;
1551 /* -1: failed, 1 ok, 0 not yet done */
1554 if (mksh_lstat(Xstring(*xs, xp), &lstatb) < 0)
1557 * special case for systems which strip trailing
1558 * slashes from regular files (eg, /etc/passwd/).
1559 * SunOS 4.1.3 does this...
1561 if ((check & GF_EXCHECK) && xp > Xstring(*xs, xp) &&
1562 xp[-1] == '/' && !S_ISDIR(lstatb.st_mode) &&
1563 (!S_ISLNK(lstatb.st_mode) ||
1564 stat_check() < 0 || !S_ISDIR(statb.st_mode)))
1567 * Possibly tack on a trailing / if there isn't already
1568 * one and if the file is a directory or a symlink to a
1571 if (((check & GF_MARKDIR) && (check & GF_GLOBBED)) &&
1572 xp > Xstring(*xs, xp) && xp[-1] != '/' &&
1573 (S_ISDIR(lstatb.st_mode) ||
1574 (S_ISLNK(lstatb.st_mode) && stat_check() > 0 &&
1575 S_ISDIR(statb.st_mode)))) {
1580 strndupx(np, Xstring(*xs, xp), Xlength(*xs, xp), ATEMP);
1585 if (xp > Xstring(*xs, xp))
1587 while (*sp == '/') {
1591 np = strchr(sp, '/');
1594 /* don't assume '/', can be multiple kinds */
1598 odirsep = '\0'; /* keep gcc quiet */
1599 se = sp + strlen(sp);
1604 * Check if sp needs globbing - done to avoid pattern checks for strings
1605 * containing MAGIC characters, open [s without the matching close ],
1606 * etc. (otherwise opendir() will be called which may fail because the
1607 * directory isn't readable - if no globbing is needed, only execute
1608 * permission should be required (as per POSIX)).
1610 if (!has_globbing(sp, se)) {
1611 XcheckN(*xs, xp, se - sp + 1);
1612 debunk(xp, sp, Xnleft(*xs, xp));
1615 globit(xs, xpp, np, wp, check);
1620 size_t len, prefix_len;
1622 /* xp = *xpp; copy_non_glob() may have re-alloc'd xs */
1624 prefix_len = Xlength(*xs, xp);
1625 dirp = opendir(prefix_len ? Xstring(*xs, xp) : ".");
1628 while ((d = readdir(dirp)) != NULL) {
1630 if (name[0] == '.' &&
1631 (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1632 /* always ignore . and .. */
1634 if ((*name == '.' && *sp != '.') ||
1635 !gmatchx(name, sp, true))
1638 len = strlen(d->d_name) + 1;
1639 XcheckN(*xs, xp, len);
1640 memcpy(xp, name, len);
1641 *xpp = xp + len - 1;
1642 globit(xs, xpp, np, wp,
1643 (check & GF_MARKDIR) | GF_GLOBBED
1644 | (np ? GF_EXCHECK : GF_NONE));
1645 xp = Xstring(*xs, xp) + prefix_len;
1656 /* remove MAGIC from string */
1658 debunk(char *dp, const char *sp, size_t dlen)
1663 if ((s = cstrchr(sp, MAGIC))) {
1664 if (s - sp >= (ssize_t)dlen)
1666 memmove(dp, sp, s - sp);
1667 for (d = dp + (s - sp); *s && (d - dp < (ssize_t)dlen); s++)
1668 if (!ISMAGIC(*s) || !(*++s & 0x80) ||
1669 !vstrchr("*+?@! ", *s & 0x7f))
1672 /* extended pattern operators: *+?@! */
1673 if ((*s & 0x7f) != ' ')
1675 if (d - dp < (ssize_t)dlen)
1679 } else if (dp != sp)
1680 strlcpy(dp, sp, dlen);
1685 * Check if p is an unquoted name, possibly followed by a / or :. If so
1686 * puts the expanded version in *dcp,dp and returns a pointer in p just
1687 * past the name, otherwise returns 0.
1690 maybe_expand_tilde(const char *p, XString *dsp, char **dpp, bool isassign)
1697 Xinit(ts, tp, 16, ATEMP);
1698 /* : only for DOASNTILDE form */
1699 while (p[0] == CHAR && p[1] != '/' && (!isassign || p[1] != ':'))
1706 r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ?
1707 do_tilde(Xstring(ts, tp)) : NULL;
1725 * based on a version by Arnold Robbins
1734 dp = str_val(global("HOME"));
1735 else if (cp[0] == '+' && cp[1] == '\0')
1736 dp = str_val(global("PWD"));
1737 else if (cp[0] == '-' && cp[1] == '\0')
1738 dp = str_val(global("OLDPWD"));
1739 #ifndef MKSH_NOPWNAM
1743 /* If HOME, PWD or OLDPWD are not set, don't expand ~ */
1744 return (dp == null ? NULL : dp);
1747 #ifndef MKSH_NOPWNAM
1749 * map userid to user's home directory.
1750 * note that 4.3's getpw adds more than 6K to the shell,
1751 * and the YP version probably adds much more.
1752 * we might consider our own version of getpwnam() to keep the size down.
1759 ap = ktenter(&homedirs, name, hash(name));
1760 if (!(ap->flag & ISSET)) {
1763 pw = getpwnam(name);
1766 strdupx(ap->val.s, pw->pw_dir, APERM);
1767 ap->flag |= DEFINED|ISSET|ALLOC;
1774 alt_expand(XPtrV *wp, char *start, char *exp_start, char *end, int fdo)
1776 unsigned int count = 0;
1777 char *brace_start, *brace_end, *comma = NULL;
1779 char *p = exp_start;
1781 /* search for open brace */
1782 while ((p = strchr(p, MAGIC)) && p[1] != '{' /*}*/)
1786 /* find matching close brace, if any */
1791 while (*p && count) {
1792 if (ISMAGIC(*p++)) {
1793 if (*p == '{' /*}*/)
1795 else if (*p == /*{*/ '}')
1797 else if (*p == ',' && count == 1)
1803 /* no valid expansions... */
1804 if (!p || count != 0) {
1806 * Note that given a{{b,c} we do not expand anything (this is
1807 * what AT&T ksh does. This may be changed to do the {b,c}
1811 glob(start, wp, tobool(fdo & DOMARKDIRS));
1813 XPput(*wp, debunk(start, start, end - start));
1818 alt_expand(wp, start, brace_end, end, fdo);
1822 /* expand expression */
1823 field_start = brace_start + 2;
1825 for (p = brace_start + 2; p != brace_end; p++) {
1827 if (*++p == '{' /*}*/)
1829 else if ((*p == /*{*/ '}' && --count == 0) ||
1830 (*p == ',' && count == 1)) {
1835 * addition safe since these operate on
1836 * one string (separate substrings)
1838 l1 = brace_start - start;
1839 l2 = (p - 1) - field_start;
1840 l3 = end - brace_end;
1841 news = alloc(l1 + l2 + l3 + 1, ATEMP);
1842 memcpy(news, start, l1);
1843 memcpy(news + l1, field_start, l2);
1844 memcpy(news + l1 + l2, brace_end, l3);
1845 news[l1 + l2 + l3] = '\0';
1846 alt_expand(wp, news, news + l1,
1847 news + l1 + l2 + l3, fdo);
1848 field_start = p + 1;
1855 /* helper function due to setjmp/longjmp woes */
1857 valsub(struct op *t, Area *ap)
1859 char * volatile cp = NULL;
1860 struct tbl * volatile vp = NULL;
1865 vp = local("REPLY", false);
1866 if (!kshsetjmp(e->jbuf))
1867 execute(t, XXCOM | XERROK, NULL);
1869 strdupx(cp, str_val(vp), ap);