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.170 2015/07/06 17:45:33 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 */
294 if (word != IFS_WORD)
300 if (word == IFS_QUOTE)
308 if (f & DONTRUNCOMMAND) {
311 *dp++ = c == COMSUB ? '(' : '{';
313 *dp++ = c == FUNSUB ? ' ' : '|';
314 while (*sp != '\0') {
324 type = comsub(&x, sp, c);
325 if (type != XBASE && (f & DOBLANK))
333 if (f & DONTRUNCOMMAND) {
335 *dp++ = '$'; *dp++ = '('; *dp++ = '(';
336 while (*sp != '\0') {
340 *dp++ = ')'; *dp++ = ')';
344 v.flag = DEFINED|ISSET|INTEGER;
348 v_evaluate(&v, substitute(sp, 0),
349 KSH_UNWIND_ERROR, true);
358 /* ${{#}var{:}[=+-?#%]word} */
361 * OSUBST [{x] plain-variable-part \0
362 * compiled-word-part CSUBST [}x]
363 * This is where all syntax checking gets done...
365 /* skip the { or x (}) */
366 const char *varname = ++sp;
371 sp = cstrchr(sp, '\0') + 1;
372 type = varsub(&x, varname, sp, &stype, &slen);
374 char *beg, *end, *str;
378 end = (beg = wdcopy(sp, ATEMP)) +
379 (wdscan(sp, CSUBST) - sp);
380 /* ({) the } or x is already skipped */
381 if (end < wdscan(beg, EOS))
383 str = snptreef(NULL, 64, "%S", beg);
385 errorf("%s: %s", str, "bad substitution");
390 if (word == IFS_QUOTE && type != XNULLSUB)
397 newst = alloc(sizeof(SubType), ATEMP);
404 st->base = Xsavepos(ds, dp);
406 if (x.var == &vtemp) {
408 st->var->flag &= ~INTEGER;
409 /* can't fail here */
412 KSH_RETURN_ERROR | 0x4);
416 st->quotew = st->quotep = quote;
417 /* skip qualifier(s) */
420 switch (stype & 0x17F) {
422 x.str = shf_smprintf("%08X",
423 (unsigned int)hash(str_val(st->var)));
428 shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
429 print_value_quoted(&shf, str_val(st->var));
430 x.str = shf_sclose(&shf);
434 char *beg, *mid, *end, *stg;
435 mksh_ari_t from = 0, num = -1, flen, finc = 0;
437 beg = wdcopy(sp, ATEMP);
438 mid = beg + (wdscan(sp, ADELIM) - sp);
439 stg = beg + (wdscan(sp, CSUBST) - sp);
441 goto unwind_substsyn;
443 if (mid[-1] == /*{*/'}') {
448 (wdscan(mid, ADELIM) - mid);
450 /* more than max delimiters */
451 end[-1] != /*{*/ '}')
452 goto unwind_substsyn;
456 evaluate(substitute(stg = wdstrip(beg, 0), 0),
457 &from, KSH_UNWIND_ERROR, true);
460 evaluate(substitute(stg = wdstrip(mid, 0), 0),
461 &num, KSH_UNWIND_ERROR, true);
465 beg = str_val(st->var);
471 finc = from < flen ? from : flen;
473 utfincptr(beg, &finc);
476 if (num < 0 || num > flen)
479 utfincptr(beg, &num);
480 strndupx(x.str, beg, num, ATEMP);
484 char *s, *p, *d, *sbeg, *end;
486 char *tpat0, *tpat1, *tpat2;
488 s = wdcopy(sp, ATEMP);
489 p = s + (wdscan(sp, ADELIM) - sp);
490 d = s + (wdscan(sp, CSUBST) - sp);
492 goto unwind_substsyn;
494 if (p[-1] == /*{*/'}')
498 sp += (d ? d : p) - s - 1;
500 WDS_KEEPQ | WDS_MAGIC);
501 pat = substitute(tpat0, 0);
503 d = wdstrip(p, WDS_KEEPQ);
504 rrep = substitute(d, 0);
515 /* XXX really? */ s[1] == '\\' ||
523 /* check for special cases */
530 /* empty pattern, reject */
535 if (gmatchx(null, tpat0, false)) {
537 * pattern matches empty
538 * string => don't loop
543 /* prepare string on which to work */
544 strdupx(s, str_val(st->var), ATEMP);
547 /* first see if we have any match at all */
550 /* anchor at the beginning */
551 tpat1 = shf_smprintf("%s%c*", ++tpat0, MAGIC);
553 } else if (*pat == '%') {
554 /* anchor at the end */
555 tpat1 = shf_smprintf("%c*%s", MAGIC, ++tpat0);
559 tpat1 = shf_smprintf("%c*%s%c*", MAGIC, pat, MAGIC);
564 * this would not be necessary if gmatchx would return
565 * the start and end values of a match found, like re*
567 if (!gmatchx(sbeg, tpat1, false))
570 /* now anchor the beginning of the match */
572 while (sbeg <= end) {
573 if (gmatchx(sbeg, tpat2, false))
578 /* now anchor the end of the match */
586 gotmatch = tobool(gmatchx(sbeg, tpat0, false));
592 strndupx(end, s, sbeg - s, ATEMP);
593 d = shf_smprintf("%s%s%s", end, rrep, p);
595 sbeg = d + (sbeg - s) + strlen(rrep);
611 /* ! DOBLANK,DOBRACE,DOTILDE */
612 f = (f & DONTRUNCOMMAND) |
613 DOPAT | DOTEMP | DOSCALAR;
614 st->quotew = quote = 0;
616 * Prepend open pattern (so |
617 * in a trim will work as
627 * Enabling tilde expansion
629 * non-standard ksh, but is
630 * consistent with rules for
631 * other assignments. Not
632 * sure what POSIX thinks of
634 * Not doing tilde expansion
635 * for integer variables is a
636 * non-POSIX thing - makes
637 * sense though, since ~ is
638 * a arithmetic operator.
640 if (!(x.var->flag & INTEGER))
641 f |= DOASNTILDE | DOTILDE;
644 * These will be done after the
645 * value has been assigned.
647 f &= ~(DOBLANK|DOGLOB|DOBRACE);
658 else if (dp == Xstring(ds, dp))
660 /* Enable tilde expansion */
666 sp += wdscan(sp, CSUBST) - sp;
670 /* only get here if expanding word */
672 /* ({) skip the } or x */
674 /* in case of ${unset:-} */
681 switch (st->stype & 0x17F) {
685 /* Append end-pattern */
690 dp = Xrestpos(ds, dp, st->base);
692 * Must use st->var since calling
693 * global would break things
696 x.str = trimsub(str_val(st->var),
698 if (x.str[0] != '\0') {
705 if (dp == Xstring(ds, dp))
715 * Restore our position and substitute
716 * the value of st->var (may not be
717 * the assigned value in the presence
718 * of integer/right-adj/etc attributes).
720 dp = Xrestpos(ds, dp, st->base);
722 * Must use st->var since calling
723 * global would cause with things
724 * like x[i+=1] to be evaluated twice.
727 * Note: not exported by FEXPORT
731 * XXX POSIX says readonly is only
732 * fatal for special builtins (setstr
733 * does readonly check).
735 len = strlen(dp) + 1;
737 debunk(alloc(len, ATEMP),
738 dp, len), KSH_UNWIND_ERROR);
739 x.str = str_val(st->var);
744 word = quote || (!*x.str && (f & DOSCALAR)) ? IFS_WORD : IFS_IWS;
747 char *s = Xrestpos(ds, dp, st->base);
749 errorf("%s: %s", st->var->name,
751 "parameter null or not set" :
752 (debunk(s, s, strlen(s) + 1), s));
758 dp = Xrestpos(ds, dp, st->base);
760 word = quote || (!*x.str && (f & DOSCALAR)) ? IFS_WORD : IFS_IWS;
765 /* default: '-' '+' */
772 /* open pattern: *(foo|bar) */
773 /* Next char is the type of pattern */
779 /* pattern separator (|) */
794 * Special case for "$@" (and "${foo[@]}") - no
795 * word is generated if $# is 0 (unless there is
796 * other stuff inside the quotes).
801 if (dp == Xstring(ds, dp) && word != IFS_WORD)
808 if ((c = *x.str++) == 0) {
821 if ((c = *x.str++) == '\0') {
823 * force null words to be created so
824 * set -- "" 2 ""; echo "$@" will do
827 if (quote && x.split)
829 if ((x.str = *x.u.strv++) == NULL) {
836 if ((f & DOHEREDOC)) {
837 /* pseudo-field-split reliably */
842 if ((f & DOSCALAR)) {
843 /* do not field-split */
852 if (quote && !x.split)
854 if (!quote && word == IFS_WS)
856 /* this is so we don't terminate */
858 /* now force-emit a word */
861 if (quote && x.split) {
862 /* terminate word for "$@" */
870 if (x.u.shf == NULL) {
875 } else if (newlines) {
876 /* spit out saved NLs */
880 while ((c = shf_getc(x.u.shf)) == 0 || c == '\n')
884 if (newlines && c != -1) {
885 shf_ungetc(c, x.u.shf);
895 subst_exstat = waitlast();
904 /* check for end of word or IFS separation */
905 if (c == 0 || (!quote && (f & DOBLANK) && doblank &&
906 !make_magic && ctype(c, C_IFS))) {
908 * How words are broken up:
911 * -----------------------------------
912 * IFS_WORD w/WS w/NWS w
913 * IFS_WS -/WS -/NWS -
914 * IFS_NWS -/NWS w/NWS -
915 * IFS_IWS -/WS w/NWS -
916 * (w means generate a word)
918 if ((word == IFS_WORD) || (word == IFS_QUOTE) || (c &&
919 (word == IFS_IWS || word == IFS_NWS) &&
920 !ctype(c, C_IFSWS))) {
925 /* also does globbing */
926 alt_expand(wp, cp, cp,
927 cp + Xlength(ds, (dp - 1)),
928 fdo | (f & DOMARKDIRS));
929 else if (fdo & DOGLOB)
930 glob(cp, wp, tobool(f & DOMARKDIRS));
931 else if ((f & DOPAT) || !(fdo & DOMAGIC))
934 XPput(*wp, debunk(cp, cp,
939 tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
942 Xinit(ds, dp, 128, ATEMP);
945 } else if (type == XSUB && ctype(c, C_IFS) &&
946 !ctype(c, C_IFSWS) && Xlength(ds, dp) == 0) {
947 *(cp = alloc(1, ATEMP)) = '\0';
952 word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
955 if (word == IFS_NWS &&
956 Xlength(ds, dp) == 0) {
957 *(cp = alloc(1, ATEMP)) = '\0';
963 /* age tilde_ok info - ~ code tests second bit */
965 /* mark any special second pass chars */
973 * For character classes - doesn't hurt
974 * to have magic !,-,]s outside of
977 if (f & (DOPAT | DOGLOB)) {
986 if (f & (DOPAT | DOGLOB)) {
987 fdo |= DOMAGIC | (f & DOGLOB);
994 if ((f & DOBRACE) && (c == '{' /*}*/ ||
996 fdo |= DOBRACE|DOMAGIC;
1001 /* Note first unquoted = for ~ */
1002 if (!(f & DOTEMP) && !saw_eq &&
1003 (Flag(FBRACEEXPAND) ||
1004 (f & DOASNTILDE))) {
1011 /* Note unquoted : for ~ */
1012 if (!(f & DOTEMP) && (f & DOASNTILDE))
1017 * tilde_ok is reset whenever
1018 * any of ' " $( $(( ${ } are seen.
1019 * Note that tilde_ok must be preserved
1020 * through the sequence ${A=a=}~
1022 if (type == XBASE &&
1023 (f & (DOTILDE | DOASNTILDE)) &&
1028 tcp = maybe_expand_tilde(sp,
1030 tobool(f & DOASNTILDE));
1042 /* undo temporary */
1047 fdo |= DOMAGIC | (f & DOGLOB);
1049 } else if (ISMAGIC(c)) {
1053 /* save output char */
1061 * Prepare to generate the string returned by ${} substitution.
1064 varsub(Expand *xp, const char *sp, const char *word,
1065 int *stypep, /* becomes qualifier type */
1066 int *slenp) /* " " len (=, :=, etc.) valid iff *stypep != 0 */
1069 int state; /* next state: XBASE, XARG, XSUB, XNULLSUB */
1070 int stype; /* substitution type */
1074 bool zero_ok = false;
1076 if ((stype = sp[0]) == '\0')
1077 /* Bad variable name */
1083 * ${#var}, string length (-U: characters, +U: octets) or array size
1084 * ${%var}, string width (-U: screen columns, +U: octets)
1087 if (stype == '%' && c == '\0')
1089 if ((stype == '#' || stype == '%') && c != '\0') {
1090 /* Can't have any modifiers for ${#...} or ${%...} */
1091 if (*word != CSUBST)
1094 /* Check for size of array */
1095 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1101 vp = global(arrayname(sp));
1102 if (vp->flag & (ISSET|ARRAY))
1104 for (; vp; vp = vp->u.array)
1105 if (vp->flag & ISSET)
1108 } else if (c == '*' || c == '@') {
1113 p = str_val(global(sp));
1114 zero_ok = p != null;
1118 /* partial utf_mbswidth reimplementation */
1126 if (!UTFMODE || (len = utf_mbtowc(&wc,
1128 /* not UTFMODE or not UTF-8 */
1129 wc = (unsigned char)(*s++);
1131 /* UTFMODE and UTF-8 */
1133 /* wc == char or wchar at s++ */
1134 if ((cw = utf_wcwidth(wc)) == -1) {
1135 /* 646, 8859-1, 10646 C0/C1 */
1143 if (Flag(FNOUNSET) && c == 0 && !zero_ok)
1144 errorf("%s: %s", sp, "parameter not set");
1145 /* unqualified variable/string substitution */
1147 xp->str = shf_smprintf("%d", c);
1151 /* Check for qualifiers in word part */
1153 c = word[slen = 0] == CHAR ? word[1] : 0;
1157 c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
1159 if (!stype && c == '/') {
1162 if (word[slen] == ADELIM) {
1166 } else if (stype == 0x80 && (c == ' ' || c == '0')) {
1168 } else if (ctype(c, C_SUBOP1)) {
1171 } else if (ctype(c, C_SUBOP2)) {
1172 /* Note: ksh88 allows :%, :%%, etc */
1175 if (word[slen + 0] == CHAR && c == word[slen + 1]) {
1179 } else if (c == '@') {
1180 /* @x where x is command char */
1183 if (word[slen] == CHAR) {
1184 stype |= word[slen + 1];
1190 if (!stype && *word != CSUBST)
1196 if (c == '*' || c == '@') {
1197 switch (stype & 0x17F) {
1198 /* can't assign to a vector */
1200 /* can't trim a vector (yet) */
1209 if (e->loc->argc == 0) {
1211 xp->var = global(sp);
1212 state = c == '@' ? XNULLSUB : XSUB;
1214 xp->u.strv = (const char **)e->loc->argv + 1;
1215 xp->str = *xp->u.strv++;
1217 xp->split = tobool(c == '@');
1223 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1227 switch (stype & 0x17F) {
1228 /* can't assign to a vector */
1230 /* can't trim a vector (yet) */
1241 if ((c = sp[0]) == '!')
1243 vp = global(arrayname(sp));
1244 for (; vp; vp = vp->u.array) {
1245 if (!(vp->flag&ISSET))
1247 XPput(wv, c == '!' ? shf_smprintf("%lu",
1251 if (XPsize(wv) == 0) {
1253 state = p[1] == '@' ? XNULLSUB : XSUB;
1257 xp->u.strv = (const char **)XPptrv(wv);
1258 xp->str = *xp->u.strv++;
1260 xp->split = tobool(p[1] == '@');
1264 /* Can't assign things like $! or $1 */
1265 if ((stype & 0x17F) == '=' &&
1266 ctype(*sp, C_VAR1 | C_DIGIT))
1268 if (*sp == '!' && sp[1]) {
1270 xp->var = global(sp);
1271 if (vstrchr(sp, '['))
1272 xp->str = shf_smprintf("%s[%lu]",
1274 arrayindex(xp->var));
1276 xp->str = xp->var->name;
1278 xp->var = global(sp);
1279 xp->str = str_val(xp->var);
1286 /* test the compiler's code generator */
1287 if (((stype < 0x100) && (ctype(c, C_SUBOP2) || c == '/' ||
1288 (((stype&0x80) ? *xp->str=='\0' : xp->str==null) ? /* undef? */
1289 c == '=' || c == '-' || c == '?' : c == '+'))) ||
1290 stype == (0x80 | '0') || stype == (0x100 | '#') ||
1291 stype == (0x100 | 'Q'))
1292 /* expand word instead of variable value */
1294 if (Flag(FNOUNSET) && xp->str == null && !zero_ok &&
1295 (ctype(c, C_SUBOP2) || (state != XBASE && c != '+')))
1296 errorf("%s: %s", sp, "parameter not set");
1301 * Run the command in $(...) and read its output.
1304 comsub(Expand *xp, const char *cp, int fn MKSH_A_UNUSED)
1309 uint8_t old_utfmode = UTFMODE;
1311 s = pushs(SSTRING, ATEMP);
1312 s->start = s->str = cp;
1314 t = compile(s, true);
1318 UTFMODE = old_utfmode;
1323 /* no waitlast() unless specifically enabled later */
1326 if (t->type == TCOM &&
1327 *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
1329 struct ioword *io = *t->ioact;
1332 if ((io->ioflag & IOTYPE) != IOREAD)
1333 errorf("%s: %s", "funny $() command",
1334 snptreef(NULL, 32, "%R", io));
1335 shf = shf_open(name = evalstr(io->name, DOTILDE), O_RDONLY, 0,
1336 SHF_MAPHI|SHF_CLEXEC);
1338 warningf(!Flag(FTALKING), "%s: %s %s: %s", name,
1339 "can't open", "$(<...) input", cstrerror(errno));
1340 } else if (fn == FUNSUB) {
1342 struct temp *tf = NULL;
1345 * create a temporary file, open for reading and writing,
1346 * with an shf open for reading (buffered) but yet unused
1348 maketemp(ATEMP, TT_FUNSUB, &tf);
1350 errorf("can't %s temporary file %s: %s",
1351 "create", tf->tffn, cstrerror(errno));
1353 /* extract shf from temporary file, unlink and free it */
1357 /* save stdout and let it point to the tempfile */
1359 ksh_dup2(shf_fileno(shf), 1, false);
1361 * run tree, with output thrown into the tempfile,
1362 * in a new function block
1365 subst_exstat = exstat & 0xFF;
1366 /* rewind the tempfile and restore regular stdout */
1367 lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
1369 } else if (fn == VALSUB) {
1370 xp->str = valsub(t, ATEMP);
1371 subst_exstat = exstat & 0xFF;
1377 shf = shf_fdopen(pv[0], SHF_RD, NULL);
1380 ksh_dup2(pv[1], 1, false);
1383 execute(t, XXCOM | XPIPEO | XFORK, NULL);
1395 * perform #pattern and %pattern substitution in ${}
1398 trimsub(char *str, char *pat, int how)
1400 char *end = strnul(str);
1403 switch (how & 0xFF) {
1405 /* shortest match at beginning */
1406 for (p = str; p <= end; p += utf_ptradj(p)) {
1408 if (gmatchx(str, pat, false)) {
1416 /* longest match at beginning */
1417 for (p = end; p >= str; p--) {
1419 if (gmatchx(str, pat, false)) {
1427 /* shortest match at end */
1430 if (gmatchx(p, pat, false))
1434 while ((p-- > str) && ((*p & 0xC0) == 0x80))
1436 if ((p < str) || (p + utf_ptradj(p) != op))
1443 /* longest match at end */
1444 for (p = str; p <= end; p++)
1445 if (gmatchx(p, pat, false)) {
1447 strndupx(end, str, p - str, ATEMP);
1453 /* no match, return string */
1459 * Name derived from V6's /etc/glob, the program that expanded filenames.
1462 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
1464 glob(char *cp, XPtrV *wp, bool markdirs)
1466 int oldsize = XPsize(*wp);
1468 if (glob_str(cp, wp, markdirs) == 0)
1469 XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
1471 qsort(XPptrv(*wp) + oldsize, XPsize(*wp) - oldsize,
1472 sizeof(void *), xstrcmp);
1476 #define GF_EXCHECK BIT(0) /* do existence check on file */
1477 #define GF_GLOBBED BIT(1) /* some globbing has been done */
1478 #define GF_MARKDIR BIT(2) /* add trailing / to directories */
1481 * Apply file globbing to cp and store the matching files in wp. Returns
1482 * the number of matches found.
1485 glob_str(char *cp, XPtrV *wp, bool markdirs)
1487 int oldsize = XPsize(*wp);
1491 Xinit(xs, xp, 256, ATEMP);
1492 globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
1495 return (XPsize(*wp) - oldsize);
1499 globit(XString *xs, /* dest string */
1500 char **xpp, /* ptr to dest end */
1501 char *sp, /* source path */
1502 XPtrV *wp, /* output list */
1503 int check) /* GF_* flags */
1505 char *np; /* next source component */
1510 /* This to allow long expansions to be interrupted */
1514 /* end of source path */
1516 * We only need to check if the file exists if a pattern
1517 * is followed by a non-pattern (eg, foo*x/bar; no check
1518 * is needed for foo* since the match must exist) or if
1519 * any patterns were expanded and the markdirs option is set.
1520 * Symlinks make things a bit tricky...
1522 if ((check & GF_EXCHECK) ||
1523 ((check & GF_MARKDIR) && (check & GF_GLOBBED))) {
1524 #define stat_check() (stat_done ? stat_done : (stat_done = \
1525 stat(Xstring(*xs, xp), &statb) < 0 ? -1 : 1))
1526 struct stat lstatb, statb;
1527 /* -1: failed, 1 ok, 0 not yet done */
1530 if (mksh_lstat(Xstring(*xs, xp), &lstatb) < 0)
1533 * special case for systems which strip trailing
1534 * slashes from regular files (eg, /etc/passwd/).
1535 * SunOS 4.1.3 does this...
1537 if ((check & GF_EXCHECK) && xp > Xstring(*xs, xp) &&
1538 xp[-1] == '/' && !S_ISDIR(lstatb.st_mode) &&
1539 (!S_ISLNK(lstatb.st_mode) ||
1540 stat_check() < 0 || !S_ISDIR(statb.st_mode)))
1543 * Possibly tack on a trailing / if there isn't already
1544 * one and if the file is a directory or a symlink to a
1547 if (((check & GF_MARKDIR) && (check & GF_GLOBBED)) &&
1548 xp > Xstring(*xs, xp) && xp[-1] != '/' &&
1549 (S_ISDIR(lstatb.st_mode) ||
1550 (S_ISLNK(lstatb.st_mode) && stat_check() > 0 &&
1551 S_ISDIR(statb.st_mode)))) {
1556 strndupx(np, Xstring(*xs, xp), Xlength(*xs, xp), ATEMP);
1561 if (xp > Xstring(*xs, xp))
1563 while (*sp == '/') {
1567 np = strchr(sp, '/');
1570 /* don't assume '/', can be multiple kinds */
1574 odirsep = '\0'; /* keep gcc quiet */
1575 se = sp + strlen(sp);
1580 * Check if sp needs globbing - done to avoid pattern checks for strings
1581 * containing MAGIC characters, open [s without the matching close ],
1582 * etc. (otherwise opendir() will be called which may fail because the
1583 * directory isn't readable - if no globbing is needed, only execute
1584 * permission should be required (as per POSIX)).
1586 if (!has_globbing(sp, se)) {
1587 XcheckN(*xs, xp, se - sp + 1);
1588 debunk(xp, sp, Xnleft(*xs, xp));
1591 globit(xs, xpp, np, wp, check);
1596 size_t len, prefix_len;
1598 /* xp = *xpp; copy_non_glob() may have re-alloc'd xs */
1600 prefix_len = Xlength(*xs, xp);
1601 dirp = opendir(prefix_len ? Xstring(*xs, xp) : ".");
1604 while ((d = readdir(dirp)) != NULL) {
1606 if (name[0] == '.' &&
1607 (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1608 /* always ignore . and .. */
1610 if ((*name == '.' && *sp != '.') ||
1611 !gmatchx(name, sp, true))
1614 len = strlen(d->d_name) + 1;
1615 XcheckN(*xs, xp, len);
1616 memcpy(xp, name, len);
1617 *xpp = xp + len - 1;
1618 globit(xs, xpp, np, wp,
1619 (check & GF_MARKDIR) | GF_GLOBBED
1620 | (np ? GF_EXCHECK : GF_NONE));
1621 xp = Xstring(*xs, xp) + prefix_len;
1632 /* remove MAGIC from string */
1634 debunk(char *dp, const char *sp, size_t dlen)
1639 if ((s = cstrchr(sp, MAGIC))) {
1640 if (s - sp >= (ssize_t)dlen)
1642 memmove(dp, sp, s - sp);
1643 for (d = dp + (s - sp); *s && (d - dp < (ssize_t)dlen); s++)
1644 if (!ISMAGIC(*s) || !(*++s & 0x80) ||
1645 !vstrchr("*+?@! ", *s & 0x7f))
1648 /* extended pattern operators: *+?@! */
1649 if ((*s & 0x7f) != ' ')
1651 if (d - dp < (ssize_t)dlen)
1655 } else if (dp != sp)
1656 strlcpy(dp, sp, dlen);
1661 * Check if p is an unquoted name, possibly followed by a / or :. If so
1662 * puts the expanded version in *dcp,dp and returns a pointer in p just
1663 * past the name, otherwise returns 0.
1666 maybe_expand_tilde(const char *p, XString *dsp, char **dpp, bool isassign)
1673 Xinit(ts, tp, 16, ATEMP);
1674 /* : only for DOASNTILDE form */
1675 while (p[0] == CHAR && p[1] != '/' && (!isassign || p[1] != ':'))
1682 r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ?
1683 do_tilde(Xstring(ts, tp)) : NULL;
1701 * based on a version by Arnold Robbins
1710 dp = str_val(global("HOME"));
1711 else if (cp[0] == '+' && cp[1] == '\0')
1712 dp = str_val(global("PWD"));
1713 else if (ksh_isdash(cp))
1714 dp = str_val(global("OLDPWD"));
1715 #ifndef MKSH_NOPWNAM
1719 /* If HOME, PWD or OLDPWD are not set, don't expand ~ */
1720 return (dp == null ? NULL : dp);
1723 #ifndef MKSH_NOPWNAM
1725 * map userid to user's home directory.
1726 * note that 4.3's getpw adds more than 6K to the shell,
1727 * and the YP version probably adds much more.
1728 * we might consider our own version of getpwnam() to keep the size down.
1735 ap = ktenter(&homedirs, name, hash(name));
1736 if (!(ap->flag & ISSET)) {
1739 pw = getpwnam(name);
1742 strdupx(ap->val.s, pw->pw_dir, APERM);
1743 ap->flag |= DEFINED|ISSET|ALLOC;
1750 alt_expand(XPtrV *wp, char *start, char *exp_start, char *end, int fdo)
1752 unsigned int count = 0;
1753 char *brace_start, *brace_end, *comma = NULL;
1755 char *p = exp_start;
1757 /* search for open brace */
1758 while ((p = strchr(p, MAGIC)) && p[1] != '{' /*}*/)
1762 /* find matching close brace, if any */
1767 while (*p && count) {
1768 if (ISMAGIC(*p++)) {
1769 if (*p == '{' /*}*/)
1771 else if (*p == /*{*/ '}')
1773 else if (*p == ',' && count == 1)
1779 /* no valid expansions... */
1780 if (!p || count != 0) {
1782 * Note that given a{{b,c} we do not expand anything (this is
1783 * what AT&T ksh does. This may be changed to do the {b,c}
1787 glob(start, wp, tobool(fdo & DOMARKDIRS));
1789 XPput(*wp, debunk(start, start, end - start));
1794 alt_expand(wp, start, brace_end, end, fdo);
1798 /* expand expression */
1799 field_start = brace_start + 2;
1801 for (p = brace_start + 2; p != brace_end; p++) {
1803 if (*++p == '{' /*}*/)
1805 else if ((*p == /*{*/ '}' && --count == 0) ||
1806 (*p == ',' && count == 1)) {
1811 * addition safe since these operate on
1812 * one string (separate substrings)
1814 l1 = brace_start - start;
1815 l2 = (p - 1) - field_start;
1816 l3 = end - brace_end;
1817 news = alloc(l1 + l2 + l3 + 1, ATEMP);
1818 memcpy(news, start, l1);
1819 memcpy(news + l1, field_start, l2);
1820 memcpy(news + l1 + l2, brace_end, l3);
1821 news[l1 + l2 + l3] = '\0';
1822 alt_expand(wp, news, news + l1,
1823 news + l1 + l2 + l3, fdo);
1824 field_start = p + 1;
1831 /* helper function due to setjmp/longjmp woes */
1833 valsub(struct op *t, Area *ap)
1835 char * volatile cp = NULL;
1836 struct tbl * volatile vp = NULL;
1841 vp = local("REPLY", false);
1842 if (!kshsetjmp(e->jbuf))
1843 execute(t, XXCOM | XERROK, NULL);
1845 strdupx(cp, str_val(vp), ap);