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
37 #include <sys/types.h>
53 * Routines to expand arguments to commands. We have to deal with
54 * backquotes, shell variables, and file metacharacters.
76 enum wordstate { WORD_IDLE, WORD_WS_DELIMITED, WORD_QUOTEMARK };
83 static char *expdest; /* output of current string */
85 static const char *argstr(const char *, struct nodelist **restrict, int,
87 static const char *exptilde(const char *, int);
88 static const char *expari(const char *, struct nodelist **restrict, int,
90 static void expbackq(union node *, int, int, struct worddest *);
91 static const char *subevalvar_trim(const char *, struct nodelist **restrict,
93 static const char *subevalvar_misc(const char *, struct nodelist **restrict,
94 const char *, int, int, int);
95 static const char *evalvar(const char *, struct nodelist **restrict, int,
97 static int varisset(const char *, int);
98 static void strtodest(const char *, int, int, int, struct worddest *);
99 static void reprocess(int, int, int, int, struct worddest *);
100 static void varvalue(const char *, int, int, int, struct worddest *);
101 static void expandmeta(char *, struct arglist *);
102 static void expmeta(char *, char *, struct arglist *);
103 static int expsortcmp(const void *, const void *);
104 static int patmatch(const char *, const char *);
105 static void cvtnum(int, char *);
106 static int collate_range_cmp(wchar_t, wchar_t);
109 emptyarglist(struct arglist *list)
112 list->args = list->smallarg;
114 list->capacity = sizeof(list->smallarg) / sizeof(list->smallarg[0]);
118 appendarglist(struct arglist *list, char *str)
123 if (list->count >= list->capacity) {
124 newcapacity = list->capacity * 2;
125 if (newcapacity < 16)
127 if (newcapacity > INT_MAX / (int)sizeof(newargs[0]))
128 error("Too many entries in arglist");
129 newargs = stalloc(newcapacity * sizeof(newargs[0]));
130 memcpy(newargs, list->args, list->count * sizeof(newargs[0]));
131 list->args = newargs;
132 list->capacity = newcapacity;
134 list->args[list->count++] = str;
138 collate_range_cmp(wchar_t c1, wchar_t c2)
140 wchar_t s1[2], s2[2];
146 return (wcscoll(s1, s2));
150 stputs_quotes(const char *data, const char *syntax, char *p)
154 if (syntax[(int)*data] == CCTL)
160 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
163 nextword(char c, int flag, char *p, struct worddest *dst)
167 is_ws = c == '\t' || c == '\n' || c == ' ';
168 if (p != stackblock() || (is_ws ? dst->state == WORD_QUOTEMARK :
169 dst->state != WORD_WS_DELIMITED) || c == '\0') {
172 expandmeta(grabstackstr(p), dst->list);
174 appendarglist(dst->list, grabstackstr(p));
175 dst->state = is_ws ? WORD_WS_DELIMITED : WORD_IDLE;
176 } else if (!is_ws && dst->state == WORD_WS_DELIMITED)
177 dst->state = WORD_IDLE;
178 /* Reserve space while the stack string is empty. */
179 appendarglist(dst->list, NULL);
184 #define NEXTWORD(c, flag, p, dstlist) p = nextword(c, flag, p, dstlist)
187 stputs_split(const char *data, const char *syntax, int flag, char *p,
188 struct worddest *dst)
193 ifs = ifsset() ? ifsval() : " \t\n";
197 if (strchr(ifs, c) != NULL) {
198 NEXTWORD(c, flag, p, dst);
201 if (flag & EXP_GLOB && syntax[(int)c] == CCTL)
207 #define STPUTS_SPLIT(data, syntax, flag, p, dst) p = stputs_split((data), syntax, flag, p, dst)
210 * Perform expansions on an argument, placing the resulting list of arguments
211 * in arglist. Parameter expansion, command substitution and arithmetic
212 * expansion are always performed; additional expansions can be requested
214 * The result is left in the stack string.
215 * When arglist is NULL, perform here document expansion.
217 * When doing something that may cause this to be re-entered, make sure
218 * the stack string is empty via grabstackstr() and do not assume expdest
222 expandarg(union node *arg, struct arglist *arglist, int flag)
224 struct worddest exparg;
225 struct nodelist *argbackq;
229 argbackq = arg->narg.backquote;
230 exparg.list = arglist;
231 exparg.state = WORD_IDLE;
232 STARTSTACKSTR(expdest);
233 argstr(arg->narg.text, &argbackq, flag, &exparg);
234 if (arglist == NULL) {
235 STACKSTRNUL(expdest);
236 return; /* here document expanded */
238 if ((flag & EXP_SPLIT) == 0 || expdest != stackblock() ||
239 exparg.state == WORD_QUOTEMARK) {
240 STPUTC('\0', expdest);
241 if (flag & EXP_SPLIT) {
243 expandmeta(grabstackstr(expdest), exparg.list);
245 appendarglist(exparg.list, grabstackstr(expdest));
248 if ((flag & EXP_SPLIT) == 0)
249 appendarglist(arglist, grabstackstr(expdest));
255 * Perform parameter expansion, command substitution and arithmetic
256 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
257 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
258 * This is used to expand word in ${var+word} etc.
259 * If EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC
260 * characters to allow for further processing.
262 * If EXP_SPLIT is set, dst receives any complete words produced.
265 argstr(const char *p, struct nodelist **restrict argbackq, int flag,
266 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, argbackq, flag, dst);
314 case CTLBACKQ|CTLQUOTE:
315 expbackq((*argbackq)->n, c & CTLQUOTE, flag, dst);
316 *argbackq = (*argbackq)->next;
319 p = expari(p, argbackq, 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, struct nodelist **restrict argbackq, int flag,
409 struct worddest *dst)
417 quoted = *p++ == '"';
418 begoff = expdest - stackblock();
419 p = argstr(p, argbackq, 0, NULL);
420 STPUTC('\0', expdest);
421 start = stackblock() + begoff;
423 q = grabstackstr(expdest);
424 result = arith(start);
425 ungrabstackstr(q, expdest);
427 start = stackblock() + begoff;
428 adj = start - expdest;
429 STADJUST(adj, expdest);
431 CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
432 fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
433 adj = strlen(expdest);
434 STADJUST(adj, expdest);
436 * If this is quoted, a '-' must not indicate a range in [...].
437 * If this is not quoted, splitting may occur.
440 result < 0 && begoff > 1 && flag & (EXP_GLOB | EXP_CASE) :
442 reprocess(expdest - adj - stackblock(), flag, VSNORMAL, quoted,
449 * Perform command substitution.
452 expbackq(union node *cmd, int quoted, int flag, struct worddest *dst)
458 char *dest = expdest;
460 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
461 int quotes = flag & (EXP_GLOB | EXP_CASE);
467 p = grabstackstr(dest);
468 evalbackcmd(cmd, &in);
469 ungrabstackstr(p, dest);
472 startloc = dest - stackblock();
474 if (!quoted && flag & EXP_SPLIT)
475 ifs = ifsset() ? ifsval() : " \t\n";
478 /* Remove trailing newlines */
480 if (--in.nleft < 0) {
483 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR)
485 TRACE(("expbackq: read returns %d\n", i));
494 if (nnl > 0 && lastc != '\n') {
495 NEXTWORD('\n', flag, dest, dst);
498 if (strchr(ifs, lastc) != NULL) {
502 NEXTWORD(lastc, flag, dest, dst);
504 CHECKSTRSPACE(2, dest);
505 if (quotes && syntax[(int)lastc] == CCTL)
506 USTPUTC(CTLESC, dest);
507 USTPUTC(lastc, dest);
510 while (dest > stackblock() + startloc && STTOPC(dest) == '\n')
518 p = grabstackstr(dest);
519 exitstatus = waitforjob(in.jp, (int *)NULL);
520 ungrabstackstr(p, dest);
522 TRACE(("expbackq: done\n"));
530 recordleft(const char *str, const char *loc, char *startp)
534 amount = ((str - 1) - (loc - startp)) - expdest;
535 STADJUST(amount, expdest);
536 while (loc != str - 1)
541 subevalvar_trim(const char *p, struct nodelist **restrict argbackq, int strloc,
542 int subtype, int startloc)
550 p = argstr(p, argbackq, EXP_CASE | EXP_TILDE, NULL);
551 STACKSTRNUL(expdest);
552 startp = stackblock() + startloc;
553 str = stackblock() + strloc;
557 for (loc = startp; loc < str; loc++) {
560 if (patmatch(str, startp)) {
562 recordleft(str, loc, startp);
570 for (loc = str - 1; loc >= startp;) {
573 if (patmatch(str, startp)) {
575 recordleft(str, loc, startp);
584 for (loc = str - 1; loc >= startp;) {
585 if (patmatch(str, loc)) {
586 amount = loc - expdest;
587 STADJUST(amount, expdest);
595 for (loc = startp; loc < str - 1; loc++) {
596 if (patmatch(str, loc)) {
597 amount = loc - expdest;
598 STADJUST(amount, expdest);
608 amount = (expdest - stackblock() - strloc) + 1;
609 STADJUST(-amount, expdest);
615 subevalvar_misc(const char *p, struct nodelist **restrict argbackq,
616 const char *var, int subtype, int startloc, int varflags)
622 end = argstr(p, argbackq, EXP_TILDE, NULL);
623 STACKSTRNUL(expdest);
624 startp = stackblock() + startloc;
628 setvar(var, startp, 0);
629 amount = startp - expdest;
630 STADJUST(amount, expdest);
634 if (*p != CTLENDVAR) {
635 outfmt(out2, "%s\n", startp);
638 error("%.*s: parameter %snot set", (int)(p - var - 1),
639 var, (varflags & VSNUL) ? "null or " : "");
648 * Expand a variable, and return a pointer to the next character in the
653 evalvar(const char *p, struct nodelist **restrict argbackq, int flag,
654 struct worddest *dst)
669 varflags = (unsigned char)*p++;
670 subtype = varflags & VSTYPE;
675 p = strchr(p, '=') + 1;
676 if (varflags & VSLINENO) {
680 } else if (special) {
681 set = varisset(var, varflags & VSNUL);
684 val = bltinlookup(var, 1);
685 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
692 startloc = expdest - stackblock();
693 if (!set && uflag && *var != '@' && *var != '*') {
701 error("%.*s: parameter not set", (int)(p - var - 1),
705 if (set && subtype != VSPLUS) {
706 /* insert the value of the variable */
708 if (varflags & VSLINENO) {
709 if (p - var > (ptrdiff_t)sizeof(buf))
711 memcpy(buf, var, p - var - 1);
712 buf[p - var - 1] = '\0';
713 strtodest(buf, flag, subtype,
714 varflags & VSQUOTE, dst);
716 varvalue(var, varflags & VSQUOTE, subtype, flag,
718 if (subtype == VSLENGTH) {
719 varlenb = expdest - stackblock() - startloc;
722 val = stackblock() + startloc;
723 for (;val != expdest; val++)
724 if ((*val & 0xC0) == 0x80)
727 STADJUST(-varlenb, expdest);
730 if (subtype == VSLENGTH) {
733 (*val & 0xC0) != 0x80)
737 strtodest(val, flag, subtype,
738 varflags & VSQUOTE, dst);
742 if (subtype == VSPLUS)
748 strtodest(buf, flag, VSNORMAL, varflags & VSQUOTE, dst);
757 return argstr(p, argbackq,
758 flag | (flag & EXP_SPLIT ? EXP_SPLIT_LIT : 0) |
759 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0), dst);
770 * Terminate the string and start recording the pattern
773 STPUTC('\0', expdest);
774 patloc = expdest - stackblock();
775 p = subevalvar_trim(p, argbackq, patloc, subtype, startloc);
776 reprocess(startloc, flag, VSNORMAL, varflags & VSQUOTE, dst);
777 if (flag & EXP_SPLIT && *var == '@' && varflags & VSQUOTE)
778 dst->state = WORD_QUOTEMARK;
784 p = subevalvar_misc(p, argbackq, var, subtype,
786 /* assert(subtype == VSASSIGN); */
787 val = lookupvar(var);
788 strtodest(val, flag, subtype, varflags & VSQUOTE, dst);
795 error("${%.*s%s}: Bad substitution", c, var,
796 (c > 0 && *p != CTLENDVAR) ? "..." : "");
802 { /* skip to end of alternative */
805 if ((c = *p++) == CTLESC)
807 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE))
808 *argbackq = (*argbackq)->next;
809 else if (c == CTLVAR) {
810 if ((*p++ & VSTYPE) != VSNORMAL)
812 } else if (c == CTLENDVAR) {
824 * Test whether a special or positional parameter is set.
828 varisset(const char *name, int nulok)
832 return backgndpidset();
833 else if (*name == '@' || *name == '*') {
834 if (*shellparam.p == NULL)
840 for (av = shellparam.p; *av; av++)
845 } else if (is_digit(*name)) {
850 num = strtol(name, NULL, 10);
851 if (errno != 0 || num > shellparam.nparam)
857 ap = shellparam.p[num - 1];
859 if (nulok && (ap == NULL || *ap == '\0'))
866 strtodest(const char *p, int flag, int subtype, int quoted,
867 struct worddest *dst)
869 if (subtype == VSLENGTH || subtype == VSTRIMLEFT ||
870 subtype == VSTRIMLEFTMAX || subtype == VSTRIMRIGHT ||
871 subtype == VSTRIMRIGHTMAX)
873 else if (flag & EXP_SPLIT && !quoted && dst != NULL)
874 STPUTS_SPLIT(p, BASESYNTAX, flag, expdest, dst);
875 else if (flag & (EXP_GLOB | EXP_CASE))
876 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
882 reprocess(int startloc, int flag, int subtype, int quoted,
883 struct worddest *dst)
885 static char *buf = NULL;
886 static size_t buflen = 0;
888 size_t len, zpos, zlen;
890 startp = stackblock() + startloc;
891 len = expdest - startp;
892 if (len >= SIZE_MAX / 2 || len > PTRDIFF_MAX)
901 while (len >= buflen)
904 buf = ckmalloc(buflen);
906 memcpy(buf, startp, len);
908 STADJUST(-(ptrdiff_t)len, expdest);
910 zlen = strlen(buf + zpos);
911 strtodest(buf + zpos, flag, subtype, quoted, dst);
915 if (flag & EXP_SPLIT && (quoted || (zlen > 0 && zpos < len)))
916 NEXTWORD('\0', flag, expdest, dst);
921 * Add the value of a special or positional parameter to the stack string.
925 varvalue(const char *name, int quoted, int subtype, int flag,
926 struct worddest *dst)
934 char buf[(NSHORTOPTS > 10 ? NSHORTOPTS : 10) + 1];
936 if (subtype == VSLENGTH)
938 splitlater = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
939 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX;
949 num = shellparam.nparam;
952 num = backgndpidval();
956 for (i = 0 ; i < NSHORTOPTS ; i++) {
961 strtodest(buf, flag, subtype, quoted, dst);
964 if (flag & EXP_SPLIT && quoted) {
965 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
966 strtodest(p, flag, subtype, quoted, dst);
969 STPUTC('\0', expdest);
971 NEXTWORD('\0', flag, expdest,
975 if (shellparam.nparam > 0)
976 dst->state = WORD_QUOTEMARK;
982 sep[0] = ifsval()[0];
986 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
987 strtodest(p, flag, subtype, quoted, dst);
991 strtodest(sep, flag, subtype, quoted, dst);
992 else if (flag & EXP_SPLIT && !quoted && **ap != '\0') {
994 STPUTC('\0', expdest);
996 NEXTWORD('\0', flag, expdest, dst);
1001 if (is_digit(*name)) {
1005 else if (num > 0 && num <= shellparam.nparam)
1006 p = shellparam.p[num - 1];
1009 strtodest(p, flag, subtype, quoted, dst);
1014 strtodest(buf, flag, subtype, quoted, dst);
1019 static char expdir[PATH_MAX];
1020 #define expdir_end (expdir + sizeof(expdir))
1023 * Perform pathname generation and remove control characters.
1024 * At this point, the only control characters should be CTLESC.
1025 * The results are stored in the list dstlist.
1028 expandmeta(char *pattern, struct arglist *dstlist)
1034 firstmatch = dstlist->count;
1036 for (; (c = *p) != '\0'; p++) {
1037 /* fast check for meta chars */
1038 if (c == '*' || c == '?' || c == '[') {
1040 expmeta(expdir, pattern, dstlist);
1045 if (dstlist->count == firstmatch) {
1050 appendarglist(dstlist, pattern);
1052 qsort(&dstlist->args[firstmatch],
1053 dstlist->count - firstmatch,
1054 sizeof(dstlist->args[0]), expsortcmp);
1060 * Do metacharacter (i.e. *, ?, [...]) expansion.
1064 expmeta(char *enddir, char *name, struct arglist *arglist)
1081 for (p = name; esc = 0, *p; p += esc + 1) {
1082 if (*p == '*' || *p == '?')
1084 else if (*p == '[') {
1086 if (*q == '!' || *q == '^')
1091 if (*q == '/' || *q == '\0')
1098 } else if (*p == '\0')
1103 if (p[esc] == '/') {
1106 start = p + esc + 1;
1110 if (metaflag == 0) { /* we've reached the end of the file name */
1111 if (enddir != expdir)
1113 for (p = name ; ; p++) {
1119 if (enddir == expdir_end)
1122 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1123 appendarglist(arglist, stsavestr(expdir));
1126 endname = name + (p - name);
1127 if (start != name) {
1133 if (enddir == expdir_end)
1137 if (enddir == expdir) {
1139 } else if (enddir == expdir + 1 && *expdir == '/') {
1145 if ((dirp = opendir(p)) == NULL)
1147 if (enddir != expdir)
1149 if (*endname == 0) {
1162 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1163 if (dp->d_name[0] == '.' && ! matchdot)
1165 if (patmatch(start, dp->d_name)) {
1166 namlen = dp->d_namlen;
1167 if (enddir + namlen + 1 > expdir_end)
1169 memcpy(enddir, dp->d_name, namlen + 1);
1171 appendarglist(arglist, stsavestr(expdir));
1173 if (dp->d_type != DT_UNKNOWN &&
1174 dp->d_type != DT_DIR &&
1175 dp->d_type != DT_LNK)
1177 if (enddir + namlen + 2 > expdir_end)
1179 enddir[namlen] = '/';
1180 enddir[namlen + 1] = '\0';
1181 expmeta(enddir + namlen + 1, endname, arglist);
1187 endname[-esc - 1] = esc ? CTLESC : '/';
1192 expsortcmp(const void *p1, const void *p2)
1194 const char *s1 = *(const char * const *)p1;
1195 const char *s2 = *(const char * const *)p2;
1197 return (strcoll(s1, s2));
1203 get_wc(const char **p)
1208 chrlen = mbtowc(&c, *p, 4);
1211 else if (chrlen == -1)
1220 * See if a character matches a character class, starting at the first colon
1222 * If a valid character class is recognized, a pointer to the next character
1223 * after the final closing bracket is stored into *end, otherwise a null
1224 * pointer is stored into *end.
1227 match_charclass(const char *p, wchar_t chr, const char **end)
1230 const char *nameend;
1235 nameend = strstr(p, ":]");
1236 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1239 memcpy(name, p, nameend - p);
1240 name[nameend - p] = '\0';
1242 cclass = wctype(name);
1243 /* An unknown class matches nothing but is valid nevertheless. */
1246 return iswctype(chr, cclass);
1251 * Returns true if the pattern matches the string.
1255 patmatch(const char *pattern, const char *string)
1257 const char *p, *q, *end;
1258 const char *bt_p, *bt_q;
1282 * A '?' does not match invalid UTF-8 but a
1283 * '*' does, so backtrack.
1295 * If the pattern ends here, we know the string
1296 * matches without needing to look at the rest of it.
1301 * First try the shortest match for the '*' that
1302 * could work. We can forget any earlier '*' since
1303 * there is no way having it match more characters
1304 * can help us, given that we are already here.
1310 const char *savep, *saveq;
1314 savep = p, saveq = q;
1316 if (*p == '!' || *p == '^') {
1328 chr = (unsigned char)*q++;
1332 p = savep, q = saveq;
1336 if (c == '[' && *p == ':') {
1337 found |= match_charclass(p, chr, &end);
1345 if (localeisutf8 && c & 0x80) {
1348 if (wc == 0) /* bad utf-8 */
1351 wc = (unsigned char)c;
1352 if (*p == '-' && p[1] != ']') {
1358 if (wc2 == 0) /* bad utf-8 */
1361 wc2 = (unsigned char)*p++;
1362 if ( collate_range_cmp(chr, wc) >= 0
1363 && collate_range_cmp(chr, wc2) <= 0
1370 } while ((c = *p++) != ']');
1371 if (found == invert)
1382 * If we have a mismatch (other than hitting the end
1383 * of the string), go back to the last '*' seen and
1384 * have it match one additional character.
1401 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1405 rmescapes(char *str)
1410 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1416 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1430 * See if a pattern matches in a case statement.
1434 casematch(union node *pattern, const char *val)
1436 struct stackmark smark;
1437 struct nodelist *argbackq;
1441 setstackmark(&smark);
1442 argbackq = pattern->narg.backquote;
1443 STARTSTACKSTR(expdest);
1444 argstr(pattern->narg.text, &argbackq, EXP_TILDE | EXP_CASE, NULL);
1445 STPUTC('\0', expdest);
1446 p = grabstackstr(expdest);
1447 result = patmatch(p, val);
1448 popstackmark(&smark);
1457 cvtnum(int num, char *buf)
1461 char *p = temp + 31;
1466 *--p = num % 10 + '0';
1467 } while ((num /= 10) != 0);
1472 memcpy(buf, p, temp + 32 - p);
1476 * Do most of the work for wordexp(3).
1480 wordexpcmd(int argc, char **argv)
1485 out1fmt("%08x", argc - 1);
1486 for (i = 1, len = 0; i < argc; i++)
1487 len += strlen(argv[i]);
1488 out1fmt("%08x", (int)len);
1489 for (i = 1; i < argc; i++)
1490 outbin(argv[i], strlen(argv[i]) + 1, out1);
1495 * Do most of the work for wordexp(3), new version.
1499 freebsd_wordexpcmd(int argc __unused, char **argv __unused)
1501 struct arglist arglist;
1502 union node *args, *n;
1509 while ((ch = nextopt("f:p")) != '\0') {
1512 fd = number(shoptarg);
1519 if (*argptr != NULL)
1520 error("wrong number of arguments");
1522 error("missing fd");
1526 args = parsewordexp();
1527 popfile(); /* will also close fd */
1529 for (n = args; n != NULL; n = n->narg.next) {
1530 if (n->narg.backquote != NULL) {
1531 outcslow('C', out1);
1532 error("command substitution disabled");
1535 outcslow(' ', out1);
1536 emptyarglist(&arglist);
1537 for (n = args; n != NULL; n = n->narg.next)
1538 expandarg(n, &arglist, EXP_FULL | EXP_TILDE);
1539 for (i = 0, len = 0; i < arglist.count; i++)
1540 len += strlen(arglist.args[i]);
1541 out1fmt("%016x %016zx", arglist.count, len);
1542 for (i = 0; i < arglist.count; i++)
1543 outbin(arglist.args[i], strlen(arglist.args[i]) + 1, out1);