expand.c revision 316942
1/*-
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 *
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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.
21 *
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
32 * SUCH DAMAGE.
33 */
34
35#ifndef lint
36#if 0
37static char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
38#endif
39#endif /* not lint */
40#include <sys/cdefs.h>
41__FBSDID("$FreeBSD: stable/10/bin/sh/expand.c 316942 2017-04-14 21:42:27Z jilles $");
42
43#include <sys/types.h>
44#include <sys/time.h>
45#include <sys/stat.h>
46#include <dirent.h>
47#include <errno.h>
48#include <inttypes.h>
49#include <limits.h>
50#include <pwd.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <unistd.h>
55#include <wchar.h>
56#include <wctype.h>
57
58/*
59 * Routines to expand arguments to commands.  We have to deal with
60 * backquotes, shell variables, and file metacharacters.
61 */
62
63#include "shell.h"
64#include "main.h"
65#include "nodes.h"
66#include "eval.h"
67#include "expand.h"
68#include "syntax.h"
69#include "parser.h"
70#include "jobs.h"
71#include "options.h"
72#include "var.h"
73#include "input.h"
74#include "output.h"
75#include "memalloc.h"
76#include "error.h"
77#include "mystring.h"
78#include "arith.h"
79#include "show.h"
80#include "builtins.h"
81
82/*
83 * Structure specifying which parts of the string should be searched
84 * for IFS characters.
85 */
86
87struct ifsregion {
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 */
92};
93
94
95static char *expdest;			/* output of current string */
96static struct nodelist *argbackq;	/* list of back quote expressions */
97static struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
98static struct ifsregion *ifslastp;	/* last struct in list */
99static struct arglist exparg;		/* holds expanded arg list */
100
101static char *argstr(char *, int);
102static char *exptilde(char *, int);
103static char *expari(char *);
104static void expbackq(union node *, int, int);
105static int subevalvar(char *, char *, int, int, int, int, int);
106static char *evalvar(char *, int);
107static int varisset(const char *, int);
108static void strtodest(const char *, int, int, int);
109static void varvalue(const char *, int, int, int);
110static void recordregion(int, int, int);
111static void removerecordregions(int);
112static void ifsbreakup(char *, struct arglist *);
113static void expandmeta(struct strlist *);
114static void expmeta(char *, char *);
115static void addfname(char *);
116static struct strlist *expsort(struct strlist *);
117static struct strlist *msort(struct strlist *, int);
118static int patmatch(const char *, const char *, int);
119static char *cvtnum(int, char *);
120static int collate_range_cmp(wchar_t, wchar_t);
121
122static int
123collate_range_cmp(wchar_t c1, wchar_t c2)
124{
125	static wchar_t s1[2], s2[2];
126
127	s1[0] = c1;
128	s2[0] = c2;
129	return (wcscoll(s1, s2));
130}
131
132static char *
133stputs_quotes(const char *data, const char *syntax, char *p)
134{
135	while (*data) {
136		CHECKSTRSPACE(2, p);
137		if (syntax[(int)*data] == CCTL)
138			USTPUTC(CTLESC, p);
139		USTPUTC(*data++, p);
140	}
141	return (p);
142}
143#define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
144
145/*
146 * Perform expansions on an argument, placing the resulting list of arguments
147 * in arglist.  Parameter expansion, command substitution and arithmetic
148 * expansion are always performed; additional expansions can be requested
149 * via flag (EXP_*).
150 * The result is left in the stack string.
151 * When arglist is NULL, perform here document expansion.
152 *
153 * Caution: this function uses global state and is not reentrant.
154 * However, a new invocation after an interrupted invocation is safe
155 * and will reset the global state for the new call.
156 */
157void
158expandarg(union node *arg, struct arglist *arglist, int flag)
159{
160	struct strlist *sp;
161	char *p;
162
163	argbackq = arg->narg.backquote;
164	STARTSTACKSTR(expdest);
165	ifsfirst.next = NULL;
166	ifslastp = NULL;
167	argstr(arg->narg.text, flag);
168	if (arglist == NULL) {
169		STACKSTRNUL(expdest);
170		return;			/* here document expanded */
171	}
172	STPUTC('\0', expdest);
173	p = grabstackstr(expdest);
174	exparg.lastp = &exparg.list;
175	if (flag & EXP_FULL) {
176		ifsbreakup(p, &exparg);
177		*exparg.lastp = NULL;
178		exparg.lastp = &exparg.list;
179		expandmeta(exparg.list);
180	} else {
181		sp = (struct strlist *)stalloc(sizeof (struct strlist));
182		sp->text = p;
183		*exparg.lastp = sp;
184		exparg.lastp = &sp->next;
185	}
186	while (ifsfirst.next != NULL) {
187		struct ifsregion *ifsp;
188		INTOFF;
189		ifsp = ifsfirst.next->next;
190		ckfree(ifsfirst.next);
191		ifsfirst.next = ifsp;
192		INTON;
193	}
194	*exparg.lastp = NULL;
195	if (exparg.list) {
196		*arglist->lastp = exparg.list;
197		arglist->lastp = exparg.lastp;
198	}
199}
200
201
202
203/*
204 * Perform parameter expansion, command substitution and arithmetic
205 * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
206 * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
207 * This is used to expand word in ${var+word} etc.
208 * If EXP_FULL or EXP_CASE are set, keep and/or generate CTLESC
209 * characters to allow for further processing.
210 * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
211 */
212static char *
213argstr(char *p, int flag)
214{
215	char c;
216	int quotes = flag & (EXP_FULL | EXP_CASE);	/* do CTLESC */
217	int firsteq = 1;
218	int split_lit;
219	int lit_quoted;
220
221	split_lit = flag & EXP_SPLIT_LIT;
222	lit_quoted = flag & EXP_LIT_QUOTED;
223	flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
224	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
225		p = exptilde(p, flag);
226	for (;;) {
227		CHECKSTRSPACE(2, expdest);
228		switch (c = *p++) {
229		case '\0':
230			return (p - 1);
231		case CTLENDVAR:
232		case CTLENDARI:
233			return (p);
234		case CTLQUOTEMARK:
235			lit_quoted = 1;
236			/* "$@" syntax adherence hack */
237			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
238				break;
239			if ((flag & EXP_FULL) != 0)
240				USTPUTC(c, expdest);
241			break;
242		case CTLQUOTEEND:
243			lit_quoted = 0;
244			break;
245		case CTLESC:
246			if (quotes)
247				USTPUTC(c, expdest);
248			c = *p++;
249			USTPUTC(c, expdest);
250			if (split_lit && !lit_quoted)
251				recordregion(expdest - stackblock() -
252				    (quotes ? 2 : 1),
253				    expdest - stackblock(), 0);
254			break;
255		case CTLVAR:
256			p = evalvar(p, flag);
257			break;
258		case CTLBACKQ:
259		case CTLBACKQ|CTLQUOTE:
260			expbackq(argbackq->n, c & CTLQUOTE, flag);
261			argbackq = argbackq->next;
262			break;
263		case CTLARI:
264			p = expari(p);
265			break;
266		case ':':
267		case '=':
268			/*
269			 * sort of a hack - expand tildes in variable
270			 * assignments (after the first '=' and after ':'s).
271			 */
272			USTPUTC(c, expdest);
273			if (split_lit && !lit_quoted)
274				recordregion(expdest - stackblock() - 1,
275				    expdest - stackblock(), 0);
276			if (flag & EXP_VARTILDE && *p == '~' &&
277			    (c != '=' || firsteq)) {
278				if (c == '=')
279					firsteq = 0;
280				p = exptilde(p, flag);
281			}
282			break;
283		default:
284			USTPUTC(c, expdest);
285			if (split_lit && !lit_quoted)
286				recordregion(expdest - stackblock() - 1,
287				    expdest - stackblock(), 0);
288		}
289	}
290}
291
292/*
293 * Perform tilde expansion, placing the result in the stack string and
294 * returning the next position in the input string to process.
295 */
296static char *
297exptilde(char *p, int flag)
298{
299	char c, *startp = p;
300	struct passwd *pw;
301	char *home;
302
303	for (;;) {
304		c = *p;
305		switch(c) {
306		case CTLESC: /* This means CTL* are always considered quoted. */
307		case CTLVAR:
308		case CTLBACKQ:
309		case CTLBACKQ | CTLQUOTE:
310		case CTLARI:
311		case CTLENDARI:
312		case CTLQUOTEMARK:
313			return (startp);
314		case ':':
315			if ((flag & EXP_VARTILDE) == 0)
316				break;
317			/* FALLTHROUGH */
318		case '\0':
319		case '/':
320		case CTLENDVAR:
321			*p = '\0';
322			if (*(startp+1) == '\0') {
323				home = lookupvar("HOME");
324			} else {
325				pw = getpwnam(startp+1);
326				home = pw != NULL ? pw->pw_dir : NULL;
327			}
328			*p = c;
329			if (home == NULL || *home == '\0')
330				return (startp);
331			strtodest(home, flag, VSNORMAL, 1);
332			return (p);
333		}
334		p++;
335	}
336}
337
338
339static void
340removerecordregions(int endoff)
341{
342	if (ifslastp == NULL)
343		return;
344
345	if (ifsfirst.endoff > endoff) {
346		while (ifsfirst.next != NULL) {
347			struct ifsregion *ifsp;
348			INTOFF;
349			ifsp = ifsfirst.next->next;
350			ckfree(ifsfirst.next);
351			ifsfirst.next = ifsp;
352			INTON;
353		}
354		if (ifsfirst.begoff > endoff)
355			ifslastp = NULL;
356		else {
357			ifslastp = &ifsfirst;
358			ifsfirst.endoff = endoff;
359		}
360		return;
361	}
362
363	ifslastp = &ifsfirst;
364	while (ifslastp->next && ifslastp->next->begoff < endoff)
365		ifslastp=ifslastp->next;
366	while (ifslastp->next != NULL) {
367		struct ifsregion *ifsp;
368		INTOFF;
369		ifsp = ifslastp->next->next;
370		ckfree(ifslastp->next);
371		ifslastp->next = ifsp;
372		INTON;
373	}
374	if (ifslastp->endoff > endoff)
375		ifslastp->endoff = endoff;
376}
377
378/*
379 * Expand arithmetic expression.
380 * Note that flag is not required as digits never require CTLESC characters.
381 */
382static char *
383expari(char *p)
384{
385	char *q, *start;
386	arith_t result;
387	int begoff;
388	int quoted;
389	int adj;
390
391	quoted = *p++ == '"';
392	begoff = expdest - stackblock();
393	p = argstr(p, 0);
394	removerecordregions(begoff);
395	STPUTC('\0', expdest);
396	start = stackblock() + begoff;
397
398	q = grabstackstr(expdest);
399	result = arith(start);
400	ungrabstackstr(q, expdest);
401
402	start = stackblock() + begoff;
403	adj = start - expdest;
404	STADJUST(adj, expdest);
405
406	CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
407	fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
408	adj = strlen(expdest);
409	STADJUST(adj, expdest);
410	if (!quoted)
411		recordregion(begoff, expdest - stackblock(), 0);
412	return p;
413}
414
415
416/*
417 * Perform command substitution.
418 */
419static void
420expbackq(union node *cmd, int quoted, int flag)
421{
422	struct backcmd in;
423	int i;
424	char buf[128];
425	char *p;
426	char *dest = expdest;
427	struct ifsregion saveifs, *savelastp;
428	struct nodelist *saveargbackq;
429	char lastc;
430	int startloc = dest - stackblock();
431	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
432	int quotes = flag & (EXP_FULL | EXP_CASE);
433	size_t nnl;
434
435	INTOFF;
436	saveifs = ifsfirst;
437	savelastp = ifslastp;
438	saveargbackq = argbackq;
439	p = grabstackstr(dest);
440	evalbackcmd(cmd, &in);
441	ungrabstackstr(p, dest);
442
443	p = in.buf;
444	lastc = '\0';
445	nnl = 0;
446	/* Don't copy trailing newlines */
447	for (;;) {
448		if (--in.nleft < 0) {
449			if (in.fd < 0)
450				break;
451			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
452			TRACE(("expbackq: read returns %d\n", i));
453			if (i <= 0)
454				break;
455			p = buf;
456			in.nleft = i - 1;
457		}
458		lastc = *p++;
459		if (lastc != '\0') {
460			if (lastc == '\n') {
461				nnl++;
462			} else {
463				CHECKSTRSPACE(nnl + 2, dest);
464				while (nnl > 0) {
465					nnl--;
466					USTPUTC('\n', dest);
467				}
468				if (quotes && syntax[(int)lastc] == CCTL)
469					USTPUTC(CTLESC, dest);
470				USTPUTC(lastc, dest);
471			}
472		}
473	}
474
475	if (in.fd >= 0)
476		close(in.fd);
477	if (in.buf)
478		ckfree(in.buf);
479	if (in.jp) {
480		p = grabstackstr(dest);
481		exitstatus = waitforjob(in.jp, (int *)NULL);
482		ungrabstackstr(p, dest);
483	}
484	TRACE(("expbackq: size=%td: \"%.*s\"\n",
485		((dest - stackblock()) - startloc),
486		(int)((dest - stackblock()) - startloc),
487		stackblock() + startloc));
488	ifsfirst = saveifs;
489	ifslastp = savelastp;
490	if (quoted == 0)
491		recordregion(startloc, dest - stackblock(), 0);
492	argbackq = saveargbackq;
493	expdest = dest;
494	INTON;
495}
496
497
498
499static void
500recordleft(const char *str, const char *loc, char *startp)
501{
502	int amount;
503
504	amount = ((str - 1) - (loc - startp)) - expdest;
505	STADJUST(amount, expdest);
506	while (loc != str - 1)
507		*startp++ = *loc++;
508}
509
510static int
511subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
512  int varflags, int quotes)
513{
514	char *startp;
515	char *loc = NULL;
516	char *q;
517	int c = 0;
518	struct nodelist *saveargbackq = argbackq;
519	int amount;
520
521	argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
522	    subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
523	    EXP_CASE : 0) | EXP_TILDE);
524	STACKSTRNUL(expdest);
525	argbackq = saveargbackq;
526	startp = stackblock() + startloc;
527	if (str == NULL)
528	    str = stackblock() + strloc;
529
530	switch (subtype) {
531	case VSASSIGN:
532		setvar(str, startp, 0);
533		amount = startp - expdest;
534		STADJUST(amount, expdest);
535		varflags &= ~VSNUL;
536		return 1;
537
538	case VSQUESTION:
539		if (*p != CTLENDVAR) {
540			outfmt(out2, "%s\n", startp);
541			error((char *)NULL);
542		}
543		error("%.*s: parameter %snot set", (int)(p - str - 1),
544		      str, (varflags & VSNUL) ? "null or "
545					      : nullstr);
546		return 0;
547
548	case VSTRIMLEFT:
549		for (loc = startp; loc < str; loc++) {
550			c = *loc;
551			*loc = '\0';
552			if (patmatch(str, startp, quotes)) {
553				*loc = c;
554				recordleft(str, loc, startp);
555				return 1;
556			}
557			*loc = c;
558			if (quotes && *loc == CTLESC)
559				loc++;
560		}
561		return 0;
562
563	case VSTRIMLEFTMAX:
564		for (loc = str - 1; loc >= startp;) {
565			c = *loc;
566			*loc = '\0';
567			if (patmatch(str, startp, quotes)) {
568				*loc = c;
569				recordleft(str, loc, startp);
570				return 1;
571			}
572			*loc = c;
573			loc--;
574			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
575				for (q = startp; q < loc; q++)
576					if (*q == CTLESC)
577						q++;
578				if (q > loc)
579					loc--;
580			}
581		}
582		return 0;
583
584	case VSTRIMRIGHT:
585		for (loc = str - 1; loc >= startp;) {
586			if (patmatch(str, loc, quotes)) {
587				amount = loc - expdest;
588				STADJUST(amount, expdest);
589				return 1;
590			}
591			loc--;
592			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
593				for (q = startp; q < loc; q++)
594					if (*q == CTLESC)
595						q++;
596				if (q > loc)
597					loc--;
598			}
599		}
600		return 0;
601
602	case VSTRIMRIGHTMAX:
603		for (loc = startp; loc < str - 1; loc++) {
604			if (patmatch(str, loc, quotes)) {
605				amount = loc - expdest;
606				STADJUST(amount, expdest);
607				return 1;
608			}
609			if (quotes && *loc == CTLESC)
610				loc++;
611		}
612		return 0;
613
614
615	default:
616		abort();
617	}
618}
619
620
621/*
622 * Expand a variable, and return a pointer to the next character in the
623 * input string.
624 */
625
626static char *
627evalvar(char *p, int flag)
628{
629	int subtype;
630	int varflags;
631	char *var;
632	const char *val;
633	int patloc;
634	int c;
635	int set;
636	int special;
637	int startloc;
638	int varlen;
639	int varlenb;
640	int easy;
641	int quotes = flag & (EXP_FULL | EXP_CASE);
642	int record = 0;
643
644	varflags = (unsigned char)*p++;
645	subtype = varflags & VSTYPE;
646	var = p;
647	special = 0;
648	if (! is_name(*p))
649		special = 1;
650	p = strchr(p, '=') + 1;
651again: /* jump here after setting a variable with ${var=text} */
652	if (varflags & VSLINENO) {
653		set = 1;
654		special = 1;
655		val = NULL;
656	} else if (special) {
657		set = varisset(var, varflags & VSNUL);
658		val = NULL;
659	} else {
660		val = bltinlookup(var, 1);
661		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
662			val = NULL;
663			set = 0;
664		} else
665			set = 1;
666	}
667	varlen = 0;
668	startloc = expdest - stackblock();
669	if (!set && uflag && *var != '@' && *var != '*') {
670		switch (subtype) {
671		case VSNORMAL:
672		case VSTRIMLEFT:
673		case VSTRIMLEFTMAX:
674		case VSTRIMRIGHT:
675		case VSTRIMRIGHTMAX:
676		case VSLENGTH:
677			error("%.*s: parameter not set", (int)(p - var - 1),
678			    var);
679		}
680	}
681	if (set && subtype != VSPLUS) {
682		/* insert the value of the variable */
683		if (special) {
684			if (varflags & VSLINENO)
685				STPUTBIN(var, p - var - 1, expdest);
686			else
687				varvalue(var, varflags & VSQUOTE, subtype, flag);
688			if (subtype == VSLENGTH) {
689				varlenb = expdest - stackblock() - startloc;
690				varlen = varlenb;
691				if (localeisutf8) {
692					val = stackblock() + startloc;
693					for (;val != expdest; val++)
694						if ((*val & 0xC0) == 0x80)
695							varlen--;
696				}
697				STADJUST(-varlenb, expdest);
698			}
699		} else {
700			if (subtype == VSLENGTH) {
701				for (;*val; val++)
702					if (!localeisutf8 ||
703					    (*val & 0xC0) != 0x80)
704						varlen++;
705			}
706			else
707				strtodest(val, flag, subtype,
708				    varflags & VSQUOTE);
709		}
710	}
711
712	if (subtype == VSPLUS)
713		set = ! set;
714
715	easy = ((varflags & VSQUOTE) == 0 ||
716		(*var == '@' && shellparam.nparam != 1));
717
718
719	switch (subtype) {
720	case VSLENGTH:
721		expdest = cvtnum(varlen, expdest);
722		record = 1;
723		break;
724
725	case VSNORMAL:
726		record = easy;
727		break;
728
729	case VSPLUS:
730	case VSMINUS:
731		if (!set) {
732			argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
733			    (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
734			break;
735		}
736		record = easy;
737		break;
738
739	case VSTRIMLEFT:
740	case VSTRIMLEFTMAX:
741	case VSTRIMRIGHT:
742	case VSTRIMRIGHTMAX:
743		if (!set)
744			break;
745		/*
746		 * Terminate the string and start recording the pattern
747		 * right after it
748		 */
749		STPUTC('\0', expdest);
750		patloc = expdest - stackblock();
751		if (subevalvar(p, NULL, patloc, subtype,
752		    startloc, varflags, quotes) == 0) {
753			int amount = (expdest - stackblock() - patloc) + 1;
754			STADJUST(-amount, expdest);
755		}
756		/* Remove any recorded regions beyond start of variable */
757		removerecordregions(startloc);
758		record = 1;
759		break;
760
761	case VSASSIGN:
762	case VSQUESTION:
763		if (!set) {
764			if (subevalvar(p, var, 0, subtype, startloc, varflags,
765			    quotes)) {
766				varflags &= ~VSNUL;
767				/*
768				 * Remove any recorded regions beyond
769				 * start of variable
770				 */
771				removerecordregions(startloc);
772				goto again;
773			}
774			break;
775		}
776		record = easy;
777		break;
778
779	case VSERROR:
780		c = p - var - 1;
781		error("${%.*s%s}: Bad substitution", c, var,
782		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
783
784	default:
785		abort();
786	}
787
788	if (record)
789		recordregion(startloc, expdest - stackblock(),
790		    varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
791		    (*var == '@' || *var == '*')));
792
793	if (subtype != VSNORMAL) {	/* skip to end of alternative */
794		int nesting = 1;
795		for (;;) {
796			if ((c = *p++) == CTLESC)
797				p++;
798			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
799				if (set)
800					argbackq = argbackq->next;
801			} else if (c == CTLVAR) {
802				if ((*p++ & VSTYPE) != VSNORMAL)
803					nesting++;
804			} else if (c == CTLENDVAR) {
805				if (--nesting == 0)
806					break;
807			}
808		}
809	}
810	return p;
811}
812
813
814
815/*
816 * Test whether a specialized variable is set.
817 */
818
819static int
820varisset(const char *name, int nulok)
821{
822
823	if (*name == '!')
824		return backgndpidset();
825	else if (*name == '@' || *name == '*') {
826		if (*shellparam.p == NULL)
827			return 0;
828
829		if (nulok) {
830			char **av;
831
832			for (av = shellparam.p; *av; av++)
833				if (**av != '\0')
834					return 1;
835			return 0;
836		}
837	} else if (is_digit(*name)) {
838		char *ap;
839		long num;
840
841		errno = 0;
842		num = strtol(name, NULL, 10);
843		if (errno != 0 || num > shellparam.nparam)
844			return 0;
845
846		if (num == 0)
847			ap = arg0;
848		else
849			ap = shellparam.p[num - 1];
850
851		if (nulok && (ap == NULL || *ap == '\0'))
852			return 0;
853	}
854	return 1;
855}
856
857static void
858strtodest(const char *p, int flag, int subtype, int quoted)
859{
860	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
861		STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
862	else
863		STPUTS(p, expdest);
864}
865
866/*
867 * Add the value of a specialized variable to the stack string.
868 */
869
870static void
871varvalue(const char *name, int quoted, int subtype, int flag)
872{
873	int num;
874	char *p;
875	int i;
876	char sep;
877	char **ap;
878
879	switch (*name) {
880	case '$':
881		num = rootpid;
882		goto numvar;
883	case '?':
884		num = oexitstatus;
885		goto numvar;
886	case '#':
887		num = shellparam.nparam;
888		goto numvar;
889	case '!':
890		num = backgndpidval();
891numvar:
892		expdest = cvtnum(num, expdest);
893		break;
894	case '-':
895		for (i = 0 ; i < NOPTS ; i++) {
896			if (optlist[i].val)
897				STPUTC(optlist[i].letter, expdest);
898		}
899		break;
900	case '@':
901		if (flag & EXP_FULL && quoted) {
902			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
903				strtodest(p, flag, subtype, quoted);
904				if (*ap)
905					STPUTC('\0', expdest);
906			}
907			break;
908		}
909		/* FALLTHROUGH */
910	case '*':
911		if (ifsset())
912			sep = ifsval()[0];
913		else
914			sep = ' ';
915		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
916			strtodest(p, flag, subtype, quoted);
917			if (!*ap)
918				break;
919			if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
920				STPUTC(sep, expdest);
921		}
922		break;
923	case '0':
924		p = arg0;
925		strtodest(p, flag, subtype, quoted);
926		break;
927	default:
928		if (is_digit(*name)) {
929			num = atoi(name);
930			if (num > 0 && num <= shellparam.nparam) {
931				p = shellparam.p[num - 1];
932				strtodest(p, flag, subtype, quoted);
933			}
934		}
935		break;
936	}
937}
938
939
940
941/*
942 * Record the fact that we have to scan this region of the
943 * string for IFS characters.
944 */
945
946static void
947recordregion(int start, int end, int inquotes)
948{
949	struct ifsregion *ifsp;
950
951	INTOFF;
952	if (ifslastp == NULL) {
953		ifsp = &ifsfirst;
954	} else {
955		if (ifslastp->endoff == start
956		    && ifslastp->inquotes == inquotes) {
957			/* extend previous area */
958			ifslastp->endoff = end;
959			INTON;
960			return;
961		}
962		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
963		ifslastp->next = ifsp;
964	}
965	ifslastp = ifsp;
966	ifslastp->next = NULL;
967	ifslastp->begoff = start;
968	ifslastp->endoff = end;
969	ifslastp->inquotes = inquotes;
970	INTON;
971}
972
973
974
975/*
976 * Break the argument string into pieces based upon IFS and add the
977 * strings to the argument list.  The regions of the string to be
978 * searched for IFS characters have been stored by recordregion.
979 * CTLESC characters are preserved but have little effect in this pass
980 * other than escaping CTL* characters.  In particular, they do not escape
981 * IFS characters: that should be done with the ifsregion mechanism.
982 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
983 * This pass treats them as a regular character, making the string non-empty.
984 * Later, they are removed along with the other CTL* characters.
985 */
986static void
987ifsbreakup(char *string, struct arglist *arglist)
988{
989	struct ifsregion *ifsp;
990	struct strlist *sp;
991	char *start;
992	char *p;
993	char *q;
994	const char *ifs;
995	const char *ifsspc;
996	int had_param_ch = 0;
997
998	start = string;
999
1000	if (ifslastp == NULL) {
1001		/* Return entire argument, IFS doesn't apply to any of it */
1002		sp = (struct strlist *)stalloc(sizeof *sp);
1003		sp->text = start;
1004		*arglist->lastp = sp;
1005		arglist->lastp = &sp->next;
1006		return;
1007	}
1008
1009	ifs = ifsset() ? ifsval() : " \t\n";
1010
1011	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1012		p = string + ifsp->begoff;
1013		while (p < string + ifsp->endoff) {
1014			q = p;
1015			if (*p == CTLESC)
1016				p++;
1017			if (ifsp->inquotes) {
1018				/* Only NULs (should be from "$@") end args */
1019				had_param_ch = 1;
1020				if (*p != 0) {
1021					p++;
1022					continue;
1023				}
1024				ifsspc = NULL;
1025			} else {
1026				if (!strchr(ifs, *p)) {
1027					had_param_ch = 1;
1028					p++;
1029					continue;
1030				}
1031				ifsspc = strchr(" \t\n", *p);
1032
1033				/* Ignore IFS whitespace at start */
1034				if (q == start && ifsspc != NULL) {
1035					p++;
1036					start = p;
1037					continue;
1038				}
1039				had_param_ch = 0;
1040			}
1041
1042			/* Save this argument... */
1043			*q = '\0';
1044			sp = (struct strlist *)stalloc(sizeof *sp);
1045			sp->text = start;
1046			*arglist->lastp = sp;
1047			arglist->lastp = &sp->next;
1048			p++;
1049
1050			if (ifsspc != NULL) {
1051				/* Ignore further trailing IFS whitespace */
1052				for (; p < string + ifsp->endoff; p++) {
1053					q = p;
1054					if (*p == CTLESC)
1055						p++;
1056					if (strchr(ifs, *p) == NULL) {
1057						p = q;
1058						break;
1059					}
1060					if (strchr(" \t\n", *p) == NULL) {
1061						p++;
1062						break;
1063					}
1064				}
1065			}
1066			start = p;
1067		}
1068	}
1069
1070	/*
1071	 * Save anything left as an argument.
1072	 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1073	 * generating 2 arguments, the second of which is empty.
1074	 * Some recent clarification of the Posix spec say that it
1075	 * should only generate one....
1076	 */
1077	if (had_param_ch || *start != 0) {
1078		sp = (struct strlist *)stalloc(sizeof *sp);
1079		sp->text = start;
1080		*arglist->lastp = sp;
1081		arglist->lastp = &sp->next;
1082	}
1083}
1084
1085
1086static char expdir[PATH_MAX];
1087#define expdir_end (expdir + sizeof(expdir))
1088
1089/*
1090 * Perform pathname generation and remove control characters.
1091 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1092 * The results are stored in the list exparg.
1093 */
1094static void
1095expandmeta(struct strlist *str)
1096{
1097	char *p;
1098	struct strlist **savelastp;
1099	struct strlist *sp;
1100	char c;
1101
1102	while (str) {
1103		if (fflag)
1104			goto nometa;
1105		p = str->text;
1106		for (;;) {			/* fast check for meta chars */
1107			if ((c = *p++) == '\0')
1108				goto nometa;
1109			if (c == '*' || c == '?' || c == '[')
1110				break;
1111		}
1112		savelastp = exparg.lastp;
1113		INTOFF;
1114		expmeta(expdir, str->text);
1115		INTON;
1116		if (exparg.lastp == savelastp) {
1117			/*
1118			 * no matches
1119			 */
1120nometa:
1121			*exparg.lastp = str;
1122			rmescapes(str->text);
1123			exparg.lastp = &str->next;
1124		} else {
1125			*exparg.lastp = NULL;
1126			*savelastp = sp = expsort(*savelastp);
1127			while (sp->next != NULL)
1128				sp = sp->next;
1129			exparg.lastp = &sp->next;
1130		}
1131		str = str->next;
1132	}
1133}
1134
1135
1136/*
1137 * Do metacharacter (i.e. *, ?, [...]) expansion.
1138 */
1139
1140static void
1141expmeta(char *enddir, char *name)
1142{
1143	const char *p;
1144	const char *q;
1145	const char *start;
1146	char *endname;
1147	int metaflag;
1148	struct stat statb;
1149	DIR *dirp;
1150	struct dirent *dp;
1151	int atend;
1152	int matchdot;
1153	int esc;
1154	int namlen;
1155
1156	metaflag = 0;
1157	start = name;
1158	for (p = name; esc = 0, *p; p += esc + 1) {
1159		if (*p == '*' || *p == '?')
1160			metaflag = 1;
1161		else if (*p == '[') {
1162			q = p + 1;
1163			if (*q == '!' || *q == '^')
1164				q++;
1165			for (;;) {
1166				while (*q == CTLQUOTEMARK)
1167					q++;
1168				if (*q == CTLESC)
1169					q++;
1170				if (*q == '/' || *q == '\0')
1171					break;
1172				if (*++q == ']') {
1173					metaflag = 1;
1174					break;
1175				}
1176			}
1177		} else if (*p == '\0')
1178			break;
1179		else if (*p == CTLQUOTEMARK)
1180			continue;
1181		else {
1182			if (*p == CTLESC)
1183				esc++;
1184			if (p[esc] == '/') {
1185				if (metaflag)
1186					break;
1187				start = p + esc + 1;
1188			}
1189		}
1190	}
1191	if (metaflag == 0) {	/* we've reached the end of the file name */
1192		if (enddir != expdir)
1193			metaflag++;
1194		for (p = name ; ; p++) {
1195			if (*p == CTLQUOTEMARK)
1196				continue;
1197			if (*p == CTLESC)
1198				p++;
1199			*enddir++ = *p;
1200			if (*p == '\0')
1201				break;
1202			if (enddir == expdir_end)
1203				return;
1204		}
1205		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1206			addfname(expdir);
1207		return;
1208	}
1209	endname = name + (p - name);
1210	if (start != name) {
1211		p = name;
1212		while (p < start) {
1213			while (*p == CTLQUOTEMARK)
1214				p++;
1215			if (*p == CTLESC)
1216				p++;
1217			*enddir++ = *p++;
1218			if (enddir == expdir_end)
1219				return;
1220		}
1221	}
1222	if (enddir == expdir) {
1223		p = ".";
1224	} else if (enddir == expdir + 1 && *expdir == '/') {
1225		p = "/";
1226	} else {
1227		p = expdir;
1228		enddir[-1] = '\0';
1229	}
1230	if ((dirp = opendir(p)) == NULL)
1231		return;
1232	if (enddir != expdir)
1233		enddir[-1] = '/';
1234	if (*endname == 0) {
1235		atend = 1;
1236	} else {
1237		atend = 0;
1238		*endname = '\0';
1239		endname += esc + 1;
1240	}
1241	matchdot = 0;
1242	p = start;
1243	while (*p == CTLQUOTEMARK)
1244		p++;
1245	if (*p == CTLESC)
1246		p++;
1247	if (*p == '.')
1248		matchdot++;
1249	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1250		if (dp->d_name[0] == '.' && ! matchdot)
1251			continue;
1252		if (patmatch(start, dp->d_name, 0)) {
1253			namlen = dp->d_namlen;
1254			if (enddir + namlen + 1 > expdir_end)
1255				continue;
1256			memcpy(enddir, dp->d_name, namlen + 1);
1257			if (atend)
1258				addfname(expdir);
1259			else {
1260				if (dp->d_type != DT_UNKNOWN &&
1261				    dp->d_type != DT_DIR &&
1262				    dp->d_type != DT_LNK)
1263					continue;
1264				if (enddir + namlen + 2 > expdir_end)
1265					continue;
1266				enddir[namlen] = '/';
1267				enddir[namlen + 1] = '\0';
1268				expmeta(enddir + namlen + 1, endname);
1269			}
1270		}
1271	}
1272	closedir(dirp);
1273	if (! atend)
1274		endname[-esc - 1] = esc ? CTLESC : '/';
1275}
1276
1277
1278/*
1279 * Add a file name to the list.
1280 */
1281
1282static void
1283addfname(char *name)
1284{
1285	char *p;
1286	struct strlist *sp;
1287
1288	p = stsavestr(name);
1289	sp = (struct strlist *)stalloc(sizeof *sp);
1290	sp->text = p;
1291	*exparg.lastp = sp;
1292	exparg.lastp = &sp->next;
1293}
1294
1295
1296/*
1297 * Sort the results of file name expansion.  It calculates the number of
1298 * strings to sort and then calls msort (short for merge sort) to do the
1299 * work.
1300 */
1301
1302static struct strlist *
1303expsort(struct strlist *str)
1304{
1305	int len;
1306	struct strlist *sp;
1307
1308	len = 0;
1309	for (sp = str ; sp ; sp = sp->next)
1310		len++;
1311	return msort(str, len);
1312}
1313
1314
1315static struct strlist *
1316msort(struct strlist *list, int len)
1317{
1318	struct strlist *p, *q = NULL;
1319	struct strlist **lpp;
1320	int half;
1321	int n;
1322
1323	if (len <= 1)
1324		return list;
1325	half = len >> 1;
1326	p = list;
1327	for (n = half ; --n >= 0 ; ) {
1328		q = p;
1329		p = p->next;
1330	}
1331	q->next = NULL;			/* terminate first half of list */
1332	q = msort(list, half);		/* sort first half of list */
1333	p = msort(p, len - half);		/* sort second half */
1334	lpp = &list;
1335	for (;;) {
1336		if (strcmp(p->text, q->text) < 0) {
1337			*lpp = p;
1338			lpp = &p->next;
1339			if ((p = *lpp) == NULL) {
1340				*lpp = q;
1341				break;
1342			}
1343		} else {
1344			*lpp = q;
1345			lpp = &q->next;
1346			if ((q = *lpp) == NULL) {
1347				*lpp = p;
1348				break;
1349			}
1350		}
1351	}
1352	return list;
1353}
1354
1355
1356
1357static wchar_t
1358get_wc(const char **p)
1359{
1360	wchar_t c;
1361	int chrlen;
1362
1363	chrlen = mbtowc(&c, *p, 4);
1364	if (chrlen == 0)
1365		return 0;
1366	else if (chrlen == -1)
1367		c = 0;
1368	else
1369		*p += chrlen;
1370	return c;
1371}
1372
1373
1374/*
1375 * See if a character matches a character class, starting at the first colon
1376 * of "[:class:]".
1377 * If a valid character class is recognized, a pointer to the next character
1378 * after the final closing bracket is stored into *end, otherwise a null
1379 * pointer is stored into *end.
1380 */
1381static int
1382match_charclass(const char *p, wchar_t chr, const char **end)
1383{
1384	char name[20];
1385	const char *nameend;
1386	wctype_t cclass;
1387
1388	*end = NULL;
1389	p++;
1390	nameend = strstr(p, ":]");
1391	if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
1392	    nameend == p)
1393		return 0;
1394	memcpy(name, p, nameend - p);
1395	name[nameend - p] = '\0';
1396	*end = nameend + 2;
1397	cclass = wctype(name);
1398	/* An unknown class matches nothing but is valid nevertheless. */
1399	if (cclass == 0)
1400		return 0;
1401	return iswctype(chr, cclass);
1402}
1403
1404
1405/*
1406 * Returns true if the pattern matches the string.
1407 */
1408
1409static int
1410patmatch(const char *pattern, const char *string, int squoted)
1411{
1412	const char *p, *q, *end;
1413	const char *bt_p, *bt_q;
1414	char c;
1415	wchar_t wc, wc2;
1416
1417	p = pattern;
1418	q = string;
1419	bt_p = NULL;
1420	bt_q = NULL;
1421	for (;;) {
1422		switch (c = *p++) {
1423		case '\0':
1424			if (*q != '\0')
1425				goto backtrack;
1426			return 1;
1427		case CTLESC:
1428			if (squoted && *q == CTLESC)
1429				q++;
1430			if (*q++ != *p++)
1431				goto backtrack;
1432			break;
1433		case CTLQUOTEMARK:
1434			continue;
1435		case '?':
1436			if (squoted && *q == CTLESC)
1437				q++;
1438			if (*q == '\0')
1439				return 0;
1440			if (localeisutf8) {
1441				wc = get_wc(&q);
1442				/*
1443				 * A '?' does not match invalid UTF-8 but a
1444				 * '*' does, so backtrack.
1445				 */
1446				if (wc == 0)
1447					goto backtrack;
1448			} else
1449				wc = (unsigned char)*q++;
1450			break;
1451		case '*':
1452			c = *p;
1453			while (c == CTLQUOTEMARK || c == '*')
1454				c = *++p;
1455			/*
1456			 * If the pattern ends here, we know the string
1457			 * matches without needing to look at the rest of it.
1458			 */
1459			if (c == '\0')
1460				return 1;
1461			/*
1462			 * First try the shortest match for the '*' that
1463			 * could work. We can forget any earlier '*' since
1464			 * there is no way having it match more characters
1465			 * can help us, given that we are already here.
1466			 */
1467			bt_p = p;
1468			bt_q = q;
1469			break;
1470		case '[': {
1471			const char *savep, *saveq;
1472			int invert, found;
1473			wchar_t chr;
1474
1475			savep = p, saveq = q;
1476			invert = 0;
1477			if (*p == '!' || *p == '^') {
1478				invert++;
1479				p++;
1480			}
1481			found = 0;
1482			if (squoted && *q == CTLESC)
1483				q++;
1484			if (*q == '\0')
1485				return 0;
1486			if (localeisutf8) {
1487				chr = get_wc(&q);
1488				if (chr == 0)
1489					goto backtrack;
1490			} else
1491				chr = (unsigned char)*q++;
1492			c = *p++;
1493			do {
1494				if (c == '\0') {
1495					p = savep, q = saveq;
1496					c = '[';
1497					goto dft;
1498				}
1499				if (c == CTLQUOTEMARK)
1500					continue;
1501				if (c == '[' && *p == ':') {
1502					found |= match_charclass(p, chr, &end);
1503					if (end != NULL)
1504						p = end;
1505				}
1506				if (c == CTLESC)
1507					c = *p++;
1508				if (localeisutf8 && c & 0x80) {
1509					p--;
1510					wc = get_wc(&p);
1511					if (wc == 0) /* bad utf-8 */
1512						return 0;
1513				} else
1514					wc = (unsigned char)c;
1515				if (*p == '-' && p[1] != ']') {
1516					p++;
1517					while (*p == CTLQUOTEMARK)
1518						p++;
1519					if (*p == CTLESC)
1520						p++;
1521					if (localeisutf8) {
1522						wc2 = get_wc(&p);
1523						if (wc2 == 0) /* bad utf-8 */
1524							return 0;
1525					} else
1526						wc2 = (unsigned char)*p++;
1527					if (   collate_range_cmp(chr, wc) >= 0
1528					    && collate_range_cmp(chr, wc2) <= 0
1529					   )
1530						found = 1;
1531				} else {
1532					if (chr == wc)
1533						found = 1;
1534				}
1535			} while ((c = *p++) != ']');
1536			if (found == invert)
1537				goto backtrack;
1538			break;
1539		}
1540dft:	        default:
1541			if (squoted && *q == CTLESC)
1542				q++;
1543			if (*q == '\0')
1544				return 0;
1545			if (*q++ == c)
1546				break;
1547backtrack:
1548			/*
1549			 * If we have a mismatch (other than hitting the end
1550			 * of the string), go back to the last '*' seen and
1551			 * have it match one additional character.
1552			 */
1553			if (bt_p == NULL)
1554				return 0;
1555			if (squoted && *bt_q == CTLESC)
1556				bt_q++;
1557			if (*bt_q == '\0')
1558				return 0;
1559			bt_q++;
1560			p = bt_p;
1561			q = bt_q;
1562			break;
1563		}
1564	}
1565}
1566
1567
1568
1569/*
1570 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1571 */
1572
1573void
1574rmescapes(char *str)
1575{
1576	char *p, *q;
1577
1578	p = str;
1579	while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1580		if (*p++ == '\0')
1581			return;
1582	}
1583	q = p;
1584	while (*p) {
1585		if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1586			p++;
1587			continue;
1588		}
1589		if (*p == CTLESC)
1590			p++;
1591		*q++ = *p++;
1592	}
1593	*q = '\0';
1594}
1595
1596
1597
1598/*
1599 * See if a pattern matches in a case statement.
1600 */
1601
1602int
1603casematch(union node *pattern, const char *val)
1604{
1605	struct stackmark smark;
1606	int result;
1607	char *p;
1608
1609	setstackmark(&smark);
1610	argbackq = pattern->narg.backquote;
1611	STARTSTACKSTR(expdest);
1612	ifslastp = NULL;
1613	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1614	STPUTC('\0', expdest);
1615	p = grabstackstr(expdest);
1616	result = patmatch(p, val, 0);
1617	popstackmark(&smark);
1618	return result;
1619}
1620
1621/*
1622 * Our own itoa().
1623 */
1624
1625static char *
1626cvtnum(int num, char *buf)
1627{
1628	char temp[32];
1629	int neg = num < 0;
1630	char *p = temp + 31;
1631
1632	temp[31] = '\0';
1633
1634	do {
1635		*--p = num % 10 + '0';
1636	} while ((num /= 10) != 0);
1637
1638	if (neg)
1639		*--p = '-';
1640
1641	STPUTS(p, buf);
1642	return buf;
1643}
1644
1645/*
1646 * Do most of the work for wordexp(3).
1647 */
1648
1649int
1650wordexpcmd(int argc, char **argv)
1651{
1652	size_t len;
1653	int i;
1654
1655	out1fmt("%08x", argc - 1);
1656	for (i = 1, len = 0; i < argc; i++)
1657		len += strlen(argv[i]);
1658	out1fmt("%08x", (int)len);
1659	for (i = 1; i < argc; i++)
1660		outbin(argv[i], strlen(argv[i]) + 1, out1);
1661        return (0);
1662}
1663
1664/*
1665 * Do most of the work for wordexp(3), new version.
1666 */
1667
1668int
1669freebsd_wordexpcmd(int argc __unused, char **argv __unused)
1670{
1671	struct arglist arglist;
1672	union node *args, *n;
1673	struct strlist *sp;
1674	size_t count, len;
1675	int ch;
1676	int protected = 0;
1677	int fd = -1;
1678
1679	while ((ch = nextopt("f:p")) != '\0') {
1680		switch (ch) {
1681		case 'f':
1682			fd = number(shoptarg);
1683			break;
1684		case 'p':
1685			protected = 1;
1686			break;
1687		}
1688	}
1689	if (*argptr != NULL)
1690		error("wrong number of arguments");
1691	if (fd < 0)
1692		error("missing fd");
1693	INTOFF;
1694	setinputfd(fd, 1);
1695	INTON;
1696	args = parsewordexp();
1697	popfile(); /* will also close fd */
1698	if (protected)
1699		for (n = args; n != NULL; n = n->narg.next) {
1700			if (n->narg.backquote != NULL) {
1701				outcslow('C', out1);
1702				error("command substitution disabled");
1703			}
1704		}
1705	outcslow(' ', out1);
1706	arglist.lastp = &arglist.list;
1707	for (n = args; n != NULL; n = n->narg.next)
1708		expandarg(n, &arglist, EXP_FULL | EXP_TILDE);
1709	*arglist.lastp = NULL;
1710	for (sp = arglist.list, count = len = 0; sp; sp = sp->next)
1711		count++, len += strlen(sp->text);
1712	out1fmt("%016zx %016zx", count, len);
1713	for (sp = arglist.list; sp; sp = sp->next)
1714		outbin(sp->text, strlen(sp->text) + 1, out1);
1715	return (0);
1716}
1717