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 char *cvtnum(int, char *);
117 static int collate_range_cmp(wchar_t, wchar_t);
120 collate_range_cmp(wchar_t c1, wchar_t c2)
122 static wchar_t s1[2], s2[2];
126 return (wcscoll(s1, s2));
130 * Expand shell variables and backquotes inside a here document.
131 * union node *arg the document
132 * int fd; where to write the expanded version
136 expandhere(union node *arg, int fd)
138 expandarg(arg, (struct arglist *)NULL, 0);
139 xwrite(fd, stackblock(), expdest - stackblock());
143 stputs_quotes(const char *data, const char *syntax, char *p)
147 if (syntax[(int)*data] == CCTL)
153 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
156 * Perform expansions on an argument, placing the resulting list of arguments
157 * in arglist. Parameter expansion, command substitution and arithmetic
158 * expansion are always performed; additional expansions can be requested
160 * The result is left in the stack string.
161 * When arglist is NULL, perform here document expansion.
163 * Caution: this function uses global state and is not reentrant.
164 * However, a new invocation after an interrupted invocation is safe
165 * and will reset the global state for the new call.
168 expandarg(union node *arg, struct arglist *arglist, int flag)
173 argbackq = arg->narg.backquote;
174 STARTSTACKSTR(expdest);
175 ifsfirst.next = NULL;
177 argstr(arg->narg.text, flag);
178 if (arglist == NULL) {
179 STACKSTRNUL(expdest);
180 return; /* here document expanded */
182 STPUTC('\0', expdest);
183 p = grabstackstr(expdest);
184 exparg.lastp = &exparg.list;
188 if (flag & EXP_FULL) {
189 ifsbreakup(p, &exparg);
190 *exparg.lastp = NULL;
191 exparg.lastp = &exparg.list;
192 expandmeta(exparg.list, flag);
194 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
196 sp = (struct strlist *)stalloc(sizeof (struct strlist));
199 exparg.lastp = &sp->next;
201 while (ifsfirst.next != NULL) {
202 struct ifsregion *ifsp;
204 ifsp = ifsfirst.next->next;
205 ckfree(ifsfirst.next);
206 ifsfirst.next = ifsp;
209 *exparg.lastp = NULL;
211 *arglist->lastp = exparg.list;
212 arglist->lastp = exparg.lastp;
219 * Perform parameter expansion, command substitution and arithmetic
220 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
221 * Processing ends at a CTLENDVAR character as well as '\0'.
222 * This is used to expand word in ${var+word} etc.
223 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
224 * characters to allow for further processing.
225 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
228 argstr(char *p, int flag)
231 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
236 split_lit = flag & EXP_SPLIT_LIT;
237 lit_quoted = flag & EXP_LIT_QUOTED;
238 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
239 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
240 p = exptilde(p, flag);
242 CHECKSTRSPACE(2, expdest);
249 /* "$@" syntax adherence hack */
250 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
252 if ((flag & EXP_FULL) != 0)
263 if (split_lit && !lit_quoted)
264 recordregion(expdest - stackblock() -
266 expdest - stackblock(), 0);
269 p = evalvar(p, flag);
272 case CTLBACKQ|CTLQUOTE:
273 expbackq(argbackq->n, c & CTLQUOTE, flag);
274 argbackq = argbackq->next;
282 * sort of a hack - expand tildes in variable
283 * assignments (after the first '=' and after ':'s).
286 if (split_lit && !lit_quoted)
287 recordregion(expdest - stackblock() - 1,
288 expdest - stackblock(), 0);
289 if (flag & EXP_VARTILDE && *p == '~' &&
290 (c != '=' || firsteq)) {
293 p = exptilde(p, flag);
298 if (split_lit && !lit_quoted)
299 recordregion(expdest - stackblock() - 1,
300 expdest - stackblock(), 0);
307 * Perform tilde expansion, placing the result in the stack string and
308 * returning the next position in the input string to process.
311 exptilde(char *p, int flag)
316 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
318 while ((c = *p) != '\0') {
320 case CTLESC: /* This means CTL* are always considered quoted. */
323 case CTLBACKQ | CTLQUOTE:
329 if (flag & EXP_VARTILDE)
340 if (*(startp+1) == '\0') {
341 if ((home = lookupvar("HOME")) == NULL)
344 if ((pw = getpwnam(startp+1)) == NULL)
352 STPUTS_QUOTES(home, SQSYNTAX, expdest);
354 STPUTS(home, expdest);
363 removerecordregions(int endoff)
365 if (ifslastp == NULL)
368 if (ifsfirst.endoff > endoff) {
369 while (ifsfirst.next != NULL) {
370 struct ifsregion *ifsp;
372 ifsp = ifsfirst.next->next;
373 ckfree(ifsfirst.next);
374 ifsfirst.next = ifsp;
377 if (ifsfirst.begoff > endoff)
380 ifslastp = &ifsfirst;
381 ifsfirst.endoff = endoff;
386 ifslastp = &ifsfirst;
387 while (ifslastp->next && ifslastp->next->begoff < endoff)
388 ifslastp=ifslastp->next;
389 while (ifslastp->next != NULL) {
390 struct ifsregion *ifsp;
392 ifsp = ifslastp->next->next;
393 ckfree(ifslastp->next);
394 ifslastp->next = ifsp;
397 if (ifslastp->endoff > endoff)
398 ifslastp->endoff = endoff;
402 * Expand arithmetic expression. Backup to start of expression,
403 * evaluate, place result in (backed up) result, adjust string position.
411 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
415 * This routine is slightly over-complicated for
416 * efficiency. First we make sure there is
417 * enough space for the result, which may be bigger
418 * than the expression. Next we
419 * scan backwards looking for the start of arithmetic. If the
420 * next previous character is a CTLESC character, then we
421 * have to rescan starting from the beginning since CTLESC
422 * characters have to be processed left to right.
424 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
425 USTPUTC('\0', expdest);
426 start = stackblock();
428 while (p >= start && *p != CTLARI)
430 if (p < start || *p != CTLARI)
431 error("missing CTLARI (shouldn't happen)");
432 if (p > start && *(p - 1) == CTLESC)
433 for (p = start; *p != CTLARI; p++)
442 removerecordregions(begoff);
445 q = grabstackstr(expdest);
447 ungrabstackstr(q, expdest);
448 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
452 recordregion(begoff, p - 1 - start, 0);
453 result = expdest - p + 1;
454 STADJUST(-result, expdest);
459 * Perform command substitution.
462 expbackq(union node *cmd, int quoted, int flag)
468 char *dest = expdest;
469 struct ifsregion saveifs, *savelastp;
470 struct nodelist *saveargbackq;
472 int startloc = dest - stackblock();
473 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
474 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
479 savelastp = ifslastp;
480 saveargbackq = argbackq;
481 p = grabstackstr(dest);
482 evalbackcmd(cmd, &in);
483 ungrabstackstr(p, dest);
485 ifslastp = savelastp;
486 argbackq = saveargbackq;
491 /* Don't copy trailing newlines */
493 if (--in.nleft < 0) {
496 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
497 TRACE(("expbackq: read returns %d\n", i));
508 CHECKSTRSPACE(nnl + 2, dest);
513 if (quotes && syntax[(int)lastc] == CCTL)
514 USTPUTC(CTLESC, dest);
515 USTPUTC(lastc, dest);
525 exitstatus = waitforjob(in.jp, (int *)NULL);
527 recordregion(startloc, dest - stackblock(), 0);
528 TRACE(("expbackq: size=%td: \"%.*s\"\n",
529 ((dest - stackblock()) - startloc),
530 (int)((dest - stackblock()) - startloc),
531 stackblock() + startloc));
539 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
540 int varflags, int quotes)
546 struct nodelist *saveargbackq = argbackq;
549 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
550 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
551 EXP_CASE : 0) | EXP_TILDE);
552 STACKSTRNUL(expdest);
553 argbackq = saveargbackq;
554 startp = stackblock() + startloc;
556 str = stackblock() + strloc;
560 setvar(str, startp, 0);
561 amount = startp - expdest;
562 STADJUST(amount, expdest);
567 if (*p != CTLENDVAR) {
568 outfmt(out2, "%s\n", startp);
571 error("%.*s: parameter %snot set", (int)(p - str - 1),
572 str, (varflags & VSNUL) ? "null or "
577 for (loc = startp; loc < str; loc++) {
580 if (patmatch(str, startp, quotes)) {
585 if (quotes && *loc == CTLESC)
591 for (loc = str - 1; loc >= startp;) {
594 if (patmatch(str, startp, quotes)) {
600 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
601 for (q = startp; q < loc; q++)
611 for (loc = str - 1; loc >= startp;) {
612 if (patmatch(str, loc, quotes)) {
613 amount = loc - expdest;
614 STADJUST(amount, expdest);
618 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
619 for (q = startp; q < loc; q++)
629 for (loc = startp; loc < str - 1; loc++) {
630 if (patmatch(str, loc, quotes)) {
631 amount = loc - expdest;
632 STADJUST(amount, expdest);
635 if (quotes && *loc == CTLESC)
646 amount = ((str - 1) - (loc - startp)) - expdest;
647 STADJUST(amount, expdest);
648 while (loc != str - 1)
655 * Expand a variable, and return a pointer to the next character in the
660 evalvar(char *p, int flag)
674 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
676 varflags = (unsigned char)*p++;
677 subtype = varflags & VSTYPE;
682 p = strchr(p, '=') + 1;
683 again: /* jump here after setting a variable with ${var=text} */
684 if (varflags & VSLINENO) {
688 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
690 } else if (special) {
691 set = varisset(var, varflags & VSNUL);
694 val = bltinlookup(var, 1);
695 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
702 startloc = expdest - stackblock();
703 if (!set && uflag && *var != '@' && *var != '*') {
711 error("%.*s: parameter not set", (int)(p - var - 1),
715 if (set && subtype != VSPLUS) {
716 /* insert the value of the variable */
718 varvalue(var, varflags & VSQUOTE, subtype, flag);
719 if (subtype == VSLENGTH) {
720 varlenb = expdest - stackblock() - startloc;
723 val = stackblock() + startloc;
724 for (;val != expdest; val++)
725 if ((*val & 0xC0) == 0x80)
728 STADJUST(-varlenb, expdest);
731 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
734 if (subtype == VSLENGTH) {
737 (*val & 0xC0) != 0x80)
742 STPUTS_QUOTES(val, syntax, expdest);
744 STPUTS(val, expdest);
750 if (subtype == VSPLUS)
753 easy = ((varflags & VSQUOTE) == 0 ||
754 (*var == '@' && shellparam.nparam != 1));
759 expdest = cvtnum(varlen, expdest);
766 recordregion(startloc, expdest - stackblock(),
767 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
768 (*var == '@' || *var == '*')));
774 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
775 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
789 * Terminate the string and start recording the pattern
792 STPUTC('\0', expdest);
793 patloc = expdest - stackblock();
794 if (subevalvar(p, NULL, patloc, subtype,
795 startloc, varflags, quotes) == 0) {
796 int amount = (expdest - stackblock() - patloc) + 1;
797 STADJUST(-amount, expdest);
799 /* Remove any recorded regions beyond start of variable */
800 removerecordregions(startloc);
806 if (subevalvar(p, var, 0, subtype, startloc, varflags,
810 * Remove any recorded regions beyond
813 removerecordregions(startloc);
824 error("${%.*s%s}: Bad substitution", c, var,
825 (c > 0 && *p != CTLENDVAR) ? "..." : "");
830 p[-1] = '='; /* recover overwritten '=' */
832 if (subtype != VSNORMAL) { /* skip to end of alternative */
835 if ((c = *p++) == CTLESC)
837 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
839 argbackq = argbackq->next;
840 } else if (c == CTLVAR) {
841 if ((*p++ & VSTYPE) != VSNORMAL)
843 } else if (c == CTLENDVAR) {
855 * Test whether a specialized variable is set.
859 varisset(char *name, int nulok)
863 return backgndpidset();
864 else if (*name == '@' || *name == '*') {
865 if (*shellparam.p == NULL)
871 for (av = shellparam.p; *av; av++)
876 } else if (is_digit(*name)) {
878 int num = atoi(name);
880 if (num > shellparam.nparam)
886 ap = shellparam.p[num - 1];
888 if (nulok && (ap == NULL || *ap == '\0'))
895 strtodest(const char *p, int flag, int subtype, int quoted)
897 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
898 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
904 * Add the value of a specialized variable to the stack string.
908 varvalue(char *name, int quoted, int subtype, int flag)
924 num = shellparam.nparam;
927 num = backgndpidval();
929 expdest = cvtnum(num, expdest);
932 for (i = 0 ; i < NOPTS ; i++) {
934 STPUTC(optlist[i].letter, expdest);
938 if (flag & EXP_FULL && quoted) {
939 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
940 strtodest(p, flag, subtype, quoted);
942 STPUTC('\0', expdest);
952 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
953 strtodest(p, flag, subtype, quoted);
956 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
957 STPUTC(sep, expdest);
962 strtodest(p, flag, subtype, quoted);
965 if (is_digit(*name)) {
967 if (num > 0 && num <= shellparam.nparam) {
968 p = shellparam.p[num - 1];
969 strtodest(p, flag, subtype, quoted);
979 * Record the fact that we have to scan this region of the
980 * string for IFS characters.
984 recordregion(int start, int end, int inquotes)
986 struct ifsregion *ifsp;
988 if (ifslastp == NULL) {
991 if (ifslastp->endoff == start
992 && ifslastp->inquotes == inquotes) {
993 /* extend previous area */
994 ifslastp->endoff = end;
997 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
998 ifslastp->next = ifsp;
1001 ifslastp->next = NULL;
1002 ifslastp->begoff = start;
1003 ifslastp->endoff = end;
1004 ifslastp->inquotes = inquotes;
1010 * Break the argument string into pieces based upon IFS and add the
1011 * strings to the argument list. The regions of the string to be
1012 * searched for IFS characters have been stored by recordregion.
1013 * CTLESC characters are preserved but have little effect in this pass
1014 * other than escaping CTL* characters. In particular, they do not escape
1015 * IFS characters: that should be done with the ifsregion mechanism.
1016 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1017 * This pass treats them as a regular character, making the string non-empty.
1018 * Later, they are removed along with the other CTL* characters.
1021 ifsbreakup(char *string, struct arglist *arglist)
1023 struct ifsregion *ifsp;
1030 int had_param_ch = 0;
1034 if (ifslastp == NULL) {
1035 /* Return entire argument, IFS doesn't apply to any of it */
1036 sp = (struct strlist *)stalloc(sizeof *sp);
1038 *arglist->lastp = sp;
1039 arglist->lastp = &sp->next;
1043 ifs = ifsset() ? ifsval() : " \t\n";
1045 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1046 p = string + ifsp->begoff;
1047 while (p < string + ifsp->endoff) {
1051 if (ifsp->inquotes) {
1052 /* Only NULs (should be from "$@") end args */
1060 if (!strchr(ifs, *p)) {
1065 ifsspc = strchr(" \t\n", *p);
1067 /* Ignore IFS whitespace at start */
1068 if (q == start && ifsspc != NULL) {
1076 /* Save this argument... */
1078 sp = (struct strlist *)stalloc(sizeof *sp);
1080 *arglist->lastp = sp;
1081 arglist->lastp = &sp->next;
1084 if (ifsspc != NULL) {
1085 /* Ignore further trailing IFS whitespace */
1086 for (; p < string + ifsp->endoff; p++) {
1090 if (strchr(ifs, *p) == NULL) {
1094 if (strchr(" \t\n", *p) == NULL) {
1105 * Save anything left as an argument.
1106 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1107 * generating 2 arguments, the second of which is empty.
1108 * Some recent clarification of the Posix spec say that it
1109 * should only generate one....
1111 if (had_param_ch || *start != 0) {
1112 sp = (struct strlist *)stalloc(sizeof *sp);
1114 *arglist->lastp = sp;
1115 arglist->lastp = &sp->next;
1120 static char expdir[PATH_MAX];
1121 #define expdir_end (expdir + sizeof(expdir))
1124 * Perform pathname generation and remove control characters.
1125 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1126 * The results are stored in the list exparg.
1129 expandmeta(struct strlist *str, int flag __unused)
1132 struct strlist **savelastp;
1135 /* TODO - EXP_REDIR */
1141 for (;;) { /* fast check for meta chars */
1142 if ((c = *p++) == '\0')
1144 if (c == '*' || c == '?' || c == '[')
1147 savelastp = exparg.lastp;
1149 expmeta(expdir, str->text);
1151 if (exparg.lastp == savelastp) {
1156 *exparg.lastp = str;
1157 rmescapes(str->text);
1158 exparg.lastp = &str->next;
1160 *exparg.lastp = NULL;
1161 *savelastp = sp = expsort(*savelastp);
1162 while (sp->next != NULL)
1164 exparg.lastp = &sp->next;
1172 * Do metacharacter (i.e. *, ?, [...]) expansion.
1176 expmeta(char *enddir, char *name)
1192 for (p = name; esc = 0, *p; p += esc + 1) {
1193 if (*p == '*' || *p == '?')
1195 else if (*p == '[') {
1197 if (*q == '!' || *q == '^')
1200 while (*q == CTLQUOTEMARK)
1204 if (*q == '/' || *q == '\0')
1211 } else if (*p == '\0')
1213 else if (*p == CTLQUOTEMARK)
1218 if (p[esc] == '/') {
1221 start = p + esc + 1;
1225 if (metaflag == 0) { /* we've reached the end of the file name */
1226 if (enddir != expdir)
1228 for (p = name ; ; p++) {
1229 if (*p == CTLQUOTEMARK)
1236 if (enddir == expdir_end)
1239 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1244 if (start != name) {
1247 while (*p == CTLQUOTEMARK)
1252 if (enddir == expdir_end)
1256 if (enddir == expdir) {
1258 } else if (enddir == expdir + 1 && *expdir == '/') {
1264 if ((dirp = opendir(p)) == NULL)
1266 if (enddir != expdir)
1268 if (*endname == 0) {
1277 while (*p == CTLQUOTEMARK)
1283 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1284 if (dp->d_name[0] == '.' && ! matchdot)
1286 if (patmatch(start, dp->d_name, 0)) {
1287 if (enddir + dp->d_namlen + 1 > expdir_end)
1289 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1293 if (enddir + dp->d_namlen + 2 > expdir_end)
1295 enddir[dp->d_namlen] = '/';
1296 enddir[dp->d_namlen + 1] = '\0';
1297 expmeta(enddir + dp->d_namlen + 1, endname);
1303 endname[-esc - 1] = esc ? CTLESC : '/';
1308 * Add a file name to the list.
1312 addfname(char *name)
1317 p = stalloc(strlen(name) + 1);
1319 sp = (struct strlist *)stalloc(sizeof *sp);
1322 exparg.lastp = &sp->next;
1327 * Sort the results of file name expansion. It calculates the number of
1328 * strings to sort and then calls msort (short for merge sort) to do the
1332 static struct strlist *
1333 expsort(struct strlist *str)
1339 for (sp = str ; sp ; sp = sp->next)
1341 return msort(str, len);
1345 static struct strlist *
1346 msort(struct strlist *list, int len)
1348 struct strlist *p, *q = NULL;
1349 struct strlist **lpp;
1357 for (n = half ; --n >= 0 ; ) {
1361 q->next = NULL; /* terminate first half of list */
1362 q = msort(list, half); /* sort first half of list */
1363 p = msort(p, len - half); /* sort second half */
1366 if (strcmp(p->text, q->text) < 0) {
1369 if ((p = *lpp) == NULL) {
1376 if ((q = *lpp) == NULL) {
1388 get_wc(const char **p)
1393 chrlen = mbtowc(&c, *p, 4);
1396 else if (chrlen == -1)
1405 * See if a character matches a character class, starting at the first colon
1407 * If a valid character class is recognized, a pointer to the next character
1408 * after the final closing bracket is stored into *end, otherwise a null
1409 * pointer is stored into *end.
1412 match_charclass(const char *p, wchar_t chr, const char **end)
1415 const char *nameend;
1420 nameend = strstr(p, ":]");
1421 if (nameend == NULL || nameend - p >= sizeof(name) || nameend == p)
1423 memcpy(name, p, nameend - p);
1424 name[nameend - p] = '\0';
1426 cclass = wctype(name);
1427 /* An unknown class matches nothing but is valid nevertheless. */
1430 return iswctype(chr, cclass);
1435 * Returns true if the pattern matches the string.
1439 patmatch(const char *pattern, const char *string, int squoted)
1441 const char *p, *q, *end;
1452 if (squoted && *q == CTLESC)
1460 if (squoted && *q == CTLESC)
1465 wc = (unsigned char)*q++;
1471 while (c == CTLQUOTEMARK || c == '*')
1473 if (c != CTLESC && c != CTLQUOTEMARK &&
1474 c != '?' && c != '*' && c != '[') {
1476 if (squoted && *q == CTLESC &&
1481 if (squoted && *q == CTLESC)
1487 if (patmatch(p, q, squoted))
1489 if (squoted && *q == CTLESC)
1491 } while (*q++ != '\0');
1499 if (*endp == '!' || *endp == '^')
1502 while (*endp == CTLQUOTEMARK)
1505 goto dft; /* no matching ] */
1506 if (*endp == CTLESC)
1512 if (*p == '!' || *p == '^') {
1517 if (squoted && *q == CTLESC)
1522 chr = (unsigned char)*q++;
1527 if (c == CTLQUOTEMARK)
1529 if (c == '[' && *p == ':') {
1530 found |= match_charclass(p, chr, &end);
1536 if (localeisutf8 && c & 0x80) {
1539 if (wc == 0) /* bad utf-8 */
1542 wc = (unsigned char)c;
1543 if (*p == '-' && p[1] != ']') {
1545 while (*p == CTLQUOTEMARK)
1551 if (wc2 == 0) /* bad utf-8 */
1554 wc2 = (unsigned char)*p++;
1555 if ( collate_range_cmp(chr, wc) >= 0
1556 && collate_range_cmp(chr, wc2) <= 0
1563 } while ((c = *p++) != ']');
1564 if (found == invert)
1569 if (squoted && *q == CTLESC)
1585 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1589 rmescapes(char *str)
1594 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1600 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1614 * See if a pattern matches in a case statement.
1618 casematch(union node *pattern, const char *val)
1620 struct stackmark smark;
1624 setstackmark(&smark);
1625 argbackq = pattern->narg.backquote;
1626 STARTSTACKSTR(expdest);
1628 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1629 STPUTC('\0', expdest);
1630 p = grabstackstr(expdest);
1631 result = patmatch(p, val, 0);
1632 popstackmark(&smark);
1641 cvtnum(int num, char *buf)
1645 char *p = temp + 31;
1650 *--p = num % 10 + '0';
1651 } while ((num /= 10) != 0);
1661 * Do most of the work for wordexp(3).
1665 wordexpcmd(int argc, char **argv)
1670 out1fmt("%08x", argc - 1);
1671 for (i = 1, len = 0; i < argc; i++)
1672 len += strlen(argv[i]);
1673 out1fmt("%08x", (int)len);
1674 for (i = 1; i < argc; i++)
1675 outbin(argv[i], strlen(argv[i]) + 1, out1);