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: src/bin/sh/expand.c,v 1.89 2011/06/12 23:06:04 jilles Exp $
42 #include <sys/types.h>
57 * Routines to expand arguments to commands. We have to deal with
58 * backquotes, shell variables, and file metacharacters.
80 * Structure specifying which parts of the string should be searched
85 struct ifsregion *next; /* next region in list */
86 int begoff; /* offset of start of region */
87 int endoff; /* offset of end of region */
88 int inquotes; /* search for nul bytes only */
92 static char *expdest; /* output of current string */
93 static struct nodelist *argbackq; /* list of back quote expressions */
94 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
95 static struct ifsregion *ifslastp; /* last struct in list */
96 static struct arglist exparg; /* holds expanded arg list */
98 static void argstr(char *, int);
99 static char *exptilde(char *, int);
100 static void expbackq(union node *, int, int);
101 static int subevalvar(char *, char *, int, int, int, int, int);
102 static char *evalvar(char *, int);
103 static int varisset(char *, int);
104 static void varvalue(char *, int, int, int);
105 static void recordregion(int, int, int);
106 static void removerecordregions(int);
107 static void ifsbreakup(char *, struct arglist *);
108 static void expandmeta(struct strlist *, int);
109 static void expmeta(char *, char *);
110 static void addfname(char *);
111 static struct strlist *expsort(struct strlist *);
112 static struct strlist *msort(struct strlist *, int);
113 static char *cvtnum(int, char *);
114 static int collate_range_cmp(wchar_t, wchar_t);
117 collate_range_cmp(wchar_t c1, wchar_t c2)
119 static wchar_t s1[2], s2[2];
123 return (wcscoll(s1, s2));
127 * Expand shell variables and backquotes inside a here document.
128 * union node *arg the document
129 * int fd; where to write the expanded version
133 expandhere(union node *arg, int fd)
135 expandarg(arg, NULL, 0);
136 xwrite(fd, stackblock(), expdest - stackblock());
140 stputs_quotes(const char *data, const char *syntax, char *p)
144 if (syntax[(int)*data] == CCTL)
150 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
153 * Perform expansions on an argument, placing the resulting list of arguments
154 * in arglist. Parameter expansion, command substitution and arithmetic
155 * expansion are always performed; additional expansions can be requested
157 * The result is left in the stack string.
158 * When arglist is NULL, perform here document expansion.
160 * Caution: this function uses global state and is not reentrant.
161 * However, a new invocation after an interrupted invocation is safe
162 * and will reset the global state for the new call.
165 expandarg(union node *arg, struct arglist *arglist, int flag)
170 argbackq = arg->narg.backquote;
171 STARTSTACKSTR(expdest);
172 ifsfirst.next = NULL;
174 argstr(arg->narg.text, flag);
175 if (arglist == NULL) {
176 STACKSTRNUL(expdest);
177 return; /* here document expanded */
179 STPUTC('\0', expdest);
180 p = grabstackstr(expdest);
181 exparg.lastp = &exparg.list;
185 if (flag & EXP_FULL) {
186 ifsbreakup(p, &exparg);
187 *exparg.lastp = NULL;
188 exparg.lastp = &exparg.list;
189 expandmeta(exparg.list, flag);
191 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
193 sp = (struct strlist *)stalloc(sizeof (struct strlist));
196 exparg.lastp = &sp->next;
198 while (ifsfirst.next != NULL) {
199 struct ifsregion *ifsp;
201 ifsp = ifsfirst.next->next;
202 ckfree(ifsfirst.next);
203 ifsfirst.next = ifsp;
206 *exparg.lastp = NULL;
208 *arglist->lastp = exparg.list;
209 arglist->lastp = exparg.lastp;
216 * Perform parameter expansion, command substitution and arithmetic
217 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
218 * Processing ends at a CTLENDVAR character as well as '\0'.
219 * This is used to expand word in ${var+word} etc.
220 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
221 * characters to allow for further processing.
222 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
225 argstr(char *p, int flag)
228 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
233 split_lit = flag & EXP_SPLIT_LIT;
234 lit_quoted = flag & EXP_LIT_QUOTED;
235 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
236 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
237 p = exptilde(p, flag);
239 CHECKSTRSPACE(2, expdest);
246 /* "$@" syntax adherence hack */
247 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
249 if ((flag & EXP_FULL) != 0)
260 if (split_lit && !lit_quoted)
261 recordregion(expdest - stackblock() -
263 expdest - stackblock(), 0);
266 p = evalvar(p, flag);
269 case CTLBACKQ|CTLQUOTE:
270 expbackq(argbackq->n, c & CTLQUOTE, flag);
271 argbackq = argbackq->next;
279 * sort of a hack - expand tildes in variable
280 * assignments (after the first '=' and after ':'s).
283 if (split_lit && !lit_quoted)
284 recordregion(expdest - stackblock() - 1,
285 expdest - stackblock(), 0);
286 if (flag & EXP_VARTILDE && *p == '~' &&
287 (c != '=' || firsteq)) {
290 p = exptilde(p, flag);
295 if (split_lit && !lit_quoted)
296 recordregion(expdest - stackblock() - 1,
297 expdest - stackblock(), 0);
304 * Perform tilde expansion, placing the result in the stack string and
305 * returning the next position in the input string to process.
308 exptilde(char *p, int flag)
313 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
315 while ((c = *p) != '\0') {
317 case CTLESC: /* This means CTL* are always considered quoted. */
320 case CTLBACKQ | CTLQUOTE:
326 if (flag & EXP_VARTILDE)
337 if (*(startp+1) == '\0') {
338 if ((home = lookupvar("HOME")) == NULL)
341 if ((pw = getpwnam(startp+1)) == NULL)
349 STPUTS_QUOTES(home, SQSYNTAX, expdest);
351 STPUTS(home, expdest);
360 removerecordregions(int endoff)
362 if (ifslastp == NULL)
365 if (ifsfirst.endoff > endoff) {
366 while (ifsfirst.next != NULL) {
367 struct ifsregion *ifsp;
369 ifsp = ifsfirst.next->next;
370 ckfree(ifsfirst.next);
371 ifsfirst.next = ifsp;
374 if (ifsfirst.begoff > endoff)
377 ifslastp = &ifsfirst;
378 ifsfirst.endoff = endoff;
383 ifslastp = &ifsfirst;
384 while (ifslastp->next && ifslastp->next->begoff < endoff)
385 ifslastp=ifslastp->next;
386 while (ifslastp->next != NULL) {
387 struct ifsregion *ifsp;
389 ifsp = ifslastp->next->next;
390 ckfree(ifslastp->next);
391 ifslastp->next = ifsp;
394 if (ifslastp->endoff > endoff)
395 ifslastp->endoff = endoff;
399 * Expand arithmetic expression. Backup to start of expression,
400 * evaluate, place result in (backed up) result, adjust string position.
408 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
412 * This routine is slightly over-complicated for
413 * efficiency. First we make sure there is
414 * enough space for the result, which may be bigger
415 * than the expression. Next we
416 * scan backwards looking for the start of arithmetic. If the
417 * next previous character is a CTLESC character, then we
418 * have to rescan starting from the beginning since CTLESC
419 * characters have to be processed left to right.
421 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
422 USTPUTC('\0', expdest);
423 start = stackblock();
425 while (p >= start && *p != CTLARI)
427 if (p < start || *p != CTLARI)
428 error("missing CTLARI (shouldn't happen)");
429 if (p > start && *(p - 1) == CTLESC)
430 for (p = start; *p != CTLARI; p++)
439 removerecordregions(begoff);
442 q = grabstackstr(expdest);
444 ungrabstackstr(q, expdest);
445 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
449 recordregion(begoff, p - 1 - start, 0);
450 result = expdest - p + 1;
451 STADJUST(-result, expdest);
456 * Perform command substitution.
459 expbackq(union node *cmd, int quoted, int flag)
465 char *dest = expdest;
466 struct ifsregion saveifs, *savelastp;
467 struct nodelist *saveargbackq;
469 int startloc = dest - stackblock();
470 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
471 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
476 savelastp = ifslastp;
477 saveargbackq = argbackq;
478 p = grabstackstr(dest);
479 evalbackcmd(cmd, &in);
480 ungrabstackstr(p, dest);
482 ifslastp = savelastp;
483 argbackq = saveargbackq;
488 /* Don't copy trailing newlines */
490 if (--in.nleft < 0) {
493 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
494 TRACE(("expbackq: read returns %d\n", i));
505 CHECKSTRSPACE(nnl + 2, dest);
510 if (quotes && syntax[(int)lastc] == CCTL)
511 USTPUTC(CTLESC, dest);
512 USTPUTC(lastc, dest);
522 exitstatus = waitforjob(in.jp, NULL);
524 recordregion(startloc, dest - stackblock(), 0);
525 TRACE(("expbackq: size=%td: \"%.*s\"\n",
526 ((dest - stackblock()) - startloc),
527 (int)((dest - stackblock()) - startloc),
528 stackblock() + startloc));
536 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
537 int varflags, int quotes)
543 struct nodelist *saveargbackq = argbackq;
546 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
547 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
548 EXP_CASE : 0) | EXP_TILDE);
549 STACKSTRNUL(expdest);
550 argbackq = saveargbackq;
551 startp = stackblock() + startloc;
553 str = stackblock() + strloc;
557 setvar(str, startp, 0);
558 amount = startp - expdest;
559 STADJUST(amount, expdest);
564 if (*p != CTLENDVAR) {
565 outfmt(out2, "%s\n", startp);
568 error("%.*s: parameter %snot set", (int)(p - str - 1),
569 str, (varflags & VSNUL) ? "null or "
574 for (loc = startp; loc < str; loc++) {
577 if (patmatch(str, startp, quotes)) {
582 if (quotes && *loc == CTLESC)
588 for (loc = str - 1; loc >= startp;) {
591 if (patmatch(str, startp, quotes)) {
597 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
598 for (q = startp; q < loc; q++)
608 for (loc = str - 1; loc >= startp;) {
609 if (patmatch(str, loc, quotes)) {
610 amount = loc - expdest;
611 STADJUST(amount, expdest);
615 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
616 for (q = startp; q < loc; q++)
626 for (loc = startp; loc < str - 1; loc++) {
627 if (patmatch(str, loc, quotes)) {
628 amount = loc - expdest;
629 STADJUST(amount, expdest);
632 if (quotes && *loc == CTLESC)
643 amount = ((str - 1) - (loc - startp)) - expdest;
644 STADJUST(amount, expdest);
645 while (loc != str - 1)
652 * Expand a variable, and return a pointer to the next character in the
657 evalvar(char *p, int flag)
671 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
673 varflags = (unsigned char)*p++;
674 subtype = varflags & VSTYPE;
679 p = strchr(p, '=') + 1;
680 again: /* jump here after setting a variable with ${var=text} */
681 if (varflags & VSLINENO) {
685 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
687 } else if (special) {
688 set = varisset(var, varflags & VSNUL);
691 val = bltinlookup(var, 1);
692 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
699 startloc = expdest - stackblock();
700 if (!set && uflag && *var != '@' && *var != '*') {
708 error("%.*s: parameter not set", (int)(p - var - 1),
712 if (set && subtype != VSPLUS) {
713 /* insert the value of the variable */
715 varvalue(var, varflags & VSQUOTE, subtype, flag);
716 if (subtype == VSLENGTH) {
717 varlenb = expdest - stackblock() - startloc;
720 val = stackblock() + startloc;
721 for (;val != expdest; val++)
722 if ((*val & 0xC0) == 0x80)
725 STADJUST(-varlenb, expdest);
728 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
731 if (subtype == VSLENGTH) {
734 (*val & 0xC0) != 0x80)
739 STPUTS_QUOTES(val, syntax, expdest);
741 STPUTS(val, expdest);
747 if (subtype == VSPLUS)
750 easy = ((varflags & VSQUOTE) == 0 ||
751 (*var == '@' && shellparam.nparam != 1));
756 expdest = cvtnum(varlen, expdest);
763 recordregion(startloc, expdest - stackblock(),
764 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
765 (*var == '@' || *var == '*')));
771 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
772 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
786 * Terminate the string and start recording the pattern
789 STPUTC('\0', expdest);
790 patloc = expdest - stackblock();
791 if (subevalvar(p, NULL, patloc, subtype,
792 startloc, varflags, quotes) == 0) {
793 int amount = (expdest - stackblock() - patloc) + 1;
794 STADJUST(-amount, expdest);
796 /* Remove any recorded regions beyond start of variable */
797 removerecordregions(startloc);
803 if (subevalvar(p, var, 0, subtype, startloc, varflags,
807 * Remove any recorded regions beyond
810 removerecordregions(startloc);
821 error("${%.*s%s}: Bad substitution", c, var,
822 (c > 0 && *p != CTLENDVAR) ? "..." : "");
827 p[-1] = '='; /* recover overwritten '=' */
829 if (subtype != VSNORMAL) { /* skip to end of alternative */
832 if ((c = *p++) == CTLESC)
834 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
836 argbackq = argbackq->next;
837 } else if (c == CTLVAR) {
838 if ((*p++ & VSTYPE) != VSNORMAL)
840 } else if (c == CTLENDVAR) {
852 * Test whether a specialized variable is set.
856 varisset(char *name, int nulok)
860 return backgndpidset();
861 else if (*name == '@' || *name == '*') {
862 if (*shellparam.p == NULL)
868 for (av = shellparam.p; *av; av++)
873 } else if (is_digit(*name)) {
875 int num = atoi(name);
877 if (num > shellparam.nparam)
883 ap = shellparam.p[num - 1];
885 if (nulok && (ap == NULL || *ap == '\0'))
892 strtodest(const char *p, int flag, int subtype, int quoted)
894 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
895 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
901 * Add the value of a specialized variable to the stack string.
905 varvalue(char *name, int quoted, int subtype, int flag)
921 num = shellparam.nparam;
924 num = backgndpidval();
926 expdest = cvtnum(num, expdest);
929 for (i = 0 ; i < NOPTS ; i++) {
931 STPUTC(optlist[i].letter, expdest);
935 if (flag & EXP_FULL && quoted) {
936 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
937 strtodest(p, flag, subtype, quoted);
939 STPUTC('\0', expdest);
949 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
950 strtodest(p, flag, subtype, quoted);
953 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
954 STPUTC(sep, expdest);
959 strtodest(p, flag, subtype, quoted);
962 if (is_digit(*name)) {
964 if (num > 0 && num <= shellparam.nparam) {
965 p = shellparam.p[num - 1];
966 strtodest(p, flag, subtype, quoted);
976 * Record the fact that we have to scan this region of the
977 * string for IFS characters.
981 recordregion(int start, int end, int inquotes)
983 struct ifsregion *ifsp;
985 if (ifslastp == NULL) {
988 if (ifslastp->endoff == start
989 && ifslastp->inquotes == inquotes) {
990 /* extend previous area */
991 ifslastp->endoff = end;
994 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
995 ifslastp->next = ifsp;
998 ifslastp->next = NULL;
999 ifslastp->begoff = start;
1000 ifslastp->endoff = end;
1001 ifslastp->inquotes = inquotes;
1007 * Break the argument string into pieces based upon IFS and add the
1008 * strings to the argument list. The regions of the string to be
1009 * searched for IFS characters have been stored by recordregion.
1010 * CTLESC characters are preserved but have little effect in this pass
1011 * other than escaping CTL* characters. In particular, they do not escape
1012 * IFS characters: that should be done with the ifsregion mechanism.
1013 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1014 * This pass treats them as a regular character, making the string non-empty.
1015 * Later, they are removed along with the other CTL* characters.
1018 ifsbreakup(char *string, struct arglist *arglist)
1020 struct ifsregion *ifsp;
1027 int had_param_ch = 0;
1031 if (ifslastp == NULL) {
1032 /* Return entire argument, IFS doesn't apply to any of it */
1033 sp = (struct strlist *)stalloc(sizeof *sp);
1035 *arglist->lastp = sp;
1036 arglist->lastp = &sp->next;
1040 ifs = ifsset() ? ifsval() : " \t\n";
1042 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1043 p = string + ifsp->begoff;
1044 while (p < string + ifsp->endoff) {
1048 if (ifsp->inquotes) {
1049 /* Only NULs (should be from "$@") end args */
1057 if (!strchr(ifs, *p)) {
1062 ifsspc = strchr(" \t\n", *p);
1064 /* Ignore IFS whitespace at start */
1065 if (q == start && ifsspc != NULL) {
1073 /* Save this argument... */
1075 sp = (struct strlist *)stalloc(sizeof *sp);
1077 *arglist->lastp = sp;
1078 arglist->lastp = &sp->next;
1081 if (ifsspc != NULL) {
1082 /* Ignore further trailing IFS whitespace */
1083 for (; p < string + ifsp->endoff; p++) {
1087 if (strchr(ifs, *p) == NULL) {
1091 if (strchr(" \t\n", *p) == NULL) {
1102 * Save anything left as an argument.
1103 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1104 * generating 2 arguments, the second of which is empty.
1105 * Some recent clarification of the Posix spec say that it
1106 * should only generate one....
1108 if (had_param_ch || *start != 0) {
1109 sp = (struct strlist *)stalloc(sizeof *sp);
1111 *arglist->lastp = sp;
1112 arglist->lastp = &sp->next;
1117 static char expdir[PATH_MAX];
1118 #define expdir_end (expdir + sizeof(expdir))
1121 * Perform pathname generation and remove control characters.
1122 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1123 * The results are stored in the list exparg.
1126 expandmeta(struct strlist *str, int flag __unused)
1129 struct strlist **savelastp;
1132 /* TODO - EXP_REDIR */
1138 for (;;) { /* fast check for meta chars */
1139 if ((c = *p++) == '\0')
1141 if (c == '*' || c == '?' || c == '[')
1144 savelastp = exparg.lastp;
1146 expmeta(expdir, str->text);
1148 if (exparg.lastp == savelastp) {
1153 *exparg.lastp = str;
1154 rmescapes(str->text);
1155 exparg.lastp = &str->next;
1157 *exparg.lastp = NULL;
1158 *savelastp = sp = expsort(*savelastp);
1159 while (sp->next != NULL)
1161 exparg.lastp = &sp->next;
1169 * Do metacharacter (i.e. *, ?, [...]) expansion.
1173 expmeta(char *enddir, char *name)
1189 for (p = name; esc = 0, *p; p += esc + 1) {
1190 if (*p == '*' || *p == '?')
1192 else if (*p == '[') {
1194 if (*q == '!' || *q == '^')
1197 while (*q == CTLQUOTEMARK)
1201 if (*q == '/' || *q == '\0')
1208 } else if (*p == '\0')
1210 else if (*p == CTLQUOTEMARK)
1215 if (p[esc] == '/') {
1218 start = p + esc + 1;
1222 if (metaflag == 0) { /* we've reached the end of the file name */
1223 if (enddir != expdir)
1225 for (p = name ; ; p++) {
1226 if (*p == CTLQUOTEMARK)
1233 if (enddir == expdir_end)
1236 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1241 if (start != name) {
1244 while (*p == CTLQUOTEMARK)
1249 if (enddir == expdir_end)
1253 if (enddir == expdir) {
1254 p = __DECONST(char *, ".");
1255 } else if (enddir == expdir + 1 && *expdir == '/') {
1256 p = __DECONST(char *, "/");
1261 if ((dirp = opendir(p)) == NULL)
1263 if (enddir != expdir)
1265 if (*endname == 0) {
1274 while (*p == CTLQUOTEMARK)
1280 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1281 if (dp->d_name[0] == '.' && ! matchdot)
1283 if (patmatch(start, dp->d_name, 0)) {
1284 if (enddir + dp->d_namlen + 1 > expdir_end)
1286 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1290 if (enddir + dp->d_namlen + 2 > expdir_end)
1292 enddir[dp->d_namlen] = '/';
1293 enddir[dp->d_namlen + 1] = '\0';
1294 expmeta(enddir + dp->d_namlen + 1, endname);
1300 endname[-esc - 1] = esc ? CTLESC : '/';
1305 * Add a file name to the list.
1309 addfname(char *name)
1314 p = stalloc(strlen(name) + 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 * Returns true if the pattern matches the string.
1406 patmatch(const char *pattern, const char *string, int squoted)
1419 if (squoted && *q == CTLESC)
1427 if (squoted && *q == CTLESC)
1432 wc = (unsigned char)*q++;
1438 while (c == CTLQUOTEMARK || c == '*')
1440 if (c != CTLESC && c != CTLQUOTEMARK &&
1441 c != '?' && c != '*' && c != '[') {
1443 if (squoted && *q == CTLESC &&
1448 if (squoted && *q == CTLESC)
1454 if (patmatch(p, q, squoted))
1456 if (squoted && *q == CTLESC)
1458 } while (*q++ != '\0');
1466 if (*endp == '!' || *endp == '^')
1469 while (*endp == CTLQUOTEMARK)
1472 goto dft; /* no matching ] */
1473 if (*endp == CTLESC)
1479 if (*p == '!' || *p == '^') {
1484 if (squoted && *q == CTLESC)
1489 chr = (unsigned char)*q++;
1494 if (c == CTLQUOTEMARK)
1498 if (localeisutf8 && c & 0x80) {
1501 if (wc == 0) /* bad utf-8 */
1504 wc = (unsigned char)c;
1505 if (*p == '-' && p[1] != ']') {
1507 while (*p == CTLQUOTEMARK)
1513 if (wc2 == 0) /* bad utf-8 */
1516 wc2 = (unsigned char)*p++;
1517 if ( collate_range_cmp(chr, wc) >= 0
1518 && collate_range_cmp(chr, wc2) <= 0
1525 } while ((c = *p++) != ']');
1526 if (found == invert)
1531 if (squoted && *q == CTLESC)
1547 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1551 rmescapes(char *str)
1556 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1562 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1576 * See if a pattern matches in a case statement.
1580 casematch(union node *pattern, const char *val)
1582 struct stackmark smark;
1586 setstackmark(&smark);
1587 argbackq = pattern->narg.backquote;
1588 STARTSTACKSTR(expdest);
1590 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1591 STPUTC('\0', expdest);
1592 p = grabstackstr(expdest);
1593 result = patmatch(p, val, 0);
1594 popstackmark(&smark);
1603 cvtnum(int num, char *buf)
1607 char *p = temp + 31;
1612 *--p = num % 10 + '0';
1613 } while ((num /= 10) != 0);
1623 * Do most of the work for wordexp(3).
1627 wordexpcmd(int argc, char **argv)
1632 out1fmt("%08x", argc - 1);
1633 for (i = 1, len = 0; i < argc; i++)
1634 len += strlen(argv[i]);
1635 out1fmt("%08x", (int)len);
1636 for (i = 1; i < argc; i++)
1637 outbin(argv[i], strlen(argv[i]) + 1, out1);