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 * 3. 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 */
93 static const char *argstr(const char *, struct nodelist **restrict, int,
95 static const char *exptilde(const char *, int);
96 static const char *expari(const char *, struct nodelist **restrict, int,
98 static void expbackq(union node *, int, int, struct worddest *);
99 static void subevalvar_trim(const char *, struct nodelist *, int, int, int);
100 static void subevalvar_misc(const char *, struct nodelist *, const char *, int,
102 static const char *evalvar(const char *, struct nodelist **restrict, int,
104 static int varisset(const char *, int);
105 static void strtodest(const char *, int, int, int, struct worddest *);
106 static void reprocess(int, int, int, int, struct worddest *);
107 static void varvalue(const char *, int, int, int, struct worddest *);
108 static void expandmeta(char *, struct arglist *);
109 static void expmeta(char *, char *, struct arglist *);
110 static int expsortcmp(const void *, const void *);
111 static int patmatch(const char *, const char *);
112 static void cvtnum(int, char *);
113 static int collate_range_cmp(wchar_t, wchar_t);
116 emptyarglist(struct arglist *list)
119 list->args = list->smallarg;
121 list->capacity = sizeof(list->smallarg) / sizeof(list->smallarg[0]);
125 appendarglist(struct arglist *list, char *str)
130 if (list->count >= list->capacity) {
131 newcapacity = list->capacity * 2;
132 if (newcapacity < 16)
134 if (newcapacity > INT_MAX / (int)sizeof(newargs[0]))
135 error("Too many entries in arglist");
136 newargs = stalloc(newcapacity * sizeof(newargs[0]));
137 memcpy(newargs, list->args, list->count * sizeof(newargs[0]));
138 list->args = newargs;
139 list->capacity = newcapacity;
141 list->args[list->count++] = str;
145 collate_range_cmp(wchar_t c1, wchar_t c2)
147 static wchar_t s1[2], s2[2];
151 return (wcscoll(s1, s2));
155 stputs_quotes(const char *data, const char *syntax, char *p)
159 if (syntax[(int)*data] == CCTL)
165 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
168 nextword(char c, int flag, char *p, struct worddest *dst)
172 is_ws = c == '\t' || c == '\n' || c == ' ';
173 if (p != stackblock() || (is_ws ? dst->state == WORD_QUOTEMARK :
174 dst->state != WORD_WS_DELIMITED) || c == '\0') {
177 expandmeta(grabstackstr(p), dst->list);
179 appendarglist(dst->list, grabstackstr(p));
180 dst->state = is_ws ? WORD_WS_DELIMITED : WORD_IDLE;
181 } else if (!is_ws && dst->state == WORD_WS_DELIMITED)
182 dst->state = WORD_IDLE;
183 /* Reserve space while the stack string is empty. */
184 appendarglist(dst->list, NULL);
189 #define NEXTWORD(c, flag, p, dstlist) p = nextword(c, flag, p, dstlist)
192 stputs_split(const char *data, const char *syntax, int flag, char *p,
193 struct worddest *dst)
198 ifs = ifsset() ? ifsval() : " \t\n";
202 if (strchr(ifs, c) != NULL) {
203 NEXTWORD(c, flag, p, dst);
206 if (flag & EXP_GLOB && syntax[(int)c] == CCTL)
212 #define STPUTS_SPLIT(data, syntax, flag, p, dst) p = stputs_split((data), syntax, flag, p, dst)
215 * Perform expansions on an argument, placing the resulting list of arguments
216 * in arglist. Parameter expansion, command substitution and arithmetic
217 * expansion are always performed; additional expansions can be requested
219 * The result is left in the stack string.
220 * When arglist is NULL, perform here document expansion.
222 * Caution: this function uses global state and is not reentrant.
223 * However, a new invocation after an interrupted invocation is safe
224 * and will reset the global state for the new call.
227 expandarg(union node *arg, struct arglist *arglist, int flag)
229 struct worddest exparg;
230 struct nodelist *argbackq;
234 argbackq = arg->narg.backquote;
235 exparg.list = arglist;
236 exparg.state = WORD_IDLE;
237 STARTSTACKSTR(expdest);
238 argstr(arg->narg.text, &argbackq, flag, &exparg);
239 if (arglist == NULL) {
240 STACKSTRNUL(expdest);
241 return; /* here document expanded */
243 if ((flag & EXP_SPLIT) == 0 || expdest != stackblock() ||
244 exparg.state == WORD_QUOTEMARK) {
245 STPUTC('\0', expdest);
246 if (flag & EXP_SPLIT) {
248 expandmeta(grabstackstr(expdest), exparg.list);
250 appendarglist(exparg.list, grabstackstr(expdest));
253 if ((flag & EXP_SPLIT) == 0)
254 appendarglist(arglist, grabstackstr(expdest));
260 * Perform parameter expansion, command substitution and arithmetic
261 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
262 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
263 * This is used to expand word in ${var+word} etc.
264 * If EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC
265 * characters to allow for further processing.
267 * If EXP_SPLIT is set, dst receives any complete words produced.
270 argstr(const char *p, struct nodelist **restrict argbackq, int flag,
271 struct worddest *dst)
274 int quotes = flag & (EXP_GLOB | EXP_CASE); /* do CTLESC */
279 split_lit = flag & EXP_SPLIT_LIT;
280 lit_quoted = flag & EXP_LIT_QUOTED;
281 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
282 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
283 p = exptilde(p, flag);
285 CHECKSTRSPACE(2, expdest);
294 /* "$@" syntax adherence hack */
295 if (p[0] == CTLVAR && (p[1] & VSQUOTE) != 0 &&
296 p[2] == '@' && p[3] == '=')
298 if ((flag & EXP_SPLIT) != 0 && expdest == stackblock())
299 dst->state = WORD_QUOTEMARK;
306 if (split_lit && !lit_quoted &&
307 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
308 NEXTWORD(c, flag, expdest, dst);
312 USTPUTC(CTLESC, expdest);
316 p = evalvar(p, argbackq, flag, dst);
319 case CTLBACKQ|CTLQUOTE:
320 expbackq((*argbackq)->n, c & CTLQUOTE, flag, dst);
321 *argbackq = (*argbackq)->next;
324 p = expari(p, argbackq, flag, dst);
329 * sort of a hack - expand tildes in variable
330 * assignments (after the first '=' and after ':'s).
332 if (split_lit && !lit_quoted &&
333 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
334 NEXTWORD(c, flag, expdest, dst);
338 if (flag & EXP_VARTILDE && *p == '~' &&
339 (c != '=' || firsteq)) {
342 p = exptilde(p, flag);
346 if (split_lit && !lit_quoted &&
347 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
348 NEXTWORD(c, flag, expdest, dst);
357 * Perform tilde expansion, placing the result in the stack string and
358 * returning the next position in the input string to process.
361 exptilde(const char *p, int flag)
364 const char *startp = p;
373 case CTLESC: /* This means CTL* are always considered quoted. */
376 case CTLBACKQ | CTLQUOTE:
382 if ((flag & EXP_VARTILDE) == 0)
388 len = p - startp - 1;
389 STPUTBIN(startp + 1, len, expdest);
390 STACKSTRNUL(expdest);
391 user = expdest - len;
393 home = lookupvar("HOME");
396 home = pw != NULL ? pw->pw_dir : NULL;
398 STADJUST(-len, expdest);
399 if (home == NULL || *home == '\0')
401 strtodest(home, flag, VSNORMAL, 1, NULL);
410 * Expand arithmetic expression.
413 expari(const char *p, struct nodelist **restrict argbackq, int flag,
414 struct worddest *dst)
422 quoted = *p++ == '"';
423 begoff = expdest - stackblock();
424 p = argstr(p, argbackq, 0, NULL);
425 STPUTC('\0', expdest);
426 start = stackblock() + begoff;
428 q = grabstackstr(expdest);
429 result = arith(start);
430 ungrabstackstr(q, expdest);
432 start = stackblock() + begoff;
433 adj = start - expdest;
434 STADJUST(adj, expdest);
436 CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
437 fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
438 adj = strlen(expdest);
439 STADJUST(adj, expdest);
441 reprocess(expdest - adj - stackblock(), flag, VSNORMAL, 0, dst);
447 * Perform command substitution.
450 expbackq(union node *cmd, int quoted, int flag, struct worddest *dst)
456 char *dest = expdest;
458 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
459 int quotes = flag & (EXP_GLOB | EXP_CASE);
464 p = grabstackstr(dest);
465 evalbackcmd(cmd, &in);
466 ungrabstackstr(p, dest);
470 if (!quoted && flag & EXP_SPLIT)
471 ifs = ifsset() ? ifsval() : " \t\n";
474 /* Don't copy trailing newlines */
476 if (--in.nleft < 0) {
479 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR)
481 TRACE(("expbackq: read returns %d\n", i));
494 if (strchr(ifs, '\n') != NULL) {
495 NEXTWORD('\n', flag, dest, dst);
498 CHECKSTRSPACE(nnl + 2, dest);
505 if (strchr(ifs, lastc) != NULL)
506 NEXTWORD(lastc, flag, dest, dst);
508 CHECKSTRSPACE(2, dest);
509 if (quotes && syntax[(int)lastc] == CCTL)
510 USTPUTC(CTLESC, dest);
511 USTPUTC(lastc, dest);
521 p = grabstackstr(dest);
522 exitstatus = waitforjob(in.jp, (int *)NULL);
523 ungrabstackstr(p, dest);
525 TRACE(("expbackq: done\n"));
533 recordleft(const char *str, const char *loc, char *startp)
537 amount = ((str - 1) - (loc - startp)) - expdest;
538 STADJUST(amount, expdest);
539 while (loc != str - 1)
544 subevalvar_trim(const char *p, struct nodelist *argbackq, int strloc,
545 int subtype, int startloc)
551 struct nodelist *argbackqcopy = argbackq;
554 argstr(p, &argbackqcopy, EXP_CASE | EXP_TILDE, NULL);
555 STACKSTRNUL(expdest);
556 startp = stackblock() + startloc;
557 str = stackblock() + strloc;
561 for (loc = startp; loc < str; loc++) {
564 if (patmatch(str, startp)) {
566 recordleft(str, loc, startp);
574 for (loc = str - 1; loc >= startp;) {
577 if (patmatch(str, startp)) {
579 recordleft(str, loc, startp);
588 for (loc = str - 1; loc >= startp;) {
589 if (patmatch(str, loc)) {
590 amount = loc - expdest;
591 STADJUST(amount, expdest);
599 for (loc = startp; loc < str - 1; loc++) {
600 if (patmatch(str, loc)) {
601 amount = loc - expdest;
602 STADJUST(amount, expdest);
612 amount = (expdest - stackblock() - strloc) + 1;
613 STADJUST(-amount, expdest);
618 subevalvar_misc(const char *p, struct nodelist *argbackq, const char *var, int subtype, int startloc,
622 struct nodelist *argbackqcopy = argbackq;
625 argstr(p, &argbackqcopy, EXP_TILDE, NULL);
626 STACKSTRNUL(expdest);
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 " : "");
651 * Expand a variable, and return a pointer to the next character in the
656 evalvar(const char *p, struct nodelist **restrict argbackq, int flag,
657 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 return argstr(p, argbackq,
762 flag | (flag & EXP_SPLIT ? EXP_SPLIT_LIT : 0) |
763 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0), dst);
774 * Terminate the string and start recording the pattern
777 STPUTC('\0', expdest);
778 patloc = expdest - stackblock();
779 subevalvar_trim(p, *argbackq, patloc, subtype, startloc);
780 reprocess(startloc, flag, VSNORMAL, varflags & VSQUOTE, dst);
781 if (flag & EXP_SPLIT && *var == '@' && varflags & VSQUOTE)
782 dst->state = WORD_QUOTEMARK;
788 subevalvar_misc(p, *argbackq, var, subtype,
790 /* assert(subtype == VSASSIGN); */
798 error("${%.*s%s}: Bad substitution", c, var,
799 (c > 0 && *p != CTLENDVAR) ? "..." : "");
805 { /* skip to end of alternative */
808 if ((c = *p++) == CTLESC)
810 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE))
811 *argbackq = (*argbackq)->next;
812 else if (c == CTLVAR) {
813 if ((*p++ & VSTYPE) != VSNORMAL)
815 } else if (c == CTLENDVAR) {
827 * Test whether a specialized variable is set.
831 varisset(const char *name, int nulok)
835 return backgndpidset();
836 else if (*name == '@' || *name == '*') {
837 if (*shellparam.p == NULL)
843 for (av = shellparam.p; *av; av++)
848 } else if (is_digit(*name)) {
853 num = strtol(name, NULL, 10);
854 if (errno != 0 || num > shellparam.nparam)
860 ap = shellparam.p[num - 1];
862 if (nulok && (ap == NULL || *ap == '\0'))
869 strtodest(const char *p, int flag, int subtype, int quoted,
870 struct worddest *dst)
872 if (subtype == VSLENGTH || subtype == VSTRIMLEFT ||
873 subtype == VSTRIMLEFTMAX || subtype == VSTRIMRIGHT ||
874 subtype == VSTRIMRIGHTMAX)
876 else if (flag & EXP_SPLIT && !quoted && dst != NULL)
877 STPUTS_SPLIT(p, BASESYNTAX, flag, expdest, dst);
878 else if (flag & (EXP_GLOB | EXP_CASE))
879 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
885 reprocess(int startloc, int flag, int subtype, int quoted,
886 struct worddest *dst)
888 static char *buf = NULL;
889 static size_t buflen = 0;
891 size_t len, zpos, zlen;
893 startp = stackblock() + startloc;
894 len = expdest - startp;
895 if (len >= SIZE_MAX / 2)
904 while (len >= buflen)
907 buf = ckmalloc(buflen);
909 memcpy(buf, startp, len);
911 STADJUST(-len, expdest);
913 zlen = strlen(buf + zpos);
914 strtodest(buf + zpos, flag, subtype, quoted, dst);
918 if (flag & EXP_SPLIT && (quoted || (zlen > 0 && zpos < len)))
919 NEXTWORD('\0', flag, expdest, dst);
924 * Add the value of a specialized variable to the stack string.
928 varvalue(const char *name, int quoted, int subtype, int flag,
929 struct worddest *dst)
937 char buf[(NSHORTOPTS > 10 ? NSHORTOPTS : 10) + 1];
939 if (subtype == VSLENGTH)
941 splitlater = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
942 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX;
952 num = shellparam.nparam;
955 num = backgndpidval();
959 for (i = 0 ; i < NSHORTOPTS ; i++) {
964 strtodest(buf, flag, subtype, quoted, dst);
967 if (flag & EXP_SPLIT && quoted) {
968 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
969 strtodest(p, flag, subtype, quoted, dst);
972 STPUTC('\0', expdest);
974 NEXTWORD('\0', flag, expdest,
978 if (shellparam.nparam > 0)
979 dst->state = WORD_QUOTEMARK;
985 sep[0] = ifsval()[0];
989 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
990 strtodest(p, flag, subtype, quoted, dst);
994 strtodest(sep, flag, subtype, quoted, dst);
995 else if (flag & EXP_SPLIT && !quoted && **ap != '\0') {
997 STPUTC('\0', expdest);
999 NEXTWORD('\0', flag, expdest, dst);
1004 if (is_digit(*name)) {
1008 else if (num > 0 && num <= shellparam.nparam)
1009 p = shellparam.p[num - 1];
1012 strtodest(p, flag, subtype, quoted, dst);
1017 strtodest(buf, flag, subtype, quoted, dst);
1022 static char expdir[PATH_MAX];
1023 #define expdir_end (expdir + sizeof(expdir))
1026 * Perform pathname generation and remove control characters.
1027 * At this point, the only control characters should be CTLESC.
1028 * The results are stored in the list dstlist.
1031 expandmeta(char *pattern, struct arglist *dstlist)
1037 firstmatch = dstlist->count;
1039 for (; (c = *p) != '\0'; p++) {
1040 /* fast check for meta chars */
1041 if (c == '*' || c == '?' || c == '[') {
1043 expmeta(expdir, pattern, dstlist);
1048 if (dstlist->count == firstmatch) {
1053 appendarglist(dstlist, pattern);
1055 qsort(&dstlist->args[firstmatch],
1056 dstlist->count - firstmatch,
1057 sizeof(dstlist->args[0]), expsortcmp);
1063 * Do metacharacter (i.e. *, ?, [...]) expansion.
1067 expmeta(char *enddir, char *name, struct arglist *arglist)
1084 for (p = name; esc = 0, *p; p += esc + 1) {
1085 if (*p == '*' || *p == '?')
1087 else if (*p == '[') {
1089 if (*q == '!' || *q == '^')
1094 if (*q == '/' || *q == '\0')
1101 } else if (*p == '\0')
1106 if (p[esc] == '/') {
1109 start = p + esc + 1;
1113 if (metaflag == 0) { /* we've reached the end of the file name */
1114 if (enddir != expdir)
1116 for (p = name ; ; p++) {
1122 if (enddir == expdir_end)
1125 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1126 appendarglist(arglist, stsavestr(expdir));
1129 endname = name + (p - name);
1130 if (start != name) {
1136 if (enddir == expdir_end)
1140 if (enddir == expdir) {
1142 } else if (enddir == expdir + 1 && *expdir == '/') {
1148 if ((dirp = opendir(p)) == NULL)
1150 if (enddir != expdir)
1152 if (*endname == 0) {
1165 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1166 if (dp->d_name[0] == '.' && ! matchdot)
1168 if (patmatch(start, dp->d_name)) {
1169 namlen = dp->d_namlen;
1170 if (enddir + namlen + 1 > expdir_end)
1172 memcpy(enddir, dp->d_name, namlen + 1);
1174 appendarglist(arglist, stsavestr(expdir));
1176 if (dp->d_type != DT_UNKNOWN &&
1177 dp->d_type != DT_DIR &&
1178 dp->d_type != DT_LNK)
1180 if (enddir + namlen + 2 > expdir_end)
1182 enddir[namlen] = '/';
1183 enddir[namlen + 1] = '\0';
1184 expmeta(enddir + namlen + 1, endname, arglist);
1190 endname[-esc - 1] = esc ? CTLESC : '/';
1195 expsortcmp(const void *p1, const void *p2)
1197 const char *s1 = *(const char * const *)p1;
1198 const char *s2 = *(const char * const *)p2;
1200 return (strcoll(s1, s2));
1206 get_wc(const char **p)
1211 chrlen = mbtowc(&c, *p, 4);
1214 else if (chrlen == -1)
1223 * See if a character matches a character class, starting at the first colon
1225 * If a valid character class is recognized, a pointer to the next character
1226 * after the final closing bracket is stored into *end, otherwise a null
1227 * pointer is stored into *end.
1230 match_charclass(const char *p, wchar_t chr, const char **end)
1233 const char *nameend;
1238 nameend = strstr(p, ":]");
1239 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1242 memcpy(name, p, nameend - p);
1243 name[nameend - p] = '\0';
1245 cclass = wctype(name);
1246 /* An unknown class matches nothing but is valid nevertheless. */
1249 return iswctype(chr, cclass);
1254 * Returns true if the pattern matches the string.
1258 patmatch(const char *pattern, const char *string)
1260 const char *p, *q, *end;
1261 const char *bt_p, *bt_q;
1285 * A '?' does not match invalid UTF-8 but a
1286 * '*' does, so backtrack.
1298 * If the pattern ends here, we know the string
1299 * matches without needing to look at the rest of it.
1304 * First try the shortest match for the '*' that
1305 * could work. We can forget any earlier '*' since
1306 * there is no way having it match more characters
1307 * can help us, given that we are already here.
1313 const char *savep, *saveq;
1317 savep = p, saveq = q;
1319 if (*p == '!' || *p == '^') {
1331 chr = (unsigned char)*q++;
1335 p = savep, q = saveq;
1339 if (c == '[' && *p == ':') {
1340 found |= match_charclass(p, chr, &end);
1346 if (localeisutf8 && c & 0x80) {
1349 if (wc == 0) /* bad utf-8 */
1352 wc = (unsigned char)c;
1353 if (*p == '-' && p[1] != ']') {
1359 if (wc2 == 0) /* bad utf-8 */
1362 wc2 = (unsigned char)*p++;
1363 if ( collate_range_cmp(chr, wc) >= 0
1364 && collate_range_cmp(chr, wc2) <= 0
1371 } while ((c = *p++) != ']');
1372 if (found == invert)
1383 * If we have a mismatch (other than hitting the end
1384 * of the string), go back to the last '*' seen and
1385 * have it match one additional character.
1402 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1406 rmescapes(char *str)
1411 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1417 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1431 * See if a pattern matches in a case statement.
1435 casematch(union node *pattern, const char *val)
1437 struct stackmark smark;
1438 struct nodelist *argbackq;
1442 setstackmark(&smark);
1443 argbackq = pattern->narg.backquote;
1444 STARTSTACKSTR(expdest);
1445 argstr(pattern->narg.text, &argbackq, EXP_TILDE | EXP_CASE, NULL);
1446 STPUTC('\0', expdest);
1447 p = grabstackstr(expdest);
1448 result = patmatch(p, val);
1449 popstackmark(&smark);
1458 cvtnum(int num, char *buf)
1462 char *p = temp + 31;
1467 *--p = num % 10 + '0';
1468 } while ((num /= 10) != 0);
1473 memcpy(buf, p, temp + 32 - p);
1477 * Do most of the work for wordexp(3).
1481 wordexpcmd(int argc, char **argv)
1486 out1fmt("%08x", argc - 1);
1487 for (i = 1, len = 0; i < argc; i++)
1488 len += strlen(argv[i]);
1489 out1fmt("%08x", (int)len);
1490 for (i = 1; i < argc; i++)
1491 outbin(argv[i], strlen(argv[i]) + 1, out1);
1496 * Do most of the work for wordexp(3), new version.
1500 freebsd_wordexpcmd(int argc __unused, char **argv __unused)
1502 struct arglist arglist;
1503 union node *args, *n;
1510 while ((ch = nextopt("f:p")) != '\0') {
1513 fd = number(shoptarg);
1520 if (*argptr != NULL)
1521 error("wrong number of arguments");
1523 error("missing fd");
1527 args = parsewordexp();
1528 popfile(); /* will also close fd */
1530 for (n = args; n != NULL; n = n->narg.next) {
1531 if (n->narg.backquote != NULL) {
1532 outcslow('C', out1);
1533 error("command substitution disabled");
1536 outcslow(' ', out1);
1537 emptyarglist(&arglist);
1538 for (n = args; n != NULL; n = n->narg.next)
1539 expandarg(n, &arglist, EXP_FULL | EXP_TILDE);
1540 for (i = 0, len = 0; i < arglist.count; i++)
1541 len += strlen(arglist.args[i]);
1542 out1fmt("%016x %016zx", arglist.count, len);
1543 for (i = 0; i < arglist.count; i++)
1544 outbin(arglist.args[i], strlen(arglist.args[i]) + 1, out1);