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.91 2011/06/15 21:48:10 jilles Exp $
42 #include <sys/types.h>
58 * Routines to expand arguments to commands. We have to deal with
59 * backquotes, shell variables, and file metacharacters.
82 * Structure specifying which parts of the string should be searched
87 struct ifsregion *next; /* next region in list */
88 int begoff; /* offset of start of region */
89 int endoff; /* offset of end of region */
90 int inquotes; /* search for nul bytes only */
94 static char *expdest; /* output of current string */
95 static struct nodelist *argbackq; /* list of back quote expressions */
96 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
97 static struct ifsregion *ifslastp; /* last struct in list */
98 static struct arglist exparg; /* holds expanded arg list */
100 static void argstr(char *, int);
101 static char *exptilde(char *, int);
102 static void expbackq(union node *, int, int);
103 static int subevalvar(char *, char *, int, int, int, int, int);
104 static char *evalvar(char *, int);
105 static int varisset(char *, int);
106 static void varvalue(char *, int, int, int);
107 static void recordregion(int, int, int);
108 static void removerecordregions(int);
109 static void ifsbreakup(char *, struct arglist *);
110 static void expandmeta(struct strlist *, int);
111 static void expmeta(char *, char *);
112 static void addfname(char *);
113 static struct strlist *expsort(struct strlist *);
114 static struct strlist *msort(struct strlist *, int);
115 static char *cvtnum(int, char *);
116 static int collate_range_cmp(wchar_t, wchar_t);
119 collate_range_cmp(wchar_t c1, wchar_t c2)
121 static wchar_t s1[2], s2[2];
125 return (wcscoll(s1, s2));
129 * Expand shell variables and backquotes inside a here document.
130 * union node *arg the document
131 * int fd; where to write the expanded version
135 expandhere(union node *arg, int fd)
137 expandarg(arg, NULL, 0);
138 xwrite(fd, stackblock(), expdest - stackblock());
142 stputs_quotes(const char *data, const char *syntax, char *p)
146 if (syntax[(int)*data] == CCTL)
152 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
155 * Perform expansions on an argument, placing the resulting list of arguments
156 * in arglist. Parameter expansion, command substitution and arithmetic
157 * expansion are always performed; additional expansions can be requested
159 * The result is left in the stack string.
160 * When arglist is NULL, perform here document expansion.
162 * Caution: this function uses global state and is not reentrant.
163 * However, a new invocation after an interrupted invocation is safe
164 * and will reset the global state for the new call.
167 expandarg(union node *arg, struct arglist *arglist, int flag)
172 argbackq = arg->narg.backquote;
173 STARTSTACKSTR(expdest);
174 ifsfirst.next = NULL;
176 argstr(arg->narg.text, flag);
177 if (arglist == NULL) {
178 STACKSTRNUL(expdest);
179 return; /* here document expanded */
181 STPUTC('\0', expdest);
182 p = grabstackstr(expdest);
183 exparg.lastp = &exparg.list;
187 if (flag & EXP_FULL) {
188 ifsbreakup(p, &exparg);
189 *exparg.lastp = NULL;
190 exparg.lastp = &exparg.list;
191 expandmeta(exparg.list, flag);
193 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
195 sp = (struct strlist *)stalloc(sizeof (struct strlist));
198 exparg.lastp = &sp->next;
200 while (ifsfirst.next != NULL) {
201 struct ifsregion *ifsp;
203 ifsp = ifsfirst.next->next;
204 ckfree(ifsfirst.next);
205 ifsfirst.next = ifsp;
208 *exparg.lastp = NULL;
210 *arglist->lastp = exparg.list;
211 arglist->lastp = exparg.lastp;
218 * Perform parameter expansion, command substitution and arithmetic
219 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
220 * Processing ends at a CTLENDVAR character as well as '\0'.
221 * This is used to expand word in ${var+word} etc.
222 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
223 * characters to allow for further processing.
224 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
227 argstr(char *p, int flag)
230 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
235 split_lit = flag & EXP_SPLIT_LIT;
236 lit_quoted = flag & EXP_LIT_QUOTED;
237 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
238 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
239 p = exptilde(p, flag);
241 CHECKSTRSPACE(2, expdest);
248 /* "$@" syntax adherence hack */
249 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
251 if ((flag & EXP_FULL) != 0)
262 if (split_lit && !lit_quoted)
263 recordregion(expdest - stackblock() -
265 expdest - stackblock(), 0);
268 p = evalvar(p, flag);
271 case CTLBACKQ|CTLQUOTE:
272 expbackq(argbackq->n, c & CTLQUOTE, flag);
273 argbackq = argbackq->next;
281 * sort of a hack - expand tildes in variable
282 * assignments (after the first '=' and after ':'s).
285 if (split_lit && !lit_quoted)
286 recordregion(expdest - stackblock() - 1,
287 expdest - stackblock(), 0);
288 if (flag & EXP_VARTILDE && *p == '~' &&
289 (c != '=' || firsteq)) {
292 p = exptilde(p, flag);
297 if (split_lit && !lit_quoted)
298 recordregion(expdest - stackblock() - 1,
299 expdest - stackblock(), 0);
306 * Perform tilde expansion, placing the result in the stack string and
307 * returning the next position in the input string to process.
310 exptilde(char *p, int flag)
315 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
317 while ((c = *p) != '\0') {
319 case CTLESC: /* This means CTL* are always considered quoted. */
322 case CTLBACKQ | CTLQUOTE:
328 if (flag & EXP_VARTILDE)
339 if (*(startp+1) == '\0') {
340 if ((home = lookupvar("HOME")) == NULL)
343 if ((pw = getpwnam(startp+1)) == NULL)
351 STPUTS_QUOTES(home, SQSYNTAX, expdest);
353 STPUTS(home, expdest);
362 removerecordregions(int endoff)
364 if (ifslastp == NULL)
367 if (ifsfirst.endoff > endoff) {
368 while (ifsfirst.next != NULL) {
369 struct ifsregion *ifsp;
371 ifsp = ifsfirst.next->next;
372 ckfree(ifsfirst.next);
373 ifsfirst.next = ifsp;
376 if (ifsfirst.begoff > endoff)
379 ifslastp = &ifsfirst;
380 ifsfirst.endoff = endoff;
385 ifslastp = &ifsfirst;
386 while (ifslastp->next && ifslastp->next->begoff < endoff)
387 ifslastp=ifslastp->next;
388 while (ifslastp->next != NULL) {
389 struct ifsregion *ifsp;
391 ifsp = ifslastp->next->next;
392 ckfree(ifslastp->next);
393 ifslastp->next = ifsp;
396 if (ifslastp->endoff > endoff)
397 ifslastp->endoff = endoff;
401 * Expand arithmetic expression. Backup to start of expression,
402 * evaluate, place result in (backed up) result, adjust string position.
410 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
414 * This routine is slightly over-complicated for
415 * efficiency. First we make sure there is
416 * enough space for the result, which may be bigger
417 * than the expression. Next we
418 * scan backwards looking for the start of arithmetic. If the
419 * next previous character is a CTLESC character, then we
420 * have to rescan starting from the beginning since CTLESC
421 * characters have to be processed left to right.
423 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
424 USTPUTC('\0', expdest);
425 start = stackblock();
427 while (p >= start && *p != CTLARI)
429 if (p < start || *p != CTLARI)
430 error("missing CTLARI (shouldn't happen)");
431 if (p > start && *(p - 1) == CTLESC)
432 for (p = start; *p != CTLARI; p++)
441 removerecordregions(begoff);
444 q = grabstackstr(expdest);
446 ungrabstackstr(q, expdest);
447 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
451 recordregion(begoff, p - 1 - start, 0);
452 result = expdest - p + 1;
453 STADJUST(-result, expdest);
458 * Perform command substitution.
461 expbackq(union node *cmd, int quoted, int flag)
467 char *dest = expdest;
468 struct ifsregion saveifs, *savelastp;
469 struct nodelist *saveargbackq;
471 int startloc = dest - stackblock();
472 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
473 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
478 savelastp = ifslastp;
479 saveargbackq = argbackq;
480 p = grabstackstr(dest);
481 evalbackcmd(cmd, &in);
482 ungrabstackstr(p, dest);
484 ifslastp = savelastp;
485 argbackq = saveargbackq;
490 /* Don't copy trailing newlines */
492 if (--in.nleft < 0) {
495 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
496 TRACE(("expbackq: read returns %d\n", i));
507 CHECKSTRSPACE(nnl + 2, dest);
512 if (quotes && syntax[(int)lastc] == CCTL)
513 USTPUTC(CTLESC, dest);
514 USTPUTC(lastc, dest);
524 exitstatus = waitforjob(in.jp, NULL);
526 recordregion(startloc, dest - stackblock(), 0);
527 TRACE(("expbackq: size=%td: \"%.*s\"\n",
528 ((dest - stackblock()) - startloc),
529 (int)((dest - stackblock()) - startloc),
530 stackblock() + startloc));
538 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
539 int varflags, int quotes)
545 struct nodelist *saveargbackq = argbackq;
548 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
549 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
550 EXP_CASE : 0) | EXP_TILDE);
551 STACKSTRNUL(expdest);
552 argbackq = saveargbackq;
553 startp = stackblock() + startloc;
555 str = stackblock() + strloc;
559 setvar(str, startp, 0);
560 amount = startp - expdest;
561 STADJUST(amount, expdest);
566 if (*p != CTLENDVAR) {
567 outfmt(out2, "%s\n", startp);
570 error("%.*s: parameter %snot set", (int)(p - str - 1),
571 str, (varflags & VSNUL) ? "null or "
576 for (loc = startp; loc < str; loc++) {
579 if (patmatch(str, startp, quotes)) {
584 if (quotes && *loc == CTLESC)
590 for (loc = str - 1; loc >= startp;) {
593 if (patmatch(str, startp, quotes)) {
599 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
600 for (q = startp; q < loc; q++)
610 for (loc = str - 1; loc >= startp;) {
611 if (patmatch(str, loc, quotes)) {
612 amount = loc - expdest;
613 STADJUST(amount, expdest);
617 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
618 for (q = startp; q < loc; q++)
628 for (loc = startp; loc < str - 1; loc++) {
629 if (patmatch(str, loc, quotes)) {
630 amount = loc - expdest;
631 STADJUST(amount, expdest);
634 if (quotes && *loc == CTLESC)
645 amount = ((str - 1) - (loc - startp)) - expdest;
646 STADJUST(amount, expdest);
647 while (loc != str - 1)
654 * Expand a variable, and return a pointer to the next character in the
659 evalvar(char *p, int flag)
673 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
675 varflags = (unsigned char)*p++;
676 subtype = varflags & VSTYPE;
681 p = strchr(p, '=') + 1;
682 again: /* jump here after setting a variable with ${var=text} */
683 if (varflags & VSLINENO) {
687 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
689 } else if (special) {
690 set = varisset(var, varflags & VSNUL);
693 val = bltinlookup(var, 1);
694 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
701 startloc = expdest - stackblock();
702 if (!set && uflag && *var != '@' && *var != '*') {
710 error("%.*s: parameter not set", (int)(p - var - 1),
714 if (set && subtype != VSPLUS) {
715 /* insert the value of the variable */
717 varvalue(var, varflags & VSQUOTE, subtype, flag);
718 if (subtype == VSLENGTH) {
719 varlenb = expdest - stackblock() - startloc;
722 val = stackblock() + startloc;
723 for (;val != expdest; val++)
724 if ((*val & 0xC0) == 0x80)
727 STADJUST(-varlenb, expdest);
730 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
733 if (subtype == VSLENGTH) {
736 (*val & 0xC0) != 0x80)
741 STPUTS_QUOTES(val, syntax, expdest);
743 STPUTS(val, expdest);
749 if (subtype == VSPLUS)
752 easy = ((varflags & VSQUOTE) == 0 ||
753 (*var == '@' && shellparam.nparam != 1));
758 expdest = cvtnum(varlen, expdest);
765 recordregion(startloc, expdest - stackblock(),
766 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
767 (*var == '@' || *var == '*')));
773 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
774 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
788 * Terminate the string and start recording the pattern
791 STPUTC('\0', expdest);
792 patloc = expdest - stackblock();
793 if (subevalvar(p, NULL, patloc, subtype,
794 startloc, varflags, quotes) == 0) {
795 int amount = (expdest - stackblock() - patloc) + 1;
796 STADJUST(-amount, expdest);
798 /* Remove any recorded regions beyond start of variable */
799 removerecordregions(startloc);
805 if (subevalvar(p, var, 0, subtype, startloc, varflags,
809 * Remove any recorded regions beyond
812 removerecordregions(startloc);
823 error("${%.*s%s}: Bad substitution", c, var,
824 (c > 0 && *p != CTLENDVAR) ? "..." : "");
829 p[-1] = '='; /* recover overwritten '=' */
831 if (subtype != VSNORMAL) { /* skip to end of alternative */
834 if ((c = *p++) == CTLESC)
836 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
838 argbackq = argbackq->next;
839 } else if (c == CTLVAR) {
840 if ((*p++ & VSTYPE) != VSNORMAL)
842 } else if (c == CTLENDVAR) {
854 * Test whether a specialized variable is set.
858 varisset(char *name, int nulok)
862 return backgndpidset();
863 else if (*name == '@' || *name == '*') {
864 if (*shellparam.p == NULL)
870 for (av = shellparam.p; *av; av++)
875 } else if (is_digit(*name)) {
877 int num = atoi(name);
879 if (num > shellparam.nparam)
885 ap = shellparam.p[num - 1];
887 if (nulok && (ap == NULL || *ap == '\0'))
894 strtodest(const char *p, int flag, int subtype, int quoted)
896 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
897 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
903 * Add the value of a specialized variable to the stack string.
907 varvalue(char *name, int quoted, int subtype, int flag)
923 num = shellparam.nparam;
926 num = backgndpidval();
928 expdest = cvtnum(num, expdest);
931 for (i = 0 ; i < NOPTS ; i++) {
933 STPUTC(optlist[i].letter, expdest);
937 if (flag & EXP_FULL && quoted) {
938 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
939 strtodest(p, flag, subtype, quoted);
941 STPUTC('\0', expdest);
951 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
952 strtodest(p, flag, subtype, quoted);
955 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
956 STPUTC(sep, expdest);
961 strtodest(p, flag, subtype, quoted);
964 if (is_digit(*name)) {
966 if (num > 0 && num <= shellparam.nparam) {
967 p = shellparam.p[num - 1];
968 strtodest(p, flag, subtype, quoted);
978 * Record the fact that we have to scan this region of the
979 * string for IFS characters.
983 recordregion(int start, int end, int inquotes)
985 struct ifsregion *ifsp;
987 if (ifslastp == NULL) {
990 if (ifslastp->endoff == start
991 && ifslastp->inquotes == inquotes) {
992 /* extend previous area */
993 ifslastp->endoff = end;
996 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
997 ifslastp->next = ifsp;
1000 ifslastp->next = NULL;
1001 ifslastp->begoff = start;
1002 ifslastp->endoff = end;
1003 ifslastp->inquotes = inquotes;
1009 * Break the argument string into pieces based upon IFS and add the
1010 * strings to the argument list. The regions of the string to be
1011 * searched for IFS characters have been stored by recordregion.
1012 * CTLESC characters are preserved but have little effect in this pass
1013 * other than escaping CTL* characters. In particular, they do not escape
1014 * IFS characters: that should be done with the ifsregion mechanism.
1015 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1016 * This pass treats them as a regular character, making the string non-empty.
1017 * Later, they are removed along with the other CTL* characters.
1020 ifsbreakup(char *string, struct arglist *arglist)
1022 struct ifsregion *ifsp;
1029 int had_param_ch = 0;
1033 if (ifslastp == NULL) {
1034 /* Return entire argument, IFS doesn't apply to any of it */
1035 sp = (struct strlist *)stalloc(sizeof *sp);
1037 *arglist->lastp = sp;
1038 arglist->lastp = &sp->next;
1042 ifs = ifsset() ? ifsval() : " \t\n";
1044 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1045 p = string + ifsp->begoff;
1046 while (p < string + ifsp->endoff) {
1050 if (ifsp->inquotes) {
1051 /* Only NULs (should be from "$@") end args */
1059 if (!strchr(ifs, *p)) {
1064 ifsspc = strchr(" \t\n", *p);
1066 /* Ignore IFS whitespace at start */
1067 if (q == start && ifsspc != NULL) {
1075 /* Save this argument... */
1077 sp = (struct strlist *)stalloc(sizeof *sp);
1079 *arglist->lastp = sp;
1080 arglist->lastp = &sp->next;
1083 if (ifsspc != NULL) {
1084 /* Ignore further trailing IFS whitespace */
1085 for (; p < string + ifsp->endoff; p++) {
1089 if (strchr(ifs, *p) == NULL) {
1093 if (strchr(" \t\n", *p) == NULL) {
1104 * Save anything left as an argument.
1105 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1106 * generating 2 arguments, the second of which is empty.
1107 * Some recent clarification of the Posix spec say that it
1108 * should only generate one....
1110 if (had_param_ch || *start != 0) {
1111 sp = (struct strlist *)stalloc(sizeof *sp);
1113 *arglist->lastp = sp;
1114 arglist->lastp = &sp->next;
1119 static char expdir[PATH_MAX];
1120 #define expdir_end (expdir + sizeof(expdir))
1123 * Perform pathname generation and remove control characters.
1124 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1125 * The results are stored in the list exparg.
1128 expandmeta(struct strlist *str, int flag __unused)
1131 struct strlist **savelastp;
1134 /* TODO - EXP_REDIR */
1140 for (;;) { /* fast check for meta chars */
1141 if ((c = *p++) == '\0')
1143 if (c == '*' || c == '?' || c == '[')
1146 savelastp = exparg.lastp;
1148 expmeta(expdir, str->text);
1150 if (exparg.lastp == savelastp) {
1155 *exparg.lastp = str;
1156 rmescapes(str->text);
1157 exparg.lastp = &str->next;
1159 *exparg.lastp = NULL;
1160 *savelastp = sp = expsort(*savelastp);
1161 while (sp->next != NULL)
1163 exparg.lastp = &sp->next;
1171 * Do metacharacter (i.e. *, ?, [...]) expansion.
1175 expmeta(char *enddir, char *name)
1191 for (p = name; esc = 0, *p; p += esc + 1) {
1192 if (*p == '*' || *p == '?')
1194 else if (*p == '[') {
1196 if (*q == '!' || *q == '^')
1199 while (*q == CTLQUOTEMARK)
1203 if (*q == '/' || *q == '\0')
1210 } else if (*p == '\0')
1212 else if (*p == CTLQUOTEMARK)
1217 if (p[esc] == '/') {
1220 start = p + esc + 1;
1224 if (metaflag == 0) { /* we've reached the end of the file name */
1225 if (enddir != expdir)
1227 for (p = name ; ; p++) {
1228 if (*p == CTLQUOTEMARK)
1235 if (enddir == expdir_end)
1238 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1243 if (start != name) {
1246 while (*p == CTLQUOTEMARK)
1251 if (enddir == expdir_end)
1255 if (enddir == expdir) {
1256 p = __DECONST(char *, ".");
1257 } else if (enddir == expdir + 1 && *expdir == '/') {
1258 p = __DECONST(char *, "/");
1263 if ((dirp = opendir(p)) == NULL)
1265 if (enddir != expdir)
1267 if (*endname == 0) {
1276 while (*p == CTLQUOTEMARK)
1282 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1283 if (dp->d_name[0] == '.' && ! matchdot)
1285 if (patmatch(start, dp->d_name, 0)) {
1286 if (enddir + dp->d_namlen + 1 > expdir_end)
1288 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1292 if (enddir + dp->d_namlen + 2 > expdir_end)
1294 enddir[dp->d_namlen] = '/';
1295 enddir[dp->d_namlen + 1] = '\0';
1296 expmeta(enddir + dp->d_namlen + 1, endname);
1302 endname[-esc - 1] = esc ? CTLESC : '/';
1307 * Add a file name to the list.
1311 addfname(char *name)
1316 p = stalloc(strlen(name) + 1);
1318 sp = (struct strlist *)stalloc(sizeof *sp);
1321 exparg.lastp = &sp->next;
1326 * Sort the results of file name expansion. It calculates the number of
1327 * strings to sort and then calls msort (short for merge sort) to do the
1331 static struct strlist *
1332 expsort(struct strlist *str)
1338 for (sp = str ; sp ; sp = sp->next)
1340 return msort(str, len);
1344 static struct strlist *
1345 msort(struct strlist *list, int len)
1347 struct strlist *p, *q = NULL;
1348 struct strlist **lpp;
1356 for (n = half ; --n >= 0 ; ) {
1360 q->next = NULL; /* terminate first half of list */
1361 q = msort(list, half); /* sort first half of list */
1362 p = msort(p, len - half); /* sort second half */
1365 if (strcmp(p->text, q->text) < 0) {
1368 if ((p = *lpp) == NULL) {
1375 if ((q = *lpp) == NULL) {
1387 get_wc(const char **p)
1392 chrlen = mbtowc(&c, *p, 4);
1395 else if (chrlen == -1)
1404 * See if a character matches a character class, starting at the first colon
1406 * If a valid character class is recognized, a pointer to the next character
1407 * after the final closing bracket is stored into *end, otherwise a null
1408 * pointer is stored into *end.
1411 match_charclass(const char *p, wchar_t chr, const char **end)
1414 const char *nameend;
1419 nameend = strstr(p, ":]");
1420 if (nameend == NULL || nameend - p >= (int)sizeof(name) || nameend == p)
1422 memcpy(name, p, nameend - p);
1423 name[nameend - p] = '\0';
1425 cclass = wctype(name);
1426 /* An unknown class matches nothing but is valid nevertheless. */
1429 return iswctype(chr, cclass);
1434 * Returns true if the pattern matches the string.
1438 patmatch(const char *pattern, const char *string, int squoted)
1440 const char *p, *q, *end;
1451 if (squoted && *q == CTLESC)
1459 if (squoted && *q == CTLESC)
1464 wc = (unsigned char)*q++;
1470 while (c == CTLQUOTEMARK || c == '*')
1472 if (c != CTLESC && c != CTLQUOTEMARK &&
1473 c != '?' && c != '*' && c != '[') {
1475 if (squoted && *q == CTLESC &&
1480 if (squoted && *q == CTLESC)
1486 if (patmatch(p, q, squoted))
1488 if (squoted && *q == CTLESC)
1490 } while (*q++ != '\0');
1498 if (*endp == '!' || *endp == '^')
1501 while (*endp == CTLQUOTEMARK)
1504 goto dft; /* no matching ] */
1505 if (*endp == CTLESC)
1511 if (*p == '!' || *p == '^') {
1516 if (squoted && *q == CTLESC)
1521 chr = (unsigned char)*q++;
1526 if (c == CTLQUOTEMARK)
1528 if (c == '[' && *p == ':') {
1529 found |= match_charclass(p, chr, &end);
1535 if (localeisutf8 && c & 0x80) {
1538 if (wc == 0) /* bad utf-8 */
1541 wc = (unsigned char)c;
1542 if (*p == '-' && p[1] != ']') {
1544 while (*p == CTLQUOTEMARK)
1550 if (wc2 == 0) /* bad utf-8 */
1553 wc2 = (unsigned char)*p++;
1554 if ( collate_range_cmp(chr, wc) >= 0
1555 && collate_range_cmp(chr, wc2) <= 0
1562 } while ((c = *p++) != ']');
1563 if (found == invert)
1568 if (squoted && *q == CTLESC)
1584 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1588 rmescapes(char *str)
1593 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1599 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1613 * See if a pattern matches in a case statement.
1617 casematch(union node *pattern, const char *val)
1619 struct stackmark smark;
1623 setstackmark(&smark);
1624 argbackq = pattern->narg.backquote;
1625 STARTSTACKSTR(expdest);
1627 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1628 STPUTC('\0', expdest);
1629 p = grabstackstr(expdest);
1630 result = patmatch(p, val, 0);
1631 popstackmark(&smark);
1640 cvtnum(int num, char *buf)
1644 char *p = temp + 31;
1649 *--p = num % 10 + '0';
1650 } while ((num /= 10) != 0);
1660 * Do most of the work for wordexp(3).
1664 wordexpcmd(int argc, char **argv)
1669 out1fmt("%08x", argc - 1);
1670 for (i = 1, len = 0; i < argc; i++)
1671 len += strlen(argv[i]);
1672 out1fmt("%08x", (int)len);
1673 for (i = 1; i < argc; i++)
1674 outbin(argv[i], strlen(argv[i]) + 1, out1);