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 #include <sys/types.h>
59 * Routines to expand arguments to commands. We have to deal with
60 * backquotes, shell variables, and file metacharacters.
82 enum wordstate { WORD_IDLE, WORD_WS_DELIMITED, WORD_QUOTEMARK };
89 static char *expdest; /* output of current string */
91 static const char *argstr(const char *, struct nodelist **restrict, int,
93 static const char *exptilde(const char *, int);
94 static const char *expari(const char *, struct nodelist **restrict, int,
96 static void expbackq(union node *, int, int, struct worddest *);
97 static const char *subevalvar_trim(const char *, struct nodelist **restrict,
99 static const char *subevalvar_misc(const char *, struct nodelist **restrict,
100 const char *, int, int, int);
101 static const char *evalvar(const char *, struct nodelist **restrict, int,
103 static int varisset(const char *, int);
104 static void strtodest(const char *, int, int, int, struct worddest *);
105 static void reprocess(int, int, int, int, struct worddest *);
106 static void varvalue(const char *, int, int, int, struct worddest *);
107 static void expandmeta(char *, struct arglist *);
108 static void expmeta(char *, char *, struct arglist *);
109 static int expsortcmp(const void *, const void *);
110 static int patmatch(const char *, const char *);
111 static void cvtnum(int, char *);
112 static int collate_range_cmp(wchar_t, wchar_t);
115 emptyarglist(struct arglist *list)
118 list->args = list->smallarg;
120 list->capacity = sizeof(list->smallarg) / sizeof(list->smallarg[0]);
124 appendarglist(struct arglist *list, char *str)
129 if (list->count >= list->capacity) {
130 newcapacity = list->capacity * 2;
131 if (newcapacity < 16)
133 if (newcapacity > INT_MAX / (int)sizeof(newargs[0]))
134 error("Too many entries in arglist");
135 newargs = stalloc(newcapacity * sizeof(newargs[0]));
136 memcpy(newargs, list->args, list->count * sizeof(newargs[0]));
137 list->args = newargs;
138 list->capacity = newcapacity;
140 list->args[list->count++] = str;
144 collate_range_cmp(wchar_t c1, wchar_t c2)
146 wchar_t s1[2], s2[2];
152 return (wcscoll(s1, s2));
156 stputs_quotes(const char *data, const char *syntax, char *p)
160 if (syntax[(int)*data] == CCTL)
166 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
169 nextword(char c, int flag, char *p, struct worddest *dst)
173 is_ws = c == '\t' || c == '\n' || c == ' ';
174 if (p != stackblock() || (is_ws ? dst->state == WORD_QUOTEMARK :
175 dst->state != WORD_WS_DELIMITED) || c == '\0') {
178 expandmeta(grabstackstr(p), dst->list);
180 appendarglist(dst->list, grabstackstr(p));
181 dst->state = is_ws ? WORD_WS_DELIMITED : WORD_IDLE;
182 } else if (!is_ws && dst->state == WORD_WS_DELIMITED)
183 dst->state = WORD_IDLE;
184 /* Reserve space while the stack string is empty. */
185 appendarglist(dst->list, NULL);
190 #define NEXTWORD(c, flag, p, dstlist) p = nextword(c, flag, p, dstlist)
193 stputs_split(const char *data, const char *syntax, int flag, char *p,
194 struct worddest *dst)
199 ifs = ifsset() ? ifsval() : " \t\n";
203 if (strchr(ifs, c) != NULL) {
204 NEXTWORD(c, flag, p, dst);
207 if (flag & EXP_GLOB && syntax[(int)c] == CCTL)
213 #define STPUTS_SPLIT(data, syntax, flag, p, dst) p = stputs_split((data), syntax, flag, p, dst)
216 * Perform expansions on an argument, placing the resulting list of arguments
217 * in arglist. Parameter expansion, command substitution and arithmetic
218 * expansion are always performed; additional expansions can be requested
220 * The result is left in the stack string.
221 * When arglist is NULL, perform here document expansion.
223 * When doing something that may cause this to be re-entered, make sure
224 * the stack string is empty via grabstackstr() and do not assume expdest
228 expandarg(union node *arg, struct arglist *arglist, int flag)
230 struct worddest exparg;
231 struct nodelist *argbackq;
235 argbackq = arg->narg.backquote;
236 exparg.list = arglist;
237 exparg.state = WORD_IDLE;
238 STARTSTACKSTR(expdest);
239 argstr(arg->narg.text, &argbackq, flag, &exparg);
240 if (arglist == NULL) {
241 STACKSTRNUL(expdest);
242 return; /* here document expanded */
244 if ((flag & EXP_SPLIT) == 0 || expdest != stackblock() ||
245 exparg.state == WORD_QUOTEMARK) {
246 STPUTC('\0', expdest);
247 if (flag & EXP_SPLIT) {
249 expandmeta(grabstackstr(expdest), exparg.list);
251 appendarglist(exparg.list, grabstackstr(expdest));
254 if ((flag & EXP_SPLIT) == 0)
255 appendarglist(arglist, grabstackstr(expdest));
261 * Perform parameter expansion, command substitution and arithmetic
262 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
263 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
264 * This is used to expand word in ${var+word} etc.
265 * If EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC
266 * characters to allow for further processing.
268 * If EXP_SPLIT is set, dst receives any complete words produced.
271 argstr(const char *p, struct nodelist **restrict argbackq, int flag,
272 struct worddest *dst)
275 int quotes = flag & (EXP_GLOB | EXP_CASE); /* do CTLESC */
280 split_lit = flag & EXP_SPLIT_LIT;
281 lit_quoted = flag & EXP_LIT_QUOTED;
282 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
283 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
284 p = exptilde(p, flag);
286 CHECKSTRSPACE(2, expdest);
295 /* "$@" syntax adherence hack */
296 if (p[0] == CTLVAR && (p[1] & VSQUOTE) != 0 &&
297 p[2] == '@' && p[3] == '=')
299 if ((flag & EXP_SPLIT) != 0 && expdest == stackblock())
300 dst->state = WORD_QUOTEMARK;
307 if (split_lit && !lit_quoted &&
308 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
309 NEXTWORD(c, flag, expdest, dst);
313 USTPUTC(CTLESC, expdest);
317 p = evalvar(p, argbackq, flag, dst);
320 case CTLBACKQ|CTLQUOTE:
321 expbackq((*argbackq)->n, c & CTLQUOTE, flag, dst);
322 *argbackq = (*argbackq)->next;
325 p = expari(p, argbackq, flag, dst);
330 * sort of a hack - expand tildes in variable
331 * assignments (after the first '=' and after ':'s).
333 if (split_lit && !lit_quoted &&
334 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
335 NEXTWORD(c, flag, expdest, dst);
339 if (flag & EXP_VARTILDE && *p == '~' &&
340 (c != '=' || firsteq)) {
343 p = exptilde(p, flag);
347 if (split_lit && !lit_quoted &&
348 strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
349 NEXTWORD(c, flag, expdest, dst);
358 * Perform tilde expansion, placing the result in the stack string and
359 * returning the next position in the input string to process.
362 exptilde(const char *p, int flag)
365 const char *startp = p;
374 case CTLESC: /* This means CTL* are always considered quoted. */
377 case CTLBACKQ | CTLQUOTE:
383 if ((flag & EXP_VARTILDE) == 0)
389 len = p - startp - 1;
390 STPUTBIN(startp + 1, len, expdest);
391 STACKSTRNUL(expdest);
392 user = expdest - len;
394 home = lookupvar("HOME");
397 home = pw != NULL ? pw->pw_dir : NULL;
399 STADJUST(-len, expdest);
400 if (home == NULL || *home == '\0')
402 strtodest(home, flag, VSNORMAL, 1, NULL);
411 * Expand arithmetic expression.
414 expari(const char *p, struct nodelist **restrict argbackq, int flag,
415 struct worddest *dst)
423 quoted = *p++ == '"';
424 begoff = expdest - stackblock();
425 p = argstr(p, argbackq, 0, NULL);
426 STPUTC('\0', expdest);
427 start = stackblock() + begoff;
429 q = grabstackstr(expdest);
430 result = arith(start);
431 ungrabstackstr(q, expdest);
433 start = stackblock() + begoff;
434 adj = start - expdest;
435 STADJUST(adj, expdest);
437 CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
438 fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
439 adj = strlen(expdest);
440 STADJUST(adj, expdest);
442 * If this is quoted, a '-' must not indicate a range in [...].
443 * If this is not quoted, splitting may occur.
446 result < 0 && begoff > 1 && flag & (EXP_GLOB | EXP_CASE) :
448 reprocess(expdest - adj - stackblock(), flag, VSNORMAL, quoted,
455 * Perform command substitution.
458 expbackq(union node *cmd, int quoted, int flag, struct worddest *dst)
464 char *dest = expdest;
466 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
467 int quotes = flag & (EXP_GLOB | EXP_CASE);
473 p = grabstackstr(dest);
474 evalbackcmd(cmd, &in);
475 ungrabstackstr(p, dest);
478 startloc = dest - stackblock();
480 if (!quoted && flag & EXP_SPLIT)
481 ifs = ifsset() ? ifsval() : " \t\n";
484 /* Remove trailing newlines */
486 if (--in.nleft < 0) {
489 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR)
491 TRACE(("expbackq: read returns %d\n", i));
500 if (nnl > 0 && lastc != '\n') {
501 NEXTWORD('\n', flag, dest, dst);
504 if (strchr(ifs, lastc) != NULL) {
508 NEXTWORD(lastc, flag, dest, dst);
510 CHECKSTRSPACE(2, dest);
511 if (quotes && syntax[(int)lastc] == CCTL)
512 USTPUTC(CTLESC, dest);
513 USTPUTC(lastc, dest);
516 while (dest > stackblock() + startloc && STTOPC(dest) == '\n')
524 p = grabstackstr(dest);
525 exitstatus = waitforjob(in.jp, (int *)NULL);
526 ungrabstackstr(p, dest);
528 TRACE(("expbackq: done\n"));
536 recordleft(const char *str, const char *loc, char *startp)
540 amount = ((str - 1) - (loc - startp)) - expdest;
541 STADJUST(amount, expdest);
542 while (loc != str - 1)
547 subevalvar_trim(const char *p, struct nodelist **restrict argbackq, int strloc,
548 int subtype, int startloc)
556 p = argstr(p, argbackq, EXP_CASE | EXP_TILDE, NULL);
557 STACKSTRNUL(expdest);
558 startp = stackblock() + startloc;
559 str = stackblock() + strloc;
563 for (loc = startp; loc < str; loc++) {
566 if (patmatch(str, startp)) {
568 recordleft(str, loc, startp);
576 for (loc = str - 1; loc >= startp;) {
579 if (patmatch(str, startp)) {
581 recordleft(str, loc, startp);
590 for (loc = str - 1; loc >= startp;) {
591 if (patmatch(str, loc)) {
592 amount = loc - expdest;
593 STADJUST(amount, expdest);
601 for (loc = startp; loc < str - 1; loc++) {
602 if (patmatch(str, loc)) {
603 amount = loc - expdest;
604 STADJUST(amount, expdest);
614 amount = (expdest - stackblock() - strloc) + 1;
615 STADJUST(-amount, expdest);
621 subevalvar_misc(const char *p, struct nodelist **restrict argbackq,
622 const char *var, int subtype, int startloc, int varflags)
628 end = argstr(p, argbackq, EXP_TILDE, NULL);
629 STACKSTRNUL(expdest);
630 startp = stackblock() + startloc;
634 setvar(var, startp, 0);
635 amount = startp - expdest;
636 STADJUST(amount, expdest);
640 if (*p != CTLENDVAR) {
641 outfmt(out2, "%s\n", startp);
644 error("%.*s: parameter %snot set", (int)(p - var - 1),
645 var, (varflags & VSNUL) ? "null or " : "");
654 * Expand a variable, and return a pointer to the next character in the
659 evalvar(const char *p, struct nodelist **restrict argbackq, int flag,
660 struct worddest *dst)
675 varflags = (unsigned char)*p++;
676 subtype = varflags & VSTYPE;
681 p = strchr(p, '=') + 1;
682 if (varflags & VSLINENO) {
686 } else if (special) {
687 set = varisset(var, varflags & VSNUL);
690 val = bltinlookup(var, 1);
691 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
698 startloc = expdest - stackblock();
699 if (!set && uflag && *var != '@' && *var != '*') {
707 error("%.*s: parameter not set", (int)(p - var - 1),
711 if (set && subtype != VSPLUS) {
712 /* insert the value of the variable */
714 if (varflags & VSLINENO) {
715 if (p - var > (ptrdiff_t)sizeof(buf))
717 memcpy(buf, var, p - var - 1);
718 buf[p - var - 1] = '\0';
719 strtodest(buf, flag, subtype,
720 varflags & VSQUOTE, dst);
722 varvalue(var, varflags & VSQUOTE, subtype, flag,
724 if (subtype == VSLENGTH) {
725 varlenb = expdest - stackblock() - startloc;
728 val = stackblock() + startloc;
729 for (;val != expdest; val++)
730 if ((*val & 0xC0) == 0x80)
733 STADJUST(-varlenb, expdest);
736 if (subtype == VSLENGTH) {
739 (*val & 0xC0) != 0x80)
743 strtodest(val, flag, subtype,
744 varflags & VSQUOTE, dst);
748 if (subtype == VSPLUS)
754 strtodest(buf, flag, VSNORMAL, varflags & VSQUOTE, dst);
763 return argstr(p, argbackq,
764 flag | (flag & EXP_SPLIT ? EXP_SPLIT_LIT : 0) |
765 (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 p = subevalvar_trim(p, argbackq, 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 p = subevalvar_misc(p, argbackq, var, subtype,
792 /* assert(subtype == VSASSIGN); */
793 val = lookupvar(var);
794 strtodest(val, flag, subtype, varflags & VSQUOTE, dst);
801 error("${%.*s%s}: Bad substitution", c, var,
802 (c > 0 && *p != CTLENDVAR) ? "..." : "");
808 { /* skip to end of alternative */
811 if ((c = *p++) == CTLESC)
813 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE))
814 *argbackq = (*argbackq)->next;
815 else if (c == CTLVAR) {
816 if ((*p++ & VSTYPE) != VSNORMAL)
818 } else if (c == CTLENDVAR) {
830 * Test whether a special or positional parameter is set.
834 varisset(const char *name, int nulok)
838 return backgndpidset();
839 else if (*name == '@' || *name == '*') {
840 if (*shellparam.p == NULL)
846 for (av = shellparam.p; *av; av++)
851 } else if (is_digit(*name)) {
856 num = strtol(name, NULL, 10);
857 if (errno != 0 || num > shellparam.nparam)
863 ap = shellparam.p[num - 1];
865 if (nulok && (ap == NULL || *ap == '\0'))
872 strtodest(const char *p, int flag, int subtype, int quoted,
873 struct worddest *dst)
875 if (subtype == VSLENGTH || subtype == VSTRIMLEFT ||
876 subtype == VSTRIMLEFTMAX || subtype == VSTRIMRIGHT ||
877 subtype == VSTRIMRIGHTMAX)
879 else if (flag & EXP_SPLIT && !quoted && dst != NULL)
880 STPUTS_SPLIT(p, BASESYNTAX, flag, expdest, dst);
881 else if (flag & (EXP_GLOB | EXP_CASE))
882 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
888 reprocess(int startloc, int flag, int subtype, int quoted,
889 struct worddest *dst)
891 static char *buf = NULL;
892 static size_t buflen = 0;
894 size_t len, zpos, zlen;
896 startp = stackblock() + startloc;
897 len = expdest - startp;
898 if (len >= SIZE_MAX / 2 || len > PTRDIFF_MAX)
907 while (len >= buflen)
910 buf = ckmalloc(buflen);
912 memcpy(buf, startp, len);
914 STADJUST(-(ptrdiff_t)len, expdest);
916 zlen = strlen(buf + zpos);
917 strtodest(buf + zpos, flag, subtype, quoted, dst);
921 if (flag & EXP_SPLIT && (quoted || (zlen > 0 && zpos < len)))
922 NEXTWORD('\0', flag, expdest, dst);
927 * Add the value of a special or positional parameter to the stack string.
931 varvalue(const char *name, int quoted, int subtype, int flag,
932 struct worddest *dst)
940 char buf[(NSHORTOPTS > 10 ? NSHORTOPTS : 10) + 1];
942 if (subtype == VSLENGTH)
944 splitlater = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
945 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX;
955 num = shellparam.nparam;
958 num = backgndpidval();
962 for (i = 0 ; i < NSHORTOPTS ; i++) {
967 strtodest(buf, flag, subtype, quoted, dst);
970 if (flag & EXP_SPLIT && quoted) {
971 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
972 strtodest(p, flag, subtype, quoted, dst);
975 STPUTC('\0', expdest);
977 NEXTWORD('\0', flag, expdest,
981 if (shellparam.nparam > 0)
982 dst->state = WORD_QUOTEMARK;
988 sep[0] = ifsval()[0];
992 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
993 strtodest(p, flag, subtype, quoted, dst);
997 strtodest(sep, flag, subtype, quoted, dst);
998 else if (flag & EXP_SPLIT && !quoted && **ap != '\0') {
1000 STPUTC('\0', expdest);
1002 NEXTWORD('\0', flag, expdest, dst);
1007 if (is_digit(*name)) {
1011 else if (num > 0 && num <= shellparam.nparam)
1012 p = shellparam.p[num - 1];
1015 strtodest(p, flag, subtype, quoted, dst);
1020 strtodest(buf, flag, subtype, quoted, dst);
1025 static char expdir[PATH_MAX];
1026 #define expdir_end (expdir + sizeof(expdir))
1029 * Perform pathname generation and remove control characters.
1030 * At this point, the only control characters should be CTLESC.
1031 * The results are stored in the list dstlist.
1034 expandmeta(char *pattern, struct arglist *dstlist)
1040 firstmatch = dstlist->count;
1042 for (; (c = *p) != '\0'; p++) {
1043 /* fast check for meta chars */
1044 if (c == '*' || c == '?' || c == '[') {
1046 expmeta(expdir, pattern, dstlist);
1051 if (dstlist->count == firstmatch) {
1056 appendarglist(dstlist, pattern);
1058 qsort(&dstlist->args[firstmatch],
1059 dstlist->count - firstmatch,
1060 sizeof(dstlist->args[0]), expsortcmp);
1066 * Do metacharacter (i.e. *, ?, [...]) expansion.
1070 expmeta(char *enddir, char *name, struct arglist *arglist)
1087 for (p = name; esc = 0, *p; p += esc + 1) {
1088 if (*p == '*' || *p == '?')
1090 else if (*p == '[') {
1092 if (*q == '!' || *q == '^')
1097 if (*q == '/' || *q == '\0')
1104 } else if (*p == '\0')
1109 if (p[esc] == '/') {
1112 start = p + esc + 1;
1116 if (metaflag == 0) { /* we've reached the end of the file name */
1117 if (enddir != expdir)
1119 for (p = name ; ; p++) {
1125 if (enddir == expdir_end)
1128 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1129 appendarglist(arglist, stsavestr(expdir));
1132 endname = name + (p - name);
1133 if (start != name) {
1139 if (enddir == expdir_end)
1143 if (enddir == expdir) {
1145 } else if (enddir == expdir + 1 && *expdir == '/') {
1151 if ((dirp = opendir(p)) == NULL)
1153 if (enddir != expdir)
1155 if (*endname == 0) {
1168 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1169 if (dp->d_name[0] == '.' && ! matchdot)
1171 if (patmatch(start, dp->d_name)) {
1172 namlen = dp->d_namlen;
1173 if (enddir + namlen + 1 > expdir_end)
1175 memcpy(enddir, dp->d_name, namlen + 1);
1177 appendarglist(arglist, stsavestr(expdir));
1179 if (dp->d_type != DT_UNKNOWN &&
1180 dp->d_type != DT_DIR &&
1181 dp->d_type != DT_LNK)
1183 if (enddir + namlen + 2 > expdir_end)
1185 enddir[namlen] = '/';
1186 enddir[namlen + 1] = '\0';
1187 expmeta(enddir + namlen + 1, endname, arglist);
1193 endname[-esc - 1] = esc ? CTLESC : '/';
1198 expsortcmp(const void *p1, const void *p2)
1200 const char *s1 = *(const char * const *)p1;
1201 const char *s2 = *(const char * const *)p2;
1203 return (strcoll(s1, s2));
1209 get_wc(const char **p)
1214 chrlen = mbtowc(&c, *p, 4);
1217 else if (chrlen == -1)
1226 * See if a character matches a character class, starting at the first colon
1228 * If a valid character class is recognized, a pointer to the next character
1229 * after the final closing bracket is stored into *end, otherwise a null
1230 * pointer is stored into *end.
1233 match_charclass(const char *p, wchar_t chr, const char **end)
1236 const char *nameend;
1241 nameend = strstr(p, ":]");
1242 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1245 memcpy(name, p, nameend - p);
1246 name[nameend - p] = '\0';
1248 cclass = wctype(name);
1249 /* An unknown class matches nothing but is valid nevertheless. */
1252 return iswctype(chr, cclass);
1257 * Returns true if the pattern matches the string.
1261 patmatch(const char *pattern, const char *string)
1263 const char *p, *q, *end;
1264 const char *bt_p, *bt_q;
1288 * A '?' does not match invalid UTF-8 but a
1289 * '*' does, so backtrack.
1301 * If the pattern ends here, we know the string
1302 * matches without needing to look at the rest of it.
1307 * First try the shortest match for the '*' that
1308 * could work. We can forget any earlier '*' since
1309 * there is no way having it match more characters
1310 * can help us, given that we are already here.
1316 const char *savep, *saveq;
1320 savep = p, saveq = q;
1322 if (*p == '!' || *p == '^') {
1334 chr = (unsigned char)*q++;
1338 p = savep, q = saveq;
1342 if (c == '[' && *p == ':') {
1343 found |= match_charclass(p, chr, &end);
1351 if (localeisutf8 && c & 0x80) {
1354 if (wc == 0) /* bad utf-8 */
1357 wc = (unsigned char)c;
1358 if (*p == '-' && p[1] != ']') {
1364 if (wc2 == 0) /* bad utf-8 */
1367 wc2 = (unsigned char)*p++;
1368 if ( collate_range_cmp(chr, wc) >= 0
1369 && collate_range_cmp(chr, wc2) <= 0
1376 } while ((c = *p++) != ']');
1377 if (found == invert)
1388 * If we have a mismatch (other than hitting the end
1389 * of the string), go back to the last '*' seen and
1390 * have it match one additional character.
1407 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1411 rmescapes(char *str)
1416 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1422 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1436 * See if a pattern matches in a case statement.
1440 casematch(union node *pattern, const char *val)
1442 struct stackmark smark;
1443 struct nodelist *argbackq;
1447 setstackmark(&smark);
1448 argbackq = pattern->narg.backquote;
1449 STARTSTACKSTR(expdest);
1450 argstr(pattern->narg.text, &argbackq, 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);