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 stputs_quotes(const char *data, const char *syntax, char *p)
135 if (syntax[(int)*data] == CCTL)
141 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
144 * Perform expansions on an argument, placing the resulting list of arguments
145 * in arglist. Parameter expansion, command substitution and arithmetic
146 * expansion are always performed; additional expansions can be requested
148 * The result is left in the stack string.
149 * When arglist is NULL, perform here document expansion.
151 * Caution: this function uses global state and is not reentrant.
152 * However, a new invocation after an interrupted invocation is safe
153 * and will reset the global state for the new call.
156 expandarg(union node *arg, struct arglist *arglist, int flag)
161 argbackq = arg->narg.backquote;
162 STARTSTACKSTR(expdest);
163 ifsfirst.next = NULL;
165 argstr(arg->narg.text, flag);
166 if (arglist == NULL) {
167 STACKSTRNUL(expdest);
168 return; /* here document expanded */
170 STPUTC('\0', expdest);
171 p = grabstackstr(expdest);
172 exparg.lastp = &exparg.list;
176 if (flag & EXP_FULL) {
177 ifsbreakup(p, &exparg);
178 *exparg.lastp = NULL;
179 exparg.lastp = &exparg.list;
180 expandmeta(exparg.list, flag);
182 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
184 sp = (struct strlist *)stalloc(sizeof (struct strlist));
187 exparg.lastp = &sp->next;
189 while (ifsfirst.next != NULL) {
190 struct ifsregion *ifsp;
192 ifsp = ifsfirst.next->next;
193 ckfree(ifsfirst.next);
194 ifsfirst.next = ifsp;
197 *exparg.lastp = NULL;
199 *arglist->lastp = exparg.list;
200 arglist->lastp = exparg.lastp;
207 * Perform parameter expansion, command substitution and arithmetic
208 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
209 * Processing ends at a CTLENDVAR character as well as '\0'.
210 * This is used to expand word in ${var+word} etc.
211 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
212 * characters to allow for further processing.
213 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
216 argstr(char *p, int flag)
219 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
224 split_lit = flag & EXP_SPLIT_LIT;
225 lit_quoted = flag & EXP_LIT_QUOTED;
226 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
227 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
228 p = exptilde(p, flag);
230 CHECKSTRSPACE(2, expdest);
237 /* "$@" syntax adherence hack */
238 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
240 if ((flag & EXP_FULL) != 0)
251 if (split_lit && !lit_quoted)
252 recordregion(expdest - stackblock() -
254 expdest - stackblock(), 0);
257 p = evalvar(p, flag);
260 case CTLBACKQ|CTLQUOTE:
261 expbackq(argbackq->n, c & CTLQUOTE, flag);
262 argbackq = argbackq->next;
270 * sort of a hack - expand tildes in variable
271 * assignments (after the first '=' and after ':'s).
274 if (split_lit && !lit_quoted)
275 recordregion(expdest - stackblock() - 1,
276 expdest - stackblock(), 0);
277 if (flag & EXP_VARTILDE && *p == '~' &&
278 (c != '=' || firsteq)) {
281 p = exptilde(p, flag);
286 if (split_lit && !lit_quoted)
287 recordregion(expdest - stackblock() - 1,
288 expdest - stackblock(), 0);
295 * Perform tilde expansion, placing the result in the stack string and
296 * returning the next position in the input string to process.
299 exptilde(char *p, int flag)
304 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
306 while ((c = *p) != '\0') {
308 case CTLESC: /* This means CTL* are always considered quoted. */
311 case CTLBACKQ | CTLQUOTE:
317 if (flag & EXP_VARTILDE)
328 if (*(startp+1) == '\0') {
329 if ((home = lookupvar("HOME")) == NULL)
332 if ((pw = getpwnam(startp+1)) == NULL)
340 STPUTS_QUOTES(home, SQSYNTAX, expdest);
342 STPUTS(home, expdest);
351 removerecordregions(int endoff)
353 if (ifslastp == NULL)
356 if (ifsfirst.endoff > endoff) {
357 while (ifsfirst.next != NULL) {
358 struct ifsregion *ifsp;
360 ifsp = ifsfirst.next->next;
361 ckfree(ifsfirst.next);
362 ifsfirst.next = ifsp;
365 if (ifsfirst.begoff > endoff)
368 ifslastp = &ifsfirst;
369 ifsfirst.endoff = endoff;
374 ifslastp = &ifsfirst;
375 while (ifslastp->next && ifslastp->next->begoff < endoff)
376 ifslastp=ifslastp->next;
377 while (ifslastp->next != NULL) {
378 struct ifsregion *ifsp;
380 ifsp = ifslastp->next->next;
381 ckfree(ifslastp->next);
382 ifslastp->next = ifsp;
385 if (ifslastp->endoff > endoff)
386 ifslastp->endoff = endoff;
390 * Expand arithmetic expression. Backup to start of expression,
391 * evaluate, place result in (backed up) result, adjust string position.
399 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
403 * This routine is slightly over-complicated for
404 * efficiency. First we make sure there is
405 * enough space for the result, which may be bigger
406 * than the expression. Next we
407 * scan backwards looking for the start of arithmetic. If the
408 * next previous character is a CTLESC character, then we
409 * have to rescan starting from the beginning since CTLESC
410 * characters have to be processed left to right.
412 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
413 USTPUTC('\0', expdest);
414 start = stackblock();
416 while (p >= start && *p != CTLARI)
418 if (p < start || *p != CTLARI)
419 error("missing CTLARI (shouldn't happen)");
420 if (p > start && *(p - 1) == CTLESC)
421 for (p = start; *p != CTLARI; p++)
430 removerecordregions(begoff);
433 q = grabstackstr(expdest);
435 ungrabstackstr(q, expdest);
436 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
440 recordregion(begoff, p - 1 - start, 0);
441 result = expdest - p + 1;
442 STADJUST(-result, expdest);
447 * Perform command substitution.
450 expbackq(union node *cmd, int quoted, int flag)
456 char *dest = expdest;
457 struct ifsregion saveifs, *savelastp;
458 struct nodelist *saveargbackq;
460 int startloc = dest - stackblock();
461 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
462 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
467 savelastp = ifslastp;
468 saveargbackq = argbackq;
469 p = grabstackstr(dest);
470 evalbackcmd(cmd, &in);
471 ungrabstackstr(p, dest);
473 ifslastp = savelastp;
474 argbackq = saveargbackq;
479 /* Don't copy trailing newlines */
481 if (--in.nleft < 0) {
484 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
485 TRACE(("expbackq: read returns %d\n", i));
496 CHECKSTRSPACE(nnl + 2, dest);
501 if (quotes && syntax[(int)lastc] == CCTL)
502 USTPUTC(CTLESC, dest);
503 USTPUTC(lastc, dest);
513 exitstatus = waitforjob(in.jp, (int *)NULL);
515 recordregion(startloc, dest - stackblock(), 0);
516 TRACE(("expbackq: size=%td: \"%.*s\"\n",
517 ((dest - stackblock()) - startloc),
518 (int)((dest - stackblock()) - startloc),
519 stackblock() + startloc));
527 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
528 int varflags, int quotes)
534 struct nodelist *saveargbackq = argbackq;
537 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
538 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
539 EXP_CASE : 0) | EXP_TILDE);
540 STACKSTRNUL(expdest);
541 argbackq = saveargbackq;
542 startp = stackblock() + startloc;
544 str = stackblock() + strloc;
548 setvar(str, startp, 0);
549 amount = startp - expdest;
550 STADJUST(amount, expdest);
555 if (*p != CTLENDVAR) {
556 outfmt(out2, "%s\n", startp);
559 error("%.*s: parameter %snot set", (int)(p - str - 1),
560 str, (varflags & VSNUL) ? "null or "
565 for (loc = startp; loc < str; loc++) {
568 if (patmatch(str, startp, quotes)) {
573 if (quotes && *loc == CTLESC)
579 for (loc = str - 1; loc >= startp;) {
582 if (patmatch(str, startp, quotes)) {
588 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
589 for (q = startp; q < loc; q++)
599 for (loc = str - 1; loc >= startp;) {
600 if (patmatch(str, loc, quotes)) {
601 amount = loc - expdest;
602 STADJUST(amount, expdest);
606 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
607 for (q = startp; q < loc; q++)
617 for (loc = startp; loc < str - 1; loc++) {
618 if (patmatch(str, loc, quotes)) {
619 amount = loc - expdest;
620 STADJUST(amount, expdest);
623 if (quotes && *loc == CTLESC)
634 amount = ((str - 1) - (loc - startp)) - expdest;
635 STADJUST(amount, expdest);
636 while (loc != str - 1)
643 * Expand a variable, and return a pointer to the next character in the
648 evalvar(char *p, int flag)
662 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
664 varflags = (unsigned char)*p++;
665 subtype = varflags & VSTYPE;
670 p = strchr(p, '=') + 1;
671 again: /* jump here after setting a variable with ${var=text} */
672 if (varflags & VSLINENO) {
676 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
678 } else if (special) {
679 set = varisset(var, varflags & VSNUL);
682 val = bltinlookup(var, 1);
683 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
690 startloc = expdest - stackblock();
691 if (!set && uflag && *var != '@' && *var != '*') {
699 error("%.*s: parameter not set", (int)(p - var - 1),
703 if (set && subtype != VSPLUS) {
704 /* insert the value of the variable */
706 varvalue(var, varflags & VSQUOTE, subtype, flag);
707 if (subtype == VSLENGTH) {
708 varlenb = expdest - stackblock() - startloc;
711 val = stackblock() + startloc;
712 for (;val != expdest; val++)
713 if ((*val & 0xC0) == 0x80)
716 STADJUST(-varlenb, expdest);
719 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
722 if (subtype == VSLENGTH) {
725 (*val & 0xC0) != 0x80)
730 STPUTS_QUOTES(val, syntax, expdest);
732 STPUTS(val, expdest);
738 if (subtype == VSPLUS)
741 easy = ((varflags & VSQUOTE) == 0 ||
742 (*var == '@' && shellparam.nparam != 1));
747 expdest = cvtnum(varlen, expdest);
754 recordregion(startloc, expdest - stackblock(),
755 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
756 (*var == '@' || *var == '*')));
762 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
763 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
777 * Terminate the string and start recording the pattern
780 STPUTC('\0', expdest);
781 patloc = expdest - stackblock();
782 if (subevalvar(p, NULL, patloc, subtype,
783 startloc, varflags, quotes) == 0) {
784 int amount = (expdest - stackblock() - patloc) + 1;
785 STADJUST(-amount, expdest);
787 /* Remove any recorded regions beyond start of variable */
788 removerecordregions(startloc);
794 if (subevalvar(p, var, 0, subtype, startloc, varflags,
798 * Remove any recorded regions beyond
801 removerecordregions(startloc);
812 error("${%.*s%s}: Bad substitution", c, var,
813 (c > 0 && *p != CTLENDVAR) ? "..." : "");
818 p[-1] = '='; /* recover overwritten '=' */
820 if (subtype != VSNORMAL) { /* skip to end of alternative */
823 if ((c = *p++) == CTLESC)
825 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
827 argbackq = argbackq->next;
828 } else if (c == CTLVAR) {
829 if ((*p++ & VSTYPE) != VSNORMAL)
831 } else if (c == CTLENDVAR) {
843 * Test whether a specialized variable is set.
847 varisset(char *name, int nulok)
851 return backgndpidset();
852 else if (*name == '@' || *name == '*') {
853 if (*shellparam.p == NULL)
859 for (av = shellparam.p; *av; av++)
864 } else if (is_digit(*name)) {
866 int num = atoi(name);
868 if (num > shellparam.nparam)
874 ap = shellparam.p[num - 1];
876 if (nulok && (ap == NULL || *ap == '\0'))
883 strtodest(const char *p, int flag, int subtype, int quoted)
885 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
886 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
892 * Add the value of a specialized variable to the stack string.
896 varvalue(char *name, int quoted, int subtype, int flag)
912 num = shellparam.nparam;
915 num = backgndpidval();
917 expdest = cvtnum(num, expdest);
920 for (i = 0 ; i < NOPTS ; i++) {
922 STPUTC(optlist[i].letter, expdest);
926 if (flag & EXP_FULL && quoted) {
927 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
928 strtodest(p, flag, subtype, quoted);
930 STPUTC('\0', expdest);
940 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
941 strtodest(p, flag, subtype, quoted);
944 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
945 STPUTC(sep, expdest);
950 strtodest(p, flag, subtype, quoted);
953 if (is_digit(*name)) {
955 if (num > 0 && num <= shellparam.nparam) {
956 p = shellparam.p[num - 1];
957 strtodest(p, flag, subtype, quoted);
967 * Record the fact that we have to scan this region of the
968 * string for IFS characters.
972 recordregion(int start, int end, int inquotes)
974 struct ifsregion *ifsp;
976 if (ifslastp == NULL) {
979 if (ifslastp->endoff == start
980 && ifslastp->inquotes == inquotes) {
981 /* extend previous area */
982 ifslastp->endoff = end;
985 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
986 ifslastp->next = ifsp;
989 ifslastp->next = NULL;
990 ifslastp->begoff = start;
991 ifslastp->endoff = end;
992 ifslastp->inquotes = inquotes;
998 * Break the argument string into pieces based upon IFS and add the
999 * strings to the argument list. The regions of the string to be
1000 * searched for IFS characters have been stored by recordregion.
1001 * CTLESC characters are preserved but have little effect in this pass
1002 * other than escaping CTL* characters. In particular, they do not escape
1003 * IFS characters: that should be done with the ifsregion mechanism.
1004 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1005 * This pass treats them as a regular character, making the string non-empty.
1006 * Later, they are removed along with the other CTL* characters.
1009 ifsbreakup(char *string, struct arglist *arglist)
1011 struct ifsregion *ifsp;
1018 int had_param_ch = 0;
1022 if (ifslastp == NULL) {
1023 /* Return entire argument, IFS doesn't apply to any of it */
1024 sp = (struct strlist *)stalloc(sizeof *sp);
1026 *arglist->lastp = sp;
1027 arglist->lastp = &sp->next;
1031 ifs = ifsset() ? ifsval() : " \t\n";
1033 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1034 p = string + ifsp->begoff;
1035 while (p < string + ifsp->endoff) {
1039 if (ifsp->inquotes) {
1040 /* Only NULs (should be from "$@") end args */
1048 if (!strchr(ifs, *p)) {
1053 ifsspc = strchr(" \t\n", *p);
1055 /* Ignore IFS whitespace at start */
1056 if (q == start && ifsspc != NULL) {
1064 /* Save this argument... */
1066 sp = (struct strlist *)stalloc(sizeof *sp);
1068 *arglist->lastp = sp;
1069 arglist->lastp = &sp->next;
1072 if (ifsspc != NULL) {
1073 /* Ignore further trailing IFS whitespace */
1074 for (; p < string + ifsp->endoff; p++) {
1078 if (strchr(ifs, *p) == NULL) {
1082 if (strchr(" \t\n", *p) == NULL) {
1093 * Save anything left as an argument.
1094 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1095 * generating 2 arguments, the second of which is empty.
1096 * Some recent clarification of the Posix spec say that it
1097 * should only generate one....
1099 if (had_param_ch || *start != 0) {
1100 sp = (struct strlist *)stalloc(sizeof *sp);
1102 *arglist->lastp = sp;
1103 arglist->lastp = &sp->next;
1108 static char expdir[PATH_MAX];
1109 #define expdir_end (expdir + sizeof(expdir))
1112 * Perform pathname generation and remove control characters.
1113 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1114 * The results are stored in the list exparg.
1117 expandmeta(struct strlist *str, int flag __unused)
1120 struct strlist **savelastp;
1123 /* TODO - EXP_REDIR */
1129 for (;;) { /* fast check for meta chars */
1130 if ((c = *p++) == '\0')
1132 if (c == '*' || c == '?' || c == '[')
1135 savelastp = exparg.lastp;
1137 expmeta(expdir, str->text);
1139 if (exparg.lastp == savelastp) {
1144 *exparg.lastp = str;
1145 rmescapes(str->text);
1146 exparg.lastp = &str->next;
1148 *exparg.lastp = NULL;
1149 *savelastp = sp = expsort(*savelastp);
1150 while (sp->next != NULL)
1152 exparg.lastp = &sp->next;
1160 * Do metacharacter (i.e. *, ?, [...]) expansion.
1164 expmeta(char *enddir, char *name)
1181 for (p = name; esc = 0, *p; p += esc + 1) {
1182 if (*p == '*' || *p == '?')
1184 else if (*p == '[') {
1186 if (*q == '!' || *q == '^')
1189 while (*q == CTLQUOTEMARK)
1193 if (*q == '/' || *q == '\0')
1200 } else if (*p == '\0')
1202 else if (*p == CTLQUOTEMARK)
1207 if (p[esc] == '/') {
1210 start = p + esc + 1;
1214 if (metaflag == 0) { /* we've reached the end of the file name */
1215 if (enddir != expdir)
1217 for (p = name ; ; p++) {
1218 if (*p == CTLQUOTEMARK)
1225 if (enddir == expdir_end)
1228 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1232 endname = name + (p - name);
1233 if (start != name) {
1236 while (*p == CTLQUOTEMARK)
1241 if (enddir == expdir_end)
1245 if (enddir == expdir) {
1247 } else if (enddir == expdir + 1 && *expdir == '/') {
1253 if ((dirp = opendir(p)) == NULL)
1255 if (enddir != expdir)
1257 if (*endname == 0) {
1266 while (*p == CTLQUOTEMARK)
1272 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1273 if (dp->d_name[0] == '.' && ! matchdot)
1275 if (patmatch(start, dp->d_name, 0)) {
1276 namlen = dp->d_namlen;
1277 if (enddir + namlen + 1 > expdir_end)
1279 memcpy(enddir, dp->d_name, namlen + 1);
1283 if (dp->d_type != DT_UNKNOWN &&
1284 dp->d_type != DT_DIR &&
1285 dp->d_type != DT_LNK)
1287 if (enddir + namlen + 2 > expdir_end)
1289 enddir[namlen] = '/';
1290 enddir[namlen + 1] = '\0';
1291 expmeta(enddir + namlen + 1, endname);
1297 endname[-esc - 1] = esc ? CTLESC : '/';
1302 * Add a file name to the list.
1306 addfname(char *name)
1311 p = stalloc(strlen(name) + 1);
1313 sp = (struct strlist *)stalloc(sizeof *sp);
1316 exparg.lastp = &sp->next;
1321 * Sort the results of file name expansion. It calculates the number of
1322 * strings to sort and then calls msort (short for merge sort) to do the
1326 static struct strlist *
1327 expsort(struct strlist *str)
1333 for (sp = str ; sp ; sp = sp->next)
1335 return msort(str, len);
1339 static struct strlist *
1340 msort(struct strlist *list, int len)
1342 struct strlist *p, *q = NULL;
1343 struct strlist **lpp;
1351 for (n = half ; --n >= 0 ; ) {
1355 q->next = NULL; /* terminate first half of list */
1356 q = msort(list, half); /* sort first half of list */
1357 p = msort(p, len - half); /* sort second half */
1360 if (strcmp(p->text, q->text) < 0) {
1363 if ((p = *lpp) == NULL) {
1370 if ((q = *lpp) == NULL) {
1382 get_wc(const char **p)
1387 chrlen = mbtowc(&c, *p, 4);
1390 else if (chrlen == -1)
1399 * See if a character matches a character class, starting at the first colon
1401 * If a valid character class is recognized, a pointer to the next character
1402 * after the final closing bracket is stored into *end, otherwise a null
1403 * pointer is stored into *end.
1406 match_charclass(const char *p, wchar_t chr, const char **end)
1409 const char *nameend;
1414 nameend = strstr(p, ":]");
1415 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1418 memcpy(name, p, nameend - p);
1419 name[nameend - p] = '\0';
1421 cclass = wctype(name);
1422 /* An unknown class matches nothing but is valid nevertheless. */
1425 return iswctype(chr, cclass);
1430 * Returns true if the pattern matches the string.
1434 patmatch(const char *pattern, const char *string, int squoted)
1436 const char *p, *q, *end;
1437 const char *bt_p, *bt_q;
1452 if (squoted && *q == CTLESC)
1460 if (squoted && *q == CTLESC)
1467 * A '?' does not match invalid UTF-8 but a
1468 * '*' does, so backtrack.
1473 wc = (unsigned char)*q++;
1477 while (c == CTLQUOTEMARK || c == '*')
1480 * If the pattern ends here, we know the string
1481 * matches without needing to look at the rest of it.
1486 * First try the shortest match for the '*' that
1487 * could work. We can forget any earlier '*' since
1488 * there is no way having it match more characters
1489 * can help us, given that we are already here.
1500 if (*endp == '!' || *endp == '^')
1503 while (*endp == CTLQUOTEMARK)
1506 goto dft; /* no matching ] */
1507 if (*endp == CTLESC)
1513 if (*p == '!' || *p == '^') {
1518 if (squoted && *q == CTLESC)
1527 chr = (unsigned char)*q++;
1530 if (c == CTLQUOTEMARK)
1532 if (c == '[' && *p == ':') {
1533 found |= match_charclass(p, chr, &end);
1539 if (localeisutf8 && c & 0x80) {
1542 if (wc == 0) /* bad utf-8 */
1545 wc = (unsigned char)c;
1546 if (*p == '-' && p[1] != ']') {
1548 while (*p == CTLQUOTEMARK)
1554 if (wc2 == 0) /* bad utf-8 */
1557 wc2 = (unsigned char)*p++;
1558 if ( collate_range_cmp(chr, wc) >= 0
1559 && collate_range_cmp(chr, wc2) <= 0
1566 } while ((c = *p++) != ']');
1567 if (found == invert)
1572 if (squoted && *q == CTLESC)
1580 * If we have a mismatch (other than hitting the end
1581 * of the string), go back to the last '*' seen and
1582 * have it match one additional character.
1586 if (squoted && *bt_q == CTLESC)
1601 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1605 rmescapes(char *str)
1610 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1616 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1630 * See if a pattern matches in a case statement.
1634 casematch(union node *pattern, const char *val)
1636 struct stackmark smark;
1640 setstackmark(&smark);
1641 argbackq = pattern->narg.backquote;
1642 STARTSTACKSTR(expdest);
1644 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1645 STPUTC('\0', expdest);
1646 p = grabstackstr(expdest);
1647 result = patmatch(p, val, 0);
1648 popstackmark(&smark);
1657 cvtnum(int num, char *buf)
1661 char *p = temp + 31;
1666 *--p = num % 10 + '0';
1667 } while ((num /= 10) != 0);
1677 * Do most of the work for wordexp(3).
1681 wordexpcmd(int argc, char **argv)
1686 out1fmt("%08x", argc - 1);
1687 for (i = 1, len = 0; i < argc; i++)
1688 len += strlen(argv[i]);
1689 out1fmt("%08x", (int)len);
1690 for (i = 1; i < argc; i++)
1691 outbin(argv[i], strlen(argv[i]) + 1, out1);