OSDN Git Service

Upgrade to mksh 50.
[android-x86/external-mksh.git] / src / eval.c
1 /*      $OpenBSD: eval.c,v 1.40 2013/09/14 20:09:30 millert Exp $       */
2
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5  *               2011, 2012, 2013, 2014
6  *      Thorsten Glaser <tg@mirbsd.org>
7  *
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.
13  *
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.
22  */
23
24 #include "sh.h"
25
26 __RCSID("$MirOS: src/bin/mksh/eval.c,v 1.150 2014/06/09 11:16:07 tg Exp $");
27
28 /*
29  * string expansion
30  *
31  * first pass: quoting, IFS separation, ~, ${}, $() and $(()) substitution.
32  * second pass: alternation ({,}), filename expansion (*?[]).
33  */
34
35 /* expansion generator state */
36 typedef struct {
37         /* not including an "int type;" member, see expand() */
38         /* string */
39         const char *str;
40         /* source */
41         union {
42                 /* string[] */
43                 const char **strv;
44                 /* file */
45                 struct shf *shf;
46         } u;
47         /* variable in ${var...} */
48         struct tbl *var;
49         /* split "$@" / call waitlast in $() */
50         bool split;
51 } Expand;
52
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 ${} */
60
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 */
65
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);
73 #ifndef MKSH_NOPWNAM
74 static char *homedir(char *);
75 #endif
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 *);
79
80 /* UTFMODE functions */
81 static int
82 utflen(const char *s)
83 {
84         size_t n;
85
86         if (UTFMODE) {
87                 n = 0;
88                 while (*s) {
89                         s += utf_ptradj(s);
90                         ++n;
91                 }
92         } else
93                 n = strlen(s);
94
95         if (n > 2147483647)
96                 n = 2147483647;
97         return ((int)n);
98 }
99
100 static void
101 utfincptr(const char *s, mksh_ari_t *lp)
102 {
103         const char *cp = s;
104
105         while ((*lp)--)
106                 cp += utf_ptradj(cp);
107         *lp = cp - s;
108 }
109
110 /* compile and expand word */
111 char *
112 substitute(const char *cp, int f)
113 {
114         struct source *s, *sold;
115
116         sold = source;
117         s = pushs(SWSTR, ATEMP);
118         s->start = s->str = cp;
119         source = s;
120         if (yylex(ONEWORD) != LWORD)
121                 internal_errorf("bad substitution");
122         source = sold;
123         afree(s, ATEMP);
124         return (evalstr(yylval.cp, f));
125 }
126
127 /*
128  * expand arg-list
129  */
130 char **
131 eval(const char **ap, int f)
132 {
133         XPtrV w;
134
135         if (*ap == NULL) {
136                 union mksh_ccphack vap;
137
138                 vap.ro = ap;
139                 return (vap.rw);
140         }
141         XPinit(w, 32);
142         /* space for shell name */
143         XPput(w, NULL);
144         while (*ap != NULL)
145                 expand(*ap++, &w, f);
146         XPput(w, NULL);
147         return ((char **)XPclose(w) + 1);
148 }
149
150 /*
151  * expand string
152  */
153 char *
154 evalstr(const char *cp, int f)
155 {
156         XPtrV w;
157         char *dp = null;
158
159         XPinit(w, 1);
160         expand(cp, &w, f);
161         if (XPsize(w))
162                 dp = *XPptrv(w);
163         XPfree(w);
164         return (dp);
165 }
166
167 /*
168  * expand string - return only one component
169  * used from iosetup to expand redirection files
170  */
171 char *
172 evalonestr(const char *cp, int f)
173 {
174         XPtrV w;
175         char *rv;
176
177         XPinit(w, 1);
178         expand(cp, &w, f);
179         switch (XPsize(w)) {
180         case 0:
181                 rv = null;
182                 break;
183         case 1:
184                 rv = (char *) *XPptrv(w);
185                 break;
186         default:
187                 rv = evalstr(cp, f&~DOGLOB);
188                 break;
189         }
190         XPfree(w);
191         return (rv);
192 }
193
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 ${..[+-=]..}) */
204 } SubType;
205
206 void
207 expand(
208     /* input word */
209     const char *ccp,
210     /* output words */
211     XPtrV *wp,
212     /* DO* flags */
213     int f)
214 {
215         int c = 0;
216         /* expansion type */
217         int type;
218         /* quoted */
219         int quote = 0;
220         /* destination string and live pointer */
221         XString ds;
222         char *dp;
223         /* source */
224         const char *sp;
225         /* second pass flags */
226         int fdo;
227         /* have word */
228         int word;
229         /* field splitting of parameter/command substitution */
230         int doblank;
231         /* expansion variables */
232         Expand x = {
233                 NULL, { NULL }, NULL, 0
234         };
235         SubType st_head, *st;
236         /* record number of trailing newlines in COMSUB */
237         int newlines = 0;
238         bool saw_eq, make_magic;
239         int tilde_ok;
240         size_t len;
241         char *cp;
242
243         if (ccp == NULL)
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);
248                 f |= DOASNTILDE;
249         }
250         if (Flag(FNOGLOB))
251                 f &= ~DOGLOB;
252         if (Flag(FMARKDIRS))
253                 f |= DOMARKDIRS;
254         if (Flag(FBRACEEXPAND) && (f & DOGLOB))
255                 f |= DOBRACE;
256
257         /* init destination string */
258         Xinit(ds, dp, 128, ATEMP);
259         type = XBASE;
260         sp = ccp;
261         fdo = 0;
262         saw_eq = false;
263         /* must be 1/0 */
264         tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0;
265         doblank = 0;
266         make_magic = false;
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));
270         st = &st_head;
271
272         while (/* CONSTCOND */ 1) {
273                 Xcheck(ds, dp);
274
275                 switch (type) {
276                 case XBASE:
277                         /* original prefixed string */
278                         c = *sp++;
279                         switch (c) {
280                         case EOS:
281                                 c = 0;
282                                 break;
283                         case CHAR:
284                                 c = *sp++;
285                                 break;
286                         case QCHAR:
287                                 /* temporary quote */
288                                 quote |= 2;
289                                 c = *sp++;
290                                 break;
291                         case OQUOTE:
292                                 word = IFS_WORD;
293                                 tilde_ok = 0;
294                                 quote = 1;
295                                 continue;
296                         case CQUOTE:
297                                 quote = st->quotew;
298                                 continue;
299                         case COMSUB:
300                         case FUNSUB:
301                         case VALSUB:
302                                 tilde_ok = 0;
303                                 if (f & DONTRUNCOMMAND) {
304                                         word = IFS_WORD;
305                                         *dp++ = '$';
306                                         *dp++ = c == COMSUB ? '(' : '{';
307                                         if (c != COMSUB)
308                                                 *dp++ = c == FUNSUB ? ' ' : '|';
309                                         while (*sp != '\0') {
310                                                 Xcheck(ds, dp);
311                                                 *dp++ = *sp++;
312                                         }
313                                         if (c != COMSUB) {
314                                                 *dp++ = ';';
315                                                 *dp++ = '}';
316                                         } else
317                                                 *dp++ = ')';
318                                 } else {
319                                         type = comsub(&x, sp, c);
320                                         if (type != XBASE && (f & DOBLANK))
321                                                 doblank++;
322                                         sp = strnul(sp) + 1;
323                                         newlines = 0;
324                                 }
325                                 continue;
326                         case EXPRSUB:
327                                 tilde_ok = 0;
328                                 if (f & DONTRUNCOMMAND) {
329                                         word = IFS_WORD;
330                                         *dp++ = '$'; *dp++ = '('; *dp++ = '(';
331                                         while (*sp != '\0') {
332                                                 Xcheck(ds, dp);
333                                                 *dp++ = *sp++;
334                                         }
335                                         *dp++ = ')'; *dp++ = ')';
336                                 } else {
337                                         struct tbl v;
338
339                                         v.flag = DEFINED|ISSET|INTEGER;
340                                         /* not default */
341                                         v.type = 10;
342                                         v.name[0] = '\0';
343                                         v_evaluate(&v, substitute(sp, 0),
344                                             KSH_UNWIND_ERROR, true);
345                                         sp = strnul(sp) + 1;
346                                         x.str = str_val(&v);
347                                         type = XSUB;
348                                         if (f & DOBLANK)
349                                                 doblank++;
350                                 }
351                                 continue;
352                         case OSUBST: {
353                                 /* ${{#}var{:}[=+-?#%]word} */
354                         /*-
355                          * format is:
356                          *      OSUBST [{x] plain-variable-part \0
357                          *          compiled-word-part CSUBST [}x]
358                          * This is where all syntax checking gets done...
359                          */
360                                 /* skip the { or x (}) */
361                                 const char *varname = ++sp;
362                                 int stype;
363                                 int slen = 0;
364
365                                 /* skip variable */
366                                 sp = cstrchr(sp, '\0') + 1;
367                                 type = varsub(&x, varname, sp, &stype, &slen);
368                                 if (type < 0) {
369                                         char *beg, *end, *str;
370  unwind_substsyn:
371                                         /* restore sp */
372                                         sp = varname - 2;
373                                         end = (beg = wdcopy(sp, ATEMP)) +
374                                             (wdscan(sp, CSUBST) - sp);
375                                         /* ({) the } or x is already skipped */
376                                         if (end < wdscan(beg, EOS))
377                                                 *end = EOS;
378                                         str = snptreef(NULL, 64, "%S", beg);
379                                         afree(beg, ATEMP);
380                                         errorf("%s: %s", str, "bad substitution");
381                                 }
382                                 if (f & DOBLANK)
383                                         doblank++;
384                                 tilde_ok = 0;
385                                 if (type == XBASE) {
386                                         /* expand? */
387                                         if (!st->next) {
388                                                 SubType *newst;
389
390                                                 newst = alloc(sizeof(SubType), ATEMP);
391                                                 newst->next = NULL;
392                                                 newst->prev = st;
393                                                 st->next = newst;
394                                         }
395                                         st = st->next;
396                                         st->stype = stype;
397                                         st->base = Xsavepos(ds, dp);
398                                         st->f = f;
399                                         if (x.var == &vtemp) {
400                                                 st->var = tempvar();
401                                                 st->var->flag &= ~INTEGER;
402                                                 /* can't fail here */
403                                                 setstr(st->var,
404                                                     str_val(x.var),
405                                                     KSH_RETURN_ERROR | 0x4);
406                                         } else
407                                                 st->var = x.var;
408
409                                         st->quotew = st->quotep = quote;
410                                         /* skip qualifier(s) */
411                                         if (stype)
412                                                 sp += slen;
413                                         switch (stype & 0x17F) {
414                                         case 0x100 | '#':
415                                                 x.str = shf_smprintf("%08X",
416                                                     (unsigned int)hash(str_val(st->var)));
417                                                 break;
418                                         case 0x100 | 'Q': {
419                                                 struct shf shf;
420
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);
424                                                 break;
425                                         }
426                                         case '0': {
427                                                 char *beg, *mid, *end, *stg;
428                                                 mksh_ari_t from = 0, num = -1, flen, finc = 0;
429
430                                                 beg = wdcopy(sp, ATEMP);
431                                                 mid = beg + (wdscan(sp, ADELIM) - sp);
432                                                 stg = beg + (wdscan(sp, CSUBST) - sp);
433                                                 if (mid >= stg)
434                                                         goto unwind_substsyn;
435                                                 mid[-2] = EOS;
436                                                 if (mid[-1] == /*{*/'}') {
437                                                         sp += mid - beg - 1;
438                                                         end = NULL;
439                                                 } else {
440                                                         end = mid +
441                                                             (wdscan(mid, ADELIM) - mid);
442                                                         if (end >= stg ||
443                                                             /* more than max delimiters */
444                                                             end[-1] != /*{*/ '}')
445                                                                 goto unwind_substsyn;
446                                                         end[-2] = EOS;
447                                                         sp += end - beg - 1;
448                                                 }
449                                                 evaluate(substitute(stg = wdstrip(beg, 0), 0),
450                                                     &from, KSH_UNWIND_ERROR, true);
451                                                 afree(stg, ATEMP);
452                                                 if (end) {
453                                                         evaluate(substitute(stg = wdstrip(mid, 0), 0),
454                                                             &num, KSH_UNWIND_ERROR, true);
455                                                         afree(stg, ATEMP);
456                                                 }
457                                                 afree(beg, ATEMP);
458                                                 beg = str_val(st->var);
459                                                 flen = utflen(beg);
460                                                 if (from < 0) {
461                                                         if (-from < flen)
462                                                                 finc = flen + from;
463                                                 } else
464                                                         finc = from < flen ? from : flen;
465                                                 if (UTFMODE)
466                                                         utfincptr(beg, &finc);
467                                                 beg += finc;
468                                                 flen = utflen(beg);
469                                                 if (num < 0 || num > flen)
470                                                         num = flen;
471                                                 if (UTFMODE)
472                                                         utfincptr(beg, &num);
473                                                 strndupx(x.str, beg, num, ATEMP);
474                                                 goto do_CSUBST;
475                                         }
476                                         case '/': {
477                                                 char *s, *p, *d, *sbeg, *end;
478                                                 char *pat, *rrep;
479                                                 char *tpat0, *tpat1, *tpat2;
480
481                                                 s = wdcopy(sp, ATEMP);
482                                                 p = s + (wdscan(sp, ADELIM) - sp);
483                                                 d = s + (wdscan(sp, CSUBST) - sp);
484                                                 if (p >= d)
485                                                         goto unwind_substsyn;
486                                                 p[-2] = EOS;
487                                                 if (p[-1] == /*{*/'}')
488                                                         d = NULL;
489                                                 else
490                                                         d[-2] = EOS;
491                                                 sp += (d ? d : p) - s - 1;
492                                                 tpat0 = wdstrip(s,
493                                                     WDS_KEEPQ | WDS_MAGIC);
494                                                 pat = substitute(tpat0, 0);
495                                                 if (d) {
496                                                         d = wdstrip(p, WDS_KEEPQ);
497                                                         rrep = substitute(d, 0);
498                                                         afree(d, ATEMP);
499                                                 } else
500                                                         rrep = null;
501                                                 afree(s, ATEMP);
502                                                 s = d = pat;
503                                                 while (*s)
504                                                         if (*s != '\\' ||
505                                                             s[1] == '%' ||
506                                                             s[1] == '#' ||
507                                                             s[1] == '\0' ||
508                                 /* XXX really? */           s[1] == '\\' ||
509                                                             s[1] == '/')
510                                                                 *d++ = *s++;
511                                                         else
512                                                                 s++;
513                                                 *d = '\0';
514                                                 afree(tpat0, ATEMP);
515
516                                                 /* check for special cases */
517                                                 d = str_val(st->var);
518                                                 mkssert(d != NULL);
519                                                 switch (*pat) {
520                                                 case '#':
521                                                         /* anchor at begin */
522                                                         tpat0 = pat + 1;
523                                                         tpat1 = rrep;
524                                                         tpat2 = d;
525                                                         break;
526                                                 case '%':
527                                                         /* anchor at end */
528                                                         tpat0 = pat + 1;
529                                                         tpat1 = d;
530                                                         tpat2 = rrep;
531                                                         break;
532                                                 case '\0':
533                                                         /* empty pattern */
534                                                         goto no_repl;
535                                                 default:
536                                                         tpat0 = pat;
537                                                         /* silence gcc */
538                                                         tpat1 = tpat2 = NULL;
539                                                 }
540                                                 if (gmatchx(null, tpat0, false)) {
541                                                         /*
542                                                          * pattern matches
543                                                          * the empty string
544                                                          */
545                                                         if (tpat0 == pat)
546                                                                 goto no_repl;
547                                                         /* but is anchored */
548                                                         s = shf_smprintf("%s%s",
549                                                             tpat1, tpat2);
550                                                         goto do_repl;
551                                                 }
552
553                                                 /* prepare string on which to work */
554                                                 strdupx(s, d, ATEMP);
555                                                 sbeg = s;
556
557                                                 /* first see if we have any match at all */
558                                                 tpat0 = pat;
559                                                 if (*pat == '#') {
560                                                         /* anchor at the beginning */
561                                                         tpat1 = shf_smprintf("%s%c*", ++tpat0, MAGIC);
562                                                         tpat2 = tpat1;
563                                                 } else if (*pat == '%') {
564                                                         /* anchor at the end */
565                                                         tpat1 = shf_smprintf("%c*%s", MAGIC, ++tpat0);
566                                                         tpat2 = tpat0;
567                                                 } else {
568                                                         /* float */
569                                                         tpat1 = shf_smprintf("%c*%s%c*", MAGIC, pat, MAGIC);
570                                                         tpat2 = tpat1 + 2;
571                                                 }
572  again_repl:
573                                                 /*
574                                                  * this would not be necessary if gmatchx would return
575                                                  * the start and end values of a match found, like re*
576                                                  */
577                                                 if (!gmatchx(sbeg, tpat1, false))
578                                                         goto end_repl;
579                                                 end = strnul(s);
580                                                 /* now anchor the beginning of the match */
581                                                 if (*pat != '#')
582                                                         while (sbeg <= end) {
583                                                                 if (gmatchx(sbeg, tpat2, false))
584                                                                         break;
585                                                                 else
586                                                                         sbeg++;
587                                                         }
588                                                 /* now anchor the end of the match */
589                                                 p = end;
590                                                 if (*pat != '%')
591                                                         while (p >= sbeg) {
592                                                                 bool gotmatch;
593
594                                                                 c = *p;
595                                                                 *p = '\0';
596                                                                 gotmatch = tobool(gmatchx(sbeg, tpat0, false));
597                                                                 *p = c;
598                                                                 if (gotmatch)
599                                                                         break;
600                                                                 p--;
601                                                         }
602                                                 strndupx(end, s, sbeg - s, ATEMP);
603                                                 d = shf_smprintf("%s%s%s", end, rrep, p);
604                                                 afree(end, ATEMP);
605                                                 sbeg = d + (sbeg - s) + strlen(rrep);
606                                                 afree(s, ATEMP);
607                                                 s = d;
608                                                 if (stype & 0x80)
609                                                         goto again_repl;
610  end_repl:
611                                                 afree(tpat1, ATEMP);
612  do_repl:
613                                                 x.str = s;
614  no_repl:
615                                                 afree(pat, ATEMP);
616                                                 if (rrep != null)
617                                                         afree(rrep, ATEMP);
618                                                 goto do_CSUBST;
619                                         }
620                                         case '#':
621                                         case '%':
622                                                 /* ! DOBLANK,DOBRACE,DOTILDE */
623                                                 f = (f & DONTRUNCOMMAND) |
624                                                     DOPAT | DOTEMP;
625                                                 st->quotew = quote = 0;
626                                                 /*
627                                                  * Prepend open pattern (so |
628                                                  * in a trim will work as
629                                                  * expected)
630                                                  */
631                                                 if (!Flag(FSH)) {
632                                                         *dp++ = MAGIC;
633                                                         *dp++ = '@' | 0x80;
634                                                 }
635                                                 break;
636                                         case '=':
637                                                 /*
638                                                  * Enabling tilde expansion
639                                                  * after :s here is
640                                                  * non-standard ksh, but is
641                                                  * consistent with rules for
642                                                  * other assignments. Not
643                                                  * sure what POSIX thinks of
644                                                  * this.
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.
650                                                  */
651                                                 if (!(x.var->flag & INTEGER))
652                                                         f |= DOASNTILDE|DOTILDE;
653                                                 f |= DOTEMP;
654                                                 /*
655                                                  * These will be done after the
656                                                  * value has been assigned.
657                                                  */
658                                                 f &= ~(DOBLANK|DOGLOB|DOBRACE);
659                                                 tilde_ok = 1;
660                                                 break;
661                                         case '?':
662                                                 f &= ~DOBLANK;
663                                                 f |= DOTEMP;
664                                                 /* FALLTHROUGH */
665                                         default:
666                                                 /* Enable tilde expansion */
667                                                 tilde_ok = 1;
668                                                 f |= DOTILDE;
669                                         }
670                                 } else
671                                         /* skip word */
672                                         sp += wdscan(sp, CSUBST) - sp;
673                                 continue;
674                         }
675                         case CSUBST:
676                                 /* only get here if expanding word */
677  do_CSUBST:
678                                 /* ({) skip the } or x */
679                                 sp++;
680                                 /* in case of ${unset:-} */
681                                 tilde_ok = 0;
682                                 *dp = '\0';
683                                 quote = st->quotep;
684                                 f = st->f;
685                                 if (f & DOBLANK)
686                                         doblank--;
687                                 switch (st->stype & 0x17F) {
688                                 case '#':
689                                 case '%':
690                                         if (!Flag(FSH)) {
691                                                 /* Append end-pattern */
692                                                 *dp++ = MAGIC;
693                                                 *dp++ = ')';
694                                         }
695                                         *dp = '\0';
696                                         dp = Xrestpos(ds, dp, st->base);
697                                         /*
698                                          * Must use st->var since calling
699                                          * global would break things
700                                          * like x[i+=1].
701                                          */
702                                         x.str = trimsub(str_val(st->var),
703                                                 dp, st->stype);
704                                         if (x.str[0] != '\0') {
705                                                 word = IFS_WS;
706                                                 type = XSUB;
707                                         } else
708                                                 type = quote ? XSUB : XNULLSUB;
709                                         if (f & DOBLANK)
710                                                 doblank++;
711                                         st = st->prev;
712                                         continue;
713                                 case '=':
714                                         /*
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).
719                                          */
720                                         dp = Xrestpos(ds, dp, st->base);
721                                         /*
722                                          * Must use st->var since calling
723                                          * global would cause with things
724                                          * like x[i+=1] to be evaluated twice.
725                                          */
726                                         /*
727                                          * Note: not exported by FEXPORT
728                                          * in AT&T ksh.
729                                          */
730                                         /*
731                                          * XXX POSIX says readonly is only
732                                          * fatal for special builtins (setstr
733                                          * does readonly check).
734                                          */
735                                         len = strlen(dp) + 1;
736                                         setstr(st->var,
737                                             debunk(alloc(len, ATEMP),
738                                             dp, len), KSH_UNWIND_ERROR);
739                                         x.str = str_val(st->var);
740                                         type = XSUB;
741                                         if (f & DOBLANK)
742                                                 doblank++;
743                                         st = st->prev;
744                                         continue;
745                                 case '?': {
746                                         char *s = Xrestpos(ds, dp, st->base);
747
748                                         errorf("%s: %s", st->var->name,
749                                             dp == s ?
750                                             "parameter null or not set" :
751                                             (debunk(s, s, strlen(s) + 1), s));
752                                 }
753                                 case '0':
754                                 case '/':
755                                 case 0x100 | '#':
756                                 case 0x100 | 'Q':
757                                         dp = Xrestpos(ds, dp, st->base);
758                                         type = XSUB;
759                                         if (f & DOBLANK)
760                                                 doblank++;
761                                         st = st->prev;
762                                         continue;
763                                 }
764                                 st = st->prev;
765                                 type = XBASE;
766                                 continue;
767
768                         case OPAT:
769                                 /* open pattern: *(foo|bar) */
770                                 /* Next char is the type of pattern */
771                                 make_magic = true;
772                                 c = *sp++ | 0x80;
773                                 break;
774
775                         case SPAT:
776                                 /* pattern separator (|) */
777                                 make_magic = true;
778                                 c = '|';
779                                 break;
780
781                         case CPAT:
782                                 /* close pattern */
783                                 make_magic = true;
784                                 c = /*(*/ ')';
785                                 break;
786                         }
787                         break;
788
789                 case XNULLSUB:
790                         /*
791                          * Special case for "$@" (and "${foo[@]}") - no
792                          * word is generated if $# is 0 (unless there is
793                          * other stuff inside the quotes).
794                          */
795                         type = XBASE;
796                         if (f & DOBLANK) {
797                                 doblank--;
798                                 /*
799                                  * XXX not really correct:
800                                  *      x=; "$x$@"
801                                  * should generate a null argument and
802                                  *      set A; "${@:+}"
803                                  * shouldn't.
804                                  */
805                                 if (dp == Xstring(ds, dp))
806                                         word = IFS_WS;
807                         }
808                         continue;
809
810                 case XSUB:
811                 case XSUBMID:
812                         if ((c = *x.str++) == 0) {
813                                 type = XBASE;
814                                 if (f & DOBLANK)
815                                         doblank--;
816                                 continue;
817                         }
818                         break;
819
820                 case XARGSEP:
821                         type = XARG;
822                         quote = 1;
823                         /* FALLTHROUGH */
824                 case XARG:
825                         if ((c = *x.str++) == '\0') {
826                                 /*
827                                  * force null words to be created so
828                                  * set -- '' 2 ''; foo "$@" will do
829                                  * the right thing
830                                  */
831                                 if (quote && x.split)
832                                         word = IFS_WORD;
833                                 if ((x.str = *x.u.strv++) == NULL) {
834                                         type = XBASE;
835                                         if (f & DOBLANK)
836                                                 doblank--;
837                                         continue;
838                                 }
839                                 c = ifs0;
840                                 if (c == 0) {
841                                         if (quote && !x.split)
842                                                 continue;
843                                         /* this is so we don't terminate */
844                                         c = ' ';
845                                         /* now force-emit a word */
846                                         goto emit_word;
847                                 }
848                                 if (quote && x.split) {
849                                         /* terminate word for "$@" */
850                                         type = XARGSEP;
851                                         quote = 0;
852                                 }
853                         }
854                         break;
855
856                 case XCOM:
857                         if (x.u.shf == NULL) {
858                                 /* $(<...) failed */
859                                 subst_exstat = 1;
860                                 /* fake EOF */
861                                 c = EOF;
862                         } else if (newlines) {
863                                 /* spit out saved NLs */
864                                 c = '\n';
865                                 --newlines;
866                         } else {
867                                 while ((c = shf_getc(x.u.shf)) == 0 || c == '\n')
868                                         if (c == '\n')
869                                                 /* save newlines */
870                                                 newlines++;
871                                 if (newlines && c != EOF) {
872                                         shf_ungetc(c, x.u.shf);
873                                         c = '\n';
874                                         --newlines;
875                                 }
876                         }
877                         if (c == EOF) {
878                                 newlines = 0;
879                                 if (x.u.shf)
880                                         shf_close(x.u.shf);
881                                 if (x.split)
882                                         subst_exstat = waitlast();
883                                 type = XBASE;
884                                 if (f & DOBLANK)
885                                         doblank--;
886                                 continue;
887                         }
888                         break;
889                 }
890
891                 /* check for end of word or IFS separation */
892                 if (c == 0 || (!quote && (f & DOBLANK) && doblank &&
893                     !make_magic && ctype(c, C_IFS))) {
894                         /*-
895                          * How words are broken up:
896                          *                      |       value of c
897                          *      word            |       ws      nws     0
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).
905                          */
906                         if (word == IFS_WORD ||
907                             (!ctype(c, C_IFSWS) && c && word == IFS_NWS)) {
908  emit_word:
909                                 *dp++ = '\0';
910                                 cp = Xclose(ds, dp);
911                                 if (fdo & DOBRACE)
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))
919                                         XPput(*wp, cp);
920                                 else
921                                         XPput(*wp, debunk(cp, cp,
922                                             strlen(cp) + 1));
923                                 fdo = 0;
924                                 saw_eq = false;
925                                 tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0;
926                                 if (c == 0)
927                                         return;
928                                 Xinit(ds, dp, 128, ATEMP);
929                         } else if (c == 0) {
930                                 return;
931                         } else if (type == XSUB && ctype(c, C_IFS) &&
932                             !ctype(c, C_IFSWS) && Xlength(ds, dp) == 0) {
933                                 *(cp = alloc(1, ATEMP)) = '\0';
934                                 XPput(*wp, cp);
935                                 type = XSUBMID;
936                         }
937                         if (word != IFS_NWS)
938                                 word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
939                 } else {
940                         if (type == XSUB) {
941                                 if (word == IFS_NWS &&
942                                     Xlength(ds, dp) == 0) {
943                                         *(cp = alloc(1, ATEMP)) = '\0';
944                                         XPput(*wp, cp);
945                                 }
946                                 type = XSUBMID;
947                         }
948
949                         /* age tilde_ok info - ~ code tests second bit */
950                         tilde_ok <<= 1;
951                         /* mark any special second pass chars */
952                         if (!quote)
953                                 switch (c) {
954                                 case '[':
955                                 case '!':
956                                 case '-':
957                                 case ']':
958                                         /*
959                                          * For character classes - doesn't hurt
960                                          * to have magic !,-,]s outside of
961                                          * [...] expressions.
962                                          */
963                                         if (f & (DOPAT | DOGLOB)) {
964                                                 fdo |= DOMAGIC;
965                                                 if (c == '[')
966                                                         fdo |= f & DOGLOB;
967                                                 *dp++ = MAGIC;
968                                         }
969                                         break;
970                                 case '*':
971                                 case '?':
972                                         if (f & (DOPAT | DOGLOB)) {
973                                                 fdo |= DOMAGIC | (f & DOGLOB);
974                                                 *dp++ = MAGIC;
975                                         }
976                                         break;
977                                 case '{':
978                                 case '}':
979                                 case ',':
980                                         if ((f & DOBRACE) && (c == '{' /*}*/ ||
981                                             (fdo & DOBRACE))) {
982                                                 fdo |= DOBRACE|DOMAGIC;
983                                                 *dp++ = MAGIC;
984                                         }
985                                         break;
986                                 case '=':
987                                         /* Note first unquoted = for ~ */
988                                         if (!(f & DOTEMP) && !saw_eq &&
989                                             (Flag(FBRACEEXPAND) ||
990                                             (f & DOASNTILDE))) {
991                                                 saw_eq = true;
992                                                 tilde_ok = 1;
993                                         }
994                                         break;
995                                 case ':':
996                                         /* : */
997                                         /* Note unquoted : for ~ */
998                                         if (!(f & DOTEMP) && (f & DOASNTILDE))
999                                                 tilde_ok = 1;
1000                                         break;
1001                                 case '~':
1002                                         /*
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=}~
1007                                          */
1008                                         if (type == XBASE &&
1009                                             (f & (DOTILDE|DOASNTILDE)) &&
1010                                             (tilde_ok & 2)) {
1011                                                 const char *tcp;
1012                                                 char *tdp = dp;
1013
1014                                                 tcp = maybe_expand_tilde(sp,
1015                                                     &ds, &tdp,
1016                                                     f & DOASNTILDE);
1017                                                 if (tcp) {
1018                                                         if (dp != tdp)
1019                                                                 word = IFS_WORD;
1020                                                         dp = tdp;
1021                                                         sp = tcp;
1022                                                         continue;
1023                                                 }
1024                                         }
1025                                         break;
1026                                 }
1027                         else
1028                                 /* undo temporary */
1029                                 quote &= ~2;
1030
1031                         if (make_magic) {
1032                                 make_magic = false;
1033                                 fdo |= DOMAGIC | (f & DOGLOB);
1034                                 *dp++ = MAGIC;
1035                         } else if (ISMAGIC(c)) {
1036                                 fdo |= DOMAGIC;
1037                                 *dp++ = MAGIC;
1038                         }
1039                         /* save output char */
1040                         *dp++ = c;
1041                         word = IFS_WORD;
1042                 }
1043         }
1044 }
1045
1046 /*
1047  * Prepare to generate the string returned by ${} substitution.
1048  */
1049 static int
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 */
1053 {
1054         int c;
1055         int state;      /* next state: XBASE, XARG, XSUB, XNULLSUB */
1056         int stype;      /* substitution type */
1057         int slen;
1058         const char *p;
1059         struct tbl *vp;
1060         bool zero_ok = false;
1061
1062         if ((stype = sp[0]) == '\0')
1063                 /* Bad variable name */
1064                 return (-1);
1065
1066         xp->var = NULL;
1067
1068         /*-
1069          * ${#var}, string length (-U: characters, +U: octets) or array size
1070          * ${%var}, string width (-U: screen columns, +U: octets)
1071          */
1072         c = sp[1];
1073         if (stype == '%' && c == '\0')
1074                 return (-1);
1075         if ((stype == '#' || stype == '%') && c != '\0') {
1076                 /* Can't have any modifiers for ${#...} or ${%...} */
1077                 if (*word != CSUBST)
1078                         return (-1);
1079                 sp++;
1080                 /* Check for size of array */
1081                 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1082                     p[2] == ']') {
1083                         int n = 0;
1084
1085                         if (stype != '#')
1086                                 return (-1);
1087                         vp = global(arrayname(sp));
1088                         if (vp->flag & (ISSET|ARRAY))
1089                                 zero_ok = true;
1090                         for (; vp; vp = vp->u.array)
1091                                 if (vp->flag & ISSET)
1092                                         n++;
1093                         c = n;
1094                 } else if (c == '*' || c == '@') {
1095                         if (stype != '#')
1096                                 return (-1);
1097                         c = e->loc->argc;
1098                 } else {
1099                         p = str_val(global(sp));
1100                         zero_ok = p != null;
1101                         if (stype == '#')
1102                                 c = utflen(p);
1103                         else {
1104                                 /* partial utf_mbswidth reimplementation */
1105                                 const char *s = p;
1106                                 unsigned int wc;
1107                                 size_t len;
1108                                 int cw;
1109
1110                                 c = 0;
1111                                 while (*s) {
1112                                         if (!UTFMODE || (len = utf_mbtowc(&wc,
1113                                             s)) == (size_t)-1)
1114                                                 /* not UTFMODE or not UTF-8 */
1115                                                 wc = (unsigned char)(*s++);
1116                                         else
1117                                                 /* UTFMODE and UTF-8 */
1118                                                 s += len;
1119                                         /* wc == char or wchar at s++ */
1120                                         if ((cw = utf_wcwidth(wc)) == -1) {
1121                                                 /* 646, 8859-1, 10646 C0/C1 */
1122                                                 c = -1;
1123                                                 break;
1124                                         }
1125                                         c += cw;
1126                                 }
1127                         }
1128                 }
1129                 if (Flag(FNOUNSET) && c == 0 && !zero_ok)
1130                         errorf("%s: %s", sp, "parameter not set");
1131                 /* unqualified variable/string substitution */
1132                 *stypep = 0;
1133                 xp->str = shf_smprintf("%d", c);
1134                 return (XSUB);
1135         }
1136
1137         /* Check for qualifiers in word part */
1138         stype = 0;
1139         c = word[slen = 0] == CHAR ? word[1] : 0;
1140         if (c == ':') {
1141                 slen += 2;
1142                 stype = 0x80;
1143                 c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
1144         }
1145         if (!stype && c == '/') {
1146                 slen += 2;
1147                 stype = c;
1148                 if (word[slen] == ADELIM) {
1149                         slen += 2;
1150                         stype |= 0x80;
1151                 }
1152         } else if (stype == 0x80 && (c == ' ' || c == '0')) {
1153                 stype |= '0';
1154         } else if (ctype(c, C_SUBOP1)) {
1155                 slen += 2;
1156                 stype |= c;
1157         } else if (ctype(c, C_SUBOP2)) {
1158                 /* Note: ksh88 allows :%, :%%, etc */
1159                 slen += 2;
1160                 stype = c;
1161                 if (word[slen + 0] == CHAR && c == word[slen + 1]) {
1162                         stype |= 0x80;
1163                         slen += 2;
1164                 }
1165         } else if (c == '@') {
1166                 /* @x where x is command char */
1167                 slen += 2;
1168                 stype |= 0x100;
1169                 if (word[slen] == CHAR) {
1170                         stype |= word[slen + 1];
1171                         slen += 2;
1172                 }
1173         } else if (stype)
1174                 /* : is not ok */
1175                 return (-1);
1176         if (!stype && *word != CSUBST)
1177                 return (-1);
1178         *stypep = stype;
1179         *slenp = slen;
1180
1181         c = sp[0];
1182         if (c == '*' || c == '@') {
1183                 switch (stype & 0x17F) {
1184                 /* can't assign to a vector */
1185                 case '=':
1186                 /* can't trim a vector (yet) */
1187                 case '%':
1188                 case '#':
1189                 case '0':
1190                 case '/':
1191                 case 0x100 | '#':
1192                 case 0x100 | 'Q':
1193                         return (-1);
1194                 }
1195                 if (e->loc->argc == 0) {
1196                         xp->str = null;
1197                         xp->var = global(sp);
1198                         state = c == '@' ? XNULLSUB : XSUB;
1199                 } else {
1200                         xp->u.strv = (const char **)e->loc->argv + 1;
1201                         xp->str = *xp->u.strv++;
1202                         /* $@ */
1203                         xp->split = tobool(c == '@');
1204                         state = XARG;
1205                 }
1206                 /* POSIX 2009? */
1207                 zero_ok = true;
1208         } else {
1209                 if ((p = cstrchr(sp, '[')) && (p[1] == '*' || p[1] == '@') &&
1210                     p[2] == ']') {
1211                         XPtrV wv;
1212
1213                         switch (stype & 0x17F) {
1214                         /* can't assign to a vector */
1215                         case '=':
1216                         /* can't trim a vector (yet) */
1217                         case '%':
1218                         case '#':
1219                         case '?':
1220                         case '0':
1221                         case '/':
1222                         case 0x100 | '#':
1223                         case 0x100 | 'Q':
1224                                 return (-1);
1225                         }
1226                         XPinit(wv, 32);
1227                         if ((c = sp[0]) == '!')
1228                                 ++sp;
1229                         vp = global(arrayname(sp));
1230                         for (; vp; vp = vp->u.array) {
1231                                 if (!(vp->flag&ISSET))
1232                                         continue;
1233                                 XPput(wv, c == '!' ? shf_smprintf("%lu",
1234                                     arrayindex(vp)) :
1235                                     str_val(vp));
1236                         }
1237                         if (XPsize(wv) == 0) {
1238                                 xp->str = null;
1239                                 state = p[1] == '@' ? XNULLSUB : XSUB;
1240                                 XPfree(wv);
1241                         } else {
1242                                 XPput(wv, 0);
1243                                 xp->u.strv = (const char **)XPptrv(wv);
1244                                 xp->str = *xp->u.strv++;
1245                                 /* ${foo[@]} */
1246                                 xp->split = tobool(p[1] == '@');
1247                                 state = XARG;
1248                         }
1249                 } else {
1250                         /* Can't assign things like $! or $1 */
1251                         if ((stype & 0x17F) == '=' &&
1252                             ctype(*sp, C_VAR1 | C_DIGIT))
1253                                 return (-1);
1254                         if (*sp == '!' && sp[1]) {
1255                                 ++sp;
1256                                 xp->var = global(sp);
1257                                 if (vstrchr(sp, '['))
1258                                         xp->str = shf_smprintf("%s[%lu]",
1259                                             xp->var->name,
1260                                             arrayindex(xp->var));
1261                                 else
1262                                         xp->str = xp->var->name;
1263                         } else {
1264                                 xp->var = global(sp);
1265                                 xp->str = str_val(xp->var);
1266                         }
1267                         state = XSUB;
1268                 }
1269         }
1270
1271         c = stype & 0x7F;
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 */
1279                 state = XBASE;
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");
1283         return (state);
1284 }
1285
1286 /*
1287  * Run the command in $(...) and read its output.
1288  */
1289 static int
1290 comsub(Expand *xp, const char *cp, int fn MKSH_A_UNUSED)
1291 {
1292         Source *s, *sold;
1293         struct op *t;
1294         struct shf *shf;
1295         uint8_t old_utfmode = UTFMODE;
1296
1297         s = pushs(SSTRING, ATEMP);
1298         s->start = s->str = cp;
1299         sold = source;
1300         t = compile(s, true);
1301         afree(s, ATEMP);
1302         source = sold;
1303
1304         UTFMODE = old_utfmode;
1305
1306         if (t == NULL)
1307                 return (XBASE);
1308
1309         /* no waitlast() unless specifically enabled later */
1310         xp->split = false;
1311
1312         if (t->type == TCOM &&
1313             *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
1314                 /* $(<file) */
1315                 struct ioword *io = *t->ioact;
1316                 char *name;
1317
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);
1323                 if (shf == NULL)
1324                         warningf(!Flag(FTALKING), "%s: %s %s: %s", name,
1325                             "can't open", "$(<...) input", cstrerror(errno));
1326         } else if (fn == FUNSUB) {
1327                 int ofd1;
1328                 struct temp *tf = NULL;
1329
1330                 /*
1331                  * create a temporary file, open for reading and writing,
1332                  * with an shf open for reading (buffered) but yet unused
1333                  */
1334                 maketemp(ATEMP, TT_FUNSUB, &tf);
1335                 if (!tf->shf) {
1336                         errorf("can't %s temporary file %s: %s",
1337                             "create", tf->tffn, cstrerror(errno));
1338                 }
1339                 /* extract shf from temporary file, unlink and free it */
1340                 shf = tf->shf;
1341                 unlink(tf->tffn);
1342                 afree(tf, ATEMP);
1343                 /* save stdout and let it point to the tempfile */
1344                 ofd1 = savefd(1);
1345                 ksh_dup2(shf_fileno(shf), 1, false);
1346                 /*
1347                  * run tree, with output thrown into the tempfile,
1348                  * in a new function block
1349                  */
1350                 valsub(t, NULL);
1351                 subst_exstat = exstat & 0xFF;
1352                 /* rewind the tempfile and restore regular stdout */
1353                 lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
1354                 restfd(1, ofd1);
1355         } else if (fn == VALSUB) {
1356                 xp->str = valsub(t, ATEMP);
1357                 subst_exstat = exstat & 0xFF;
1358                 return (XSUB);
1359         } else {
1360                 int ofd1, pv[2];
1361
1362                 openpipe(pv);
1363                 shf = shf_fdopen(pv[0], SHF_RD, NULL);
1364                 ofd1 = savefd(1);
1365                 if (pv[1] != 1) {
1366                         ksh_dup2(pv[1], 1, false);
1367                         close(pv[1]);
1368                 }
1369                 execute(t, XXCOM | XPIPEO | XFORK, NULL);
1370                 restfd(1, ofd1);
1371                 startlast();
1372                 /* waitlast() */
1373                 xp->split = true;
1374         }
1375
1376         xp->u.shf = shf;
1377         return (XCOM);
1378 }
1379
1380 /*
1381  * perform #pattern and %pattern substitution in ${}
1382  */
1383 static char *
1384 trimsub(char *str, char *pat, int how)
1385 {
1386         char *end = strnul(str);
1387         char *p, c;
1388
1389         switch (how & 0xFF) {
1390         case '#':
1391                 /* shortest match at beginning */
1392                 for (p = str; p <= end; p += utf_ptradj(p)) {
1393                         c = *p; *p = '\0';
1394                         if (gmatchx(str, pat, false)) {
1395                                 *p = c;
1396                                 return (p);
1397                         }
1398                         *p = c;
1399                 }
1400                 break;
1401         case '#'|0x80:
1402                 /* longest match at beginning */
1403                 for (p = end; p >= str; p--) {
1404                         c = *p; *p = '\0';
1405                         if (gmatchx(str, pat, false)) {
1406                                 *p = c;
1407                                 return (p);
1408                         }
1409                         *p = c;
1410                 }
1411                 break;
1412         case '%':
1413                 /* shortest match at end */
1414                 p = end;
1415                 while (p >= str) {
1416                         if (gmatchx(p, pat, false))
1417                                 goto trimsub_match;
1418                         if (UTFMODE) {
1419                                 char *op = p;
1420                                 while ((p-- > str) && ((*p & 0xC0) == 0x80))
1421                                         ;
1422                                 if ((p < str) || (p + utf_ptradj(p) != op))
1423                                         p = op - 1;
1424                         } else
1425                                 --p;
1426                 }
1427                 break;
1428         case '%'|0x80:
1429                 /* longest match at end */
1430                 for (p = str; p <= end; p++)
1431                         if (gmatchx(p, pat, false)) {
1432  trimsub_match:
1433                                 strndupx(end, str, p - str, ATEMP);
1434                                 return (end);
1435                         }
1436                 break;
1437         }
1438
1439         /* no match, return string */
1440         return (str);
1441 }
1442
1443 /*
1444  * glob
1445  * Name derived from V6's /etc/glob, the program that expanded filenames.
1446  */
1447
1448 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
1449 static void
1450 glob(char *cp, XPtrV *wp, bool markdirs)
1451 {
1452         int oldsize = XPsize(*wp);
1453
1454         if (glob_str(cp, wp, markdirs) == 0)
1455                 XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
1456         else
1457                 qsort(XPptrv(*wp) + oldsize, XPsize(*wp) - oldsize,
1458                     sizeof(void *), xstrcmp);
1459 }
1460
1461 #define GF_NONE         0
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 */
1465
1466 /*
1467  * Apply file globbing to cp and store the matching files in wp. Returns
1468  * the number of matches found.
1469  */
1470 int
1471 glob_str(char *cp, XPtrV *wp, bool markdirs)
1472 {
1473         int oldsize = XPsize(*wp);
1474         XString xs;
1475         char *xp;
1476
1477         Xinit(xs, xp, 256, ATEMP);
1478         globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
1479         Xfree(xs, xp);
1480
1481         return (XPsize(*wp) - oldsize);
1482 }
1483
1484 static void
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 */
1490 {
1491         char *np;               /* next source component */
1492         char *xp = *xpp;
1493         char *se;
1494         char odirsep;
1495
1496         /* This to allow long expansions to be interrupted */
1497         intrcheck();
1498
1499         if (sp == NULL) {
1500                 /* end of source path */
1501                 /*
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...
1507                  */
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 */
1514                         int stat_done = 0;
1515
1516                         if (mksh_lstat(Xstring(*xs, xp), &lstatb) < 0)
1517                                 return;
1518                         /*
1519                          * special case for systems which strip trailing
1520                          * slashes from regular files (eg, /etc/passwd/).
1521                          * SunOS 4.1.3 does this...
1522                          */
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)))
1527                                 return;
1528                         /*
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
1531                          * directory
1532                          */
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)))) {
1538                                 *xp++ = '/';
1539                                 *xp = '\0';
1540                         }
1541                 }
1542                 strndupx(np, Xstring(*xs, xp), Xlength(*xs, xp), ATEMP);
1543                 XPput(*wp, np);
1544                 return;
1545         }
1546
1547         if (xp > Xstring(*xs, xp))
1548                 *xp++ = '/';
1549         while (*sp == '/') {
1550                 Xcheck(*xs, xp);
1551                 *xp++ = *sp++;
1552         }
1553         np = strchr(sp, '/');
1554         if (np != NULL) {
1555                 se = np;
1556                 /* don't assume '/', can be multiple kinds */
1557                 odirsep = *np;
1558                 *np++ = '\0';
1559         } else {
1560                 odirsep = '\0'; /* keep gcc quiet */
1561                 se = sp + strlen(sp);
1562         }
1563
1564
1565         /*
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)).
1571          */
1572         if (!has_globbing(sp, se)) {
1573                 XcheckN(*xs, xp, se - sp + 1);
1574                 debunk(xp, sp, Xnleft(*xs, xp));
1575                 xp += strlen(xp);
1576                 *xpp = xp;
1577                 globit(xs, xpp, np, wp, check);
1578         } else {
1579                 DIR *dirp;
1580                 struct dirent *d;
1581                 char *name;
1582                 size_t len, prefix_len;
1583
1584                 /* xp = *xpp;   copy_non_glob() may have re-alloc'd xs */
1585                 *xp = '\0';
1586                 prefix_len = Xlength(*xs, xp);
1587                 dirp = opendir(prefix_len ? Xstring(*xs, xp) : ".");
1588                 if (dirp == NULL)
1589                         goto Nodir;
1590                 while ((d = readdir(dirp)) != NULL) {
1591                         name = d->d_name;
1592                         if (name[0] == '.' &&
1593                             (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1594                                 /* always ignore . and .. */
1595                                 continue;
1596                         if ((*name == '.' && *sp != '.') ||
1597                             !gmatchx(name, sp, true))
1598                                 continue;
1599
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;
1608                 }
1609                 closedir(dirp);
1610  Nodir:
1611                 ;
1612         }
1613
1614         if (np != NULL)
1615                 *--np = odirsep;
1616 }
1617
1618 /* remove MAGIC from string */
1619 char *
1620 debunk(char *dp, const char *sp, size_t dlen)
1621 {
1622         char *d;
1623         const char *s;
1624
1625         if ((s = cstrchr(sp, MAGIC))) {
1626                 if (s - sp >= (ssize_t)dlen)
1627                         return (dp);
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))
1632                                 *d++ = *s;
1633                         else {
1634                                 /* extended pattern operators: *+?@! */
1635                                 if ((*s & 0x7f) != ' ')
1636                                         *d++ = *s & 0x7f;
1637                                 if (d - dp < (ssize_t)dlen)
1638                                         *d++ = '(';
1639                         }
1640                 *d = '\0';
1641         } else if (dp != sp)
1642                 strlcpy(dp, sp, dlen);
1643         return (dp);
1644 }
1645
1646 /*
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.
1650  */
1651 static const char *
1652 maybe_expand_tilde(const char *p, XString *dsp, char **dpp, int isassign)
1653 {
1654         XString ts;
1655         char *dp = *dpp;
1656         char *tp;
1657         const char *r;
1658
1659         Xinit(ts, tp, 16, ATEMP);
1660         /* : only for DOASNTILDE form */
1661         while (p[0] == CHAR && p[1] != '/' && (!isassign || p[1] != ':'))
1662         {
1663                 Xcheck(ts, tp);
1664                 *tp++ = p[1];
1665                 p += 2;
1666         }
1667         *tp = '\0';
1668         r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ?
1669             tilde(Xstring(ts, tp)) : NULL;
1670         Xfree(ts, tp);
1671         if (r) {
1672                 while (*r) {
1673                         Xcheck(*dsp, dp);
1674                         if (ISMAGIC(*r))
1675                                 *dp++ = MAGIC;
1676                         *dp++ = *r++;
1677                 }
1678                 *dpp = dp;
1679                 r = p;
1680         }
1681         return (r);
1682 }
1683
1684 /*
1685  * tilde expansion
1686  *
1687  * based on a version by Arnold Robbins
1688  */
1689
1690 char *
1691 tilde(char *cp)
1692 {
1693         char *dp = null;
1694
1695         if (cp[0] == '\0')
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
1702         else
1703                 dp = homedir(cp);
1704 #endif
1705         /* If HOME, PWD or OLDPWD are not set, don't expand ~ */
1706         return (dp == null ? NULL : dp);
1707 }
1708
1709 #ifndef MKSH_NOPWNAM
1710 /*
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.
1715  */
1716 static char *
1717 homedir(char *name)
1718 {
1719         struct tbl *ap;
1720
1721         ap = ktenter(&homedirs, name, hash(name));
1722         if (!(ap->flag & ISSET)) {
1723                 struct passwd *pw;
1724
1725                 pw = getpwnam(name);
1726                 if (pw == NULL)
1727                         return (NULL);
1728                 strdupx(ap->val.s, pw->pw_dir, APERM);
1729                 ap->flag |= DEFINED|ISSET|ALLOC;
1730         }
1731         return (ap->val.s);
1732 }
1733 #endif
1734
1735 static void
1736 alt_expand(XPtrV *wp, char *start, char *exp_start, char *end, int fdo)
1737 {
1738         int count = 0;
1739         char *brace_start, *brace_end, *comma = NULL;
1740         char *field_start;
1741         char *p;
1742
1743         /* search for open brace */
1744         for (p = exp_start; (p = strchr(p, MAGIC)) && p[1] != '{' /*}*/; p += 2)
1745                 ;
1746         brace_start = p;
1747
1748         /* find matching close brace, if any */
1749         if (p) {
1750                 comma = NULL;
1751                 count = 1;
1752                 for (p += 2; *p && count; p++) {
1753                         if (ISMAGIC(*p)) {
1754                                 if (*++p == '{' /*}*/)
1755                                         count++;
1756                                 else if (*p == /*{*/ '}')
1757                                         --count;
1758                                 else if (*p == ',' && count == 1)
1759                                         comma = p;
1760                         }
1761                 }
1762         }
1763         /* no valid expansions... */
1764         if (!p || count != 0) {
1765                 /*
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}
1768                  * expansion. }
1769                  */
1770                 if (fdo & DOGLOB)
1771                         glob(start, wp, tobool(fdo & DOMARKDIRS));
1772                 else
1773                         XPput(*wp, debunk(start, start, end - start));
1774                 return;
1775         }
1776         brace_end = p;
1777         if (!comma) {
1778                 alt_expand(wp, start, brace_end, end, fdo);
1779                 return;
1780         }
1781
1782         /* expand expression */
1783         field_start = brace_start + 2;
1784         count = 1;
1785         for (p = brace_start + 2; p != brace_end; p++) {
1786                 if (ISMAGIC(*p)) {
1787                         if (*++p == '{' /*}*/)
1788                                 count++;
1789                         else if ((*p == /*{*/ '}' && --count == 0) ||
1790                             (*p == ',' && count == 1)) {
1791                                 char *news;
1792                                 int l1, l2, l3;
1793
1794                                 /*
1795                                  * addition safe since these operate on
1796                                  * one string (separate substrings)
1797                                  */
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;
1809                         }
1810                 }
1811         }
1812         return;
1813 }
1814
1815 /* helper function due to setjmp/longjmp woes */
1816 static char *
1817 valsub(struct op *t, Area *ap)
1818 {
1819         char * volatile cp = NULL;
1820         struct tbl * volatile vp = NULL;
1821
1822         newenv(E_FUNC);
1823         newblock();
1824         if (ap)
1825                 vp = local("REPLY", false);
1826         if (!kshsetjmp(e->jbuf))
1827                 execute(t, XXCOM | XERROK, NULL);
1828         if (vp)
1829                 strdupx(cp, str_val(vp), ap);
1830         quitenv(NULL);
1831
1832         return (cp);
1833 }