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.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
37 static char sccsid[] = "@(#)expand.c 8.5 (Berkeley) 5/15/95";
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include <sys/types.h>
59 * Routines to expand arguments to commands. We have to deal with
60 * backquotes, shell variables, and file metacharacters.
83 * Structure specifying which parts of the string should be searched
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 */
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 */
101 static void argstr(char *, int);
102 static char *exptilde(char *, int);
103 static void expbackq(union node *, int, int);
104 static int subevalvar(char *, char *, int, int, int, int, int);
105 static char *evalvar(char *, int);
106 static int varisset(char *, int);
107 static void varvalue(char *, int, int, int);
108 static void recordregion(int, int, int);
109 static void removerecordregions(int);
110 static void ifsbreakup(char *, struct arglist *);
111 static void expandmeta(struct strlist *, int);
112 static void expmeta(char *, char *);
113 static void addfname(char *);
114 static struct strlist *expsort(struct strlist *);
115 static struct strlist *msort(struct strlist *, int);
116 static int patmatch(const char *, const char *, int);
117 static char *cvtnum(int, char *);
118 static int collate_range_cmp(wchar_t, wchar_t);
121 collate_range_cmp(wchar_t c1, wchar_t c2)
123 static wchar_t s1[2], s2[2];
127 return (wcscoll(s1, s2));
131 * Expand shell variables and backquotes inside a here document.
132 * union node *arg the document
133 * int fd; where to write the expanded version
137 expandhere(union node *arg, int fd)
139 expandarg(arg, (struct arglist *)NULL, 0);
140 xwrite(fd, stackblock(), expdest - stackblock());
144 stputs_quotes(const char *data, const char *syntax, char *p)
148 if (syntax[(int)*data] == CCTL)
154 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
157 * Perform expansions on an argument, placing the resulting list of arguments
158 * in arglist. Parameter expansion, command substitution and arithmetic
159 * expansion are always performed; additional expansions can be requested
161 * The result is left in the stack string.
162 * When arglist is NULL, perform here document expansion.
164 * Caution: this function uses global state and is not reentrant.
165 * However, a new invocation after an interrupted invocation is safe
166 * and will reset the global state for the new call.
169 expandarg(union node *arg, struct arglist *arglist, int flag)
174 argbackq = arg->narg.backquote;
175 STARTSTACKSTR(expdest);
176 ifsfirst.next = NULL;
178 argstr(arg->narg.text, flag);
179 if (arglist == NULL) {
180 STACKSTRNUL(expdest);
181 return; /* here document expanded */
183 STPUTC('\0', expdest);
184 p = grabstackstr(expdest);
185 exparg.lastp = &exparg.list;
189 if (flag & EXP_FULL) {
190 ifsbreakup(p, &exparg);
191 *exparg.lastp = NULL;
192 exparg.lastp = &exparg.list;
193 expandmeta(exparg.list, flag);
195 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
197 sp = (struct strlist *)stalloc(sizeof (struct strlist));
200 exparg.lastp = &sp->next;
202 while (ifsfirst.next != NULL) {
203 struct ifsregion *ifsp;
205 ifsp = ifsfirst.next->next;
206 ckfree(ifsfirst.next);
207 ifsfirst.next = ifsp;
210 *exparg.lastp = NULL;
212 *arglist->lastp = exparg.list;
213 arglist->lastp = exparg.lastp;
220 * Perform parameter expansion, command substitution and arithmetic
221 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
222 * Processing ends at a CTLENDVAR character as well as '\0'.
223 * This is used to expand word in ${var+word} etc.
224 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
225 * characters to allow for further processing.
226 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
229 argstr(char *p, int flag)
232 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
237 split_lit = flag & EXP_SPLIT_LIT;
238 lit_quoted = flag & EXP_LIT_QUOTED;
239 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
240 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
241 p = exptilde(p, flag);
243 CHECKSTRSPACE(2, expdest);
250 /* "$@" syntax adherence hack */
251 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
253 if ((flag & EXP_FULL) != 0)
264 if (split_lit && !lit_quoted)
265 recordregion(expdest - stackblock() -
267 expdest - stackblock(), 0);
270 p = evalvar(p, flag);
273 case CTLBACKQ|CTLQUOTE:
274 expbackq(argbackq->n, c & CTLQUOTE, flag);
275 argbackq = argbackq->next;
283 * sort of a hack - expand tildes in variable
284 * assignments (after the first '=' and after ':'s).
287 if (split_lit && !lit_quoted)
288 recordregion(expdest - stackblock() - 1,
289 expdest - stackblock(), 0);
290 if (flag & EXP_VARTILDE && *p == '~' &&
291 (c != '=' || firsteq)) {
294 p = exptilde(p, flag);
299 if (split_lit && !lit_quoted)
300 recordregion(expdest - stackblock() - 1,
301 expdest - stackblock(), 0);
308 * Perform tilde expansion, placing the result in the stack string and
309 * returning the next position in the input string to process.
312 exptilde(char *p, int flag)
317 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
319 while ((c = *p) != '\0') {
321 case CTLESC: /* This means CTL* are always considered quoted. */
324 case CTLBACKQ | CTLQUOTE:
330 if (flag & EXP_VARTILDE)
341 if (*(startp+1) == '\0') {
342 if ((home = lookupvar("HOME")) == NULL)
345 if ((pw = getpwnam(startp+1)) == NULL)
353 STPUTS_QUOTES(home, SQSYNTAX, expdest);
355 STPUTS(home, expdest);
364 removerecordregions(int endoff)
366 if (ifslastp == NULL)
369 if (ifsfirst.endoff > endoff) {
370 while (ifsfirst.next != NULL) {
371 struct ifsregion *ifsp;
373 ifsp = ifsfirst.next->next;
374 ckfree(ifsfirst.next);
375 ifsfirst.next = ifsp;
378 if (ifsfirst.begoff > endoff)
381 ifslastp = &ifsfirst;
382 ifsfirst.endoff = endoff;
387 ifslastp = &ifsfirst;
388 while (ifslastp->next && ifslastp->next->begoff < endoff)
389 ifslastp=ifslastp->next;
390 while (ifslastp->next != NULL) {
391 struct ifsregion *ifsp;
393 ifsp = ifslastp->next->next;
394 ckfree(ifslastp->next);
395 ifslastp->next = ifsp;
398 if (ifslastp->endoff > endoff)
399 ifslastp->endoff = endoff;
403 * Expand arithmetic expression. Backup to start of expression,
404 * evaluate, place result in (backed up) result, adjust string position.
412 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
416 * This routine is slightly over-complicated for
417 * efficiency. First we make sure there is
418 * enough space for the result, which may be bigger
419 * than the expression. Next we
420 * scan backwards looking for the start of arithmetic. If the
421 * next previous character is a CTLESC character, then we
422 * have to rescan starting from the beginning since CTLESC
423 * characters have to be processed left to right.
425 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
426 USTPUTC('\0', expdest);
427 start = stackblock();
429 while (p >= start && *p != CTLARI)
431 if (p < start || *p != CTLARI)
432 error("missing CTLARI (shouldn't happen)");
433 if (p > start && *(p - 1) == CTLESC)
434 for (p = start; *p != CTLARI; p++)
443 removerecordregions(begoff);
446 q = grabstackstr(expdest);
448 ungrabstackstr(q, expdest);
449 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
453 recordregion(begoff, p - 1 - start, 0);
454 result = expdest - p + 1;
455 STADJUST(-result, expdest);
460 * Perform command substitution.
463 expbackq(union node *cmd, int quoted, int flag)
469 char *dest = expdest;
470 struct ifsregion saveifs, *savelastp;
471 struct nodelist *saveargbackq;
473 int startloc = dest - stackblock();
474 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
475 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
480 savelastp = ifslastp;
481 saveargbackq = argbackq;
482 p = grabstackstr(dest);
483 evalbackcmd(cmd, &in);
484 ungrabstackstr(p, dest);
486 ifslastp = savelastp;
487 argbackq = saveargbackq;
492 /* Don't copy trailing newlines */
494 if (--in.nleft < 0) {
497 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
498 TRACE(("expbackq: read returns %d\n", i));
509 CHECKSTRSPACE(nnl + 2, dest);
514 if (quotes && syntax[(int)lastc] == CCTL)
515 USTPUTC(CTLESC, dest);
516 USTPUTC(lastc, dest);
526 exitstatus = waitforjob(in.jp, (int *)NULL);
528 recordregion(startloc, dest - stackblock(), 0);
529 TRACE(("expbackq: size=%td: \"%.*s\"\n",
530 ((dest - stackblock()) - startloc),
531 (int)((dest - stackblock()) - startloc),
532 stackblock() + startloc));
540 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
541 int varflags, int quotes)
547 struct nodelist *saveargbackq = argbackq;
550 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
551 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
552 EXP_CASE : 0) | EXP_TILDE);
553 STACKSTRNUL(expdest);
554 argbackq = saveargbackq;
555 startp = stackblock() + startloc;
557 str = stackblock() + strloc;
561 setvar(str, startp, 0);
562 amount = startp - expdest;
563 STADJUST(amount, expdest);
568 if (*p != CTLENDVAR) {
569 outfmt(out2, "%s\n", startp);
572 error("%.*s: parameter %snot set", (int)(p - str - 1),
573 str, (varflags & VSNUL) ? "null or "
578 for (loc = startp; loc < str; loc++) {
581 if (patmatch(str, startp, quotes)) {
586 if (quotes && *loc == CTLESC)
592 for (loc = str - 1; loc >= startp;) {
595 if (patmatch(str, startp, quotes)) {
601 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
602 for (q = startp; q < loc; q++)
612 for (loc = str - 1; loc >= startp;) {
613 if (patmatch(str, loc, quotes)) {
614 amount = loc - expdest;
615 STADJUST(amount, expdest);
619 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
620 for (q = startp; q < loc; q++)
630 for (loc = startp; loc < str - 1; loc++) {
631 if (patmatch(str, loc, quotes)) {
632 amount = loc - expdest;
633 STADJUST(amount, expdest);
636 if (quotes && *loc == CTLESC)
647 amount = ((str - 1) - (loc - startp)) - expdest;
648 STADJUST(amount, expdest);
649 while (loc != str - 1)
656 * Expand a variable, and return a pointer to the next character in the
661 evalvar(char *p, int flag)
675 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
677 varflags = (unsigned char)*p++;
678 subtype = varflags & VSTYPE;
683 p = strchr(p, '=') + 1;
684 again: /* jump here after setting a variable with ${var=text} */
685 if (varflags & VSLINENO) {
689 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
691 } else if (special) {
692 set = varisset(var, varflags & VSNUL);
695 val = bltinlookup(var, 1);
696 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
703 startloc = expdest - stackblock();
704 if (!set && uflag && *var != '@' && *var != '*') {
712 error("%.*s: parameter not set", (int)(p - var - 1),
716 if (set && subtype != VSPLUS) {
717 /* insert the value of the variable */
719 varvalue(var, varflags & VSQUOTE, subtype, flag);
720 if (subtype == VSLENGTH) {
721 varlenb = expdest - stackblock() - startloc;
724 val = stackblock() + startloc;
725 for (;val != expdest; val++)
726 if ((*val & 0xC0) == 0x80)
729 STADJUST(-varlenb, expdest);
732 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
735 if (subtype == VSLENGTH) {
738 (*val & 0xC0) != 0x80)
743 STPUTS_QUOTES(val, syntax, expdest);
745 STPUTS(val, expdest);
751 if (subtype == VSPLUS)
754 easy = ((varflags & VSQUOTE) == 0 ||
755 (*var == '@' && shellparam.nparam != 1));
760 expdest = cvtnum(varlen, expdest);
767 recordregion(startloc, expdest - stackblock(),
768 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
769 (*var == '@' || *var == '*')));
775 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
776 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
790 * Terminate the string and start recording the pattern
793 STPUTC('\0', expdest);
794 patloc = expdest - stackblock();
795 if (subevalvar(p, NULL, patloc, subtype,
796 startloc, varflags, quotes) == 0) {
797 int amount = (expdest - stackblock() - patloc) + 1;
798 STADJUST(-amount, expdest);
800 /* Remove any recorded regions beyond start of variable */
801 removerecordregions(startloc);
807 if (subevalvar(p, var, 0, subtype, startloc, varflags,
811 * Remove any recorded regions beyond
814 removerecordregions(startloc);
825 error("${%.*s%s}: Bad substitution", c, var,
826 (c > 0 && *p != CTLENDVAR) ? "..." : "");
831 p[-1] = '='; /* recover overwritten '=' */
833 if (subtype != VSNORMAL) { /* skip to end of alternative */
836 if ((c = *p++) == CTLESC)
838 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
840 argbackq = argbackq->next;
841 } else if (c == CTLVAR) {
842 if ((*p++ & VSTYPE) != VSNORMAL)
844 } else if (c == CTLENDVAR) {
856 * Test whether a specialized variable is set.
860 varisset(char *name, int nulok)
864 return backgndpidset();
865 else if (*name == '@' || *name == '*') {
866 if (*shellparam.p == NULL)
872 for (av = shellparam.p; *av; av++)
877 } else if (is_digit(*name)) {
879 int num = atoi(name);
881 if (num > shellparam.nparam)
887 ap = shellparam.p[num - 1];
889 if (nulok && (ap == NULL || *ap == '\0'))
896 strtodest(const char *p, int flag, int subtype, int quoted)
898 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
899 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
905 * Add the value of a specialized variable to the stack string.
909 varvalue(char *name, int quoted, int subtype, int flag)
925 num = shellparam.nparam;
928 num = backgndpidval();
930 expdest = cvtnum(num, expdest);
933 for (i = 0 ; i < NOPTS ; i++) {
935 STPUTC(optlist[i].letter, expdest);
939 if (flag & EXP_FULL && quoted) {
940 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
941 strtodest(p, flag, subtype, quoted);
943 STPUTC('\0', expdest);
953 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
954 strtodest(p, flag, subtype, quoted);
957 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
958 STPUTC(sep, expdest);
963 strtodest(p, flag, subtype, quoted);
966 if (is_digit(*name)) {
968 if (num > 0 && num <= shellparam.nparam) {
969 p = shellparam.p[num - 1];
970 strtodest(p, flag, subtype, quoted);
980 * Record the fact that we have to scan this region of the
981 * string for IFS characters.
985 recordregion(int start, int end, int inquotes)
987 struct ifsregion *ifsp;
990 if (ifslastp == NULL) {
993 if (ifslastp->endoff == start
994 && ifslastp->inquotes == inquotes) {
995 /* extend previous area */
996 ifslastp->endoff = end;
1000 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
1001 ifslastp->next = ifsp;
1004 ifslastp->next = NULL;
1005 ifslastp->begoff = start;
1006 ifslastp->endoff = end;
1007 ifslastp->inquotes = inquotes;
1014 * Break the argument string into pieces based upon IFS and add the
1015 * strings to the argument list. The regions of the string to be
1016 * searched for IFS characters have been stored by recordregion.
1017 * CTLESC characters are preserved but have little effect in this pass
1018 * other than escaping CTL* characters. In particular, they do not escape
1019 * IFS characters: that should be done with the ifsregion mechanism.
1020 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1021 * This pass treats them as a regular character, making the string non-empty.
1022 * Later, they are removed along with the other CTL* characters.
1025 ifsbreakup(char *string, struct arglist *arglist)
1027 struct ifsregion *ifsp;
1034 int had_param_ch = 0;
1038 if (ifslastp == NULL) {
1039 /* Return entire argument, IFS doesn't apply to any of it */
1040 sp = (struct strlist *)stalloc(sizeof *sp);
1042 *arglist->lastp = sp;
1043 arglist->lastp = &sp->next;
1047 ifs = ifsset() ? ifsval() : " \t\n";
1049 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1050 p = string + ifsp->begoff;
1051 while (p < string + ifsp->endoff) {
1055 if (ifsp->inquotes) {
1056 /* Only NULs (should be from "$@") end args */
1064 if (!strchr(ifs, *p)) {
1069 ifsspc = strchr(" \t\n", *p);
1071 /* Ignore IFS whitespace at start */
1072 if (q == start && ifsspc != NULL) {
1080 /* Save this argument... */
1082 sp = (struct strlist *)stalloc(sizeof *sp);
1084 *arglist->lastp = sp;
1085 arglist->lastp = &sp->next;
1088 if (ifsspc != NULL) {
1089 /* Ignore further trailing IFS whitespace */
1090 for (; p < string + ifsp->endoff; p++) {
1094 if (strchr(ifs, *p) == NULL) {
1098 if (strchr(" \t\n", *p) == NULL) {
1109 * Save anything left as an argument.
1110 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1111 * generating 2 arguments, the second of which is empty.
1112 * Some recent clarification of the Posix spec say that it
1113 * should only generate one....
1115 if (had_param_ch || *start != 0) {
1116 sp = (struct strlist *)stalloc(sizeof *sp);
1118 *arglist->lastp = sp;
1119 arglist->lastp = &sp->next;
1124 static char expdir[PATH_MAX];
1125 #define expdir_end (expdir + sizeof(expdir))
1128 * Perform pathname generation and remove control characters.
1129 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1130 * The results are stored in the list exparg.
1133 expandmeta(struct strlist *str, int flag __unused)
1136 struct strlist **savelastp;
1139 /* TODO - EXP_REDIR */
1145 for (;;) { /* fast check for meta chars */
1146 if ((c = *p++) == '\0')
1148 if (c == '*' || c == '?' || c == '[')
1151 savelastp = exparg.lastp;
1153 expmeta(expdir, str->text);
1155 if (exparg.lastp == savelastp) {
1160 *exparg.lastp = str;
1161 rmescapes(str->text);
1162 exparg.lastp = &str->next;
1164 *exparg.lastp = NULL;
1165 *savelastp = sp = expsort(*savelastp);
1166 while (sp->next != NULL)
1168 exparg.lastp = &sp->next;
1176 * Do metacharacter (i.e. *, ?, [...]) expansion.
1180 expmeta(char *enddir, char *name)
1196 for (p = name; esc = 0, *p; p += esc + 1) {
1197 if (*p == '*' || *p == '?')
1199 else if (*p == '[') {
1201 if (*q == '!' || *q == '^')
1204 while (*q == CTLQUOTEMARK)
1208 if (*q == '/' || *q == '\0')
1215 } else if (*p == '\0')
1217 else if (*p == CTLQUOTEMARK)
1222 if (p[esc] == '/') {
1225 start = p + esc + 1;
1229 if (metaflag == 0) { /* we've reached the end of the file name */
1230 if (enddir != expdir)
1232 for (p = name ; ; p++) {
1233 if (*p == CTLQUOTEMARK)
1240 if (enddir == expdir_end)
1243 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1248 if (start != name) {
1251 while (*p == CTLQUOTEMARK)
1256 if (enddir == expdir_end)
1260 if (enddir == expdir) {
1262 } else if (enddir == expdir + 1 && *expdir == '/') {
1268 if ((dirp = opendir(p)) == NULL)
1270 if (enddir != expdir)
1272 if (*endname == 0) {
1281 while (*p == CTLQUOTEMARK)
1287 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1288 if (dp->d_name[0] == '.' && ! matchdot)
1290 if (patmatch(start, dp->d_name, 0)) {
1291 if (enddir + dp->d_namlen + 1 > expdir_end)
1293 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1297 if (enddir + dp->d_namlen + 2 > expdir_end)
1299 enddir[dp->d_namlen] = '/';
1300 enddir[dp->d_namlen + 1] = '\0';
1301 expmeta(enddir + dp->d_namlen + 1, endname);
1307 endname[-esc - 1] = esc ? CTLESC : '/';
1312 * Add a file name to the list.
1316 addfname(char *name)
1321 p = stalloc(strlen(name) + 1);
1323 sp = (struct strlist *)stalloc(sizeof *sp);
1326 exparg.lastp = &sp->next;
1331 * Sort the results of file name expansion. It calculates the number of
1332 * strings to sort and then calls msort (short for merge sort) to do the
1336 static struct strlist *
1337 expsort(struct strlist *str)
1343 for (sp = str ; sp ; sp = sp->next)
1345 return msort(str, len);
1349 static struct strlist *
1350 msort(struct strlist *list, int len)
1352 struct strlist *p, *q = NULL;
1353 struct strlist **lpp;
1361 for (n = half ; --n >= 0 ; ) {
1365 q->next = NULL; /* terminate first half of list */
1366 q = msort(list, half); /* sort first half of list */
1367 p = msort(p, len - half); /* sort second half */
1370 if (strcmp(p->text, q->text) < 0) {
1373 if ((p = *lpp) == NULL) {
1380 if ((q = *lpp) == NULL) {
1392 get_wc(const char **p)
1397 chrlen = mbtowc(&c, *p, 4);
1400 else if (chrlen == -1)
1409 * See if a character matches a character class, starting at the first colon
1411 * If a valid character class is recognized, a pointer to the next character
1412 * after the final closing bracket is stored into *end, otherwise a null
1413 * pointer is stored into *end.
1416 match_charclass(const char *p, wchar_t chr, const char **end)
1419 const char *nameend;
1424 nameend = strstr(p, ":]");
1425 if (nameend == NULL || nameend - p >= sizeof(name) || nameend == p)
1427 memcpy(name, p, nameend - p);
1428 name[nameend - p] = '\0';
1430 cclass = wctype(name);
1431 /* An unknown class matches nothing but is valid nevertheless. */
1434 return iswctype(chr, cclass);
1439 * Returns true if the pattern matches the string.
1443 patmatch(const char *pattern, const char *string, int squoted)
1445 const char *p, *q, *end;
1446 const char *bt_p, *bt_q;
1461 if (squoted && *q == CTLESC)
1469 if (squoted && *q == CTLESC)
1476 * A '?' does not match invalid UTF-8 but a
1477 * '*' does, so backtrack.
1482 wc = (unsigned char)*q++;
1486 while (c == CTLQUOTEMARK || c == '*')
1489 * If the pattern ends here, we know the string
1490 * matches without needing to look at the rest of it.
1495 * First try the shortest match for the '*' that
1496 * could work. We can forget any earlier '*' since
1497 * there is no way having it match more characters
1498 * can help us, given that we are already here.
1509 if (*endp == '!' || *endp == '^')
1512 while (*endp == CTLQUOTEMARK)
1515 goto dft; /* no matching ] */
1516 if (*endp == CTLESC)
1522 if (*p == '!' || *p == '^') {
1527 if (squoted && *q == CTLESC)
1536 chr = (unsigned char)*q++;
1539 if (c == CTLQUOTEMARK)
1541 if (c == '[' && *p == ':') {
1542 found |= match_charclass(p, chr, &end);
1548 if (localeisutf8 && c & 0x80) {
1551 if (wc == 0) /* bad utf-8 */
1554 wc = (unsigned char)c;
1555 if (*p == '-' && p[1] != ']') {
1557 while (*p == CTLQUOTEMARK)
1563 if (wc2 == 0) /* bad utf-8 */
1566 wc2 = (unsigned char)*p++;
1567 if ( collate_range_cmp(chr, wc) >= 0
1568 && collate_range_cmp(chr, wc2) <= 0
1575 } while ((c = *p++) != ']');
1576 if (found == invert)
1581 if (squoted && *q == CTLESC)
1589 * If we have a mismatch (other than hitting the end
1590 * of the string), go back to the last '*' seen and
1591 * have it match one additional character.
1595 if (squoted && *bt_q == CTLESC)
1610 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1614 rmescapes(char *str)
1619 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1625 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1639 * See if a pattern matches in a case statement.
1643 casematch(union node *pattern, const char *val)
1645 struct stackmark smark;
1649 setstackmark(&smark);
1650 argbackq = pattern->narg.backquote;
1651 STARTSTACKSTR(expdest);
1653 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1654 STPUTC('\0', expdest);
1655 p = grabstackstr(expdest);
1656 result = patmatch(p, val, 0);
1657 popstackmark(&smark);
1666 cvtnum(int num, char *buf)
1670 char *p = temp + 31;
1675 *--p = num % 10 + '0';
1676 } while ((num /= 10) != 0);
1686 * Do most of the work for wordexp(3).
1690 wordexpcmd(int argc, char **argv)
1695 out1fmt("%08x", argc - 1);
1696 for (i = 1, len = 0; i < argc; i++)
1697 len += strlen(argv[i]);
1698 out1fmt("%08x", (int)len);
1699 for (i = 1; i < argc; i++)
1700 outbin(argv[i], strlen(argv[i]) + 1, out1);