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 expari(int);
104 static void expbackq(union node *, int, int);
105 static int subevalvar(char *, char *, int, int, int, int, int);
106 static char *evalvar(char *, int);
107 static int varisset(char *, int);
108 static void varvalue(char *, int, int, int);
109 static void recordregion(int, int, int);
110 static void removerecordregions(int);
111 static void ifsbreakup(char *, struct arglist *);
112 static void expandmeta(struct strlist *, int);
113 static void expmeta(char *, char *);
114 static void addfname(char *);
115 static struct strlist *expsort(struct strlist *);
116 static struct strlist *msort(struct strlist *, int);
117 static int patmatch(const char *, const char *, int);
118 static char *cvtnum(int, char *);
119 static int collate_range_cmp(wchar_t, wchar_t);
122 collate_range_cmp(wchar_t c1, wchar_t c2)
124 static wchar_t s1[2], s2[2];
128 return (wcscoll(s1, s2));
132 stputs_quotes(const char *data, const char *syntax, char *p)
136 if (syntax[(int)*data] == CCTL)
142 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
145 * Perform expansions on an argument, placing the resulting list of arguments
146 * in arglist. Parameter expansion, command substitution and arithmetic
147 * expansion are always performed; additional expansions can be requested
149 * The result is left in the stack string.
150 * When arglist is NULL, perform here document expansion.
152 * Caution: this function uses global state and is not reentrant.
153 * However, a new invocation after an interrupted invocation is safe
154 * and will reset the global state for the new call.
157 expandarg(union node *arg, struct arglist *arglist, int flag)
162 argbackq = arg->narg.backquote;
163 STARTSTACKSTR(expdest);
164 ifsfirst.next = NULL;
166 argstr(arg->narg.text, flag);
167 if (arglist == NULL) {
168 STACKSTRNUL(expdest);
169 return; /* here document expanded */
171 STPUTC('\0', expdest);
172 p = grabstackstr(expdest);
173 exparg.lastp = &exparg.list;
177 if (flag & EXP_FULL) {
178 ifsbreakup(p, &exparg);
179 *exparg.lastp = NULL;
180 exparg.lastp = &exparg.list;
181 expandmeta(exparg.list, flag);
183 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
185 sp = (struct strlist *)stalloc(sizeof (struct strlist));
188 exparg.lastp = &sp->next;
190 while (ifsfirst.next != NULL) {
191 struct ifsregion *ifsp;
193 ifsp = ifsfirst.next->next;
194 ckfree(ifsfirst.next);
195 ifsfirst.next = ifsp;
198 *exparg.lastp = NULL;
200 *arglist->lastp = exparg.list;
201 arglist->lastp = exparg.lastp;
208 * Perform parameter expansion, command substitution and arithmetic
209 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
210 * Processing ends at a CTLENDVAR character as well as '\0'.
211 * This is used to expand word in ${var+word} etc.
212 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
213 * characters to allow for further processing.
214 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
217 argstr(char *p, int flag)
220 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
225 split_lit = flag & EXP_SPLIT_LIT;
226 lit_quoted = flag & EXP_LIT_QUOTED;
227 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
228 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
229 p = exptilde(p, flag);
231 CHECKSTRSPACE(2, expdest);
238 /* "$@" syntax adherence hack */
239 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
241 if ((flag & EXP_FULL) != 0)
252 if (split_lit && !lit_quoted)
253 recordregion(expdest - stackblock() -
255 expdest - stackblock(), 0);
258 p = evalvar(p, flag);
261 case CTLBACKQ|CTLQUOTE:
262 expbackq(argbackq->n, c & CTLQUOTE, flag);
263 argbackq = argbackq->next;
271 * sort of a hack - expand tildes in variable
272 * assignments (after the first '=' and after ':'s).
275 if (split_lit && !lit_quoted)
276 recordregion(expdest - stackblock() - 1,
277 expdest - stackblock(), 0);
278 if (flag & EXP_VARTILDE && *p == '~' &&
279 (c != '=' || firsteq)) {
282 p = exptilde(p, flag);
287 if (split_lit && !lit_quoted)
288 recordregion(expdest - stackblock() - 1,
289 expdest - stackblock(), 0);
296 * Perform tilde expansion, placing the result in the stack string and
297 * returning the next position in the input string to process.
300 exptilde(char *p, int flag)
305 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
307 while ((c = *p) != '\0') {
309 case CTLESC: /* This means CTL* are always considered quoted. */
312 case CTLBACKQ | CTLQUOTE:
318 if (flag & EXP_VARTILDE)
329 if (*(startp+1) == '\0') {
330 if ((home = lookupvar("HOME")) == NULL)
333 if ((pw = getpwnam(startp+1)) == NULL)
341 STPUTS_QUOTES(home, SQSYNTAX, expdest);
343 STPUTS(home, expdest);
352 removerecordregions(int endoff)
354 if (ifslastp == NULL)
357 if (ifsfirst.endoff > endoff) {
358 while (ifsfirst.next != NULL) {
359 struct ifsregion *ifsp;
361 ifsp = ifsfirst.next->next;
362 ckfree(ifsfirst.next);
363 ifsfirst.next = ifsp;
366 if (ifsfirst.begoff > endoff)
369 ifslastp = &ifsfirst;
370 ifsfirst.endoff = endoff;
375 ifslastp = &ifsfirst;
376 while (ifslastp->next && ifslastp->next->begoff < endoff)
377 ifslastp=ifslastp->next;
378 while (ifslastp->next != NULL) {
379 struct ifsregion *ifsp;
381 ifsp = ifslastp->next->next;
382 ckfree(ifslastp->next);
383 ifslastp->next = ifsp;
386 if (ifslastp->endoff > endoff)
387 ifslastp->endoff = endoff;
391 * Expand arithmetic expression. Backup to start of expression,
392 * evaluate, place result in (backed up) result, adjust string position.
400 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
404 * This routine is slightly over-complicated for
405 * efficiency. First we make sure there is
406 * enough space for the result, which may be bigger
407 * than the expression. Next we
408 * scan backwards looking for the start of arithmetic. If the
409 * next previous character is a CTLESC character, then we
410 * have to rescan starting from the beginning since CTLESC
411 * characters have to be processed left to right.
413 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
414 USTPUTC('\0', expdest);
415 start = stackblock();
417 while (p >= start && *p != CTLARI)
419 if (p < start || *p != CTLARI)
420 error("missing CTLARI (shouldn't happen)");
421 if (p > start && *(p - 1) == CTLESC)
422 for (p = start; *p != CTLARI; p++)
431 removerecordregions(begoff);
434 q = grabstackstr(expdest);
436 ungrabstackstr(q, expdest);
437 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
441 recordregion(begoff, p - 1 - start, 0);
442 result = expdest - p + 1;
443 STADJUST(-result, expdest);
448 * Perform command substitution.
451 expbackq(union node *cmd, int quoted, int flag)
457 char *dest = expdest;
458 struct ifsregion saveifs, *savelastp;
459 struct nodelist *saveargbackq;
461 int startloc = dest - stackblock();
462 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
463 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
468 savelastp = ifslastp;
469 saveargbackq = argbackq;
470 p = grabstackstr(dest);
471 evalbackcmd(cmd, &in);
472 ungrabstackstr(p, dest);
474 ifslastp = savelastp;
475 argbackq = saveargbackq;
480 /* Don't copy trailing newlines */
482 if (--in.nleft < 0) {
485 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
486 TRACE(("expbackq: read returns %d\n", i));
497 CHECKSTRSPACE(nnl + 2, dest);
502 if (quotes && syntax[(int)lastc] == CCTL)
503 USTPUTC(CTLESC, dest);
504 USTPUTC(lastc, dest);
514 exitstatus = waitforjob(in.jp, (int *)NULL);
516 recordregion(startloc, dest - stackblock(), 0);
517 TRACE(("expbackq: size=%td: \"%.*s\"\n",
518 ((dest - stackblock()) - startloc),
519 (int)((dest - stackblock()) - startloc),
520 stackblock() + startloc));
528 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
529 int varflags, int quotes)
535 struct nodelist *saveargbackq = argbackq;
538 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
539 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
540 EXP_CASE : 0) | EXP_TILDE);
541 STACKSTRNUL(expdest);
542 argbackq = saveargbackq;
543 startp = stackblock() + startloc;
545 str = stackblock() + strloc;
549 setvar(str, startp, 0);
550 amount = startp - expdest;
551 STADJUST(amount, expdest);
556 if (*p != CTLENDVAR) {
557 outfmt(out2, "%s\n", startp);
560 error("%.*s: parameter %snot set", (int)(p - str - 1),
561 str, (varflags & VSNUL) ? "null or "
566 for (loc = startp; loc < str; loc++) {
569 if (patmatch(str, startp, quotes)) {
574 if (quotes && *loc == CTLESC)
580 for (loc = str - 1; loc >= startp;) {
583 if (patmatch(str, startp, quotes)) {
589 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
590 for (q = startp; q < loc; q++)
600 for (loc = str - 1; loc >= startp;) {
601 if (patmatch(str, loc, quotes)) {
602 amount = loc - expdest;
603 STADJUST(amount, expdest);
607 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
608 for (q = startp; q < loc; q++)
618 for (loc = startp; loc < str - 1; loc++) {
619 if (patmatch(str, loc, quotes)) {
620 amount = loc - expdest;
621 STADJUST(amount, expdest);
624 if (quotes && *loc == CTLESC)
635 amount = ((str - 1) - (loc - startp)) - expdest;
636 STADJUST(amount, expdest);
637 while (loc != str - 1)
644 * Expand a variable, and return a pointer to the next character in the
649 evalvar(char *p, int flag)
663 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
665 varflags = (unsigned char)*p++;
666 subtype = varflags & VSTYPE;
671 p = strchr(p, '=') + 1;
672 again: /* jump here after setting a variable with ${var=text} */
673 if (varflags & VSLINENO) {
677 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
679 } else if (special) {
680 set = varisset(var, varflags & VSNUL);
683 val = bltinlookup(var, 1);
684 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
691 startloc = expdest - stackblock();
692 if (!set && uflag && *var != '@' && *var != '*') {
700 error("%.*s: parameter not set", (int)(p - var - 1),
704 if (set && subtype != VSPLUS) {
705 /* insert the value of the variable */
707 varvalue(var, varflags & VSQUOTE, subtype, flag);
708 if (subtype == VSLENGTH) {
709 varlenb = expdest - stackblock() - startloc;
712 val = stackblock() + startloc;
713 for (;val != expdest; val++)
714 if ((*val & 0xC0) == 0x80)
717 STADJUST(-varlenb, expdest);
720 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
723 if (subtype == VSLENGTH) {
726 (*val & 0xC0) != 0x80)
731 STPUTS_QUOTES(val, syntax, expdest);
733 STPUTS(val, expdest);
739 if (subtype == VSPLUS)
742 easy = ((varflags & VSQUOTE) == 0 ||
743 (*var == '@' && shellparam.nparam != 1));
748 expdest = cvtnum(varlen, expdest);
755 recordregion(startloc, expdest - stackblock(),
756 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
757 (*var == '@' || *var == '*')));
763 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
764 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
778 * Terminate the string and start recording the pattern
781 STPUTC('\0', expdest);
782 patloc = expdest - stackblock();
783 if (subevalvar(p, NULL, patloc, subtype,
784 startloc, varflags, quotes) == 0) {
785 int amount = (expdest - stackblock() - patloc) + 1;
786 STADJUST(-amount, expdest);
788 /* Remove any recorded regions beyond start of variable */
789 removerecordregions(startloc);
795 if (subevalvar(p, var, 0, subtype, startloc, varflags,
799 * Remove any recorded regions beyond
802 removerecordregions(startloc);
813 error("${%.*s%s}: Bad substitution", c, var,
814 (c > 0 && *p != CTLENDVAR) ? "..." : "");
819 p[-1] = '='; /* recover overwritten '=' */
821 if (subtype != VSNORMAL) { /* skip to end of alternative */
824 if ((c = *p++) == CTLESC)
826 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
828 argbackq = argbackq->next;
829 } else if (c == CTLVAR) {
830 if ((*p++ & VSTYPE) != VSNORMAL)
832 } else if (c == CTLENDVAR) {
844 * Test whether a specialized variable is set.
848 varisset(char *name, int nulok)
852 return backgndpidset();
853 else if (*name == '@' || *name == '*') {
854 if (*shellparam.p == NULL)
860 for (av = shellparam.p; *av; av++)
865 } else if (is_digit(*name)) {
867 int num = atoi(name);
869 if (num > shellparam.nparam)
875 ap = shellparam.p[num - 1];
877 if (nulok && (ap == NULL || *ap == '\0'))
884 strtodest(const char *p, int flag, int subtype, int quoted)
886 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
887 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
893 * Add the value of a specialized variable to the stack string.
897 varvalue(char *name, int quoted, int subtype, int flag)
913 num = shellparam.nparam;
916 num = backgndpidval();
918 expdest = cvtnum(num, expdest);
921 for (i = 0 ; i < NOPTS ; i++) {
923 STPUTC(optlist[i].letter, expdest);
927 if (flag & EXP_FULL && quoted) {
928 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
929 strtodest(p, flag, subtype, quoted);
931 STPUTC('\0', expdest);
941 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
942 strtodest(p, flag, subtype, quoted);
945 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
946 STPUTC(sep, expdest);
951 strtodest(p, flag, subtype, quoted);
954 if (is_digit(*name)) {
956 if (num > 0 && num <= shellparam.nparam) {
957 p = shellparam.p[num - 1];
958 strtodest(p, flag, subtype, quoted);
968 * Record the fact that we have to scan this region of the
969 * string for IFS characters.
973 recordregion(int start, int end, int inquotes)
975 struct ifsregion *ifsp;
977 if (ifslastp == NULL) {
980 if (ifslastp->endoff == start
981 && ifslastp->inquotes == inquotes) {
982 /* extend previous area */
983 ifslastp->endoff = end;
986 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
987 ifslastp->next = ifsp;
990 ifslastp->next = NULL;
991 ifslastp->begoff = start;
992 ifslastp->endoff = end;
993 ifslastp->inquotes = inquotes;
999 * Break the argument string into pieces based upon IFS and add the
1000 * strings to the argument list. The regions of the string to be
1001 * searched for IFS characters have been stored by recordregion.
1002 * CTLESC characters are preserved but have little effect in this pass
1003 * other than escaping CTL* characters. In particular, they do not escape
1004 * IFS characters: that should be done with the ifsregion mechanism.
1005 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1006 * This pass treats them as a regular character, making the string non-empty.
1007 * Later, they are removed along with the other CTL* characters.
1010 ifsbreakup(char *string, struct arglist *arglist)
1012 struct ifsregion *ifsp;
1019 int had_param_ch = 0;
1023 if (ifslastp == NULL) {
1024 /* Return entire argument, IFS doesn't apply to any of it */
1025 sp = (struct strlist *)stalloc(sizeof *sp);
1027 *arglist->lastp = sp;
1028 arglist->lastp = &sp->next;
1032 ifs = ifsset() ? ifsval() : " \t\n";
1034 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1035 p = string + ifsp->begoff;
1036 while (p < string + ifsp->endoff) {
1040 if (ifsp->inquotes) {
1041 /* Only NULs (should be from "$@") end args */
1049 if (!strchr(ifs, *p)) {
1054 ifsspc = strchr(" \t\n", *p);
1056 /* Ignore IFS whitespace at start */
1057 if (q == start && ifsspc != NULL) {
1065 /* Save this argument... */
1067 sp = (struct strlist *)stalloc(sizeof *sp);
1069 *arglist->lastp = sp;
1070 arglist->lastp = &sp->next;
1073 if (ifsspc != NULL) {
1074 /* Ignore further trailing IFS whitespace */
1075 for (; p < string + ifsp->endoff; p++) {
1079 if (strchr(ifs, *p) == NULL) {
1083 if (strchr(" \t\n", *p) == NULL) {
1094 * Save anything left as an argument.
1095 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1096 * generating 2 arguments, the second of which is empty.
1097 * Some recent clarification of the Posix spec say that it
1098 * should only generate one....
1100 if (had_param_ch || *start != 0) {
1101 sp = (struct strlist *)stalloc(sizeof *sp);
1103 *arglist->lastp = sp;
1104 arglist->lastp = &sp->next;
1109 static char expdir[PATH_MAX];
1110 #define expdir_end (expdir + sizeof(expdir))
1113 * Perform pathname generation and remove control characters.
1114 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1115 * The results are stored in the list exparg.
1118 expandmeta(struct strlist *str, int flag __unused)
1121 struct strlist **savelastp;
1124 /* TODO - EXP_REDIR */
1130 for (;;) { /* fast check for meta chars */
1131 if ((c = *p++) == '\0')
1133 if (c == '*' || c == '?' || c == '[')
1136 savelastp = exparg.lastp;
1138 expmeta(expdir, str->text);
1140 if (exparg.lastp == savelastp) {
1145 *exparg.lastp = str;
1146 rmescapes(str->text);
1147 exparg.lastp = &str->next;
1149 *exparg.lastp = NULL;
1150 *savelastp = sp = expsort(*savelastp);
1151 while (sp->next != NULL)
1153 exparg.lastp = &sp->next;
1161 * Do metacharacter (i.e. *, ?, [...]) expansion.
1165 expmeta(char *enddir, char *name)
1182 for (p = name; esc = 0, *p; p += esc + 1) {
1183 if (*p == '*' || *p == '?')
1185 else if (*p == '[') {
1187 if (*q == '!' || *q == '^')
1190 while (*q == CTLQUOTEMARK)
1194 if (*q == '/' || *q == '\0')
1201 } else if (*p == '\0')
1203 else if (*p == CTLQUOTEMARK)
1208 if (p[esc] == '/') {
1211 start = p + esc + 1;
1215 if (metaflag == 0) { /* we've reached the end of the file name */
1216 if (enddir != expdir)
1218 for (p = name ; ; p++) {
1219 if (*p == CTLQUOTEMARK)
1226 if (enddir == expdir_end)
1229 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1233 endname = name + (p - name);
1234 if (start != name) {
1237 while (*p == CTLQUOTEMARK)
1242 if (enddir == expdir_end)
1246 if (enddir == expdir) {
1248 } else if (enddir == expdir + 1 && *expdir == '/') {
1254 if ((dirp = opendir(p)) == NULL)
1256 if (enddir != expdir)
1258 if (*endname == 0) {
1267 while (*p == CTLQUOTEMARK)
1273 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1274 if (dp->d_name[0] == '.' && ! matchdot)
1276 if (patmatch(start, dp->d_name, 0)) {
1277 namlen = dp->d_namlen;
1278 if (enddir + namlen + 1 > expdir_end)
1280 memcpy(enddir, dp->d_name, namlen + 1);
1284 if (dp->d_type != DT_UNKNOWN &&
1285 dp->d_type != DT_DIR &&
1286 dp->d_type != DT_LNK)
1288 if (enddir + namlen + 2 > expdir_end)
1290 enddir[namlen] = '/';
1291 enddir[namlen + 1] = '\0';
1292 expmeta(enddir + namlen + 1, endname);
1298 endname[-esc - 1] = esc ? CTLESC : '/';
1303 * Add a file name to the list.
1307 addfname(char *name)
1314 p = stalloc(len + 1);
1315 memcpy(p, name, len + 1);
1316 sp = (struct strlist *)stalloc(sizeof *sp);
1319 exparg.lastp = &sp->next;
1324 * Sort the results of file name expansion. It calculates the number of
1325 * strings to sort and then calls msort (short for merge sort) to do the
1329 static struct strlist *
1330 expsort(struct strlist *str)
1336 for (sp = str ; sp ; sp = sp->next)
1338 return msort(str, len);
1342 static struct strlist *
1343 msort(struct strlist *list, int len)
1345 struct strlist *p, *q = NULL;
1346 struct strlist **lpp;
1354 for (n = half ; --n >= 0 ; ) {
1358 q->next = NULL; /* terminate first half of list */
1359 q = msort(list, half); /* sort first half of list */
1360 p = msort(p, len - half); /* sort second half */
1363 if (strcmp(p->text, q->text) < 0) {
1366 if ((p = *lpp) == NULL) {
1373 if ((q = *lpp) == NULL) {
1385 get_wc(const char **p)
1390 chrlen = mbtowc(&c, *p, 4);
1393 else if (chrlen == -1)
1402 * See if a character matches a character class, starting at the first colon
1404 * If a valid character class is recognized, a pointer to the next character
1405 * after the final closing bracket is stored into *end, otherwise a null
1406 * pointer is stored into *end.
1409 match_charclass(const char *p, wchar_t chr, const char **end)
1412 const char *nameend;
1417 nameend = strstr(p, ":]");
1418 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1421 memcpy(name, p, nameend - p);
1422 name[nameend - p] = '\0';
1424 cclass = wctype(name);
1425 /* An unknown class matches nothing but is valid nevertheless. */
1428 return iswctype(chr, cclass);
1433 * Returns true if the pattern matches the string.
1437 patmatch(const char *pattern, const char *string, int squoted)
1439 const char *p, *q, *end;
1440 const char *bt_p, *bt_q;
1455 if (squoted && *q == CTLESC)
1463 if (squoted && *q == CTLESC)
1470 * A '?' does not match invalid UTF-8 but a
1471 * '*' does, so backtrack.
1476 wc = (unsigned char)*q++;
1480 while (c == CTLQUOTEMARK || c == '*')
1483 * If the pattern ends here, we know the string
1484 * matches without needing to look at the rest of it.
1489 * First try the shortest match for the '*' that
1490 * could work. We can forget any earlier '*' since
1491 * there is no way having it match more characters
1492 * can help us, given that we are already here.
1503 if (*endp == '!' || *endp == '^')
1506 while (*endp == CTLQUOTEMARK)
1509 goto dft; /* no matching ] */
1510 if (*endp == CTLESC)
1516 if (*p == '!' || *p == '^') {
1521 if (squoted && *q == CTLESC)
1530 chr = (unsigned char)*q++;
1533 if (c == CTLQUOTEMARK)
1535 if (c == '[' && *p == ':') {
1536 found |= match_charclass(p, chr, &end);
1542 if (localeisutf8 && c & 0x80) {
1545 if (wc == 0) /* bad utf-8 */
1548 wc = (unsigned char)c;
1549 if (*p == '-' && p[1] != ']') {
1551 while (*p == CTLQUOTEMARK)
1557 if (wc2 == 0) /* bad utf-8 */
1560 wc2 = (unsigned char)*p++;
1561 if ( collate_range_cmp(chr, wc) >= 0
1562 && collate_range_cmp(chr, wc2) <= 0
1569 } while ((c = *p++) != ']');
1570 if (found == invert)
1575 if (squoted && *q == CTLESC)
1583 * If we have a mismatch (other than hitting the end
1584 * of the string), go back to the last '*' seen and
1585 * have it match one additional character.
1589 if (squoted && *bt_q == CTLESC)
1604 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1608 rmescapes(char *str)
1613 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1619 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1633 * See if a pattern matches in a case statement.
1637 casematch(union node *pattern, const char *val)
1639 struct stackmark smark;
1643 setstackmark(&smark);
1644 argbackq = pattern->narg.backquote;
1645 STARTSTACKSTR(expdest);
1647 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1648 STPUTC('\0', expdest);
1649 p = grabstackstr(expdest);
1650 result = patmatch(p, val, 0);
1651 popstackmark(&smark);
1660 cvtnum(int num, char *buf)
1664 char *p = temp + 31;
1669 *--p = num % 10 + '0';
1670 } while ((num /= 10) != 0);
1680 * Do most of the work for wordexp(3).
1684 wordexpcmd(int argc, char **argv)
1689 out1fmt("%08x", argc - 1);
1690 for (i = 1, len = 0; i < argc; i++)
1691 len += strlen(argv[i]);
1692 out1fmt("%08x", (int)len);
1693 for (i = 1; i < argc; i++)
1694 outbin(argv[i], strlen(argv[i]) + 1, out1);