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.90 2011/06/13 21:03:27 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.
81 * Structure specifying which parts of the string should be searched
86 struct ifsregion *next; /* next region in list */
87 int begoff; /* offset of start of region */
88 int endoff; /* offset of end of region */
89 int inquotes; /* search for nul bytes only */
93 static char *expdest; /* output of current string */
94 static struct nodelist *argbackq; /* list of back quote expressions */
95 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
96 static struct ifsregion *ifslastp; /* last struct in list */
97 static struct arglist exparg; /* holds expanded arg list */
99 static void argstr(char *, int);
100 static char *exptilde(char *, int);
101 static void expbackq(union node *, int, int);
102 static int subevalvar(char *, char *, int, int, int, int, int);
103 static char *evalvar(char *, int);
104 static int varisset(char *, int);
105 static void varvalue(char *, int, int, int);
106 static void recordregion(int, int, int);
107 static void removerecordregions(int);
108 static void ifsbreakup(char *, struct arglist *);
109 static void expandmeta(struct strlist *, int);
110 static void expmeta(char *, char *);
111 static void addfname(char *);
112 static struct strlist *expsort(struct strlist *);
113 static struct strlist *msort(struct strlist *, int);
114 static char *cvtnum(int, char *);
115 static int collate_range_cmp(wchar_t, wchar_t);
118 collate_range_cmp(wchar_t c1, wchar_t c2)
120 static wchar_t s1[2], s2[2];
124 return (wcscoll(s1, s2));
128 * Expand shell variables and backquotes inside a here document.
129 * union node *arg the document
130 * int fd; where to write the expanded version
134 expandhere(union node *arg, int fd)
136 expandarg(arg, NULL, 0);
137 xwrite(fd, stackblock(), expdest - stackblock());
141 stputs_quotes(const char *data, const char *syntax, char *p)
145 if (syntax[(int)*data] == CCTL)
151 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
154 * Perform expansions on an argument, placing the resulting list of arguments
155 * in arglist. Parameter expansion, command substitution and arithmetic
156 * expansion are always performed; additional expansions can be requested
158 * The result is left in the stack string.
159 * When arglist is NULL, perform here document expansion.
161 * Caution: this function uses global state and is not reentrant.
162 * However, a new invocation after an interrupted invocation is safe
163 * and will reset the global state for the new call.
166 expandarg(union node *arg, struct arglist *arglist, int flag)
171 argbackq = arg->narg.backquote;
172 STARTSTACKSTR(expdest);
173 ifsfirst.next = NULL;
175 argstr(arg->narg.text, flag);
176 if (arglist == NULL) {
177 STACKSTRNUL(expdest);
178 return; /* here document expanded */
180 STPUTC('\0', expdest);
181 p = grabstackstr(expdest);
182 exparg.lastp = &exparg.list;
186 if (flag & EXP_FULL) {
187 ifsbreakup(p, &exparg);
188 *exparg.lastp = NULL;
189 exparg.lastp = &exparg.list;
190 expandmeta(exparg.list, flag);
192 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
194 sp = (struct strlist *)stalloc(sizeof (struct strlist));
197 exparg.lastp = &sp->next;
199 while (ifsfirst.next != NULL) {
200 struct ifsregion *ifsp;
202 ifsp = ifsfirst.next->next;
203 ckfree(ifsfirst.next);
204 ifsfirst.next = ifsp;
207 *exparg.lastp = NULL;
209 *arglist->lastp = exparg.list;
210 arglist->lastp = exparg.lastp;
217 * Perform parameter expansion, command substitution and arithmetic
218 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
219 * Processing ends at a CTLENDVAR character as well as '\0'.
220 * This is used to expand word in ${var+word} etc.
221 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
222 * characters to allow for further processing.
223 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
226 argstr(char *p, int flag)
229 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
234 split_lit = flag & EXP_SPLIT_LIT;
235 lit_quoted = flag & EXP_LIT_QUOTED;
236 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
237 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
238 p = exptilde(p, flag);
240 CHECKSTRSPACE(2, expdest);
247 /* "$@" syntax adherence hack */
248 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
250 if ((flag & EXP_FULL) != 0)
261 if (split_lit && !lit_quoted)
262 recordregion(expdest - stackblock() -
264 expdest - stackblock(), 0);
267 p = evalvar(p, flag);
270 case CTLBACKQ|CTLQUOTE:
271 expbackq(argbackq->n, c & CTLQUOTE, flag);
272 argbackq = argbackq->next;
280 * sort of a hack - expand tildes in variable
281 * assignments (after the first '=' and after ':'s).
284 if (split_lit && !lit_quoted)
285 recordregion(expdest - stackblock() - 1,
286 expdest - stackblock(), 0);
287 if (flag & EXP_VARTILDE && *p == '~' &&
288 (c != '=' || firsteq)) {
291 p = exptilde(p, flag);
296 if (split_lit && !lit_quoted)
297 recordregion(expdest - stackblock() - 1,
298 expdest - stackblock(), 0);
305 * Perform tilde expansion, placing the result in the stack string and
306 * returning the next position in the input string to process.
309 exptilde(char *p, int flag)
314 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
316 while ((c = *p) != '\0') {
318 case CTLESC: /* This means CTL* are always considered quoted. */
321 case CTLBACKQ | CTLQUOTE:
327 if (flag & EXP_VARTILDE)
338 if (*(startp+1) == '\0') {
339 if ((home = lookupvar("HOME")) == NULL)
342 if ((pw = getpwnam(startp+1)) == NULL)
350 STPUTS_QUOTES(home, SQSYNTAX, expdest);
352 STPUTS(home, expdest);
361 removerecordregions(int endoff)
363 if (ifslastp == NULL)
366 if (ifsfirst.endoff > endoff) {
367 while (ifsfirst.next != NULL) {
368 struct ifsregion *ifsp;
370 ifsp = ifsfirst.next->next;
371 ckfree(ifsfirst.next);
372 ifsfirst.next = ifsp;
375 if (ifsfirst.begoff > endoff)
378 ifslastp = &ifsfirst;
379 ifsfirst.endoff = endoff;
384 ifslastp = &ifsfirst;
385 while (ifslastp->next && ifslastp->next->begoff < endoff)
386 ifslastp=ifslastp->next;
387 while (ifslastp->next != NULL) {
388 struct ifsregion *ifsp;
390 ifsp = ifslastp->next->next;
391 ckfree(ifslastp->next);
392 ifslastp->next = ifsp;
395 if (ifslastp->endoff > endoff)
396 ifslastp->endoff = endoff;
400 * Expand arithmetic expression. Backup to start of expression,
401 * evaluate, place result in (backed up) result, adjust string position.
409 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
413 * This routine is slightly over-complicated for
414 * efficiency. First we make sure there is
415 * enough space for the result, which may be bigger
416 * than the expression. Next we
417 * scan backwards looking for the start of arithmetic. If the
418 * next previous character is a CTLESC character, then we
419 * have to rescan starting from the beginning since CTLESC
420 * characters have to be processed left to right.
422 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
423 USTPUTC('\0', expdest);
424 start = stackblock();
426 while (p >= start && *p != CTLARI)
428 if (p < start || *p != CTLARI)
429 error("missing CTLARI (shouldn't happen)");
430 if (p > start && *(p - 1) == CTLESC)
431 for (p = start; *p != CTLARI; p++)
440 removerecordregions(begoff);
443 q = grabstackstr(expdest);
445 ungrabstackstr(q, expdest);
446 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
450 recordregion(begoff, p - 1 - start, 0);
451 result = expdest - p + 1;
452 STADJUST(-result, expdest);
457 * Perform command substitution.
460 expbackq(union node *cmd, int quoted, int flag)
466 char *dest = expdest;
467 struct ifsregion saveifs, *savelastp;
468 struct nodelist *saveargbackq;
470 int startloc = dest - stackblock();
471 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
472 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
477 savelastp = ifslastp;
478 saveargbackq = argbackq;
479 p = grabstackstr(dest);
480 evalbackcmd(cmd, &in);
481 ungrabstackstr(p, dest);
483 ifslastp = savelastp;
484 argbackq = saveargbackq;
489 /* Don't copy trailing newlines */
491 if (--in.nleft < 0) {
494 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
495 TRACE(("expbackq: read returns %d\n", i));
506 CHECKSTRSPACE(nnl + 2, dest);
511 if (quotes && syntax[(int)lastc] == CCTL)
512 USTPUTC(CTLESC, dest);
513 USTPUTC(lastc, dest);
523 exitstatus = waitforjob(in.jp, NULL);
525 recordregion(startloc, dest - stackblock(), 0);
526 TRACE(("expbackq: size=%td: \"%.*s\"\n",
527 ((dest - stackblock()) - startloc),
528 (int)((dest - stackblock()) - startloc),
529 stackblock() + startloc));
537 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
538 int varflags, int quotes)
544 struct nodelist *saveargbackq = argbackq;
547 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
548 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
549 EXP_CASE : 0) | EXP_TILDE);
550 STACKSTRNUL(expdest);
551 argbackq = saveargbackq;
552 startp = stackblock() + startloc;
554 str = stackblock() + strloc;
558 setvar(str, startp, 0);
559 amount = startp - expdest;
560 STADJUST(amount, expdest);
565 if (*p != CTLENDVAR) {
566 outfmt(out2, "%s\n", startp);
569 error("%.*s: parameter %snot set", (int)(p - str - 1),
570 str, (varflags & VSNUL) ? "null or "
575 for (loc = startp; loc < str; loc++) {
578 if (patmatch(str, startp, quotes)) {
583 if (quotes && *loc == CTLESC)
589 for (loc = str - 1; loc >= startp;) {
592 if (patmatch(str, startp, quotes)) {
598 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
599 for (q = startp; q < loc; q++)
609 for (loc = str - 1; loc >= startp;) {
610 if (patmatch(str, loc, quotes)) {
611 amount = loc - expdest;
612 STADJUST(amount, expdest);
616 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
617 for (q = startp; q < loc; q++)
627 for (loc = startp; loc < str - 1; loc++) {
628 if (patmatch(str, loc, quotes)) {
629 amount = loc - expdest;
630 STADJUST(amount, expdest);
633 if (quotes && *loc == CTLESC)
644 amount = ((str - 1) - (loc - startp)) - expdest;
645 STADJUST(amount, expdest);
646 while (loc != str - 1)
653 * Expand a variable, and return a pointer to the next character in the
658 evalvar(char *p, int flag)
672 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
674 varflags = (unsigned char)*p++;
675 subtype = varflags & VSTYPE;
680 p = strchr(p, '=') + 1;
681 again: /* jump here after setting a variable with ${var=text} */
682 if (varflags & VSLINENO) {
686 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
688 } else if (special) {
689 set = varisset(var, varflags & VSNUL);
692 val = bltinlookup(var, 1);
693 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
700 startloc = expdest - stackblock();
701 if (!set && uflag && *var != '@' && *var != '*') {
709 error("%.*s: parameter not set", (int)(p - var - 1),
713 if (set && subtype != VSPLUS) {
714 /* insert the value of the variable */
716 varvalue(var, varflags & VSQUOTE, subtype, flag);
717 if (subtype == VSLENGTH) {
718 varlenb = expdest - stackblock() - startloc;
721 val = stackblock() + startloc;
722 for (;val != expdest; val++)
723 if ((*val & 0xC0) == 0x80)
726 STADJUST(-varlenb, expdest);
729 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
732 if (subtype == VSLENGTH) {
735 (*val & 0xC0) != 0x80)
740 STPUTS_QUOTES(val, syntax, expdest);
742 STPUTS(val, expdest);
748 if (subtype == VSPLUS)
751 easy = ((varflags & VSQUOTE) == 0 ||
752 (*var == '@' && shellparam.nparam != 1));
757 expdest = cvtnum(varlen, expdest);
764 recordregion(startloc, expdest - stackblock(),
765 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
766 (*var == '@' || *var == '*')));
772 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
773 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
787 * Terminate the string and start recording the pattern
790 STPUTC('\0', expdest);
791 patloc = expdest - stackblock();
792 if (subevalvar(p, NULL, patloc, subtype,
793 startloc, varflags, quotes) == 0) {
794 int amount = (expdest - stackblock() - patloc) + 1;
795 STADJUST(-amount, expdest);
797 /* Remove any recorded regions beyond start of variable */
798 removerecordregions(startloc);
804 if (subevalvar(p, var, 0, subtype, startloc, varflags,
808 * Remove any recorded regions beyond
811 removerecordregions(startloc);
822 error("${%.*s%s}: Bad substitution", c, var,
823 (c > 0 && *p != CTLENDVAR) ? "..." : "");
828 p[-1] = '='; /* recover overwritten '=' */
830 if (subtype != VSNORMAL) { /* skip to end of alternative */
833 if ((c = *p++) == CTLESC)
835 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
837 argbackq = argbackq->next;
838 } else if (c == CTLVAR) {
839 if ((*p++ & VSTYPE) != VSNORMAL)
841 } else if (c == CTLENDVAR) {
853 * Test whether a specialized variable is set.
857 varisset(char *name, int nulok)
861 return backgndpidset();
862 else if (*name == '@' || *name == '*') {
863 if (*shellparam.p == NULL)
869 for (av = shellparam.p; *av; av++)
874 } else if (is_digit(*name)) {
876 int num = atoi(name);
878 if (num > shellparam.nparam)
884 ap = shellparam.p[num - 1];
886 if (nulok && (ap == NULL || *ap == '\0'))
893 strtodest(const char *p, int flag, int subtype, int quoted)
895 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
896 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
902 * Add the value of a specialized variable to the stack string.
906 varvalue(char *name, int quoted, int subtype, int flag)
922 num = shellparam.nparam;
925 num = backgndpidval();
927 expdest = cvtnum(num, expdest);
930 for (i = 0 ; i < NOPTS ; i++) {
932 STPUTC(optlist[i].letter, expdest);
936 if (flag & EXP_FULL && quoted) {
937 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
938 strtodest(p, flag, subtype, quoted);
940 STPUTC('\0', expdest);
950 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
951 strtodest(p, flag, subtype, quoted);
954 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
955 STPUTC(sep, expdest);
960 strtodest(p, flag, subtype, quoted);
963 if (is_digit(*name)) {
965 if (num > 0 && num <= shellparam.nparam) {
966 p = shellparam.p[num - 1];
967 strtodest(p, flag, subtype, quoted);
977 * Record the fact that we have to scan this region of the
978 * string for IFS characters.
982 recordregion(int start, int end, int inquotes)
984 struct ifsregion *ifsp;
986 if (ifslastp == NULL) {
989 if (ifslastp->endoff == start
990 && ifslastp->inquotes == inquotes) {
991 /* extend previous area */
992 ifslastp->endoff = end;
995 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
996 ifslastp->next = ifsp;
999 ifslastp->next = NULL;
1000 ifslastp->begoff = start;
1001 ifslastp->endoff = end;
1002 ifslastp->inquotes = inquotes;
1008 * Break the argument string into pieces based upon IFS and add the
1009 * strings to the argument list. The regions of the string to be
1010 * searched for IFS characters have been stored by recordregion.
1011 * CTLESC characters are preserved but have little effect in this pass
1012 * other than escaping CTL* characters. In particular, they do not escape
1013 * IFS characters: that should be done with the ifsregion mechanism.
1014 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1015 * This pass treats them as a regular character, making the string non-empty.
1016 * Later, they are removed along with the other CTL* characters.
1019 ifsbreakup(char *string, struct arglist *arglist)
1021 struct ifsregion *ifsp;
1028 int had_param_ch = 0;
1032 if (ifslastp == NULL) {
1033 /* Return entire argument, IFS doesn't apply to any of it */
1034 sp = (struct strlist *)stalloc(sizeof *sp);
1036 *arglist->lastp = sp;
1037 arglist->lastp = &sp->next;
1041 ifs = ifsset() ? ifsval() : " \t\n";
1043 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1044 p = string + ifsp->begoff;
1045 while (p < string + ifsp->endoff) {
1049 if (ifsp->inquotes) {
1050 /* Only NULs (should be from "$@") end args */
1058 if (!strchr(ifs, *p)) {
1063 ifsspc = strchr(" \t\n", *p);
1065 /* Ignore IFS whitespace at start */
1066 if (q == start && ifsspc != NULL) {
1074 /* Save this argument... */
1076 sp = (struct strlist *)stalloc(sizeof *sp);
1078 *arglist->lastp = sp;
1079 arglist->lastp = &sp->next;
1082 if (ifsspc != NULL) {
1083 /* Ignore further trailing IFS whitespace */
1084 for (; p < string + ifsp->endoff; p++) {
1088 if (strchr(ifs, *p) == NULL) {
1092 if (strchr(" \t\n", *p) == NULL) {
1103 * Save anything left as an argument.
1104 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1105 * generating 2 arguments, the second of which is empty.
1106 * Some recent clarification of the Posix spec say that it
1107 * should only generate one....
1109 if (had_param_ch || *start != 0) {
1110 sp = (struct strlist *)stalloc(sizeof *sp);
1112 *arglist->lastp = sp;
1113 arglist->lastp = &sp->next;
1118 static char expdir[PATH_MAX];
1119 #define expdir_end (expdir + sizeof(expdir))
1122 * Perform pathname generation and remove control characters.
1123 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1124 * The results are stored in the list exparg.
1127 expandmeta(struct strlist *str, int flag __unused)
1130 struct strlist **savelastp;
1133 /* TODO - EXP_REDIR */
1139 for (;;) { /* fast check for meta chars */
1140 if ((c = *p++) == '\0')
1142 if (c == '*' || c == '?' || c == '[')
1145 savelastp = exparg.lastp;
1147 expmeta(expdir, str->text);
1149 if (exparg.lastp == savelastp) {
1154 *exparg.lastp = str;
1155 rmescapes(str->text);
1156 exparg.lastp = &str->next;
1158 *exparg.lastp = NULL;
1159 *savelastp = sp = expsort(*savelastp);
1160 while (sp->next != NULL)
1162 exparg.lastp = &sp->next;
1170 * Do metacharacter (i.e. *, ?, [...]) expansion.
1174 expmeta(char *enddir, char *name)
1190 for (p = name; esc = 0, *p; p += esc + 1) {
1191 if (*p == '*' || *p == '?')
1193 else if (*p == '[') {
1195 if (*q == '!' || *q == '^')
1198 while (*q == CTLQUOTEMARK)
1202 if (*q == '/' || *q == '\0')
1209 } else if (*p == '\0')
1211 else if (*p == CTLQUOTEMARK)
1216 if (p[esc] == '/') {
1219 start = p + esc + 1;
1223 if (metaflag == 0) { /* we've reached the end of the file name */
1224 if (enddir != expdir)
1226 for (p = name ; ; p++) {
1227 if (*p == CTLQUOTEMARK)
1234 if (enddir == expdir_end)
1237 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1242 if (start != name) {
1245 while (*p == CTLQUOTEMARK)
1250 if (enddir == expdir_end)
1254 if (enddir == expdir) {
1255 p = __DECONST(char *, ".");
1256 } else if (enddir == expdir + 1 && *expdir == '/') {
1257 p = __DECONST(char *, "/");
1262 if ((dirp = opendir(p)) == NULL)
1264 if (enddir != expdir)
1266 if (*endname == 0) {
1275 while (*p == CTLQUOTEMARK)
1281 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1282 if (dp->d_name[0] == '.' && ! matchdot)
1284 if (patmatch(start, dp->d_name, 0)) {
1285 if (enddir + dp->d_namlen + 1 > expdir_end)
1287 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1291 if (enddir + dp->d_namlen + 2 > expdir_end)
1293 enddir[dp->d_namlen] = '/';
1294 enddir[dp->d_namlen + 1] = '\0';
1295 expmeta(enddir + dp->d_namlen + 1, endname);
1301 endname[-esc - 1] = esc ? CTLESC : '/';
1306 * Add a file name to the list.
1310 addfname(char *name)
1315 p = stalloc(strlen(name) + 1);
1317 sp = (struct strlist *)stalloc(sizeof *sp);
1320 exparg.lastp = &sp->next;
1325 * Sort the results of file name expansion. It calculates the number of
1326 * strings to sort and then calls msort (short for merge sort) to do the
1330 static struct strlist *
1331 expsort(struct strlist *str)
1337 for (sp = str ; sp ; sp = sp->next)
1339 return msort(str, len);
1343 static struct strlist *
1344 msort(struct strlist *list, int len)
1346 struct strlist *p, *q = NULL;
1347 struct strlist **lpp;
1355 for (n = half ; --n >= 0 ; ) {
1359 q->next = NULL; /* terminate first half of list */
1360 q = msort(list, half); /* sort first half of list */
1361 p = msort(p, len - half); /* sort second half */
1364 if (strcmp(p->text, q->text) < 0) {
1367 if ((p = *lpp) == NULL) {
1374 if ((q = *lpp) == NULL) {
1386 get_wc(const char **p)
1391 chrlen = mbtowc(&c, *p, 4);
1394 else if (chrlen == -1)
1403 * Returns true if the pattern matches the string.
1407 patmatch(const char *pattern, const char *string, int squoted)
1420 if (squoted && *q == CTLESC)
1428 if (squoted && *q == CTLESC)
1433 wc = (unsigned char)*q++;
1439 while (c == CTLQUOTEMARK || c == '*')
1441 if (c != CTLESC && c != CTLQUOTEMARK &&
1442 c != '?' && c != '*' && c != '[') {
1444 if (squoted && *q == CTLESC &&
1449 if (squoted && *q == CTLESC)
1455 if (patmatch(p, q, squoted))
1457 if (squoted && *q == CTLESC)
1459 } while (*q++ != '\0');
1467 if (*endp == '!' || *endp == '^')
1470 while (*endp == CTLQUOTEMARK)
1473 goto dft; /* no matching ] */
1474 if (*endp == CTLESC)
1480 if (*p == '!' || *p == '^') {
1485 if (squoted && *q == CTLESC)
1490 chr = (unsigned char)*q++;
1495 if (c == CTLQUOTEMARK)
1499 if (localeisutf8 && c & 0x80) {
1502 if (wc == 0) /* bad utf-8 */
1505 wc = (unsigned char)c;
1506 if (*p == '-' && p[1] != ']') {
1508 while (*p == CTLQUOTEMARK)
1514 if (wc2 == 0) /* bad utf-8 */
1517 wc2 = (unsigned char)*p++;
1518 if ( collate_range_cmp(chr, wc) >= 0
1519 && collate_range_cmp(chr, wc2) <= 0
1526 } while ((c = *p++) != ']');
1527 if (found == invert)
1532 if (squoted && *q == CTLESC)
1548 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1552 rmescapes(char *str)
1557 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1563 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1577 * See if a pattern matches in a case statement.
1581 casematch(union node *pattern, const char *val)
1583 struct stackmark smark;
1587 setstackmark(&smark);
1588 argbackq = pattern->narg.backquote;
1589 STARTSTACKSTR(expdest);
1591 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1592 STPUTC('\0', expdest);
1593 p = grabstackstr(expdest);
1594 result = patmatch(p, val, 0);
1595 popstackmark(&smark);
1604 cvtnum(int num, char *buf)
1608 char *p = temp + 31;
1613 *--p = num % 10 + '0';
1614 } while ((num /= 10) != 0);
1624 * Do most of the work for wordexp(3).
1628 wordexpcmd(int argc, char **argv)
1633 out1fmt("%08x", argc - 1);
1634 for (i = 1, len = 0; i < argc; i++)
1635 len += strlen(argv[i]);
1636 out1fmt("%08x", (int)len);
1637 for (i = 1; i < argc; i++)
1638 outbin(argv[i], strlen(argv[i]) + 1, out1);