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
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.150 2014/06/09 11:16:07 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) */
63 #define IFS_WS 1 /* have seen IFS white-space */
64 #define IFS_NWS 2 /* have seen IFS non-white-space */
66 static int varsub(Expand *, const char *, const char *, int *, int *);
67 static int comsub(Expand *, const char *, int);
68 static char *valsub(struct op *, Area *);
69 static char *trimsub(char *, char *, int);
70 static void glob(char *, XPtrV *, bool);
71 static void globit(XString *, char **, char *, XPtrV *, int);
72 static const char *maybe_expand_tilde(const char *, XString *, char **, int);
74 static char *homedir(char *);
76 static void alt_expand(XPtrV *, char *, char *, char *, int);
77 static int utflen(const char *) MKSH_A_PURE;
78 static void utfincptr(const char *, mksh_ari_t *);
80 /* UTFMODE functions */
101 utfincptr(const char *s, mksh_ari_t *lp)
106 cp += utf_ptradj(cp);
110 /* compile and expand word */
112 substitute(const char *cp, int f)
114 struct source *s, *sold;
117 s = pushs(SWSTR, ATEMP);
118 s->start = s->str = cp;
120 if (yylex(ONEWORD) != LWORD)
121 internal_errorf("bad substitution");
124 return (evalstr(yylval.cp, f));
131 eval(const char **ap, int f)
136 union mksh_ccphack vap;
142 /* space for shell name */
145 expand(*ap++, &w, f);
147 return ((char **)XPclose(w) + 1);
154 evalstr(const char *cp, int f)
168 * expand string - return only one component
169 * used from iosetup to expand redirection files
172 evalonestr(const char *cp, int f)
184 rv = (char *) *XPptrv(w);
187 rv = evalstr(cp, f&~DOGLOB);
194 /* for nested substitution: ${var:=$var2} */
195 typedef struct SubType {
196 struct tbl *var; /* variable for ${var..} */
197 struct SubType *prev; /* old type */
198 struct SubType *next; /* poped type (to avoid re-allocating) */
199 size_t base; /* begin position of expanded word */
200 short stype; /* [=+-?%#] action after expanded word */
201 short f; /* saved value of f (DOPAT, etc) */
202 uint8_t quotep; /* saved value of quote (for ${..[%#]..}) */
203 uint8_t quotew; /* saved value of quote (for ${..[+-=]..}) */
220 /* destination string and live pointer */
225 /* second pass flags */
229 /* field splitting of parameter/command substitution */
231 /* expansion variables */
233 NULL, { NULL }, NULL, 0
235 SubType st_head, *st;
236 /* record number of trailing newlines in COMSUB */
238 bool saw_eq, make_magic;
244 internal_errorf("expand(NULL)");
245 /* for alias, readonly, set, typeset commands */
246 if ((f & DOVACHECK) && is_wdvarassign(ccp)) {
247 f &= ~(DOVACHECK|DOBLANK|DOGLOB|DOTILDE);
254 if (Flag(FBRACEEXPAND) && (f & DOGLOB))
257 /* init destination string */
258 Xinit(ds, dp, 128, ATEMP);
264 tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0;
267 word = (f&DOBLANK) ? IFS_WS : IFS_WORD;
268 /* clang doesn't know OSUBST comes before CSUBST */
269 memset(&st_head, 0, sizeof(st_head));
272 while (/* CONSTCOND */ 1) {
277 /* original prefixed string */
287 /* temporary quote */
303 if (f & DONTRUNCOMMAND) {
306 *dp++ = c == COMSUB ? '(' : '{';
308 *dp++ = c == FUNSUB ? ' ' : '|';
309 while (*sp != '\0') {
319 type = comsub(&x, sp, c);
320 if (type != XBASE && (f & DOBLANK))
328 if (f & DONTRUNCOMMAND) {
330 *dp++ = '$'; *dp++ = '('; *dp++ = '(';
331 while (*sp != '\0') {
335 *dp++ = ')'; *dp++ = ')';
339 v.flag = DEFINED|ISSET|INTEGER;
343 v_evaluate(&v, substitute(sp, 0),
344 KSH_UNWIND_ERROR, true);
353 /* ${{#}var{:}[=+-?#%]word} */
356 * OSUBST [{x] plain-variable-part \0
357 * compiled-word-part CSUBST [}x]
358 * This is where all syntax checking gets done...
360 /* skip the { or x (}) */
361 const char *varname = ++sp;
366 sp = cstrchr(sp, '\0') + 1;
367 type = varsub(&x, varname, sp, &stype, &slen);
369 char *beg, *end, *str;
373 end = (beg = wdcopy(sp, ATEMP)) +
374 (wdscan(sp, CSUBST) - sp);
375 /* ({) the } or x is already skipped */
376 if (end < wdscan(beg, EOS))
378 str = snptreef(NULL, 64, "%S", beg);
380 errorf("%s: %s", str, "bad substitution");
390 newst = alloc(sizeof(SubType), ATEMP);
397 st->base = Xsavepos(ds, dp);
399 if (x.var == &vtemp) {
401 st->var->flag &= ~INTEGER;
402 /* can't fail here */
405 KSH_RETURN_ERROR | 0x4);
409 st->quotew = st->quotep = quote;
410 /* skip qualifier(s) */
413 switch (stype & 0x17F) {
415 x.str = shf_smprintf("%08X",
416 (unsigned int)hash(str_val(st->var)));
421 shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
422 print_value_quoted(&shf, str_val(st->var));
423 x.str = shf_sclose(&shf);
427 char *beg, *mid, *end, *stg;
428 mksh_ari_t from = 0, num = -1, flen, finc = 0;
430 beg = wdcopy(sp, ATEMP);
431 mid = beg + (wdscan(sp, ADELIM) - sp);
432 stg = beg + (wdscan(sp, CSUBST) - sp);
434 goto unwind_substsyn;
436 if (mid[-1] == /*{*/'}') {
441 (wdscan(mid, ADELIM) - mid);
443 /* more than max delimiters */
444 end[-1] != /*{*/ '}')
445 goto unwind_substsyn;
449 evaluate(substitute(stg = wdstrip(beg, 0), 0),
450 &from, KSH_UNWIND_ERROR, true);
453 evaluate(substitute(stg = wdstrip(mid, 0), 0),
454 &num, KSH_UNWIND_ERROR, true);
458 beg = str_val(st->var);
464 finc = from < flen ? from : flen;
466 utfincptr(beg, &finc);
469 if (num < 0 || num > flen)
472 utfincptr(beg, &num);
473 strndupx(x.str, beg, num, ATEMP);
477 char *s, *p, *d, *sbeg, *end;
479 char *tpat0, *tpat1, *tpat2;
481 s = wdcopy(sp, ATEMP);
482 p = s + (wdscan(sp, ADELIM) - sp);
483 d = s + (wdscan(sp, CSUBST) - sp);
485 goto unwind_substsyn;
487 if (p[-1] == /*{*/'}')
491 sp += (d ? d : p) - s - 1;
493 WDS_KEEPQ | WDS_MAGIC);
494 pat = substitute(tpat0, 0);
496 d = wdstrip(p, WDS_KEEPQ);
497 rrep = substitute(d, 0);
508 /* XXX really? */ s[1] == '\\' ||
516 /* check for special cases */
517 d = str_val(st->var);
521 /* anchor at begin */
538 tpat1 = tpat2 = NULL;
540 if (gmatchx(null, tpat0, false)) {
547 /* but is anchored */
548 s = shf_smprintf("%s%s",
553 /* prepare string on which to work */
554 strdupx(s, d, ATEMP);
557 /* first see if we have any match at all */
560 /* anchor at the beginning */
561 tpat1 = shf_smprintf("%s%c*", ++tpat0, MAGIC);
563 } else if (*pat == '%') {
564 /* anchor at the end */
565 tpat1 = shf_smprintf("%c*%s", MAGIC, ++tpat0);
569 tpat1 = shf_smprintf("%c*%s%c*", MAGIC, pat, MAGIC);
574 * this would not be necessary if gmatchx would return
575 * the start and end values of a match found, like re*
577 if (!gmatchx(sbeg, tpat1, false))
580 /* now anchor the beginning of the match */
582 while (sbeg <= end) {
583 if (gmatchx(sbeg, tpat2, false))
588 /* now anchor the end of the match */
596 gotmatch = tobool(gmatchx(sbeg, tpat0, false));
602 strndupx(end, s, sbeg - s, ATEMP);
603 d = shf_smprintf("%s%s%s", end, rrep, p);
605 sbeg = d + (sbeg - s) + strlen(rrep);
622 /* ! DOBLANK,DOBRACE,DOTILDE */
623 f = (f & DONTRUNCOMMAND) |
625 st->quotew = quote = 0;
627 * Prepend open pattern (so |
628 * in a trim will work as
638 * Enabling tilde expansion
640 * non-standard ksh, but is
641 * consistent with rules for
642 * other assignments. Not
643 * sure what POSIX thinks of
645 * Not doing tilde expansion
646 * for integer variables is a
647 * non-POSIX thing - makes
648 * sense though, since ~ is
649 * a arithmetic operator.
651 if (!(x.var->flag & INTEGER))
652 f |= DOASNTILDE|DOTILDE;
655 * These will be done after the
656 * value has been assigned.
658 f &= ~(DOBLANK|DOGLOB|DOBRACE);
666 /* Enable tilde expansion */
672 sp += wdscan(sp, CSUBST) - sp;
676 /* only get here if expanding word */
678 /* ({) skip the } or x */
680 /* in case of ${unset:-} */
687 switch (st->stype & 0x17F) {
691 /* Append end-pattern */
696 dp = Xrestpos(ds, dp, st->base);
698 * Must use st->var since calling
699 * global would break things
702 x.str = trimsub(str_val(st->var),
704 if (x.str[0] != '\0') {
708 type = quote ? XSUB : XNULLSUB;
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);
746 char *s = Xrestpos(ds, dp, st->base);
748 errorf("%s: %s", st->var->name,
750 "parameter null or not set" :
751 (debunk(s, s, strlen(s) + 1), s));
757 dp = Xrestpos(ds, dp, st->base);
769 /* open pattern: *(foo|bar) */
770 /* Next char is the type of pattern */
776 /* pattern separator (|) */
791 * Special case for "$@" (and "${foo[@]}") - no
792 * word is generated if $# is 0 (unless there is
793 * other stuff inside the quotes).
799 * XXX not really correct:
801 * should generate a null argument and
805 if (dp == Xstring(ds, dp))
812 if ((c = *x.str++) == 0) {
825 if ((c = *x.str++) == '\0') {
827 * force null words to be created so
828 * set -- '' 2 ''; foo "$@" will do
831 if (quote && x.split)
833 if ((x.str = *x.u.strv++) == NULL) {
841 if (quote && !x.split)
843 /* this is so we don't terminate */
845 /* now force-emit a word */
848 if (quote && x.split) {
849 /* terminate word for "$@" */
857 if (x.u.shf == NULL) {
862 } else if (newlines) {
863 /* spit out saved NLs */
867 while ((c = shf_getc(x.u.shf)) == 0 || c == '\n')
871 if (newlines && c != EOF) {
872 shf_ungetc(c, x.u.shf);
882 subst_exstat = waitlast();
891 /* check for end of word or IFS separation */
892 if (c == 0 || (!quote && (f & DOBLANK) && doblank &&
893 !make_magic && ctype(c, C_IFS))) {
895 * How words are broken up:
898 * -----------------------------------
899 * IFS_WORD w/WS w/NWS w
900 * IFS_WS -/WS w/NWS -
901 * IFS_NWS -/NWS w/NWS w
902 * (w means generate a word)
903 * Note that IFS_NWS/0 generates a word (AT&T ksh
904 * doesn't do this, but POSIX does).
906 if (word == IFS_WORD ||
907 (!ctype(c, C_IFSWS) && c && word == IFS_NWS)) {
912 /* also does globbing */
913 alt_expand(wp, cp, cp,
914 cp + Xlength(ds, (dp - 1)),
915 fdo | (f & DOMARKDIRS));
916 else if (fdo & DOGLOB)
917 glob(cp, wp, tobool(f & DOMARKDIRS));
918 else if ((f & DOPAT) || !(fdo & DOMAGIC))
921 XPput(*wp, debunk(cp, cp,
925 tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0;
928 Xinit(ds, dp, 128, ATEMP);
931 } else if (type == XSUB && ctype(c, C_IFS) &&
932 !ctype(c, C_IFSWS) && Xlength(ds, dp) == 0) {
933 *(cp = alloc(1, ATEMP)) = '\0';
938 word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
941 if (word == IFS_NWS &&
942 Xlength(ds, dp) == 0) {
943 *(cp = alloc(1, ATEMP)) = '\0';
949 /* age tilde_ok info - ~ code tests second bit */
951 /* mark any special second pass chars */
959 * For character classes - doesn't hurt
960 * to have magic !,-,]s outside of
963 if (f & (DOPAT | DOGLOB)) {
972 if (f & (DOPAT | DOGLOB)) {
973 fdo |= DOMAGIC | (f & DOGLOB);
980 if ((f & DOBRACE) && (c == '{' /*}*/ ||
982 fdo |= DOBRACE|DOMAGIC;
987 /* Note first unquoted = for ~ */
988 if (!(f & DOTEMP) && !saw_eq &&
989 (Flag(FBRACEEXPAND) ||
997 /* Note unquoted : for ~ */
998 if (!(f & DOTEMP) && (f & DOASNTILDE))
1003 * tilde_ok is reset whenever
1004 * any of ' " $( $(( ${ } are seen.
1005 * Note that tilde_ok must be preserved
1006 * through the sequence ${A=a=}~
1008 if (type == XBASE &&
1009 (f & (DOTILDE|DOASNTILDE)) &&
1014 tcp = maybe_expand_tilde(sp,
1028 /* undo temporary */
1033 fdo |= DOMAGIC | (f & DOGLOB);
1035 } else if (ISMAGIC(c)) {
1039 /* save output char */
1047 * Prepare to generate the string returned by ${} substitution.
1050 varsub(Expand *xp, const char *sp, const char *word,
1051 int *stypep, /* becomes qualifier type */
1052 int *slenp) /* " " len (=, :=, etc.) valid iff *stypep != 0 */
1055 int state; /* next state: XBASE, XARG, XSUB, XNULLSUB */
1056 int stype; /* substitution type */
1060 bool zero_ok = false;
1062 if ((stype = sp[0]) == '\0')
1063 /* Bad variable name */
1069 * ${#var}, string length (-U: characters, +U: octets) or array size
1070 * ${%var}, string width (-U: screen columns, +U: octets)
1073 if (stype == '%' && c == '\0')
1075 if ((stype == '#' || stype == '%') && c != '\0') {
1076 /* Can't have any modifiers for ${#...} or ${%...} */
1077 if (*word != CSUBST)
1080 /* Check for size of array */
1081 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1087 vp = global(arrayname(sp));
1088 if (vp->flag & (ISSET|ARRAY))
1090 for (; vp; vp = vp->u.array)
1091 if (vp->flag & ISSET)
1094 } else if (c == '*' || c == '@') {
1099 p = str_val(global(sp));
1100 zero_ok = p != null;
1104 /* partial utf_mbswidth reimplementation */
1112 if (!UTFMODE || (len = utf_mbtowc(&wc,
1114 /* not UTFMODE or not UTF-8 */
1115 wc = (unsigned char)(*s++);
1117 /* UTFMODE and UTF-8 */
1119 /* wc == char or wchar at s++ */
1120 if ((cw = utf_wcwidth(wc)) == -1) {
1121 /* 646, 8859-1, 10646 C0/C1 */
1129 if (Flag(FNOUNSET) && c == 0 && !zero_ok)
1130 errorf("%s: %s", sp, "parameter not set");
1131 /* unqualified variable/string substitution */
1133 xp->str = shf_smprintf("%d", c);
1137 /* Check for qualifiers in word part */
1139 c = word[slen = 0] == CHAR ? word[1] : 0;
1143 c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
1145 if (!stype && c == '/') {
1148 if (word[slen] == ADELIM) {
1152 } else if (stype == 0x80 && (c == ' ' || c == '0')) {
1154 } else if (ctype(c, C_SUBOP1)) {
1157 } else if (ctype(c, C_SUBOP2)) {
1158 /* Note: ksh88 allows :%, :%%, etc */
1161 if (word[slen + 0] == CHAR && c == word[slen + 1]) {
1165 } else if (c == '@') {
1166 /* @x where x is command char */
1169 if (word[slen] == CHAR) {
1170 stype |= word[slen + 1];
1176 if (!stype && *word != CSUBST)
1182 if (c == '*' || c == '@') {
1183 switch (stype & 0x17F) {
1184 /* can't assign to a vector */
1186 /* can't trim a vector (yet) */
1195 if (e->loc->argc == 0) {
1197 xp->var = global(sp);
1198 state = c == '@' ? XNULLSUB : XSUB;
1200 xp->u.strv = (const char **)e->loc->argv + 1;
1201 xp->str = *xp->u.strv++;
1203 xp->split = tobool(c == '@');
1209 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1213 switch (stype & 0x17F) {
1214 /* can't assign to a vector */
1216 /* can't trim a vector (yet) */
1227 if ((c = sp[0]) == '!')
1229 vp = global(arrayname(sp));
1230 for (; vp; vp = vp->u.array) {
1231 if (!(vp->flag&ISSET))
1233 XPput(wv, c == '!' ? shf_smprintf("%lu",
1237 if (XPsize(wv) == 0) {
1239 state = p[1] == '@' ? XNULLSUB : XSUB;
1243 xp->u.strv = (const char **)XPptrv(wv);
1244 xp->str = *xp->u.strv++;
1246 xp->split = tobool(p[1] == '@');
1250 /* Can't assign things like $! or $1 */
1251 if ((stype & 0x17F) == '=' &&
1252 ctype(*sp, C_VAR1 | C_DIGIT))
1254 if (*sp == '!' && sp[1]) {
1256 xp->var = global(sp);
1257 if (vstrchr(sp, '['))
1258 xp->str = shf_smprintf("%s[%lu]",
1260 arrayindex(xp->var));
1262 xp->str = xp->var->name;
1264 xp->var = global(sp);
1265 xp->str = str_val(xp->var);
1272 /* test the compiler's code generator */
1273 if (((stype < 0x100) && (ctype(c, C_SUBOP2) || c == '/' ||
1274 (((stype&0x80) ? *xp->str=='\0' : xp->str==null) ? /* undef? */
1275 c == '=' || c == '-' || c == '?' : c == '+'))) ||
1276 stype == (0x80 | '0') || stype == (0x100 | '#') ||
1277 stype == (0x100 | 'Q'))
1278 /* expand word instead of variable value */
1280 if (Flag(FNOUNSET) && xp->str == null && !zero_ok &&
1281 (ctype(c, C_SUBOP2) || (state != XBASE && c != '+')))
1282 errorf("%s: %s", sp, "parameter not set");
1287 * Run the command in $(...) and read its output.
1290 comsub(Expand *xp, const char *cp, int fn MKSH_A_UNUSED)
1295 uint8_t old_utfmode = UTFMODE;
1297 s = pushs(SSTRING, ATEMP);
1298 s->start = s->str = cp;
1300 t = compile(s, true);
1304 UTFMODE = old_utfmode;
1309 /* no waitlast() unless specifically enabled later */
1312 if (t->type == TCOM &&
1313 *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
1315 struct ioword *io = *t->ioact;
1318 if ((io->flag & IOTYPE) != IOREAD)
1319 errorf("%s: %s", "funny $() command",
1320 snptreef(NULL, 32, "%R", io));
1321 shf = shf_open(name = evalstr(io->name, DOTILDE), O_RDONLY, 0,
1322 SHF_MAPHI|SHF_CLEXEC);
1324 warningf(!Flag(FTALKING), "%s: %s %s: %s", name,
1325 "can't open", "$(<...) input", cstrerror(errno));
1326 } else if (fn == FUNSUB) {
1328 struct temp *tf = NULL;
1331 * create a temporary file, open for reading and writing,
1332 * with an shf open for reading (buffered) but yet unused
1334 maketemp(ATEMP, TT_FUNSUB, &tf);
1336 errorf("can't %s temporary file %s: %s",
1337 "create", tf->tffn, cstrerror(errno));
1339 /* extract shf from temporary file, unlink and free it */
1343 /* save stdout and let it point to the tempfile */
1345 ksh_dup2(shf_fileno(shf), 1, false);
1347 * run tree, with output thrown into the tempfile,
1348 * in a new function block
1351 subst_exstat = exstat & 0xFF;
1352 /* rewind the tempfile and restore regular stdout */
1353 lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
1355 } else if (fn == VALSUB) {
1356 xp->str = valsub(t, ATEMP);
1357 subst_exstat = exstat & 0xFF;
1363 shf = shf_fdopen(pv[0], SHF_RD, NULL);
1366 ksh_dup2(pv[1], 1, false);
1369 execute(t, XXCOM | XPIPEO | XFORK, NULL);
1381 * perform #pattern and %pattern substitution in ${}
1384 trimsub(char *str, char *pat, int how)
1386 char *end = strnul(str);
1389 switch (how & 0xFF) {
1391 /* shortest match at beginning */
1392 for (p = str; p <= end; p += utf_ptradj(p)) {
1394 if (gmatchx(str, pat, false)) {
1402 /* longest match at beginning */
1403 for (p = end; p >= str; p--) {
1405 if (gmatchx(str, pat, false)) {
1413 /* shortest match at end */
1416 if (gmatchx(p, pat, false))
1420 while ((p-- > str) && ((*p & 0xC0) == 0x80))
1422 if ((p < str) || (p + utf_ptradj(p) != op))
1429 /* longest match at end */
1430 for (p = str; p <= end; p++)
1431 if (gmatchx(p, pat, false)) {
1433 strndupx(end, str, p - str, ATEMP);
1439 /* no match, return string */
1445 * Name derived from V6's /etc/glob, the program that expanded filenames.
1448 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
1450 glob(char *cp, XPtrV *wp, bool markdirs)
1452 int oldsize = XPsize(*wp);
1454 if (glob_str(cp, wp, markdirs) == 0)
1455 XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
1457 qsort(XPptrv(*wp) + oldsize, XPsize(*wp) - oldsize,
1458 sizeof(void *), xstrcmp);
1462 #define GF_EXCHECK BIT(0) /* do existence check on file */
1463 #define GF_GLOBBED BIT(1) /* some globbing has been done */
1464 #define GF_MARKDIR BIT(2) /* add trailing / to directories */
1467 * Apply file globbing to cp and store the matching files in wp. Returns
1468 * the number of matches found.
1471 glob_str(char *cp, XPtrV *wp, bool markdirs)
1473 int oldsize = XPsize(*wp);
1477 Xinit(xs, xp, 256, ATEMP);
1478 globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
1481 return (XPsize(*wp) - oldsize);
1485 globit(XString *xs, /* dest string */
1486 char **xpp, /* ptr to dest end */
1487 char *sp, /* source path */
1488 XPtrV *wp, /* output list */
1489 int check) /* GF_* flags */
1491 char *np; /* next source component */
1496 /* This to allow long expansions to be interrupted */
1500 /* end of source path */
1502 * We only need to check if the file exists if a pattern
1503 * is followed by a non-pattern (eg, foo*x/bar; no check
1504 * is needed for foo* since the match must exist) or if
1505 * any patterns were expanded and the markdirs option is set.
1506 * Symlinks make things a bit tricky...
1508 if ((check & GF_EXCHECK) ||
1509 ((check & GF_MARKDIR) && (check & GF_GLOBBED))) {
1510 #define stat_check() (stat_done ? stat_done : (stat_done = \
1511 stat(Xstring(*xs, xp), &statb) < 0 ? -1 : 1))
1512 struct stat lstatb, statb;
1513 /* -1: failed, 1 ok, 0 not yet done */
1516 if (mksh_lstat(Xstring(*xs, xp), &lstatb) < 0)
1519 * special case for systems which strip trailing
1520 * slashes from regular files (eg, /etc/passwd/).
1521 * SunOS 4.1.3 does this...
1523 if ((check & GF_EXCHECK) && xp > Xstring(*xs, xp) &&
1524 xp[-1] == '/' && !S_ISDIR(lstatb.st_mode) &&
1525 (!S_ISLNK(lstatb.st_mode) ||
1526 stat_check() < 0 || !S_ISDIR(statb.st_mode)))
1529 * Possibly tack on a trailing / if there isn't already
1530 * one and if the file is a directory or a symlink to a
1533 if (((check & GF_MARKDIR) && (check & GF_GLOBBED)) &&
1534 xp > Xstring(*xs, xp) && xp[-1] != '/' &&
1535 (S_ISDIR(lstatb.st_mode) ||
1536 (S_ISLNK(lstatb.st_mode) && stat_check() > 0 &&
1537 S_ISDIR(statb.st_mode)))) {
1542 strndupx(np, Xstring(*xs, xp), Xlength(*xs, xp), ATEMP);
1547 if (xp > Xstring(*xs, xp))
1549 while (*sp == '/') {
1553 np = strchr(sp, '/');
1556 /* don't assume '/', can be multiple kinds */
1560 odirsep = '\0'; /* keep gcc quiet */
1561 se = sp + strlen(sp);
1566 * Check if sp needs globbing - done to avoid pattern checks for strings
1567 * containing MAGIC characters, open [s without the matching close ],
1568 * etc. (otherwise opendir() will be called which may fail because the
1569 * directory isn't readable - if no globbing is needed, only execute
1570 * permission should be required (as per POSIX)).
1572 if (!has_globbing(sp, se)) {
1573 XcheckN(*xs, xp, se - sp + 1);
1574 debunk(xp, sp, Xnleft(*xs, xp));
1577 globit(xs, xpp, np, wp, check);
1582 size_t len, prefix_len;
1584 /* xp = *xpp; copy_non_glob() may have re-alloc'd xs */
1586 prefix_len = Xlength(*xs, xp);
1587 dirp = opendir(prefix_len ? Xstring(*xs, xp) : ".");
1590 while ((d = readdir(dirp)) != NULL) {
1592 if (name[0] == '.' &&
1593 (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1594 /* always ignore . and .. */
1596 if ((*name == '.' && *sp != '.') ||
1597 !gmatchx(name, sp, true))
1600 len = strlen(d->d_name) + 1;
1601 XcheckN(*xs, xp, len);
1602 memcpy(xp, name, len);
1603 *xpp = xp + len - 1;
1604 globit(xs, xpp, np, wp,
1605 (check & GF_MARKDIR) | GF_GLOBBED
1606 | (np ? GF_EXCHECK : GF_NONE));
1607 xp = Xstring(*xs, xp) + prefix_len;
1618 /* remove MAGIC from string */
1620 debunk(char *dp, const char *sp, size_t dlen)
1625 if ((s = cstrchr(sp, MAGIC))) {
1626 if (s - sp >= (ssize_t)dlen)
1628 memmove(dp, sp, s - sp);
1629 for (d = dp + (s - sp); *s && (d - dp < (ssize_t)dlen); s++)
1630 if (!ISMAGIC(*s) || !(*++s & 0x80) ||
1631 !vstrchr("*+?@! ", *s & 0x7f))
1634 /* extended pattern operators: *+?@! */
1635 if ((*s & 0x7f) != ' ')
1637 if (d - dp < (ssize_t)dlen)
1641 } else if (dp != sp)
1642 strlcpy(dp, sp, dlen);
1647 * Check if p is an unquoted name, possibly followed by a / or :. If so
1648 * puts the expanded version in *dcp,dp and returns a pointer in p just
1649 * past the name, otherwise returns 0.
1652 maybe_expand_tilde(const char *p, XString *dsp, char **dpp, int isassign)
1659 Xinit(ts, tp, 16, ATEMP);
1660 /* : only for DOASNTILDE form */
1661 while (p[0] == CHAR && p[1] != '/' && (!isassign || p[1] != ':'))
1668 r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ?
1669 tilde(Xstring(ts, tp)) : NULL;
1687 * based on a version by Arnold Robbins
1696 dp = str_val(global("HOME"));
1697 else if (cp[0] == '+' && cp[1] == '\0')
1698 dp = str_val(global("PWD"));
1699 else if (cp[0] == '-' && cp[1] == '\0')
1700 dp = str_val(global("OLDPWD"));
1701 #ifndef MKSH_NOPWNAM
1705 /* If HOME, PWD or OLDPWD are not set, don't expand ~ */
1706 return (dp == null ? NULL : dp);
1709 #ifndef MKSH_NOPWNAM
1711 * map userid to user's home directory.
1712 * note that 4.3's getpw adds more than 6K to the shell,
1713 * and the YP version probably adds much more.
1714 * we might consider our own version of getpwnam() to keep the size down.
1721 ap = ktenter(&homedirs, name, hash(name));
1722 if (!(ap->flag & ISSET)) {
1725 pw = getpwnam(name);
1728 strdupx(ap->val.s, pw->pw_dir, APERM);
1729 ap->flag |= DEFINED|ISSET|ALLOC;
1736 alt_expand(XPtrV *wp, char *start, char *exp_start, char *end, int fdo)
1739 char *brace_start, *brace_end, *comma = NULL;
1743 /* search for open brace */
1744 for (p = exp_start; (p = strchr(p, MAGIC)) && p[1] != '{' /*}*/; p += 2)
1748 /* find matching close brace, if any */
1752 for (p += 2; *p && count; p++) {
1754 if (*++p == '{' /*}*/)
1756 else if (*p == /*{*/ '}')
1758 else if (*p == ',' && count == 1)
1763 /* no valid expansions... */
1764 if (!p || count != 0) {
1766 * Note that given a{{b,c} we do not expand anything (this is
1767 * what AT&T ksh does. This may be changed to do the {b,c}
1771 glob(start, wp, tobool(fdo & DOMARKDIRS));
1773 XPput(*wp, debunk(start, start, end - start));
1778 alt_expand(wp, start, brace_end, end, fdo);
1782 /* expand expression */
1783 field_start = brace_start + 2;
1785 for (p = brace_start + 2; p != brace_end; p++) {
1787 if (*++p == '{' /*}*/)
1789 else if ((*p == /*{*/ '}' && --count == 0) ||
1790 (*p == ',' && count == 1)) {
1795 * addition safe since these operate on
1796 * one string (separate substrings)
1798 l1 = brace_start - start;
1799 l2 = (p - 1) - field_start;
1800 l3 = end - brace_end;
1801 news = alloc(l1 + l2 + l3 + 1, ATEMP);
1802 memcpy(news, start, l1);
1803 memcpy(news + l1, field_start, l2);
1804 memcpy(news + l1 + l2, brace_end, l3);
1805 news[l1 + l2 + l3] = '\0';
1806 alt_expand(wp, news, news + l1,
1807 news + l1 + l2 + l3, fdo);
1808 field_start = p + 1;
1815 /* helper function due to setjmp/longjmp woes */
1817 valsub(struct op *t, Area *ap)
1819 char * volatile cp = NULL;
1820 struct tbl * volatile vp = NULL;
1825 vp = local("REPLY", false);
1826 if (!kshsetjmp(e->jbuf))
1827 execute(t, XXCOM | XERROK, NULL);
1829 strdupx(cp, str_val(vp), ap);