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
34 * @(#)expand.c 8.5 (Berkeley) 5/15/95
35 * $FreeBSD: head/bin/sh/expand.c 246288 2013-02-03 15:54:57Z jilles $
38 #include <sys/types.h>
54 * Routines to expand arguments to commands. We have to deal with
55 * backquotes, shell variables, and file metacharacters.
78 * Structure specifying which parts of the string should be searched
83 struct ifsregion *next; /* next region in list */
84 int begoff; /* offset of start of region */
85 int endoff; /* offset of end of region */
86 int inquotes; /* search for nul bytes only */
90 static char *expdest; /* output of current string */
91 static struct nodelist *argbackq; /* list of back quote expressions */
92 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
93 static struct ifsregion *ifslastp; /* last struct in list */
94 static struct arglist exparg; /* holds expanded arg list */
96 static void argstr(char *, int);
97 static char *exptilde(char *, int);
98 static void expbackq(union node *, int, int);
99 static int subevalvar(char *, char *, int, int, int, int, int);
100 static char *evalvar(char *, int);
101 static int varisset(char *, int);
102 static void varvalue(char *, int, int, int);
103 static void recordregion(int, int, int);
104 static void removerecordregions(int);
105 static void ifsbreakup(char *, struct arglist *);
106 static void expandmeta(struct strlist *, int);
107 static void expmeta(char *, char *);
108 static void addfname(char *);
109 static struct strlist *expsort(struct strlist *);
110 static struct strlist *msort(struct strlist *, int);
111 static int patmatch(const char *, const char *, int);
112 static char *cvtnum(int, char *);
113 static int collate_range_cmp(wchar_t, wchar_t);
116 collate_range_cmp(wchar_t c1, wchar_t c2)
118 static wchar_t s1[2], s2[2];
122 return (wcscoll(s1, s2));
126 stputs_quotes(const char *data, const char *syntax, char *p)
130 if (syntax[(int)*data] == CCTL)
136 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
139 * Perform expansions on an argument, placing the resulting list of arguments
140 * in arglist. Parameter expansion, command substitution and arithmetic
141 * expansion are always performed; additional expansions can be requested
143 * The result is left in the stack string.
144 * When arglist is NULL, perform here document expansion.
146 * Caution: this function uses global state and is not reentrant.
147 * However, a new invocation after an interrupted invocation is safe
148 * and will reset the global state for the new call.
151 expandarg(union node *arg, struct arglist *arglist, int flag)
156 argbackq = arg->narg.backquote;
157 STARTSTACKSTR(expdest);
158 ifsfirst.next = NULL;
160 argstr(arg->narg.text, flag);
161 if (arglist == NULL) {
162 STACKSTRNUL(expdest);
163 return; /* here document expanded */
165 STPUTC('\0', expdest);
166 p = grabstackstr(expdest);
167 exparg.lastp = &exparg.list;
171 if (flag & EXP_FULL) {
172 ifsbreakup(p, &exparg);
173 *exparg.lastp = NULL;
174 exparg.lastp = &exparg.list;
175 expandmeta(exparg.list, flag);
177 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
179 sp = (struct strlist *)stalloc(sizeof (struct strlist));
182 exparg.lastp = &sp->next;
184 while (ifsfirst.next != NULL) {
185 struct ifsregion *ifsp;
187 ifsp = ifsfirst.next->next;
188 ckfree(ifsfirst.next);
189 ifsfirst.next = ifsp;
192 *exparg.lastp = NULL;
194 *arglist->lastp = exparg.list;
195 arglist->lastp = exparg.lastp;
202 * Perform parameter expansion, command substitution and arithmetic
203 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
204 * Processing ends at a CTLENDVAR character as well as '\0'.
205 * This is used to expand word in ${var+word} etc.
206 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
207 * characters to allow for further processing.
208 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
211 argstr(char *p, int flag)
214 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
219 split_lit = flag & EXP_SPLIT_LIT;
220 lit_quoted = flag & EXP_LIT_QUOTED;
221 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
222 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
223 p = exptilde(p, flag);
225 CHECKSTRSPACE(2, expdest);
232 /* "$@" syntax adherence hack */
233 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
235 if ((flag & EXP_FULL) != 0)
246 if (split_lit && !lit_quoted)
247 recordregion(expdest - stackblock() -
249 expdest - stackblock(), 0);
252 p = evalvar(p, flag);
255 case CTLBACKQ|CTLQUOTE:
256 expbackq(argbackq->n, c & CTLQUOTE, flag);
257 argbackq = argbackq->next;
265 * sort of a hack - expand tildes in variable
266 * assignments (after the first '=' and after ':'s).
269 if (split_lit && !lit_quoted)
270 recordregion(expdest - stackblock() - 1,
271 expdest - stackblock(), 0);
272 if (flag & EXP_VARTILDE && *p == '~' &&
273 (c != '=' || firsteq)) {
276 p = exptilde(p, flag);
281 if (split_lit && !lit_quoted)
282 recordregion(expdest - stackblock() - 1,
283 expdest - stackblock(), 0);
290 * Perform tilde expansion, placing the result in the stack string and
291 * returning the next position in the input string to process.
294 exptilde(char *p, int flag)
299 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
301 while ((c = *p) != '\0') {
303 case CTLESC: /* This means CTL* are always considered quoted. */
306 case CTLBACKQ | CTLQUOTE:
312 if (flag & EXP_VARTILDE)
323 if (*(startp+1) == '\0') {
324 if ((home = lookupvar("HOME")) == NULL)
327 if ((pw = getpwnam(startp+1)) == NULL)
335 STPUTS_QUOTES(home, SQSYNTAX, expdest);
337 STPUTS(home, expdest);
346 removerecordregions(int endoff)
348 if (ifslastp == NULL)
351 if (ifsfirst.endoff > endoff) {
352 while (ifsfirst.next != NULL) {
353 struct ifsregion *ifsp;
355 ifsp = ifsfirst.next->next;
356 ckfree(ifsfirst.next);
357 ifsfirst.next = ifsp;
360 if (ifsfirst.begoff > endoff)
363 ifslastp = &ifsfirst;
364 ifsfirst.endoff = endoff;
369 ifslastp = &ifsfirst;
370 while (ifslastp->next && ifslastp->next->begoff < endoff)
371 ifslastp=ifslastp->next;
372 while (ifslastp->next != NULL) {
373 struct ifsregion *ifsp;
375 ifsp = ifslastp->next->next;
376 ckfree(ifslastp->next);
377 ifslastp->next = ifsp;
380 if (ifslastp->endoff > endoff)
381 ifslastp->endoff = endoff;
385 * Expand arithmetic expression. Backup to start of expression,
386 * evaluate, place result in (backed up) result, adjust string position.
394 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
398 * This routine is slightly over-complicated for
399 * efficiency. First we make sure there is
400 * enough space for the result, which may be bigger
401 * than the expression. Next we
402 * scan backwards looking for the start of arithmetic. If the
403 * next previous character is a CTLESC character, then we
404 * have to rescan starting from the beginning since CTLESC
405 * characters have to be processed left to right.
407 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
408 USTPUTC('\0', expdest);
409 start = stackblock();
411 while (p >= start && *p != CTLARI)
413 if (p < start || *p != CTLARI)
414 error("missing CTLARI (shouldn't happen)");
415 if (p > start && *(p - 1) == CTLESC)
416 for (p = start; *p != CTLARI; p++)
425 removerecordregions(begoff);
428 q = grabstackstr(expdest);
430 ungrabstackstr(q, expdest);
431 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
435 recordregion(begoff, p - 1 - start, 0);
436 result = expdest - p + 1;
437 STADJUST(-result, expdest);
442 * Perform command substitution.
445 expbackq(union node *cmd, int quoted, int flag)
451 char *dest = expdest;
452 struct ifsregion saveifs, *savelastp;
453 struct nodelist *saveargbackq;
455 int startloc = dest - stackblock();
456 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
457 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
462 savelastp = ifslastp;
463 saveargbackq = argbackq;
464 p = grabstackstr(dest);
465 evalbackcmd(cmd, &in);
466 ungrabstackstr(p, dest);
468 ifslastp = savelastp;
469 argbackq = saveargbackq;
474 /* Don't copy trailing newlines */
476 if (--in.nleft < 0) {
479 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
480 TRACE(("expbackq: read returns %d\n", i));
491 CHECKSTRSPACE(nnl + 2, dest);
496 if (quotes && syntax[(int)lastc] == CCTL)
497 USTPUTC(CTLESC, dest);
498 USTPUTC(lastc, dest);
508 exitstatus = waitforjob(in.jp, NULL);
510 recordregion(startloc, dest - stackblock(), 0);
511 TRACE(("expbackq: size=%td: \"%.*s\"\n",
512 ((dest - stackblock()) - startloc),
513 (int)((dest - stackblock()) - startloc),
514 stackblock() + startloc));
522 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
523 int varflags, int quotes)
529 struct nodelist *saveargbackq = argbackq;
532 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
533 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
534 EXP_CASE : 0) | EXP_TILDE);
535 STACKSTRNUL(expdest);
536 argbackq = saveargbackq;
537 startp = stackblock() + startloc;
539 str = stackblock() + strloc;
543 setvar(str, startp, 0);
544 amount = startp - expdest;
545 STADJUST(amount, expdest);
550 if (*p != CTLENDVAR) {
551 outfmt(out2, "%s\n", startp);
554 error("%.*s: parameter %snot set", (int)(p - str - 1),
555 str, (varflags & VSNUL) ? "null or "
560 for (loc = startp; loc < str; loc++) {
563 if (patmatch(str, startp, quotes)) {
568 if (quotes && *loc == CTLESC)
574 for (loc = str - 1; loc >= startp;) {
577 if (patmatch(str, startp, quotes)) {
583 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
584 for (q = startp; q < loc; q++)
594 for (loc = str - 1; loc >= startp;) {
595 if (patmatch(str, loc, quotes)) {
596 amount = loc - expdest;
597 STADJUST(amount, expdest);
601 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
602 for (q = startp; q < loc; q++)
612 for (loc = startp; loc < str - 1; loc++) {
613 if (patmatch(str, loc, quotes)) {
614 amount = loc - expdest;
615 STADJUST(amount, expdest);
618 if (quotes && *loc == CTLESC)
629 amount = ((str - 1) - (loc - startp)) - expdest;
630 STADJUST(amount, expdest);
631 while (loc != str - 1)
638 * Expand a variable, and return a pointer to the next character in the
643 evalvar(char *p, int flag)
657 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
659 varflags = (unsigned char)*p++;
660 subtype = varflags & VSTYPE;
665 p = strchr(p, '=') + 1;
666 again: /* jump here after setting a variable with ${var=text} */
667 if (varflags & VSLINENO) {
671 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
673 } else if (special) {
674 set = varisset(var, varflags & VSNUL);
677 val = bltinlookup(var, 1);
678 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
685 startloc = expdest - stackblock();
686 if (!set && uflag && *var != '@' && *var != '*') {
694 error("%.*s: parameter not set", (int)(p - var - 1),
698 if (set && subtype != VSPLUS) {
699 /* insert the value of the variable */
701 varvalue(var, varflags & VSQUOTE, subtype, flag);
702 if (subtype == VSLENGTH) {
703 varlenb = expdest - stackblock() - startloc;
706 val = stackblock() + startloc;
707 for (;val != expdest; val++)
708 if ((*val & 0xC0) == 0x80)
711 STADJUST(-varlenb, expdest);
714 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
717 if (subtype == VSLENGTH) {
720 (*val & 0xC0) != 0x80)
725 STPUTS_QUOTES(val, syntax, expdest);
727 STPUTS(val, expdest);
733 if (subtype == VSPLUS)
736 easy = ((varflags & VSQUOTE) == 0 ||
737 (*var == '@' && shellparam.nparam != 1));
742 expdest = cvtnum(varlen, expdest);
749 recordregion(startloc, expdest - stackblock(),
750 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
751 (*var == '@' || *var == '*')));
757 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
758 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
772 * Terminate the string and start recording the pattern
775 STPUTC('\0', expdest);
776 patloc = expdest - stackblock();
777 if (subevalvar(p, NULL, patloc, subtype,
778 startloc, varflags, quotes) == 0) {
779 int amount = (expdest - stackblock() - patloc) + 1;
780 STADJUST(-amount, expdest);
782 /* Remove any recorded regions beyond start of variable */
783 removerecordregions(startloc);
789 if (subevalvar(p, var, 0, subtype, startloc, varflags,
793 * Remove any recorded regions beyond
796 removerecordregions(startloc);
807 error("${%.*s%s}: Bad substitution", c, var,
808 (c > 0 && *p != CTLENDVAR) ? "..." : "");
813 p[-1] = '='; /* recover overwritten '=' */
815 if (subtype != VSNORMAL) { /* skip to end of alternative */
818 if ((c = *p++) == CTLESC)
820 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
822 argbackq = argbackq->next;
823 } else if (c == CTLVAR) {
824 if ((*p++ & VSTYPE) != VSNORMAL)
826 } else if (c == CTLENDVAR) {
838 * Test whether a specialized variable is set.
842 varisset(char *name, int nulok)
846 return backgndpidset();
847 else if (*name == '@' || *name == '*') {
848 if (*shellparam.p == NULL)
854 for (av = shellparam.p; *av; av++)
859 } else if (is_digit(*name)) {
861 int num = atoi(name);
863 if (num > shellparam.nparam)
869 ap = shellparam.p[num - 1];
871 if (nulok && (ap == NULL || *ap == '\0'))
878 strtodest(const char *p, int flag, int subtype, int quoted)
880 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
881 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
887 * Add the value of a specialized variable to the stack string.
891 varvalue(char *name, int quoted, int subtype, int flag)
907 num = shellparam.nparam;
910 num = backgndpidval();
912 expdest = cvtnum(num, expdest);
915 for (i = 0 ; i < NOPTS ; i++) {
917 STPUTC(optlist[i].letter, expdest);
921 if (flag & EXP_FULL && quoted) {
922 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
923 strtodest(p, flag, subtype, quoted);
925 STPUTC('\0', expdest);
935 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
936 strtodest(p, flag, subtype, quoted);
939 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
940 STPUTC(sep, expdest);
945 strtodest(p, flag, subtype, quoted);
948 if (is_digit(*name)) {
950 if (num > 0 && num <= shellparam.nparam) {
951 p = shellparam.p[num - 1];
952 strtodest(p, flag, subtype, quoted);
962 * Record the fact that we have to scan this region of the
963 * string for IFS characters.
967 recordregion(int start, int end, int inquotes)
969 struct ifsregion *ifsp;
971 if (ifslastp == NULL) {
974 if (ifslastp->endoff == start
975 && ifslastp->inquotes == inquotes) {
976 /* extend previous area */
977 ifslastp->endoff = end;
980 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
981 ifslastp->next = ifsp;
984 ifslastp->next = NULL;
985 ifslastp->begoff = start;
986 ifslastp->endoff = end;
987 ifslastp->inquotes = inquotes;
993 * Break the argument string into pieces based upon IFS and add the
994 * strings to the argument list. The regions of the string to be
995 * searched for IFS characters have been stored by recordregion.
996 * CTLESC characters are preserved but have little effect in this pass
997 * other than escaping CTL* characters. In particular, they do not escape
998 * IFS characters: that should be done with the ifsregion mechanism.
999 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1000 * This pass treats them as a regular character, making the string non-empty.
1001 * Later, they are removed along with the other CTL* characters.
1004 ifsbreakup(char *string, struct arglist *arglist)
1006 struct ifsregion *ifsp;
1013 int had_param_ch = 0;
1017 if (ifslastp == NULL) {
1018 /* Return entire argument, IFS doesn't apply to any of it */
1019 sp = (struct strlist *)stalloc(sizeof *sp);
1021 *arglist->lastp = sp;
1022 arglist->lastp = &sp->next;
1026 ifs = ifsset() ? ifsval() : " \t\n";
1028 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1029 p = string + ifsp->begoff;
1030 while (p < string + ifsp->endoff) {
1034 if (ifsp->inquotes) {
1035 /* Only NULs (should be from "$@") end args */
1043 if (!strchr(ifs, *p)) {
1048 ifsspc = strchr(" \t\n", *p);
1050 /* Ignore IFS whitespace at start */
1051 if (q == start && ifsspc != NULL) {
1059 /* Save this argument... */
1061 sp = (struct strlist *)stalloc(sizeof *sp);
1063 *arglist->lastp = sp;
1064 arglist->lastp = &sp->next;
1067 if (ifsspc != NULL) {
1068 /* Ignore further trailing IFS whitespace */
1069 for (; p < string + ifsp->endoff; p++) {
1073 if (strchr(ifs, *p) == NULL) {
1077 if (strchr(" \t\n", *p) == NULL) {
1088 * Save anything left as an argument.
1089 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1090 * generating 2 arguments, the second of which is empty.
1091 * Some recent clarification of the Posix spec say that it
1092 * should only generate one....
1094 if (had_param_ch || *start != 0) {
1095 sp = (struct strlist *)stalloc(sizeof *sp);
1097 *arglist->lastp = sp;
1098 arglist->lastp = &sp->next;
1103 static char expdir[PATH_MAX];
1104 #define expdir_end (expdir + sizeof(expdir))
1107 * Perform pathname generation and remove control characters.
1108 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1109 * The results are stored in the list exparg.
1112 expandmeta(struct strlist *str, int flag __unused)
1115 struct strlist **savelastp;
1118 /* TODO - EXP_REDIR */
1124 for (;;) { /* fast check for meta chars */
1125 if ((c = *p++) == '\0')
1127 if (c == '*' || c == '?' || c == '[')
1130 savelastp = exparg.lastp;
1132 expmeta(expdir, str->text);
1134 if (exparg.lastp == savelastp) {
1139 *exparg.lastp = str;
1140 rmescapes(str->text);
1141 exparg.lastp = &str->next;
1143 *exparg.lastp = NULL;
1144 *savelastp = sp = expsort(*savelastp);
1145 while (sp->next != NULL)
1147 exparg.lastp = &sp->next;
1155 * Do metacharacter (i.e. *, ?, [...]) expansion.
1159 expmeta(char *enddir, char *name)
1176 for (p = name; esc = 0, *p; p += esc + 1) {
1177 if (*p == '*' || *p == '?')
1179 else if (*p == '[') {
1181 if (*q == '!' || *q == '^')
1184 while (*q == CTLQUOTEMARK)
1188 if (*q == '/' || *q == '\0')
1195 } else if (*p == '\0')
1197 else if (*p == CTLQUOTEMARK)
1202 if (p[esc] == '/') {
1205 start = p + esc + 1;
1209 if (metaflag == 0) { /* we've reached the end of the file name */
1210 if (enddir != expdir)
1212 for (p = name ; ; p++) {
1213 if (*p == CTLQUOTEMARK)
1220 if (enddir == expdir_end)
1223 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1228 if (start != name) {
1231 while (*p == CTLQUOTEMARK)
1236 if (enddir == expdir_end)
1240 if (enddir == expdir) {
1241 p = __DECONST(char *, ".");
1242 } else if (enddir == expdir + 1 && *expdir == '/') {
1243 p = __DECONST(char *, "/");
1248 if ((dirp = opendir(p)) == NULL)
1250 if (enddir != expdir)
1252 if (*endname == 0) {
1261 while (*p == CTLQUOTEMARK)
1267 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1268 if (dp->d_name[0] == '.' && ! matchdot)
1270 if (patmatch(start, dp->d_name, 0)) {
1271 namlen = dp->d_namlen;
1272 if (enddir + namlen + 1 > expdir_end)
1274 memcpy(enddir, dp->d_name, namlen + 1);
1278 if (dp->d_type != DT_UNKNOWN &&
1279 dp->d_type != DT_DIR &&
1280 dp->d_type != DT_LNK)
1282 if (enddir + namlen + 2 > expdir_end)
1284 enddir[namlen] = '/';
1285 enddir[namlen + 1] = '\0';
1286 expmeta(enddir + namlen + 1, endname);
1292 endname[-esc - 1] = esc ? CTLESC : '/';
1297 * Add a file name to the list.
1301 addfname(char *name)
1306 p = stalloc(strlen(name) + 1);
1308 sp = (struct strlist *)stalloc(sizeof *sp);
1311 exparg.lastp = &sp->next;
1316 * Sort the results of file name expansion. It calculates the number of
1317 * strings to sort and then calls msort (short for merge sort) to do the
1321 static struct strlist *
1322 expsort(struct strlist *str)
1328 for (sp = str ; sp ; sp = sp->next)
1330 return msort(str, len);
1334 static struct strlist *
1335 msort(struct strlist *list, int len)
1337 struct strlist *p, *q = NULL;
1338 struct strlist **lpp;
1346 for (n = half ; --n >= 0 ; ) {
1350 q->next = NULL; /* terminate first half of list */
1351 q = msort(list, half); /* sort first half of list */
1352 p = msort(p, len - half); /* sort second half */
1355 if (strcmp(p->text, q->text) < 0) {
1358 if ((p = *lpp) == NULL) {
1365 if ((q = *lpp) == NULL) {
1377 get_wc(const char **p)
1382 chrlen = mbtowc(&c, *p, 4);
1385 else if (chrlen == -1)
1394 * See if a character matches a character class, starting at the first colon
1396 * If a valid character class is recognized, a pointer to the next character
1397 * after the final closing bracket is stored into *end, otherwise a null
1398 * pointer is stored into *end.
1401 match_charclass(const char *p, wchar_t chr, const char **end)
1404 const char *nameend;
1409 nameend = strstr(p, ":]");
1410 if (nameend == NULL || nameend - p >= (int)sizeof(name) || nameend == p)
1412 memcpy(name, p, nameend - p);
1413 name[nameend - p] = '\0';
1415 cclass = wctype(name);
1416 /* An unknown class matches nothing but is valid nevertheless. */
1419 return iswctype(chr, cclass);
1424 * Returns true if the pattern matches the string.
1428 patmatch(const char *pattern, const char *string, int squoted)
1430 const char *p, *q, *end;
1431 const char *bt_p, *bt_q;
1446 if (squoted && *q == CTLESC)
1454 if (squoted && *q == CTLESC)
1461 * A '?' does not match invalid UTF-8 but a
1462 * '*' does, so backtrack.
1467 wc = (unsigned char)*q++;
1471 while (c == CTLQUOTEMARK || c == '*')
1474 * If the pattern ends here, we know the string
1475 * matches without needing to look at the rest of it.
1480 * First try the shortest match for the '*' that
1481 * could work. We can forget any earlier '*' since
1482 * there is no way having it match more characters
1483 * can help us, given that we are already here.
1494 if (*endp == '!' || *endp == '^')
1497 while (*endp == CTLQUOTEMARK)
1500 goto dft; /* no matching ] */
1501 if (*endp == CTLESC)
1507 if (*p == '!' || *p == '^') {
1512 if (squoted && *q == CTLESC)
1521 chr = (unsigned char)*q++;
1524 if (c == CTLQUOTEMARK)
1526 if (c == '[' && *p == ':') {
1527 found |= match_charclass(p, chr, &end);
1533 if (localeisutf8 && c & 0x80) {
1536 if (wc == 0) /* bad utf-8 */
1539 wc = (unsigned char)c;
1540 if (*p == '-' && p[1] != ']') {
1542 while (*p == CTLQUOTEMARK)
1548 if (wc2 == 0) /* bad utf-8 */
1551 wc2 = (unsigned char)*p++;
1552 if ( collate_range_cmp(chr, wc) >= 0
1553 && collate_range_cmp(chr, wc2) <= 0
1560 } while ((c = *p++) != ']');
1561 if (found == invert)
1566 if (squoted && *q == CTLESC)
1574 * If we have a mismatch (other than hitting the end
1575 * of the string), go back to the last '*' seen and
1576 * have it match one additional character.
1580 if (squoted && *bt_q == CTLESC)
1595 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1599 rmescapes(char *str)
1604 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1610 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1624 * See if a pattern matches in a case statement.
1628 casematch(union node *pattern, const char *val)
1630 struct stackmark smark;
1634 setstackmark(&smark);
1635 argbackq = pattern->narg.backquote;
1636 STARTSTACKSTR(expdest);
1638 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1639 STPUTC('\0', expdest);
1640 p = grabstackstr(expdest);
1641 result = patmatch(p, val, 0);
1642 popstackmark(&smark);
1651 cvtnum(int num, char *buf)
1655 char *p = temp + 31;
1660 *--p = num % 10 + '0';
1661 } while ((num /= 10) != 0);
1671 * Do most of the work for wordexp(3).
1675 wordexpcmd(int argc, char **argv)
1680 out1fmt("%08x", argc - 1);
1681 for (i = 1, len = 0; i < argc; i++)
1682 len += strlen(argv[i]);
1683 out1fmt("%08x", (int)len);
1684 for (i = 1; i < argc; i++)
1685 outbin(argv[i], strlen(argv[i]) + 1, out1);