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