]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - bin/sh/expand.c
Sync sh(1) in stable/10 to head.
[FreeBSD/stable/10.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 void 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(char *, int);
108 static void varvalue(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 void
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                 case CTLENDVAR:
235                 case CTLENDARI:
236                         goto breakloop;
237                 case CTLQUOTEMARK:
238                         lit_quoted = 1;
239                         /* "$@" syntax adherence hack */
240                         if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
241                                 break;
242                         if ((flag & EXP_FULL) != 0)
243                                 USTPUTC(c, expdest);
244                         break;
245                 case CTLQUOTEEND:
246                         lit_quoted = 0;
247                         break;
248                 case CTLESC:
249                         if (quotes)
250                                 USTPUTC(c, expdest);
251                         c = *p++;
252                         USTPUTC(c, expdest);
253                         if (split_lit && !lit_quoted)
254                                 recordregion(expdest - stackblock() -
255                                     (quotes ? 2 : 1),
256                                     expdest - stackblock(), 0);
257                         break;
258                 case CTLVAR:
259                         p = evalvar(p, flag);
260                         break;
261                 case CTLBACKQ:
262                 case CTLBACKQ|CTLQUOTE:
263                         expbackq(argbackq->n, c & CTLQUOTE, flag);
264                         argbackq = argbackq->next;
265                         break;
266                 case CTLARI:
267                         p = expari(p);
268                         break;
269                 case ':':
270                 case '=':
271                         /*
272                          * sort of a hack - expand tildes in variable
273                          * assignments (after the first '=' and after ':'s).
274                          */
275                         USTPUTC(c, expdest);
276                         if (split_lit && !lit_quoted)
277                                 recordregion(expdest - stackblock() - 1,
278                                     expdest - stackblock(), 0);
279                         if (flag & EXP_VARTILDE && *p == '~' &&
280                             (c != '=' || firsteq)) {
281                                 if (c == '=')
282                                         firsteq = 0;
283                                 p = exptilde(p, flag);
284                         }
285                         break;
286                 default:
287                         USTPUTC(c, expdest);
288                         if (split_lit && !lit_quoted)
289                                 recordregion(expdest - stackblock() - 1,
290                                     expdest - stackblock(), 0);
291                 }
292         }
293 breakloop:;
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 c;
403         int nesting;
404         int adj;
405
406         quoted = *p++ == '"';
407         begoff = expdest - stackblock();
408         argstr(p, 0);
409         removerecordregions(begoff);
410         STPUTC('\0', expdest);
411         start = stackblock() + begoff;
412
413         q = grabstackstr(expdest);
414         result = arith(start);
415         ungrabstackstr(q, expdest);
416
417         start = stackblock() + begoff;
418         adj = start - expdest;
419         STADJUST(adj, expdest);
420
421         CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
422         fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
423         adj = strlen(expdest);
424         STADJUST(adj, expdest);
425         if (!quoted)
426                 recordregion(begoff, expdest - stackblock(), 0);
427         nesting = 1;
428         while (nesting > 0) {
429                 c = *p++;
430                 if (c == CTLESC)
431                         p++;
432                 else if (c == CTLARI)
433                         nesting++;
434                 else if (c == CTLENDARI)
435                         nesting--;
436                 else if (c == CTLVAR)
437                         p++; /* ignore variable substitution byte */
438                 else if (c == '\0')
439                         return p - 1;
440         }
441         return p;
442 }
443
444
445 /*
446  * Perform command substitution.
447  */
448 static void
449 expbackq(union node *cmd, int quoted, int flag)
450 {
451         struct backcmd in;
452         int i;
453         char buf[128];
454         char *p;
455         char *dest = expdest;
456         struct ifsregion saveifs, *savelastp;
457         struct nodelist *saveargbackq;
458         char lastc;
459         int startloc = dest - stackblock();
460         char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
461         int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
462         size_t nnl;
463
464         INTOFF;
465         saveifs = ifsfirst;
466         savelastp = ifslastp;
467         saveargbackq = argbackq;
468         p = grabstackstr(dest);
469         evalbackcmd(cmd, &in);
470         ungrabstackstr(p, dest);
471         ifsfirst = saveifs;
472         ifslastp = savelastp;
473         argbackq = saveargbackq;
474
475         p = in.buf;
476         lastc = '\0';
477         nnl = 0;
478         /* Don't copy trailing newlines */
479         for (;;) {
480                 if (--in.nleft < 0) {
481                         if (in.fd < 0)
482                                 break;
483                         while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
484                         TRACE(("expbackq: read returns %d\n", i));
485                         if (i <= 0)
486                                 break;
487                         p = buf;
488                         in.nleft = i - 1;
489                 }
490                 lastc = *p++;
491                 if (lastc != '\0') {
492                         if (lastc == '\n') {
493                                 nnl++;
494                         } else {
495                                 CHECKSTRSPACE(nnl + 2, dest);
496                                 while (nnl > 0) {
497                                         nnl--;
498                                         USTPUTC('\n', dest);
499                                 }
500                                 if (quotes && syntax[(int)lastc] == CCTL)
501                                         USTPUTC(CTLESC, dest);
502                                 USTPUTC(lastc, dest);
503                         }
504                 }
505         }
506
507         if (in.fd >= 0)
508                 close(in.fd);
509         if (in.buf)
510                 ckfree(in.buf);
511         if (in.jp)
512                 exitstatus = waitforjob(in.jp, (int *)NULL);
513         if (quoted == 0)
514                 recordregion(startloc, dest - stackblock(), 0);
515         TRACE(("expbackq: size=%td: \"%.*s\"\n",
516                 ((dest - stackblock()) - startloc),
517                 (int)((dest - stackblock()) - startloc),
518                 stackblock() + startloc));
519         expdest = dest;
520         INTON;
521 }
522
523
524
525 static int
526 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
527   int varflags, int quotes)
528 {
529         char *startp;
530         char *loc = NULL;
531         char *q;
532         int c = 0;
533         struct nodelist *saveargbackq = argbackq;
534         int amount;
535
536         argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
537             subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
538             EXP_CASE : 0) | EXP_TILDE);
539         STACKSTRNUL(expdest);
540         argbackq = saveargbackq;
541         startp = stackblock() + startloc;
542         if (str == NULL)
543             str = stackblock() + strloc;
544
545         switch (subtype) {
546         case VSASSIGN:
547                 setvar(str, startp, 0);
548                 amount = startp - expdest;
549                 STADJUST(amount, expdest);
550                 varflags &= ~VSNUL;
551                 return 1;
552
553         case VSQUESTION:
554                 if (*p != CTLENDVAR) {
555                         outfmt(out2, "%s\n", startp);
556                         error((char *)NULL);
557                 }
558                 error("%.*s: parameter %snot set", (int)(p - str - 1),
559                       str, (varflags & VSNUL) ? "null or "
560                                               : nullstr);
561                 return 0;
562
563         case VSTRIMLEFT:
564                 for (loc = startp; loc < str; loc++) {
565                         c = *loc;
566                         *loc = '\0';
567                         if (patmatch(str, startp, quotes)) {
568                                 *loc = c;
569                                 goto recordleft;
570                         }
571                         *loc = c;
572                         if (quotes && *loc == CTLESC)
573                                 loc++;
574                 }
575                 return 0;
576
577         case VSTRIMLEFTMAX:
578                 for (loc = str - 1; loc >= startp;) {
579                         c = *loc;
580                         *loc = '\0';
581                         if (patmatch(str, startp, quotes)) {
582                                 *loc = c;
583                                 goto recordleft;
584                         }
585                         *loc = c;
586                         loc--;
587                         if (quotes && loc > startp && *(loc - 1) == CTLESC) {
588                                 for (q = startp; q < loc; q++)
589                                         if (*q == CTLESC)
590                                                 q++;
591                                 if (q > loc)
592                                         loc--;
593                         }
594                 }
595                 return 0;
596
597         case VSTRIMRIGHT:
598                 for (loc = str - 1; loc >= startp;) {
599                         if (patmatch(str, loc, quotes)) {
600                                 amount = loc - expdest;
601                                 STADJUST(amount, expdest);
602                                 return 1;
603                         }
604                         loc--;
605                         if (quotes && loc > startp && *(loc - 1) == CTLESC) {
606                                 for (q = startp; q < loc; q++)
607                                         if (*q == CTLESC)
608                                                 q++;
609                                 if (q > loc)
610                                         loc--;
611                         }
612                 }
613                 return 0;
614
615         case VSTRIMRIGHTMAX:
616                 for (loc = startp; loc < str - 1; loc++) {
617                         if (patmatch(str, loc, quotes)) {
618                                 amount = loc - expdest;
619                                 STADJUST(amount, expdest);
620                                 return 1;
621                         }
622                         if (quotes && *loc == CTLESC)
623                                 loc++;
624                 }
625                 return 0;
626
627
628         default:
629                 abort();
630         }
631
632 recordleft:
633         amount = ((str - 1) - (loc - startp)) - expdest;
634         STADJUST(amount, expdest);
635         while (loc != str - 1)
636                 *startp++ = *loc++;
637         return 1;
638 }
639
640
641 /*
642  * Expand a variable, and return a pointer to the next character in the
643  * input string.
644  */
645
646 static char *
647 evalvar(char *p, int flag)
648 {
649         int subtype;
650         int varflags;
651         char *var;
652         char *val;
653         int patloc;
654         int c;
655         int set;
656         int special;
657         int startloc;
658         int varlen;
659         int varlenb;
660         int easy;
661         int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
662
663         varflags = (unsigned char)*p++;
664         subtype = varflags & VSTYPE;
665         var = p;
666         special = 0;
667         if (! is_name(*p))
668                 special = 1;
669         p = strchr(p, '=') + 1;
670 again: /* jump here after setting a variable with ${var=text} */
671         if (varflags & VSLINENO) {
672                 set = 1;
673                 special = 1;
674                 val = NULL;
675         } else if (special) {
676                 set = varisset(var, varflags & VSNUL);
677                 val = NULL;
678         } else {
679                 val = bltinlookup(var, 1);
680                 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
681                         val = NULL;
682                         set = 0;
683                 } else
684                         set = 1;
685         }
686         varlen = 0;
687         startloc = expdest - stackblock();
688         if (!set && uflag && *var != '@' && *var != '*') {
689                 switch (subtype) {
690                 case VSNORMAL:
691                 case VSTRIMLEFT:
692                 case VSTRIMLEFTMAX:
693                 case VSTRIMRIGHT:
694                 case VSTRIMRIGHTMAX:
695                 case VSLENGTH:
696                         error("%.*s: parameter not set", (int)(p - var - 1),
697                             var);
698                 }
699         }
700         if (set && subtype != VSPLUS) {
701                 /* insert the value of the variable */
702                 if (special) {
703                         if (varflags & VSLINENO)
704                                 STPUTBIN(var, p - var - 1, expdest);
705                         else
706                                 varvalue(var, varflags & VSQUOTE, subtype, flag);
707                         if (subtype == VSLENGTH) {
708                                 varlenb = expdest - stackblock() - startloc;
709                                 varlen = varlenb;
710                                 if (localeisutf8) {
711                                         val = stackblock() + startloc;
712                                         for (;val != expdest; val++)
713                                                 if ((*val & 0xC0) == 0x80)
714                                                         varlen--;
715                                 }
716                                 STADJUST(-varlenb, expdest);
717                         }
718                 } else {
719                         char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
720                                                                   : BASESYNTAX;
721
722                         if (subtype == VSLENGTH) {
723                                 for (;*val; val++)
724                                         if (!localeisutf8 ||
725                                             (*val & 0xC0) != 0x80)
726                                                 varlen++;
727                         }
728                         else {
729                                 if (quotes)
730                                         STPUTS_QUOTES(val, syntax, expdest);
731                                 else
732                                         STPUTS(val, expdest);
733
734                         }
735                 }
736         }
737
738         if (subtype == VSPLUS)
739                 set = ! set;
740
741         easy = ((varflags & VSQUOTE) == 0 ||
742                 (*var == '@' && shellparam.nparam != 1));
743
744
745         switch (subtype) {
746         case VSLENGTH:
747                 expdest = cvtnum(varlen, expdest);
748                 goto record;
749
750         case VSNORMAL:
751                 if (!easy)
752                         break;
753 record:
754                 recordregion(startloc, expdest - stackblock(),
755                     varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
756                     (*var == '@' || *var == '*')));
757                 break;
758
759         case VSPLUS:
760         case VSMINUS:
761                 if (!set) {
762                         argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
763                             (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
764                         break;
765                 }
766                 if (easy)
767                         goto record;
768                 break;
769
770         case VSTRIMLEFT:
771         case VSTRIMLEFTMAX:
772         case VSTRIMRIGHT:
773         case VSTRIMRIGHTMAX:
774                 if (!set)
775                         break;
776                 /*
777                  * Terminate the string and start recording the pattern
778                  * right after it
779                  */
780                 STPUTC('\0', expdest);
781                 patloc = expdest - stackblock();
782                 if (subevalvar(p, NULL, patloc, subtype,
783                     startloc, varflags, quotes) == 0) {
784                         int amount = (expdest - stackblock() - patloc) + 1;
785                         STADJUST(-amount, expdest);
786                 }
787                 /* Remove any recorded regions beyond start of variable */
788                 removerecordregions(startloc);
789                 goto record;
790
791         case VSASSIGN:
792         case VSQUESTION:
793                 if (!set) {
794                         if (subevalvar(p, var, 0, subtype, startloc, varflags,
795                             quotes)) {
796                                 varflags &= ~VSNUL;
797                                 /*
798                                  * Remove any recorded regions beyond
799                                  * start of variable
800                                  */
801                                 removerecordregions(startloc);
802                                 goto again;
803                         }
804                         break;
805                 }
806                 if (easy)
807                         goto record;
808                 break;
809
810         case VSERROR:
811                 c = p - var - 1;
812                 error("${%.*s%s}: Bad substitution", c, var,
813                     (c > 0 && *p != CTLENDVAR) ? "..." : "");
814
815         default:
816                 abort();
817         }
818
819         if (subtype != VSNORMAL) {      /* skip to end of alternative */
820                 int nesting = 1;
821                 for (;;) {
822                         if ((c = *p++) == CTLESC)
823                                 p++;
824                         else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
825                                 if (set)
826                                         argbackq = argbackq->next;
827                         } else if (c == CTLVAR) {
828                                 if ((*p++ & VSTYPE) != VSNORMAL)
829                                         nesting++;
830                         } else if (c == CTLENDVAR) {
831                                 if (--nesting == 0)
832                                         break;
833                         }
834                 }
835         }
836         return p;
837 }
838
839
840
841 /*
842  * Test whether a specialized variable is set.
843  */
844
845 static int
846 varisset(char *name, int nulok)
847 {
848
849         if (*name == '!')
850                 return backgndpidset();
851         else if (*name == '@' || *name == '*') {
852                 if (*shellparam.p == NULL)
853                         return 0;
854
855                 if (nulok) {
856                         char **av;
857
858                         for (av = shellparam.p; *av; av++)
859                                 if (**av != '\0')
860                                         return 1;
861                         return 0;
862                 }
863         } else if (is_digit(*name)) {
864                 char *ap;
865                 int num = atoi(name);
866
867                 if (num > shellparam.nparam)
868                         return 0;
869
870                 if (num == 0)
871                         ap = arg0;
872                 else
873                         ap = shellparam.p[num - 1];
874
875                 if (nulok && (ap == NULL || *ap == '\0'))
876                         return 0;
877         }
878         return 1;
879 }
880
881 static void
882 strtodest(const char *p, int flag, int subtype, int quoted)
883 {
884         if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
885                 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
886         else
887                 STPUTS(p, expdest);
888 }
889
890 /*
891  * Add the value of a specialized variable to the stack string.
892  */
893
894 static void
895 varvalue(char *name, int quoted, int subtype, int flag)
896 {
897         int num;
898         char *p;
899         int i;
900         char sep;
901         char **ap;
902
903         switch (*name) {
904         case '$':
905                 num = rootpid;
906                 goto numvar;
907         case '?':
908                 num = oexitstatus;
909                 goto numvar;
910         case '#':
911                 num = shellparam.nparam;
912                 goto numvar;
913         case '!':
914                 num = backgndpidval();
915 numvar:
916                 expdest = cvtnum(num, expdest);
917                 break;
918         case '-':
919                 for (i = 0 ; i < NOPTS ; i++) {
920                         if (optlist[i].val)
921                                 STPUTC(optlist[i].letter, expdest);
922                 }
923                 break;
924         case '@':
925                 if (flag & EXP_FULL && quoted) {
926                         for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
927                                 strtodest(p, flag, subtype, quoted);
928                                 if (*ap)
929                                         STPUTC('\0', expdest);
930                         }
931                         break;
932                 }
933                 /* FALLTHROUGH */
934         case '*':
935                 if (ifsset())
936                         sep = ifsval()[0];
937                 else
938                         sep = ' ';
939                 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
940                         strtodest(p, flag, subtype, quoted);
941                         if (!*ap)
942                                 break;
943                         if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
944                                 STPUTC(sep, expdest);
945                 }
946                 break;
947         case '0':
948                 p = arg0;
949                 strtodest(p, flag, subtype, quoted);
950                 break;
951         default:
952                 if (is_digit(*name)) {
953                         num = atoi(name);
954                         if (num > 0 && num <= shellparam.nparam) {
955                                 p = shellparam.p[num - 1];
956                                 strtodest(p, flag, subtype, quoted);
957                         }
958                 }
959                 break;
960         }
961 }
962
963
964
965 /*
966  * Record the fact that we have to scan this region of the
967  * string for IFS characters.
968  */
969
970 static void
971 recordregion(int start, int end, int inquotes)
972 {
973         struct ifsregion *ifsp;
974
975         if (ifslastp == NULL) {
976                 ifsp = &ifsfirst;
977         } else {
978                 if (ifslastp->endoff == start
979                     && ifslastp->inquotes == inquotes) {
980                         /* extend previous area */
981                         ifslastp->endoff = end;
982                         return;
983                 }
984                 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
985                 ifslastp->next = ifsp;
986         }
987         ifslastp = ifsp;
988         ifslastp->next = NULL;
989         ifslastp->begoff = start;
990         ifslastp->endoff = end;
991         ifslastp->inquotes = inquotes;
992 }
993
994
995
996 /*
997  * Break the argument string into pieces based upon IFS and add the
998  * strings to the argument list.  The regions of the string to be
999  * searched for IFS characters have been stored by recordregion.
1000  * CTLESC characters are preserved but have little effect in this pass
1001  * other than escaping CTL* characters.  In particular, they do not escape
1002  * IFS characters: that should be done with the ifsregion mechanism.
1003  * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1004  * This pass treats them as a regular character, making the string non-empty.
1005  * Later, they are removed along with the other CTL* characters.
1006  */
1007 static void
1008 ifsbreakup(char *string, struct arglist *arglist)
1009 {
1010         struct ifsregion *ifsp;
1011         struct strlist *sp;
1012         char *start;
1013         char *p;
1014         char *q;
1015         const char *ifs;
1016         const char *ifsspc;
1017         int had_param_ch = 0;
1018
1019         start = string;
1020
1021         if (ifslastp == NULL) {
1022                 /* Return entire argument, IFS doesn't apply to any of it */
1023                 sp = (struct strlist *)stalloc(sizeof *sp);
1024                 sp->text = start;
1025                 *arglist->lastp = sp;
1026                 arglist->lastp = &sp->next;
1027                 return;
1028         }
1029
1030         ifs = ifsset() ? ifsval() : " \t\n";
1031
1032         for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1033                 p = string + ifsp->begoff;
1034                 while (p < string + ifsp->endoff) {
1035                         q = p;
1036                         if (*p == CTLESC)
1037                                 p++;
1038                         if (ifsp->inquotes) {
1039                                 /* Only NULs (should be from "$@") end args */
1040                                 had_param_ch = 1;
1041                                 if (*p != 0) {
1042                                         p++;
1043                                         continue;
1044                                 }
1045                                 ifsspc = NULL;
1046                         } else {
1047                                 if (!strchr(ifs, *p)) {
1048                                         had_param_ch = 1;
1049                                         p++;
1050                                         continue;
1051                                 }
1052                                 ifsspc = strchr(" \t\n", *p);
1053
1054                                 /* Ignore IFS whitespace at start */
1055                                 if (q == start && ifsspc != NULL) {
1056                                         p++;
1057                                         start = p;
1058                                         continue;
1059                                 }
1060                                 had_param_ch = 0;
1061                         }
1062
1063                         /* Save this argument... */
1064                         *q = '\0';
1065                         sp = (struct strlist *)stalloc(sizeof *sp);
1066                         sp->text = start;
1067                         *arglist->lastp = sp;
1068                         arglist->lastp = &sp->next;
1069                         p++;
1070
1071                         if (ifsspc != NULL) {
1072                                 /* Ignore further trailing IFS whitespace */
1073                                 for (; p < string + ifsp->endoff; p++) {
1074                                         q = p;
1075                                         if (*p == CTLESC)
1076                                                 p++;
1077                                         if (strchr(ifs, *p) == NULL) {
1078                                                 p = q;
1079                                                 break;
1080                                         }
1081                                         if (strchr(" \t\n", *p) == NULL) {
1082                                                 p++;
1083                                                 break;
1084                                         }
1085                                 }
1086                         }
1087                         start = p;
1088                 }
1089         }
1090
1091         /*
1092          * Save anything left as an argument.
1093          * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1094          * generating 2 arguments, the second of which is empty.
1095          * Some recent clarification of the Posix spec say that it
1096          * should only generate one....
1097          */
1098         if (had_param_ch || *start != 0) {
1099                 sp = (struct strlist *)stalloc(sizeof *sp);
1100                 sp->text = start;
1101                 *arglist->lastp = sp;
1102                 arglist->lastp = &sp->next;
1103         }
1104 }
1105
1106
1107 static char expdir[PATH_MAX];
1108 #define expdir_end (expdir + sizeof(expdir))
1109
1110 /*
1111  * Perform pathname generation and remove control characters.
1112  * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1113  * The results are stored in the list exparg.
1114  */
1115 static void
1116 expandmeta(struct strlist *str, int flag __unused)
1117 {
1118         char *p;
1119         struct strlist **savelastp;
1120         struct strlist *sp;
1121         char c;
1122         /* TODO - EXP_REDIR */
1123
1124         while (str) {
1125                 if (fflag)
1126                         goto nometa;
1127                 p = str->text;
1128                 for (;;) {                      /* fast check for meta chars */
1129                         if ((c = *p++) == '\0')
1130                                 goto nometa;
1131                         if (c == '*' || c == '?' || c == '[')
1132                                 break;
1133                 }
1134                 savelastp = exparg.lastp;
1135                 INTOFF;
1136                 expmeta(expdir, str->text);
1137                 INTON;
1138                 if (exparg.lastp == savelastp) {
1139                         /*
1140                          * no matches
1141                          */
1142 nometa:
1143                         *exparg.lastp = str;
1144                         rmescapes(str->text);
1145                         exparg.lastp = &str->next;
1146                 } else {
1147                         *exparg.lastp = NULL;
1148                         *savelastp = sp = expsort(*savelastp);
1149                         while (sp->next != NULL)
1150                                 sp = sp->next;
1151                         exparg.lastp = &sp->next;
1152                 }
1153                 str = str->next;
1154         }
1155 }
1156
1157
1158 /*
1159  * Do metacharacter (i.e. *, ?, [...]) expansion.
1160  */
1161
1162 static void
1163 expmeta(char *enddir, char *name)
1164 {
1165         const char *p;
1166         const char *q;
1167         const char *start;
1168         char *endname;
1169         int metaflag;
1170         struct stat statb;
1171         DIR *dirp;
1172         struct dirent *dp;
1173         int atend;
1174         int matchdot;
1175         int esc;
1176         int namlen;
1177
1178         metaflag = 0;
1179         start = name;
1180         for (p = name; esc = 0, *p; p += esc + 1) {
1181                 if (*p == '*' || *p == '?')
1182                         metaflag = 1;
1183                 else if (*p == '[') {
1184                         q = p + 1;
1185                         if (*q == '!' || *q == '^')
1186                                 q++;
1187                         for (;;) {
1188                                 while (*q == CTLQUOTEMARK)
1189                                         q++;
1190                                 if (*q == CTLESC)
1191                                         q++;
1192                                 if (*q == '/' || *q == '\0')
1193                                         break;
1194                                 if (*++q == ']') {
1195                                         metaflag = 1;
1196                                         break;
1197                                 }
1198                         }
1199                 } else if (*p == '\0')
1200                         break;
1201                 else if (*p == CTLQUOTEMARK)
1202                         continue;
1203                 else {
1204                         if (*p == CTLESC)
1205                                 esc++;
1206                         if (p[esc] == '/') {
1207                                 if (metaflag)
1208                                         break;
1209                                 start = p + esc + 1;
1210                         }
1211                 }
1212         }
1213         if (metaflag == 0) {    /* we've reached the end of the file name */
1214                 if (enddir != expdir)
1215                         metaflag++;
1216                 for (p = name ; ; p++) {
1217                         if (*p == CTLQUOTEMARK)
1218                                 continue;
1219                         if (*p == CTLESC)
1220                                 p++;
1221                         *enddir++ = *p;
1222                         if (*p == '\0')
1223                                 break;
1224                         if (enddir == expdir_end)
1225                                 return;
1226                 }
1227                 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1228                         addfname(expdir);
1229                 return;
1230         }
1231         endname = name + (p - name);
1232         if (start != name) {
1233                 p = name;
1234                 while (p < start) {
1235                         while (*p == CTLQUOTEMARK)
1236                                 p++;
1237                         if (*p == CTLESC)
1238                                 p++;
1239                         *enddir++ = *p++;
1240                         if (enddir == expdir_end)
1241                                 return;
1242                 }
1243         }
1244         if (enddir == expdir) {
1245                 p = ".";
1246         } else if (enddir == expdir + 1 && *expdir == '/') {
1247                 p = "/";
1248         } else {
1249                 p = expdir;
1250                 enddir[-1] = '\0';
1251         }
1252         if ((dirp = opendir(p)) == NULL)
1253                 return;
1254         if (enddir != expdir)
1255                 enddir[-1] = '/';
1256         if (*endname == 0) {
1257                 atend = 1;
1258         } else {
1259                 atend = 0;
1260                 *endname = '\0';
1261                 endname += esc + 1;
1262         }
1263         matchdot = 0;
1264         p = start;
1265         while (*p == CTLQUOTEMARK)
1266                 p++;
1267         if (*p == CTLESC)
1268                 p++;
1269         if (*p == '.')
1270                 matchdot++;
1271         while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1272                 if (dp->d_name[0] == '.' && ! matchdot)
1273                         continue;
1274                 if (patmatch(start, dp->d_name, 0)) {
1275                         namlen = dp->d_namlen;
1276                         if (enddir + namlen + 1 > expdir_end)
1277                                 continue;
1278                         memcpy(enddir, dp->d_name, namlen + 1);
1279                         if (atend)
1280                                 addfname(expdir);
1281                         else {
1282                                 if (dp->d_type != DT_UNKNOWN &&
1283                                     dp->d_type != DT_DIR &&
1284                                     dp->d_type != DT_LNK)
1285                                         continue;
1286                                 if (enddir + namlen + 2 > expdir_end)
1287                                         continue;
1288                                 enddir[namlen] = '/';
1289                                 enddir[namlen + 1] = '\0';
1290                                 expmeta(enddir + namlen + 1, endname);
1291                         }
1292                 }
1293         }
1294         closedir(dirp);
1295         if (! atend)
1296                 endname[-esc - 1] = esc ? CTLESC : '/';
1297 }
1298
1299
1300 /*
1301  * Add a file name to the list.
1302  */
1303
1304 static void
1305 addfname(char *name)
1306 {
1307         char *p;
1308         struct strlist *sp;
1309         size_t len;
1310
1311         len = strlen(name);
1312         p = stalloc(len + 1);
1313         memcpy(p, name, len + 1);
1314         sp = (struct strlist *)stalloc(sizeof *sp);
1315         sp->text = p;
1316         *exparg.lastp = sp;
1317         exparg.lastp = &sp->next;
1318 }
1319
1320
1321 /*
1322  * Sort the results of file name expansion.  It calculates the number of
1323  * strings to sort and then calls msort (short for merge sort) to do the
1324  * work.
1325  */
1326
1327 static struct strlist *
1328 expsort(struct strlist *str)
1329 {
1330         int len;
1331         struct strlist *sp;
1332
1333         len = 0;
1334         for (sp = str ; sp ; sp = sp->next)
1335                 len++;
1336         return msort(str, len);
1337 }
1338
1339
1340 static struct strlist *
1341 msort(struct strlist *list, int len)
1342 {
1343         struct strlist *p, *q = NULL;
1344         struct strlist **lpp;
1345         int half;
1346         int n;
1347
1348         if (len <= 1)
1349                 return list;
1350         half = len >> 1;
1351         p = list;
1352         for (n = half ; --n >= 0 ; ) {
1353                 q = p;
1354                 p = p->next;
1355         }
1356         q->next = NULL;                 /* terminate first half of list */
1357         q = msort(list, half);          /* sort first half of list */
1358         p = msort(p, len - half);               /* sort second half */
1359         lpp = &list;
1360         for (;;) {
1361                 if (strcmp(p->text, q->text) < 0) {
1362                         *lpp = p;
1363                         lpp = &p->next;
1364                         if ((p = *lpp) == NULL) {
1365                                 *lpp = q;
1366                                 break;
1367                         }
1368                 } else {
1369                         *lpp = q;
1370                         lpp = &q->next;
1371                         if ((q = *lpp) == NULL) {
1372                                 *lpp = p;
1373                                 break;
1374                         }
1375                 }
1376         }
1377         return list;
1378 }
1379
1380
1381
1382 static wchar_t
1383 get_wc(const char **p)
1384 {
1385         wchar_t c;
1386         int chrlen;
1387
1388         chrlen = mbtowc(&c, *p, 4);
1389         if (chrlen == 0)
1390                 return 0;
1391         else if (chrlen == -1)
1392                 c = 0;
1393         else
1394                 *p += chrlen;
1395         return c;
1396 }
1397
1398
1399 /*
1400  * See if a character matches a character class, starting at the first colon
1401  * of "[:class:]".
1402  * If a valid character class is recognized, a pointer to the next character
1403  * after the final closing bracket is stored into *end, otherwise a null
1404  * pointer is stored into *end.
1405  */
1406 static int
1407 match_charclass(const char *p, wchar_t chr, const char **end)
1408 {
1409         char name[20];
1410         const char *nameend;
1411         wctype_t cclass;
1412
1413         *end = NULL;
1414         p++;
1415         nameend = strstr(p, ":]");
1416         if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1417             nameend == p)
1418                 return 0;
1419         memcpy(name, p, nameend - p);
1420         name[nameend - p] = '\0';
1421         *end = nameend + 2;
1422         cclass = wctype(name);
1423         /* An unknown class matches nothing but is valid nevertheless. */
1424         if (cclass == 0)
1425                 return 0;
1426         return iswctype(chr, cclass);
1427 }
1428
1429
1430 /*
1431  * Returns true if the pattern matches the string.
1432  */
1433
1434 static int
1435 patmatch(const char *pattern, const char *string, int squoted)
1436 {
1437         const char *p, *q, *end;
1438         const char *bt_p, *bt_q;
1439         char c;
1440         wchar_t wc, wc2;
1441
1442         p = pattern;
1443         q = string;
1444         bt_p = NULL;
1445         bt_q = NULL;
1446         for (;;) {
1447                 switch (c = *p++) {
1448                 case '\0':
1449                         if (*q != '\0')
1450                                 goto backtrack;
1451                         return 1;
1452                 case CTLESC:
1453                         if (squoted && *q == CTLESC)
1454                                 q++;
1455                         if (*q++ != *p++)
1456                                 goto backtrack;
1457                         break;
1458                 case CTLQUOTEMARK:
1459                         continue;
1460                 case '?':
1461                         if (squoted && *q == CTLESC)
1462                                 q++;
1463                         if (*q == '\0')
1464                                 return 0;
1465                         if (localeisutf8) {
1466                                 wc = get_wc(&q);
1467                                 /*
1468                                  * A '?' does not match invalid UTF-8 but a
1469                                  * '*' does, so backtrack.
1470                                  */
1471                                 if (wc == 0)
1472                                         goto backtrack;
1473                         } else
1474                                 wc = (unsigned char)*q++;
1475                         break;
1476                 case '*':
1477                         c = *p;
1478                         while (c == CTLQUOTEMARK || c == '*')
1479                                 c = *++p;
1480                         /*
1481                          * If the pattern ends here, we know the string
1482                          * matches without needing to look at the rest of it.
1483                          */
1484                         if (c == '\0')
1485                                 return 1;
1486                         /*
1487                          * First try the shortest match for the '*' that
1488                          * could work. We can forget any earlier '*' since
1489                          * there is no way having it match more characters
1490                          * can help us, given that we are already here.
1491                          */
1492                         bt_p = p;
1493                         bt_q = q;
1494                         break;
1495                 case '[': {
1496                         const char *endp;
1497                         int invert, found;
1498                         wchar_t chr;
1499
1500                         endp = p;
1501                         if (*endp == '!' || *endp == '^')
1502                                 endp++;
1503                         for (;;) {
1504                                 while (*endp == CTLQUOTEMARK)
1505                                         endp++;
1506                                 if (*endp == 0)
1507                                         goto dft;               /* no matching ] */
1508                                 if (*endp == CTLESC)
1509                                         endp++;
1510                                 if (*++endp == ']')
1511                                         break;
1512                         }
1513                         invert = 0;
1514                         if (*p == '!' || *p == '^') {
1515                                 invert++;
1516                                 p++;
1517                         }
1518                         found = 0;
1519                         if (squoted && *q == CTLESC)
1520                                 q++;
1521                         if (*q == '\0')
1522                                 return 0;
1523                         if (localeisutf8) {
1524                                 chr = get_wc(&q);
1525                                 if (chr == 0)
1526                                         goto backtrack;
1527                         } else
1528                                 chr = (unsigned char)*q++;
1529                         c = *p++;
1530                         do {
1531                                 if (c == CTLQUOTEMARK)
1532                                         continue;
1533                                 if (c == '[' && *p == ':') {
1534                                         found |= match_charclass(p, chr, &end);
1535                                         if (end != NULL)
1536                                                 p = end;
1537                                 }
1538                                 if (c == CTLESC)
1539                                         c = *p++;
1540                                 if (localeisutf8 && c & 0x80) {
1541                                         p--;
1542                                         wc = get_wc(&p);
1543                                         if (wc == 0) /* bad utf-8 */
1544                                                 return 0;
1545                                 } else
1546                                         wc = (unsigned char)c;
1547                                 if (*p == '-' && p[1] != ']') {
1548                                         p++;
1549                                         while (*p == CTLQUOTEMARK)
1550                                                 p++;
1551                                         if (*p == CTLESC)
1552                                                 p++;
1553                                         if (localeisutf8) {
1554                                                 wc2 = get_wc(&p);
1555                                                 if (wc2 == 0) /* bad utf-8 */
1556                                                         return 0;
1557                                         } else
1558                                                 wc2 = (unsigned char)*p++;
1559                                         if (   collate_range_cmp(chr, wc) >= 0
1560                                             && collate_range_cmp(chr, wc2) <= 0
1561                                            )
1562                                                 found = 1;
1563                                 } else {
1564                                         if (chr == wc)
1565                                                 found = 1;
1566                                 }
1567                         } while ((c = *p++) != ']');
1568                         if (found == invert)
1569                                 goto backtrack;
1570                         break;
1571                 }
1572 dft:            default:
1573                         if (squoted && *q == CTLESC)
1574                                 q++;
1575                         if (*q == '\0')
1576                                 return 0;
1577                         if (*q++ == c)
1578                                 break;
1579 backtrack:
1580                         /*
1581                          * If we have a mismatch (other than hitting the end
1582                          * of the string), go back to the last '*' seen and
1583                          * have it match one additional character.
1584                          */
1585                         if (bt_p == NULL)
1586                                 return 0;
1587                         if (squoted && *bt_q == CTLESC)
1588                                 bt_q++;
1589                         if (*bt_q == '\0')
1590                                 return 0;
1591                         bt_q++;
1592                         p = bt_p;
1593                         q = bt_q;
1594                         break;
1595                 }
1596         }
1597 }
1598
1599
1600
1601 /*
1602  * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1603  */
1604
1605 void
1606 rmescapes(char *str)
1607 {
1608         char *p, *q;
1609
1610         p = str;
1611         while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1612                 if (*p++ == '\0')
1613                         return;
1614         }
1615         q = p;
1616         while (*p) {
1617                 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1618                         p++;
1619                         continue;
1620                 }
1621                 if (*p == CTLESC)
1622                         p++;
1623                 *q++ = *p++;
1624         }
1625         *q = '\0';
1626 }
1627
1628
1629
1630 /*
1631  * See if a pattern matches in a case statement.
1632  */
1633
1634 int
1635 casematch(union node *pattern, const char *val)
1636 {
1637         struct stackmark smark;
1638         int result;
1639         char *p;
1640
1641         setstackmark(&smark);
1642         argbackq = pattern->narg.backquote;
1643         STARTSTACKSTR(expdest);
1644         ifslastp = NULL;
1645         argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1646         STPUTC('\0', expdest);
1647         p = grabstackstr(expdest);
1648         result = patmatch(p, val, 0);
1649         popstackmark(&smark);
1650         return result;
1651 }
1652
1653 /*
1654  * Our own itoa().
1655  */
1656
1657 static char *
1658 cvtnum(int num, char *buf)
1659 {
1660         char temp[32];
1661         int neg = num < 0;
1662         char *p = temp + 31;
1663
1664         temp[31] = '\0';
1665
1666         do {
1667                 *--p = num % 10 + '0';
1668         } while ((num /= 10) != 0);
1669
1670         if (neg)
1671                 *--p = '-';
1672
1673         STPUTS(p, buf);
1674         return buf;
1675 }
1676
1677 /*
1678  * Do most of the work for wordexp(3).
1679  */
1680
1681 int
1682 wordexpcmd(int argc, char **argv)
1683 {
1684         size_t len;
1685         int i;
1686
1687         out1fmt("%08x", argc - 1);
1688         for (i = 1, len = 0; i < argc; i++)
1689                 len += strlen(argv[i]);
1690         out1fmt("%08x", (int)len);
1691         for (i = 1; i < argc; i++)
1692                 outbin(argv[i], strlen(argv[i]) + 1, out1);
1693         return (0);
1694 }