2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1997-2005
5 * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 static char sccsid[] = "@(#)expand.c 8.5 (Berkeley) 5/15/95";
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include <sys/types.h>
59 * Routines to expand arguments to commands. We have to deal with
60 * backquotes, shell variables, and file metacharacters.
83 * Structure specifying which parts of the string should be searched
88 struct ifsregion *next; /* next region in list */
89 int begoff; /* offset of start of region */
90 int endoff; /* offset of end of region */
91 int inquotes; /* search for nul bytes only */
95 static char *expdest; /* output of current string */
96 static struct nodelist *argbackq; /* list of back quote expressions */
97 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
98 static struct ifsregion *ifslastp; /* last struct in list */
99 static struct arglist exparg; /* holds expanded arg list */
101 static char *argstr(char *, int);
102 static char *exptilde(char *, int);
103 static char *expari(char *);
104 static void expbackq(union node *, int, int);
105 static int subevalvar(char *, char *, int, int, int, int, int);
106 static char *evalvar(char *, int);
107 static int varisset(const char *, int);
108 static void varvalue(const char *, int, int, int);
109 static void recordregion(int, int, int);
110 static void removerecordregions(int);
111 static void ifsbreakup(char *, struct arglist *);
112 static void expandmeta(struct strlist *, int);
113 static void expmeta(char *, char *);
114 static void addfname(char *);
115 static struct strlist *expsort(struct strlist *);
116 static struct strlist *msort(struct strlist *, int);
117 static int patmatch(const char *, const char *, int);
118 static char *cvtnum(int, char *);
119 static int collate_range_cmp(wchar_t, wchar_t);
122 collate_range_cmp(wchar_t c1, wchar_t c2)
124 static wchar_t s1[2], s2[2];
128 return (wcscoll(s1, s2));
132 stputs_quotes(const char *data, const char *syntax, char *p)
136 if (syntax[(int)*data] == CCTL)
142 #define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
145 * Perform expansions on an argument, placing the resulting list of arguments
146 * in arglist. Parameter expansion, command substitution and arithmetic
147 * expansion are always performed; additional expansions can be requested
149 * The result is left in the stack string.
150 * When arglist is NULL, perform here document expansion.
152 * Caution: this function uses global state and is not reentrant.
153 * However, a new invocation after an interrupted invocation is safe
154 * and will reset the global state for the new call.
157 expandarg(union node *arg, struct arglist *arglist, int flag)
162 argbackq = arg->narg.backquote;
163 STARTSTACKSTR(expdest);
164 ifsfirst.next = NULL;
166 argstr(arg->narg.text, flag);
167 if (arglist == NULL) {
168 STACKSTRNUL(expdest);
169 return; /* here document expanded */
171 STPUTC('\0', expdest);
172 p = grabstackstr(expdest);
173 exparg.lastp = &exparg.list;
177 if (flag & EXP_FULL) {
178 ifsbreakup(p, &exparg);
179 *exparg.lastp = NULL;
180 exparg.lastp = &exparg.list;
181 expandmeta(exparg.list, flag);
183 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
185 sp = (struct strlist *)stalloc(sizeof (struct strlist));
188 exparg.lastp = &sp->next;
190 while (ifsfirst.next != NULL) {
191 struct ifsregion *ifsp;
193 ifsp = ifsfirst.next->next;
194 ckfree(ifsfirst.next);
195 ifsfirst.next = ifsp;
198 *exparg.lastp = NULL;
200 *arglist->lastp = exparg.list;
201 arglist->lastp = exparg.lastp;
208 * Perform parameter expansion, command substitution and arithmetic
209 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
210 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
211 * This is used to expand word in ${var+word} etc.
212 * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
213 * characters to allow for further processing.
214 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
217 argstr(char *p, int flag)
220 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
225 split_lit = flag & EXP_SPLIT_LIT;
226 lit_quoted = flag & EXP_LIT_QUOTED;
227 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
228 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
229 p = exptilde(p, flag);
231 CHECKSTRSPACE(2, expdest);
240 /* "$@" syntax adherence hack */
241 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
243 if ((flag & EXP_FULL) != 0)
254 if (split_lit && !lit_quoted)
255 recordregion(expdest - stackblock() -
257 expdest - stackblock(), 0);
260 p = evalvar(p, flag);
263 case CTLBACKQ|CTLQUOTE:
264 expbackq(argbackq->n, c & CTLQUOTE, flag);
265 argbackq = argbackq->next;
273 * sort of a hack - expand tildes in variable
274 * assignments (after the first '=' and after ':'s).
277 if (split_lit && !lit_quoted)
278 recordregion(expdest - stackblock() - 1,
279 expdest - stackblock(), 0);
280 if (flag & EXP_VARTILDE && *p == '~' &&
281 (c != '=' || firsteq)) {
284 p = exptilde(p, flag);
289 if (split_lit && !lit_quoted)
290 recordregion(expdest - stackblock() - 1,
291 expdest - stackblock(), 0);
297 * Perform tilde expansion, placing the result in the stack string and
298 * returning the next position in the input string to process.
301 exptilde(char *p, int flag)
306 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
308 while ((c = *p) != '\0') {
310 case CTLESC: /* This means CTL* are always considered quoted. */
313 case CTLBACKQ | CTLQUOTE:
319 if (flag & EXP_VARTILDE)
330 if (*(startp+1) == '\0') {
331 if ((home = lookupvar("HOME")) == NULL)
334 if ((pw = getpwnam(startp+1)) == NULL)
342 STPUTS_QUOTES(home, SQSYNTAX, expdest);
344 STPUTS(home, expdest);
353 removerecordregions(int endoff)
355 if (ifslastp == NULL)
358 if (ifsfirst.endoff > endoff) {
359 while (ifsfirst.next != NULL) {
360 struct ifsregion *ifsp;
362 ifsp = ifsfirst.next->next;
363 ckfree(ifsfirst.next);
364 ifsfirst.next = ifsp;
367 if (ifsfirst.begoff > endoff)
370 ifslastp = &ifsfirst;
371 ifsfirst.endoff = endoff;
376 ifslastp = &ifsfirst;
377 while (ifslastp->next && ifslastp->next->begoff < endoff)
378 ifslastp=ifslastp->next;
379 while (ifslastp->next != NULL) {
380 struct ifsregion *ifsp;
382 ifsp = ifslastp->next->next;
383 ckfree(ifslastp->next);
384 ifslastp->next = ifsp;
387 if (ifslastp->endoff > endoff)
388 ifslastp->endoff = endoff;
392 * Expand arithmetic expression.
393 * Note that flag is not required as digits never require CTLESC characters.
404 quoted = *p++ == '"';
405 begoff = expdest - stackblock();
407 removerecordregions(begoff);
408 STPUTC('\0', expdest);
409 start = stackblock() + begoff;
411 q = grabstackstr(expdest);
412 result = arith(start);
413 ungrabstackstr(q, expdest);
415 start = stackblock() + begoff;
416 adj = start - expdest;
417 STADJUST(adj, expdest);
419 CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
420 fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
421 adj = strlen(expdest);
422 STADJUST(adj, expdest);
424 recordregion(begoff, expdest - stackblock(), 0);
430 * Perform command substitution.
433 expbackq(union node *cmd, int quoted, int flag)
439 char *dest = expdest;
440 struct ifsregion saveifs, *savelastp;
441 struct nodelist *saveargbackq;
443 int startloc = dest - stackblock();
444 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
445 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
450 savelastp = ifslastp;
451 saveargbackq = argbackq;
452 p = grabstackstr(dest);
453 evalbackcmd(cmd, &in);
454 ungrabstackstr(p, dest);
456 ifslastp = savelastp;
457 argbackq = saveargbackq;
462 /* Don't copy trailing newlines */
464 if (--in.nleft < 0) {
467 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
468 TRACE(("expbackq: read returns %d\n", i));
479 CHECKSTRSPACE(nnl + 2, dest);
484 if (quotes && syntax[(int)lastc] == CCTL)
485 USTPUTC(CTLESC, dest);
486 USTPUTC(lastc, dest);
496 exitstatus = waitforjob(in.jp, (int *)NULL);
498 recordregion(startloc, dest - stackblock(), 0);
499 TRACE(("expbackq: size=%td: \"%.*s\"\n",
500 ((dest - stackblock()) - startloc),
501 (int)((dest - stackblock()) - startloc),
502 stackblock() + startloc));
510 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
511 int varflags, int quotes)
517 struct nodelist *saveargbackq = argbackq;
520 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
521 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
522 EXP_CASE : 0) | EXP_TILDE);
523 STACKSTRNUL(expdest);
524 argbackq = saveargbackq;
525 startp = stackblock() + startloc;
527 str = stackblock() + strloc;
531 setvar(str, startp, 0);
532 amount = startp - expdest;
533 STADJUST(amount, expdest);
538 if (*p != CTLENDVAR) {
539 outfmt(out2, "%s\n", startp);
542 error("%.*s: parameter %snot set", (int)(p - str - 1),
543 str, (varflags & VSNUL) ? "null or "
548 for (loc = startp; loc < str; loc++) {
551 if (patmatch(str, startp, quotes)) {
556 if (quotes && *loc == CTLESC)
562 for (loc = str - 1; loc >= startp;) {
565 if (patmatch(str, startp, quotes)) {
571 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
572 for (q = startp; q < loc; q++)
582 for (loc = str - 1; loc >= startp;) {
583 if (patmatch(str, loc, quotes)) {
584 amount = loc - expdest;
585 STADJUST(amount, expdest);
589 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
590 for (q = startp; q < loc; q++)
600 for (loc = startp; loc < str - 1; loc++) {
601 if (patmatch(str, loc, quotes)) {
602 amount = loc - expdest;
603 STADJUST(amount, expdest);
606 if (quotes && *loc == CTLESC)
617 amount = ((str - 1) - (loc - startp)) - expdest;
618 STADJUST(amount, expdest);
619 while (loc != str - 1)
626 * Expand a variable, and return a pointer to the next character in the
631 evalvar(char *p, int flag)
645 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
647 varflags = (unsigned char)*p++;
648 subtype = varflags & VSTYPE;
653 p = strchr(p, '=') + 1;
654 again: /* jump here after setting a variable with ${var=text} */
655 if (varflags & VSLINENO) {
659 } else if (special) {
660 set = varisset(var, varflags & VSNUL);
663 val = bltinlookup(var, 1);
664 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
671 startloc = expdest - stackblock();
672 if (!set && uflag && *var != '@' && *var != '*') {
680 error("%.*s: parameter not set", (int)(p - var - 1),
684 if (set && subtype != VSPLUS) {
685 /* insert the value of the variable */
687 if (varflags & VSLINENO)
688 STPUTBIN(var, p - var - 1, expdest);
690 varvalue(var, varflags & VSQUOTE, subtype, flag);
691 if (subtype == VSLENGTH) {
692 varlenb = expdest - stackblock() - startloc;
695 val = stackblock() + startloc;
696 for (;val != expdest; val++)
697 if ((*val & 0xC0) == 0x80)
700 STADJUST(-varlenb, expdest);
703 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
706 if (subtype == VSLENGTH) {
709 (*val & 0xC0) != 0x80)
714 STPUTS_QUOTES(val, syntax, expdest);
716 STPUTS(val, expdest);
722 if (subtype == VSPLUS)
725 easy = ((varflags & VSQUOTE) == 0 ||
726 (*var == '@' && shellparam.nparam != 1));
731 expdest = cvtnum(varlen, expdest);
738 recordregion(startloc, expdest - stackblock(),
739 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
740 (*var == '@' || *var == '*')));
746 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
747 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
761 * Terminate the string and start recording the pattern
764 STPUTC('\0', expdest);
765 patloc = expdest - stackblock();
766 if (subevalvar(p, NULL, patloc, subtype,
767 startloc, varflags, quotes) == 0) {
768 int amount = (expdest - stackblock() - patloc) + 1;
769 STADJUST(-amount, expdest);
771 /* Remove any recorded regions beyond start of variable */
772 removerecordregions(startloc);
778 if (subevalvar(p, var, 0, subtype, startloc, varflags,
782 * Remove any recorded regions beyond
785 removerecordregions(startloc);
796 error("${%.*s%s}: Bad substitution", c, var,
797 (c > 0 && *p != CTLENDVAR) ? "..." : "");
803 if (subtype != VSNORMAL) { /* skip to end of alternative */
806 if ((c = *p++) == CTLESC)
808 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
810 argbackq = argbackq->next;
811 } else if (c == CTLVAR) {
812 if ((*p++ & VSTYPE) != VSNORMAL)
814 } else if (c == CTLENDVAR) {
826 * Test whether a specialized variable is set.
830 varisset(const char *name, int nulok)
834 return backgndpidset();
835 else if (*name == '@' || *name == '*') {
836 if (*shellparam.p == NULL)
842 for (av = shellparam.p; *av; av++)
847 } else if (is_digit(*name)) {
852 num = strtol(name, NULL, 10);
853 if (errno != 0 || num > shellparam.nparam)
859 ap = shellparam.p[num - 1];
861 if (nulok && (ap == NULL || *ap == '\0'))
868 strtodest(const char *p, int flag, int subtype, int quoted)
870 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
871 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
877 * Add the value of a specialized variable to the stack string.
881 varvalue(const char *name, int quoted, int subtype, int flag)
897 num = shellparam.nparam;
900 num = backgndpidval();
902 expdest = cvtnum(num, expdest);
905 for (i = 0 ; i < NOPTS ; i++) {
907 STPUTC(optlist[i].letter, expdest);
911 if (flag & EXP_FULL && quoted) {
912 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
913 strtodest(p, flag, subtype, quoted);
915 STPUTC('\0', expdest);
925 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
926 strtodest(p, flag, subtype, quoted);
929 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
930 STPUTC(sep, expdest);
934 if (is_digit(*name)) {
938 else if (num > 0 && num <= shellparam.nparam)
939 p = shellparam.p[num - 1];
942 strtodest(p, flag, subtype, quoted);
951 * Record the fact that we have to scan this region of the
952 * string for IFS characters.
956 recordregion(int start, int end, int inquotes)
958 struct ifsregion *ifsp;
961 if (ifslastp == NULL) {
964 if (ifslastp->endoff == start
965 && ifslastp->inquotes == inquotes) {
966 /* extend previous area */
967 ifslastp->endoff = end;
971 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
972 ifslastp->next = ifsp;
975 ifslastp->next = NULL;
976 ifslastp->begoff = start;
977 ifslastp->endoff = end;
978 ifslastp->inquotes = inquotes;
985 * Break the argument string into pieces based upon IFS and add the
986 * strings to the argument list. The regions of the string to be
987 * searched for IFS characters have been stored by recordregion.
988 * CTLESC characters are preserved but have little effect in this pass
989 * other than escaping CTL* characters. In particular, they do not escape
990 * IFS characters: that should be done with the ifsregion mechanism.
991 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
992 * This pass treats them as a regular character, making the string non-empty.
993 * Later, they are removed along with the other CTL* characters.
996 ifsbreakup(char *string, struct arglist *arglist)
998 struct ifsregion *ifsp;
1005 int had_param_ch = 0;
1009 if (ifslastp == NULL) {
1010 /* Return entire argument, IFS doesn't apply to any of it */
1011 sp = (struct strlist *)stalloc(sizeof *sp);
1013 *arglist->lastp = sp;
1014 arglist->lastp = &sp->next;
1018 ifs = ifsset() ? ifsval() : " \t\n";
1020 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1021 p = string + ifsp->begoff;
1022 while (p < string + ifsp->endoff) {
1026 if (ifsp->inquotes) {
1027 /* Only NULs (should be from "$@") end args */
1035 if (!strchr(ifs, *p)) {
1040 ifsspc = strchr(" \t\n", *p);
1042 /* Ignore IFS whitespace at start */
1043 if (q == start && ifsspc != NULL) {
1051 /* Save this argument... */
1053 sp = (struct strlist *)stalloc(sizeof *sp);
1055 *arglist->lastp = sp;
1056 arglist->lastp = &sp->next;
1059 if (ifsspc != NULL) {
1060 /* Ignore further trailing IFS whitespace */
1061 for (; p < string + ifsp->endoff; p++) {
1065 if (strchr(ifs, *p) == NULL) {
1069 if (strchr(" \t\n", *p) == NULL) {
1080 * Save anything left as an argument.
1081 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1082 * generating 2 arguments, the second of which is empty.
1083 * Some recent clarification of the Posix spec say that it
1084 * should only generate one....
1086 if (had_param_ch || *start != 0) {
1087 sp = (struct strlist *)stalloc(sizeof *sp);
1089 *arglist->lastp = sp;
1090 arglist->lastp = &sp->next;
1095 static char expdir[PATH_MAX];
1096 #define expdir_end (expdir + sizeof(expdir))
1099 * Perform pathname generation and remove control characters.
1100 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1101 * The results are stored in the list exparg.
1104 expandmeta(struct strlist *str, int flag __unused)
1107 struct strlist **savelastp;
1110 /* TODO - EXP_REDIR */
1116 for (;;) { /* fast check for meta chars */
1117 if ((c = *p++) == '\0')
1119 if (c == '*' || c == '?' || c == '[')
1122 savelastp = exparg.lastp;
1124 expmeta(expdir, str->text);
1126 if (exparg.lastp == savelastp) {
1131 *exparg.lastp = str;
1132 rmescapes(str->text);
1133 exparg.lastp = &str->next;
1135 *exparg.lastp = NULL;
1136 *savelastp = sp = expsort(*savelastp);
1137 while (sp->next != NULL)
1139 exparg.lastp = &sp->next;
1147 * Do metacharacter (i.e. *, ?, [...]) expansion.
1151 expmeta(char *enddir, char *name)
1168 for (p = name; esc = 0, *p; p += esc + 1) {
1169 if (*p == '*' || *p == '?')
1171 else if (*p == '[') {
1173 if (*q == '!' || *q == '^')
1176 while (*q == CTLQUOTEMARK)
1180 if (*q == '/' || *q == '\0')
1187 } else if (*p == '\0')
1189 else if (*p == CTLQUOTEMARK)
1194 if (p[esc] == '/') {
1197 start = p + esc + 1;
1201 if (metaflag == 0) { /* we've reached the end of the file name */
1202 if (enddir != expdir)
1204 for (p = name ; ; p++) {
1205 if (*p == CTLQUOTEMARK)
1212 if (enddir == expdir_end)
1215 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1219 endname = name + (p - name);
1220 if (start != name) {
1223 while (*p == CTLQUOTEMARK)
1228 if (enddir == expdir_end)
1232 if (enddir == expdir) {
1234 } else if (enddir == expdir + 1 && *expdir == '/') {
1240 if ((dirp = opendir(p)) == NULL)
1242 if (enddir != expdir)
1244 if (*endname == 0) {
1253 while (*p == CTLQUOTEMARK)
1259 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1260 if (dp->d_name[0] == '.' && ! matchdot)
1262 if (patmatch(start, dp->d_name, 0)) {
1263 namlen = dp->d_namlen;
1264 if (enddir + namlen + 1 > expdir_end)
1266 memcpy(enddir, dp->d_name, namlen + 1);
1270 if (dp->d_type != DT_UNKNOWN &&
1271 dp->d_type != DT_DIR &&
1272 dp->d_type != DT_LNK)
1274 if (enddir + namlen + 2 > expdir_end)
1276 enddir[namlen] = '/';
1277 enddir[namlen + 1] = '\0';
1278 expmeta(enddir + namlen + 1, endname);
1284 endname[-esc - 1] = esc ? CTLESC : '/';
1289 * Add a file name to the list.
1293 addfname(char *name)
1300 p = stalloc(len + 1);
1301 memcpy(p, name, len + 1);
1302 sp = (struct strlist *)stalloc(sizeof *sp);
1305 exparg.lastp = &sp->next;
1310 * Sort the results of file name expansion. It calculates the number of
1311 * strings to sort and then calls msort (short for merge sort) to do the
1315 static struct strlist *
1316 expsort(struct strlist *str)
1322 for (sp = str ; sp ; sp = sp->next)
1324 return msort(str, len);
1328 static struct strlist *
1329 msort(struct strlist *list, int len)
1331 struct strlist *p, *q = NULL;
1332 struct strlist **lpp;
1340 for (n = half ; --n >= 0 ; ) {
1344 q->next = NULL; /* terminate first half of list */
1345 q = msort(list, half); /* sort first half of list */
1346 p = msort(p, len - half); /* sort second half */
1349 if (strcmp(p->text, q->text) < 0) {
1352 if ((p = *lpp) == NULL) {
1359 if ((q = *lpp) == NULL) {
1371 get_wc(const char **p)
1376 chrlen = mbtowc(&c, *p, 4);
1379 else if (chrlen == -1)
1388 * See if a character matches a character class, starting at the first colon
1390 * If a valid character class is recognized, a pointer to the next character
1391 * after the final closing bracket is stored into *end, otherwise a null
1392 * pointer is stored into *end.
1395 match_charclass(const char *p, wchar_t chr, const char **end)
1398 const char *nameend;
1403 nameend = strstr(p, ":]");
1404 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1407 memcpy(name, p, nameend - p);
1408 name[nameend - p] = '\0';
1410 cclass = wctype(name);
1411 /* An unknown class matches nothing but is valid nevertheless. */
1414 return iswctype(chr, cclass);
1419 * Returns true if the pattern matches the string.
1423 patmatch(const char *pattern, const char *string, int squoted)
1425 const char *p, *q, *end;
1426 const char *bt_p, *bt_q;
1441 if (squoted && *q == CTLESC)
1449 if (squoted && *q == CTLESC)
1456 * A '?' does not match invalid UTF-8 but a
1457 * '*' does, so backtrack.
1462 wc = (unsigned char)*q++;
1466 while (c == CTLQUOTEMARK || c == '*')
1469 * If the pattern ends here, we know the string
1470 * matches without needing to look at the rest of it.
1475 * First try the shortest match for the '*' that
1476 * could work. We can forget any earlier '*' since
1477 * there is no way having it match more characters
1478 * can help us, given that we are already here.
1489 if (*endp == '!' || *endp == '^')
1492 while (*endp == CTLQUOTEMARK)
1495 goto dft; /* no matching ] */
1496 if (*endp == CTLESC)
1502 if (*p == '!' || *p == '^') {
1507 if (squoted && *q == CTLESC)
1516 chr = (unsigned char)*q++;
1519 if (c == CTLQUOTEMARK)
1521 if (c == '[' && *p == ':') {
1522 found |= match_charclass(p, chr, &end);
1528 if (localeisutf8 && c & 0x80) {
1531 if (wc == 0) /* bad utf-8 */
1534 wc = (unsigned char)c;
1535 if (*p == '-' && p[1] != ']') {
1537 while (*p == CTLQUOTEMARK)
1543 if (wc2 == 0) /* bad utf-8 */
1546 wc2 = (unsigned char)*p++;
1547 if ( collate_range_cmp(chr, wc) >= 0
1548 && collate_range_cmp(chr, wc2) <= 0
1555 } while ((c = *p++) != ']');
1556 if (found == invert)
1561 if (squoted && *q == CTLESC)
1569 * If we have a mismatch (other than hitting the end
1570 * of the string), go back to the last '*' seen and
1571 * have it match one additional character.
1575 if (squoted && *bt_q == CTLESC)
1590 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1594 rmescapes(char *str)
1599 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1605 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1619 * See if a pattern matches in a case statement.
1623 casematch(union node *pattern, const char *val)
1625 struct stackmark smark;
1629 setstackmark(&smark);
1630 argbackq = pattern->narg.backquote;
1631 STARTSTACKSTR(expdest);
1633 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1634 STPUTC('\0', expdest);
1635 p = grabstackstr(expdest);
1636 result = patmatch(p, val, 0);
1637 popstackmark(&smark);
1646 cvtnum(int num, char *buf)
1650 char *p = temp + 31;
1655 *--p = num % 10 + '0';
1656 } while ((num /= 10) != 0);
1666 * Do most of the work for wordexp(3).
1670 wordexpcmd(int argc, char **argv)
1675 out1fmt("%08x", argc - 1);
1676 for (i = 1, len = 0; i < argc; i++)
1677 len += strlen(argv[i]);
1678 out1fmt("%08x", (int)len);
1679 for (i = 1; i < argc; i++)
1680 outbin(argv[i], strlen(argv[i]) + 1, out1);