xref: /netbsd-src/bin/sh/expand.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. 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.
23  *
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
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 /*static char sccsid[] = "from: @(#)expand.c	8.2 (Berkeley) 10/22/93";*/
39 static char *rcsid = "$Id: expand.c,v 1.12 1994/12/04 07:12:11 cgd Exp $";
40 #endif /* not lint */
41 
42 /*
43  * Routines to expand arguments to commands.  We have to deal with
44  * backquotes, shell variables, and file metacharacters.
45  */
46 
47 #include "shell.h"
48 #include "main.h"
49 #include "nodes.h"
50 #include "eval.h"
51 #include "expand.h"
52 #include "syntax.h"
53 #include "parser.h"
54 #include "jobs.h"
55 #include "options.h"
56 #include "var.h"
57 #include "input.h"
58 #include "output.h"
59 #include "memalloc.h"
60 #include "error.h"
61 #include "mystring.h"
62 #include <sys/types.h>
63 #include <sys/time.h>
64 #include <sys/stat.h>
65 #include <errno.h>
66 #include <dirent.h>
67 #include <unistd.h>
68 #include <pwd.h>
69 
70 /*
71  * Structure specifying which parts of the string should be searched
72  * for IFS characters.
73  */
74 
75 struct ifsregion {
76 	struct ifsregion *next;	/* next region in list */
77 	int begoff;		/* offset of start of region */
78 	int endoff;		/* offset of end of region */
79 	int nulonly;		/* search for nul bytes only */
80 };
81 
82 
83 char *expdest;			/* output of current string */
84 struct nodelist *argbackq;	/* list of back quote expressions */
85 struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
86 struct ifsregion *ifslastp;	/* last struct in list */
87 struct arglist exparg;		/* holds expanded arg list */
88 
89 #ifdef __STDC__
90 STATIC void argstr(char *, int);
91 STATIC void expbackq(union node *, int, int);
92 STATIC char *evalvar(char *, int);
93 STATIC int varisset(int);
94 STATIC void varvalue(int, int, int);
95 STATIC void recordregion(int, int, int);
96 STATIC void ifsbreakup(char *, struct arglist *);
97 STATIC void expandmeta(struct strlist *, int);
98 STATIC void expmeta(char *, char *);
99 STATIC void expari(int);
100 STATIC void addfname(char *);
101 STATIC struct strlist *expsort(struct strlist *);
102 STATIC struct strlist *msort(struct strlist *, int);
103 STATIC int pmatch(char *, char *);
104 STATIC char *exptilde(char *, int);
105 #else
106 STATIC void argstr();
107 STATIC void expbackq();
108 STATIC char *evalvar();
109 STATIC int varisset();
110 STATIC void varvalue();
111 STATIC void recordregion();
112 STATIC void ifsbreakup();
113 STATIC void expandmeta();
114 STATIC void expmeta();
115 STATIC void expari();
116 STATIC void addfname();
117 STATIC struct strlist *expsort();
118 STATIC struct strlist *msort();
119 STATIC int pmatch();
120 STATIC char *exptilde();
121 #endif
122 
123 /*
124  * Expand shell variables and backquotes inside a here document.
125  */
126 
127 void
128 expandhere(arg, fd)
129 	union node *arg;	/* the document */
130 	int fd;			/* where to write the expanded version */
131 	{
132 	herefd = fd;
133 	expandarg(arg, (struct arglist *)NULL, 0);
134 	xwrite(fd, stackblock(), expdest - stackblock());
135 }
136 
137 
138 /*
139  * Perform variable substitution and command substitution on an argument,
140  * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
141  * perform splitting and file name expansion.  When arglist is NULL, perform
142  * here document expansion.
143  */
144 
145 void
146 expandarg(arg, arglist, flag)
147 	union node *arg;
148 	struct arglist *arglist;
149 	int flag;
150 {
151 	struct strlist *sp;
152 	char *p;
153 
154 	argbackq = arg->narg.backquote;
155 	STARTSTACKSTR(expdest);
156 	ifsfirst.next = NULL;
157 	ifslastp = NULL;
158 	argstr(arg->narg.text, flag);
159 	if (arglist == NULL) {
160 		return;			/* here document expanded */
161 	}
162 	STPUTC('\0', expdest);
163 	p = grabstackstr(expdest);
164 	exparg.lastp = &exparg.list;
165 	/*
166 	 * TODO - EXP_REDIR
167 	 */
168 	if (flag & EXP_FULL) {
169 		ifsbreakup(p, &exparg);
170 		*exparg.lastp = NULL;
171 		exparg.lastp = &exparg.list;
172 		expandmeta(exparg.list, flag);
173 	} else {
174 		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
175 			rmescapes(p);
176 		sp = (struct strlist *)stalloc(sizeof (struct strlist));
177 		sp->text = p;
178 		*exparg.lastp = sp;
179 		exparg.lastp = &sp->next;
180 	}
181 	while (ifsfirst.next != NULL) {
182 		struct ifsregion *ifsp;
183 		INTOFF;
184 		ifsp = ifsfirst.next->next;
185 		ckfree(ifsfirst.next);
186 		ifsfirst.next = ifsp;
187 		INTON;
188 	}
189 	*exparg.lastp = NULL;
190 	if (exparg.list) {
191 		*arglist->lastp = exparg.list;
192 		arglist->lastp = exparg.lastp;
193 	}
194 }
195 
196 
197 
198 /*
199  * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
200  * characters to allow for further processing.  Otherwise treat
201  * $@ like $* since no splitting will be performed.
202  */
203 
204 STATIC void
205 argstr(p, flag)
206 	register char *p;
207 	int flag;
208 {
209 	register char c;
210 	int quotes = flag & (EXP_FULL | EXP_CASE);	/* do CTLESC */
211 	int firsteq = 1;
212 
213 	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
214 		p = exptilde(p, flag);
215 	for (;;) {
216 		switch (c = *p++) {
217 		case '\0':
218 		case CTLENDVAR: /* ??? */
219 			goto breakloop;
220 		case CTLESC:
221 			if (quotes)
222 				STPUTC(c, expdest);
223 			c = *p++;
224 			STPUTC(c, expdest);
225 			break;
226 		case CTLVAR:
227 			p = evalvar(p, flag);
228 			break;
229 		case CTLBACKQ:
230 		case CTLBACKQ|CTLQUOTE:
231 			expbackq(argbackq->n, c & CTLQUOTE, flag);
232 			argbackq = argbackq->next;
233 			break;
234 		case CTLENDARI:
235 			expari(flag);
236 			break;
237 		case ':':
238 		case '=':
239 			/*
240 			 * sort of a hack - expand tildes in variable
241 			 * assignments (after the first '=' and after ':'s).
242 			 */
243 			STPUTC(c, expdest);
244 			if (flag & EXP_VARTILDE && *p == '~') {
245 				if (c == '=') {
246 					if (firsteq)
247 						firsteq = 0;
248 					else
249 						break;
250 				}
251 				p = exptilde(p, flag);
252 			}
253 			break;
254 		default:
255 			STPUTC(c, expdest);
256 		}
257 	}
258 breakloop:;
259 }
260 
261 STATIC char *
262 exptilde(p, flag)
263 	char *p;
264 	int flag;
265 {
266 	char c, *startp = p;
267 	struct passwd *pw;
268 	char *home;
269 	int quotes = flag & (EXP_FULL | EXP_CASE);
270 
271 	while (c = *p) {
272 		switch(c) {
273 		case CTLESC:
274 			return (startp);
275 		case ':':
276 			if (flag & EXP_VARTILDE)
277 				goto done;
278 			break;
279 		case '/':
280 			goto done;
281 		}
282 		p++;
283 	}
284 done:
285 	*p = '\0';
286 	if (*(startp+1) == '\0') {
287 		if ((home = lookupvar("HOME")) == NULL)
288 			goto lose;
289 	} else {
290 		if ((pw = getpwnam(startp+1)) == NULL)
291 			goto lose;
292 		home = pw->pw_dir;
293 	}
294 	if (*home == '\0')
295 		goto lose;
296 	*p = c;
297 	while (c = *home++) {
298 		if (quotes && SQSYNTAX[c] == CCTL)
299 			STPUTC(CTLESC, expdest);
300 		STPUTC(c, expdest);
301 	}
302 	return (p);
303 lose:
304 	*p = c;
305 	return (startp);
306 }
307 
308 
309 /*
310  * Expand arithmetic expression.  Backup to start of expression,
311  * evaluate, place result in (backed up) result, adjust string position.
312  */
313 void
314 expari(flag)
315 	int flag;
316 {
317 	char *p, *start;
318 	int result;
319 	int quotes = flag & (EXP_FULL | EXP_CASE);
320 
321 	/*
322 	 * This routine is slightly over-compilcated for
323 	 * efficiency.  First we make sure there is
324 	 * enough space for the result, which may be bigger
325 	 * than the expression if we add exponentation.  Next we
326 	 * scan backwards looking for the start of arithmetic.  If the
327 	 * next previous character is a CTLESC character, then we
328 	 * have to rescan starting from the beginning since CTLESC
329 	 * characters have to be processed left to right.
330 	 */
331 	CHECKSTRSPACE(8, expdest);
332 	USTPUTC('\0', expdest);
333 	start = stackblock();
334 	p = expdest;
335 	while (*p != CTLARI && p >= start)
336 		--p;
337 	if (*p != CTLARI)
338 		error("missing CTLARI (shouldn't happen)");
339 	if (p > start && *(p-1) == CTLESC)
340 		for (p = start; *p != CTLARI; p++)
341 			if (*p == CTLESC)
342 				p++;
343 	if (quotes)
344 		rmescapes(p+1);
345 	result = arith(p+1);
346 	fmtstr(p, 10, "%d", result);
347 	while (*p++)
348 		;
349 	result = expdest - p + 1;
350 	STADJUST(-result, expdest);
351 }
352 
353 
354 /*
355  * Expand stuff in backwards quotes.
356  */
357 
358 STATIC void
359 expbackq(cmd, quoted, flag)
360 	union node *cmd;
361 	int quoted;
362 	int flag;
363 {
364 	struct backcmd in;
365 	int i;
366 	char buf[128];
367 	char *p;
368 	char *dest = expdest;
369 	struct ifsregion saveifs, *savelastp;
370 	struct nodelist *saveargbackq;
371 	char lastc;
372 	int startloc = dest - stackblock();
373 	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
374 	int saveherefd;
375 	int quotes = flag & (EXP_FULL | EXP_CASE);
376 
377 	INTOFF;
378 	saveifs = ifsfirst;
379 	savelastp = ifslastp;
380 	saveargbackq = argbackq;
381 	saveherefd = herefd;
382 	herefd = -1;
383 	p = grabstackstr(dest);
384 	evalbackcmd(cmd, &in);
385 	ungrabstackstr(p, dest);
386 	ifsfirst = saveifs;
387 	ifslastp = savelastp;
388 	argbackq = saveargbackq;
389 	herefd = saveherefd;
390 
391 	p = in.buf;
392 	lastc = '\0';
393 	for (;;) {
394 		if (--in.nleft < 0) {
395 			if (in.fd < 0)
396 				break;
397 			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
398 			TRACE(("expbackq: read returns %d\n", i));
399 			if (i <= 0)
400 				break;
401 			p = buf;
402 			in.nleft = i - 1;
403 		}
404 		lastc = *p++;
405 		if (lastc != '\0') {
406 			if (quotes && syntax[lastc] == CCTL)
407 				STPUTC(CTLESC, dest);
408 			STPUTC(lastc, dest);
409 		}
410 	}
411 	if (lastc == '\n') {
412 		STUNPUTC(dest);
413 	}
414 	if (in.fd >= 0)
415 		close(in.fd);
416 	if (in.buf)
417 		ckfree(in.buf);
418 	if (in.jp)
419 		exitstatus = waitforjob(in.jp);
420 	if (quoted == 0)
421 		recordregion(startloc, dest - stackblock(), 0);
422 	TRACE(("evalbackq: size=%d: \"%.*s\"\n",
423 		(dest - stackblock()) - startloc,
424 		(dest - stackblock()) - startloc,
425 		stackblock() + startloc));
426 	expdest = dest;
427 	INTON;
428 }
429 
430 
431 
432 /*
433  * Expand a variable, and return a pointer to the next character in the
434  * input string.
435  */
436 
437 STATIC char *
438 evalvar(p, flag)
439 	char *p;
440 	int flag;
441 {
442 	int subtype;
443 	int varflags;
444 	char *var;
445 	char *val;
446 	int c;
447 	int set;
448 	int special;
449 	int startloc;
450 	int quotes = flag & (EXP_FULL | EXP_CASE);
451 
452 	varflags = *p++;
453 	subtype = varflags & VSTYPE;
454 	var = p;
455 	special = 0;
456 	if (! is_name(*p))
457 		special = 1;
458 	p = strchr(p, '=') + 1;
459 again: /* jump here after setting a variable with ${var=text} */
460 	if (special) {
461 		set = varisset(*var);
462 		val = NULL;
463 	} else {
464 		val = lookupvar(var);
465 		if (val == NULL || (varflags & VSNUL) && val[0] == '\0') {
466 			val = NULL;
467 			set = 0;
468 		} else
469 			set = 1;
470 	}
471 	startloc = expdest - stackblock();
472 	if (set && subtype != VSPLUS) {
473 		/* insert the value of the variable */
474 		if (special) {
475 			varvalue(*var, varflags & VSQUOTE, flag & EXP_FULL);
476 		} else {
477 			char const *syntax = (varflags & VSQUOTE)? DQSYNTAX : BASESYNTAX;
478 
479 			while (*val) {
480 				if (quotes && syntax[*val] == CCTL)
481 					STPUTC(CTLESC, expdest);
482 				STPUTC(*val++, expdest);
483 			}
484 		}
485 	}
486 	if (subtype == VSPLUS)
487 		set = ! set;
488 	if (((varflags & VSQUOTE) == 0 || (*var == '@' && shellparam.nparam != 1))
489 	 && (set || subtype == VSNORMAL))
490 		recordregion(startloc, expdest - stackblock(), varflags & VSQUOTE);
491 	if (! set && subtype != VSNORMAL) {
492 		if (subtype == VSPLUS || subtype == VSMINUS) {
493 			argstr(p, flag);
494 		} else {
495 			char *startp;
496 			int saveherefd = herefd;
497 			struct nodelist *saveargbackq = argbackq;
498 			herefd = -1;
499 			argstr(p, 0);
500 			STACKSTRNUL(expdest);
501 			herefd = saveherefd;
502 			argbackq = saveargbackq;
503 			startp = stackblock() + startloc;
504 			if (subtype == VSASSIGN) {
505 				setvar(var, startp, 0);
506 				STADJUST(startp - expdest, expdest);
507 				varflags &=~ VSNUL;
508 				goto again;
509 			}
510 			/* subtype == VSQUESTION */
511 			if (*p != CTLENDVAR) {
512 				outfmt(&errout, "%s\n", startp);
513 				error((char *)NULL);
514 			}
515 			error("%.*s: parameter %snot set", p - var - 1,
516 				var, (varflags & VSNUL)? "null or " : nullstr);
517 		}
518 	}
519 	if (subtype != VSNORMAL) {	/* skip to end of alternative */
520 		int nesting = 1;
521 		for (;;) {
522 			if ((c = *p++) == CTLESC)
523 				p++;
524 			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
525 				if (set)
526 					argbackq = argbackq->next;
527 			} else if (c == CTLVAR) {
528 				if ((*p++ & VSTYPE) != VSNORMAL)
529 					nesting++;
530 			} else if (c == CTLENDVAR) {
531 				if (--nesting == 0)
532 					break;
533 			}
534 		}
535 	}
536 	return p;
537 }
538 
539 
540 
541 /*
542  * Test whether a specialized variable is set.
543  */
544 
545 STATIC int
546 varisset(name)
547 	char name;
548 	{
549 	char **ap;
550 
551 	if (name == '!') {
552 		if (backgndpid == -1)
553 			return 0;
554 	} else if (name == '@' || name == '*') {
555 		if (*shellparam.p == NULL)
556 			return 0;
557 	} else if ((unsigned)(name -= '1') <= '9' - '1') {
558 		ap = shellparam.p;
559 		do {
560 			if (*ap++ == NULL)
561 				return 0;
562 		} while (--name >= 0);
563 	}
564 	return 1;
565 }
566 
567 
568 
569 /*
570  * Add the value of a specialized variable to the stack string.
571  */
572 
573 STATIC void
574 varvalue(name, quoted, allow_split)
575 	char name;
576 	int quoted;
577 	int allow_split;
578 {
579 	int num;
580 	char temp[32];
581 	char *p;
582 	int i;
583 	extern int exitstatus;
584 	char sep;
585 	char **ap;
586 	char const *syntax;
587 
588 #define STRTODEST(p) \
589 	do {\
590 	if (allow_split) { \
591 		syntax = quoted? DQSYNTAX : BASESYNTAX; \
592 		while (*p) { \
593 			if (syntax[*p] == CCTL) \
594 				STPUTC(CTLESC, expdest); \
595 			STPUTC(*p++, expdest); \
596 		} \
597 	} else \
598 		while (*p) \
599 			STPUTC(*p++, expdest); \
600 	} while (0)
601 
602 
603 	switch (name) {
604 	case '$':
605 		num = rootpid;
606 		goto numvar;
607 	case '?':
608 		num = exitstatus;
609 		goto numvar;
610 	case '#':
611 		num = shellparam.nparam;
612 		goto numvar;
613 	case '!':
614 		num = backgndpid;
615 numvar:
616 		p = temp + 31;
617 		temp[31] = '\0';
618 		do {
619 			*--p = num % 10 + '0';
620 		} while ((num /= 10) != 0);
621 		while (*p)
622 			STPUTC(*p++, expdest);
623 		break;
624 	case '-':
625 		for (i = 0 ; i < NOPTS ; i++) {
626 			if (optlist[i].val)
627 				STPUTC(optlist[i].letter, expdest);
628 		}
629 		break;
630 	case '@':
631 		if (allow_split) {
632 			sep = '\0';
633 			goto allargs;
634 		}
635 		/* fall through */
636 	case '*':
637 		sep = ' ';
638 allargs:
639 		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
640 			STRTODEST(p);
641 			if (*ap)
642 				STPUTC(sep, expdest);
643 		}
644 		break;
645 	case '0':
646 		p = arg0;
647 		STRTODEST(p);
648 		break;
649 	default:
650 		if ((unsigned)(name -= '1') <= '9' - '1') {
651 			p = shellparam.p[name];
652 			STRTODEST(p);
653 		}
654 		break;
655 	}
656 }
657 
658 
659 
660 /*
661  * Record the the fact that we have to scan this region of the
662  * string for IFS characters.
663  */
664 
665 STATIC void
666 recordregion(start, end, nulonly)
667 	int start;
668 	int end;
669 	int nulonly;
670 {
671 	register struct ifsregion *ifsp;
672 
673 	if (ifslastp == NULL) {
674 		ifsp = &ifsfirst;
675 	} else {
676 		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
677 		ifslastp->next = ifsp;
678 	}
679 	ifslastp = ifsp;
680 	ifslastp->next = NULL;
681 	ifslastp->begoff = start;
682 	ifslastp->endoff = end;
683 	ifslastp->nulonly = nulonly;
684 }
685 
686 
687 
688 /*
689  * Break the argument string into pieces based upon IFS and add the
690  * strings to the argument list.  The regions of the string to be
691  * searched for IFS characters have been stored by recordregion.
692  */
693 
694 STATIC void
695 ifsbreakup(string, arglist)
696 	char *string;
697 	struct arglist *arglist;
698 	{
699 	struct ifsregion *ifsp;
700 	struct strlist *sp;
701 	char *start;
702 	register char *p;
703 	char *q;
704 	char *ifs;
705 
706 	start = string;
707 	if (ifslastp != NULL) {
708 		ifsp = &ifsfirst;
709 		do {
710 			p = string + ifsp->begoff;
711 			ifs = ifsp->nulonly? nullstr : ifsval();
712 			while (p < string + ifsp->endoff) {
713 				q = p;
714 				if (*p == CTLESC)
715 					p++;
716 				if (strchr(ifs, *p++)) {
717 					if (q > start || *ifs != ' ') {
718 						*q = '\0';
719 						sp = (struct strlist *)stalloc(sizeof *sp);
720 						sp->text = start;
721 						*arglist->lastp = sp;
722 						arglist->lastp = &sp->next;
723 					}
724 					if (*ifs == ' ') {
725 						for (;;) {
726 							if (p >= string + ifsp->endoff)
727 								break;
728 							q = p;
729 							if (*p == CTLESC)
730 								p++;
731 							if (strchr(ifs, *p++) == NULL) {
732 								p = q;
733 								break;
734 							}
735 						}
736 					}
737 					start = p;
738 				}
739 			}
740 		} while ((ifsp = ifsp->next) != NULL);
741 		if (*start || (*ifs != ' ' && start > string)) {
742 			sp = (struct strlist *)stalloc(sizeof *sp);
743 			sp->text = start;
744 			*arglist->lastp = sp;
745 			arglist->lastp = &sp->next;
746 		}
747 	} else {
748 		sp = (struct strlist *)stalloc(sizeof *sp);
749 		sp->text = start;
750 		*arglist->lastp = sp;
751 		arglist->lastp = &sp->next;
752 	}
753 }
754 
755 
756 
757 /*
758  * Expand shell metacharacters.  At this point, the only control characters
759  * should be escapes.  The results are stored in the list exparg.
760  */
761 
762 char *expdir;
763 
764 
765 STATIC void
766 expandmeta(str, flag)
767 	struct strlist *str;
768 	int flag;
769 {
770 	char *p;
771 	struct strlist **savelastp;
772 	struct strlist *sp;
773 	char c;
774 	/* TODO - EXP_REDIR */
775 
776 	while (str) {
777 		if (fflag)
778 			goto nometa;
779 		p = str->text;
780 		for (;;) {			/* fast check for meta chars */
781 			if ((c = *p++) == '\0')
782 				goto nometa;
783 			if (c == '*' || c == '?' || c == '[' || c == '!')
784 				break;
785 		}
786 		savelastp = exparg.lastp;
787 		INTOFF;
788 		if (expdir == NULL) {
789 			int i = strlen(str->text);
790 			expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
791 		}
792 
793 		expmeta(expdir, str->text);
794 		ckfree(expdir);
795 		expdir = NULL;
796 		INTON;
797 		if (exparg.lastp == savelastp) {
798 			/*
799 			 * no matches
800 			 */
801 nometa:
802 			*exparg.lastp = str;
803 			rmescapes(str->text);
804 			exparg.lastp = &str->next;
805 		} else {
806 			*exparg.lastp = NULL;
807 			*savelastp = sp = expsort(*savelastp);
808 			while (sp->next != NULL)
809 				sp = sp->next;
810 			exparg.lastp = &sp->next;
811 		}
812 		str = str->next;
813 	}
814 }
815 
816 
817 /*
818  * Do metacharacter (i.e. *, ?, [...]) expansion.
819  */
820 
821 STATIC void
822 expmeta(enddir, name)
823 	char *enddir;
824 	char *name;
825 	{
826 	register char *p;
827 	char *q;
828 	char *start;
829 	char *endname;
830 	int metaflag;
831 	struct stat statb;
832 	DIR *dirp;
833 	struct dirent *dp;
834 	int atend;
835 	int matchdot;
836 
837 	metaflag = 0;
838 	start = name;
839 	for (p = name ; ; p++) {
840 		if (*p == '*' || *p == '?')
841 			metaflag = 1;
842 		else if (*p == '[') {
843 			q = p + 1;
844 			if (*q == '!')
845 				q++;
846 			for (;;) {
847 				if (*q == CTLESC)
848 					q++;
849 				if (*q == '/' || *q == '\0')
850 					break;
851 				if (*++q == ']') {
852 					metaflag = 1;
853 					break;
854 				}
855 			}
856 		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
857 			metaflag = 1;
858 		} else if (*p == '\0')
859 			break;
860 		else if (*p == CTLESC)
861 			p++;
862 		if (*p == '/') {
863 			if (metaflag)
864 				break;
865 			start = p + 1;
866 		}
867 	}
868 	if (metaflag == 0) {	/* we've reached the end of the file name */
869 		if (enddir != expdir)
870 			metaflag++;
871 		for (p = name ; ; p++) {
872 			if (*p == CTLESC)
873 				p++;
874 			*enddir++ = *p;
875 			if (*p == '\0')
876 				break;
877 		}
878 		if (metaflag == 0 || stat(expdir, &statb) >= 0)
879 			addfname(expdir);
880 		return;
881 	}
882 	endname = p;
883 	if (start != name) {
884 		p = name;
885 		while (p < start) {
886 			if (*p == CTLESC)
887 				p++;
888 			*enddir++ = *p++;
889 		}
890 	}
891 	if (enddir == expdir) {
892 		p = ".";
893 	} else if (enddir == expdir + 1 && *expdir == '/') {
894 		p = "/";
895 	} else {
896 		p = expdir;
897 		enddir[-1] = '\0';
898 	}
899 	if ((dirp = opendir(p)) == NULL)
900 		return;
901 	if (enddir != expdir)
902 		enddir[-1] = '/';
903 	if (*endname == 0) {
904 		atend = 1;
905 	} else {
906 		atend = 0;
907 		*endname++ = '\0';
908 	}
909 	matchdot = 0;
910 	if (start[0] == '.' || start[0] == CTLESC && start[1] == '.')
911 		matchdot++;
912 	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
913 		if (dp->d_name[0] == '.' && ! matchdot)
914 			continue;
915 		if (patmatch(start, dp->d_name)) {
916 			if (atend) {
917 				scopy(dp->d_name, enddir);
918 				addfname(expdir);
919 			} else {
920 				char *q;
921 				for (p = enddir, q = dp->d_name ; *p++ = *q++ ;);
922 				p[-1] = '/';
923 				expmeta(p, endname);
924 			}
925 		}
926 	}
927 	closedir(dirp);
928 	if (! atend)
929 		endname[-1] = '/';
930 }
931 
932 
933 /*
934  * Add a file name to the list.
935  */
936 
937 STATIC void
938 addfname(name)
939 	char *name;
940 	{
941 	char *p;
942 	struct strlist *sp;
943 
944 	p = stalloc(strlen(name) + 1);
945 	scopy(name, p);
946 	sp = (struct strlist *)stalloc(sizeof *sp);
947 	sp->text = p;
948 	*exparg.lastp = sp;
949 	exparg.lastp = &sp->next;
950 }
951 
952 
953 /*
954  * Sort the results of file name expansion.  It calculates the number of
955  * strings to sort and then calls msort (short for merge sort) to do the
956  * work.
957  */
958 
959 STATIC struct strlist *
960 expsort(str)
961 	struct strlist *str;
962 	{
963 	int len;
964 	struct strlist *sp;
965 
966 	len = 0;
967 	for (sp = str ; sp ; sp = sp->next)
968 		len++;
969 	return msort(str, len);
970 }
971 
972 
973 STATIC struct strlist *
974 msort(list, len)
975 	struct strlist *list;
976 	int len;
977 {
978 	struct strlist *p, *q;
979 	struct strlist **lpp;
980 	int half;
981 	int n;
982 
983 	if (len <= 1)
984 		return list;
985 	half = len >> 1;
986 	p = list;
987 	for (n = half ; --n >= 0 ; ) {
988 		q = p;
989 		p = p->next;
990 	}
991 	q->next = NULL;			/* terminate first half of list */
992 	q = msort(list, half);		/* sort first half of list */
993 	p = msort(p, len - half);		/* sort second half */
994 	lpp = &list;
995 	for (;;) {
996 		if (strcmp(p->text, q->text) < 0) {
997 			*lpp = p;
998 			lpp = &p->next;
999 			if ((p = *lpp) == NULL) {
1000 				*lpp = q;
1001 				break;
1002 			}
1003 		} else {
1004 			*lpp = q;
1005 			lpp = &q->next;
1006 			if ((q = *lpp) == NULL) {
1007 				*lpp = p;
1008 				break;
1009 			}
1010 		}
1011 	}
1012 	return list;
1013 }
1014 
1015 
1016 
1017 /*
1018  * Returns true if the pattern matches the string.
1019  */
1020 
1021 int
1022 patmatch(pattern, string)
1023 	char *pattern;
1024 	char *string;
1025 	{
1026 #ifdef notdef
1027 	if (pattern[0] == '!' && pattern[1] == '!')
1028 		return 1 - pmatch(pattern + 2, string);
1029 	else
1030 #endif
1031 		return pmatch(pattern, string);
1032 }
1033 
1034 
1035 STATIC int
1036 pmatch(pattern, string)
1037 	char *pattern;
1038 	char *string;
1039 	{
1040 	register char *p, *q;
1041 	register char c;
1042 
1043 	p = pattern;
1044 	q = string;
1045 	for (;;) {
1046 		switch (c = *p++) {
1047 		case '\0':
1048 			goto breakloop;
1049 		case CTLESC:
1050 			if (*q++ != *p++)
1051 				return 0;
1052 			break;
1053 		case '?':
1054 			if (*q++ == '\0')
1055 				return 0;
1056 			break;
1057 		case '*':
1058 			c = *p;
1059 			if (c != CTLESC && c != '?' && c != '*' && c != '[') {
1060 				while (*q != c) {
1061 					if (*q == '\0')
1062 						return 0;
1063 					q++;
1064 				}
1065 			}
1066 			do {
1067 				if (pmatch(p, q))
1068 					return 1;
1069 			} while (*q++ != '\0');
1070 			return 0;
1071 		case '[': {
1072 			char *endp;
1073 			int invert, found;
1074 			char chr;
1075 
1076 			endp = p;
1077 			if (*endp == '!')
1078 				endp++;
1079 			for (;;) {
1080 				if (*endp == '\0')
1081 					goto dft;		/* no matching ] */
1082 				if (*endp == CTLESC)
1083 					endp++;
1084 				if (*++endp == ']')
1085 					break;
1086 			}
1087 			invert = 0;
1088 			if (*p == '!') {
1089 				invert++;
1090 				p++;
1091 			}
1092 			found = 0;
1093 			chr = *q++;
1094 			if (chr == '\0')
1095 				return 0;
1096 			c = *p++;
1097 			do {
1098 				if (c == CTLESC)
1099 					c = *p++;
1100 				if (*p == '-' && p[1] != ']') {
1101 					p++;
1102 					if (*p == CTLESC)
1103 						p++;
1104 					if (chr >= c && chr <= *p)
1105 						found = 1;
1106 					p++;
1107 				} else {
1108 					if (chr == c)
1109 						found = 1;
1110 				}
1111 			} while ((c = *p++) != ']');
1112 			if (found == invert)
1113 				return 0;
1114 			break;
1115 		}
1116 dft:	        default:
1117 			if (*q++ != c)
1118 				return 0;
1119 			break;
1120 		}
1121 	}
1122 breakloop:
1123 	if (*q != '\0')
1124 		return 0;
1125 	return 1;
1126 }
1127 
1128 
1129 
1130 /*
1131  * Remove any CTLESC characters from a string.
1132  */
1133 
1134 void
1135 rmescapes(str)
1136 	char *str;
1137 	{
1138 	register char *p, *q;
1139 
1140 	p = str;
1141 	while (*p != CTLESC) {
1142 		if (*p++ == '\0')
1143 			return;
1144 	}
1145 	q = p;
1146 	while (*p) {
1147 		if (*p == CTLESC)
1148 			p++;
1149 		*q++ = *p++;
1150 	}
1151 	*q = '\0';
1152 }
1153 
1154 
1155 
1156 /*
1157  * See if a pattern matches in a case statement.
1158  */
1159 
1160 int
1161 casematch(pattern, val)
1162 	union node *pattern;
1163 	char *val;
1164 	{
1165 	struct stackmark smark;
1166 	int result;
1167 	char *p;
1168 
1169 	setstackmark(&smark);
1170 	argbackq = pattern->narg.backquote;
1171 	STARTSTACKSTR(expdest);
1172 	ifslastp = NULL;
1173 	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1174 	STPUTC('\0', expdest);
1175 	p = grabstackstr(expdest);
1176 	result = patmatch(p, val);
1177 	popstackmark(&smark);
1178 	return result;
1179 }
1180