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.
6 * Copyright (c) 2010-2015
7 * Jilles Tjoelker <jilles@stack.nl>. All rights reserved.
9 * This code is derived from software contributed to Berkeley by
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 static char sccsid[] = "@(#)expand.c 8.5 (Berkeley) 5/15/95";
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
45 #include <sys/types.h>
61 * Routines to expand arguments to commands. We have to deal with
62 * backquotes, shell variables, and file metacharacters.
84 enum wordstate { WORD_IDLE, WORD_WS_DELIMITED, WORD_QUOTEMARK };
91 static char *expdest; /* output of current string */
92 static struct nodelist *argbackq; /* list of back quote expressions */
94 static const char *argstr(const char *, int, struct worddest *);
95 static const char *exptilde(const char *, int);
96 static const char *expari(const char *, int, struct worddest *);
97 static void expbackq(union node *, int, int, struct worddest *);
98 static void subevalvar_trim(const char *, int, int, int);
99 static int subevalvar_misc(const char *, const char *, int, int, int);
100 static const char *evalvar(const char *, int, struct worddest *);
101 static int varisset(const char *, int);
102 static void strtodest(const char *, int, int, int, struct worddest *);
103 static void reprocess(int, int, int, int, struct worddest *);
104 static void varvalue(const char *, int, int, int, struct worddest *);
105 static void expandmeta(char *, struct arglist *);
106 static void expmeta(char *, char *, struct arglist *);
107 static int expsortcmp(const void *, const void *);
108 static int patmatch(const char *, const char *);
109 static void cvtnum(int, char *);
110 static int collate_range_cmp(wchar_t, wchar_t);
113 emptyarglist(struct arglist *list)
116 list->args = list->smallarg;
118 list->capacity = sizeof(list->smallarg) / sizeof(list->smallarg[0]);
122 appendarglist(struct arglist *list, char *str)
127 if (list->count >= list->capacity) {
128 newcapacity = list->capacity * 2;
129 if (newcapacity < 16)
131 if (newcapacity > INT_MAX / (int)sizeof(newargs[0]))
132 error("Too many entries in arglist");
133 newargs = stalloc(newcapacity * sizeof(newargs[0]));
134 memcpy(newargs, list->args, list->count * sizeof(newargs[0]));
135 list->args = newargs;
136 list->capacity = newcapacity;
138 list->args[list->count++] = str;
142 collate_range_cmp(wchar_t c1, wchar_t c2)
144 static wchar_t s1[2], s2[2];
148 return (wcscoll(s1, s2));
152 stputs_quotes(const char *data, const char *syntax, char *p)
156 if (syntax[(int)*data] == CCTL)
162 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
165 nextword(char c, int flag, char *p, struct worddest *dst)
169 is_ws = c == '\t' || c == '\n' || c == ' ';
170 if (p != stackblock() || (is_ws ? dst->state == WORD_QUOTEMARK :
171 dst->state != WORD_WS_DELIMITED) || c == '\0') {
174 expandmeta(grabstackstr(p), dst->list);
176 appendarglist(dst->list, grabstackstr(p));
177 dst->state = is_ws ? WORD_WS_DELIMITED : WORD_IDLE;
178 } else if (!is_ws && dst->state == WORD_WS_DELIMITED)
179 dst->state = WORD_IDLE;
180 /* Reserve space while the stack string is empty. */
181 appendarglist(dst->list, NULL);
186 #define NEXTWORD(c, flag, p, dstlist) p = nextword(c, flag, p, dstlist)
189 stputs_split(const char *data, const char *syntax, int flag, char *p,
190 struct worddest *dst)
195 ifs = ifsset() ? ifsval() : " \t\n";
199 if (strchr(ifs, c) != NULL) {
200 NEXTWORD(c, flag, p, dst);
203 if (flag & EXP_GLOB && syntax[(int)c] == CCTL)
209 #define STPUTS_SPLIT(data, syntax, flag, p, dst) p = stputs_split((data), syntax, flag, p, dst)
212 * Perform expansions on an argument, placing the resulting list of arguments
213 * in arglist. Parameter expansion, command substitution and arithmetic
214 * expansion are always performed; additional expansions can be requested
216 * The result is left in the stack string.
217 * When arglist is NULL, perform here document expansion.
219 * Caution: this function uses global state and is not reentrant.
220 * However, a new invocation after an interrupted invocation is safe
221 * and will reset the global state for the new call.
224 expandarg(union node *arg, struct arglist *arglist, int flag)
226 struct worddest exparg;
230 argbackq = arg->narg.backquote;
231 exparg.list = arglist;
232 exparg.state = WORD_IDLE;
233 STARTSTACKSTR(expdest);
234 argstr(arg->narg.text, flag, &exparg);
235 if (arglist == NULL) {
236 STACKSTRNUL(expdest);
237 return; /* here document expanded */
239 if ((flag & EXP_SPLIT) == 0 || expdest != stackblock() ||
240 exparg.state == WORD_QUOTEMARK) {
241 STPUTC('\0', expdest);
242 if (flag & EXP_SPLIT) {
244 expandmeta(grabstackstr(expdest), exparg.list);
246 appendarglist(exparg.list, grabstackstr(expdest));
249 if ((flag & EXP_SPLIT) == 0)
250 appendarglist(arglist, grabstackstr(expdest));
256 * Perform parameter expansion, command substitution and arithmetic
257 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
258 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
259 * This is used to expand word in ${var+word} etc.
260 * If EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC
261 * characters to allow for further processing.
263 * If EXP_SPLIT is set, dst receives any complete words produced.
266 argstr(const char *p, int flag, struct worddest *dst)
269 int quotes = flag & (EXP_GLOB | EXP_CASE); /* do CTLESC */
274 split_lit = flag & EXP_SPLIT_LIT;
275 lit_quoted = flag & EXP_LIT_QUOTED;
276 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
277 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
278 p = exptilde(p, flag);
280 CHECKSTRSPACE(2, expdest);
289 /* "$@" syntax adherence hack */
290 if (p[0] == CTLVAR && (p[1] & VSQUOTE) != 0 &&
291 p[2] == '@' && p[3] == '=')
293 if ((flag & EXP_SPLIT) != 0 && expdest == stackblock())
294 dst->state = WORD_QUOTEMARK;
301 if (split_lit && !lit_quoted &&
302 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
303 NEXTWORD(c, flag, expdest, dst);
307 USTPUTC(CTLESC, expdest);
311 p = evalvar(p, flag, dst);
314 case CTLBACKQ|CTLQUOTE:
315 expbackq(argbackq->n, c & CTLQUOTE, flag, dst);
316 argbackq = argbackq->next;
319 p = expari(p, flag, dst);
324 * sort of a hack - expand tildes in variable
325 * assignments (after the first '=' and after ':'s).
327 if (split_lit && !lit_quoted &&
328 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
329 NEXTWORD(c, flag, expdest, dst);
333 if (flag & EXP_VARTILDE && *p == '~' &&
334 (c != '=' || firsteq)) {
337 p = exptilde(p, flag);
341 if (split_lit && !lit_quoted &&
342 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
343 NEXTWORD(c, flag, expdest, dst);
352 * Perform tilde expansion, placing the result in the stack string and
353 * returning the next position in the input string to process.
356 exptilde(const char *p, int flag)
359 const char *startp = p;
368 case CTLESC: /* This means CTL* are always considered quoted. */
371 case CTLBACKQ | CTLQUOTE:
377 if ((flag & EXP_VARTILDE) == 0)
383 len = p - startp - 1;
384 STPUTBIN(startp + 1, len, expdest);
385 STACKSTRNUL(expdest);
386 user = expdest - len;
388 home = lookupvar("HOME");
391 home = pw != NULL ? pw->pw_dir : NULL;
393 STADJUST(-len, expdest);
394 if (home == NULL || *home == '\0')
396 strtodest(home, flag, VSNORMAL, 1, NULL);
405 * Expand arithmetic expression.
408 expari(const char *p, int flag, struct worddest *dst)
416 quoted = *p++ == '"';
417 begoff = expdest - stackblock();
418 p = argstr(p, 0, NULL);
419 STPUTC('\0', expdest);
420 start = stackblock() + begoff;
422 q = grabstackstr(expdest);
423 result = arith(start);
424 ungrabstackstr(q, expdest);
426 start = stackblock() + begoff;
427 adj = start - expdest;
428 STADJUST(adj, expdest);
430 CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
431 fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
432 adj = strlen(expdest);
433 STADJUST(adj, expdest);
435 reprocess(expdest - adj - stackblock(), flag, VSNORMAL, 0, dst);
441 * Perform command substitution.
444 expbackq(union node *cmd, int quoted, int flag, struct worddest *dst)
450 char *dest = expdest;
451 struct nodelist *saveargbackq;
453 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
454 int quotes = flag & (EXP_GLOB | EXP_CASE);
459 saveargbackq = argbackq;
460 p = grabstackstr(dest);
461 evalbackcmd(cmd, &in);
462 ungrabstackstr(p, dest);
466 if (!quoted && flag & EXP_SPLIT)
467 ifs = ifsset() ? ifsval() : " \t\n";
470 /* Don't copy trailing newlines */
472 if (--in.nleft < 0) {
475 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
476 TRACE(("expbackq: read returns %d\n", i));
489 if (strchr(ifs, '\n') != NULL) {
490 NEXTWORD('\n', flag, dest, dst);
493 CHECKSTRSPACE(nnl + 2, dest);
500 if (strchr(ifs, lastc) != NULL)
501 NEXTWORD(lastc, flag, dest, dst);
503 CHECKSTRSPACE(2, dest);
504 if (quotes && syntax[(int)lastc] == CCTL)
505 USTPUTC(CTLESC, dest);
506 USTPUTC(lastc, dest);
516 p = grabstackstr(dest);
517 exitstatus = waitforjob(in.jp, (int *)NULL);
518 ungrabstackstr(p, dest);
520 TRACE(("expbackq: size=%td: \"%.*s\"\n",
521 ((dest - stackblock()) - startloc),
522 (int)((dest - stackblock()) - startloc),
523 stackblock() + startloc));
524 argbackq = saveargbackq;
532 recordleft(const char *str, const char *loc, char *startp)
536 amount = ((str - 1) - (loc - startp)) - expdest;
537 STADJUST(amount, expdest);
538 while (loc != str - 1)
543 subevalvar_trim(const char *p, int strloc, int subtype, int startloc)
549 struct nodelist *saveargbackq = argbackq;
552 argstr(p, EXP_CASE | EXP_TILDE, NULL);
553 STACKSTRNUL(expdest);
554 argbackq = saveargbackq;
555 startp = stackblock() + startloc;
556 str = stackblock() + strloc;
560 for (loc = startp; loc < str; loc++) {
563 if (patmatch(str, startp)) {
565 recordleft(str, loc, startp);
573 for (loc = str - 1; loc >= startp;) {
576 if (patmatch(str, startp)) {
578 recordleft(str, loc, startp);
587 for (loc = str - 1; loc >= startp;) {
588 if (patmatch(str, loc)) {
589 amount = loc - expdest;
590 STADJUST(amount, expdest);
598 for (loc = startp; loc < str - 1; loc++) {
599 if (patmatch(str, loc)) {
600 amount = loc - expdest;
601 STADJUST(amount, expdest);
611 amount = (expdest - stackblock() - strloc) + 1;
612 STADJUST(-amount, expdest);
617 subevalvar_misc(const char *p, const char *var, int subtype, int startloc,
621 struct nodelist *saveargbackq = argbackq;
624 argstr(p, EXP_TILDE, NULL);
625 STACKSTRNUL(expdest);
626 argbackq = saveargbackq;
627 startp = stackblock() + startloc;
631 setvar(var, startp, 0);
632 amount = startp - expdest;
633 STADJUST(amount, expdest);
637 if (*p != CTLENDVAR) {
638 outfmt(out2, "%s\n", startp);
641 error("%.*s: parameter %snot set", (int)(p - var - 1),
642 var, (varflags & VSNUL) ? "null or " : "");
652 * Expand a variable, and return a pointer to the next character in the
657 evalvar(const char *p, int flag, struct worddest *dst)
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 } else if (special) {
685 set = varisset(var, varflags & VSNUL);
688 val = bltinlookup(var, 1);
689 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
696 startloc = expdest - stackblock();
697 if (!set && uflag && *var != '@' && *var != '*') {
705 error("%.*s: parameter not set", (int)(p - var - 1),
709 if (set && subtype != VSPLUS) {
710 /* insert the value of the variable */
712 if (varflags & VSLINENO) {
713 if (p - var > (ptrdiff_t)sizeof(buf))
715 memcpy(buf, var, p - var - 1);
716 buf[p - var - 1] = '\0';
717 strtodest(buf, flag, subtype,
718 varflags & VSQUOTE, dst);
720 varvalue(var, varflags & VSQUOTE, subtype, flag,
722 if (subtype == VSLENGTH) {
723 varlenb = expdest - stackblock() - startloc;
726 val = stackblock() + startloc;
727 for (;val != expdest; val++)
728 if ((*val & 0xC0) == 0x80)
731 STADJUST(-varlenb, expdest);
734 if (subtype == VSLENGTH) {
737 (*val & 0xC0) != 0x80)
741 strtodest(val, flag, subtype,
742 varflags & VSQUOTE, dst);
746 if (subtype == VSPLUS)
752 strtodest(buf, flag, VSNORMAL, varflags & VSQUOTE, dst);
761 argstr(p, flag | (flag & EXP_SPLIT ? EXP_SPLIT_LIT : 0) |
762 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0), dst);
776 * Terminate the string and start recording the pattern
779 STPUTC('\0', expdest);
780 patloc = expdest - stackblock();
781 subevalvar_trim(p, patloc, subtype, startloc);
782 reprocess(startloc, flag, VSNORMAL, varflags & VSQUOTE, dst);
783 if (flag & EXP_SPLIT && *var == '@' && varflags & VSQUOTE)
784 dst->state = WORD_QUOTEMARK;
790 if (subevalvar_misc(p, var, subtype, startloc,
801 error("${%.*s%s}: Bad substitution", c, var,
802 (c > 0 && *p != CTLENDVAR) ? "..." : "");
808 if (subtype != VSNORMAL) { /* skip to end of alternative */
811 if ((c = *p++) == CTLESC)
813 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
815 argbackq = argbackq->next;
816 } else if (c == CTLVAR) {
817 if ((*p++ & VSTYPE) != VSNORMAL)
819 } else if (c == CTLENDVAR) {
831 * Test whether a specialized variable is set.
835 varisset(const char *name, int nulok)
839 return backgndpidset();
840 else if (*name == '@' || *name == '*') {
841 if (*shellparam.p == NULL)
847 for (av = shellparam.p; *av; av++)
852 } else if (is_digit(*name)) {
857 num = strtol(name, NULL, 10);
858 if (errno != 0 || num > shellparam.nparam)
864 ap = shellparam.p[num - 1];
866 if (nulok && (ap == NULL || *ap == '\0'))
873 strtodest(const char *p, int flag, int subtype, int quoted,
874 struct worddest *dst)
876 if (subtype == VSLENGTH || subtype == VSTRIMLEFT ||
877 subtype == VSTRIMLEFTMAX || subtype == VSTRIMRIGHT ||
878 subtype == VSTRIMRIGHTMAX)
880 else if (flag & EXP_SPLIT && !quoted && dst != NULL)
881 STPUTS_SPLIT(p, BASESYNTAX, flag, expdest, dst);
882 else if (flag & (EXP_GLOB | EXP_CASE))
883 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
889 reprocess(int startloc, int flag, int subtype, int quoted,
890 struct worddest *dst)
892 static char *buf = NULL;
893 static size_t buflen = 0;
895 size_t len, zpos, zlen;
897 startp = stackblock() + startloc;
898 len = expdest - startp;
899 if (len >= SIZE_MAX / 2 || len > PTRDIFF_MAX)
908 while (len >= buflen)
911 buf = ckmalloc(buflen);
913 memcpy(buf, startp, len);
915 STADJUST(-(ptrdiff_t)len, expdest);
917 zlen = strlen(buf + zpos);
918 strtodest(buf + zpos, flag, subtype, quoted, dst);
922 if (flag & EXP_SPLIT && (quoted || (zlen > 0 && zpos < len)))
923 NEXTWORD('\0', flag, expdest, dst);
928 * Add the value of a specialized variable to the stack string.
932 varvalue(const char *name, int quoted, int subtype, int flag,
933 struct worddest *dst)
941 char buf[(NSHORTOPTS > 10 ? NSHORTOPTS : 10) + 1];
943 if (subtype == VSLENGTH)
945 splitlater = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
946 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX;
956 num = shellparam.nparam;
959 num = backgndpidval();
963 for (i = 0 ; i < NSHORTOPTS ; i++) {
968 strtodest(buf, flag, subtype, quoted, dst);
971 if (flag & EXP_SPLIT && quoted) {
972 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
973 strtodest(p, flag, subtype, quoted, dst);
976 STPUTC('\0', expdest);
978 NEXTWORD('\0', flag, expdest,
982 if (shellparam.nparam > 0)
983 dst->state = WORD_QUOTEMARK;
989 sep[0] = ifsval()[0];
993 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
994 strtodest(p, flag, subtype, quoted, dst);
998 strtodest(sep, flag, subtype, quoted, dst);
999 else if (flag & EXP_SPLIT && !quoted && **ap != '\0') {
1001 STPUTC('\0', expdest);
1003 NEXTWORD('\0', flag, expdest, dst);
1008 if (is_digit(*name)) {
1012 else if (num > 0 && num <= shellparam.nparam)
1013 p = shellparam.p[num - 1];
1016 strtodest(p, flag, subtype, quoted, dst);
1021 strtodest(buf, flag, subtype, quoted, dst);
1026 static char expdir[PATH_MAX];
1027 #define expdir_end (expdir + sizeof(expdir))
1030 * Perform pathname generation and remove control characters.
1031 * At this point, the only control characters should be CTLESC.
1032 * The results are stored in the list dstlist.
1035 expandmeta(char *pattern, struct arglist *dstlist)
1041 firstmatch = dstlist->count;
1043 for (; (c = *p) != '\0'; p++) {
1044 /* fast check for meta chars */
1045 if (c == '*' || c == '?' || c == '[') {
1047 expmeta(expdir, pattern, dstlist);
1052 if (dstlist->count == firstmatch) {
1057 appendarglist(dstlist, pattern);
1059 qsort(&dstlist->args[firstmatch],
1060 dstlist->count - firstmatch,
1061 sizeof(dstlist->args[0]), expsortcmp);
1067 * Do metacharacter (i.e. *, ?, [...]) expansion.
1071 expmeta(char *enddir, char *name, struct arglist *arglist)
1088 for (p = name; esc = 0, *p; p += esc + 1) {
1089 if (*p == '*' || *p == '?')
1091 else if (*p == '[') {
1093 if (*q == '!' || *q == '^')
1098 if (*q == '/' || *q == '\0')
1105 } else if (*p == '\0')
1110 if (p[esc] == '/') {
1113 start = p + esc + 1;
1117 if (metaflag == 0) { /* we've reached the end of the file name */
1118 if (enddir != expdir)
1120 for (p = name ; ; p++) {
1126 if (enddir == expdir_end)
1129 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1130 appendarglist(arglist, stsavestr(expdir));
1133 endname = name + (p - name);
1134 if (start != name) {
1140 if (enddir == expdir_end)
1144 if (enddir == expdir) {
1146 } else if (enddir == expdir + 1 && *expdir == '/') {
1152 if ((dirp = opendir(p)) == NULL)
1154 if (enddir != expdir)
1156 if (*endname == 0) {
1169 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1170 if (dp->d_name[0] == '.' && ! matchdot)
1172 if (patmatch(start, dp->d_name)) {
1173 namlen = dp->d_namlen;
1174 if (enddir + namlen + 1 > expdir_end)
1176 memcpy(enddir, dp->d_name, namlen + 1);
1178 appendarglist(arglist, stsavestr(expdir));
1180 if (dp->d_type != DT_UNKNOWN &&
1181 dp->d_type != DT_DIR &&
1182 dp->d_type != DT_LNK)
1184 if (enddir + namlen + 2 > expdir_end)
1186 enddir[namlen] = '/';
1187 enddir[namlen + 1] = '\0';
1188 expmeta(enddir + namlen + 1, endname, arglist);
1194 endname[-esc - 1] = esc ? CTLESC : '/';
1199 expsortcmp(const void *p1, const void *p2)
1201 const char *s1 = *(const char * const *)p1;
1202 const char *s2 = *(const char * const *)p2;
1204 return (strcoll(s1, s2));
1210 get_wc(const char **p)
1215 chrlen = mbtowc(&c, *p, 4);
1218 else if (chrlen == -1)
1227 * See if a character matches a character class, starting at the first colon
1229 * If a valid character class is recognized, a pointer to the next character
1230 * after the final closing bracket is stored into *end, otherwise a null
1231 * pointer is stored into *end.
1234 match_charclass(const char *p, wchar_t chr, const char **end)
1237 const char *nameend;
1242 nameend = strstr(p, ":]");
1243 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1246 memcpy(name, p, nameend - p);
1247 name[nameend - p] = '\0';
1249 cclass = wctype(name);
1250 /* An unknown class matches nothing but is valid nevertheless. */
1253 return iswctype(chr, cclass);
1258 * Returns true if the pattern matches the string.
1262 patmatch(const char *pattern, const char *string)
1264 const char *p, *q, *end;
1265 const char *bt_p, *bt_q;
1289 * A '?' does not match invalid UTF-8 but a
1290 * '*' does, so backtrack.
1302 * If the pattern ends here, we know the string
1303 * matches without needing to look at the rest of it.
1308 * First try the shortest match for the '*' that
1309 * could work. We can forget any earlier '*' since
1310 * there is no way having it match more characters
1311 * can help us, given that we are already here.
1317 const char *savep, *saveq;
1321 savep = p, saveq = q;
1323 if (*p == '!' || *p == '^') {
1335 chr = (unsigned char)*q++;
1339 p = savep, q = saveq;
1343 if (c == '[' && *p == ':') {
1344 found |= match_charclass(p, chr, &end);
1352 if (localeisutf8 && c & 0x80) {
1355 if (wc == 0) /* bad utf-8 */
1358 wc = (unsigned char)c;
1359 if (*p == '-' && p[1] != ']') {
1365 if (wc2 == 0) /* bad utf-8 */
1368 wc2 = (unsigned char)*p++;
1369 if ( collate_range_cmp(chr, wc) >= 0
1370 && collate_range_cmp(chr, wc2) <= 0
1377 } while ((c = *p++) != ']');
1378 if (found == invert)
1389 * If we have a mismatch (other than hitting the end
1390 * of the string), go back to the last '*' seen and
1391 * have it match one additional character.
1408 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1412 rmescapes(char *str)
1417 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1423 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1437 * See if a pattern matches in a case statement.
1441 casematch(union node *pattern, const char *val)
1443 struct stackmark smark;
1447 setstackmark(&smark);
1448 argbackq = pattern->narg.backquote;
1449 STARTSTACKSTR(expdest);
1450 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE, NULL);
1451 STPUTC('\0', expdest);
1452 p = grabstackstr(expdest);
1453 result = patmatch(p, val);
1454 popstackmark(&smark);
1463 cvtnum(int num, char *buf)
1467 char *p = temp + 31;
1472 *--p = num % 10 + '0';
1473 } while ((num /= 10) != 0);
1478 memcpy(buf, p, temp + 32 - p);
1482 * Do most of the work for wordexp(3).
1486 wordexpcmd(int argc, char **argv)
1491 out1fmt("%08x", argc - 1);
1492 for (i = 1, len = 0; i < argc; i++)
1493 len += strlen(argv[i]);
1494 out1fmt("%08x", (int)len);
1495 for (i = 1; i < argc; i++)
1496 outbin(argv[i], strlen(argv[i]) + 1, out1);
1501 * Do most of the work for wordexp(3), new version.
1505 freebsd_wordexpcmd(int argc __unused, char **argv __unused)
1507 struct arglist arglist;
1508 union node *args, *n;
1515 while ((ch = nextopt("f:p")) != '\0') {
1518 fd = number(shoptarg);
1525 if (*argptr != NULL)
1526 error("wrong number of arguments");
1528 error("missing fd");
1532 args = parsewordexp();
1533 popfile(); /* will also close fd */
1535 for (n = args; n != NULL; n = n->narg.next) {
1536 if (n->narg.backquote != NULL) {
1537 outcslow('C', out1);
1538 error("command substitution disabled");
1541 outcslow(' ', out1);
1542 emptyarglist(&arglist);
1543 for (n = args; n != NULL; n = n->narg.next)
1544 expandarg(n, &arglist, EXP_FULL | EXP_TILDE);
1545 for (i = 0, len = 0; i < arglist.count; i++)
1546 len += strlen(arglist.args[i]);
1547 out1fmt("%016x %016zx", arglist.count, len);
1548 for (i = 0; i < arglist.count; i++)
1549 outbin(arglist.args[i], strlen(arglist.args[i]) + 1, out1);