2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/param.h>
45 #include "expand.h" /* defines rmescapes() */
57 #include "exec.h" /* to check for special builtins */
59 #include "myhistedit.h"
63 * Shell command parser.
68 /* values of checkkwd variable */
73 /* values returned by readtoken */
79 struct heredoc *next; /* next here document in list */
80 union node *here; /* redirection node */
81 char *eofmark; /* string indicating end of input */
82 int striptabs; /* if set, strip leading tabs */
86 struct parser_temp *next;
91 static struct heredoc *heredoclist; /* list of here documents to read */
92 static int doprompt; /* if set, prompt the user */
93 static int needprompt; /* true if interactive and at start of line */
94 static int lasttoken; /* last token read */
95 static int tokpushback; /* last token pushed back */
96 static char *wordtext; /* text of last word returned by readtoken */
98 static struct nodelist *backquotelist;
99 static union node *redirnode;
100 static struct heredoc *heredoc;
101 static int quoteflag; /* set if (part of) last token was quoted */
102 static int startlinno; /* line # where last token started */
103 static int funclinno; /* line # where the current function started */
104 static struct parser_temp *parser_temp;
106 #define NOEOFMARK ((const char *)&heredoclist)
109 static union node *list(int);
110 static union node *andor(void);
111 static union node *pipeline(void);
112 static union node *command(void);
113 static union node *simplecmd(union node **, union node *);
114 static union node *makename(void);
115 static union node *makebinary(int type, union node *n1, union node *n2);
116 static void parsefname(void);
117 static void parseheredoc(void);
118 static int peektoken(void);
119 static int readtoken(void);
120 static int xxreadtoken(void);
121 static int readtoken1(int, const char *, const char *, int);
122 static int noexpand(char *);
123 static void consumetoken(int);
124 static void synexpect(int) __dead2;
125 static void synerror(const char *) __dead2;
126 static void setprompt(int);
127 static int pgetc_linecont(void);
128 static void getusername(char *, size_t);
132 parser_temp_alloc(size_t len)
134 struct parser_temp *t;
137 t = ckmalloc(sizeof(*t));
139 t->next = parser_temp;
141 t->data = ckmalloc(len);
148 parser_temp_realloc(void *ptr, size_t len)
150 struct parser_temp *t;
155 error("bug: parser_temp_realloc misused");
156 t->data = ckrealloc(t->data, len);
163 parser_temp_free_upto(void *ptr)
165 struct parser_temp *t;
169 while (parser_temp != NULL && !done) {
171 parser_temp = t->next;
172 done = t->data == ptr;
178 error("bug: parser_temp_free_upto misused");
183 parser_temp_free_all(void)
185 struct parser_temp *t;
188 while (parser_temp != NULL) {
190 parser_temp = t->next;
199 * Read and parse a command. Returns NEOF on end of file. (NULL is a
200 * valid parse tree indicating a blank line.)
204 parsecmd(int interact)
208 /* This assumes the parser is not re-entered,
209 * which could happen if we add command substitution on PS1/PS2.
211 parser_temp_free_all();
233 * Read and parse words for wordexp.
234 * Returns a list of NARG nodes; NULL if there are no words.
239 union node *n, *first = NULL, **pnext;
242 /* This assumes the parser is not re-entered,
243 * which could happen if we add command substitution on PS1/PS2.
245 parser_temp_free_all();
254 while ((t = readtoken()) != TEOF) {
259 pnext = &n->narg.next;
268 union node *ntop, *n1, *n2, *n3;
271 checkkwd = CHKNL | CHKKWD | CHKALIAS;
272 if (!nlflag && tokendlist[peektoken()])
278 if (tok == TBACKGND) {
279 if (n2 != NULL && n2->type == NPIPE) {
280 n2->npipe.backgnd = 1;
281 } else if (n2 != NULL && n2->type == NREDIR) {
284 n3 = (union node *)stalloc(sizeof (struct nredir));
287 n3->nredir.redirect = NULL;
293 else if (n1 == NULL) {
294 n1 = makebinary(NSEMI, ntop, n2);
298 n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
299 n1->nbinary.ch2 = n3;
312 } else if (tok == TEOF && nlflag) {
318 checkkwd = CHKNL | CHKKWD | CHKALIAS;
319 if (!nlflag && tokendlist[peektoken()])
326 pungetc(); /* push back EOF on input */
347 if ((t = readtoken()) == TAND) {
349 } else if (t == TOR) {
355 n = makebinary(t, n, pipeline());
364 union node *n1, *n2, *pipenode;
365 struct nodelist *lp, *prev;
369 checkkwd = CHKNL | CHKKWD | CHKALIAS;
370 TRACE(("pipeline: entered\n"));
371 while (readtoken() == TNOT)
375 if (readtoken() == TPIPE) {
376 pipenode = (union node *)stalloc(sizeof (struct npipe));
377 pipenode->type = NPIPE;
378 pipenode->npipe.backgnd = 0;
379 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
380 pipenode->npipe.cmdlist = lp;
384 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
385 checkkwd = CHKNL | CHKKWD | CHKALIAS;
393 } while (readtoken() == TPIPE);
399 n2 = (union node *)stalloc(sizeof (struct nnot));
413 union node *ap, **app;
414 union node *cp, **cpp;
415 union node *redir, **rpp;
419 checkkwd = CHKNL | CHKKWD | CHKALIAS;
425 /* Check for redirection which may precede command */
426 while (readtoken() == TREDIR) {
427 *rpp = n2 = redirnode;
428 rpp = &n2->nfile.next;
433 switch (readtoken()) {
435 n1 = (union node *)stalloc(sizeof (struct nif));
437 if ((n1->nif.test = list(0)) == NULL)
440 n1->nif.ifpart = list(0);
442 while (readtoken() == TELIF) {
443 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
444 n2 = n2->nif.elsepart;
446 if ((n2->nif.test = list(0)) == NULL)
449 n2->nif.ifpart = list(0);
451 if (lasttoken == TELSE)
452 n2->nif.elsepart = list(0);
454 n2->nif.elsepart = NULL;
458 checkkwd = CHKKWD | CHKALIAS;
463 if ((n1 = list(0)) == NULL)
466 n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
468 checkkwd = CHKKWD | CHKALIAS;
471 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
472 synerror("Bad for loop variable");
473 n1 = (union node *)stalloc(sizeof (struct nfor));
475 n1->nfor.var = wordtext;
477 if (readtoken() == TWORD && !quoteflag &&
478 equal(wordtext, "in")) {
480 while (readtoken() == TWORD) {
483 app = &n2->narg.next;
487 if (lasttoken == TNL)
489 else if (lasttoken != TSEMI)
492 static char argvars[5] = {
493 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
495 n2 = (union node *)stalloc(sizeof (struct narg));
497 n2->narg.text = argvars;
498 n2->narg.backquote = NULL;
499 n2->narg.next = NULL;
502 * Newline or semicolon here is optional (but note
503 * that the original Bourne shell only allowed NL).
505 if (lasttoken != TSEMI)
508 checkkwd = CHKNL | CHKKWD | CHKALIAS;
509 if ((t = readtoken()) == TDO)
511 else if (t == TBEGIN)
515 n1->nfor.body = list(0);
517 checkkwd = CHKKWD | CHKALIAS;
520 n1 = (union node *)stalloc(sizeof (struct ncase));
523 n1->ncase.expr = makename();
525 if (readtoken() != TWORD || ! equal(wordtext, "in"))
526 synerror("expecting \"in\"");
527 cpp = &n1->ncase.cases;
528 checkkwd = CHKNL | CHKKWD, readtoken();
529 while (lasttoken != TESAC) {
530 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
532 app = &cp->nclist.pattern;
533 if (lasttoken == TLP)
536 *app = ap = makename();
537 checkkwd = CHKNL | CHKKWD;
538 if (readtoken() != TPIPE)
540 app = &ap->narg.next;
543 ap->narg.next = NULL;
544 if (lasttoken != TRP)
546 cp->nclist.body = list(0);
548 checkkwd = CHKNL | CHKKWD | CHKALIAS;
549 if ((t = readtoken()) != TESAC) {
552 else if (t == TFALLTHRU)
553 cp->type = NCLISTFALLTHRU;
556 checkkwd = CHKNL | CHKKWD, readtoken();
558 cpp = &cp->nclist.next;
561 checkkwd = CHKKWD | CHKALIAS;
564 n1 = (union node *)stalloc(sizeof (struct nredir));
565 n1->type = NSUBSHELL;
566 n1->nredir.n = list(0);
567 n1->nredir.redirect = NULL;
569 checkkwd = CHKKWD | CHKALIAS;
575 checkkwd = CHKKWD | CHKALIAS;
577 /* A simple command must have at least one redirection or word. */
592 n1 = simplecmd(rpp, redir);
598 /* Now check for redirection which may follow command */
599 while (readtoken() == TREDIR) {
600 *rpp = n2 = redirnode;
601 rpp = &n2->nfile.next;
608 n2 = (union node *)stalloc(sizeof (struct nredir));
613 n1->nredir.redirect = redir;
621 simplecmd(union node **rpp, union node *redir)
623 union node *args, **app;
624 union node **orig_rpp = rpp;
625 union node *n = NULL;
629 /* If we don't have any redirections already, then we must reset */
630 /* rpp to be the address of the local redir variable. */
637 * We save the incoming value, because we need this for shell
638 * functions. There can not be a redirect or an argument between
639 * the function name and the open parenthesis.
643 savecheckkwd = CHKALIAS;
646 checkkwd = savecheckkwd;
647 if (readtoken() == TWORD) {
651 if (savecheckkwd != 0 && !isassignment(wordtext))
653 } else if (lasttoken == TREDIR) {
654 *rpp = n = redirnode;
655 rpp = &n->nfile.next;
656 parsefname(); /* read name of redirection file */
657 } else if (lasttoken == TLP && app == &args->narg.next
658 && rpp == orig_rpp) {
659 /* We have a function */
663 * - Require plain text.
664 * - Functions with '/' cannot be called.
666 * - Reject ksh extended glob patterns.
668 if (!noexpand(n->narg.text) || quoteflag ||
669 strchr(n->narg.text, '/') ||
671 n->narg.text[strlen(n->narg.text) - 1]))
672 synerror("Bad function name");
673 rmescapes(n->narg.text);
674 if (find_builtin(n->narg.text, &special) >= 0 &&
676 synerror("Cannot override a special builtin with a function");
678 n->narg.next = command();
688 n = (union node *)stalloc(sizeof (struct ncmd));
691 n->ncmd.redirect = redir;
700 n = (union node *)stalloc(sizeof (struct narg));
703 n->narg.text = wordtext;
704 n->narg.backquote = backquotelist;
709 makebinary(int type, union node *n1, union node *n2)
713 n = (union node *)stalloc(sizeof (struct nbinary));
723 checkkwd |= CHKALIAS;
727 fixredir(union node *n, const char *text, int err)
729 TRACE(("Fix redir %s %d\n", text, err));
731 n->ndup.vname = NULL;
733 if (is_digit(text[0]) && text[1] == '\0')
734 n->ndup.dupfd = digit_val(text[0]);
735 else if (text[0] == '-' && text[1] == '\0')
740 synerror("Bad fd number");
742 n->ndup.vname = makename();
750 union node *n = redirnode;
753 if (n->type == NHERE) {
754 struct heredoc *here = heredoc;
759 TRACE(("Here document %d\n", n->type));
760 if (here->striptabs) {
761 while (*wordtext == '\t')
764 if (! noexpand(wordtext))
765 synerror("Illegal eof marker for << redirection");
767 here->eofmark = wordtext;
769 if (heredoclist == NULL)
772 for (p = heredoclist ; p->next ; p = p->next);
775 } else if (n->type == NTOFD || n->type == NFROMFD) {
776 fixredir(n, wordtext, 0);
778 n->nfile.fname = makename();
784 * Input any here documents.
790 struct heredoc *here;
793 while (heredoclist) {
795 heredoclist = here->next;
800 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
801 here->eofmark, here->striptabs);
803 here->here->nhere.doc = n;
823 int alreadyseen = tokpushback;
832 if (checkkwd & CHKNL) {
840 * check for keywords and aliases
842 if (t == TWORD && !quoteflag)
844 const char * const *pp;
846 if (checkkwd & CHKKWD)
847 for (pp = parsekwd; *pp; pp++) {
848 if (**pp == *wordtext && equal(*pp, wordtext))
850 lasttoken = t = pp - parsekwd + KWDOFFSET;
851 TRACE(("keyword %s recognized\n", tokname[t]));
855 if (checkkwd & CHKALIAS &&
856 (ap = lookupalias(wordtext, 1)) != NULL) {
857 pushstring(ap->val, strlen(ap->val), ap);
867 TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
869 TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
876 * Read the next input token.
877 * If the token is a word, we set backquotelist to the list of cmds in
878 * backquotes. We set quoteflag to true if any part of the word was
880 * If the token is TREDIR, then we set redirnode to a structure containing
882 * In all cases, the variable startlinno is set to the number of the line
883 * on which the token starts.
885 * [Change comment: here documents and internal procedures]
886 * [Readtoken shouldn't have any arguments. Perhaps we should make the
887 * word parsing code into a separate routine. In this case, readtoken
888 * doesn't need to have any internal procedures, but parseword does.
889 * We could also make parseoperator in essence the main routine, and
890 * have parseword (readtoken1?) handle both words and redirection.]
893 #define RETURN(token) return lasttoken = token
909 for (;;) { /* until token or start of word found */
915 while ((c = pgetc()) != '\n' && c != PEOF);
919 if (pgetc() == '\n') {
920 startlinno = ++plinno;
930 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
933 needprompt = doprompt;
938 if (pgetc_linecont() == '&')
943 if (pgetc_linecont() == '|')
948 c = pgetc_linecont();
965 #define MAXNEST_static 8
968 const char *syntax; /* *SYNTAX */
969 int parenlevel; /* levels of parentheses in arithmetic */
970 enum tokenstate_category
973 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
974 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
981 * Check to see whether we are at the end of the here document. When this
982 * is called, c is set to the first character of the next input line. If
983 * we are at the end of the here document, this routine sets the c to PEOF.
984 * The new value of c is returned.
988 checkend(int c, const char *eofmark, int striptabs)
998 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
1000 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
1004 needprompt = doprompt;
1008 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
1010 } else if (c == '\n' && *eofmark == '\0') {
1013 needprompt = doprompt;
1020 * Parse a redirection operator. The variable "out" points to a string
1021 * specifying the fd to be redirected. The variable "c" contains the
1022 * first character of the redirection operator.
1026 parseredir(char *out, int c)
1031 np = (union node *)stalloc(sizeof (struct nfile));
1034 c = pgetc_linecont();
1040 np->type = NCLOBBER;
1045 } else { /* c == '<' */
1047 c = pgetc_linecont();
1049 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1050 np = (union node *)stalloc(sizeof (struct nhere));
1054 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1056 if ((c = pgetc_linecont()) == '-') {
1057 heredoc->striptabs = 1;
1059 heredoc->striptabs = 0;
1062 } else if (c == '&')
1072 np->nfile.fd = digit_val(fd);
1077 * Called to parse command substitutions.
1081 parsebackq(char *out, struct nodelist **pbqlist,
1082 int oldstyle, int dblquote, int quoted)
1084 struct nodelist **nlpp;
1087 struct jmploc jmploc;
1088 struct jmploc *const savehandler = handler;
1091 const int bq_startlinno = plinno;
1092 char *volatile ostr = NULL;
1093 struct parsefile *const savetopfile = getcurrentfile();
1094 struct heredoc *const saveheredoclist = heredoclist;
1095 struct heredoc *here;
1098 if (setjmp(jmploc.loc)) {
1099 popfilesupto(savetopfile);
1104 heredoclist = saveheredoclist;
1105 handler = savehandler;
1106 if (exception == EXERROR) {
1107 startlinno = bq_startlinno;
1108 synerror("Error in command substitution");
1110 longjmp(handler->loc, 1);
1113 savelen = out - stackblock();
1115 str = ckmalloc(savelen);
1116 memcpy(str, stackblock(), savelen);
1122 /* We must read until the closing backquote, giving special
1123 treatment to some slashes, and then push the string and
1124 reread it as input, interpreting it normally. */
1130 STARTSTACKSTR(oout);
1136 CHECKSTRSPACE(2, oout);
1137 c = pgetc_linecont();
1143 if (c != '\\' && c != '`' && c != '$'
1144 && (!dblquote || c != '"'))
1145 USTPUTC('\\', oout);
1150 needprompt = doprompt;
1154 startlinno = plinno;
1155 synerror("EOF in backquote substitution");
1163 USTPUTC('\0', oout);
1164 olen = oout - stackblock();
1166 ostr = ckmalloc(olen);
1167 memcpy(ostr, stackblock(), olen);
1168 setinputstring(ostr, 1);
1173 nlpp = &(*nlpp)->next;
1174 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1175 (*nlpp)->next = NULL;
1178 saveprompt = doprompt;
1185 if (peektoken() != TEOF)
1187 doprompt = saveprompt;
1194 * Start reading from old file again, ignoring any pushed back
1195 * tokens left from the backquote parsing
1201 CHECKSTRSPACE(savelen + 1, out);
1204 memcpy(out, str, savelen);
1205 STADJUST(savelen, out);
1213 here = saveheredoclist;
1215 while (here->next != NULL)
1217 here->next = heredoclist;
1218 heredoclist = saveheredoclist;
1220 handler = savehandler;
1223 USTPUTC(CTLBACKQ | CTLQUOTE, out);
1225 USTPUTC(CTLBACKQ, out);
1231 * Called to parse a backslash escape sequence inside $'...'.
1232 * The backslash has already been read.
1235 readcstyleesc(char *out)
1243 synerror("Unterminated quoted string");
1256 case 'a': v = '\a'; break;
1257 case 'b': v = '\b'; break;
1258 case 'e': v = '\033'; break;
1259 case 'f': v = '\f'; break;
1260 case 'n': v = '\n'; break;
1261 case 'r': v = '\r'; break;
1262 case 't': v = '\t'; break;
1263 case 'v': v = '\v'; break;
1268 if (c >= '0' && c <= '9')
1269 v = (v << 4) + c - '0';
1270 else if (c >= 'A' && c <= 'F')
1271 v = (v << 4) + c - 'A' + 10;
1272 else if (c >= 'a' && c <= 'f')
1273 v = (v << 4) + c - 'a' + 10;
1279 case '0': case '1': case '2': case '3':
1280 case '4': case '5': case '6': case '7':
1283 if (c >= '0' && c <= '7') {
1287 if (c >= '0' && c <= '7') {
1297 if (c < 0x3f || c > 0x7a || c == 0x60)
1298 synerror("Bad escape sequence");
1299 if (c == '\\' && pgetc() != '\\')
1300 synerror("Bad escape sequence");
1308 n = c == 'U' ? 8 : 4;
1310 for (i = 0; i < n; i++) {
1312 if (c >= '0' && c <= '9')
1313 v = (v << 4) + c - '0';
1314 else if (c >= 'A' && c <= 'F')
1315 v = (v << 4) + c - 'A' + 10;
1316 else if (c >= 'a' && c <= 'f')
1317 v = (v << 4) + c - 'a' + 10;
1319 synerror("Bad escape sequence");
1321 if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1322 synerror("Bad escape sequence");
1323 /* We really need iconv here. */
1324 if (initial_localeisutf8 && v > 127) {
1325 CHECKSTRSPACE(4, out);
1327 * We cannot use wctomb() as the locale may have
1331 USTPUTC(0xc0 | v >> 6, out);
1332 USTPUTC(0x80 | (v & 0x3f), out);
1334 } else if (v <= 0xffff) {
1335 USTPUTC(0xe0 | v >> 12, out);
1336 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1337 USTPUTC(0x80 | (v & 0x3f), out);
1339 } else if (v <= 0x10ffff) {
1340 USTPUTC(0xf0 | v >> 18, out);
1341 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1342 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1343 USTPUTC(0x80 | (v & 0x3f), out);
1351 synerror("Bad escape sequence");
1355 * We can't handle NUL bytes.
1356 * POSIX says we should skip till the closing quote.
1359 while ((c = pgetc()) != '\'') {
1363 synerror("Unterminated quoted string");
1375 if (SQSYNTAX[vc] == CCTL)
1376 USTPUTC(CTLESC, out);
1383 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1384 * is not NULL, read a here document. In the latter case, eofmark is the
1385 * word which marks the end of the document and striptabs is true if
1386 * leading tabs should be stripped from the document. The argument firstc
1387 * is the first character of the input token or document.
1389 * Because C does not have internal subroutines, I have simulated them
1390 * using goto's to implement the subroutine linkage. The following macros
1391 * will run code that appears at the end of readtoken1.
1394 #define PARSESUB() {goto parsesub; parsesub_return:;}
1395 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1398 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1404 struct nodelist *bqlist;
1409 struct tokenstate state_static[MAXNEST_static];
1410 int maxnest = MAXNEST_static;
1411 struct tokenstate *state = state_static;
1414 startlinno = plinno;
1419 state[level].syntax = initialsyntax;
1420 state[level].parenlevel = 0;
1421 state[level].category = TSTATE_TOP;
1424 loop: { /* for each line, until end of word */
1425 if (eofmark && eofmark != NOEOFMARK)
1426 /* set c to PEOF if at end of here document */
1427 c = checkend(c, eofmark, striptabs);
1428 for (;;) { /* until end of line or end of word */
1429 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
1431 synentry = state[level].syntax[c];
1434 case CNL: /* '\n' */
1436 goto endword; /* exit outer loop */
1446 goto loop; /* continue outer loop */
1449 out = readcstyleesc(out);
1457 if (eofmark == NULL || initialsyntax != SQSYNTAX)
1458 USTPUTC(CTLESC, out);
1461 case CBACK: /* backslash */
1466 } else if (c == '\n') {
1473 if (state[level].syntax == DQSYNTAX &&
1474 c != '\\' && c != '`' && c != '$' &&
1475 (c != '"' || (eofmark != NULL &&
1476 newvarnest == 0)) &&
1477 (c != '}' || state[level].category != TSTATE_VAR_OLD))
1479 if ((eofmark == NULL ||
1481 state[level].syntax == BASESYNTAX)
1482 USTPUTC(CTLQUOTEMARK, out);
1483 if (SQSYNTAX[c] == CCTL)
1484 USTPUTC(CTLESC, out);
1486 if ((eofmark == NULL ||
1488 state[level].syntax == BASESYNTAX &&
1489 state[level].category == TSTATE_VAR_OLD)
1490 USTPUTC(CTLQUOTEEND, out);
1495 USTPUTC(CTLQUOTEMARK, out);
1496 state[level].syntax = SQSYNTAX;
1500 USTPUTC(CTLQUOTEMARK, out);
1501 state[level].syntax = DQSYNTAX;
1504 if (eofmark != NULL && newvarnest == 0)
1507 if (state[level].category == TSTATE_VAR_OLD)
1508 USTPUTC(CTLQUOTEEND, out);
1509 state[level].syntax = BASESYNTAX;
1513 case CVAR: /* '$' */
1514 PARSESUB(); /* parse substitution */
1516 case CENDVAR: /* '}' */
1518 ((state[level].category == TSTATE_VAR_OLD &&
1519 state[level].syntax ==
1520 state[level - 1].syntax) ||
1521 (state[level].category == TSTATE_VAR_NEW &&
1522 state[level].syntax == BASESYNTAX))) {
1523 if (state[level].category == TSTATE_VAR_NEW)
1526 USTPUTC(CTLENDVAR, out);
1531 case CLP: /* '(' in arithmetic */
1532 state[level].parenlevel++;
1535 case CRP: /* ')' in arithmetic */
1536 if (state[level].parenlevel > 0) {
1538 --state[level].parenlevel;
1540 if (pgetc_linecont() == ')') {
1542 state[level].category == TSTATE_ARITH) {
1544 USTPUTC(CTLENDARI, out);
1550 * (don't 2nd guess - no error)
1557 case CBQUOTE: /* '`' */
1558 out = parsebackq(out, &bqlist, 1,
1559 state[level].syntax == DQSYNTAX &&
1560 (eofmark == NULL || newvarnest > 0),
1561 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1564 goto endword; /* exit outer loop */
1569 goto endword; /* exit outer loop */
1576 if (state[level].syntax == ARISYNTAX)
1577 synerror("Missing '))'");
1578 if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1579 synerror("Unterminated quoted string");
1580 if (state[level].category == TSTATE_VAR_OLD ||
1581 state[level].category == TSTATE_VAR_NEW) {
1582 startlinno = plinno;
1583 synerror("Missing '}'");
1585 if (state != state_static)
1586 parser_temp_free_upto(state);
1588 len = out - stackblock();
1590 if (eofmark == NULL) {
1591 if ((c == '>' || c == '<')
1594 && (*out == '\0' || is_digit(*out))) {
1596 return lasttoken = TREDIR;
1602 backquotelist = bqlist;
1603 grabstackblock(len);
1605 return lasttoken = TWORD;
1606 /* end of readtoken routine */
1610 * Parse a substitution. At this point, we have read the dollar sign
1619 static const char types[] = "}-+?=";
1624 c = pgetc_linecont();
1625 if (c == '(') { /* $(command) or $((arith)) */
1626 if (pgetc_linecont() == '(') {
1630 out = parsebackq(out, &bqlist, 0,
1631 state[level].syntax == DQSYNTAX &&
1632 (eofmark == NULL || newvarnest > 0),
1633 state[level].syntax == DQSYNTAX ||
1634 state[level].syntax == ARISYNTAX);
1636 } else if (c == '{' || is_name(c) || is_special(c)) {
1637 USTPUTC(CTLVAR, out);
1638 typeloc = out - stackblock();
1639 USTPUTC(VSNORMAL, out);
1643 c = pgetc_linecont();
1647 if (!is_eof(c) && is_name(c)) {
1651 c = pgetc_linecont();
1653 } while (!is_eof(c) && is_in_name(c));
1655 strncmp(out - length, "LINENO", length) == 0) {
1656 /* Replace the variable name with the
1657 * current line number. */
1659 CHECKSTRSPACE(11, out);
1662 linno -= funclinno - 1;
1663 length = snprintf(out, 11, "%d", linno);
1669 } else if (is_digit(c)) {
1670 if (subtype != VSNORMAL) {
1673 c = pgetc_linecont();
1674 } while (is_digit(c));
1677 c = pgetc_linecont();
1679 } else if (is_special(c)) {
1681 c = pgetc_linecont();
1682 if (subtype == 0 && c1 == '#') {
1684 if (strchr(types, c) == NULL && c != ':' &&
1685 c != '#' && c != '%')
1688 c = pgetc_linecont();
1689 if (c1 != '}' && c == '}') {
1704 else if (c == '\n' || c == PEOF)
1705 synerror("Unexpected end of line in substitution");
1706 else if (BASESYNTAX[c] != CCTL)
1713 c = pgetc_linecont();
1716 p = strchr(types, c);
1718 if (c == '\n' || c == PEOF)
1719 synerror("Unexpected end of line in substitution");
1722 if (BASESYNTAX[c] != CCTL)
1726 subtype = p - types + VSNORMAL;
1732 subtype = c == '#' ? VSTRIMLEFT :
1734 c = pgetc_linecont();
1742 } else if (subtype != VSERROR) {
1743 if (subtype == VSLENGTH && c != '}')
1748 if (state[level].syntax == DQSYNTAX ||
1749 state[level].syntax == ARISYNTAX)
1751 *(stackblock() + typeloc) = subtype | flags;
1752 if (subtype != VSNORMAL) {
1753 if (level + 1 >= maxnest) {
1755 if (state == state_static) {
1756 state = parser_temp_alloc(
1757 maxnest * sizeof(*state));
1758 memcpy(state, state_static,
1759 MAXNEST_static * sizeof(*state));
1761 state = parser_temp_realloc(state,
1762 maxnest * sizeof(*state));
1765 state[level].parenlevel = 0;
1766 if (subtype == VSMINUS || subtype == VSPLUS ||
1767 subtype == VSQUESTION || subtype == VSASSIGN) {
1769 * For operators that were in the Bourne shell,
1770 * inherit the double-quote state.
1772 state[level].syntax = state[level - 1].syntax;
1773 state[level].category = TSTATE_VAR_OLD;
1776 * The other operators take a pattern,
1777 * so go to BASESYNTAX.
1778 * Also, ' and " are now special, even
1779 * in here documents.
1781 state[level].syntax = BASESYNTAX;
1782 state[level].category = TSTATE_VAR_NEW;
1786 } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1787 /* $'cstylequotes' */
1788 USTPUTC(CTLQUOTEMARK, out);
1789 state[level].syntax = SQSYNTAX;
1795 goto parsesub_return;
1800 * Parse an arithmetic expansion (indicate start of one and set state)
1804 if (level + 1 >= maxnest) {
1806 if (state == state_static) {
1807 state = parser_temp_alloc(
1808 maxnest * sizeof(*state));
1809 memcpy(state, state_static,
1810 MAXNEST_static * sizeof(*state));
1812 state = parser_temp_realloc(state,
1813 maxnest * sizeof(*state));
1816 state[level].syntax = ARISYNTAX;
1817 state[level].parenlevel = 0;
1818 state[level].category = TSTATE_ARITH;
1819 USTPUTC(CTLARI, out);
1820 if (state[level - 1].syntax == DQSYNTAX)
1824 goto parsearith_return;
1827 } /* end of readtoken */
1831 * Returns true if the text contains nothing to expand (no dollar signs
1836 noexpand(char *text)
1842 while ((c = *p++) != '\0') {
1843 if ( c == CTLQUOTEMARK)
1847 else if (BASESYNTAX[(int)c] == CCTL)
1855 * Return true if the argument is a legal variable name (a letter or
1856 * underscore followed by zero or more letters, underscores, and digits).
1860 goodname(const char *name)
1868 if (! is_in_name(*p))
1876 isassignment(const char *p)
1884 else if (!is_in_name(*p))
1892 consumetoken(int token)
1894 if (readtoken() != token)
1900 * Called when an unexpected token is read during the parse. The argument
1901 * is the token that is expected, or -1 if more than one type of token can
1902 * occur at this point.
1906 synexpect(int token)
1911 fmtstr(msg, 64, "%s unexpected (expecting %s)",
1912 tokname[lasttoken], tokname[token]);
1914 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1921 synerror(const char *msg)
1924 outfmt(out2, "%s: %d: ", commandname, startlinno);
1926 outfmt(out2, "%s: ", arg0);
1927 outfmt(out2, "Syntax error: %s\n", msg);
1928 error((char *)NULL);
1932 setprompt(int which)
1934 whichprompt = which;
1942 out2str(getprompt(NULL));
1948 pgetc_linecont(void)
1952 while ((c = pgetc_macro()) == '\\') {
1962 /* Allow the backslash to be pushed back. */
1963 pushstring("\\", 1, NULL);
1971 static struct passwd *
1980 return (getpwnam(login));
1985 getusername(char *name, size_t namelen)
1987 static char cached_name[MAXLOGNAME];
1991 if (cached_name[0] == '\0') {
1995 * Handle the case when there is more than one
1996 * login with the same UID, or when the login
1997 * returned by getlogin(2) does no longer match
2001 if (pw == NULL || pw->pw_uid != euid)
2002 pw = getpwuid(euid);
2005 strlcpy(cached_name, pw->pw_name,
2006 sizeof(cached_name));
2008 snprintf(cached_name, sizeof(cached_name),
2013 strlcpy(name, cached_name, namelen);
2018 * called by editline -- any expansions to the prompt
2019 * should be added here.
2022 getprompt(void *unused __unused)
2024 static char ps[PROMPTLEN];
2030 static char internal_error[] = "??";
2033 * Select prompt format.
2035 switch (whichprompt) {
2046 return internal_error;
2050 * Format prompt string.
2052 for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++) {
2061 * Non-printing sequence begin and end.
2069 * Literal \ and some ASCII characters:
2080 else if (*fmt == 'e')
2082 else if (*fmt == 'r')
2092 if (i < PROMPTLEN - 3) {
2099 * Print the current time as per provided strftime format.
2102 char tfmt[128] = "%X"; /* \D{} means %X. */
2105 if (fmt[1] != '{') {
2107 * "\D" but not "\D{", so treat the '\'
2108 * literally and rewind fmt to treat 'D'
2109 * literally next iteration.
2115 fmt += 2; /* Consume "D{". */
2116 if (fmt[0] != '}') {
2119 end = memccpy(tfmt, fmt, '}', sizeof(tfmt));
2122 * Format too long or no '}', so
2123 * ignore "\D{" altogether.
2124 * The loop will do i++, but nothing
2125 * was written to ps, so do i-- here.
2126 * Rewind fmt for similar reason.
2132 *--end = '\0'; /* Ignore the copy of '}'. */
2135 now = localtime(&(time_t){time(NULL)});
2136 i += strftime(&ps[i], PROMPTLEN - i - 1, tfmt, now);
2137 i--; /* The loop will do i++. */
2144 * \h specifies just the local hostname,
2145 * \H specifies fully-qualified hostname.
2150 gethostname(&ps[i], PROMPTLEN - i - 1);
2151 ps[PROMPTLEN - 1] = '\0';
2152 /* Skip to end of hostname. */
2153 trim = (*fmt == 'h') ? '.' : '\0';
2154 while ((ps[i] != '\0') && (ps[i] != trim))
2164 getusername(&ps[i], PROMPTLEN - i);
2165 /* Skip to end of username. */
2166 while (ps[i + 1] != '\0')
2171 * Working directory.
2173 * \W specifies just the final component,
2174 * \w specifies the entire path.
2178 pwd = lookupvar("PWD");
2179 if (pwd == NULL || *pwd == '\0')
2182 *pwd == '/' && pwd[1] != '\0')
2183 strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2186 home = lookupvar("HOME");
2188 homelen = strlen(home);
2190 strcmp(home, "/") != 0 &&
2191 strncmp(pwd, home, homelen) == 0 &&
2192 (pwd[homelen] == '/' ||
2193 pwd[homelen] == '\0')) {
2194 strlcpy(&ps[i], "~",
2200 strlcpy(&ps[i], pwd, PROMPTLEN - i);
2203 /* Skip to end of path. */
2204 while (ps[i + 1] != '\0')
2211 * '$' for normal users, '#' for root.
2214 ps[i] = (geteuid() != 0) ? '$' : '#';
2218 * Emit unrecognized formats verbatim.
2222 if (i < PROMPTLEN - 2)
2234 expandstr(const char *ps)
2237 struct jmploc jmploc;
2238 struct jmploc *const savehandler = handler;
2239 const int saveprompt = doprompt;
2240 struct parsefile *const savetopfile = getcurrentfile();
2241 struct parser_temp *const saveparser_temp = parser_temp;
2242 const char *result = NULL;
2244 if (!setjmp(jmploc.loc)) {
2247 setinputstring(ps, 1);
2249 readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
2250 if (backquotelist != NULL)
2251 error("Command substitution not allowed here");
2255 n.narg.text = wordtext;
2256 n.narg.backquote = backquotelist;
2258 expandarg(&n, NULL, 0);
2259 result = stackblock();
2262 handler = savehandler;
2263 doprompt = saveprompt;
2264 popfilesupto(savetopfile);
2265 if (parser_temp != saveparser_temp) {
2266 parser_temp_free_all();
2267 parser_temp = saveparser_temp;
2269 if (result != NULL) {
2271 } else if (exception == EXINT)