parser.c revision 179022
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 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)parser.c	8.7 (Berkeley) 5/16/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/sh/parser.c 179022 2008-05-15 19:55:27Z stefanf $");
40
41#include <stdlib.h>
42#include <unistd.h>
43
44#include "shell.h"
45#include "parser.h"
46#include "nodes.h"
47#include "expand.h"	/* defines rmescapes() */
48#include "syntax.h"
49#include "options.h"
50#include "input.h"
51#include "output.h"
52#include "var.h"
53#include "error.h"
54#include "memalloc.h"
55#include "mystring.h"
56#include "alias.h"
57#include "show.h"
58#include "eval.h"
59#ifndef NO_HISTORY
60#include "myhistedit.h"
61#endif
62
63/*
64 * Shell command parser.
65 */
66
67#define	EOFMARKLEN	79
68#define	PROMPTLEN	128
69
70/* values returned by readtoken */
71#include "token.h"
72
73
74
75struct heredoc {
76	struct heredoc *next;	/* next here document in list */
77	union node *here;		/* redirection node */
78	char *eofmark;		/* string indicating end of input */
79	int striptabs;		/* if set, strip leading tabs */
80};
81
82
83
84STATIC struct heredoc *heredoclist;	/* list of here documents to read */
85STATIC int parsebackquote;	/* nonzero if we are inside backquotes */
86STATIC int doprompt;		/* if set, prompt the user */
87STATIC int needprompt;		/* true if interactive and at start of line */
88STATIC int lasttoken;		/* last token read */
89MKINIT int tokpushback;		/* last token pushed back */
90STATIC char *wordtext;		/* text of last word returned by readtoken */
91MKINIT int checkkwd;            /* 1 == check for kwds, 2 == also eat newlines */
92STATIC struct nodelist *backquotelist;
93STATIC union node *redirnode;
94STATIC struct heredoc *heredoc;
95STATIC int quoteflag;		/* set if (part of) last token was quoted */
96STATIC int startlinno;		/* line # where last token started */
97STATIC int funclinno;		/* line # where the current function started */
98
99/* XXX When 'noaliases' is set to one, no alias expansion takes place. */
100static int noaliases = 0;
101
102
103STATIC union node *list(int);
104STATIC union node *andor(void);
105STATIC union node *pipeline(void);
106STATIC union node *command(void);
107STATIC union node *simplecmd(union node **, union node *);
108STATIC union node *makename(void);
109STATIC void parsefname(void);
110STATIC void parseheredoc(void);
111STATIC int peektoken(void);
112STATIC int readtoken(void);
113STATIC int xxreadtoken(void);
114STATIC int readtoken1(int, char const *, char *, int);
115STATIC int noexpand(char *);
116STATIC void synexpect(int);
117STATIC void synerror(char *);
118STATIC void setprompt(int);
119
120
121/*
122 * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
123 * valid parse tree indicating a blank line.)
124 */
125
126union node *
127parsecmd(int interact)
128{
129	int t;
130
131	tokpushback = 0;
132	doprompt = interact;
133	if (doprompt)
134		setprompt(1);
135	else
136		setprompt(0);
137	needprompt = 0;
138	t = readtoken();
139	if (t == TEOF)
140		return NEOF;
141	if (t == TNL)
142		return NULL;
143	tokpushback++;
144	return list(1);
145}
146
147
148STATIC union node *
149list(int nlflag)
150{
151	union node *n1, *n2, *n3;
152	int tok;
153
154	checkkwd = 2;
155	if (nlflag == 0 && tokendlist[peektoken()])
156		return NULL;
157	n1 = NULL;
158	for (;;) {
159		n2 = andor();
160		tok = readtoken();
161		if (tok == TBACKGND) {
162			if (n2->type == NCMD || n2->type == NPIPE) {
163				n2->ncmd.backgnd = 1;
164			} else if (n2->type == NREDIR) {
165				n2->type = NBACKGND;
166			} else {
167				n3 = (union node *)stalloc(sizeof (struct nredir));
168				n3->type = NBACKGND;
169				n3->nredir.n = n2;
170				n3->nredir.redirect = NULL;
171				n2 = n3;
172			}
173		}
174		if (n1 == NULL) {
175			n1 = n2;
176		}
177		else {
178			n3 = (union node *)stalloc(sizeof (struct nbinary));
179			n3->type = NSEMI;
180			n3->nbinary.ch1 = n1;
181			n3->nbinary.ch2 = n2;
182			n1 = n3;
183		}
184		switch (tok) {
185		case TBACKGND:
186		case TSEMI:
187			tok = readtoken();
188			/* FALLTHROUGH */
189		case TNL:
190			if (tok == TNL) {
191				parseheredoc();
192				if (nlflag)
193					return n1;
194			} else {
195				tokpushback++;
196			}
197			checkkwd = 2;
198			if (tokendlist[peektoken()])
199				return n1;
200			break;
201		case TEOF:
202			if (heredoclist)
203				parseheredoc();
204			else
205				pungetc();		/* push back EOF on input */
206			return n1;
207		default:
208			if (nlflag)
209				synexpect(-1);
210			tokpushback++;
211			return n1;
212		}
213	}
214}
215
216
217
218STATIC union node *
219andor(void)
220{
221	union node *n1, *n2, *n3;
222	int t;
223
224	n1 = pipeline();
225	for (;;) {
226		if ((t = readtoken()) == TAND) {
227			t = NAND;
228		} else if (t == TOR) {
229			t = NOR;
230		} else {
231			tokpushback++;
232			return n1;
233		}
234		n2 = pipeline();
235		n3 = (union node *)stalloc(sizeof (struct nbinary));
236		n3->type = t;
237		n3->nbinary.ch1 = n1;
238		n3->nbinary.ch2 = n2;
239		n1 = n3;
240	}
241}
242
243
244
245STATIC union node *
246pipeline(void)
247{
248	union node *n1, *n2, *pipenode;
249	struct nodelist *lp, *prev;
250	int negate;
251
252	negate = 0;
253	TRACE(("pipeline: entered\n"));
254	while (readtoken() == TNOT)
255		negate = !negate;
256	tokpushback++;
257	n1 = command();
258	if (readtoken() == TPIPE) {
259		pipenode = (union node *)stalloc(sizeof (struct npipe));
260		pipenode->type = NPIPE;
261		pipenode->npipe.backgnd = 0;
262		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
263		pipenode->npipe.cmdlist = lp;
264		lp->n = n1;
265		do {
266			prev = lp;
267			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
268			lp->n = command();
269			prev->next = lp;
270		} while (readtoken() == TPIPE);
271		lp->next = NULL;
272		n1 = pipenode;
273	}
274	tokpushback++;
275	if (negate) {
276		n2 = (union node *)stalloc(sizeof (struct nnot));
277		n2->type = NNOT;
278		n2->nnot.com = n1;
279		return n2;
280	} else
281		return n1;
282}
283
284
285
286STATIC union node *
287command(void)
288{
289	union node *n1, *n2;
290	union node *ap, **app;
291	union node *cp, **cpp;
292	union node *redir, **rpp;
293	int t, negate = 0;
294
295	checkkwd = 2;
296	redir = NULL;
297	n1 = NULL;
298	rpp = &redir;
299
300	/* Check for redirection which may precede command */
301	while (readtoken() == TREDIR) {
302		*rpp = n2 = redirnode;
303		rpp = &n2->nfile.next;
304		parsefname();
305	}
306	tokpushback++;
307
308	while (readtoken() == TNOT) {
309		TRACE(("command: TNOT recognized\n"));
310		negate = !negate;
311	}
312	tokpushback++;
313
314	switch (readtoken()) {
315	case TIF:
316		n1 = (union node *)stalloc(sizeof (struct nif));
317		n1->type = NIF;
318		if ((n1->nif.test = list(0)) == NULL)
319			synexpect(-1);
320		if (readtoken() != TTHEN)
321			synexpect(TTHEN);
322		n1->nif.ifpart = list(0);
323		n2 = n1;
324		while (readtoken() == TELIF) {
325			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
326			n2 = n2->nif.elsepart;
327			n2->type = NIF;
328			if ((n2->nif.test = list(0)) == NULL)
329				synexpect(-1);
330			if (readtoken() != TTHEN)
331				synexpect(TTHEN);
332			n2->nif.ifpart = list(0);
333		}
334		if (lasttoken == TELSE)
335			n2->nif.elsepart = list(0);
336		else {
337			n2->nif.elsepart = NULL;
338			tokpushback++;
339		}
340		if (readtoken() != TFI)
341			synexpect(TFI);
342		checkkwd = 1;
343		break;
344	case TWHILE:
345	case TUNTIL: {
346		int got;
347		n1 = (union node *)stalloc(sizeof (struct nbinary));
348		n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
349		if ((n1->nbinary.ch1 = list(0)) == NULL)
350			synexpect(-1);
351		if ((got=readtoken()) != TDO) {
352TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : ""));
353			synexpect(TDO);
354		}
355		n1->nbinary.ch2 = list(0);
356		if (readtoken() != TDONE)
357			synexpect(TDONE);
358		checkkwd = 1;
359		break;
360	}
361	case TFOR:
362		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
363			synerror("Bad for loop variable");
364		n1 = (union node *)stalloc(sizeof (struct nfor));
365		n1->type = NFOR;
366		n1->nfor.var = wordtext;
367		if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
368			app = &ap;
369			while (readtoken() == TWORD) {
370				n2 = (union node *)stalloc(sizeof (struct narg));
371				n2->type = NARG;
372				n2->narg.text = wordtext;
373				n2->narg.backquote = backquotelist;
374				*app = n2;
375				app = &n2->narg.next;
376			}
377			*app = NULL;
378			n1->nfor.args = ap;
379			if (lasttoken != TNL && lasttoken != TSEMI)
380				synexpect(-1);
381		} else {
382			static char argvars[5] = {
383				CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
384			};
385			n2 = (union node *)stalloc(sizeof (struct narg));
386			n2->type = NARG;
387			n2->narg.text = argvars;
388			n2->narg.backquote = NULL;
389			n2->narg.next = NULL;
390			n1->nfor.args = n2;
391			/*
392			 * Newline or semicolon here is optional (but note
393			 * that the original Bourne shell only allowed NL).
394			 */
395			if (lasttoken != TNL && lasttoken != TSEMI)
396				tokpushback++;
397		}
398		checkkwd = 2;
399		if ((t = readtoken()) == TDO)
400			t = TDONE;
401		else if (t == TBEGIN)
402			t = TEND;
403		else
404			synexpect(-1);
405		n1->nfor.body = list(0);
406		if (readtoken() != t)
407			synexpect(t);
408		checkkwd = 1;
409		break;
410	case TCASE:
411		n1 = (union node *)stalloc(sizeof (struct ncase));
412		n1->type = NCASE;
413		if (readtoken() != TWORD)
414			synexpect(TWORD);
415		n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
416		n2->type = NARG;
417		n2->narg.text = wordtext;
418		n2->narg.backquote = backquotelist;
419		n2->narg.next = NULL;
420		while (readtoken() == TNL);
421		if (lasttoken != TWORD || ! equal(wordtext, "in"))
422			synerror("expecting \"in\"");
423		cpp = &n1->ncase.cases;
424		noaliases = 1;	/* turn off alias expansion */
425		checkkwd = 2, readtoken();
426		while (lasttoken != TESAC) {
427			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
428			cp->type = NCLIST;
429			app = &cp->nclist.pattern;
430			if (lasttoken == TLP)
431				readtoken();
432			for (;;) {
433				*app = ap = (union node *)stalloc(sizeof (struct narg));
434				ap->type = NARG;
435				ap->narg.text = wordtext;
436				ap->narg.backquote = backquotelist;
437				if (checkkwd = 2, readtoken() != TPIPE)
438					break;
439				app = &ap->narg.next;
440				readtoken();
441			}
442			ap->narg.next = NULL;
443			if (lasttoken != TRP)
444				noaliases = 0, synexpect(TRP);
445			cp->nclist.body = list(0);
446
447			checkkwd = 2;
448			if ((t = readtoken()) != TESAC) {
449				if (t != TENDCASE)
450					noaliases = 0, synexpect(TENDCASE);
451				else
452					checkkwd = 2, readtoken();
453			}
454			cpp = &cp->nclist.next;
455		}
456		noaliases = 0;	/* reset alias expansion */
457		*cpp = NULL;
458		checkkwd = 1;
459		break;
460	case TLP:
461		n1 = (union node *)stalloc(sizeof (struct nredir));
462		n1->type = NSUBSHELL;
463		n1->nredir.n = list(0);
464		n1->nredir.redirect = NULL;
465		if (readtoken() != TRP)
466			synexpect(TRP);
467		checkkwd = 1;
468		break;
469	case TBEGIN:
470		n1 = list(0);
471		if (readtoken() != TEND)
472			synexpect(TEND);
473		checkkwd = 1;
474		break;
475	/* Handle an empty command like other simple commands.  */
476	case TSEMI:
477	case TAND:
478	case TOR:
479		/*
480		 * An empty command before a ; doesn't make much sense, and
481		 * should certainly be disallowed in the case of `if ;'.
482		 */
483		if (!redir)
484			synexpect(-1);
485	case TNL:
486	case TEOF:
487	case TWORD:
488	case TRP:
489		tokpushback++;
490		n1 = simplecmd(rpp, redir);
491		goto checkneg;
492	default:
493		synexpect(-1);
494	}
495
496	/* Now check for redirection which may follow command */
497	while (readtoken() == TREDIR) {
498		*rpp = n2 = redirnode;
499		rpp = &n2->nfile.next;
500		parsefname();
501	}
502	tokpushback++;
503	*rpp = NULL;
504	if (redir) {
505		if (n1->type != NSUBSHELL) {
506			n2 = (union node *)stalloc(sizeof (struct nredir));
507			n2->type = NREDIR;
508			n2->nredir.n = n1;
509			n1 = n2;
510		}
511		n1->nredir.redirect = redir;
512	}
513
514checkneg:
515	if (negate) {
516		n2 = (union node *)stalloc(sizeof (struct nnot));
517		n2->type = NNOT;
518		n2->nnot.com = n1;
519		return n2;
520	}
521	else
522		return n1;
523}
524
525
526STATIC union node *
527simplecmd(union node **rpp, union node *redir)
528{
529	union node *args, **app;
530	union node **orig_rpp = rpp;
531	union node *n = NULL, *n2;
532	int negate = 0;
533
534	/* If we don't have any redirections already, then we must reset */
535	/* rpp to be the address of the local redir variable.  */
536	if (redir == 0)
537		rpp = &redir;
538
539	args = NULL;
540	app = &args;
541	/*
542	 * We save the incoming value, because we need this for shell
543	 * functions.  There can not be a redirect or an argument between
544	 * the function name and the open parenthesis.
545	 */
546	orig_rpp = rpp;
547
548	while (readtoken() == TNOT) {
549		TRACE(("command: TNOT recognized\n"));
550		negate = !negate;
551	}
552	tokpushback++;
553
554	for (;;) {
555		if (readtoken() == TWORD) {
556			n = (union node *)stalloc(sizeof (struct narg));
557			n->type = NARG;
558			n->narg.text = wordtext;
559			n->narg.backquote = backquotelist;
560			*app = n;
561			app = &n->narg.next;
562		} else if (lasttoken == TREDIR) {
563			*rpp = n = redirnode;
564			rpp = &n->nfile.next;
565			parsefname();	/* read name of redirection file */
566		} else if (lasttoken == TLP && app == &args->narg.next
567					    && rpp == orig_rpp) {
568			/* We have a function */
569			if (readtoken() != TRP)
570				synexpect(TRP);
571			funclinno = plinno;
572#ifdef notdef
573			if (! goodname(n->narg.text))
574				synerror("Bad function name");
575#endif
576			n->type = NDEFUN;
577			n->narg.next = command();
578			funclinno = 0;
579			goto checkneg;
580		} else {
581			tokpushback++;
582			break;
583		}
584	}
585	*app = NULL;
586	*rpp = NULL;
587	n = (union node *)stalloc(sizeof (struct ncmd));
588	n->type = NCMD;
589	n->ncmd.backgnd = 0;
590	n->ncmd.args = args;
591	n->ncmd.redirect = redir;
592
593checkneg:
594	if (negate) {
595		n2 = (union node *)stalloc(sizeof (struct nnot));
596		n2->type = NNOT;
597		n2->nnot.com = n;
598		return n2;
599	}
600	else
601		return n;
602}
603
604STATIC union node *
605makename(void)
606{
607	union node *n;
608
609	n = (union node *)stalloc(sizeof (struct narg));
610	n->type = NARG;
611	n->narg.next = NULL;
612	n->narg.text = wordtext;
613	n->narg.backquote = backquotelist;
614	return n;
615}
616
617void fixredir(union node *n, const char *text, int err)
618{
619	TRACE(("Fix redir %s %d\n", text, err));
620	if (!err)
621		n->ndup.vname = NULL;
622
623	if (is_digit(text[0]) && text[1] == '\0')
624		n->ndup.dupfd = digit_val(text[0]);
625	else if (text[0] == '-' && text[1] == '\0')
626		n->ndup.dupfd = -1;
627	else {
628
629		if (err)
630			synerror("Bad fd number");
631		else
632			n->ndup.vname = makename();
633	}
634}
635
636
637STATIC void
638parsefname(void)
639{
640	union node *n = redirnode;
641
642	if (readtoken() != TWORD)
643		synexpect(-1);
644	if (n->type == NHERE) {
645		struct heredoc *here = heredoc;
646		struct heredoc *p;
647		int i;
648
649		if (quoteflag == 0)
650			n->type = NXHERE;
651		TRACE(("Here document %d\n", n->type));
652		if (here->striptabs) {
653			while (*wordtext == '\t')
654				wordtext++;
655		}
656		if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
657			synerror("Illegal eof marker for << redirection");
658		rmescapes(wordtext);
659		here->eofmark = wordtext;
660		here->next = NULL;
661		if (heredoclist == NULL)
662			heredoclist = here;
663		else {
664			for (p = heredoclist ; p->next ; p = p->next);
665			p->next = here;
666		}
667	} else if (n->type == NTOFD || n->type == NFROMFD) {
668		fixredir(n, wordtext, 0);
669	} else {
670		n->nfile.fname = makename();
671	}
672}
673
674
675/*
676 * Input any here documents.
677 */
678
679STATIC void
680parseheredoc(void)
681{
682	struct heredoc *here;
683	union node *n;
684
685	while (heredoclist) {
686		here = heredoclist;
687		heredoclist = here->next;
688		if (needprompt) {
689			setprompt(2);
690			needprompt = 0;
691		}
692		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
693				here->eofmark, here->striptabs);
694		n = (union node *)stalloc(sizeof (struct narg));
695		n->narg.type = NARG;
696		n->narg.next = NULL;
697		n->narg.text = wordtext;
698		n->narg.backquote = backquotelist;
699		here->here->nhere.doc = n;
700	}
701}
702
703STATIC int
704peektoken(void)
705{
706	int t;
707
708	t = readtoken();
709	tokpushback++;
710	return (t);
711}
712
713STATIC int
714readtoken(void)
715{
716	int t;
717	int savecheckkwd = checkkwd;
718	struct alias *ap;
719#ifdef DEBUG
720	int alreadyseen = tokpushback;
721#endif
722
723	top:
724	t = xxreadtoken();
725
726	if (checkkwd) {
727		/*
728		 * eat newlines
729		 */
730		if (checkkwd == 2) {
731			checkkwd = 0;
732			while (t == TNL) {
733				parseheredoc();
734				t = xxreadtoken();
735			}
736		} else
737			checkkwd = 0;
738		/*
739		 * check for keywords and aliases
740		 */
741		if (t == TWORD && !quoteflag)
742		{
743			const char * const *pp;
744
745			for (pp = parsekwd; *pp; pp++) {
746				if (**pp == *wordtext && equal(*pp, wordtext))
747				{
748					lasttoken = t = pp - parsekwd + KWDOFFSET;
749					TRACE(("keyword %s recognized\n", tokname[t]));
750					goto out;
751				}
752			}
753			if (noaliases == 0 &&
754			    (ap = lookupalias(wordtext, 1)) != NULL) {
755				pushstring(ap->val, strlen(ap->val), ap);
756				checkkwd = savecheckkwd;
757				goto top;
758			}
759		}
760out:
761		checkkwd = (t == TNOT) ? savecheckkwd : 0;
762	}
763#ifdef DEBUG
764	if (!alreadyseen)
765	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
766	else
767	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
768#endif
769	return (t);
770}
771
772
773/*
774 * Read the next input token.
775 * If the token is a word, we set backquotelist to the list of cmds in
776 *	backquotes.  We set quoteflag to true if any part of the word was
777 *	quoted.
778 * If the token is TREDIR, then we set redirnode to a structure containing
779 *	the redirection.
780 * In all cases, the variable startlinno is set to the number of the line
781 *	on which the token starts.
782 *
783 * [Change comment:  here documents and internal procedures]
784 * [Readtoken shouldn't have any arguments.  Perhaps we should make the
785 *  word parsing code into a separate routine.  In this case, readtoken
786 *  doesn't need to have any internal procedures, but parseword does.
787 *  We could also make parseoperator in essence the main routine, and
788 *  have parseword (readtoken1?) handle both words and redirection.]
789 */
790
791#define RETURN(token)	return lasttoken = token
792
793STATIC int
794xxreadtoken(void)
795{
796	int c;
797
798	if (tokpushback) {
799		tokpushback = 0;
800		return lasttoken;
801	}
802	if (needprompt) {
803		setprompt(2);
804		needprompt = 0;
805	}
806	startlinno = plinno;
807	for (;;) {	/* until token or start of word found */
808		c = pgetc_macro();
809		if (c == ' ' || c == '\t')
810			continue;		/* quick check for white space first */
811		switch (c) {
812		case ' ': case '\t':
813			continue;
814		case '#':
815			while ((c = pgetc()) != '\n' && c != PEOF);
816			pungetc();
817			continue;
818		case '\\':
819			if (pgetc() == '\n') {
820				startlinno = ++plinno;
821				if (doprompt)
822					setprompt(2);
823				else
824					setprompt(0);
825				continue;
826			}
827			pungetc();
828			goto breakloop;
829		case '\n':
830			plinno++;
831			needprompt = doprompt;
832			RETURN(TNL);
833		case PEOF:
834			RETURN(TEOF);
835		case '&':
836			if (pgetc() == '&')
837				RETURN(TAND);
838			pungetc();
839			RETURN(TBACKGND);
840		case '|':
841			if (pgetc() == '|')
842				RETURN(TOR);
843			pungetc();
844			RETURN(TPIPE);
845		case ';':
846			if (pgetc() == ';')
847				RETURN(TENDCASE);
848			pungetc();
849			RETURN(TSEMI);
850		case '(':
851			RETURN(TLP);
852		case ')':
853			RETURN(TRP);
854		default:
855			goto breakloop;
856		}
857	}
858breakloop:
859	return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
860#undef RETURN
861}
862
863
864
865/*
866 * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
867 * is not NULL, read a here document.  In the latter case, eofmark is the
868 * word which marks the end of the document and striptabs is true if
869 * leading tabs should be stripped from the document.  The argument firstc
870 * is the first character of the input token or document.
871 *
872 * Because C does not have internal subroutines, I have simulated them
873 * using goto's to implement the subroutine linkage.  The following macros
874 * will run code that appears at the end of readtoken1.
875 */
876
877#define CHECKEND()	{goto checkend; checkend_return:;}
878#define PARSEREDIR()	{goto parseredir; parseredir_return:;}
879#define PARSESUB()	{goto parsesub; parsesub_return:;}
880#define PARSEBACKQOLD()	{oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
881#define PARSEBACKQNEW()	{oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
882#define	PARSEARITH()	{goto parsearith; parsearith_return:;}
883
884STATIC int
885readtoken1(int firstc, char const *syntax, char *eofmark, int striptabs)
886{
887	int c = firstc;
888	char *out;
889	int len;
890	char line[EOFMARKLEN + 1];
891	struct nodelist *bqlist;
892	int quotef;
893	int dblquote;
894	int varnest;	/* levels of variables expansion */
895	int arinest;	/* levels of arithmetic expansion */
896	int parenlevel;	/* levels of parens in arithmetic */
897	int oldstyle;
898	char const *prevsyntax;	/* syntax before arithmetic */
899	int synentry;
900#if __GNUC__
901	/* Avoid longjmp clobbering */
902	(void) &out;
903	(void) &quotef;
904	(void) &dblquote;
905	(void) &varnest;
906	(void) &arinest;
907	(void) &parenlevel;
908	(void) &oldstyle;
909	(void) &prevsyntax;
910	(void) &syntax;
911	(void) &synentry;
912#endif
913
914	startlinno = plinno;
915	dblquote = 0;
916	if (syntax == DQSYNTAX)
917		dblquote = 1;
918	quotef = 0;
919	bqlist = NULL;
920	varnest = 0;
921	arinest = 0;
922	parenlevel = 0;
923
924	STARTSTACKSTR(out);
925	loop: {	/* for each line, until end of word */
926		CHECKEND();	/* set c to PEOF if at end of here document */
927		for (;;) {	/* until end of line or end of word */
928			CHECKSTRSPACE(3, out);	/* permit 3 calls to USTPUTC */
929
930			synentry = syntax[c];
931
932			switch(synentry) {
933			case CNL:	/* '\n' */
934				if (syntax == BASESYNTAX)
935					goto endword;	/* exit outer loop */
936				USTPUTC(c, out);
937				plinno++;
938				if (doprompt)
939					setprompt(2);
940				else
941					setprompt(0);
942				c = pgetc();
943				goto loop;		/* continue outer loop */
944			case CWORD:
945				USTPUTC(c, out);
946				break;
947			case CCTL:
948				if (eofmark == NULL || dblquote)
949					USTPUTC(CTLESC, out);
950				USTPUTC(c, out);
951				break;
952			case CBACK:	/* backslash */
953				c = pgetc();
954				if (c == PEOF) {
955					USTPUTC('\\', out);
956					pungetc();
957				} else if (c == '\n') {
958					plinno++;
959					if (doprompt)
960						setprompt(2);
961					else
962						setprompt(0);
963				} else {
964					if (dblquote && c != '\\' &&
965					    c != '`' && c != '$' &&
966					    (c != '"' || eofmark != NULL))
967						USTPUTC('\\', out);
968					if (SQSYNTAX[c] == CCTL)
969						USTPUTC(CTLESC, out);
970					else if (eofmark == NULL)
971						USTPUTC(CTLQUOTEMARK, out);
972					USTPUTC(c, out);
973					quotef++;
974				}
975				break;
976			case CSQUOTE:
977				if (eofmark == NULL)
978					USTPUTC(CTLQUOTEMARK, out);
979				syntax = SQSYNTAX;
980				break;
981			case CDQUOTE:
982				if (eofmark == NULL)
983					USTPUTC(CTLQUOTEMARK, out);
984				syntax = DQSYNTAX;
985				dblquote = 1;
986				break;
987			case CENDQUOTE:
988				if (eofmark != NULL && arinest == 0 &&
989				    varnest == 0) {
990					USTPUTC(c, out);
991				} else {
992					if (arinest) {
993						syntax = ARISYNTAX;
994						dblquote = 0;
995					} else if (eofmark == NULL) {
996						syntax = BASESYNTAX;
997						dblquote = 0;
998					}
999					quotef++;
1000				}
1001				break;
1002			case CVAR:	/* '$' */
1003				PARSESUB();		/* parse substitution */
1004				break;
1005			case CENDVAR:	/* '}' */
1006				if (varnest > 0) {
1007					varnest--;
1008					USTPUTC(CTLENDVAR, out);
1009				} else {
1010					USTPUTC(c, out);
1011				}
1012				break;
1013			case CLP:	/* '(' in arithmetic */
1014				parenlevel++;
1015				USTPUTC(c, out);
1016				break;
1017			case CRP:	/* ')' in arithmetic */
1018				if (parenlevel > 0) {
1019					USTPUTC(c, out);
1020					--parenlevel;
1021				} else {
1022					if (pgetc() == ')') {
1023						if (--arinest == 0) {
1024							USTPUTC(CTLENDARI, out);
1025							syntax = prevsyntax;
1026							if (syntax == DQSYNTAX)
1027								dblquote = 1;
1028							else
1029								dblquote = 0;
1030						} else
1031							USTPUTC(')', out);
1032					} else {
1033						/*
1034						 * unbalanced parens
1035						 *  (don't 2nd guess - no error)
1036						 */
1037						pungetc();
1038						USTPUTC(')', out);
1039					}
1040				}
1041				break;
1042			case CBQUOTE:	/* '`' */
1043				PARSEBACKQOLD();
1044				break;
1045			case CEOF:
1046				goto endword;		/* exit outer loop */
1047			default:
1048				if (varnest == 0)
1049					goto endword;	/* exit outer loop */
1050				USTPUTC(c, out);
1051			}
1052			c = pgetc_macro();
1053		}
1054	}
1055endword:
1056	if (syntax == ARISYNTAX)
1057		synerror("Missing '))'");
1058	if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
1059		synerror("Unterminated quoted string");
1060	if (varnest != 0) {
1061		startlinno = plinno;
1062		synerror("Missing '}'");
1063	}
1064	USTPUTC('\0', out);
1065	len = out - stackblock();
1066	out = stackblock();
1067	if (eofmark == NULL) {
1068		if ((c == '>' || c == '<')
1069		 && quotef == 0
1070		 && len <= 2
1071		 && (*out == '\0' || is_digit(*out))) {
1072			PARSEREDIR();
1073			return lasttoken = TREDIR;
1074		} else {
1075			pungetc();
1076		}
1077	}
1078	quoteflag = quotef;
1079	backquotelist = bqlist;
1080	grabstackblock(len);
1081	wordtext = out;
1082	return lasttoken = TWORD;
1083/* end of readtoken routine */
1084
1085
1086
1087/*
1088 * Check to see whether we are at the end of the here document.  When this
1089 * is called, c is set to the first character of the next input line.  If
1090 * we are at the end of the here document, this routine sets the c to PEOF.
1091 */
1092
1093checkend: {
1094	if (eofmark) {
1095		if (striptabs) {
1096			while (c == '\t')
1097				c = pgetc();
1098		}
1099		if (c == *eofmark) {
1100			if (pfgets(line, sizeof line) != NULL) {
1101				char *p, *q;
1102
1103				p = line;
1104				for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
1105				if (*p == '\n' && *q == '\0') {
1106					c = PEOF;
1107					plinno++;
1108					needprompt = doprompt;
1109				} else {
1110					pushstring(line, strlen(line), NULL);
1111				}
1112			}
1113		}
1114	}
1115	goto checkend_return;
1116}
1117
1118
1119/*
1120 * Parse a redirection operator.  The variable "out" points to a string
1121 * specifying the fd to be redirected.  The variable "c" contains the
1122 * first character of the redirection operator.
1123 */
1124
1125parseredir: {
1126	char fd = *out;
1127	union node *np;
1128
1129	np = (union node *)stalloc(sizeof (struct nfile));
1130	if (c == '>') {
1131		np->nfile.fd = 1;
1132		c = pgetc();
1133		if (c == '>')
1134			np->type = NAPPEND;
1135		else if (c == '&')
1136			np->type = NTOFD;
1137		else if (c == '|')
1138			np->type = NCLOBBER;
1139		else {
1140			np->type = NTO;
1141			pungetc();
1142		}
1143	} else {	/* c == '<' */
1144		np->nfile.fd = 0;
1145		c = pgetc();
1146		if (c == '<') {
1147			if (sizeof (struct nfile) != sizeof (struct nhere)) {
1148				np = (union node *)stalloc(sizeof (struct nhere));
1149				np->nfile.fd = 0;
1150			}
1151			np->type = NHERE;
1152			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1153			heredoc->here = np;
1154			if ((c = pgetc()) == '-') {
1155				heredoc->striptabs = 1;
1156			} else {
1157				heredoc->striptabs = 0;
1158				pungetc();
1159			}
1160		} else if (c == '&')
1161			np->type = NFROMFD;
1162		else if (c == '>')
1163			np->type = NFROMTO;
1164		else {
1165			np->type = NFROM;
1166			pungetc();
1167		}
1168	}
1169	if (fd != '\0')
1170		np->nfile.fd = digit_val(fd);
1171	redirnode = np;
1172	goto parseredir_return;
1173}
1174
1175
1176/*
1177 * Parse a substitution.  At this point, we have read the dollar sign
1178 * and nothing else.
1179 */
1180
1181parsesub: {
1182	char buf[10];
1183	int subtype;
1184	int typeloc;
1185	int flags;
1186	char *p;
1187	static const char types[] = "}-+?=";
1188	int bracketed_name = 0; /* used to handle ${[0-9]*} variables */
1189	int i;
1190	int linno;
1191
1192	c = pgetc();
1193	if (c != '(' && c != '{' && (is_eof(c) || !is_name(c)) &&
1194	    !is_special(c)) {
1195		USTPUTC('$', out);
1196		pungetc();
1197	} else if (c == '(') {	/* $(command) or $((arith)) */
1198		if (pgetc() == '(') {
1199			PARSEARITH();
1200		} else {
1201			pungetc();
1202			PARSEBACKQNEW();
1203		}
1204	} else {
1205		USTPUTC(CTLVAR, out);
1206		typeloc = out - stackblock();
1207		USTPUTC(VSNORMAL, out);
1208		subtype = VSNORMAL;
1209		flags = 0;
1210		if (c == '{') {
1211			bracketed_name = 1;
1212			c = pgetc();
1213			if (c == '#') {
1214				if ((c = pgetc()) == '}')
1215					c = '#';
1216				else
1217					subtype = VSLENGTH;
1218			}
1219			else
1220				subtype = 0;
1221		}
1222		if (!is_eof(c) && is_name(c)) {
1223			p = out;
1224			do {
1225				STPUTC(c, out);
1226				c = pgetc();
1227			} while (!is_eof(c) && is_in_name(c));
1228			if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
1229				/* Replace the variable name with the
1230				 * current line number. */
1231				linno = plinno;
1232				if (funclinno != 0)
1233					linno -= funclinno - 1;
1234				snprintf(buf, sizeof(buf), "%d", linno);
1235				STADJUST(-6, out);
1236				for (i = 0; buf[i] != '\0'; i++)
1237					STPUTC(buf[i], out);
1238				flags |= VSLINENO;
1239			}
1240		} else if (is_digit(c)) {
1241			if (bracketed_name) {
1242				do {
1243					STPUTC(c, out);
1244					c = pgetc();
1245				} while (is_digit(c));
1246			} else {
1247				STPUTC(c, out);
1248				c = pgetc();
1249			}
1250		} else {
1251			if (! is_special(c)) {
1252				subtype = VSERROR;
1253				if (c == '}')
1254					pungetc();
1255				else
1256					USTPUTC(c, out);
1257			} else {
1258				USTPUTC(c, out);
1259				c = pgetc();
1260			}
1261		}
1262		if (subtype == 0) {
1263			switch (c) {
1264			case ':':
1265				flags |= VSNUL;
1266				c = pgetc();
1267				/*FALLTHROUGH*/
1268			default:
1269				p = strchr(types, c);
1270				if (p == NULL) {
1271					if (flags == VSNUL)
1272						STPUTC(':', out);
1273					STPUTC(c, out);
1274					subtype = VSERROR;
1275				} else
1276					subtype = p - types + VSNORMAL;
1277				break;
1278			case '%':
1279			case '#':
1280				{
1281					int cc = c;
1282					subtype = c == '#' ? VSTRIMLEFT :
1283							     VSTRIMRIGHT;
1284					c = pgetc();
1285					if (c == cc)
1286						subtype++;
1287					else
1288						pungetc();
1289					break;
1290				}
1291			}
1292		} else if (subtype != VSERROR) {
1293			pungetc();
1294		}
1295		STPUTC('=', out);
1296		if (subtype != VSLENGTH && (dblquote || arinest))
1297			flags |= VSQUOTE;
1298		*(stackblock() + typeloc) = subtype | flags;
1299		if (subtype != VSNORMAL)
1300			varnest++;
1301	}
1302	goto parsesub_return;
1303}
1304
1305
1306/*
1307 * Called to parse command substitutions.  Newstyle is set if the command
1308 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
1309 * list of commands (passed by reference), and savelen is the number of
1310 * characters on the top of the stack which must be preserved.
1311 */
1312
1313parsebackq: {
1314	struct nodelist **nlpp;
1315	int savepbq;
1316	union node *n;
1317	char *volatile str;
1318	struct jmploc jmploc;
1319	struct jmploc *volatile savehandler;
1320	int savelen;
1321	int saveprompt;
1322#if __GNUC__
1323	/* Avoid longjmp clobbering */
1324	(void) &saveprompt;
1325#endif
1326
1327	savepbq = parsebackquote;
1328	if (setjmp(jmploc.loc)) {
1329		if (str)
1330			ckfree(str);
1331		parsebackquote = 0;
1332		handler = savehandler;
1333		longjmp(handler->loc, 1);
1334	}
1335	INTOFF;
1336	str = NULL;
1337	savelen = out - stackblock();
1338	if (savelen > 0) {
1339		str = ckmalloc(savelen);
1340		memcpy(str, stackblock(), savelen);
1341	}
1342	savehandler = handler;
1343	handler = &jmploc;
1344	INTON;
1345        if (oldstyle) {
1346                /* We must read until the closing backquote, giving special
1347                   treatment to some slashes, and then push the string and
1348                   reread it as input, interpreting it normally.  */
1349                char *out;
1350                int c;
1351                int savelen;
1352                char *str;
1353
1354
1355                STARTSTACKSTR(out);
1356		for (;;) {
1357			if (needprompt) {
1358				setprompt(2);
1359				needprompt = 0;
1360			}
1361			switch (c = pgetc()) {
1362			case '`':
1363				goto done;
1364
1365			case '\\':
1366                                if ((c = pgetc()) == '\n') {
1367					plinno++;
1368					if (doprompt)
1369						setprompt(2);
1370					else
1371						setprompt(0);
1372					/*
1373					 * If eating a newline, avoid putting
1374					 * the newline into the new character
1375					 * stream (via the STPUTC after the
1376					 * switch).
1377					 */
1378					continue;
1379				}
1380                                if (c != '\\' && c != '`' && c != '$'
1381                                    && (!dblquote || c != '"'))
1382                                        STPUTC('\\', out);
1383				break;
1384
1385			case '\n':
1386				plinno++;
1387				needprompt = doprompt;
1388				break;
1389
1390			case PEOF:
1391			        startlinno = plinno;
1392				synerror("EOF in backquote substitution");
1393 				break;
1394
1395			default:
1396				break;
1397			}
1398			STPUTC(c, out);
1399                }
1400done:
1401                STPUTC('\0', out);
1402                savelen = out - stackblock();
1403                if (savelen > 0) {
1404                        str = ckmalloc(savelen);
1405                        memcpy(str, stackblock(), savelen);
1406			setinputstring(str, 1);
1407                }
1408        }
1409	nlpp = &bqlist;
1410	while (*nlpp)
1411		nlpp = &(*nlpp)->next;
1412	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1413	(*nlpp)->next = NULL;
1414	parsebackquote = oldstyle;
1415
1416	if (oldstyle) {
1417		saveprompt = doprompt;
1418		doprompt = 0;
1419	}
1420
1421	n = list(0);
1422
1423	if (oldstyle)
1424		doprompt = saveprompt;
1425	else {
1426		if (readtoken() != TRP)
1427			synexpect(TRP);
1428	}
1429
1430	(*nlpp)->n = n;
1431        if (oldstyle) {
1432		/*
1433		 * Start reading from old file again, ignoring any pushed back
1434		 * tokens left from the backquote parsing
1435		 */
1436                popfile();
1437		tokpushback = 0;
1438	}
1439	while (stackblocksize() <= savelen)
1440		growstackblock();
1441	STARTSTACKSTR(out);
1442	if (str) {
1443		memcpy(out, str, savelen);
1444		STADJUST(savelen, out);
1445		INTOFF;
1446		ckfree(str);
1447		str = NULL;
1448		INTON;
1449	}
1450	parsebackquote = savepbq;
1451	handler = savehandler;
1452	if (arinest || dblquote)
1453		USTPUTC(CTLBACKQ | CTLQUOTE, out);
1454	else
1455		USTPUTC(CTLBACKQ, out);
1456	if (oldstyle)
1457		goto parsebackq_oldreturn;
1458	else
1459		goto parsebackq_newreturn;
1460}
1461
1462/*
1463 * Parse an arithmetic expansion (indicate start of one and set state)
1464 */
1465parsearith: {
1466
1467	if (++arinest == 1) {
1468		prevsyntax = syntax;
1469		syntax = ARISYNTAX;
1470		USTPUTC(CTLARI, out);
1471		if (dblquote)
1472			USTPUTC('"',out);
1473		else
1474			USTPUTC(' ',out);
1475	} else {
1476		/*
1477		 * we collapse embedded arithmetic expansion to
1478		 * parenthesis, which should be equivalent
1479		 */
1480		USTPUTC('(', out);
1481	}
1482	goto parsearith_return;
1483}
1484
1485} /* end of readtoken */
1486
1487
1488
1489#ifdef mkinit
1490RESET {
1491	tokpushback = 0;
1492	checkkwd = 0;
1493}
1494#endif
1495
1496/*
1497 * Returns true if the text contains nothing to expand (no dollar signs
1498 * or backquotes).
1499 */
1500
1501STATIC int
1502noexpand(char *text)
1503{
1504	char *p;
1505	char c;
1506
1507	p = text;
1508	while ((c = *p++) != '\0') {
1509		if ( c == CTLQUOTEMARK)
1510			continue;
1511		if (c == CTLESC)
1512			p++;
1513		else if (BASESYNTAX[(int)c] == CCTL)
1514			return 0;
1515	}
1516	return 1;
1517}
1518
1519
1520/*
1521 * Return true if the argument is a legal variable name (a letter or
1522 * underscore followed by zero or more letters, underscores, and digits).
1523 */
1524
1525int
1526goodname(char *name)
1527{
1528	char *p;
1529
1530	p = name;
1531	if (! is_name(*p))
1532		return 0;
1533	while (*++p) {
1534		if (! is_in_name(*p))
1535			return 0;
1536	}
1537	return 1;
1538}
1539
1540
1541/*
1542 * Called when an unexpected token is read during the parse.  The argument
1543 * is the token that is expected, or -1 if more than one type of token can
1544 * occur at this point.
1545 */
1546
1547STATIC void
1548synexpect(int token)
1549{
1550	char msg[64];
1551
1552	if (token >= 0) {
1553		fmtstr(msg, 64, "%s unexpected (expecting %s)",
1554			tokname[lasttoken], tokname[token]);
1555	} else {
1556		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1557	}
1558	synerror(msg);
1559}
1560
1561
1562STATIC void
1563synerror(char *msg)
1564{
1565	if (commandname)
1566		outfmt(&errout, "%s: %d: ", commandname, startlinno);
1567	outfmt(&errout, "Syntax error: %s\n", msg);
1568	error((char *)NULL);
1569}
1570
1571STATIC void
1572setprompt(int which)
1573{
1574	whichprompt = which;
1575
1576#ifndef NO_HISTORY
1577	if (!el)
1578#endif
1579		out2str(getprompt(NULL));
1580}
1581
1582/*
1583 * called by editline -- any expansions to the prompt
1584 *    should be added here.
1585 */
1586char *
1587getprompt(void *unused __unused)
1588{
1589	static char ps[PROMPTLEN];
1590	char *fmt;
1591	int i, j, trim;
1592
1593	/*
1594	 * Select prompt format.
1595	 */
1596	switch (whichprompt) {
1597	case 0:
1598		fmt = "";
1599		break;
1600	case 1:
1601		fmt = ps1val();
1602		break;
1603	case 2:
1604		fmt = ps2val();
1605		break;
1606	default:
1607		return "<internal prompt error>";
1608	}
1609
1610	/*
1611	 * Format prompt string.
1612	 */
1613	for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++)
1614		if (*fmt == '\\')
1615			switch (*++fmt) {
1616
1617				/*
1618				 * Hostname.
1619				 *
1620				 * \h specifies just the local hostname,
1621				 * \H specifies fully-qualified hostname.
1622				 */
1623			case 'h':
1624			case 'H':
1625				ps[i] = '\0';
1626				gethostname(&ps[i], PROMPTLEN - i);
1627				/* Skip to end of hostname. */
1628				trim = (*fmt == 'h') ? '.' : '\0';
1629				while ((ps[i+1] != '\0') && (ps[i+1] != trim))
1630					i++;
1631				break;
1632
1633				/*
1634				 * Working directory.
1635				 *
1636				 * \W specifies just the final component,
1637				 * \w specifies the entire path.
1638				 */
1639			case 'W':
1640			case 'w':
1641				ps[i] = '\0';
1642				getcwd(&ps[i], PROMPTLEN - i);
1643				if (*fmt == 'W') {
1644					/* Final path component only. */
1645					trim = 1;
1646					for (j = i; ps[j] != '\0'; j++)
1647					  if (ps[j] == '/')
1648						trim = j + 1;
1649					memmove(&ps[i], &ps[trim],
1650					    j - trim + 1);
1651				}
1652				/* Skip to end of path. */
1653				while (ps[i + 1] != '\0')
1654					i++;
1655				break;
1656
1657				/*
1658				 * Superuser status.
1659				 *
1660				 * '$' for normal users, '#' for root.
1661				 */
1662			case '$':
1663				ps[i] = (geteuid() != 0) ? '$' : '#';
1664				break;
1665
1666				/*
1667				 * A literal \.
1668				 */
1669			case '\\':
1670				ps[i] = '\\';
1671				break;
1672
1673				/*
1674				 * Emit unrecognized formats verbatim.
1675				 */
1676			default:
1677				ps[i++] = '\\';
1678				ps[i] = *fmt;
1679				break;
1680			}
1681		else
1682			ps[i] = *fmt;
1683	ps[i] = '\0';
1684	return (ps);
1685}
1686