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;
174 if (flag & EXP_FULL) {
175 ifsbreakup(p, &exparg);
176 *exparg.lastp = NULL;
177 exparg.lastp = &exparg.list;
178 expandmeta(exparg.list, flag);
180 sp = (struct strlist *)stalloc(sizeof (struct strlist));
183 exparg.lastp = &sp->next;
185 while (ifsfirst.next != NULL) {
186 struct ifsregion *ifsp;
188 ifsp = ifsfirst.next->next;
189 ckfree(ifsfirst.next);
190 ifsfirst.next = ifsp;
193 *exparg.lastp = NULL;
195 *arglist->lastp = exparg.list;
196 arglist->lastp = exparg.lastp;
203 * Perform parameter expansion, command substitution and arithmetic
204 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
205 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
206 * This is used to expand word in ${var+word} etc.
207 * If EXP_FULL or EXP_CASE are set, keep and/or generate CTLESC
208 * characters to allow for further processing.
209 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
212 argstr(char *p, int flag)
215 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
220 split_lit = flag & EXP_SPLIT_LIT;
221 lit_quoted = flag & EXP_LIT_QUOTED;
222 flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
223 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
224 p = exptilde(p, flag);
226 CHECKSTRSPACE(2, expdest);
235 /* "$@" syntax adherence hack */
236 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
238 if ((flag & EXP_FULL) != 0)
249 if (split_lit && !lit_quoted)
250 recordregion(expdest - stackblock() -
252 expdest - stackblock(), 0);
255 p = evalvar(p, flag);
258 case CTLBACKQ|CTLQUOTE:
259 expbackq(argbackq->n, c & CTLQUOTE, flag);
260 argbackq = argbackq->next;
268 * sort of a hack - expand tildes in variable
269 * assignments (after the first '=' and after ':'s).
272 if (split_lit && !lit_quoted)
273 recordregion(expdest - stackblock() - 1,
274 expdest - stackblock(), 0);
275 if (flag & EXP_VARTILDE && *p == '~' &&
276 (c != '=' || firsteq)) {
279 p = exptilde(p, flag);
284 if (split_lit && !lit_quoted)
285 recordregion(expdest - stackblock() - 1,
286 expdest - stackblock(), 0);
292 * Perform tilde expansion, placing the result in the stack string and
293 * returning the next position in the input string to process.
296 exptilde(char *p, int flag)
301 int quotes = flag & (EXP_FULL | EXP_CASE);
303 while ((c = *p) != '\0') {
305 case CTLESC: /* This means CTL* are always considered quoted. */
308 case CTLBACKQ | CTLQUOTE:
314 if (flag & EXP_VARTILDE)
325 if (*(startp+1) == '\0') {
326 if ((home = lookupvar("HOME")) == NULL)
329 if ((pw = getpwnam(startp+1)) == NULL)
337 STPUTS_QUOTES(home, DQSYNTAX, expdest);
339 STPUTS(home, expdest);
348 removerecordregions(int endoff)
350 if (ifslastp == NULL)
353 if (ifsfirst.endoff > endoff) {
354 while (ifsfirst.next != NULL) {
355 struct ifsregion *ifsp;
357 ifsp = ifsfirst.next->next;
358 ckfree(ifsfirst.next);
359 ifsfirst.next = ifsp;
362 if (ifsfirst.begoff > endoff)
365 ifslastp = &ifsfirst;
366 ifsfirst.endoff = endoff;
371 ifslastp = &ifsfirst;
372 while (ifslastp->next && ifslastp->next->begoff < endoff)
373 ifslastp=ifslastp->next;
374 while (ifslastp->next != NULL) {
375 struct ifsregion *ifsp;
377 ifsp = ifslastp->next->next;
378 ckfree(ifslastp->next);
379 ifslastp->next = ifsp;
382 if (ifslastp->endoff > endoff)
383 ifslastp->endoff = endoff;
387 * Expand arithmetic expression.
388 * Note that flag is not required as digits never require CTLESC characters.
399 quoted = *p++ == '"';
400 begoff = expdest - stackblock();
402 removerecordregions(begoff);
403 STPUTC('\0', expdest);
404 start = stackblock() + begoff;
406 q = grabstackstr(expdest);
407 result = arith(start);
408 ungrabstackstr(q, expdest);
410 start = stackblock() + begoff;
411 adj = start - expdest;
412 STADJUST(adj, expdest);
414 CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
415 fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
416 adj = strlen(expdest);
417 STADJUST(adj, expdest);
419 recordregion(begoff, expdest - stackblock(), 0);
425 * Perform command substitution.
428 expbackq(union node *cmd, int quoted, int flag)
434 char *dest = expdest;
435 struct ifsregion saveifs, *savelastp;
436 struct nodelist *saveargbackq;
438 int startloc = dest - stackblock();
439 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
440 int quotes = flag & (EXP_FULL | EXP_CASE);
445 savelastp = ifslastp;
446 saveargbackq = argbackq;
447 p = grabstackstr(dest);
448 evalbackcmd(cmd, &in);
449 ungrabstackstr(p, dest);
451 ifslastp = savelastp;
452 argbackq = saveargbackq;
457 /* Don't copy trailing newlines */
459 if (--in.nleft < 0) {
462 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
463 TRACE(("expbackq: read returns %d\n", i));
474 CHECKSTRSPACE(nnl + 2, dest);
479 if (quotes && syntax[(int)lastc] == CCTL)
480 USTPUTC(CTLESC, dest);
481 USTPUTC(lastc, dest);
491 exitstatus = waitforjob(in.jp, (int *)NULL);
493 recordregion(startloc, dest - stackblock(), 0);
494 TRACE(("expbackq: size=%td: \"%.*s\"\n",
495 ((dest - stackblock()) - startloc),
496 (int)((dest - stackblock()) - startloc),
497 stackblock() + startloc));
505 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
506 int varflags, int quotes)
512 struct nodelist *saveargbackq = argbackq;
515 argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
516 subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
517 EXP_CASE : 0) | EXP_TILDE);
518 STACKSTRNUL(expdest);
519 argbackq = saveargbackq;
520 startp = stackblock() + startloc;
522 str = stackblock() + strloc;
526 setvar(str, startp, 0);
527 amount = startp - expdest;
528 STADJUST(amount, expdest);
533 if (*p != CTLENDVAR) {
534 outfmt(out2, "%s\n", startp);
537 error("%.*s: parameter %snot set", (int)(p - str - 1),
538 str, (varflags & VSNUL) ? "null or "
543 for (loc = startp; loc < str; loc++) {
546 if (patmatch(str, startp, quotes)) {
551 if (quotes && *loc == CTLESC)
557 for (loc = str - 1; loc >= startp;) {
560 if (patmatch(str, startp, quotes)) {
566 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
567 for (q = startp; q < loc; q++)
577 for (loc = str - 1; loc >= startp;) {
578 if (patmatch(str, loc, quotes)) {
579 amount = loc - expdest;
580 STADJUST(amount, expdest);
584 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
585 for (q = startp; q < loc; q++)
595 for (loc = startp; loc < str - 1; loc++) {
596 if (patmatch(str, loc, quotes)) {
597 amount = loc - expdest;
598 STADJUST(amount, expdest);
601 if (quotes && *loc == CTLESC)
612 amount = ((str - 1) - (loc - startp)) - expdest;
613 STADJUST(amount, expdest);
614 while (loc != str - 1)
621 * Expand a variable, and return a pointer to the next character in the
626 evalvar(char *p, int flag)
640 int quotes = flag & (EXP_FULL | EXP_CASE);
642 varflags = (unsigned char)*p++;
643 subtype = varflags & VSTYPE;
648 p = strchr(p, '=') + 1;
649 again: /* jump here after setting a variable with ${var=text} */
650 if (varflags & VSLINENO) {
654 } else if (special) {
655 set = varisset(var, varflags & VSNUL);
658 val = bltinlookup(var, 1);
659 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
666 startloc = expdest - stackblock();
667 if (!set && uflag && *var != '@' && *var != '*') {
675 error("%.*s: parameter not set", (int)(p - var - 1),
679 if (set && subtype != VSPLUS) {
680 /* insert the value of the variable */
682 if (varflags & VSLINENO)
683 STPUTBIN(var, p - var - 1, expdest);
685 varvalue(var, varflags & VSQUOTE, subtype, flag);
686 if (subtype == VSLENGTH) {
687 varlenb = expdest - stackblock() - startloc;
690 val = stackblock() + startloc;
691 for (;val != expdest; val++)
692 if ((*val & 0xC0) == 0x80)
695 STADJUST(-varlenb, expdest);
698 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
701 if (subtype == VSLENGTH) {
704 (*val & 0xC0) != 0x80)
709 STPUTS_QUOTES(val, syntax, expdest);
711 STPUTS(val, expdest);
717 if (subtype == VSPLUS)
720 easy = ((varflags & VSQUOTE) == 0 ||
721 (*var == '@' && shellparam.nparam != 1));
726 expdest = cvtnum(varlen, expdest);
733 recordregion(startloc, expdest - stackblock(),
734 varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
735 (*var == '@' || *var == '*')));
741 argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
742 (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
756 * Terminate the string and start recording the pattern
759 STPUTC('\0', expdest);
760 patloc = expdest - stackblock();
761 if (subevalvar(p, NULL, patloc, subtype,
762 startloc, varflags, quotes) == 0) {
763 int amount = (expdest - stackblock() - patloc) + 1;
764 STADJUST(-amount, expdest);
766 /* Remove any recorded regions beyond start of variable */
767 removerecordregions(startloc);
773 if (subevalvar(p, var, 0, subtype, startloc, varflags,
777 * Remove any recorded regions beyond
780 removerecordregions(startloc);
791 error("${%.*s%s}: Bad substitution", c, var,
792 (c > 0 && *p != CTLENDVAR) ? "..." : "");
798 if (subtype != VSNORMAL) { /* skip to end of alternative */
801 if ((c = *p++) == CTLESC)
803 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
805 argbackq = argbackq->next;
806 } else if (c == CTLVAR) {
807 if ((*p++ & VSTYPE) != VSNORMAL)
809 } else if (c == CTLENDVAR) {
821 * Test whether a specialized variable is set.
825 varisset(const char *name, int nulok)
829 return backgndpidset();
830 else if (*name == '@' || *name == '*') {
831 if (*shellparam.p == NULL)
837 for (av = shellparam.p; *av; av++)
842 } else if (is_digit(*name)) {
847 num = strtol(name, NULL, 10);
848 if (errno != 0 || num > shellparam.nparam)
854 ap = shellparam.p[num - 1];
856 if (nulok && (ap == NULL || *ap == '\0'))
863 strtodest(const char *p, int flag, int subtype, int quoted)
865 if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
866 STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
872 * Add the value of a specialized variable to the stack string.
876 varvalue(const char *name, int quoted, int subtype, int flag)
892 num = shellparam.nparam;
895 num = backgndpidval();
897 expdest = cvtnum(num, expdest);
900 for (i = 0 ; i < NOPTS ; i++) {
902 STPUTC(optlist[i].letter, expdest);
906 if (flag & EXP_FULL && quoted) {
907 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
908 strtodest(p, flag, subtype, quoted);
910 STPUTC('\0', expdest);
920 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
921 strtodest(p, flag, subtype, quoted);
924 if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
925 STPUTC(sep, expdest);
930 strtodest(p, flag, subtype, quoted);
933 if (is_digit(*name)) {
935 if (num > 0 && num <= shellparam.nparam) {
936 p = shellparam.p[num - 1];
937 strtodest(p, flag, subtype, quoted);
947 * Record the fact that we have to scan this region of the
948 * string for IFS characters.
952 recordregion(int start, int end, int inquotes)
954 struct ifsregion *ifsp;
957 if (ifslastp == NULL) {
960 if (ifslastp->endoff == start
961 && ifslastp->inquotes == inquotes) {
962 /* extend previous area */
963 ifslastp->endoff = end;
967 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
968 ifslastp->next = ifsp;
971 ifslastp->next = NULL;
972 ifslastp->begoff = start;
973 ifslastp->endoff = end;
974 ifslastp->inquotes = inquotes;
981 * Break the argument string into pieces based upon IFS and add the
982 * strings to the argument list. The regions of the string to be
983 * searched for IFS characters have been stored by recordregion.
984 * CTLESC characters are preserved but have little effect in this pass
985 * other than escaping CTL* characters. In particular, they do not escape
986 * IFS characters: that should be done with the ifsregion mechanism.
987 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
988 * This pass treats them as a regular character, making the string non-empty.
989 * Later, they are removed along with the other CTL* characters.
992 ifsbreakup(char *string, struct arglist *arglist)
994 struct ifsregion *ifsp;
1001 int had_param_ch = 0;
1005 if (ifslastp == NULL) {
1006 /* Return entire argument, IFS doesn't apply to any of it */
1007 sp = (struct strlist *)stalloc(sizeof *sp);
1009 *arglist->lastp = sp;
1010 arglist->lastp = &sp->next;
1014 ifs = ifsset() ? ifsval() : " \t\n";
1016 for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1017 p = string + ifsp->begoff;
1018 while (p < string + ifsp->endoff) {
1022 if (ifsp->inquotes) {
1023 /* Only NULs (should be from "$@") end args */
1031 if (!strchr(ifs, *p)) {
1036 ifsspc = strchr(" \t\n", *p);
1038 /* Ignore IFS whitespace at start */
1039 if (q == start && ifsspc != NULL) {
1047 /* Save this argument... */
1049 sp = (struct strlist *)stalloc(sizeof *sp);
1051 *arglist->lastp = sp;
1052 arglist->lastp = &sp->next;
1055 if (ifsspc != NULL) {
1056 /* Ignore further trailing IFS whitespace */
1057 for (; p < string + ifsp->endoff; p++) {
1061 if (strchr(ifs, *p) == NULL) {
1065 if (strchr(" \t\n", *p) == NULL) {
1076 * Save anything left as an argument.
1077 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1078 * generating 2 arguments, the second of which is empty.
1079 * Some recent clarification of the Posix spec say that it
1080 * should only generate one....
1082 if (had_param_ch || *start != 0) {
1083 sp = (struct strlist *)stalloc(sizeof *sp);
1085 *arglist->lastp = sp;
1086 arglist->lastp = &sp->next;
1091 static char expdir[PATH_MAX];
1092 #define expdir_end (expdir + sizeof(expdir))
1095 * Perform pathname generation and remove control characters.
1096 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1097 * The results are stored in the list exparg.
1100 expandmeta(struct strlist *str, int flag __unused)
1103 struct strlist **savelastp;
1111 for (;;) { /* fast check for meta chars */
1112 if ((c = *p++) == '\0')
1114 if (c == '*' || c == '?' || c == '[')
1117 savelastp = exparg.lastp;
1119 expmeta(expdir, str->text);
1121 if (exparg.lastp == savelastp) {
1126 *exparg.lastp = str;
1127 rmescapes(str->text);
1128 exparg.lastp = &str->next;
1130 *exparg.lastp = NULL;
1131 *savelastp = sp = expsort(*savelastp);
1132 while (sp->next != NULL)
1134 exparg.lastp = &sp->next;
1142 * Do metacharacter (i.e. *, ?, [...]) expansion.
1146 expmeta(char *enddir, char *name)
1163 for (p = name; esc = 0, *p; p += esc + 1) {
1164 if (*p == '*' || *p == '?')
1166 else if (*p == '[') {
1168 if (*q == '!' || *q == '^')
1171 while (*q == CTLQUOTEMARK)
1175 if (*q == '/' || *q == '\0')
1182 } else if (*p == '\0')
1184 else if (*p == CTLQUOTEMARK)
1189 if (p[esc] == '/') {
1192 start = p + esc + 1;
1196 if (metaflag == 0) { /* we've reached the end of the file name */
1197 if (enddir != expdir)
1199 for (p = name ; ; p++) {
1200 if (*p == CTLQUOTEMARK)
1207 if (enddir == expdir_end)
1210 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1214 endname = name + (p - name);
1215 if (start != name) {
1218 while (*p == CTLQUOTEMARK)
1223 if (enddir == expdir_end)
1227 if (enddir == expdir) {
1229 } else if (enddir == expdir + 1 && *expdir == '/') {
1235 if ((dirp = opendir(p)) == NULL)
1237 if (enddir != expdir)
1239 if (*endname == 0) {
1248 while (*p == CTLQUOTEMARK)
1254 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1255 if (dp->d_name[0] == '.' && ! matchdot)
1257 if (patmatch(start, dp->d_name, 0)) {
1258 namlen = dp->d_namlen;
1259 if (enddir + namlen + 1 > expdir_end)
1261 memcpy(enddir, dp->d_name, namlen + 1);
1265 if (dp->d_type != DT_UNKNOWN &&
1266 dp->d_type != DT_DIR &&
1267 dp->d_type != DT_LNK)
1269 if (enddir + namlen + 2 > expdir_end)
1271 enddir[namlen] = '/';
1272 enddir[namlen + 1] = '\0';
1273 expmeta(enddir + namlen + 1, endname);
1279 endname[-esc - 1] = esc ? CTLESC : '/';
1284 * Add a file name to the list.
1288 addfname(char *name)
1295 p = stalloc(len + 1);
1296 memcpy(p, name, len + 1);
1297 sp = (struct strlist *)stalloc(sizeof *sp);
1300 exparg.lastp = &sp->next;
1305 * Sort the results of file name expansion. It calculates the number of
1306 * strings to sort and then calls msort (short for merge sort) to do the
1310 static struct strlist *
1311 expsort(struct strlist *str)
1317 for (sp = str ; sp ; sp = sp->next)
1319 return msort(str, len);
1323 static struct strlist *
1324 msort(struct strlist *list, int len)
1326 struct strlist *p, *q = NULL;
1327 struct strlist **lpp;
1335 for (n = half ; --n >= 0 ; ) {
1339 q->next = NULL; /* terminate first half of list */
1340 q = msort(list, half); /* sort first half of list */
1341 p = msort(p, len - half); /* sort second half */
1344 if (strcmp(p->text, q->text) < 0) {
1347 if ((p = *lpp) == NULL) {
1354 if ((q = *lpp) == NULL) {
1366 get_wc(const char **p)
1371 chrlen = mbtowc(&c, *p, 4);
1374 else if (chrlen == -1)
1383 * See if a character matches a character class, starting at the first colon
1385 * If a valid character class is recognized, a pointer to the next character
1386 * after the final closing bracket is stored into *end, otherwise a null
1387 * pointer is stored into *end.
1390 match_charclass(const char *p, wchar_t chr, const char **end)
1393 const char *nameend;
1398 nameend = strstr(p, ":]");
1399 if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1402 memcpy(name, p, nameend - p);
1403 name[nameend - p] = '\0';
1405 cclass = wctype(name);
1406 /* An unknown class matches nothing but is valid nevertheless. */
1409 return iswctype(chr, cclass);
1414 * Returns true if the pattern matches the string.
1418 patmatch(const char *pattern, const char *string, int squoted)
1420 const char *p, *q, *end;
1421 const char *bt_p, *bt_q;
1436 if (squoted && *q == CTLESC)
1444 if (squoted && *q == CTLESC)
1451 * A '?' does not match invalid UTF-8 but a
1452 * '*' does, so backtrack.
1457 wc = (unsigned char)*q++;
1461 while (c == CTLQUOTEMARK || c == '*')
1464 * If the pattern ends here, we know the string
1465 * matches without needing to look at the rest of it.
1470 * First try the shortest match for the '*' that
1471 * could work. We can forget any earlier '*' since
1472 * there is no way having it match more characters
1473 * can help us, given that we are already here.
1484 if (*endp == '!' || *endp == '^')
1487 while (*endp == CTLQUOTEMARK)
1490 goto dft; /* no matching ] */
1491 if (*endp == CTLESC)
1497 if (*p == '!' || *p == '^') {
1502 if (squoted && *q == CTLESC)
1511 chr = (unsigned char)*q++;
1514 if (c == CTLQUOTEMARK)
1516 if (c == '[' && *p == ':') {
1517 found |= match_charclass(p, chr, &end);
1523 if (localeisutf8 && c & 0x80) {
1526 if (wc == 0) /* bad utf-8 */
1529 wc = (unsigned char)c;
1530 if (*p == '-' && p[1] != ']') {
1532 while (*p == CTLQUOTEMARK)
1538 if (wc2 == 0) /* bad utf-8 */
1541 wc2 = (unsigned char)*p++;
1542 if ( collate_range_cmp(chr, wc) >= 0
1543 && collate_range_cmp(chr, wc2) <= 0
1550 } while ((c = *p++) != ']');
1551 if (found == invert)
1556 if (squoted && *q == CTLESC)
1564 * If we have a mismatch (other than hitting the end
1565 * of the string), go back to the last '*' seen and
1566 * have it match one additional character.
1570 if (squoted && *bt_q == CTLESC)
1585 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1589 rmescapes(char *str)
1594 while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1600 if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1614 * See if a pattern matches in a case statement.
1618 casematch(union node *pattern, const char *val)
1620 struct stackmark smark;
1624 setstackmark(&smark);
1625 argbackq = pattern->narg.backquote;
1626 STARTSTACKSTR(expdest);
1628 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1629 STPUTC('\0', expdest);
1630 p = grabstackstr(expdest);
1631 result = patmatch(p, val, 0);
1632 popstackmark(&smark);
1641 cvtnum(int num, char *buf)
1645 char *p = temp + 31;
1650 *--p = num % 10 + '0';
1651 } while ((num /= 10) != 0);
1661 * Do most of the work for wordexp(3).
1665 wordexpcmd(int argc, char **argv)
1670 out1fmt("%08x", argc - 1);
1671 for (i = 1, len = 0; i < argc; i++)
1672 len += strlen(argv[i]);
1673 out1fmt("%08x", (int)len);
1674 for (i = 1; i < argc; i++)
1675 outbin(argv[i], strlen(argv[i]) + 1, out1);