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.84 2011/05/07 14:32:16 jilles Exp $
42 #include <sys/types.h>
56 * Routines to expand arguments to commands. We have to deal with
57 * backquotes, shell variables, and file metacharacters.
79 * Structure specifying which parts of the string should be searched
84 struct ifsregion *next; /* next region in list */
85 int begoff; /* offset of start of region */
86 int endoff; /* offset of end of region */
87 int inquotes; /* search for nul bytes only */
91 static char *expdest; /* output of current string */
92 static struct nodelist *argbackq; /* list of back quote expressions */
93 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
94 static struct ifsregion *ifslastp; /* last struct in list */
95 static struct arglist exparg; /* holds expanded arg list */
97 static void argstr(char *, int);
98 static char *exptilde(char *, int);
99 static void expbackq(union node *, int, int);
100 static int subevalvar(char *, char *, int, int, int, int, int);
101 static char *evalvar(char *, int);
102 static int varisset(char *, int);
103 static void varvalue(char *, int, int, int);
104 static void recordregion(int, int, int);
105 static void removerecordregions(int);
106 static void ifsbreakup(char *, struct arglist *);
107 static void expandmeta(struct strlist *, int);
108 static void expmeta(char *, char *);
109 static void addfname(char *);
110 static struct strlist *expsort(struct strlist *);
111 static struct strlist *msort(struct strlist *, int);
112 static char *cvtnum(int, char *);
113 static int collate_range_cmp(int, int);
116 collate_range_cmp(int c1, int c2)
118 static char s1[2], s2[2];
122 return (strcoll(s1, s2));
126 * Expand shell variables and backquotes inside a here document.
127 * union node *arg the document
128 * int fd; where to write the expanded version
132 expandhere(union node *arg, int fd)
134 expandarg(arg, NULL, 0);
135 xwrite(fd, stackblock(), expdest - stackblock());
139 stputs_quotes(const char *data, const char *syntax, char *p)
143 if (syntax[(int)*data] == CCTL)
149 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
152 * Perform expansions on an argument, placing the resulting list of arguments
153 * in arglist. Parameter expansion, command substitution and arithmetic
154 * expansion are always performed; additional expansions can be requested
156 * The result is left in the stack string.
157 * When arglist is NULL, perform here document expansion.
159 * Caution: this function uses global state and is not reentrant.
160 * However, a new invocation after an interrupted invocation is safe
161 * and will reset the global state for the new call.
164 expandarg(union node *arg, struct arglist *arglist, int flag)
169 argbackq = arg->narg.backquote;
170 STARTSTACKSTR(expdest);
171 ifsfirst.next = NULL;
173 argstr(arg->narg.text, flag);
174 if (arglist == NULL) {
175 return; /* here document expanded */
177 STPUTC('\0', expdest);
178 p = grabstackstr(expdest);
179 exparg.lastp = &exparg.list;
183 if (flag & EXP_FULL) {
184 ifsbreakup(p, &exparg);
185 *exparg.lastp = NULL;
186 exparg.lastp = &exparg.list;
187 expandmeta(exparg.list, flag);
189 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
191 sp = (struct strlist *)stalloc(sizeof (struct strlist));
194 exparg.lastp = &sp->next;
196 while (ifsfirst.next != NULL) {
197 struct ifsregion *ifsp;
199 ifsp = ifsfirst.next->next;
200 ckfree(ifsfirst.next);
201 ifsfirst.next = ifsp;
204 *exparg.lastp = NULL;
206 *arglist->lastp = exparg.list;
207 arglist->lastp = exparg.lastp;
214 * Perform parameter expansion, command substitution and arithmetic
215 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
216 * Processing ends at a CTLENDVAR character as well as '\0'.
217 * This is used to expand word in ${var+word} etc.
218 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
219 * characters to allow for further processing.
220 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
223 argstr(char *p, int flag)
226 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
231 split_lit = flag & EXP_SPLIT_LIT;
232 lit_quoted = flag & EXP_LIT_QUOTED;
233 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
234 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
235 p = exptilde(p, flag);
237 CHECKSTRSPACE(2, expdest);
244 /* "$@" syntax adherence hack */
245 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
247 if ((flag & EXP_FULL) != 0)
258 if (split_lit && !lit_quoted)
259 recordregion(expdest - stackblock() -
261 expdest - stackblock(), 0);
264 p = evalvar(p, flag);
267 case CTLBACKQ|CTLQUOTE:
268 expbackq(argbackq->n, c & CTLQUOTE, flag);
269 argbackq = argbackq->next;
277 * sort of a hack - expand tildes in variable
278 * assignments (after the first '=' and after ':'s).
281 if (split_lit && !lit_quoted)
282 recordregion(expdest - stackblock() - 1,
283 expdest - stackblock(), 0);
284 if (flag & EXP_VARTILDE && *p == '~' &&
285 (c != '=' || firsteq)) {
288 p = exptilde(p, flag);
293 if (split_lit && !lit_quoted)
294 recordregion(expdest - stackblock() - 1,
295 expdest - stackblock(), 0);
302 * Perform tilde expansion, placing the result in the stack string and
303 * returning the next position in the input string to process.
306 exptilde(char *p, int flag)
311 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
313 while ((c = *p) != '\0') {
315 case CTLESC: /* This means CTL* are always considered quoted. */
318 case CTLBACKQ | CTLQUOTE:
324 if (flag & EXP_VARTILDE)
335 if (*(startp+1) == '\0') {
336 if ((home = lookupvar("HOME")) == NULL)
339 if ((pw = getpwnam(startp+1)) == NULL)
347 STPUTS_QUOTES(home, SQSYNTAX, expdest);
349 STPUTS(home, expdest);
358 removerecordregions(int endoff)
360 if (ifslastp == NULL)
363 if (ifsfirst.endoff > endoff) {
364 while (ifsfirst.next != NULL) {
365 struct ifsregion *ifsp;
367 ifsp = ifsfirst.next->next;
368 ckfree(ifsfirst.next);
369 ifsfirst.next = ifsp;
372 if (ifsfirst.begoff > endoff)
375 ifslastp = &ifsfirst;
376 ifsfirst.endoff = endoff;
381 ifslastp = &ifsfirst;
382 while (ifslastp->next && ifslastp->next->begoff < endoff)
383 ifslastp=ifslastp->next;
384 while (ifslastp->next != NULL) {
385 struct ifsregion *ifsp;
387 ifsp = ifslastp->next->next;
388 ckfree(ifslastp->next);
389 ifslastp->next = ifsp;
392 if (ifslastp->endoff > endoff)
393 ifslastp->endoff = endoff;
397 * Expand arithmetic expression. Backup to start of expression,
398 * evaluate, place result in (backed up) result, adjust string position.
406 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
410 * This routine is slightly over-complicated for
411 * efficiency. First we make sure there is
412 * enough space for the result, which may be bigger
413 * than the expression. Next we
414 * scan backwards looking for the start of arithmetic. If the
415 * next previous character is a CTLESC character, then we
416 * have to rescan starting from the beginning since CTLESC
417 * characters have to be processed left to right.
419 CHECKSTRSPACE(DIGITS(result) - 2, expdest);
420 USTPUTC('\0', expdest);
421 start = stackblock();
423 while (p >= start && *p != CTLARI)
425 if (p < start || *p != CTLARI)
426 error("missing CTLARI (shouldn't happen)");
427 if (p > start && *(p - 1) == CTLESC)
428 for (p = start; *p != CTLARI; p++)
437 removerecordregions(begoff);
440 q = grabstackstr(expdest);
442 ungrabstackstr(q, expdest);
443 fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
447 recordregion(begoff, p - 1 - start, 0);
448 result = expdest - p + 1;
449 STADJUST(-result, expdest);
454 * Perform command substitution.
457 expbackq(union node *cmd, int quoted, int flag)
463 char *dest = expdest;
464 struct ifsregion saveifs, *savelastp;
465 struct nodelist *saveargbackq;
467 int startloc = dest - stackblock();
468 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
469 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
474 savelastp = ifslastp;
475 saveargbackq = argbackq;
476 p = grabstackstr(dest);
477 evalbackcmd(cmd, &in);
478 ungrabstackstr(p, dest);
480 ifslastp = savelastp;
481 argbackq = saveargbackq;
486 /* Don't copy trailing newlines */
488 if (--in.nleft < 0) {
491 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
492 TRACE(("expbackq: read returns %d\n", i));
503 CHECKSTRSPACE(nnl + 2, dest);
508 if (quotes && syntax[(int)lastc] == CCTL)
509 USTPUTC(CTLESC, dest);
510 USTPUTC(lastc, dest);
520 exitstatus = waitforjob(in.jp, NULL);
522 recordregion(startloc, dest - stackblock(), 0);
523 TRACE(("expbackq: size=%td: \"%.*s\"\n",
524 ((dest - stackblock()) - startloc),
525 (int)((dest - stackblock()) - startloc),
526 stackblock() + startloc));
534 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
535 int varflags, int quotes)
541 struct nodelist *saveargbackq = argbackq;
544 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
545 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
546 EXP_CASE : 0) | EXP_TILDE);
547 STACKSTRNUL(expdest);
548 argbackq = saveargbackq;
549 startp = stackblock() + startloc;
551 str = stackblock() + strloc;
555 setvar(str, startp, 0);
556 amount = startp - expdest;
557 STADJUST(amount, expdest);
562 if (*p != CTLENDVAR) {
563 outfmt(out2, "%s\n", startp);
566 error("%.*s: parameter %snot set", (int)(p - str - 1),
567 str, (varflags & VSNUL) ? "null or "
572 for (loc = startp; loc < str; loc++) {
575 if (patmatch(str, startp, quotes)) {
580 if (quotes && *loc == CTLESC)
586 for (loc = str - 1; loc >= startp;) {
589 if (patmatch(str, startp, quotes)) {
595 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
596 for (q = startp; q < loc; q++)
606 for (loc = str - 1; loc >= startp;) {
607 if (patmatch(str, loc, quotes)) {
608 amount = loc - expdest;
609 STADJUST(amount, expdest);
613 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
614 for (q = startp; q < loc; q++)
624 for (loc = startp; loc < str - 1; loc++) {
625 if (patmatch(str, loc, quotes)) {
626 amount = loc - expdest;
627 STADJUST(amount, expdest);
630 if (quotes && *loc == CTLESC)
641 amount = ((str - 1) - (loc - startp)) - expdest;
642 STADJUST(amount, expdest);
643 while (loc != str - 1)
650 * Expand a variable, and return a pointer to the next character in the
655 evalvar(char *p, int flag)
669 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
671 varflags = (unsigned char)*p++;
672 subtype = varflags & VSTYPE;
677 p = strchr(p, '=') + 1;
678 again: /* jump here after setting a variable with ${var=text} */
679 if (varflags & VSLINENO) {
683 p[-1] = '\0'; /* temporarily overwrite '=' to have \0
685 } else if (special) {
686 set = varisset(var, varflags & VSNUL);
689 val = bltinlookup(var, 1);
690 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
697 startloc = expdest - stackblock();
698 if (!set && uflag && *var != '@' && *var != '*') {
706 error("%.*s: parameter not set", (int)(p - var - 1),
710 if (set && subtype != VSPLUS) {
711 /* insert the value of the variable */
713 varvalue(var, varflags & VSQUOTE, subtype, flag);
714 if (subtype == VSLENGTH) {
715 varlenb = expdest - stackblock() - startloc;
718 val = stackblock() + startloc;
719 for (;val != expdest; val++)
720 if ((*val & 0xC0) == 0x80)
723 STADJUST(-varlenb, expdest);
726 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
729 if (subtype == VSLENGTH) {
732 (*val & 0xC0) != 0x80)
737 STPUTS_QUOTES(val, syntax, expdest);
739 STPUTS(val, expdest);
745 if (subtype == VSPLUS)
748 easy = ((varflags & VSQUOTE) == 0 ||
749 (*var == '@' && shellparam.nparam != 1));
754 expdest = cvtnum(varlen, expdest);
761 recordregion(startloc, expdest - stackblock(),
768 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
769 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
783 * Terminate the string and start recording the pattern
786 STPUTC('\0', expdest);
787 patloc = expdest - stackblock();
788 if (subevalvar(p, NULL, patloc, subtype,
789 startloc, varflags, quotes) == 0) {
790 int amount = (expdest - stackblock() - patloc) + 1;
791 STADJUST(-amount, expdest);
793 /* Remove any recorded regions beyond start of variable */
794 removerecordregions(startloc);
800 if (subevalvar(p, var, 0, subtype, startloc, varflags,
804 * Remove any recorded regions beyond
807 removerecordregions(startloc);
818 error("${%.*s%s}: Bad substitution", c, var,
819 (c > 0 && *p != CTLENDVAR) ? "..." : "");
824 p[-1] = '='; /* recover overwritten '=' */
826 if (subtype != VSNORMAL) { /* skip to end of alternative */
829 if ((c = *p++) == CTLESC)
831 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
833 argbackq = argbackq->next;
834 } else if (c == CTLVAR) {
835 if ((*p++ & VSTYPE) != VSNORMAL)
837 } else if (c == CTLENDVAR) {
849 * Test whether a specialized variable is set.
853 varisset(char *name, int nulok)
857 return backgndpidset();
858 else if (*name == '@' || *name == '*') {
859 if (*shellparam.p == NULL)
865 for (av = shellparam.p; *av; av++)
870 } else if (is_digit(*name)) {
872 int num = atoi(name);
874 if (num > shellparam.nparam)
880 ap = shellparam.p[num - 1];
882 if (nulok && (ap == NULL || *ap == '\0'))
889 strtodest(const char *p, int flag, int subtype, int quoted)
891 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
892 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
898 * Add the value of a specialized variable to the stack string.
902 varvalue(char *name, int quoted, int subtype, int flag)
918 num = shellparam.nparam;
921 num = backgndpidval();
923 expdest = cvtnum(num, expdest);
926 for (i = 0 ; i < NOPTS ; i++) {
928 STPUTC(optlist[i].letter, expdest);
932 if (flag & EXP_FULL && quoted) {
933 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
934 strtodest(p, flag, subtype, quoted);
936 STPUTC('\0', expdest);
946 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
947 strtodest(p, flag, subtype, quoted);
949 STPUTC(sep, expdest);
954 strtodest(p, flag, subtype, quoted);
957 if (is_digit(*name)) {
959 if (num > 0 && num <= shellparam.nparam) {
960 p = shellparam.p[num - 1];
961 strtodest(p, flag, subtype, quoted);
971 * Record the fact that we have to scan this region of the
972 * string for IFS characters.
976 recordregion(int start, int end, int inquotes)
978 struct ifsregion *ifsp;
980 if (ifslastp == NULL) {
983 if (ifslastp->endoff == start
984 && ifslastp->inquotes == inquotes) {
985 /* extend previous area */
986 ifslastp->endoff = end;
989 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
990 ifslastp->next = ifsp;
993 ifslastp->next = NULL;
994 ifslastp->begoff = start;
995 ifslastp->endoff = end;
996 ifslastp->inquotes = inquotes;
1002 * Break the argument string into pieces based upon IFS and add the
1003 * strings to the argument list. The regions of the string to be
1004 * searched for IFS characters have been stored by recordregion.
1005 * CTLESC characters are preserved but have little effect in this pass
1006 * other than escaping CTL* characters. In particular, they do not escape
1007 * IFS characters: that should be done with the ifsregion mechanism.
1008 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1009 * This pass treats them as a regular character, making the string non-empty.
1010 * Later, they are removed along with the other CTL* characters.
1013 ifsbreakup(char *string, struct arglist *arglist)
1015 struct ifsregion *ifsp;
1022 int had_param_ch = 0;
1026 if (ifslastp == NULL) {
1027 /* Return entire argument, IFS doesn't apply to any of it */
1028 sp = (struct strlist *)stalloc(sizeof *sp);
1030 *arglist->lastp = sp;
1031 arglist->lastp = &sp->next;
1035 ifs = ifsset() ? ifsval() : " \t\n";
1037 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1038 p = string + ifsp->begoff;
1039 while (p < string + ifsp->endoff) {
1043 if (ifsp->inquotes) {
1044 /* Only NULs (should be from "$@") end args */
1052 if (!strchr(ifs, *p)) {
1057 ifsspc = strchr(" \t\n", *p);
1059 /* Ignore IFS whitespace at start */
1060 if (q == start && ifsspc != NULL) {
1068 /* Save this argument... */
1070 sp = (struct strlist *)stalloc(sizeof *sp);
1072 *arglist->lastp = sp;
1073 arglist->lastp = &sp->next;
1076 if (ifsspc != NULL) {
1077 /* Ignore further trailing IFS whitespace */
1078 for (; p < string + ifsp->endoff; p++) {
1082 if (strchr(ifs, *p) == NULL) {
1086 if (strchr(" \t\n", *p) == NULL) {
1097 * Save anything left as an argument.
1098 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1099 * generating 2 arguments, the second of which is empty.
1100 * Some recent clarification of the Posix spec say that it
1101 * should only generate one....
1103 if (had_param_ch || *start != 0) {
1104 sp = (struct strlist *)stalloc(sizeof *sp);
1106 *arglist->lastp = sp;
1107 arglist->lastp = &sp->next;
1112 static char expdir[PATH_MAX];
1113 #define expdir_end (expdir + sizeof(expdir))
1116 * Perform pathname generation and remove control characters.
1117 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1118 * The results are stored in the list exparg.
1121 expandmeta(struct strlist *str, int flag __unused)
1124 struct strlist **savelastp;
1127 /* TODO - EXP_REDIR */
1133 for (;;) { /* fast check for meta chars */
1134 if ((c = *p++) == '\0')
1136 if (c == '*' || c == '?' || c == '[')
1139 savelastp = exparg.lastp;
1141 expmeta(expdir, str->text);
1143 if (exparg.lastp == savelastp) {
1148 *exparg.lastp = str;
1149 rmescapes(str->text);
1150 exparg.lastp = &str->next;
1152 *exparg.lastp = NULL;
1153 *savelastp = sp = expsort(*savelastp);
1154 while (sp->next != NULL)
1156 exparg.lastp = &sp->next;
1164 * Do metacharacter (i.e. *, ?, [...]) expansion.
1168 expmeta(char *enddir, char *name)
1184 for (p = name; esc = 0, *p; p += esc + 1) {
1185 if (*p == '*' || *p == '?')
1187 else if (*p == '[') {
1189 if (*q == '!' || *q == '^')
1192 while (*q == CTLQUOTEMARK)
1196 if (*q == '/' || *q == '\0')
1203 } else if (*p == '\0')
1205 else if (*p == CTLQUOTEMARK)
1210 if (p[esc] == '/') {
1213 start = p + esc + 1;
1217 if (metaflag == 0) { /* we've reached the end of the file name */
1218 if (enddir != expdir)
1220 for (p = name ; ; p++) {
1221 if (*p == CTLQUOTEMARK)
1228 if (enddir == expdir_end)
1231 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1236 if (start != name) {
1239 while (*p == CTLQUOTEMARK)
1244 if (enddir == expdir_end)
1248 if (enddir == expdir) {
1249 p = __DECONST(char *, ".");
1250 } else if (enddir == expdir + 1 && *expdir == '/') {
1251 p = __DECONST(char *, "/");
1256 if ((dirp = opendir(p)) == NULL)
1258 if (enddir != expdir)
1260 if (*endname == 0) {
1269 while (*p == CTLQUOTEMARK)
1275 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1276 if (dp->d_name[0] == '.' && ! matchdot)
1278 if (patmatch(start, dp->d_name, 0)) {
1279 if (enddir + dp->d_namlen + 1 > expdir_end)
1281 memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1285 if (enddir + dp->d_namlen + 2 > expdir_end)
1287 enddir[dp->d_namlen] = '/';
1288 enddir[dp->d_namlen + 1] = '\0';
1289 expmeta(enddir + dp->d_namlen + 1, endname);
1295 endname[-esc - 1] = esc ? CTLESC : '/';
1300 * Add a file name to the list.
1304 addfname(char *name)
1309 p = stalloc(strlen(name) + 1);
1311 sp = (struct strlist *)stalloc(sizeof *sp);
1314 exparg.lastp = &sp->next;
1319 * Sort the results of file name expansion. It calculates the number of
1320 * strings to sort and then calls msort (short for merge sort) to do the
1324 static struct strlist *
1325 expsort(struct strlist *str)
1331 for (sp = str ; sp ; sp = sp->next)
1333 return msort(str, len);
1337 static struct strlist *
1338 msort(struct strlist *list, int len)
1340 struct strlist *p, *q = NULL;
1341 struct strlist **lpp;
1349 for (n = half ; --n >= 0 ; ) {
1353 q->next = NULL; /* terminate first half of list */
1354 q = msort(list, half); /* sort first half of list */
1355 p = msort(p, len - half); /* sort second half */
1358 if (strcmp(p->text, q->text) < 0) {
1361 if ((p = *lpp) == NULL) {
1368 if ((q = *lpp) == NULL) {
1380 * Returns true if the pattern matches the string.
1384 patmatch(const char *pattern, const char *string, int squoted)
1396 if (squoted && *q == CTLESC)
1404 if (squoted && *q == CTLESC)
1411 while (c == CTLQUOTEMARK || c == '*')
1413 if (c != CTLESC && c != CTLQUOTEMARK &&
1414 c != '?' && c != '*' && c != '[') {
1416 if (squoted && *q == CTLESC &&
1421 if (squoted && *q == CTLESC)
1427 if (patmatch(p, q, squoted))
1429 if (squoted && *q == CTLESC)
1431 } while (*q++ != '\0');
1439 if (*endp == '!' || *endp == '^')
1442 while (*endp == CTLQUOTEMARK)
1445 goto dft; /* no matching ] */
1446 if (*endp == CTLESC)
1452 if (*p == '!' || *p == '^') {
1458 if (squoted && chr == CTLESC)
1464 if (c == CTLQUOTEMARK)
1468 if (*p == '-' && p[1] != ']') {
1470 while (*p == CTLQUOTEMARK)
1474 if ( collate_range_cmp(chr, c) >= 0
1475 && collate_range_cmp(chr, *p) <= 0
1483 } while ((c = *p++) != ']');
1484 if (found == invert)
1489 if (squoted && *q == CTLESC)
1505 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1509 rmescapes(char *str)
1514 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1520 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1534 * See if a pattern matches in a case statement.
1538 casematch(union node *pattern, const char *val)
1540 struct stackmark smark;
1544 setstackmark(&smark);
1545 argbackq = pattern->narg.backquote;
1546 STARTSTACKSTR(expdest);
1548 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1549 STPUTC('\0', expdest);
1550 p = grabstackstr(expdest);
1551 result = patmatch(p, val, 0);
1552 popstackmark(&smark);
1561 cvtnum(int num, char *buf)
1565 char *p = temp + 31;
1570 *--p = num % 10 + '0';
1571 } while ((num /= 10) != 0);
1581 * Check statically if expanding a string may have side effects.
1584 expandhassideeffects(const char *p)
1590 while ((c = *p++) != '\0') {
1597 /* Expanding $! sets the job to remembered. */
1600 if ((c & VSTYPE) == VSASSIGN)
1603 * If we are in arithmetic, the parameter may contain
1604 * '=' which may cause side effects. Exceptions are
1605 * the length of a parameter and $$, $# and $? which
1606 * are always numeric.
1608 if ((c & VSTYPE) == VSLENGTH) {
1614 if ((*p == '$' || *p == '#' || *p == '?') &&
1623 case CTLBACKQ | CTLQUOTE:
1635 /* Allow '==' operator. */
1642 case '!': case '<': case '>':
1643 /* Allow '!=', '<=', '>=' operators. */
1653 * Do most of the work for wordexp(3).
1657 wordexpcmd(int argc, char **argv)
1662 out1fmt("%08x", argc - 1);
1663 for (i = 1, len = 0; i < argc; i++)
1664 len += strlen(argv[i]);
1665 out1fmt("%08x", (int)len);
1666 for (i = 1; i < argc; i++)
1667 outbin(argv[i], strlen(argv[i]) + 1, out1);