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, 2016, 2017
6 * mirabilos <m@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.201 2017/04/06 01:59:54 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 /* beginning 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(Tbadsubst);
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; /* start 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)
310 if (f & DONTRUNCOMMAND) {
323 *dp++ = c == VALSUB ? '|' : ' ';
327 while (*sp != '\0') {
335 type = comsub(&x, sp, c);
336 if (type != XBASE && (f & DOBLANK))
344 if (f & DONTRUNCOMMAND) {
346 *dp++ = '$'; *dp++ = '('; *dp++ = '(';
347 while (*sp != '\0') {
351 *dp++ = ')'; *dp++ = ')';
355 v.flag = DEFINED|ISSET|INTEGER;
359 v_evaluate(&v, substitute(sp, 0),
360 KSH_UNWIND_ERROR, true);
369 /* ${{#}var{:}[=+-?#%]word} */
372 * OSUBST [{x] plain-variable-part \0
373 * compiled-word-part CSUBST [}x]
374 * This is where all syntax checking gets done...
376 /* skip the { or x (}) */
377 const char *varname = ++sp;
382 sp = cstrchr(sp, '\0') + 1;
383 type = varsub(&x, varname, sp, &stype, &slen);
385 char *beg, *end, *str;
389 beg = wdcopy(sp, ATEMP);
390 end = (wdscan(cstrchr(sp, '\0') + 1,
392 /* ({) the } or x is already skipped */
393 if (end < wdscan(beg, EOS))
395 str = snptreef(NULL, 64, Tf_S, beg);
397 errorf(Tf_sD_s, str, Tbadsubst);
402 if (word == IFS_QUOTE && type != XNULLSUB)
409 newst = alloc(sizeof(SubType), ATEMP);
416 st->base = Xsavepos(ds, dp);
418 if (x.var == vtemp) {
419 st->var = tempvar(vtemp->name);
420 st->var->flag &= ~INTEGER;
421 /* can't fail here */
424 KSH_RETURN_ERROR | 0x4);
428 st->quotew = st->quotep = quote;
429 /* skip qualifier(s) */
432 switch (stype & 0x17F) {
434 x.str = shf_smprintf("%08X",
435 (unsigned int)hash(str_val(st->var)));
440 shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
441 print_value_quoted(&shf, str_val(st->var));
442 x.str = shf_sclose(&shf);
446 char *beg, *mid, *end, *stg;
447 mksh_ari_t from = 0, num = -1, flen, finc = 0;
449 beg = wdcopy(sp, ATEMP);
450 mid = beg + (wdscan(sp, ADELIM) - sp);
451 stg = beg + (wdscan(sp, CSUBST) - sp);
453 if (mid[-1] == /*{*/'}') {
458 (wdscan(mid, ADELIM) - mid);
459 if (end[-1] != /*{*/ '}')
460 /* more than max delimiters */
461 goto unwind_substsyn;
465 evaluate(substitute(stg = wdstrip(beg, 0), 0),
466 &from, KSH_UNWIND_ERROR, true);
469 evaluate(substitute(stg = wdstrip(mid, 0), 0),
470 &num, KSH_UNWIND_ERROR, true);
474 beg = str_val(st->var);
480 finc = from < flen ? from : flen;
482 utfincptr(beg, &finc);
485 if (num < 0 || num > flen)
488 utfincptr(beg, &num);
489 strndupx(x.str, beg, num, ATEMP);
494 char *s, *p, *d, *sbeg, *end;
495 char *pat = NULL, *rrep = null;
496 char fpat = 0, *tpat1, *tpat2;
497 char *ws, *wpat, *wrep;
499 s = ws = wdcopy(sp, ATEMP);
500 p = s + (wdscan(sp, ADELIM) - sp);
501 d = s + (wdscan(sp, CSUBST) - sp);
503 if (p[-1] == /*{*/'}')
507 sp += (d ? d : p) - s - 1;
508 if (!(stype & 0x180) &&
510 (s[1] == '#' || s[1] == '%'))
512 wpat = s + (fpat ? 2 : 0);
514 if (!(stype & 0x100)) {
515 rrep = wrep ? evalstr(wrep,
516 DOTILDE | DOSCALAR) :
520 /* prepare string on which to work */
521 strdupx(s, str_val(st->var), ATEMP);
525 DOTILDE | DOSCALAR | DOPAT);
526 /* check for special cases */
527 if (!*pat && !fpat) {
534 if ((stype & 0x180) &&
535 gmatchx(null, pat, false)) {
537 * pattern matches empty
538 * string => don't loop
543 /* first see if we have any match at all */
545 /* anchor at the beginning */
546 tpat1 = shf_smprintf("%s%c*", pat, MAGIC);
548 } else if (fpat == '%') {
549 /* anchor at the end */
550 tpat1 = shf_smprintf("%c*%s", MAGIC, pat);
554 tpat1 = shf_smprintf("%c*%s%c*", MAGIC, pat, MAGIC);
559 * this would not be necessary if gmatchx would return
560 * the start and end values of a match found, like re*
562 if (!gmatchx(sbeg, tpat1, false))
565 /* now anchor the beginning of the match */
567 while (sbeg <= end) {
568 if (gmatchx(sbeg, tpat2, false))
573 /* now anchor the end of the match */
581 gotmatch = tobool(gmatchx(sbeg, pat, false));
587 strndupx(end, sbeg, p - sbeg, ATEMP);
593 rrep = wrep ? evalstr(wrep,
594 DOTILDE | DOSCALAR) :
597 strndupx(end, s, sbeg - s, ATEMP);
598 d = shf_smprintf(Tf_sss, end, rrep, p);
600 sbeg = d + (sbeg - s) + strlen(rrep);
607 } else if (stype & 0x80)
621 /* ! DOBLANK,DOBRACE */
622 f = (f & DONTRUNCOMMAND) |
626 st->quotew = quote = 0;
628 * Prepend open pattern (so |
629 * in a trim will work as
639 * Tilde expansion for string
640 * variables in POSIX mode is
641 * governed by Austinbug 351.
642 * In non-POSIX mode historic
643 * ksh behaviour (enable it!)
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;
653 f |= DOTEMP | DOSCALAR;
655 * These will be done after the
656 * value has been assigned.
658 f &= ~(DOBLANK|DOGLOB|DOBRACE);
663 errorf("%s: parameter null or not set",
672 else if (dp == Xstring(ds, dp))
674 /* Enable tilde expansion */
680 sp += wdscan(sp, CSUBST) - sp;
684 /* only get here if expanding word */
686 /* ({) skip the } or x */
688 /* in case of ${unset:-} */
695 switch (st->stype & 0x17F) {
699 /* Append end-pattern */
704 dp = Xrestpos(ds, dp, st->base);
706 * Must use st->var since calling
707 * global would break things
710 x.str = trimsub(str_val(st->var),
712 if (x.str[0] != '\0') {
719 if (dp == Xstring(ds, dp))
729 * Restore our position and substitute
730 * the value of st->var (may not be
731 * the assigned value in the presence
732 * of integer/right-adj/etc attributes).
734 dp = Xrestpos(ds, dp, st->base);
736 * Must use st->var since calling
737 * global would cause with things
738 * like x[i+=1] to be evaluated twice.
741 * Note: not exported by FEXPORT
745 * XXX POSIX says readonly is only
746 * fatal for special builtins (setstr
747 * does readonly check).
749 len = strlen(dp) + 1;
751 debunk(alloc(len, ATEMP),
752 dp, len), KSH_UNWIND_ERROR);
753 x.str = str_val(st->var);
758 word = quote || (!*x.str && (f & DOSCALAR)) ? IFS_WORD : IFS_IWS;
761 dp = Xrestpos(ds, dp, st->base);
763 errorf(Tf_sD_s, st->var->name,
764 debunk(dp, dp, strlen(dp) + 1));
771 dp = Xrestpos(ds, dp, st->base);
773 word = quote || (!*x.str && (f & DOSCALAR)) ? IFS_WORD : IFS_IWS;
778 /* default: '-' '+' */
785 /* open pattern: *(foo|bar) */
786 /* Next char is the type of pattern */
792 /* pattern separator (|) */
807 * Special case for "$@" (and "${foo[@]}") - no
808 * word is generated if $# is 0 (unless there is
809 * other stuff inside the quotes).
814 if (dp == Xstring(ds, dp) && word != IFS_WORD)
821 if ((c = *x.str++) == 0) {
834 if ((c = *x.str++) == '\0') {
836 * force null words to be created so
837 * set -- "" 2 ""; echo "$@" will do
840 if (quote && x.split)
842 if ((x.str = *x.u.strv++) == NULL) {
849 if ((f & DOHEREDOC)) {
850 /* pseudo-field-split reliably */
855 if ((f & DOSCALAR)) {
856 /* do not field-split */
865 if (quote && !x.split)
867 if (!quote && word == IFS_WS)
869 /* this is so we don't terminate */
871 /* now force-emit a word */
874 if (quote && x.split) {
875 /* terminate word for "$@" */
883 if (x.u.shf == NULL) {
888 } else if (newlines) {
889 /* spit out saved NLs */
893 while ((c = shf_getc(x.u.shf)) == 0 ||
894 #ifdef MKSH_WITH_TEXTMODE
898 #ifdef MKSH_WITH_TEXTMODE
900 c = shf_getc(x.u.shf);
905 shf_ungetc(c, x.u.shf);
917 if (newlines && c != -1) {
918 shf_ungetc(c, x.u.shf);
928 subst_exstat = waitlast();
937 /* check for end of word or IFS separation */
938 if (c == 0 || (!quote && (f & DOBLANK) && doblank &&
939 !make_magic && ctype(c, C_IFS))) {
941 * How words are broken up:
944 * -----------------------------------
945 * IFS_WORD w/WS w/NWS w
946 * IFS_WS -/WS -/NWS -
947 * IFS_NWS -/NWS w/NWS -
948 * IFS_IWS -/WS w/NWS -
949 * (w means generate a word)
951 if ((word == IFS_WORD) || (word == IFS_QUOTE) || (c &&
952 (word == IFS_IWS || word == IFS_NWS) &&
953 !ctype(c, C_IFSWS))) {
960 /* also does globbing */
961 alt_expand(wp, cp, cp,
962 cp + Xlength(ds, (dp - 1)),
963 fdo | (f & DOMARKDIRS));
964 else if (fdo & DOGLOB)
965 glob(cp, wp, tobool(f & DOMARKDIRS));
966 else if ((f & DOPAT) || !(fdo & DOMAGIC))
969 XPput(*wp, debunk(cp, cp,
974 tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
977 Xinit(ds, dp, 128, ATEMP);
980 } else if (type == XSUB && ctype(c, C_IFS) &&
981 !ctype(c, C_IFSWS) && Xlength(ds, dp) == 0) {
982 *(cp = alloc(1, ATEMP)) = '\0';
987 word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
990 if (word == IFS_NWS &&
991 Xlength(ds, dp) == 0) {
992 *(cp = alloc(1, ATEMP)) = '\0';
998 /* age tilde_ok info - ~ code tests second bit */
1000 /* mark any special second pass chars */
1008 * For character classes - doesn't hurt
1009 * to have magic !,-,]s outside of
1010 * [...] expressions.
1012 if (f & (DOPAT | DOGLOB)) {
1021 if (f & (DOPAT | DOGLOB)) {
1022 fdo |= DOMAGIC | (f & DOGLOB);
1029 if ((f & DOBRACE) && (c == '{' /*}*/ ||
1031 fdo |= DOBRACE|DOMAGIC;
1036 /* Note first unquoted = for ~ */
1037 if (!(f & DOTEMP) && (!Flag(FPOSIX) ||
1038 (f & DOASNTILDE)) && !saw_eq) {
1045 /* Note unquoted : for ~ */
1046 if (!(f & DOTEMP) && (f & DOASNTILDE))
1051 * tilde_ok is reset whenever
1052 * any of ' " $( $(( ${ } are seen.
1053 * Note that tilde_ok must be preserved
1054 * through the sequence ${A=a=}~
1056 if (type == XBASE &&
1057 (f & (DOTILDE | DOASNTILDE)) &&
1062 tcp = maybe_expand_tilde(sp,
1064 tobool(f & DOASNTILDE));
1076 /* undo temporary */
1081 fdo |= DOMAGIC | (f & DOGLOB);
1083 } else if (ISMAGIC(c)) {
1087 /* save output char */
1095 hasnonempty(const char **strv)
1106 * Prepare to generate the string returned by ${} substitution.
1109 varsub(Expand *xp, const char *sp, const char *word,
1110 int *stypep, /* becomes qualifier type */
1111 int *slenp) /* " " len (=, :=, etc.) valid iff *stypep != 0 */
1114 int state; /* next state: XBASE, XARG, XSUB, XNULLSUB */
1115 int stype; /* substitution type */
1119 bool zero_ok = false;
1121 if ((stype = sp[0]) == '\0')
1122 /* Bad variable name */
1128 * ${#var}, string length (-U: characters, +U: octets) or array size
1129 * ${%var}, string width (-U: screen columns, +U: octets)
1132 if (stype == '%' && c == '\0')
1134 if ((stype == '#' || stype == '%') && c != '\0') {
1135 /* Can't have any modifiers for ${#...} or ${%...} */
1136 if (*word != CSUBST)
1139 /* Check for size of array */
1140 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1146 vp = global(arrayname(sp));
1147 if (vp->flag & (ISSET|ARRAY))
1149 for (; vp; vp = vp->u.array)
1150 if (vp->flag & ISSET)
1153 } else if (c == '*' || c == '@') {
1158 p = str_val(global(sp));
1159 zero_ok = p != null;
1163 /* partial utf_mbswidth reimplementation */
1171 if (!UTFMODE || (len = utf_mbtowc(&wc,
1173 /* not UTFMODE or not UTF-8 */
1174 wc = (unsigned char)(*s++);
1176 /* UTFMODE and UTF-8 */
1178 /* wc == char or wchar at s++ */
1179 if ((cw = utf_wcwidth(wc)) == -1) {
1180 /* 646, 8859-1, 10646 C0/C1 */
1188 if (Flag(FNOUNSET) && c == 0 && !zero_ok)
1189 errorf(Tf_parm, sp);
1190 /* unqualified variable/string substitution */
1192 xp->str = shf_smprintf(Tf_d, c);
1195 if (stype == '!' && c != '\0' && *word == CSUBST) {
1197 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1203 xp->var = global(sp);
1204 xp->str = p ? shf_smprintf("%s[%lu]",
1205 xp->var->name, arrayindex(xp->var)) : xp->var->name;
1210 /* Check for qualifiers in word part */
1212 c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
1216 c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
1218 if (!stype && c == '/') {
1221 if (word[slen] == ADELIM && word[slen + 1] == c) {
1225 } else if (stype == 0x80 && (c == ' ' || c == '0')) {
1227 } else if (ctype(c, C_SUBOP1)) {
1230 } else if (ksh_issubop2(c)) {
1231 /* Note: ksh88 allows :%, :%%, etc */
1234 if (word[slen + 0] == CHAR && c == word[slen + 1]) {
1238 } else if (c == '@') {
1239 /* @x where x is command char */
1240 switch (c = word[slen + 2] == CHAR ? word[slen + 3] : 0) {
1253 if (!stype && *word != CSUBST)
1257 if (c == '*' || c == '@') {
1258 switch (stype & 0x17F) {
1259 /* can't assign to a vector */
1261 /* can't trim a vector (yet) */
1272 if (e->loc->argc == 0) {
1274 xp->var = global(sp);
1275 state = c == '@' ? XNULLSUB : XSUB;
1277 xp->u.strv = (const char **)e->loc->argv + 1;
1278 xp->str = *xp->u.strv++;
1280 xp->split = tobool(c == '@');
1285 } else if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1289 switch (stype & 0x17F) {
1290 /* can't assign to a vector */
1292 /* can't trim a vector (yet) */
1306 vp = global(arrayname(sp));
1307 for (; vp; vp = vp->u.array) {
1308 if (!(vp->flag&ISSET))
1310 XPput(wv, c == '!' ? shf_smprintf(Tf_lu,
1314 if (XPsize(wv) == 0) {
1316 state = p[1] == '@' ? XNULLSUB : XSUB;
1320 xp->u.strv = (const char **)XPptrv(wv);
1321 xp->str = *xp->u.strv++;
1323 xp->split = tobool(p[1] == '@');
1327 xp->var = global(sp);
1328 xp->str = str_val(xp->var);
1329 /* can't assign things like $! or $1 */
1330 if ((stype & 0x17F) == '=' && !*xp->str &&
1331 ctype(*sp, C_VAR1 | C_DIGIT))
1337 /* test the compiler's code generator */
1338 if (((stype < 0x100) && (ksh_issubop2(c) ||
1339 (((stype & 0x80) ? *xp->str == '\0' : xp->str == null) &&
1340 (state != XARG || (ifs0 || xp->split ?
1341 (xp->u.strv[0] == NULL) : !hasnonempty(xp->u.strv))) ?
1342 c == '=' || c == '-' || c == '?' : c == '+'))) ||
1343 stype == (0x80 | '0') || stype == (0x100 | '#') ||
1344 stype == (0x100 | 'Q') || (stype & 0x7F) == '/')
1345 /* expand word instead of variable value */
1347 if (Flag(FNOUNSET) && xp->str == null && !zero_ok &&
1348 (ksh_issubop2(c) || (state != XBASE && c != '+')))
1349 errorf(Tf_parm, sp);
1356 * Run the command in $(...) and read its output.
1359 comsub(Expand *xp, const char *cp, int fn)
1364 bool doalias = false;
1365 uint8_t old_utfmode = UTFMODE;
1377 s = pushs(SSTRING, ATEMP);
1378 s->start = s->str = cp;
1380 t = compile(s, true, doalias);
1384 UTFMODE = old_utfmode;
1389 /* no waitlast() unless specifically enabled later */
1392 if (t->type == TCOM &&
1393 *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
1395 struct ioword *io = *t->ioact;
1398 switch (io->ioflag & IOTYPE) {
1400 shf = shf_open(name = evalstr(io->ioname, DOTILDE),
1401 O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
1403 warningf(!Flag(FTALKING), Tf_sD_s_sD_s,
1404 name, Tcant_open, "$(<...) input",
1408 if (!herein(io, &name)) {
1410 /* as $(…) requires, trim trailing newlines */
1411 name += strlen(name);
1412 while (name > xp->str && name[-1] == '\n')
1420 errorf(Tf_sD_s, T_funny_command,
1421 snptreef(NULL, 32, Tft_R, io));
1423 } else if (fn == FUNSUB) {
1425 struct temp *tf = NULL;
1428 * create a temporary file, open for reading and writing,
1429 * with an shf open for reading (buffered) but yet unused
1431 maketemp(ATEMP, TT_FUNSUB, &tf);
1434 Tcreate, tf->tffn, cstrerror(errno));
1436 /* extract shf from temporary file, unlink and free it */
1440 /* save stdout and let it point to the tempfile */
1442 ksh_dup2(shf_fileno(shf), 1, false);
1444 * run tree, with output thrown into the tempfile,
1445 * in a new function block
1448 subst_exstat = exstat & 0xFF;
1449 /* rewind the tempfile and restore regular stdout */
1450 lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
1452 } else if (fn == VALSUB) {
1453 xp->str = valsub(t, ATEMP);
1454 subst_exstat = exstat & 0xFF;
1460 shf = shf_fdopen(pv[0], SHF_RD, NULL);
1463 ksh_dup2(pv[1], 1, false);
1466 execute(t, XXCOM | XPIPEO | XFORK, NULL);
1478 * perform #pattern and %pattern substitution in ${}
1481 trimsub(char *str, char *pat, int how)
1483 char *end = strnul(str);
1486 switch (how & 0xFF) {
1488 /* shortest match at beginning */
1489 for (p = str; p <= end; p += utf_ptradj(p)) {
1491 if (gmatchx(str, pat, false)) {
1500 /* longest match at beginning */
1501 for (p = end; p >= str; p--) {
1503 if (gmatchx(str, pat, false)) {
1512 /* shortest match at end */
1515 if (gmatchx(p, pat, false))
1519 while ((p-- > str) && ((*p & 0xC0) == 0x80))
1521 if ((p < str) || (p + utf_ptradj(p) != op))
1528 /* longest match at end */
1529 for (p = str; p <= end; p++)
1530 if (gmatchx(p, pat, false)) {
1533 strndupx(end, str, p - str, ATEMP);
1539 /* no match, return string */
1545 * Name derived from V6's /etc/glob, the program that expanded filenames.
1548 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
1550 glob(char *cp, XPtrV *wp, bool markdirs)
1552 int oldsize = XPsize(*wp);
1554 if (glob_str(cp, wp, markdirs) == 0)
1555 XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
1557 qsort(XPptrv(*wp) + oldsize, XPsize(*wp) - oldsize,
1558 sizeof(void *), xstrcmp);
1562 #define GF_EXCHECK BIT(0) /* do existence check on file */
1563 #define GF_GLOBBED BIT(1) /* some globbing has been done */
1564 #define GF_MARKDIR BIT(2) /* add trailing / to directories */
1567 * Apply file globbing to cp and store the matching files in wp. Returns
1568 * the number of matches found.
1571 glob_str(char *cp, XPtrV *wp, bool markdirs)
1573 int oldsize = XPsize(*wp);
1577 Xinit(xs, xp, 256, ATEMP);
1578 globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
1581 return (XPsize(*wp) - oldsize);
1585 globit(XString *xs, /* dest string */
1586 char **xpp, /* ptr to dest end */
1587 char *sp, /* source path */
1588 XPtrV *wp, /* output list */
1589 int check) /* GF_* flags */
1591 char *np; /* next source component */
1596 /* This to allow long expansions to be interrupted */
1600 /* end of source path */
1602 * We only need to check if the file exists if a pattern
1603 * is followed by a non-pattern (eg, foo*x/bar; no check
1604 * is needed for foo* since the match must exist) or if
1605 * any patterns were expanded and the markdirs option is set.
1606 * Symlinks make things a bit tricky...
1608 if ((check & GF_EXCHECK) ||
1609 ((check & GF_MARKDIR) && (check & GF_GLOBBED))) {
1610 #define stat_check() (stat_done ? stat_done : (stat_done = \
1611 stat(Xstring(*xs, xp), &statb) < 0 ? -1 : 1))
1612 struct stat lstatb, statb;
1613 /* -1: failed, 1 ok, 0 not yet done */
1616 if (mksh_lstat(Xstring(*xs, xp), &lstatb) < 0)
1619 * special case for systems which strip trailing
1620 * slashes from regular files (eg, /etc/passwd/).
1621 * SunOS 4.1.3 does this...
1623 if ((check & GF_EXCHECK) && xp > Xstring(*xs, xp) &&
1624 mksh_cdirsep(xp[-1]) && !S_ISDIR(lstatb.st_mode) &&
1625 (!S_ISLNK(lstatb.st_mode) ||
1626 stat_check() < 0 || !S_ISDIR(statb.st_mode)))
1629 * Possibly tack on a trailing / if there isn't already
1630 * one and if the file is a directory or a symlink to a
1633 if (((check & GF_MARKDIR) && (check & GF_GLOBBED)) &&
1634 xp > Xstring(*xs, xp) && !mksh_cdirsep(xp[-1]) &&
1635 (S_ISDIR(lstatb.st_mode) ||
1636 (S_ISLNK(lstatb.st_mode) && stat_check() > 0 &&
1637 S_ISDIR(statb.st_mode)))) {
1642 strndupx(np, Xstring(*xs, xp), Xlength(*xs, xp), ATEMP);
1647 if (xp > Xstring(*xs, xp))
1649 while (mksh_cdirsep(*sp)) {
1653 np = mksh_sdirsep(sp);
1656 /* don't assume '/', can be multiple kinds */
1660 odirsep = '\0'; /* keep gcc quiet */
1661 se = sp + strlen(sp);
1666 * Check if sp needs globbing - done to avoid pattern checks for strings
1667 * containing MAGIC characters, open [s without the matching close ],
1668 * etc. (otherwise opendir() will be called which may fail because the
1669 * directory isn't readable - if no globbing is needed, only execute
1670 * permission should be required (as per POSIX)).
1672 if (!has_globbing(sp, se)) {
1673 XcheckN(*xs, xp, se - sp + 1);
1674 debunk(xp, sp, Xnleft(*xs, xp));
1677 globit(xs, xpp, np, wp, check);
1682 size_t len, prefix_len;
1684 /* xp = *xpp; copy_non_glob() may have re-alloc'd xs */
1686 prefix_len = Xlength(*xs, xp);
1687 dirp = opendir(prefix_len ? Xstring(*xs, xp) : Tdot);
1690 while ((d = readdir(dirp)) != NULL) {
1692 if (name[0] == '.' &&
1693 (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1694 /* always ignore . and .. */
1696 if ((*name == '.' && *sp != '.') ||
1697 !gmatchx(name, sp, true))
1700 len = strlen(d->d_name) + 1;
1701 XcheckN(*xs, xp, len);
1702 memcpy(xp, name, len);
1703 *xpp = xp + len - 1;
1704 globit(xs, xpp, np, wp,
1705 (check & GF_MARKDIR) | GF_GLOBBED
1706 | (np ? GF_EXCHECK : GF_NONE));
1707 xp = Xstring(*xs, xp) + prefix_len;
1718 /* remove MAGIC from string */
1720 debunk(char *dp, const char *sp, size_t dlen)
1725 if ((s = cstrchr(sp, MAGIC))) {
1726 if (s - sp >= (ssize_t)dlen)
1728 memmove(dp, sp, s - sp);
1729 for (d = dp + (s - sp); *s && (d - dp < (ssize_t)dlen); s++)
1730 if (!ISMAGIC(*s) || !(*++s & 0x80) ||
1731 !vstrchr("*+?@! ", *s & 0x7f))
1734 /* extended pattern operators: *+?@! */
1735 if ((*s & 0x7f) != ' ')
1737 if (d - dp < (ssize_t)dlen)
1741 } else if (dp != sp)
1742 strlcpy(dp, sp, dlen);
1747 * Check if p is an unquoted name, possibly followed by a / or :. If so
1748 * puts the expanded version in *dcp,dp and returns a pointer in p just
1749 * past the name, otherwise returns 0.
1752 maybe_expand_tilde(const char *p, XString *dsp, char **dpp, bool isassign)
1759 Xinit(ts, tp, 16, ATEMP);
1760 /* : only for DOASNTILDE form */
1761 while (p[0] == CHAR && /* not cdirsep */ p[1] != '/' &&
1762 (!isassign || p[1] != ':')) {
1768 r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ?
1769 do_tilde(Xstring(ts, tp)) : NULL;
1787 * based on a version by Arnold Robbins
1793 #ifndef MKSH_NOPWNAM
1794 bool do_simplify = true;
1798 dp = str_val(global("HOME"));
1799 else if (cp[0] == '+' && cp[1] == '\0')
1800 dp = str_val(global(TPWD));
1801 else if (ksh_isdash(cp))
1802 dp = str_val(global(TOLDPWD));
1803 #ifndef MKSH_NOPWNAM
1806 do_simplify = false;
1810 /* if parameters aren't set, don't expand ~ */
1811 if (dp == NULL || dp == null)
1814 /* simplify parameters as if cwd upon entry */
1815 #ifndef MKSH_NOPWNAM
1819 strdupx(dp, dp, ATEMP);
1825 #ifndef MKSH_NOPWNAM
1827 * map userid to user's home directory.
1828 * note that 4.3's getpw adds more than 6K to the shell,
1829 * and the YP version probably adds much more.
1830 * we might consider our own version of getpwnam() to keep the size down.
1837 ap = ktenter(&homedirs, name, hash(name));
1838 if (!(ap->flag & ISSET)) {
1841 pw = getpwnam(name);
1844 strdupx(ap->val.s, pw->pw_dir, APERM);
1845 ap->flag |= DEFINED|ISSET|ALLOC;
1852 alt_expand(XPtrV *wp, char *start, char *exp_start, char *end, int fdo)
1854 unsigned int count = 0;
1855 char *brace_start, *brace_end, *comma = NULL;
1857 char *p = exp_start;
1859 /* search for open brace */
1860 while ((p = strchr(p, MAGIC)) && p[1] != '{' /*}*/)
1864 /* find matching close brace, if any */
1869 while (*p && count) {
1870 if (ISMAGIC(*p++)) {
1871 if (*p == '{' /*}*/)
1873 else if (*p == /*{*/ '}')
1875 else if (*p == ',' && count == 1)
1881 /* no valid expansions... */
1882 if (!p || count != 0) {
1884 * Note that given a{{b,c} we do not expand anything (this is
1885 * what AT&T ksh does. This may be changed to do the {b,c}
1889 glob(start, wp, tobool(fdo & DOMARKDIRS));
1891 XPput(*wp, debunk(start, start, end - start));
1896 alt_expand(wp, start, brace_end, end, fdo);
1900 /* expand expression */
1901 field_start = brace_start + 2;
1903 for (p = brace_start + 2; p != brace_end; p++) {
1905 if (*++p == '{' /*}*/)
1907 else if ((*p == /*{*/ '}' && --count == 0) ||
1908 (*p == ',' && count == 1)) {
1913 * addition safe since these operate on
1914 * one string (separate substrings)
1916 l1 = brace_start - start;
1917 l2 = (p - 1) - field_start;
1918 l3 = end - brace_end;
1919 news = alloc(l1 + l2 + l3 + 1, ATEMP);
1920 memcpy(news, start, l1);
1921 memcpy(news + l1, field_start, l2);
1922 memcpy(news + l1 + l2, brace_end, l3);
1923 news[l1 + l2 + l3] = '\0';
1924 alt_expand(wp, news, news + l1,
1925 news + l1 + l2 + l3, fdo);
1926 field_start = p + 1;
1933 /* helper function due to setjmp/longjmp woes */
1935 valsub(struct op *t, Area *ap)
1937 char * volatile cp = NULL;
1938 struct tbl * volatile vp = NULL;
1943 vp = local("REPLY", false);
1944 if (!kshsetjmp(e->jbuf))
1945 execute(t, XXCOM | XERROK, NULL);
1947 strdupx(cp, str_val(vp), ap);