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.86 2011/05/27 15:56:13 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 return; /* here document expanded */
178 STPUTC('\0', expdest);
179 p = grabstackstr(expdest);
180 exparg.lastp = &exparg.list;
184 if (flag & EXP_FULL) {
185 ifsbreakup(p, &exparg);
186 *exparg.lastp = NULL;
187 exparg.lastp = &exparg.list;
188 expandmeta(exparg.list, flag);
190 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
192 sp = (struct strlist *)stalloc(sizeof (struct strlist));
195 exparg.lastp = &sp->next;
197 while (ifsfirst.next != NULL) {
198 struct ifsregion *ifsp;
200 ifsp = ifsfirst.next->next;
201 ckfree(ifsfirst.next);
202 ifsfirst.next = ifsp;
205 *exparg.lastp = NULL;
207 *arglist->lastp = exparg.list;
208 arglist->lastp = exparg.lastp;
215 * Perform parameter expansion, command substitution and arithmetic
216 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
217 * Processing ends at a CTLENDVAR character as well as '\0'.
218 * This is used to expand word in ${var+word} etc.
219 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
220 * characters to allow for further processing.
221 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
224 argstr(char *p, int flag)
227 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
232 split_lit = flag & EXP_SPLIT_LIT;
233 lit_quoted = flag & EXP_LIT_QUOTED;
234 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
235 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
236 p = exptilde(p, flag);
238 CHECKSTRSPACE(2, expdest);
245 /* "$@" syntax adherence hack */
246 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
248 if ((flag & EXP_FULL) != 0)
259 if (split_lit && !lit_quoted)
260 recordregion(expdest - stackblock() -
262 expdest - stackblock(), 0);
265 p = evalvar(p, flag);
268 case CTLBACKQ|CTLQUOTE:
269 expbackq(argbackq->n, c & CTLQUOTE, flag);
270 argbackq = argbackq->next;
278 * sort of a hack - expand tildes in variable
279 * assignments (after the first '=' and after ':'s).
282 if (split_lit && !lit_quoted)
283 recordregion(expdest - stackblock() - 1,
284 expdest - stackblock(), 0);
285 if (flag & EXP_VARTILDE && *p == '~' &&
286 (c != '=' || firsteq)) {
289 p = exptilde(p, flag);
294 if (split_lit && !lit_quoted)
295 recordregion(expdest - stackblock() - 1,
296 expdest - stackblock(), 0);
303 * Perform tilde expansion, placing the result in the stack string and
304 * returning the next position in the input string to process.
307 exptilde(char *p, int flag)
312 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
314 while ((c = *p) != '\0') {
316 case CTLESC: /* This means CTL* are always considered quoted. */
319 case CTLBACKQ | CTLQUOTE:
325 if (flag & EXP_VARTILDE)
336 if (*(startp+1) == '\0') {
337 if ((home = lookupvar("HOME")) == NULL)
340 if ((pw = getpwnam(startp+1)) == NULL)
348 STPUTS_QUOTES(home, SQSYNTAX, expdest);
350 STPUTS(home, expdest);
359 removerecordregions(int endoff)
361 if (ifslastp == NULL)
364 if (ifsfirst.endoff > endoff) {
365 while (ifsfirst.next != NULL) {
366 struct ifsregion *ifsp;
368 ifsp = ifsfirst.next->next;
369 ckfree(ifsfirst.next);
370 ifsfirst.next = ifsp;
373 if (ifsfirst.begoff > endoff)
376 ifslastp = &ifsfirst;
377 ifsfirst.endoff = endoff;
382 ifslastp = &ifsfirst;
383 while (ifslastp->next && ifslastp->next->begoff < endoff)
384 ifslastp=ifslastp->next;
385 while (ifslastp->next != NULL) {
386 struct ifsregion *ifsp;
388 ifsp = ifslastp->next->next;
389 ckfree(ifslastp->next);
390 ifslastp->next = ifsp;
393 if (ifslastp->endoff > endoff)
394 ifslastp->endoff = endoff;
398 * Expand arithmetic expression. Backup to start of expression,
399 * evaluate, place result in (backed up) result, adjust string position.
407 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
411 * This routine is slightly over-complicated for
412 * efficiency. First we make sure there is
413 * enough space for the result, which may be bigger
414 * than the expression. Next we
415 * scan backwards looking for the start of arithmetic. If the
416 * next previous character is a CTLESC character, then we
417 * have to rescan starting from the beginning since CTLESC
418 * characters have to be processed left to right.
420 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
421 USTPUTC('\0', expdest);
422 start = stackblock();
424 while (p >= start && *p != CTLARI)
426 if (p < start || *p != CTLARI)
427 error("missing CTLARI (shouldn't happen)");
428 if (p > start && *(p - 1) == CTLESC)
429 for (p = start; *p != CTLARI; p++)
438 removerecordregions(begoff);
441 q = grabstackstr(expdest);
443 ungrabstackstr(q, expdest);
444 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
448 recordregion(begoff, p - 1 - start, 0);
449 result = expdest - p + 1;
450 STADJUST(-result, expdest);
455 * Perform command substitution.
458 expbackq(union node *cmd, int quoted, int flag)
464 char *dest = expdest;
465 struct ifsregion saveifs, *savelastp;
466 struct nodelist *saveargbackq;
468 int startloc = dest - stackblock();
469 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
470 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
475 savelastp = ifslastp;
476 saveargbackq = argbackq;
477 p = grabstackstr(dest);
478 evalbackcmd(cmd, &in);
479 ungrabstackstr(p, dest);
481 ifslastp = savelastp;
482 argbackq = saveargbackq;
487 /* Don't copy trailing newlines */
489 if (--in.nleft < 0) {
492 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
493 TRACE(("expbackq: read returns %d\n", i));
504 CHECKSTRSPACE(nnl + 2, dest);
509 if (quotes && syntax[(int)lastc] == CCTL)
510 USTPUTC(CTLESC, dest);
511 USTPUTC(lastc, dest);
521 exitstatus = waitforjob(in.jp, NULL);
523 recordregion(startloc, dest - stackblock(), 0);
524 TRACE(("expbackq: size=%td: \"%.*s\"\n",
525 ((dest - stackblock()) - startloc),
526 (int)((dest - stackblock()) - startloc),
527 stackblock() + startloc));
535 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
536 int varflags, int quotes)
542 struct nodelist *saveargbackq = argbackq;
545 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
546 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
547 EXP_CASE : 0) | EXP_TILDE);
548 STACKSTRNUL(expdest);
549 argbackq = saveargbackq;
550 startp = stackblock() + startloc;
552 str = stackblock() + strloc;
556 setvar(str, startp, 0);
557 amount = startp - expdest;
558 STADJUST(amount, expdest);
563 if (*p != CTLENDVAR) {
564 outfmt(out2, "%s\n", startp);
567 error("%.*s: parameter %snot set", (int)(p - str - 1),
568 str, (varflags & VSNUL) ? "null or "
573 for (loc = startp; loc < str; loc++) {
576 if (patmatch(str, startp, quotes)) {
581 if (quotes && *loc == CTLESC)
587 for (loc = str - 1; loc >= startp;) {
590 if (patmatch(str, startp, quotes)) {
596 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
597 for (q = startp; q < loc; q++)
607 for (loc = str - 1; loc >= startp;) {
608 if (patmatch(str, loc, quotes)) {
609 amount = loc - expdest;
610 STADJUST(amount, expdest);
614 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
615 for (q = startp; q < loc; q++)
625 for (loc = startp; loc < str - 1; loc++) {
626 if (patmatch(str, loc, quotes)) {
627 amount = loc - expdest;
628 STADJUST(amount, expdest);
631 if (quotes && *loc == CTLESC)
642 amount = ((str - 1) - (loc - startp)) - expdest;
643 STADJUST(amount, expdest);
644 while (loc != str - 1)
651 * Expand a variable, and return a pointer to the next character in the
656 evalvar(char *p, int flag)
670 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
672 varflags = (unsigned char)*p++;
673 subtype = varflags & VSTYPE;
678 p = strchr(p, '=') + 1;
679 again: /* jump here after setting a variable with ${var=text} */
680 if (varflags & VSLINENO) {
684 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
686 } else if (special) {
687 set = varisset(var, varflags & VSNUL);
690 val = bltinlookup(var, 1);
691 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
698 startloc = expdest - stackblock();
699 if (!set && uflag && *var != '@' && *var != '*') {
707 error("%.*s: parameter not set", (int)(p - var - 1),
711 if (set && subtype != VSPLUS) {
712 /* insert the value of the variable */
714 varvalue(var, varflags & VSQUOTE, subtype, flag);
715 if (subtype == VSLENGTH) {
716 varlenb = expdest - stackblock() - startloc;
719 val = stackblock() + startloc;
720 for (;val != expdest; val++)
721 if ((*val & 0xC0) == 0x80)
724 STADJUST(-varlenb, expdest);
727 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
730 if (subtype == VSLENGTH) {
733 (*val & 0xC0) != 0x80)
738 STPUTS_QUOTES(val, syntax, expdest);
740 STPUTS(val, expdest);
746 if (subtype == VSPLUS)
749 easy = ((varflags & VSQUOTE) == 0 ||
750 (*var == '@' && shellparam.nparam != 1));
755 expdest = cvtnum(varlen, expdest);
762 recordregion(startloc, expdest - stackblock(),
763 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
764 (*var == '@' || *var == '*')));
770 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
771 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
785 * Terminate the string and start recording the pattern
788 STPUTC('\0', expdest);
789 patloc = expdest - stackblock();
790 if (subevalvar(p, NULL, patloc, subtype,
791 startloc, varflags, quotes) == 0) {
792 int amount = (expdest - stackblock() - patloc) + 1;
793 STADJUST(-amount, expdest);
795 /* Remove any recorded regions beyond start of variable */
796 removerecordregions(startloc);
802 if (subevalvar(p, var, 0, subtype, startloc, varflags,
806 * Remove any recorded regions beyond
809 removerecordregions(startloc);
820 error("${%.*s%s}: Bad substitution", c, var,
821 (c > 0 && *p != CTLENDVAR) ? "..." : "");
826 p[-1] = '='; /* recover overwritten '=' */
828 if (subtype != VSNORMAL) { /* skip to end of alternative */
831 if ((c = *p++) == CTLESC)
833 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
835 argbackq = argbackq->next;
836 } else if (c == CTLVAR) {
837 if ((*p++ & VSTYPE) != VSNORMAL)
839 } else if (c == CTLENDVAR) {
851 * Test whether a specialized variable is set.
855 varisset(char *name, int nulok)
859 return backgndpidset();
860 else if (*name == '@' || *name == '*') {
861 if (*shellparam.p == NULL)
867 for (av = shellparam.p; *av; av++)
872 } else if (is_digit(*name)) {
874 int num = atoi(name);
876 if (num > shellparam.nparam)
882 ap = shellparam.p[num - 1];
884 if (nulok && (ap == NULL || *ap == '\0'))
891 strtodest(const char *p, int flag, int subtype, int quoted)
893 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
894 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
900 * Add the value of a specialized variable to the stack string.
904 varvalue(char *name, int quoted, int subtype, int flag)
920 num = shellparam.nparam;
923 num = backgndpidval();
925 expdest = cvtnum(num, expdest);
928 for (i = 0 ; i < NOPTS ; i++) {
930 STPUTC(optlist[i].letter, expdest);
934 if (flag & EXP_FULL && quoted) {
935 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
936 strtodest(p, flag, subtype, quoted);
938 STPUTC('\0', expdest);
948 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
949 strtodest(p, flag, subtype, quoted);
952 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
953 STPUTC(sep, expdest);
958 strtodest(p, flag, subtype, quoted);
961 if (is_digit(*name)) {
963 if (num > 0 && num <= shellparam.nparam) {
964 p = shellparam.p[num - 1];
965 strtodest(p, flag, subtype, quoted);
975 * Record the fact that we have to scan this region of the
976 * string for IFS characters.
980 recordregion(int start, int end, int inquotes)
982 struct ifsregion *ifsp;
984 if (ifslastp == NULL) {
987 if (ifslastp->endoff == start
988 && ifslastp->inquotes == inquotes) {
989 /* extend previous area */
990 ifslastp->endoff = end;
993 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
994 ifslastp->next = ifsp;
997 ifslastp->next = NULL;
998 ifslastp->begoff = start;
999 ifslastp->endoff = end;
1000 ifslastp->inquotes = inquotes;
1006 * Break the argument string into pieces based upon IFS and add the
1007 * strings to the argument list. The regions of the string to be
1008 * searched for IFS characters have been stored by recordregion.
1009 * CTLESC characters are preserved but have little effect in this pass
1010 * other than escaping CTL* characters. In particular, they do not escape
1011 * IFS characters: that should be done with the ifsregion mechanism.
1012 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1013 * This pass treats them as a regular character, making the string non-empty.
1014 * Later, they are removed along with the other CTL* characters.
1017 ifsbreakup(char *string, struct arglist *arglist)
1019 struct ifsregion *ifsp;
1026 int had_param_ch = 0;
1030 if (ifslastp == NULL) {
1031 /* Return entire argument, IFS doesn't apply to any of it */
1032 sp = (struct strlist *)stalloc(sizeof *sp);
1034 *arglist->lastp = sp;
1035 arglist->lastp = &sp->next;
1039 ifs = ifsset() ? ifsval() : " \t\n";
1041 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1042 p = string + ifsp->begoff;
1043 while (p < string + ifsp->endoff) {
1047 if (ifsp->inquotes) {
1048 /* Only NULs (should be from "$@") end args */
1056 if (!strchr(ifs, *p)) {
1061 ifsspc = strchr(" \t\n", *p);
1063 /* Ignore IFS whitespace at start */
1064 if (q == start && ifsspc != NULL) {
1072 /* Save this argument... */
1074 sp = (struct strlist *)stalloc(sizeof *sp);
1076 *arglist->lastp = sp;
1077 arglist->lastp = &sp->next;
1080 if (ifsspc != NULL) {
1081 /* Ignore further trailing IFS whitespace */
1082 for (; p < string + ifsp->endoff; p++) {
1086 if (strchr(ifs, *p) == NULL) {
1090 if (strchr(" \t\n", *p) == NULL) {
1101 * Save anything left as an argument.
1102 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1103 * generating 2 arguments, the second of which is empty.
1104 * Some recent clarification of the Posix spec say that it
1105 * should only generate one....
1107 if (had_param_ch || *start != 0) {
1108 sp = (struct strlist *)stalloc(sizeof *sp);
1110 *arglist->lastp = sp;
1111 arglist->lastp = &sp->next;
1116 static char expdir[PATH_MAX];
1117 #define expdir_end (expdir + sizeof(expdir))
1120 * Perform pathname generation and remove control characters.
1121 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1122 * The results are stored in the list exparg.
1125 expandmeta(struct strlist *str, int flag __unused)
1128 struct strlist **savelastp;
1131 /* TODO - EXP_REDIR */
1137 for (;;) { /* fast check for meta chars */
1138 if ((c = *p++) == '\0')
1140 if (c == '*' || c == '?' || c == '[')
1143 savelastp = exparg.lastp;
1145 expmeta(expdir, str->text);
1147 if (exparg.lastp == savelastp) {
1152 *exparg.lastp = str;
1153 rmescapes(str->text);
1154 exparg.lastp = &str->next;
1156 *exparg.lastp = NULL;
1157 *savelastp = sp = expsort(*savelastp);
1158 while (sp->next != NULL)
1160 exparg.lastp = &sp->next;
1168 * Do metacharacter (i.e. *, ?, [...]) expansion.
1172 expmeta(char *enddir, char *name)
1188 for (p = name; esc = 0, *p; p += esc + 1) {
1189 if (*p == '*' || *p == '?')
1191 else if (*p == '[') {
1193 if (*q == '!' || *q == '^')
1196 while (*q == CTLQUOTEMARK)
1200 if (*q == '/' || *q == '\0')
1207 } else if (*p == '\0')
1209 else if (*p == CTLQUOTEMARK)
1214 if (p[esc] == '/') {
1217 start = p + esc + 1;
1221 if (metaflag == 0) { /* we've reached the end of the file name */
1222 if (enddir != expdir)
1224 for (p = name ; ; p++) {
1225 if (*p == CTLQUOTEMARK)
1232 if (enddir == expdir_end)
1235 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1240 if (start != name) {
1243 while (*p == CTLQUOTEMARK)
1248 if (enddir == expdir_end)
1252 if (enddir == expdir) {
1253 p = __DECONST(char *, ".");
1254 } else if (enddir == expdir + 1 && *expdir == '/') {
1255 p = __DECONST(char *, "/");
1260 if ((dirp = opendir(p)) == NULL)
1262 if (enddir != expdir)
1264 if (*endname == 0) {
1273 while (*p == CTLQUOTEMARK)
1279 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1280 if (dp->d_name[0] == '.' && ! matchdot)
1282 if (patmatch(start, dp->d_name, 0)) {
1283 if (enddir + dp->d_namlen + 1 > expdir_end)
1285 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1289 if (enddir + dp->d_namlen + 2 > expdir_end)
1291 enddir[dp->d_namlen] = '/';
1292 enddir[dp->d_namlen + 1] = '\0';
1293 expmeta(enddir + dp->d_namlen + 1, endname);
1299 endname[-esc - 1] = esc ? CTLESC : '/';
1304 * Add a file name to the list.
1308 addfname(char *name)
1313 p = stalloc(strlen(name) + 1);
1315 sp = (struct strlist *)stalloc(sizeof *sp);
1318 exparg.lastp = &sp->next;
1323 * Sort the results of file name expansion. It calculates the number of
1324 * strings to sort and then calls msort (short for merge sort) to do the
1328 static struct strlist *
1329 expsort(struct strlist *str)
1335 for (sp = str ; sp ; sp = sp->next)
1337 return msort(str, len);
1341 static struct strlist *
1342 msort(struct strlist *list, int len)
1344 struct strlist *p, *q = NULL;
1345 struct strlist **lpp;
1353 for (n = half ; --n >= 0 ; ) {
1357 q->next = NULL; /* terminate first half of list */
1358 q = msort(list, half); /* sort first half of list */
1359 p = msort(p, len - half); /* sort second half */
1362 if (strcmp(p->text, q->text) < 0) {
1365 if ((p = *lpp) == NULL) {
1372 if ((q = *lpp) == NULL) {
1384 get_wc(const char **p)
1389 chrlen = mbtowc(&c, *p, 4);
1392 else if (chrlen == -1)
1401 * Returns true if the pattern matches the string.
1405 patmatch(const char *pattern, const char *string, int squoted)
1418 if (squoted && *q == CTLESC)
1426 if (squoted && *q == CTLESC)
1431 wc = (unsigned char)*q++;
1437 while (c == CTLQUOTEMARK || c == '*')
1439 if (c != CTLESC && c != CTLQUOTEMARK &&
1440 c != '?' && c != '*' && c != '[') {
1442 if (squoted && *q == CTLESC &&
1447 if (squoted && *q == CTLESC)
1453 if (patmatch(p, q, squoted))
1455 if (squoted && *q == CTLESC)
1457 } while (*q++ != '\0');
1465 if (*endp == '!' || *endp == '^')
1468 while (*endp == CTLQUOTEMARK)
1471 goto dft; /* no matching ] */
1472 if (*endp == CTLESC)
1478 if (*p == '!' || *p == '^') {
1483 if (squoted && *q == CTLESC)
1488 chr = (unsigned char)*q++;
1493 if (c == CTLQUOTEMARK)
1497 if (localeisutf8 && c & 0x80) {
1500 if (wc == 0) /* bad utf-8 */
1503 wc = (unsigned char)c;
1504 if (*p == '-' && p[1] != ']') {
1506 while (*p == CTLQUOTEMARK)
1512 if (wc2 == 0) /* bad utf-8 */
1515 wc2 = (unsigned char)*p++;
1516 if ( collate_range_cmp(chr, wc) >= 0
1517 && collate_range_cmp(chr, wc2) <= 0
1524 } while ((c = *p++) != ']');
1525 if (found == invert)
1530 if (squoted && *q == CTLESC)
1546 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1550 rmescapes(char *str)
1555 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1561 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1575 * See if a pattern matches in a case statement.
1579 casematch(union node *pattern, const char *val)
1581 struct stackmark smark;
1585 setstackmark(&smark);
1586 argbackq = pattern->narg.backquote;
1587 STARTSTACKSTR(expdest);
1589 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1590 STPUTC('\0', expdest);
1591 p = grabstackstr(expdest);
1592 result = patmatch(p, val, 0);
1593 popstackmark(&smark);
1602 cvtnum(int num, char *buf)
1606 char *p = temp + 31;
1611 *--p = num % 10 + '0';
1612 } while ((num /= 10) != 0);
1622 * Check statically if expanding a string may have side effects.
1625 expandhassideeffects(const char *p)
1631 while ((c = *p++) != '\0') {
1638 /* Expanding $! sets the job to remembered. */
1641 if ((c & VSTYPE) == VSASSIGN)
1644 * If we are in arithmetic, the parameter may contain
1645 * '=' which may cause side effects. Exceptions are
1646 * the length of a parameter and $$, $# and $? which
1647 * are always numeric.
1649 if ((c & VSTYPE) == VSLENGTH) {
1655 if ((*p == '$' || *p == '#' || *p == '?') &&
1664 case CTLBACKQ | CTLQUOTE:
1676 /* Allow '==' operator. */
1683 case '!': case '<': case '>':
1684 /* Allow '!=', '<=', '>=' operators. */
1694 * Do most of the work for wordexp(3).
1698 wordexpcmd(int argc, char **argv)
1703 out1fmt("%08x", argc - 1);
1704 for (i = 1, len = 0; i < argc; i++)
1705 len += strlen(argv[i]);
1706 out1fmt("%08x", (int)len);
1707 for (i = 1; i < argc; i++)
1708 outbin(argv[i], strlen(argv[i]) + 1, out1);