]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/expand.c
MFV of r270725, tzdata2014f
[FreeBSD/FreeBSD.git] / bin / sh / expand.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1997-2005
5  *      Herbert Xu <herbert@gondor.apana.org.au>.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #ifndef lint
36 #if 0
37 static char sccsid[] = "@(#)expand.c    8.5 (Berkeley) 5/15/95";
38 #endif
39 #endif /* not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #include <sys/types.h>
44 #include <sys/time.h>
45 #include <sys/stat.h>
46 #include <dirent.h>
47 #include <errno.h>
48 #include <inttypes.h>
49 #include <limits.h>
50 #include <pwd.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <wchar.h>
56 #include <wctype.h>
57
58 /*
59  * Routines to expand arguments to commands.  We have to deal with
60  * backquotes, shell variables, and file metacharacters.
61  */
62
63 #include "shell.h"
64 #include "main.h"
65 #include "nodes.h"
66 #include "eval.h"
67 #include "expand.h"
68 #include "syntax.h"
69 #include "parser.h"
70 #include "jobs.h"
71 #include "options.h"
72 #include "var.h"
73 #include "input.h"
74 #include "output.h"
75 #include "memalloc.h"
76 #include "error.h"
77 #include "mystring.h"
78 #include "arith.h"
79 #include "show.h"
80 #include "builtins.h"
81
82 /*
83  * Structure specifying which parts of the string should be searched
84  * for IFS characters.
85  */
86
87 struct ifsregion {
88         struct ifsregion *next; /* next region in list */
89         int begoff;             /* offset of start of region */
90         int endoff;             /* offset of end of region */
91         int inquotes;           /* search for nul bytes only */
92 };
93
94
95 static char *expdest;                   /* output of current string */
96 static struct nodelist *argbackq;       /* list of back quote expressions */
97 static struct ifsregion ifsfirst;       /* first struct in list of ifs regions */
98 static struct ifsregion *ifslastp;      /* last struct in list */
99 static struct arglist exparg;           /* holds expanded arg list */
100
101 static char *argstr(char *, int);
102 static char *exptilde(char *, int);
103 static char *expari(char *);
104 static void expbackq(union node *, int, int);
105 static int subevalvar(char *, char *, int, int, int, int, int);
106 static char *evalvar(char *, int);
107 static int varisset(const char *, int);
108 static void varvalue(const char *, int, int, int);
109 static void recordregion(int, int, int);
110 static void removerecordregions(int);
111 static void ifsbreakup(char *, struct arglist *);
112 static void expandmeta(struct strlist *, int);
113 static void expmeta(char *, char *);
114 static void addfname(char *);
115 static struct strlist *expsort(struct strlist *);
116 static struct strlist *msort(struct strlist *, int);
117 static int patmatch(const char *, const char *, int);
118 static char *cvtnum(int, char *);
119 static int collate_range_cmp(wchar_t, wchar_t);
120
121 static int
122 collate_range_cmp(wchar_t c1, wchar_t c2)
123 {
124         static wchar_t s1[2], s2[2];
125
126         s1[0] = c1;
127         s2[0] = c2;
128         return (wcscoll(s1, s2));
129 }
130
131 static char *
132 stputs_quotes(const char *data, const char *syntax, char *p)
133 {
134         while (*data) {
135                 CHECKSTRSPACE(2, p);
136                 if (syntax[(int)*data] == CCTL)
137                         USTPUTC(CTLESC, p);
138                 USTPUTC(*data++, p);
139         }
140         return (p);
141 }
142 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
143
144 /*
145  * Perform expansions on an argument, placing the resulting list of arguments
146  * in arglist.  Parameter expansion, command substitution and arithmetic
147  * expansion are always performed; additional expansions can be requested
148  * via flag (EXP_*).
149  * The result is left in the stack string.
150  * When arglist is NULL, perform here document expansion.
151  *
152  * Caution: this function uses global state and is not reentrant.
153  * However, a new invocation after an interrupted invocation is safe
154  * and will reset the global state for the new call.
155  */
156 void
157 expandarg(union node *arg, struct arglist *arglist, int flag)
158 {
159         struct strlist *sp;
160         char *p;
161
162         argbackq = arg->narg.backquote;
163         STARTSTACKSTR(expdest);
164         ifsfirst.next = NULL;
165         ifslastp = NULL;
166         argstr(arg->narg.text, flag);
167         if (arglist == NULL) {
168                 STACKSTRNUL(expdest);
169                 return;                 /* here document expanded */
170         }
171         STPUTC('\0', expdest);
172         p = grabstackstr(expdest);
173         exparg.lastp = &exparg.list;
174         /*
175          * TODO - EXP_REDIR
176          */
177         if (flag & EXP_FULL) {
178                 ifsbreakup(p, &exparg);
179                 *exparg.lastp = NULL;
180                 exparg.lastp = &exparg.list;
181                 expandmeta(exparg.list, flag);
182         } else {
183                 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
184                         rmescapes(p);
185                 sp = (struct strlist *)stalloc(sizeof (struct strlist));
186                 sp->text = p;
187                 *exparg.lastp = sp;
188                 exparg.lastp = &sp->next;
189         }
190         while (ifsfirst.next != NULL) {
191                 struct ifsregion *ifsp;
192                 INTOFF;
193                 ifsp = ifsfirst.next->next;
194                 ckfree(ifsfirst.next);
195                 ifsfirst.next = ifsp;
196                 INTON;
197         }
198         *exparg.lastp = NULL;
199         if (exparg.list) {
200                 *arglist->lastp = exparg.list;
201                 arglist->lastp = exparg.lastp;
202         }
203 }
204
205
206
207 /*
208  * Perform parameter expansion, command substitution and arithmetic
209  * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
210  * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
211  * This is used to expand word in ${var+word} etc.
212  * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
213  * characters to allow for further processing.
214  * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
215  */
216 static char *
217 argstr(char *p, int flag)
218 {
219         char c;
220         int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);  /* do CTLESC */
221         int firsteq = 1;
222         int split_lit;
223         int lit_quoted;
224
225         split_lit = flag & EXP_SPLIT_LIT;
226         lit_quoted = flag & EXP_LIT_QUOTED;
227         flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
228         if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
229                 p = exptilde(p, flag);
230         for (;;) {
231                 CHECKSTRSPACE(2, expdest);
232                 switch (c = *p++) {
233                 case '\0':
234                         return (p - 1);
235                 case CTLENDVAR:
236                 case CTLENDARI:
237                         return (p);
238                 case CTLQUOTEMARK:
239                         lit_quoted = 1;
240                         /* "$@" syntax adherence hack */
241                         if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
242                                 break;
243                         if ((flag & EXP_FULL) != 0)
244                                 USTPUTC(c, expdest);
245                         break;
246                 case CTLQUOTEEND:
247                         lit_quoted = 0;
248                         break;
249                 case CTLESC:
250                         if (quotes)
251                                 USTPUTC(c, expdest);
252                         c = *p++;
253                         USTPUTC(c, expdest);
254                         if (split_lit && !lit_quoted)
255                                 recordregion(expdest - stackblock() -
256                                     (quotes ? 2 : 1),
257                                     expdest - stackblock(), 0);
258                         break;
259                 case CTLVAR:
260                         p = evalvar(p, flag);
261                         break;
262                 case CTLBACKQ:
263                 case CTLBACKQ|CTLQUOTE:
264                         expbackq(argbackq->n, c & CTLQUOTE, flag);
265                         argbackq = argbackq->next;
266                         break;
267                 case CTLARI:
268                         p = expari(p);
269                         break;
270                 case ':':
271                 case '=':
272                         /*
273                          * sort of a hack - expand tildes in variable
274                          * assignments (after the first '=' and after ':'s).
275                          */
276                         USTPUTC(c, expdest);
277                         if (split_lit && !lit_quoted)
278                                 recordregion(expdest - stackblock() - 1,
279                                     expdest - stackblock(), 0);
280                         if (flag & EXP_VARTILDE && *p == '~' &&
281                             (c != '=' || firsteq)) {
282                                 if (c == '=')
283                                         firsteq = 0;
284                                 p = exptilde(p, flag);
285                         }
286                         break;
287                 default:
288                         USTPUTC(c, expdest);
289                         if (split_lit && !lit_quoted)
290                                 recordregion(expdest - stackblock() - 1,
291                                     expdest - stackblock(), 0);
292                 }
293         }
294 }
295
296 /*
297  * Perform tilde expansion, placing the result in the stack string and
298  * returning the next position in the input string to process.
299  */
300 static char *
301 exptilde(char *p, int flag)
302 {
303         char c, *startp = p;
304         struct passwd *pw;
305         char *home;
306         int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
307
308         while ((c = *p) != '\0') {
309                 switch(c) {
310                 case CTLESC: /* This means CTL* are always considered quoted. */
311                 case CTLVAR:
312                 case CTLBACKQ:
313                 case CTLBACKQ | CTLQUOTE:
314                 case CTLARI:
315                 case CTLENDARI:
316                 case CTLQUOTEMARK:
317                         return (startp);
318                 case ':':
319                         if (flag & EXP_VARTILDE)
320                                 goto done;
321                         break;
322                 case '/':
323                 case CTLENDVAR:
324                         goto done;
325                 }
326                 p++;
327         }
328 done:
329         *p = '\0';
330         if (*(startp+1) == '\0') {
331                 if ((home = lookupvar("HOME")) == NULL)
332                         goto lose;
333         } else {
334                 if ((pw = getpwnam(startp+1)) == NULL)
335                         goto lose;
336                 home = pw->pw_dir;
337         }
338         if (*home == '\0')
339                 goto lose;
340         *p = c;
341         if (quotes)
342                 STPUTS_QUOTES(home, SQSYNTAX, expdest);
343         else
344                 STPUTS(home, expdest);
345         return (p);
346 lose:
347         *p = c;
348         return (startp);
349 }
350
351
352 static void
353 removerecordregions(int endoff)
354 {
355         if (ifslastp == NULL)
356                 return;
357
358         if (ifsfirst.endoff > endoff) {
359                 while (ifsfirst.next != NULL) {
360                         struct ifsregion *ifsp;
361                         INTOFF;
362                         ifsp = ifsfirst.next->next;
363                         ckfree(ifsfirst.next);
364                         ifsfirst.next = ifsp;
365                         INTON;
366                 }
367                 if (ifsfirst.begoff > endoff)
368                         ifslastp = NULL;
369                 else {
370                         ifslastp = &ifsfirst;
371                         ifsfirst.endoff = endoff;
372                 }
373                 return;
374         }
375
376         ifslastp = &ifsfirst;
377         while (ifslastp->next && ifslastp->next->begoff < endoff)
378                 ifslastp=ifslastp->next;
379         while (ifslastp->next != NULL) {
380                 struct ifsregion *ifsp;
381                 INTOFF;
382                 ifsp = ifslastp->next->next;
383                 ckfree(ifslastp->next);
384                 ifslastp->next = ifsp;
385                 INTON;
386         }
387         if (ifslastp->endoff > endoff)
388                 ifslastp->endoff = endoff;
389 }
390
391 /*
392  * Expand arithmetic expression.
393  * Note that flag is not required as digits never require CTLESC characters.
394  */
395 static char *
396 expari(char *p)
397 {
398         char *q, *start;
399         arith_t result;
400         int begoff;
401         int quoted;
402         int adj;
403
404         quoted = *p++ == '"';
405         begoff = expdest - stackblock();
406         p = argstr(p, 0);
407         removerecordregions(begoff);
408         STPUTC('\0', expdest);
409         start = stackblock() + begoff;
410
411         q = grabstackstr(expdest);
412         result = arith(start);
413         ungrabstackstr(q, expdest);
414
415         start = stackblock() + begoff;
416         adj = start - expdest;
417         STADJUST(adj, expdest);
418
419         CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
420         fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
421         adj = strlen(expdest);
422         STADJUST(adj, expdest);
423         if (!quoted)
424                 recordregion(begoff, expdest - stackblock(), 0);
425         return p;
426 }
427
428
429 /*
430  * Perform command substitution.
431  */
432 static void
433 expbackq(union node *cmd, int quoted, int flag)
434 {
435         struct backcmd in;
436         int i;
437         char buf[128];
438         char *p;
439         char *dest = expdest;
440         struct ifsregion saveifs, *savelastp;
441         struct nodelist *saveargbackq;
442         char lastc;
443         int startloc = dest - stackblock();
444         char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
445         int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
446         size_t nnl;
447
448         INTOFF;
449         saveifs = ifsfirst;
450         savelastp = ifslastp;
451         saveargbackq = argbackq;
452         p = grabstackstr(dest);
453         evalbackcmd(cmd, &in);
454         ungrabstackstr(p, dest);
455         ifsfirst = saveifs;
456         ifslastp = savelastp;
457         argbackq = saveargbackq;
458
459         p = in.buf;
460         lastc = '\0';
461         nnl = 0;
462         /* Don't copy trailing newlines */
463         for (;;) {
464                 if (--in.nleft < 0) {
465                         if (in.fd < 0)
466                                 break;
467                         while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
468                         TRACE(("expbackq: read returns %d\n", i));
469                         if (i <= 0)
470                                 break;
471                         p = buf;
472                         in.nleft = i - 1;
473                 }
474                 lastc = *p++;
475                 if (lastc != '\0') {
476                         if (lastc == '\n') {
477                                 nnl++;
478                         } else {
479                                 CHECKSTRSPACE(nnl + 2, dest);
480                                 while (nnl > 0) {
481                                         nnl--;
482                                         USTPUTC('\n', dest);
483                                 }
484                                 if (quotes && syntax[(int)lastc] == CCTL)
485                                         USTPUTC(CTLESC, dest);
486                                 USTPUTC(lastc, dest);
487                         }
488                 }
489         }
490
491         if (in.fd >= 0)
492                 close(in.fd);
493         if (in.buf)
494                 ckfree(in.buf);
495         if (in.jp)
496                 exitstatus = waitforjob(in.jp, (int *)NULL);
497         if (quoted == 0)
498                 recordregion(startloc, dest - stackblock(), 0);
499         TRACE(("expbackq: size=%td: \"%.*s\"\n",
500                 ((dest - stackblock()) - startloc),
501                 (int)((dest - stackblock()) - startloc),
502                 stackblock() + startloc));
503         expdest = dest;
504         INTON;
505 }
506
507
508
509 static int
510 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
511   int varflags, int quotes)
512 {
513         char *startp;
514         char *loc = NULL;
515         char *q;
516         int c = 0;
517         struct nodelist *saveargbackq = argbackq;
518         int amount;
519
520         argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
521             subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
522             EXP_CASE : 0) | EXP_TILDE);
523         STACKSTRNUL(expdest);
524         argbackq = saveargbackq;
525         startp = stackblock() + startloc;
526         if (str == NULL)
527             str = stackblock() + strloc;
528
529         switch (subtype) {
530         case VSASSIGN:
531                 setvar(str, startp, 0);
532                 amount = startp - expdest;
533                 STADJUST(amount, expdest);
534                 varflags &= ~VSNUL;
535                 return 1;
536
537         case VSQUESTION:
538                 if (*p != CTLENDVAR) {
539                         outfmt(out2, "%s\n", startp);
540                         error((char *)NULL);
541                 }
542                 error("%.*s: parameter %snot set", (int)(p - str - 1),
543                       str, (varflags & VSNUL) ? "null or "
544                                               : nullstr);
545                 return 0;
546
547         case VSTRIMLEFT:
548                 for (loc = startp; loc < str; loc++) {
549                         c = *loc;
550                         *loc = '\0';
551                         if (patmatch(str, startp, quotes)) {
552                                 *loc = c;
553                                 goto recordleft;
554                         }
555                         *loc = c;
556                         if (quotes && *loc == CTLESC)
557                                 loc++;
558                 }
559                 return 0;
560
561         case VSTRIMLEFTMAX:
562                 for (loc = str - 1; loc >= startp;) {
563                         c = *loc;
564                         *loc = '\0';
565                         if (patmatch(str, startp, quotes)) {
566                                 *loc = c;
567                                 goto recordleft;
568                         }
569                         *loc = c;
570                         loc--;
571                         if (quotes && loc > startp && *(loc - 1) == CTLESC) {
572                                 for (q = startp; q < loc; q++)
573                                         if (*q == CTLESC)
574                                                 q++;
575                                 if (q > loc)
576                                         loc--;
577                         }
578                 }
579                 return 0;
580
581         case VSTRIMRIGHT:
582                 for (loc = str - 1; loc >= startp;) {
583                         if (patmatch(str, loc, quotes)) {
584                                 amount = loc - expdest;
585                                 STADJUST(amount, expdest);
586                                 return 1;
587                         }
588                         loc--;
589                         if (quotes && loc > startp && *(loc - 1) == CTLESC) {
590                                 for (q = startp; q < loc; q++)
591                                         if (*q == CTLESC)
592                                                 q++;
593                                 if (q > loc)
594                                         loc--;
595                         }
596                 }
597                 return 0;
598
599         case VSTRIMRIGHTMAX:
600                 for (loc = startp; loc < str - 1; loc++) {
601                         if (patmatch(str, loc, quotes)) {
602                                 amount = loc - expdest;
603                                 STADJUST(amount, expdest);
604                                 return 1;
605                         }
606                         if (quotes && *loc == CTLESC)
607                                 loc++;
608                 }
609                 return 0;
610
611
612         default:
613                 abort();
614         }
615
616 recordleft:
617         amount = ((str - 1) - (loc - startp)) - expdest;
618         STADJUST(amount, expdest);
619         while (loc != str - 1)
620                 *startp++ = *loc++;
621         return 1;
622 }
623
624
625 /*
626  * Expand a variable, and return a pointer to the next character in the
627  * input string.
628  */
629
630 static char *
631 evalvar(char *p, int flag)
632 {
633         int subtype;
634         int varflags;
635         char *var;
636         const char *val;
637         int patloc;
638         int c;
639         int set;
640         int special;
641         int startloc;
642         int varlen;
643         int varlenb;
644         int easy;
645         int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
646
647         varflags = (unsigned char)*p++;
648         subtype = varflags & VSTYPE;
649         var = p;
650         special = 0;
651         if (! is_name(*p))
652                 special = 1;
653         p = strchr(p, '=') + 1;
654 again: /* jump here after setting a variable with ${var=text} */
655         if (varflags & VSLINENO) {
656                 set = 1;
657                 special = 1;
658                 val = NULL;
659         } else if (special) {
660                 set = varisset(var, varflags & VSNUL);
661                 val = NULL;
662         } else {
663                 val = bltinlookup(var, 1);
664                 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
665                         val = NULL;
666                         set = 0;
667                 } else
668                         set = 1;
669         }
670         varlen = 0;
671         startloc = expdest - stackblock();
672         if (!set && uflag && *var != '@' && *var != '*') {
673                 switch (subtype) {
674                 case VSNORMAL:
675                 case VSTRIMLEFT:
676                 case VSTRIMLEFTMAX:
677                 case VSTRIMRIGHT:
678                 case VSTRIMRIGHTMAX:
679                 case VSLENGTH:
680                         error("%.*s: parameter not set", (int)(p - var - 1),
681                             var);
682                 }
683         }
684         if (set && subtype != VSPLUS) {
685                 /* insert the value of the variable */
686                 if (special) {
687                         if (varflags & VSLINENO)
688                                 STPUTBIN(var, p - var - 1, expdest);
689                         else
690                                 varvalue(var, varflags & VSQUOTE, subtype, flag);
691                         if (subtype == VSLENGTH) {
692                                 varlenb = expdest - stackblock() - startloc;
693                                 varlen = varlenb;
694                                 if (localeisutf8) {
695                                         val = stackblock() + startloc;
696                                         for (;val != expdest; val++)
697                                                 if ((*val & 0xC0) == 0x80)
698                                                         varlen--;
699                                 }
700                                 STADJUST(-varlenb, expdest);
701                         }
702                 } else {
703                         char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
704                                                                   : BASESYNTAX;
705
706                         if (subtype == VSLENGTH) {
707                                 for (;*val; val++)
708                                         if (!localeisutf8 ||
709                                             (*val & 0xC0) != 0x80)
710                                                 varlen++;
711                         }
712                         else {
713                                 if (quotes)
714                                         STPUTS_QUOTES(val, syntax, expdest);
715                                 else
716                                         STPUTS(val, expdest);
717
718                         }
719                 }
720         }
721
722         if (subtype == VSPLUS)
723                 set = ! set;
724
725         easy = ((varflags & VSQUOTE) == 0 ||
726                 (*var == '@' && shellparam.nparam != 1));
727
728
729         switch (subtype) {
730         case VSLENGTH:
731                 expdest = cvtnum(varlen, expdest);
732                 goto record;
733
734         case VSNORMAL:
735                 if (!easy)
736                         break;
737 record:
738                 recordregion(startloc, expdest - stackblock(),
739                     varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
740                     (*var == '@' || *var == '*')));
741                 break;
742
743         case VSPLUS:
744         case VSMINUS:
745                 if (!set) {
746                         argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
747                             (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
748                         break;
749                 }
750                 if (easy)
751                         goto record;
752                 break;
753
754         case VSTRIMLEFT:
755         case VSTRIMLEFTMAX:
756         case VSTRIMRIGHT:
757         case VSTRIMRIGHTMAX:
758                 if (!set)
759                         break;
760                 /*
761                  * Terminate the string and start recording the pattern
762                  * right after it
763                  */
764                 STPUTC('\0', expdest);
765                 patloc = expdest - stackblock();
766                 if (subevalvar(p, NULL, patloc, subtype,
767                     startloc, varflags, quotes) == 0) {
768                         int amount = (expdest - stackblock() - patloc) + 1;
769                         STADJUST(-amount, expdest);
770                 }
771                 /* Remove any recorded regions beyond start of variable */
772                 removerecordregions(startloc);
773                 goto record;
774
775         case VSASSIGN:
776         case VSQUESTION:
777                 if (!set) {
778                         if (subevalvar(p, var, 0, subtype, startloc, varflags,
779                             quotes)) {
780                                 varflags &= ~VSNUL;
781                                 /*
782                                  * Remove any recorded regions beyond
783                                  * start of variable
784                                  */
785                                 removerecordregions(startloc);
786                                 goto again;
787                         }
788                         break;
789                 }
790                 if (easy)
791                         goto record;
792                 break;
793
794         case VSERROR:
795                 c = p - var - 1;
796                 error("${%.*s%s}: Bad substitution", c, var,
797                     (c > 0 && *p != CTLENDVAR) ? "..." : "");
798
799         default:
800                 abort();
801         }
802
803         if (subtype != VSNORMAL) {      /* skip to end of alternative */
804                 int nesting = 1;
805                 for (;;) {
806                         if ((c = *p++) == CTLESC)
807                                 p++;
808                         else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
809                                 if (set)
810                                         argbackq = argbackq->next;
811                         } else if (c == CTLVAR) {
812                                 if ((*p++ & VSTYPE) != VSNORMAL)
813                                         nesting++;
814                         } else if (c == CTLENDVAR) {
815                                 if (--nesting == 0)
816                                         break;
817                         }
818                 }
819         }
820         return p;
821 }
822
823
824
825 /*
826  * Test whether a specialized variable is set.
827  */
828
829 static int
830 varisset(const char *name, int nulok)
831 {
832
833         if (*name == '!')
834                 return backgndpidset();
835         else if (*name == '@' || *name == '*') {
836                 if (*shellparam.p == NULL)
837                         return 0;
838
839                 if (nulok) {
840                         char **av;
841
842                         for (av = shellparam.p; *av; av++)
843                                 if (**av != '\0')
844                                         return 1;
845                         return 0;
846                 }
847         } else if (is_digit(*name)) {
848                 char *ap;
849                 long num;
850
851                 errno = 0;
852                 num = strtol(name, NULL, 10);
853                 if (errno != 0 || num > shellparam.nparam)
854                         return 0;
855
856                 if (num == 0)
857                         ap = arg0;
858                 else
859                         ap = shellparam.p[num - 1];
860
861                 if (nulok && (ap == NULL || *ap == '\0'))
862                         return 0;
863         }
864         return 1;
865 }
866
867 static void
868 strtodest(const char *p, int flag, int subtype, int quoted)
869 {
870         if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
871                 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
872         else
873                 STPUTS(p, expdest);
874 }
875
876 /*
877  * Add the value of a specialized variable to the stack string.
878  */
879
880 static void
881 varvalue(const char *name, int quoted, int subtype, int flag)
882 {
883         int num;
884         char *p;
885         int i;
886         char sep;
887         char **ap;
888
889         switch (*name) {
890         case '$':
891                 num = rootpid;
892                 goto numvar;
893         case '?':
894                 num = oexitstatus;
895                 goto numvar;
896         case '#':
897                 num = shellparam.nparam;
898                 goto numvar;
899         case '!':
900                 num = backgndpidval();
901 numvar:
902                 expdest = cvtnum(num, expdest);
903                 break;
904         case '-':
905                 for (i = 0 ; i < NOPTS ; i++) {
906                         if (optlist[i].val)
907                                 STPUTC(optlist[i].letter, expdest);
908                 }
909                 break;
910         case '@':
911                 if (flag & EXP_FULL && quoted) {
912                         for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
913                                 strtodest(p, flag, subtype, quoted);
914                                 if (*ap)
915                                         STPUTC('\0', expdest);
916                         }
917                         break;
918                 }
919                 /* FALLTHROUGH */
920         case '*':
921                 if (ifsset())
922                         sep = ifsval()[0];
923                 else
924                         sep = ' ';
925                 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
926                         strtodest(p, flag, subtype, quoted);
927                         if (!*ap)
928                                 break;
929                         if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
930                                 STPUTC(sep, expdest);
931                 }
932                 break;
933         default:
934                 if (is_digit(*name)) {
935                         num = atoi(name);
936                         if (num == 0)
937                                 p = arg0;
938                         else if (num > 0 && num <= shellparam.nparam)
939                                 p = shellparam.p[num - 1];
940                         else
941                                 break;
942                         strtodest(p, flag, subtype, quoted);
943                 }
944                 break;
945         }
946 }
947
948
949
950 /*
951  * Record the fact that we have to scan this region of the
952  * string for IFS characters.
953  */
954
955 static void
956 recordregion(int start, int end, int inquotes)
957 {
958         struct ifsregion *ifsp;
959
960         INTOFF;
961         if (ifslastp == NULL) {
962                 ifsp = &ifsfirst;
963         } else {
964                 if (ifslastp->endoff == start
965                     && ifslastp->inquotes == inquotes) {
966                         /* extend previous area */
967                         ifslastp->endoff = end;
968                         INTON;
969                         return;
970                 }
971                 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
972                 ifslastp->next = ifsp;
973         }
974         ifslastp = ifsp;
975         ifslastp->next = NULL;
976         ifslastp->begoff = start;
977         ifslastp->endoff = end;
978         ifslastp->inquotes = inquotes;
979         INTON;
980 }
981
982
983
984 /*
985  * Break the argument string into pieces based upon IFS and add the
986  * strings to the argument list.  The regions of the string to be
987  * searched for IFS characters have been stored by recordregion.
988  * CTLESC characters are preserved but have little effect in this pass
989  * other than escaping CTL* characters.  In particular, they do not escape
990  * IFS characters: that should be done with the ifsregion mechanism.
991  * CTLQUOTEMARK characters are used to preserve empty quoted strings.
992  * This pass treats them as a regular character, making the string non-empty.
993  * Later, they are removed along with the other CTL* characters.
994  */
995 static void
996 ifsbreakup(char *string, struct arglist *arglist)
997 {
998         struct ifsregion *ifsp;
999         struct strlist *sp;
1000         char *start;
1001         char *p;
1002         char *q;
1003         const char *ifs;
1004         const char *ifsspc;
1005         int had_param_ch = 0;
1006
1007         start = string;
1008
1009         if (ifslastp == NULL) {
1010                 /* Return entire argument, IFS doesn't apply to any of it */
1011                 sp = (struct strlist *)stalloc(sizeof *sp);
1012                 sp->text = start;
1013                 *arglist->lastp = sp;
1014                 arglist->lastp = &sp->next;
1015                 return;
1016         }
1017
1018         ifs = ifsset() ? ifsval() : " \t\n";
1019
1020         for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1021                 p = string + ifsp->begoff;
1022                 while (p < string + ifsp->endoff) {
1023                         q = p;
1024                         if (*p == CTLESC)
1025                                 p++;
1026                         if (ifsp->inquotes) {
1027                                 /* Only NULs (should be from "$@") end args */
1028                                 had_param_ch = 1;
1029                                 if (*p != 0) {
1030                                         p++;
1031                                         continue;
1032                                 }
1033                                 ifsspc = NULL;
1034                         } else {
1035                                 if (!strchr(ifs, *p)) {
1036                                         had_param_ch = 1;
1037                                         p++;
1038                                         continue;
1039                                 }
1040                                 ifsspc = strchr(" \t\n", *p);
1041
1042                                 /* Ignore IFS whitespace at start */
1043                                 if (q == start && ifsspc != NULL) {
1044                                         p++;
1045                                         start = p;
1046                                         continue;
1047                                 }
1048                                 had_param_ch = 0;
1049                         }
1050
1051                         /* Save this argument... */
1052                         *q = '\0';
1053                         sp = (struct strlist *)stalloc(sizeof *sp);
1054                         sp->text = start;
1055                         *arglist->lastp = sp;
1056                         arglist->lastp = &sp->next;
1057                         p++;
1058
1059                         if (ifsspc != NULL) {
1060                                 /* Ignore further trailing IFS whitespace */
1061                                 for (; p < string + ifsp->endoff; p++) {
1062                                         q = p;
1063                                         if (*p == CTLESC)
1064                                                 p++;
1065                                         if (strchr(ifs, *p) == NULL) {
1066                                                 p = q;
1067                                                 break;
1068                                         }
1069                                         if (strchr(" \t\n", *p) == NULL) {
1070                                                 p++;
1071                                                 break;
1072                                         }
1073                                 }
1074                         }
1075                         start = p;
1076                 }
1077         }
1078
1079         /*
1080          * Save anything left as an argument.
1081          * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1082          * generating 2 arguments, the second of which is empty.
1083          * Some recent clarification of the Posix spec say that it
1084          * should only generate one....
1085          */
1086         if (had_param_ch || *start != 0) {
1087                 sp = (struct strlist *)stalloc(sizeof *sp);
1088                 sp->text = start;
1089                 *arglist->lastp = sp;
1090                 arglist->lastp = &sp->next;
1091         }
1092 }
1093
1094
1095 static char expdir[PATH_MAX];
1096 #define expdir_end (expdir + sizeof(expdir))
1097
1098 /*
1099  * Perform pathname generation and remove control characters.
1100  * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1101  * The results are stored in the list exparg.
1102  */
1103 static void
1104 expandmeta(struct strlist *str, int flag __unused)
1105 {
1106         char *p;
1107         struct strlist **savelastp;
1108         struct strlist *sp;
1109         char c;
1110         /* TODO - EXP_REDIR */
1111
1112         while (str) {
1113                 if (fflag)
1114                         goto nometa;
1115                 p = str->text;
1116                 for (;;) {                      /* fast check for meta chars */
1117                         if ((c = *p++) == '\0')
1118                                 goto nometa;
1119                         if (c == '*' || c == '?' || c == '[')
1120                                 break;
1121                 }
1122                 savelastp = exparg.lastp;
1123                 INTOFF;
1124                 expmeta(expdir, str->text);
1125                 INTON;
1126                 if (exparg.lastp == savelastp) {
1127                         /*
1128                          * no matches
1129                          */
1130 nometa:
1131                         *exparg.lastp = str;
1132                         rmescapes(str->text);
1133                         exparg.lastp = &str->next;
1134                 } else {
1135                         *exparg.lastp = NULL;
1136                         *savelastp = sp = expsort(*savelastp);
1137                         while (sp->next != NULL)
1138                                 sp = sp->next;
1139                         exparg.lastp = &sp->next;
1140                 }
1141                 str = str->next;
1142         }
1143 }
1144
1145
1146 /*
1147  * Do metacharacter (i.e. *, ?, [...]) expansion.
1148  */
1149
1150 static void
1151 expmeta(char *enddir, char *name)
1152 {
1153         const char *p;
1154         const char *q;
1155         const char *start;
1156         char *endname;
1157         int metaflag;
1158         struct stat statb;
1159         DIR *dirp;
1160         struct dirent *dp;
1161         int atend;
1162         int matchdot;
1163         int esc;
1164         int namlen;
1165
1166         metaflag = 0;
1167         start = name;
1168         for (p = name; esc = 0, *p; p += esc + 1) {
1169                 if (*p == '*' || *p == '?')
1170                         metaflag = 1;
1171                 else if (*p == '[') {
1172                         q = p + 1;
1173                         if (*q == '!' || *q == '^')
1174                                 q++;
1175                         for (;;) {
1176                                 while (*q == CTLQUOTEMARK)
1177                                         q++;
1178                                 if (*q == CTLESC)
1179                                         q++;
1180                                 if (*q == '/' || *q == '\0')
1181                                         break;
1182                                 if (*++q == ']') {
1183                                         metaflag = 1;
1184                                         break;
1185                                 }
1186                         }
1187                 } else if (*p == '\0')
1188                         break;
1189                 else if (*p == CTLQUOTEMARK)
1190                         continue;
1191                 else {
1192                         if (*p == CTLESC)
1193                                 esc++;
1194                         if (p[esc] == '/') {
1195                                 if (metaflag)
1196                                         break;
1197                                 start = p + esc + 1;
1198                         }
1199                 }
1200         }
1201         if (metaflag == 0) {    /* we've reached the end of the file name */
1202                 if (enddir != expdir)
1203                         metaflag++;
1204                 for (p = name ; ; p++) {
1205                         if (*p == CTLQUOTEMARK)
1206                                 continue;
1207                         if (*p == CTLESC)
1208                                 p++;
1209                         *enddir++ = *p;
1210                         if (*p == '\0')
1211                                 break;
1212                         if (enddir == expdir_end)
1213                                 return;
1214                 }
1215                 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1216                         addfname(expdir);
1217                 return;
1218         }
1219         endname = name + (p - name);
1220         if (start != name) {
1221                 p = name;
1222                 while (p < start) {
1223                         while (*p == CTLQUOTEMARK)
1224                                 p++;
1225                         if (*p == CTLESC)
1226                                 p++;
1227                         *enddir++ = *p++;
1228                         if (enddir == expdir_end)
1229                                 return;
1230                 }
1231         }
1232         if (enddir == expdir) {
1233                 p = ".";
1234         } else if (enddir == expdir + 1 && *expdir == '/') {
1235                 p = "/";
1236         } else {
1237                 p = expdir;
1238                 enddir[-1] = '\0';
1239         }
1240         if ((dirp = opendir(p)) == NULL)
1241                 return;
1242         if (enddir != expdir)
1243                 enddir[-1] = '/';
1244         if (*endname == 0) {
1245                 atend = 1;
1246         } else {
1247                 atend = 0;
1248                 *endname = '\0';
1249                 endname += esc + 1;
1250         }
1251         matchdot = 0;
1252         p = start;
1253         while (*p == CTLQUOTEMARK)
1254                 p++;
1255         if (*p == CTLESC)
1256                 p++;
1257         if (*p == '.')
1258                 matchdot++;
1259         while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1260                 if (dp->d_name[0] == '.' && ! matchdot)
1261                         continue;
1262                 if (patmatch(start, dp->d_name, 0)) {
1263                         namlen = dp->d_namlen;
1264                         if (enddir + namlen + 1 > expdir_end)
1265                                 continue;
1266                         memcpy(enddir, dp->d_name, namlen + 1);
1267                         if (atend)
1268                                 addfname(expdir);
1269                         else {
1270                                 if (dp->d_type != DT_UNKNOWN &&
1271                                     dp->d_type != DT_DIR &&
1272                                     dp->d_type != DT_LNK)
1273                                         continue;
1274                                 if (enddir + namlen + 2 > expdir_end)
1275                                         continue;
1276                                 enddir[namlen] = '/';
1277                                 enddir[namlen + 1] = '\0';
1278                                 expmeta(enddir + namlen + 1, endname);
1279                         }
1280                 }
1281         }
1282         closedir(dirp);
1283         if (! atend)
1284                 endname[-esc - 1] = esc ? CTLESC : '/';
1285 }
1286
1287
1288 /*
1289  * Add a file name to the list.
1290  */
1291
1292 static void
1293 addfname(char *name)
1294 {
1295         char *p;
1296         struct strlist *sp;
1297         size_t len;
1298
1299         len = strlen(name);
1300         p = stalloc(len + 1);
1301         memcpy(p, name, len + 1);
1302         sp = (struct strlist *)stalloc(sizeof *sp);
1303         sp->text = p;
1304         *exparg.lastp = sp;
1305         exparg.lastp = &sp->next;
1306 }
1307
1308
1309 /*
1310  * Sort the results of file name expansion.  It calculates the number of
1311  * strings to sort and then calls msort (short for merge sort) to do the
1312  * work.
1313  */
1314
1315 static struct strlist *
1316 expsort(struct strlist *str)
1317 {
1318         int len;
1319         struct strlist *sp;
1320
1321         len = 0;
1322         for (sp = str ; sp ; sp = sp->next)
1323                 len++;
1324         return msort(str, len);
1325 }
1326
1327
1328 static struct strlist *
1329 msort(struct strlist *list, int len)
1330 {
1331         struct strlist *p, *q = NULL;
1332         struct strlist **lpp;
1333         int half;
1334         int n;
1335
1336         if (len <= 1)
1337                 return list;
1338         half = len >> 1;
1339         p = list;
1340         for (n = half ; --n >= 0 ; ) {
1341                 q = p;
1342                 p = p->next;
1343         }
1344         q->next = NULL;                 /* terminate first half of list */
1345         q = msort(list, half);          /* sort first half of list */
1346         p = msort(p, len - half);               /* sort second half */
1347         lpp = &list;
1348         for (;;) {
1349                 if (strcmp(p->text, q->text) < 0) {
1350                         *lpp = p;
1351                         lpp = &p->next;
1352                         if ((p = *lpp) == NULL) {
1353                                 *lpp = q;
1354                                 break;
1355                         }
1356                 } else {
1357                         *lpp = q;
1358                         lpp = &q->next;
1359                         if ((q = *lpp) == NULL) {
1360                                 *lpp = p;
1361                                 break;
1362                         }
1363                 }
1364         }
1365         return list;
1366 }
1367
1368
1369
1370 static wchar_t
1371 get_wc(const char **p)
1372 {
1373         wchar_t c;
1374         int chrlen;
1375
1376         chrlen = mbtowc(&c, *p, 4);
1377         if (chrlen == 0)
1378                 return 0;
1379         else if (chrlen == -1)
1380                 c = 0;
1381         else
1382                 *p += chrlen;
1383         return c;
1384 }
1385
1386
1387 /*
1388  * See if a character matches a character class, starting at the first colon
1389  * of "[:class:]".
1390  * If a valid character class is recognized, a pointer to the next character
1391  * after the final closing bracket is stored into *end, otherwise a null
1392  * pointer is stored into *end.
1393  */
1394 static int
1395 match_charclass(const char *p, wchar_t chr, const char **end)
1396 {
1397         char name[20];
1398         const char *nameend;
1399         wctype_t cclass;
1400
1401         *end = NULL;
1402         p++;
1403         nameend = strstr(p, ":]");
1404         if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1405             nameend == p)
1406                 return 0;
1407         memcpy(name, p, nameend - p);
1408         name[nameend - p] = '\0';
1409         *end = nameend + 2;
1410         cclass = wctype(name);
1411         /* An unknown class matches nothing but is valid nevertheless. */
1412         if (cclass == 0)
1413                 return 0;
1414         return iswctype(chr, cclass);
1415 }
1416
1417
1418 /*
1419  * Returns true if the pattern matches the string.
1420  */
1421
1422 static int
1423 patmatch(const char *pattern, const char *string, int squoted)
1424 {
1425         const char *p, *q, *end;
1426         const char *bt_p, *bt_q;
1427         char c;
1428         wchar_t wc, wc2;
1429
1430         p = pattern;
1431         q = string;
1432         bt_p = NULL;
1433         bt_q = NULL;
1434         for (;;) {
1435                 switch (c = *p++) {
1436                 case '\0':
1437                         if (*q != '\0')
1438                                 goto backtrack;
1439                         return 1;
1440                 case CTLESC:
1441                         if (squoted && *q == CTLESC)
1442                                 q++;
1443                         if (*q++ != *p++)
1444                                 goto backtrack;
1445                         break;
1446                 case CTLQUOTEMARK:
1447                         continue;
1448                 case '?':
1449                         if (squoted && *q == CTLESC)
1450                                 q++;
1451                         if (*q == '\0')
1452                                 return 0;
1453                         if (localeisutf8) {
1454                                 wc = get_wc(&q);
1455                                 /*
1456                                  * A '?' does not match invalid UTF-8 but a
1457                                  * '*' does, so backtrack.
1458                                  */
1459                                 if (wc == 0)
1460                                         goto backtrack;
1461                         } else
1462                                 wc = (unsigned char)*q++;
1463                         break;
1464                 case '*':
1465                         c = *p;
1466                         while (c == CTLQUOTEMARK || c == '*')
1467                                 c = *++p;
1468                         /*
1469                          * If the pattern ends here, we know the string
1470                          * matches without needing to look at the rest of it.
1471                          */
1472                         if (c == '\0')
1473                                 return 1;
1474                         /*
1475                          * First try the shortest match for the '*' that
1476                          * could work. We can forget any earlier '*' since
1477                          * there is no way having it match more characters
1478                          * can help us, given that we are already here.
1479                          */
1480                         bt_p = p;
1481                         bt_q = q;
1482                         break;
1483                 case '[': {
1484                         const char *endp;
1485                         int invert, found;
1486                         wchar_t chr;
1487
1488                         endp = p;
1489                         if (*endp == '!' || *endp == '^')
1490                                 endp++;
1491                         for (;;) {
1492                                 while (*endp == CTLQUOTEMARK)
1493                                         endp++;
1494                                 if (*endp == 0)
1495                                         goto dft;               /* no matching ] */
1496                                 if (*endp == CTLESC)
1497                                         endp++;
1498                                 if (*++endp == ']')
1499                                         break;
1500                         }
1501                         invert = 0;
1502                         if (*p == '!' || *p == '^') {
1503                                 invert++;
1504                                 p++;
1505                         }
1506                         found = 0;
1507                         if (squoted && *q == CTLESC)
1508                                 q++;
1509                         if (*q == '\0')
1510                                 return 0;
1511                         if (localeisutf8) {
1512                                 chr = get_wc(&q);
1513                                 if (chr == 0)
1514                                         goto backtrack;
1515                         } else
1516                                 chr = (unsigned char)*q++;
1517                         c = *p++;
1518                         do {
1519                                 if (c == CTLQUOTEMARK)
1520                                         continue;
1521                                 if (c == '[' && *p == ':') {
1522                                         found |= match_charclass(p, chr, &end);
1523                                         if (end != NULL)
1524                                                 p = end;
1525                                 }
1526                                 if (c == CTLESC)
1527                                         c = *p++;
1528                                 if (localeisutf8 && c & 0x80) {
1529                                         p--;
1530                                         wc = get_wc(&p);
1531                                         if (wc == 0) /* bad utf-8 */
1532                                                 return 0;
1533                                 } else
1534                                         wc = (unsigned char)c;
1535                                 if (*p == '-' && p[1] != ']') {
1536                                         p++;
1537                                         while (*p == CTLQUOTEMARK)
1538                                                 p++;
1539                                         if (*p == CTLESC)
1540                                                 p++;
1541                                         if (localeisutf8) {
1542                                                 wc2 = get_wc(&p);
1543                                                 if (wc2 == 0) /* bad utf-8 */
1544                                                         return 0;
1545                                         } else
1546                                                 wc2 = (unsigned char)*p++;
1547                                         if (   collate_range_cmp(chr, wc) >= 0
1548                                             && collate_range_cmp(chr, wc2) <= 0
1549                                            )
1550                                                 found = 1;
1551                                 } else {
1552                                         if (chr == wc)
1553                                                 found = 1;
1554                                 }
1555                         } while ((c = *p++) != ']');
1556                         if (found == invert)
1557                                 goto backtrack;
1558                         break;
1559                 }
1560 dft:            default:
1561                         if (squoted && *q == CTLESC)
1562                                 q++;
1563                         if (*q == '\0')
1564                                 return 0;
1565                         if (*q++ == c)
1566                                 break;
1567 backtrack:
1568                         /*
1569                          * If we have a mismatch (other than hitting the end
1570                          * of the string), go back to the last '*' seen and
1571                          * have it match one additional character.
1572                          */
1573                         if (bt_p == NULL)
1574                                 return 0;
1575                         if (squoted && *bt_q == CTLESC)
1576                                 bt_q++;
1577                         if (*bt_q == '\0')
1578                                 return 0;
1579                         bt_q++;
1580                         p = bt_p;
1581                         q = bt_q;
1582                         break;
1583                 }
1584         }
1585 }
1586
1587
1588
1589 /*
1590  * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1591  */
1592
1593 void
1594 rmescapes(char *str)
1595 {
1596         char *p, *q;
1597
1598         p = str;
1599         while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1600                 if (*p++ == '\0')
1601                         return;
1602         }
1603         q = p;
1604         while (*p) {
1605                 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1606                         p++;
1607                         continue;
1608                 }
1609                 if (*p == CTLESC)
1610                         p++;
1611                 *q++ = *p++;
1612         }
1613         *q = '\0';
1614 }
1615
1616
1617
1618 /*
1619  * See if a pattern matches in a case statement.
1620  */
1621
1622 int
1623 casematch(union node *pattern, const char *val)
1624 {
1625         struct stackmark smark;
1626         int result;
1627         char *p;
1628
1629         setstackmark(&smark);
1630         argbackq = pattern->narg.backquote;
1631         STARTSTACKSTR(expdest);
1632         ifslastp = NULL;
1633         argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1634         STPUTC('\0', expdest);
1635         p = grabstackstr(expdest);
1636         result = patmatch(p, val, 0);
1637         popstackmark(&smark);
1638         return result;
1639 }
1640
1641 /*
1642  * Our own itoa().
1643  */
1644
1645 static char *
1646 cvtnum(int num, char *buf)
1647 {
1648         char temp[32];
1649         int neg = num < 0;
1650         char *p = temp + 31;
1651
1652         temp[31] = '\0';
1653
1654         do {
1655                 *--p = num % 10 + '0';
1656         } while ((num /= 10) != 0);
1657
1658         if (neg)
1659                 *--p = '-';
1660
1661         STPUTS(p, buf);
1662         return buf;
1663 }
1664
1665 /*
1666  * Do most of the work for wordexp(3).
1667  */
1668
1669 int
1670 wordexpcmd(int argc, char **argv)
1671 {
1672         size_t len;
1673         int i;
1674
1675         out1fmt("%08x", argc - 1);
1676         for (i = 1, len = 0; i < argc; i++)
1677                 len += strlen(argv[i]);
1678         out1fmt("%08x", (int)len);
1679         for (i = 1; i < argc; i++)
1680                 outbin(argv[i], strlen(argv[i]) + 1, out1);
1681         return (0);
1682 }