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 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)expand.c 8.5 (Berkeley) 5/15/95
39 * $FreeBSD: head/bin/sh/expand.c 246288 2013-02-03 15:54:57Z jilles $
42 #include <sys/types.h>
58 * Routines to expand arguments to commands. We have to deal with
59 * backquotes, shell variables, and file metacharacters.
82 * Structure specifying which parts of the string should be searched
87 struct ifsregion *next; /* next region in list */
88 int begoff; /* offset of start of region */
89 int endoff; /* offset of end of region */
90 int inquotes; /* search for nul bytes only */
94 static char *expdest; /* output of current string */
95 static struct nodelist *argbackq; /* list of back quote expressions */
96 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
97 static struct ifsregion *ifslastp; /* last struct in list */
98 static struct arglist exparg; /* holds expanded arg list */
100 static void argstr(char *, int);
101 static char *exptilde(char *, int);
102 static void expbackq(union node *, int, int);
103 static int subevalvar(char *, char *, int, int, int, int, int);
104 static char *evalvar(char *, int);
105 static int varisset(char *, int);
106 static void varvalue(char *, int, int, int);
107 static void recordregion(int, int, int);
108 static void removerecordregions(int);
109 static void ifsbreakup(char *, struct arglist *);
110 static void expandmeta(struct strlist *, int);
111 static void expmeta(char *, char *);
112 static void addfname(char *);
113 static struct strlist *expsort(struct strlist *);
114 static struct strlist *msort(struct strlist *, int);
115 static int patmatch(const char *, const char *, 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 stputs_quotes(const char *data, const char *syntax, char *p)
134 if (syntax[(int)*data] == CCTL)
140 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
143 * Perform expansions on an argument, placing the resulting list of arguments
144 * in arglist. Parameter expansion, command substitution and arithmetic
145 * expansion are always performed; additional expansions can be requested
147 * The result is left in the stack string.
148 * When arglist is NULL, perform here document expansion.
150 * Caution: this function uses global state and is not reentrant.
151 * However, a new invocation after an interrupted invocation is safe
152 * and will reset the global state for the new call.
155 expandarg(union node *arg, struct arglist *arglist, int flag)
160 argbackq = arg->narg.backquote;
161 STARTSTACKSTR(expdest);
162 ifsfirst.next = NULL;
164 argstr(arg->narg.text, flag);
165 if (arglist == NULL) {
166 STACKSTRNUL(expdest);
167 return; /* here document expanded */
169 STPUTC('\0', expdest);
170 p = grabstackstr(expdest);
171 exparg.lastp = &exparg.list;
175 if (flag & EXP_FULL) {
176 ifsbreakup(p, &exparg);
177 *exparg.lastp = NULL;
178 exparg.lastp = &exparg.list;
179 expandmeta(exparg.list, flag);
181 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
183 sp = (struct strlist *)stalloc(sizeof (struct strlist));
186 exparg.lastp = &sp->next;
188 while (ifsfirst.next != NULL) {
189 struct ifsregion *ifsp;
191 ifsp = ifsfirst.next->next;
192 ckfree(ifsfirst.next);
193 ifsfirst.next = ifsp;
196 *exparg.lastp = NULL;
198 *arglist->lastp = exparg.list;
199 arglist->lastp = exparg.lastp;
206 * Perform parameter expansion, command substitution and arithmetic
207 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
208 * Processing ends at a CTLENDVAR character as well as '\0'.
209 * This is used to expand word in ${var+word} etc.
210 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
211 * characters to allow for further processing.
212 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
215 argstr(char *p, int flag)
218 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
223 split_lit = flag & EXP_SPLIT_LIT;
224 lit_quoted = flag & EXP_LIT_QUOTED;
225 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
226 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
227 p = exptilde(p, flag);
229 CHECKSTRSPACE(2, expdest);
236 /* "$@" syntax adherence hack */
237 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
239 if ((flag & EXP_FULL) != 0)
250 if (split_lit && !lit_quoted)
251 recordregion(expdest - stackblock() -
253 expdest - stackblock(), 0);
256 p = evalvar(p, flag);
259 case CTLBACKQ|CTLQUOTE:
260 expbackq(argbackq->n, c & CTLQUOTE, flag);
261 argbackq = argbackq->next;
269 * sort of a hack - expand tildes in variable
270 * assignments (after the first '=' and after ':'s).
273 if (split_lit && !lit_quoted)
274 recordregion(expdest - stackblock() - 1,
275 expdest - stackblock(), 0);
276 if (flag & EXP_VARTILDE && *p == '~' &&
277 (c != '=' || firsteq)) {
280 p = exptilde(p, flag);
285 if (split_lit && !lit_quoted)
286 recordregion(expdest - stackblock() - 1,
287 expdest - stackblock(), 0);
294 * Perform tilde expansion, placing the result in the stack string and
295 * returning the next position in the input string to process.
298 exptilde(char *p, int flag)
303 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
305 while ((c = *p) != '\0') {
307 case CTLESC: /* This means CTL* are always considered quoted. */
310 case CTLBACKQ | CTLQUOTE:
316 if (flag & EXP_VARTILDE)
327 if (*(startp+1) == '\0') {
328 if ((home = lookupvar("HOME")) == NULL)
331 if ((pw = getpwnam(startp+1)) == NULL)
339 STPUTS_QUOTES(home, SQSYNTAX, expdest);
341 STPUTS(home, expdest);
350 removerecordregions(int endoff)
352 if (ifslastp == NULL)
355 if (ifsfirst.endoff > endoff) {
356 while (ifsfirst.next != NULL) {
357 struct ifsregion *ifsp;
359 ifsp = ifsfirst.next->next;
360 ckfree(ifsfirst.next);
361 ifsfirst.next = ifsp;
364 if (ifsfirst.begoff > endoff)
367 ifslastp = &ifsfirst;
368 ifsfirst.endoff = endoff;
373 ifslastp = &ifsfirst;
374 while (ifslastp->next && ifslastp->next->begoff < endoff)
375 ifslastp=ifslastp->next;
376 while (ifslastp->next != NULL) {
377 struct ifsregion *ifsp;
379 ifsp = ifslastp->next->next;
380 ckfree(ifslastp->next);
381 ifslastp->next = ifsp;
384 if (ifslastp->endoff > endoff)
385 ifslastp->endoff = endoff;
389 * Expand arithmetic expression. Backup to start of expression,
390 * evaluate, place result in (backed up) result, adjust string position.
398 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
402 * This routine is slightly over-complicated for
403 * efficiency. First we make sure there is
404 * enough space for the result, which may be bigger
405 * than the expression. Next we
406 * scan backwards looking for the start of arithmetic. If the
407 * next previous character is a CTLESC character, then we
408 * have to rescan starting from the beginning since CTLESC
409 * characters have to be processed left to right.
411 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
412 USTPUTC('\0', expdest);
413 start = stackblock();
415 while (p >= start && *p != CTLARI)
417 if (p < start || *p != CTLARI)
418 error("missing CTLARI (shouldn't happen)");
419 if (p > start && *(p - 1) == CTLESC)
420 for (p = start; *p != CTLARI; p++)
429 removerecordregions(begoff);
432 q = grabstackstr(expdest);
434 ungrabstackstr(q, expdest);
435 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
439 recordregion(begoff, p - 1 - start, 0);
440 result = expdest - p + 1;
441 STADJUST(-result, expdest);
446 * Perform command substitution.
449 expbackq(union node *cmd, int quoted, int flag)
455 char *dest = expdest;
456 struct ifsregion saveifs, *savelastp;
457 struct nodelist *saveargbackq;
459 int startloc = dest - stackblock();
460 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
461 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
466 savelastp = ifslastp;
467 saveargbackq = argbackq;
468 p = grabstackstr(dest);
469 evalbackcmd(cmd, &in);
470 ungrabstackstr(p, dest);
472 ifslastp = savelastp;
473 argbackq = saveargbackq;
478 /* Don't copy trailing newlines */
480 if (--in.nleft < 0) {
483 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
484 TRACE(("expbackq: read returns %d\n", i));
495 CHECKSTRSPACE(nnl + 2, dest);
500 if (quotes && syntax[(int)lastc] == CCTL)
501 USTPUTC(CTLESC, dest);
502 USTPUTC(lastc, dest);
512 exitstatus = waitforjob(in.jp, NULL);
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));
526 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
527 int varflags, int quotes)
533 struct nodelist *saveargbackq = argbackq;
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;
543 str = stackblock() + strloc;
547 setvar(str, startp, 0);
548 amount = startp - expdest;
549 STADJUST(amount, expdest);
554 if (*p != CTLENDVAR) {
555 outfmt(out2, "%s\n", startp);
558 error("%.*s: parameter %snot set", (int)(p - str - 1),
559 str, (varflags & VSNUL) ? "null or "
564 for (loc = startp; loc < str; loc++) {
567 if (patmatch(str, startp, quotes)) {
572 if (quotes && *loc == CTLESC)
578 for (loc = str - 1; loc >= startp;) {
581 if (patmatch(str, startp, quotes)) {
587 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
588 for (q = startp; q < loc; q++)
598 for (loc = str - 1; loc >= startp;) {
599 if (patmatch(str, loc, quotes)) {
600 amount = loc - expdest;
601 STADJUST(amount, expdest);
605 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
606 for (q = startp; q < loc; q++)
616 for (loc = startp; loc < str - 1; loc++) {
617 if (patmatch(str, loc, quotes)) {
618 amount = loc - expdest;
619 STADJUST(amount, expdest);
622 if (quotes && *loc == CTLESC)
633 amount = ((str - 1) - (loc - startp)) - expdest;
634 STADJUST(amount, expdest);
635 while (loc != str - 1)
642 * Expand a variable, and return a pointer to the next character in the
647 evalvar(char *p, int flag)
661 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
663 varflags = (unsigned char)*p++;
664 subtype = varflags & VSTYPE;
669 p = strchr(p, '=') + 1;
670 again: /* jump here after setting a variable with ${var=text} */
671 if (varflags & VSLINENO) {
675 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
677 } else if (special) {
678 set = varisset(var, varflags & VSNUL);
681 val = bltinlookup(var, 1);
682 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
689 startloc = expdest - stackblock();
690 if (!set && uflag && *var != '@' && *var != '*') {
698 error("%.*s: parameter not set", (int)(p - var - 1),
702 if (set && subtype != VSPLUS) {
703 /* insert the value of the variable */
705 varvalue(var, varflags & VSQUOTE, subtype, flag);
706 if (subtype == VSLENGTH) {
707 varlenb = expdest - stackblock() - startloc;
710 val = stackblock() + startloc;
711 for (;val != expdest; val++)
712 if ((*val & 0xC0) == 0x80)
715 STADJUST(-varlenb, expdest);
718 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
721 if (subtype == VSLENGTH) {
724 (*val & 0xC0) != 0x80)
729 STPUTS_QUOTES(val, syntax, expdest);
731 STPUTS(val, expdest);
737 if (subtype == VSPLUS)
740 easy = ((varflags & VSQUOTE) == 0 ||
741 (*var == '@' && shellparam.nparam != 1));
746 expdest = cvtnum(varlen, expdest);
753 recordregion(startloc, expdest - stackblock(),
754 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
755 (*var == '@' || *var == '*')));
761 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
762 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
776 * Terminate the string and start recording the pattern
779 STPUTC('\0', expdest);
780 patloc = expdest - stackblock();
781 if (subevalvar(p, NULL, patloc, subtype,
782 startloc, varflags, quotes) == 0) {
783 int amount = (expdest - stackblock() - patloc) + 1;
784 STADJUST(-amount, expdest);
786 /* Remove any recorded regions beyond start of variable */
787 removerecordregions(startloc);
793 if (subevalvar(p, var, 0, subtype, startloc, varflags,
797 * Remove any recorded regions beyond
800 removerecordregions(startloc);
811 error("${%.*s%s}: Bad substitution", c, var,
812 (c > 0 && *p != CTLENDVAR) ? "..." : "");
817 p[-1] = '='; /* recover overwritten '=' */
819 if (subtype != VSNORMAL) { /* skip to end of alternative */
822 if ((c = *p++) == CTLESC)
824 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
826 argbackq = argbackq->next;
827 } else if (c == CTLVAR) {
828 if ((*p++ & VSTYPE) != VSNORMAL)
830 } else if (c == CTLENDVAR) {
842 * Test whether a specialized variable is set.
846 varisset(char *name, int nulok)
850 return backgndpidset();
851 else if (*name == '@' || *name == '*') {
852 if (*shellparam.p == NULL)
858 for (av = shellparam.p; *av; av++)
863 } else if (is_digit(*name)) {
865 int num = atoi(name);
867 if (num > shellparam.nparam)
873 ap = shellparam.p[num - 1];
875 if (nulok && (ap == NULL || *ap == '\0'))
882 strtodest(const char *p, int flag, int subtype, int quoted)
884 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
885 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
891 * Add the value of a specialized variable to the stack string.
895 varvalue(char *name, int quoted, int subtype, int flag)
911 num = shellparam.nparam;
914 num = backgndpidval();
916 expdest = cvtnum(num, expdest);
919 for (i = 0 ; i < NOPTS ; i++) {
921 STPUTC(optlist[i].letter, expdest);
925 if (flag & EXP_FULL && quoted) {
926 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
927 strtodest(p, flag, subtype, quoted);
929 STPUTC('\0', expdest);
939 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
940 strtodest(p, flag, subtype, quoted);
943 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
944 STPUTC(sep, expdest);
949 strtodest(p, flag, subtype, quoted);
952 if (is_digit(*name)) {
954 if (num > 0 && num <= shellparam.nparam) {
955 p = shellparam.p[num - 1];
956 strtodest(p, flag, subtype, quoted);
966 * Record the fact that we have to scan this region of the
967 * string for IFS characters.
971 recordregion(int start, int end, int inquotes)
973 struct ifsregion *ifsp;
975 if (ifslastp == NULL) {
978 if (ifslastp->endoff == start
979 && ifslastp->inquotes == inquotes) {
980 /* extend previous area */
981 ifslastp->endoff = end;
984 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
985 ifslastp->next = ifsp;
988 ifslastp->next = NULL;
989 ifslastp->begoff = start;
990 ifslastp->endoff = end;
991 ifslastp->inquotes = inquotes;
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.
1008 ifsbreakup(char *string, struct arglist *arglist)
1010 struct ifsregion *ifsp;
1017 int had_param_ch = 0;
1021 if (ifslastp == NULL) {
1022 /* Return entire argument, IFS doesn't apply to any of it */
1023 sp = (struct strlist *)stalloc(sizeof *sp);
1025 *arglist->lastp = sp;
1026 arglist->lastp = &sp->next;
1030 ifs = ifsset() ? ifsval() : " \t\n";
1032 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1033 p = string + ifsp->begoff;
1034 while (p < string + ifsp->endoff) {
1038 if (ifsp->inquotes) {
1039 /* Only NULs (should be from "$@") end args */
1047 if (!strchr(ifs, *p)) {
1052 ifsspc = strchr(" \t\n", *p);
1054 /* Ignore IFS whitespace at start */
1055 if (q == start && ifsspc != NULL) {
1063 /* Save this argument... */
1065 sp = (struct strlist *)stalloc(sizeof *sp);
1067 *arglist->lastp = sp;
1068 arglist->lastp = &sp->next;
1071 if (ifsspc != NULL) {
1072 /* Ignore further trailing IFS whitespace */
1073 for (; p < string + ifsp->endoff; p++) {
1077 if (strchr(ifs, *p) == NULL) {
1081 if (strchr(" \t\n", *p) == NULL) {
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....
1098 if (had_param_ch || *start != 0) {
1099 sp = (struct strlist *)stalloc(sizeof *sp);
1101 *arglist->lastp = sp;
1102 arglist->lastp = &sp->next;
1107 static char expdir[PATH_MAX];
1108 #define expdir_end (expdir + sizeof(expdir))
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.
1116 expandmeta(struct strlist *str, int flag __unused)
1119 struct strlist **savelastp;
1122 /* TODO - EXP_REDIR */
1128 for (;;) { /* fast check for meta chars */
1129 if ((c = *p++) == '\0')
1131 if (c == '*' || c == '?' || c == '[')
1134 savelastp = exparg.lastp;
1136 expmeta(expdir, str->text);
1138 if (exparg.lastp == savelastp) {
1143 *exparg.lastp = str;
1144 rmescapes(str->text);
1145 exparg.lastp = &str->next;
1147 *exparg.lastp = NULL;
1148 *savelastp = sp = expsort(*savelastp);
1149 while (sp->next != NULL)
1151 exparg.lastp = &sp->next;
1159 * Do metacharacter (i.e. *, ?, [...]) expansion.
1163 expmeta(char *enddir, char *name)
1180 for (p = name; esc = 0, *p; p += esc + 1) {
1181 if (*p == '*' || *p == '?')
1183 else if (*p == '[') {
1185 if (*q == '!' || *q == '^')
1188 while (*q == CTLQUOTEMARK)
1192 if (*q == '/' || *q == '\0')
1199 } else if (*p == '\0')
1201 else if (*p == CTLQUOTEMARK)
1206 if (p[esc] == '/') {
1209 start = p + esc + 1;
1213 if (metaflag == 0) { /* we've reached the end of the file name */
1214 if (enddir != expdir)
1216 for (p = name ; ; p++) {
1217 if (*p == CTLQUOTEMARK)
1224 if (enddir == expdir_end)
1227 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1232 if (start != name) {
1235 while (*p == CTLQUOTEMARK)
1240 if (enddir == expdir_end)
1244 if (enddir == expdir) {
1245 p = __DECONST(char *, ".");
1246 } else if (enddir == expdir + 1 && *expdir == '/') {
1247 p = __DECONST(char *, "/");
1252 if ((dirp = opendir(p)) == NULL)
1254 if (enddir != expdir)
1256 if (*endname == 0) {
1265 while (*p == CTLQUOTEMARK)
1271 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1272 if (dp->d_name[0] == '.' && ! matchdot)
1274 if (patmatch(start, dp->d_name, 0)) {
1275 namlen = dp->d_namlen;
1276 if (enddir + namlen + 1 > expdir_end)
1278 memcpy(enddir, dp->d_name, namlen + 1);
1282 if (dp->d_type != DT_UNKNOWN &&
1283 dp->d_type != DT_DIR &&
1284 dp->d_type != DT_LNK)
1286 if (enddir + namlen + 2 > expdir_end)
1288 enddir[namlen] = '/';
1289 enddir[namlen + 1] = '\0';
1290 expmeta(enddir + namlen + 1, endname);
1296 endname[-esc - 1] = esc ? CTLESC : '/';
1301 * Add a file name to the list.
1305 addfname(char *name)
1310 p = stalloc(strlen(name) + 1);
1312 sp = (struct strlist *)stalloc(sizeof *sp);
1315 exparg.lastp = &sp->next;
1320 * Sort the results of file name expansion. It calculates the number of
1321 * strings to sort and then calls msort (short for merge sort) to do the
1325 static struct strlist *
1326 expsort(struct strlist *str)
1332 for (sp = str ; sp ; sp = sp->next)
1334 return msort(str, len);
1338 static struct strlist *
1339 msort(struct strlist *list, int len)
1341 struct strlist *p, *q = NULL;
1342 struct strlist **lpp;
1350 for (n = half ; --n >= 0 ; ) {
1354 q->next = NULL; /* terminate first half of list */
1355 q = msort(list, half); /* sort first half of list */
1356 p = msort(p, len - half); /* sort second half */
1359 if (strcmp(p->text, q->text) < 0) {
1362 if ((p = *lpp) == NULL) {
1369 if ((q = *lpp) == NULL) {
1381 get_wc(const char **p)
1386 chrlen = mbtowc(&c, *p, 4);
1389 else if (chrlen == -1)
1398 * See if a character matches a character class, starting at the first colon
1400 * If a valid character class is recognized, a pointer to the next character
1401 * after the final closing bracket is stored into *end, otherwise a null
1402 * pointer is stored into *end.
1405 match_charclass(const char *p, wchar_t chr, const char **end)
1408 const char *nameend;
1413 nameend = strstr(p, ":]");
1414 if (nameend == NULL || nameend - p >= (int)sizeof(name) || nameend == p)
1416 memcpy(name, p, nameend - p);
1417 name[nameend - p] = '\0';
1419 cclass = wctype(name);
1420 /* An unknown class matches nothing but is valid nevertheless. */
1423 return iswctype(chr, cclass);
1428 * Returns true if the pattern matches the string.
1432 patmatch(const char *pattern, const char *string, int squoted)
1434 const char *p, *q, *end;
1435 const char *bt_p, *bt_q;
1450 if (squoted && *q == CTLESC)
1458 if (squoted && *q == CTLESC)
1465 * A '?' does not match invalid UTF-8 but a
1466 * '*' does, so backtrack.
1471 wc = (unsigned char)*q++;
1475 while (c == CTLQUOTEMARK || c == '*')
1478 * If the pattern ends here, we know the string
1479 * matches without needing to look at the rest of it.
1484 * First try the shortest match for the '*' that
1485 * could work. We can forget any earlier '*' since
1486 * there is no way having it match more characters
1487 * can help us, given that we are already here.
1498 if (*endp == '!' || *endp == '^')
1501 while (*endp == CTLQUOTEMARK)
1504 goto dft; /* no matching ] */
1505 if (*endp == CTLESC)
1511 if (*p == '!' || *p == '^') {
1516 if (squoted && *q == CTLESC)
1525 chr = (unsigned char)*q++;
1528 if (c == CTLQUOTEMARK)
1530 if (c == '[' && *p == ':') {
1531 found |= match_charclass(p, chr, &end);
1537 if (localeisutf8 && c & 0x80) {
1540 if (wc == 0) /* bad utf-8 */
1543 wc = (unsigned char)c;
1544 if (*p == '-' && p[1] != ']') {
1546 while (*p == CTLQUOTEMARK)
1552 if (wc2 == 0) /* bad utf-8 */
1555 wc2 = (unsigned char)*p++;
1556 if ( collate_range_cmp(chr, wc) >= 0
1557 && collate_range_cmp(chr, wc2) <= 0
1564 } while ((c = *p++) != ']');
1565 if (found == invert)
1570 if (squoted && *q == CTLESC)
1578 * If we have a mismatch (other than hitting the end
1579 * of the string), go back to the last '*' seen and
1580 * have it match one additional character.
1584 if (squoted && *bt_q == CTLESC)
1599 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1603 rmescapes(char *str)
1608 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1614 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1628 * See if a pattern matches in a case statement.
1632 casematch(union node *pattern, const char *val)
1634 struct stackmark smark;
1638 setstackmark(&smark);
1639 argbackq = pattern->narg.backquote;
1640 STARTSTACKSTR(expdest);
1642 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1643 STPUTC('\0', expdest);
1644 p = grabstackstr(expdest);
1645 result = patmatch(p, val, 0);
1646 popstackmark(&smark);
1655 cvtnum(int num, char *buf)
1659 char *p = temp + 31;
1664 *--p = num % 10 + '0';
1665 } while ((num /= 10) != 0);
1675 * Do most of the work for wordexp(3).
1679 wordexpcmd(int argc, char **argv)
1684 out1fmt("%08x", argc - 1);
1685 for (i = 1, len = 0; i < argc; i++)
1686 len += strlen(argv[i]);
1687 out1fmt("%08x", (int)len);
1688 for (i = 1; i < argc; i++)
1689 outbin(argv[i], strlen(argv[i]) + 1, out1);