aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

parser.c (60031B)


      1 /* -
      2  * spdx-license-identifier: bsd-3-clause
      3  *
      4  * copyright (c) 1991, 1993
      5  * the regents of the university of california. all rights reserved
      6  *
      7  * this code is derived from software contributed to berkeley by
      8  * kenneth almquist
      9  *
     10  * redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. redistributions of source code must retain the above copyright
     14  * notice, this list of conditions and the following disclaimer
     15  * 2. redistributions in binary form must reproduce the above copyright
     16  * notice, this list of conditions and the following disclaimer in the
     17  * documentation and/or other materials provided with the distribution
     18  * 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
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE
     25  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE
     33  */
     34 
     35 #if FEATURE_SH_EXT
     36 #ifndef _DEFAULT_SOURCE
     37 #define _DEFAULT_SOURCE
     38 #endif
     39 #ifndef _GNU_SOURCE
     40 #define _GNU_SOURCE
     41 #endif
     42 #endif
     43 #include <pwd.h>
     44 #include <stdio.h>
     45 #include <stdlib.h>
     46 #include <sys/param.h>
     47 #include <time.h>
     48 #include <unistd.h>
     49 
     50 #include "shell.h"
     51 
     52 #undef strlcpy
     53 #define strlcpy xstrlcpy
     54 size_t xstrlcpy(char *, const char *, size_t);
     55 
     56 #include "alias.h"
     57 #include "error.h"
     58 #include "eval.h"
     59 #include "exec.h"   /* to check for special builtins */
     60 #include "expand.h" /* defines rmescapes() */
     61 #include "input.h"
     62 #include "jobs.h"
     63 #include "main.h"
     64 #include "memalloc.h"
     65 #include "mystring.h"
     66 #include "nodes.h"
     67 #include "options.h"
     68 #include "output.h"
     69 #include "parser.h"
     70 #include "show.h"
     71 #include "syntax.h"
     72 #include "var.h"
     73 #ifndef NO_HISTORY
     74 #include "lineedit.h"
     75 #endif
     76 
     77 /*
     78  * shell command parser
     79  */
     80 
     81 #define PROMPTLEN 192
     82 
     83 /* values of checkkwd variable */
     84 #define CHKALIAS 0x1
     85 #define CHKKWD   0x2
     86 #define CHKNL    0x4
     87 
     88 /* values returned by readtoken */
     89 #include "token.h"
     90 
     91 struct heredoc {
     92   struct heredoc *next;      /* next here document in list */
     93   union node     *here;      /* redirection node */
     94   char           *eofmark;   /* string indicating end of input */
     95   int             striptabs; /* if set, strip leading tabs */
     96 };
     97 
     98 struct parser_temp {
     99   struct parser_temp *next;
    100   void               *data;
    101 };
    102 
    103 static struct heredoc     *heredoclist; /* list of here documents to read */
    104 static int                 doprompt;    /* if set, prompt the user */
    105 static int                 needprompt;  /* true if interactive and at start of line */
    106 static int                 lasttoken;   /* last token read */
    107 static int                 tokpushback; /* last token pushed back */
    108 static char               *wordtext;    /* text of last word returned by readtoken */
    109 static int                 checkkwd;
    110 static struct nodelist    *backquotelist;
    111 static union node         *redirnode;
    112 static struct heredoc     *heredoc;
    113 static int                 quoteflag;  /* set if (part of) last token was quoted */
    114 static int                 startlinno; /* line # where last token started */
    115 static int                 funclinno;  /* line # where the current function started */
    116 static struct parser_temp *parser_temp;
    117 
    118 #define NOEOFMARK ((const char *)&heredoclist)
    119 
    120 static union node *list(int);
    121 static union node *andor(void);
    122 static union node *pipeline(void);
    123 static union node *command(void);
    124 static union node *simplecmd(union node **, union node *);
    125 static union node *makename(void);
    126 static union node *makebinary(int type, union node *n1, union node *n2);
    127 static void        parsefname(void);
    128 static void        parseheredoc(void);
    129 static int         peektoken(void);
    130 static int         readtoken(void);
    131 static int         xxreadtoken(void);
    132 static int         readtoken1(int, const char *, const char *, int);
    133 static int         noexpand(char *);
    134 static void        consumetoken(int);
    135 static void        synexpect(int) __dead2;
    136 static void        synerror(const char *) __dead2;
    137 static void        setprompt(int);
    138 static int         pgetc_linecont(void);
    139 static void        getusername(char *, size_t);
    140 
    141 static void *
    142 parser_temp_alloc(size_t len)
    143 {
    144   struct parser_temp *t;
    145 
    146   INTOFF;
    147   t           = ckmalloc(sizeof(*t));
    148   t->data     = NULL;
    149   t->next     = parser_temp;
    150   parser_temp = t;
    151   t->data     = ckmalloc(len);
    152   INTON;
    153   return t->data;
    154 }
    155 
    156 static void *
    157 parser_temp_realloc(void *ptr, size_t len)
    158 {
    159   struct parser_temp *t;
    160 
    161   INTOFF;
    162   t = parser_temp;
    163   if (ptr != t->data)
    164     error("bug: parser_temp_realloc misused");
    165   t->data = ckrealloc(t->data, len);
    166   INTON;
    167   return t->data;
    168 }
    169 
    170 static void
    171 parser_temp_free_upto(void *ptr)
    172 {
    173   struct parser_temp *t;
    174   int                 done = 0;
    175 
    176   INTOFF;
    177   while (parser_temp != NULL && !done) {
    178     t           = parser_temp;
    179     parser_temp = t->next;
    180     done        = t->data == ptr;
    181     ckfree(t->data);
    182     ckfree(t);
    183   }
    184   INTON;
    185   if (!done)
    186     error("bug: parser_temp_free_upto misused");
    187 }
    188 
    189 static void
    190 parser_temp_free_all(void)
    191 {
    192   struct parser_temp *t;
    193 
    194   INTOFF;
    195   while (parser_temp != NULL) {
    196     t           = parser_temp;
    197     parser_temp = t->next;
    198     ckfree(t->data);
    199     ckfree(t);
    200   }
    201   INTON;
    202 }
    203 
    204 /*
    205  * read and parse a command. returns NEOF on end of file. (NULL is a
    206  * valid parse tree indicating a blank line.)
    207  */
    208 
    209 union node *
    210 parsecmd(int interact)
    211 {
    212   int t;
    213 
    214   /* this assumes the parser is not re-entered,
    215    * which could happen if we add command substitution on PS1/PS2
    216    */
    217   parser_temp_free_all();
    218   heredoclist = NULL;
    219 
    220   tokpushback = 0;
    221   checkkwd    = 0;
    222   doprompt    = interact;
    223   if (doprompt)
    224     setprompt(1);
    225   else
    226     setprompt(0);
    227   needprompt = 0;
    228   t          = readtoken();
    229   if (t == TEOF)
    230     return NEOF;
    231   if (t == TNL)
    232     return NULL;
    233   tokpushback++;
    234   return list(1);
    235 }
    236 
    237 /*
    238  * read and parse words for wordexp
    239  * returns a list of NARG nodes; NULL if there are no words
    240  */
    241 union node *
    242 parsewordexp(void)
    243 {
    244   union node *n, *first = NULL, **pnext;
    245   int         t;
    246 
    247   /* this assumes the parser is not re-entered,
    248    * which could happen if we add command substitution on PS1/PS2
    249    */
    250   parser_temp_free_all();
    251   heredoclist = NULL;
    252 
    253   tokpushback = 0;
    254   checkkwd    = 0;
    255   doprompt    = 0;
    256   setprompt(0);
    257   needprompt = 0;
    258   pnext      = &first;
    259   while ((t = readtoken()) != TEOF) {
    260     if (t != TWORD)
    261       synexpect(TWORD);
    262     n      = makename();
    263     *pnext = n;
    264     pnext  = &n->narg.next;
    265   }
    266   return first;
    267 }
    268 
    269 static union node *
    270 list(int nlflag)
    271 {
    272   union node *ntop, *n1, *n2, *n3;
    273   int         tok;
    274 
    275   checkkwd = CHKNL | CHKKWD | CHKALIAS;
    276   if (!nlflag && tokendlist[peektoken()])
    277     return NULL;
    278   ntop = n1 = NULL;
    279   for (;;) {
    280     n2  = andor();
    281     tok = readtoken();
    282     if (tok == TBACKGND) {
    283       if (n2 != NULL && n2->type == NPIPE) {
    284         n2->npipe.backgnd = 1;
    285       } else if (n2 != NULL && n2->type == NREDIR) {
    286         n2->type = NBACKGND;
    287       } else {
    288         n3                  = (union node *)stalloc(sizeof(struct nredir));
    289         n3->type            = NBACKGND;
    290         n3->nredir.n        = n2;
    291         n3->nredir.redirect = NULL;
    292         n2                  = n3;
    293       }
    294     }
    295     if (ntop == NULL)
    296       ntop = n2;
    297     else if (n1 == NULL) {
    298       n1   = makebinary(NSEMI, ntop, n2);
    299       ntop = n1;
    300     } else {
    301       n3              = makebinary(NSEMI, n1->nbinary.ch2, n2);
    302       n1->nbinary.ch2 = n3;
    303       n1              = n3;
    304     }
    305     switch (tok) {
    306       case TBACKGND:
    307       case TSEMI:
    308         tok = readtoken();
    309         /* FALLTHROUGH */
    310       case TNL:
    311         if (tok == TNL) {
    312           parseheredoc();
    313           if (nlflag)
    314             return ntop;
    315         } else if (tok == TEOF && nlflag) {
    316           parseheredoc();
    317           return ntop;
    318         } else {
    319           tokpushback++;
    320         }
    321         checkkwd = CHKNL | CHKKWD | CHKALIAS;
    322         if (!nlflag && tokendlist[peektoken()])
    323           return ntop;
    324         break;
    325       case TEOF:
    326         if (heredoclist)
    327           parseheredoc();
    328         else
    329           pungetc(); /* push back EOF on input */
    330         return ntop;
    331       default:
    332         if (nlflag)
    333           synexpect(-1);
    334         tokpushback++;
    335         return ntop;
    336     }
    337   }
    338 }
    339 
    340 static union node *
    341 andor(void)
    342 {
    343   union node *n;
    344   int         t;
    345 
    346   n = pipeline();
    347   for (;;) {
    348     if ((t = readtoken()) == TAND) {
    349       t = NAND;
    350     } else if (t == TOR) {
    351       t = NOR;
    352     } else {
    353       tokpushback++;
    354       return n;
    355     }
    356     n = makebinary(t, n, pipeline());
    357   }
    358 }
    359 
    360 static union node *
    361 pipeline(void)
    362 {
    363   union node      *n1, *n2, *pipenode;
    364   struct nodelist *lp, *prev;
    365   int              negate, t;
    366 
    367   negate   = 0;
    368   checkkwd = CHKNL | CHKKWD | CHKALIAS;
    369   TRACE(("pipeline: entered\n"));
    370   while (readtoken() == TNOT)
    371     negate = !negate;
    372   tokpushback++;
    373   n1 = command();
    374   if (readtoken() == TPIPE) {
    375     pipenode                = (union node *)stalloc(sizeof(struct npipe));
    376     pipenode->type          = NPIPE;
    377     pipenode->npipe.backgnd = 0;
    378     lp                      = (struct nodelist *)stalloc(sizeof(struct nodelist));
    379     pipenode->npipe.cmdlist = lp;
    380     lp->n                   = n1;
    381     do {
    382       prev     = lp;
    383       lp       = (struct nodelist *)stalloc(sizeof(struct nodelist));
    384       checkkwd = CHKNL | CHKKWD | CHKALIAS;
    385       t        = readtoken();
    386       tokpushback++;
    387       if (t == TNOT)
    388         lp->n = pipeline();
    389       else
    390         lp->n = command();
    391       prev->next = lp;
    392     } while (readtoken() == TPIPE);
    393     lp->next = NULL;
    394     n1       = pipenode;
    395   }
    396   tokpushback++;
    397   if (negate) {
    398     n2           = (union node *)stalloc(sizeof(struct nnot));
    399     n2->type     = NNOT;
    400     n2->nnot.com = n1;
    401     return n2;
    402   } else
    403     return n1;
    404 }
    405 
    406 static union node *
    407 command(void)
    408 {
    409   union node *n1, *n2;
    410   union node *ap, **app;
    411   union node *cp, **cpp;
    412   union node *redir, **rpp;
    413   int         t;
    414   int         is_subshell;
    415 
    416   checkkwd    = CHKNL | CHKKWD | CHKALIAS;
    417   is_subshell = 0;
    418   redir       = NULL;
    419   n1          = NULL;
    420   rpp         = &redir;
    421 
    422   /* check for redirection which may precede command */
    423   while (readtoken() == TREDIR) {
    424     *rpp = n2 = redirnode;
    425     rpp       = &n2->nfile.next;
    426     parsefname();
    427   }
    428   tokpushback++;
    429 
    430   switch (readtoken()) {
    431     case TIF:
    432       n1       = (union node *)stalloc(sizeof(struct nif));
    433       n1->type = NIF;
    434       if ((n1->nif.test = list(0)) == NULL)
    435         synexpect(-1);
    436       consumetoken(TTHEN);
    437       n1->nif.ifpart = list(0);
    438       n2             = n1;
    439       while (readtoken() == TELIF) {
    440         n2->nif.elsepart = (union node *)stalloc(sizeof(struct nif));
    441         n2               = n2->nif.elsepart;
    442         n2->type         = NIF;
    443         if ((n2->nif.test = list(0)) == NULL)
    444           synexpect(-1);
    445         consumetoken(TTHEN);
    446         n2->nif.ifpart = list(0);
    447       }
    448       if (lasttoken == TELSE)
    449         n2->nif.elsepart = list(0);
    450       else {
    451         n2->nif.elsepart = NULL;
    452         tokpushback++;
    453       }
    454       consumetoken(TFI);
    455       checkkwd = CHKKWD | CHKALIAS;
    456       break;
    457     case TWHILE:
    458     case TUNTIL:
    459       t = lasttoken;
    460       if ((n1 = list(0)) == NULL)
    461         synexpect(-1);
    462       consumetoken(TDO);
    463       n1 = makebinary((t == TWHILE) ? NWHILE : NUNTIL, n1, list(0));
    464       consumetoken(TDONE);
    465       checkkwd = CHKKWD | CHKALIAS;
    466       break;
    467     case TFOR:
    468       if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
    469         synerror("Bad for loop variable");
    470       n1           = (union node *)stalloc(sizeof(struct nfor));
    471       n1->type     = NFOR;
    472       n1->nfor.var = wordtext;
    473       checkkwd     = CHKNL;
    474       if (readtoken() == TWORD && !quoteflag && equal(wordtext, "in")) {
    475         app = &ap;
    476         while (readtoken() == TWORD) {
    477           n2   = makename();
    478           *app = n2;
    479           app  = &n2->narg.next;
    480         }
    481         *app          = NULL;
    482         n1->nfor.args = ap;
    483         if (lasttoken == TNL)
    484           tokpushback++;
    485         else if (lasttoken != TSEMI)
    486           synexpect(-1);
    487       } else {
    488         static char argvars[5] = {CTLVAR, (char)(VSNORMAL | VSQUOTE), '@', '=', '\0'};
    489         n2                     = (union node *)stalloc(sizeof(struct narg));
    490         n2->type               = NARG;
    491         n2->narg.text          = argvars;
    492         n2->narg.backquote     = NULL;
    493         n2->narg.next          = NULL;
    494         n1->nfor.args          = n2;
    495         /*
    496          * newline or semicolon here is optional (but note
    497          * that the original bourne shell only allowed NL)
    498          */
    499         if (lasttoken != TSEMI)
    500           tokpushback++;
    501       }
    502       checkkwd = CHKNL | CHKKWD | CHKALIAS;
    503       if ((t = readtoken()) == TDO)
    504         t = TDONE;
    505       else if (t == TBEGIN)
    506         t = TEND;
    507       else
    508         synexpect(-1);
    509       n1->nfor.body = list(0);
    510       consumetoken(t);
    511       checkkwd = CHKKWD | CHKALIAS;
    512       break;
    513     case TCASE:
    514       n1       = (union node *)stalloc(sizeof(struct ncase));
    515       n1->type = NCASE;
    516       consumetoken(TWORD);
    517       n1->ncase.expr = makename();
    518       checkkwd       = CHKNL;
    519       if (readtoken() != TWORD || !equal(wordtext, "in"))
    520         synerror("expecting \"in\"");
    521       cpp      = &n1->ncase.cases;
    522       checkkwd = CHKNL | CHKKWD, readtoken();
    523       while (lasttoken != TESAC) {
    524         *cpp = cp = (union node *)stalloc(sizeof(struct nclist));
    525         cp->type  = NCLIST;
    526         app       = &cp->nclist.pattern;
    527         if (lasttoken == TLP)
    528           readtoken();
    529         for (;;) {
    530           *app = ap = makename();
    531           checkkwd  = CHKNL | CHKKWD;
    532           if (readtoken() != TPIPE)
    533             break;
    534           app = &ap->narg.next;
    535           readtoken();
    536         }
    537         ap->narg.next = NULL;
    538         if (lasttoken != TRP)
    539           synexpect(TRP);
    540         cp->nclist.body = list(0);
    541 
    542         checkkwd = CHKNL | CHKKWD | CHKALIAS;
    543         if ((t = readtoken()) != TESAC) {
    544           if (t == TENDCASE)
    545             ;
    546           else if (t == TFALLTHRU)
    547             cp->type = NCLISTFALLTHRU;
    548           else
    549             synexpect(TENDCASE);
    550           checkkwd = CHKNL | CHKKWD, readtoken();
    551         }
    552         cpp = &cp->nclist.next;
    553       }
    554       *cpp     = NULL;
    555       checkkwd = CHKKWD | CHKALIAS;
    556       break;
    557     case TLP:
    558       n1                  = (union node *)stalloc(sizeof(struct nredir));
    559       n1->type            = NSUBSHELL;
    560       n1->nredir.n        = list(0);
    561       n1->nredir.redirect = NULL;
    562       consumetoken(TRP);
    563       checkkwd    = CHKKWD | CHKALIAS;
    564       is_subshell = 1;
    565       break;
    566     case TBEGIN:
    567       n1 = list(0);
    568       consumetoken(TEND);
    569       checkkwd = CHKKWD | CHKALIAS;
    570       break;
    571     /* a simple command must have at least one redirection or word */
    572     case TBACKGND:
    573     case TSEMI:
    574     case TAND:
    575     case TOR:
    576     case TPIPE:
    577     case TENDCASE:
    578     case TFALLTHRU:
    579     case TEOF:
    580     case TNL:
    581     case TRP:
    582       if (!redir)
    583         synexpect(-1);
    584       /* fallthrough */
    585     case TWORD:
    586       tokpushback++;
    587       n1 = simplecmd(rpp, redir);
    588       return n1;
    589     default:
    590       synexpect(-1);
    591   }
    592 
    593   /* now check for redirection which may follow command */
    594   while (readtoken() == TREDIR) {
    595     *rpp = n2 = redirnode;
    596     rpp       = &n2->nfile.next;
    597     parsefname();
    598   }
    599   tokpushback++;
    600   *rpp = NULL;
    601   if (redir) {
    602     if (!is_subshell) {
    603       n2           = (union node *)stalloc(sizeof(struct nredir));
    604       n2->type     = NREDIR;
    605       n2->nredir.n = n1;
    606       n1           = n2;
    607     }
    608     n1->nredir.redirect = redir;
    609   }
    610 
    611   return n1;
    612 }
    613 
    614 static union node *
    615 simplecmd(union node **rpp, union node *redir)
    616 {
    617   union node  *args, **app;
    618   union node **orig_rpp = rpp;
    619   union node  *n        = NULL;
    620   int          special;
    621   int          savecheckkwd;
    622 
    623   /* if we dont have any redirections already, then we must reset */
    624   /* rpp to be the address of the local redir variable */
    625   if (redir == NULL)
    626     rpp = &redir;
    627 
    628   args = NULL;
    629   app  = &args;
    630   /*
    631    * we save the incoming value, because we need this for shell
    632    * functions. there can not be a redirect or an argument between
    633    * the function name and the open parenthesis
    634    */
    635   orig_rpp = rpp;
    636 
    637   savecheckkwd = CHKALIAS;
    638 
    639   for (;;) {
    640     checkkwd = savecheckkwd;
    641     if (readtoken() == TWORD) {
    642       n    = makename();
    643       *app = n;
    644       app  = &n->narg.next;
    645       if (savecheckkwd != 0 && !isassignment(wordtext))
    646         savecheckkwd = 0;
    647     } else if (lasttoken == TREDIR) {
    648       *rpp = n = redirnode;
    649       rpp      = &n->nfile.next;
    650       parsefname(); /* read name of redirection file */
    651     } else if (lasttoken == TLP && app == &args->narg.next && rpp == orig_rpp) {
    652       /* we have a function */
    653       consumetoken(TRP);
    654       funclinno = plinno;
    655       /*
    656        * - require plain text
    657        * - functions with '/' cannot be called
    658        * - reject name=()
    659        * - reject ksh extended glob patterns
    660        */
    661       if (!noexpand(n->narg.text) || quoteflag || strchr(n->narg.text, '/')
    662           || strchr("!%*+-=?@}~", n->narg.text[strlen(n->narg.text) - 1]))
    663         synerror("Bad function name");
    664       rmescapes(n->narg.text);
    665       if (find_builtin(n->narg.text, &special) >= 0 && special)
    666         synerror(
    667             "Cannot override a special builtin "
    668             "with a function"
    669         );
    670       n->type      = NDEFUN;
    671       n->narg.next = command();
    672       funclinno    = 0;
    673       return n;
    674     } else {
    675       tokpushback++;
    676       break;
    677     }
    678   }
    679   *app             = NULL;
    680   *rpp             = NULL;
    681   n                = (union node *)stalloc(sizeof(struct ncmd));
    682   n->type          = NCMD;
    683   n->ncmd.args     = args;
    684   n->ncmd.redirect = redir;
    685   return n;
    686 }
    687 
    688 static union node *
    689 makename(void)
    690 {
    691   union node *n;
    692 
    693   n                 = (union node *)stalloc(sizeof(struct narg));
    694   n->type           = NARG;
    695   n->narg.next      = NULL;
    696   n->narg.text      = wordtext;
    697   n->narg.backquote = backquotelist;
    698   return n;
    699 }
    700 
    701 static union node *
    702 makebinary(int type, union node *n1, union node *n2)
    703 {
    704   union node *n;
    705 
    706   n              = (union node *)stalloc(sizeof(struct nbinary));
    707   n->type        = type;
    708   n->nbinary.ch1 = n1;
    709   n->nbinary.ch2 = n2;
    710   return (n);
    711 }
    712 
    713 void
    714 forcealias(void)
    715 {
    716   checkkwd |= CHKALIAS;
    717 }
    718 
    719 void
    720 fixredir(union node *n, const char *text, int err)
    721 {
    722   TRACE(("Fix redir %s %d\n", text, err));
    723   if (!err)
    724     n->ndup.vname = NULL;
    725 
    726   if (is_digit(text[0]) && text[1] == '\0')
    727     n->ndup.dupfd = digit_val(text[0]);
    728   else if (text[0] == '-' && text[1] == '\0')
    729     n->ndup.dupfd = -1;
    730   else {
    731     if (err)
    732       synerror("Bad fd number");
    733     else
    734       n->ndup.vname = makename();
    735   }
    736 }
    737 
    738 static void
    739 parsefname(void)
    740 {
    741   union node *n = redirnode;
    742 
    743   consumetoken(TWORD);
    744   if (n->type == NHERE) {
    745     struct heredoc *here = heredoc;
    746     struct heredoc *p;
    747 
    748     if (quoteflag == 0)
    749       n->type = NXHERE;
    750     TRACE(("Here document %d\n", n->type));
    751     if (here->striptabs) {
    752       while (*wordtext == '\t')
    753         wordtext++;
    754     }
    755     if (!noexpand(wordtext))
    756       synerror("Illegal eof marker for << redirection");
    757     rmescapes(wordtext);
    758     here->eofmark = wordtext;
    759     here->next    = NULL;
    760     if (heredoclist == NULL)
    761       heredoclist = here;
    762     else {
    763       for (p = heredoclist; p->next; p = p->next)
    764         ;
    765       p->next = here;
    766     }
    767   } else if (n->type == NTOFD || n->type == NFROMFD) {
    768     fixredir(n, wordtext, 0);
    769   } else {
    770     n->nfile.fname = makename();
    771   }
    772 }
    773 
    774 /*
    775  * input any here documents
    776  */
    777 
    778 static void
    779 parseheredoc(void)
    780 {
    781   struct heredoc *here;
    782   union node     *n;
    783 
    784   while (heredoclist) {
    785     here        = heredoclist;
    786     heredoclist = here->next;
    787     if (needprompt) {
    788       setprompt(2);
    789       needprompt = 0;
    790     }
    791     readtoken1(
    792         pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX, here->eofmark, here->striptabs
    793     );
    794     n                     = makename();
    795     here->here->nhere.doc = n;
    796   }
    797 }
    798 
    799 static int
    800 peektoken(void)
    801 {
    802   int t;
    803 
    804   t = readtoken();
    805   tokpushback++;
    806   return (t);
    807 }
    808 
    809 static int
    810 readtoken(void)
    811 {
    812   int           t;
    813   struct alias *ap;
    814 #ifdef DEBUG
    815   int alreadyseen = tokpushback;
    816 #endif
    817 
    818 top:
    819   t = xxreadtoken();
    820 
    821   /*
    822    * eat newlines
    823    */
    824   if (checkkwd & CHKNL) {
    825     while (t == TNL) {
    826       parseheredoc();
    827       t = xxreadtoken();
    828     }
    829   }
    830 
    831   /*
    832    * check for keywords and aliases
    833    */
    834   if (t == TWORD && !quoteflag) {
    835     const char *const *pp;
    836 
    837     if (checkkwd & CHKKWD)
    838       for (pp = parsekwd; *pp; pp++) {
    839         if (**pp == *wordtext && equal(*pp, wordtext)) {
    840           lasttoken = t = pp - parsekwd + KWDOFFSET;
    841           TRACE(("keyword %s recognized\n", tokname[t]));
    842           goto out;
    843         }
    844       }
    845     if (checkkwd & CHKALIAS && (ap = lookupalias(wordtext, 1)) != NULL) {
    846       pushstring(ap->val, strlen(ap->val), ap);
    847       goto top;
    848     }
    849   }
    850 out:
    851   if (t != TNOT)
    852     checkkwd = 0;
    853 
    854 #ifdef DEBUG
    855   if (!alreadyseen)
    856     TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
    857   else
    858     TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
    859 #endif
    860   return (t);
    861 }
    862 
    863 /*
    864  * read the next input token
    865  * if the token is a word, we set backquotelist to the list of cmds in
    866  * backquotes. we set quoteflag to true if any part of the word was
    867  * quoted
    868  * if the token is TREDIR, then we set redirnode to a structure containing
    869  * the redirection
    870  * in all cases, the variable startlinno is set to the number of the line
    871  * on which the token starts
    872  *
    873  * [change comment: here documents and internal procedures]
    874  * [readtoken shouldnt have any arguments. perhaps we should make the
    875  * word parsing code into a separate routine. in this case, readtoken
    876  * doesnt need to have any internal procedures, but parseword does
    877  * we could also make parseoperator in essence the main routine, and
    878  * have parseword (readtoken1?) handle both words and redirection.]
    879  */
    880 
    881 #define RETURN(token) return lasttoken = token
    882 
    883 static int
    884 xxreadtoken(void)
    885 {
    886   int c;
    887 
    888   if (tokpushback) {
    889     tokpushback = 0;
    890     return lasttoken;
    891   }
    892   if (needprompt) {
    893     setprompt(2);
    894     needprompt = 0;
    895   }
    896   startlinno = plinno;
    897   for (;;) { /* until token or start of word found */
    898     c = pgetc_macro();
    899     switch (c) {
    900       case ' ':
    901       case '\t':
    902         continue;
    903       case '#':
    904         while ((c = pgetc()) != '\n' && c != PEOF)
    905           ;
    906         pungetc();
    907         continue;
    908       case '\\':
    909         if (pgetc() == '\n') {
    910           startlinno = ++plinno;
    911           if (doprompt)
    912             setprompt(2);
    913           else
    914             setprompt(0);
    915           continue;
    916         }
    917         pungetc();
    918         /* FALLTHROUGH */
    919       default:
    920         return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
    921       case '\n':
    922         plinno++;
    923         needprompt = doprompt;
    924         RETURN(TNL);
    925       case PEOF:
    926         RETURN(TEOF);
    927       case '&':
    928         if (pgetc_linecont() == '&')
    929           RETURN(TAND);
    930         pungetc();
    931         RETURN(TBACKGND);
    932       case '|':
    933         if (pgetc_linecont() == '|')
    934           RETURN(TOR);
    935         pungetc();
    936         RETURN(TPIPE);
    937       case ';':
    938         c = pgetc_linecont();
    939         if (c == ';')
    940           RETURN(TENDCASE);
    941         else if (c == '&')
    942           RETURN(TFALLTHRU);
    943         pungetc();
    944         RETURN(TSEMI);
    945       case '(':
    946         RETURN(TLP);
    947       case ')':
    948         RETURN(TRP);
    949     }
    950   }
    951 #undef RETURN
    952 }
    953 
    954 #define MAXNEST_static 8
    955 struct tokenstate {
    956   const char *syntax;     /* *SYNTAX */
    957   int         parenlevel; /* levels of parentheses in arithmetic */
    958   enum tokenstate_category {
    959     TSTATE_TOP,
    960     TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
    961     TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
    962     TSTATE_ARITH
    963   } category;
    964 };
    965 
    966 /*
    967  * check to see whether we are at the end of the here document. when this
    968  * is called, c is set to the first character of the next input line. if
    969  * we are at the end of the here document, this routine sets the c to PEOF
    970  * the new value of c is returned
    971  */
    972 
    973 static int
    974 checkend(int c, const char *eofmark, int striptabs)
    975 {
    976   if (striptabs) {
    977     while (c == '\t')
    978       c = pgetc();
    979   }
    980   if (c == *eofmark) {
    981     int         c2;
    982     const char *q;
    983 
    984     for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
    985       ;
    986     if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
    987       c = PEOF;
    988       if (c2 == '\n') {
    989         plinno++;
    990         needprompt = doprompt;
    991       }
    992     } else {
    993       pungetc();
    994       pushstring(eofmark + 1, q - (eofmark + 1), NULL);
    995     }
    996   } else if (c == '\n' && *eofmark == '\0') {
    997     c = PEOF;
    998     plinno++;
    999     needprompt = doprompt;
   1000   }
   1001   return (c);
   1002 }
   1003 
   1004 /*
   1005  * parse a redirection operator. the variable "out" points to a string
   1006  * specifying the fd to be redirected. the variable "c" contains the
   1007  * first character of the redirection operator
   1008  */
   1009 
   1010 static void
   1011 parseredir(char *out, int c)
   1012 {
   1013   char        fd = *out;
   1014   union node *np;
   1015 
   1016   np = (union node *)stalloc(sizeof(struct nfile));
   1017   if (c == '>') {
   1018     np->nfile.fd = 1;
   1019     c            = pgetc_linecont();
   1020     if (c == '>')
   1021       np->type = NAPPEND;
   1022     else if (c == '&')
   1023       np->type = NTOFD;
   1024     else if (c == '|')
   1025       np->type = NCLOBBER;
   1026     else {
   1027       np->type = NTO;
   1028       pungetc();
   1029     }
   1030   } else { /* c == '<' */
   1031     np->nfile.fd = 0;
   1032     c            = pgetc_linecont();
   1033     if (c == '<') {
   1034       if (sizeof(struct nfile) != sizeof(struct nhere)) {
   1035         np           = (union node *)stalloc(sizeof(struct nhere));
   1036         np->nfile.fd = 0;
   1037       }
   1038       np->type      = NHERE;
   1039       heredoc       = (struct heredoc *)stalloc(sizeof(struct heredoc));
   1040       heredoc->here = np;
   1041       if ((c = pgetc_linecont()) == '-') {
   1042         heredoc->striptabs = 1;
   1043       } else {
   1044         heredoc->striptabs = 0;
   1045         pungetc();
   1046       }
   1047     } else if (c == '&')
   1048       np->type = NFROMFD;
   1049     else if (c == '>')
   1050       np->type = NFROMTO;
   1051     else {
   1052       np->type = NFROM;
   1053       pungetc();
   1054     }
   1055   }
   1056   if (fd != '\0')
   1057     np->nfile.fd = digit_val(fd);
   1058   redirnode = np;
   1059 }
   1060 
   1061 /*
   1062  * called to parse command substitutions
   1063  */
   1064 
   1065 static char *
   1066 parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int quoted)
   1067 {
   1068   struct nodelist **nlpp;
   1069   union node       *n;
   1070   char *volatile str;
   1071   struct jmploc        jmploc;
   1072   struct jmploc *const savehandler = handler;
   1073   size_t               savelen;
   1074   int                  saveprompt;
   1075   const int            bq_startlinno      = plinno;
   1076   char *volatile ostr                     = NULL;
   1077   struct parsefile *const savetopfile     = getcurrentfile();
   1078   struct heredoc *const   saveheredoclist = heredoclist;
   1079   struct heredoc         *here;
   1080 
   1081   str = NULL;
   1082   if (setjmp(jmploc.loc)) {
   1083     popfilesupto(savetopfile);
   1084     if (str)
   1085       ckfree(str);
   1086     if (ostr)
   1087       ckfree(ostr);
   1088     heredoclist = saveheredoclist;
   1089     handler     = savehandler;
   1090     if (exception == EXERROR) {
   1091       startlinno = bq_startlinno;
   1092       synerror("Error in command substitution");
   1093     }
   1094     longjmp(handler->loc, 1);
   1095   }
   1096   INTOFF;
   1097   savelen = out - stackblock();
   1098   if (savelen > 0) {
   1099     str = ckmalloc(savelen);
   1100     memcpy(str, stackblock(), savelen);
   1101   }
   1102   handler     = &jmploc;
   1103   heredoclist = NULL;
   1104   INTON;
   1105   if (oldstyle) {
   1106     /* we must read until the closing backquote, giving special
   1107      * treatment to some slashes, and then push the string and
   1108      * reread it as input, interpreting it normally */
   1109     char *oout;
   1110     int   c;
   1111     int   olen;
   1112 
   1113     STARTSTACKSTR(oout);
   1114     for (;;) {
   1115       if (needprompt) {
   1116         setprompt(2);
   1117         needprompt = 0;
   1118       }
   1119       CHECKSTRSPACE(2, oout);
   1120       c = pgetc_linecont();
   1121       if (c == '`')
   1122         break;
   1123       switch (c) {
   1124         case '\\':
   1125           c = pgetc();
   1126           if (c != '\\' && c != '`' && c != '$' && (!dblquote || c != '"'))
   1127             USTPUTC('\\', oout);
   1128           break;
   1129 
   1130         case '\n':
   1131           plinno++;
   1132           needprompt = doprompt;
   1133           break;
   1134 
   1135         case PEOF:
   1136           startlinno = plinno;
   1137           synerror("EOF in backquote substitution");
   1138           break;
   1139 
   1140         default:
   1141           break;
   1142       }
   1143       USTPUTC(c, oout);
   1144     }
   1145     USTPUTC('\0', oout);
   1146     olen = oout - stackblock();
   1147     INTOFF;
   1148     ostr = ckmalloc(olen);
   1149     memcpy(ostr, stackblock(), olen);
   1150     setinputstring(ostr);
   1151     INTON;
   1152   }
   1153   nlpp = pbqlist;
   1154   while (*nlpp)
   1155     nlpp = &(*nlpp)->next;
   1156   *nlpp         = (struct nodelist *)stalloc(sizeof(struct nodelist));
   1157   (*nlpp)->next = NULL;
   1158 
   1159   if (oldstyle) {
   1160     saveprompt = doprompt;
   1161     doprompt   = 0;
   1162   }
   1163 
   1164   n = list(0);
   1165 
   1166   if (oldstyle) {
   1167     if (peektoken() != TEOF)
   1168       synexpect(-1);
   1169     doprompt = saveprompt;
   1170   } else
   1171     consumetoken(TRP);
   1172 
   1173   (*nlpp)->n = n;
   1174   if (oldstyle) {
   1175     /*
   1176      * start reading from old file again, ignoring any pushed back
   1177      * tokens left from the backquote parsing
   1178      */
   1179     popfile();
   1180     tokpushback = 0;
   1181   }
   1182   STARTSTACKSTR(out);
   1183   CHECKSTRSPACE(savelen + 1, out);
   1184   INTOFF;
   1185   if (str) {
   1186     memcpy(out, str, savelen);
   1187     STADJUST(savelen, out);
   1188     ckfree(str);
   1189     str = NULL;
   1190   }
   1191   if (ostr) {
   1192     ckfree(ostr);
   1193     ostr = NULL;
   1194   }
   1195   here = saveheredoclist;
   1196   if (here != NULL) {
   1197     while (here->next != NULL)
   1198       here = here->next;
   1199     here->next  = heredoclist;
   1200     heredoclist = saveheredoclist;
   1201   }
   1202   handler = savehandler;
   1203   INTON;
   1204   if (quoted)
   1205     USTPUTC(CTLBACKQ | CTLQUOTE, out);
   1206   else
   1207     USTPUTC(CTLBACKQ, out);
   1208   return out;
   1209 }
   1210 
   1211 /*
   1212  * called to parse a backslash escape sequence inside $'...'
   1213  * the backslash has already been read
   1214  */
   1215 static char *
   1216 readcstyleesc(char *out)
   1217 {
   1218   int          c, vc, i, n;
   1219   unsigned int v;
   1220 
   1221   c = pgetc();
   1222   switch (c) {
   1223     case '\0':
   1224       synerror("Unterminated quoted string");
   1225     case '\n':
   1226       plinno++;
   1227       if (doprompt)
   1228         setprompt(2);
   1229       else
   1230         setprompt(0);
   1231       return out;
   1232     case '\\':
   1233     case '\'':
   1234     case '"':
   1235       v = c;
   1236       break;
   1237     case 'a':
   1238       v = '\a';
   1239       break;
   1240     case 'b':
   1241       v = '\b';
   1242       break;
   1243     case 'e':
   1244       v = '\033';
   1245       break;
   1246     case 'f':
   1247       v = '\f';
   1248       break;
   1249     case 'n':
   1250       v = '\n';
   1251       break;
   1252     case 'r':
   1253       v = '\r';
   1254       break;
   1255     case 't':
   1256       v = '\t';
   1257       break;
   1258     case 'v':
   1259       v = '\v';
   1260       break;
   1261     case 'x':
   1262       v = 0;
   1263       for (;;) {
   1264         c = pgetc();
   1265         if (c >= '0' && c <= '9')
   1266           v = (v << 4) + c - '0';
   1267         else if (c >= 'A' && c <= 'F')
   1268           v = (v << 4) + c - 'A' + 10;
   1269         else if (c >= 'a' && c <= 'f')
   1270           v = (v << 4) + c - 'a' + 10;
   1271         else
   1272           break;
   1273       }
   1274       pungetc();
   1275       break;
   1276     case '0':
   1277     case '1':
   1278     case '2':
   1279     case '3':
   1280     case '4':
   1281     case '5':
   1282     case '6':
   1283     case '7':
   1284       v = c - '0';
   1285       c = pgetc();
   1286       if (c >= '0' && c <= '7') {
   1287         v <<= 3;
   1288         v += c - '0';
   1289         c = pgetc();
   1290         if (c >= '0' && c <= '7') {
   1291           v <<= 3;
   1292           v += c - '0';
   1293         } else
   1294           pungetc();
   1295       } else
   1296         pungetc();
   1297       break;
   1298     case 'c':
   1299       c = pgetc();
   1300       if (c < 0x3f || c > 0x7a || c == 0x60)
   1301         synerror("Bad escape sequence");
   1302       if (c == '\\' && pgetc() != '\\')
   1303         synerror("Bad escape sequence");
   1304       if (c == '?')
   1305         v = 127;
   1306       else
   1307         v = c & 0x1f;
   1308       break;
   1309     case 'u':
   1310     case 'U':
   1311       n = c == 'U' ? 8 : 4;
   1312       v = 0;
   1313       for (i = 0; i < n; i++) {
   1314         c = pgetc();
   1315         if (c >= '0' && c <= '9')
   1316           v = (v << 4) + c - '0';
   1317         else if (c >= 'A' && c <= 'F')
   1318           v = (v << 4) + c - 'A' + 10;
   1319         else if (c >= 'a' && c <= 'f')
   1320           v = (v << 4) + c - 'a' + 10;
   1321         else
   1322           synerror("Bad escape sequence");
   1323       }
   1324       if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
   1325         synerror("Bad escape sequence");
   1326       /* we really need iconv here */
   1327       if (initial_localeisutf8 && v > 127) {
   1328         CHECKSTRSPACE(4, out);
   1329         /*
   1330          * we cannot use wctomb() as the locale may have
   1331          * changed
   1332          */
   1333         if (v <= 0x7ff) {
   1334           USTPUTC(0xc0 | v >> 6, out);
   1335           USTPUTC(0x80 | (v & 0x3f), out);
   1336           return out;
   1337         } else if (v <= 0xffff) {
   1338           USTPUTC(0xe0 | v >> 12, out);
   1339           USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
   1340           USTPUTC(0x80 | (v & 0x3f), out);
   1341           return out;
   1342         } else if (v <= 0x10ffff) {
   1343           USTPUTC(0xf0 | v >> 18, out);
   1344           USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
   1345           USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
   1346           USTPUTC(0x80 | (v & 0x3f), out);
   1347           return out;
   1348         }
   1349       }
   1350       if (v > 127)
   1351         v = '?';
   1352       break;
   1353     default:
   1354       synerror("Bad escape sequence");
   1355   }
   1356   vc = (char)v;
   1357   /*
   1358    * we cant handle NUL bytes
   1359    * POSIX says we should skip till the closing quote
   1360    */
   1361   if (vc == '\0') {
   1362     while ((c = pgetc()) != '\'') {
   1363       if (c == '\\')
   1364         c = pgetc();
   1365       if (c == PEOF)
   1366         synerror("Unterminated quoted string");
   1367       if (c == '\n') {
   1368         plinno++;
   1369         if (doprompt)
   1370           setprompt(2);
   1371         else
   1372           setprompt(0);
   1373       }
   1374     }
   1375     pungetc();
   1376     return out;
   1377   }
   1378   if (SQSYNTAX[vc] == CCTL)
   1379     USTPUTC(CTLESC, out);
   1380   USTPUTC(vc, out);
   1381   return out;
   1382 }
   1383 
   1384 /*
   1385  * if eofmark is NULL, read a word or a redirection symbol. if eofmark
   1386  * is not NULL, read a here document. in the latter case, eofmark is the
   1387  * word which marks the end of the document and striptabs is true if
   1388  * leading tabs should be stripped from the document. the argument firstc
   1389  * is the first character of the input token or document
   1390  *
   1391  * because c does not have internal subroutines, i have simulated them
   1392  * using goto's to implement the subroutine linkage. the following macros
   1393  * will run code that appears at the end of readtoken1
   1394  */
   1395 
   1396 #define PARSESUB()                                                                                 \
   1397   {                                                                                                \
   1398     goto parsesub;                                                                                 \
   1399   parsesub_return:;                                                                                \
   1400   }
   1401 #define PARSEARITH()                                                                               \
   1402   {                                                                                                \
   1403     goto parsearith;                                                                               \
   1404   parsearith_return:;                                                                              \
   1405   }
   1406 
   1407 static int
   1408 readtoken1(int firstc, char const *initialsyntax, const char *eofmark, int striptabs)
   1409 {
   1410   int                c = firstc;
   1411   char              *out;
   1412   int                len;
   1413   struct nodelist   *bqlist;
   1414   int                quotef;
   1415   int                newvarnest;
   1416   int                level;
   1417   int                synentry;
   1418   struct tokenstate  state_static[MAXNEST_static];
   1419   int                maxnest    = MAXNEST_static;
   1420   struct tokenstate *state      = state_static;
   1421   int                sqiscstyle = 0;
   1422 
   1423   startlinno              = plinno;
   1424   quotef                  = 0;
   1425   bqlist                  = NULL;
   1426   newvarnest              = 0;
   1427   level                   = 0;
   1428   state[level].syntax     = initialsyntax;
   1429   state[level].parenlevel = 0;
   1430   state[level].category   = TSTATE_TOP;
   1431 
   1432   STARTSTACKSTR(out);
   1433 loop:
   1434   { /* for each line, until end of word */
   1435     if (eofmark && eofmark != NOEOFMARK)
   1436       /* set c to PEOF if at end of here document */
   1437       c = checkend(c, eofmark, striptabs);
   1438     for (;;) {               /* until end of line or end of word */
   1439       CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
   1440 
   1441       synentry = state[level].syntax[c];
   1442 
   1443       switch (synentry) {
   1444         case CNL: /* '\n' */
   1445           if (level == 0)
   1446             goto endword; /* exit outer loop */
   1447                           /* FALLTHROUGH */
   1448         case CQNL:
   1449           USTPUTC(c, out);
   1450           plinno++;
   1451           if (doprompt)
   1452             setprompt(2);
   1453           else
   1454             setprompt(0);
   1455           c = pgetc();
   1456           goto loop; /* continue outer loop */
   1457         case CSBACK:
   1458           if (sqiscstyle) {
   1459             out = readcstyleesc(out);
   1460             break;
   1461           }
   1462           /* FALLTHROUGH */
   1463         case CWORD:
   1464           USTPUTC(c, out);
   1465           break;
   1466         case CCTL:
   1467           if (eofmark == NULL || initialsyntax != SQSYNTAX)
   1468             USTPUTC(CTLESC, out);
   1469           USTPUTC(c, out);
   1470           break;
   1471         case CBACK: /* backslash */
   1472           c = pgetc();
   1473           if (c == PEOF) {
   1474             USTPUTC('\\', out);
   1475             pungetc();
   1476           } else if (c == '\n') {
   1477             plinno++;
   1478             if (doprompt)
   1479               setprompt(2);
   1480             else
   1481               setprompt(0);
   1482           } else {
   1483             if (state[level].syntax == DQSYNTAX && c != '\\' && c != '`' && c != '$'
   1484                 && (c != '"' || (eofmark != NULL && newvarnest == 0))
   1485                 && (c != '}' || state[level].category != TSTATE_VAR_OLD))
   1486               USTPUTC('\\', out);
   1487             if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX)
   1488               USTPUTC(CTLQUOTEMARK, out);
   1489             if (SQSYNTAX[c] == CCTL)
   1490               USTPUTC(CTLESC, out);
   1491             USTPUTC(c, out);
   1492             if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX
   1493                 && state[level].category == TSTATE_VAR_OLD)
   1494               USTPUTC(CTLQUOTEEND, out);
   1495             quotef++;
   1496           }
   1497           break;
   1498         case CSQUOTE:
   1499           USTPUTC(CTLQUOTEMARK, out);
   1500           state[level].syntax = SQSYNTAX;
   1501           sqiscstyle          = 0;
   1502           break;
   1503         case CDQUOTE:
   1504           USTPUTC(CTLQUOTEMARK, out);
   1505           state[level].syntax = DQSYNTAX;
   1506           break;
   1507         case CENDQUOTE:
   1508           if (eofmark != NULL && newvarnest == 0)
   1509             USTPUTC(c, out);
   1510           else {
   1511             if (state[level].category == TSTATE_VAR_OLD)
   1512               USTPUTC(CTLQUOTEEND, out);
   1513             state[level].syntax = BASESYNTAX;
   1514             quotef++;
   1515           }
   1516           break;
   1517         case CVAR:    /* '$' */
   1518           PARSESUB(); /* parse substitution */
   1519           break;
   1520         case CENDVAR: /* '}' */
   1521           if (level > 0
   1522               && ((state[level].category == TSTATE_VAR_OLD
   1523                    && state[level].syntax == state[level - 1].syntax)
   1524                   || (state[level].category == TSTATE_VAR_NEW
   1525                       && state[level].syntax == BASESYNTAX))) {
   1526             if (state[level].category == TSTATE_VAR_NEW)
   1527               newvarnest--;
   1528             level--;
   1529             USTPUTC(CTLENDVAR, out);
   1530           } else {
   1531             USTPUTC(c, out);
   1532           }
   1533           break;
   1534         case CLP: /* '(' in arithmetic */
   1535           state[level].parenlevel++;
   1536           USTPUTC(c, out);
   1537           break;
   1538         case CRP: /* ')' in arithmetic */
   1539           if (state[level].parenlevel > 0) {
   1540             USTPUTC(c, out);
   1541             --state[level].parenlevel;
   1542           } else {
   1543             if (pgetc_linecont() == ')') {
   1544               if (level > 0 && state[level].category == TSTATE_ARITH) {
   1545                 level--;
   1546                 USTPUTC(CTLENDARI, out);
   1547               } else
   1548                 USTPUTC(')', out);
   1549             } else {
   1550               /*
   1551                * unbalanced parens
   1552                * (dont 2nd guess - no error)
   1553                */
   1554               pungetc();
   1555               USTPUTC(')', out);
   1556             }
   1557           }
   1558           break;
   1559         case CBQUOTE: /* '`' */
   1560           out = parsebackq(
   1561               out,
   1562               &bqlist,
   1563               1,
   1564               state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0),
   1565               state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX
   1566           );
   1567           break;
   1568         case CEOF:
   1569           goto endword; /* exit outer loop */
   1570         case CIGN:
   1571           break;
   1572         default:
   1573           if (level == 0)
   1574             goto endword; /* exit outer loop */
   1575           USTPUTC(c, out);
   1576       }
   1577       c = pgetc_macro();
   1578     }
   1579   }
   1580 endword:
   1581   if (state[level].syntax == ARISYNTAX)
   1582     synerror("Missing '))'");
   1583   if (state[level].syntax != BASESYNTAX && eofmark == NULL)
   1584     synerror("Unterminated quoted string");
   1585   if (state[level].category == TSTATE_VAR_OLD || state[level].category == TSTATE_VAR_NEW) {
   1586     startlinno = plinno;
   1587     synerror("Missing '}'");
   1588   }
   1589   if (state != state_static)
   1590     parser_temp_free_upto(state);
   1591   USTPUTC('\0', out);
   1592   len = out - stackblock();
   1593   out = stackblock();
   1594   if (eofmark == NULL) {
   1595     if ((c == '>' || c == '<') && quotef == 0 && len <= 2 && (*out == '\0' || is_digit(*out))) {
   1596       parseredir(out, c);
   1597       return lasttoken = TREDIR;
   1598     } else {
   1599       pungetc();
   1600     }
   1601   }
   1602   quoteflag     = quotef;
   1603   backquotelist = bqlist;
   1604   grabstackblock(len);
   1605   wordtext         = out;
   1606   return lasttoken = TWORD;
   1607   /* end of readtoken routine */
   1608 
   1609   /*
   1610    * parse a substitution. at this point, we have read the dollar sign
   1611    * and nothing else
   1612    */
   1613 
   1614 parsesub:
   1615   {
   1616     int               subtype;
   1617     int               typeloc;
   1618     int               flags;
   1619     char             *p;
   1620     static const char types[] = "}-+?=";
   1621     int               linno;
   1622     int               length;
   1623     int               c1;
   1624 
   1625     c = pgetc_linecont();
   1626     if (c == '(') { /* $(command) or $((arith)) */
   1627       if (pgetc_linecont() == '(') {
   1628         PARSEARITH();
   1629       } else {
   1630         pungetc();
   1631         out = parsebackq(
   1632             out,
   1633             &bqlist,
   1634             0,
   1635             state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0),
   1636             state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX
   1637         );
   1638       }
   1639     } else if (c == '{' || is_name(c) || is_special(c)) {
   1640       USTPUTC(CTLVAR, out);
   1641       typeloc = out - stackblock();
   1642       USTPUTC(VSNORMAL, out);
   1643       subtype = VSNORMAL;
   1644       flags   = 0;
   1645       if (c == '{') {
   1646         c       = pgetc_linecont();
   1647         subtype = 0;
   1648       }
   1649     varname:
   1650       if (!is_eof(c) && is_name(c)) {
   1651         length = 0;
   1652         do {
   1653           STPUTC(c, out);
   1654           c = pgetc_linecont();
   1655           length++;
   1656         } while (!is_eof(c) && is_in_name(c));
   1657         if (length == 6 && strncmp(out - length, "LINENO", length) == 0) {
   1658           /* replace the variable name with the
   1659            * current line number */
   1660           STADJUST(-6, out);
   1661           CHECKSTRSPACE(11, out);
   1662           linno = plinno;
   1663           if (funclinno != 0)
   1664             linno -= funclinno - 1;
   1665           length = snprintf(out, 11, "%d", linno);
   1666           if (length > 10)
   1667             length = 10;
   1668           out += length;
   1669           flags |= VSLINENO;
   1670         }
   1671       } else if (is_digit(c)) {
   1672         if (subtype != VSNORMAL) {
   1673           do {
   1674             STPUTC(c, out);
   1675             c = pgetc_linecont();
   1676           } while (is_digit(c));
   1677         } else {
   1678           USTPUTC(c, out);
   1679           c = pgetc_linecont();
   1680         }
   1681       } else if (is_special(c)) {
   1682         c1 = c;
   1683         c  = pgetc_linecont();
   1684         if (subtype == 0 && c1 == '#') {
   1685           subtype = VSLENGTH;
   1686           if (strchr(types, c) == NULL && c != ':' && c != '#' && c != '%')
   1687             goto varname;
   1688           c1 = c;
   1689           c  = pgetc_linecont();
   1690           if (c1 != '}' && c == '}') {
   1691             pungetc();
   1692             c = c1;
   1693             goto varname;
   1694           }
   1695           pungetc();
   1696           c       = c1;
   1697           c1      = '#';
   1698           subtype = 0;
   1699         }
   1700         USTPUTC(c1, out);
   1701       } else {
   1702         subtype = VSERROR;
   1703         if (c == '}')
   1704           pungetc();
   1705         else if (c == '\n' || c == PEOF)
   1706           synerror(
   1707               "Unexpected end of line in "
   1708               "substitution"
   1709           );
   1710         else if (BASESYNTAX[c] != CCTL)
   1711           USTPUTC(c, out);
   1712       }
   1713       if (subtype == 0) {
   1714         switch (c) {
   1715           case ':':
   1716             flags |= VSNUL;
   1717             c = pgetc_linecont();
   1718             /* FALLTHROUGH */
   1719           default:
   1720             p = strchr(types, c);
   1721             if (p == NULL) {
   1722               if (c == '\n' || c == PEOF)
   1723                 synerror(
   1724                     "Unexpected end of "
   1725                     "line in substitution"
   1726                 );
   1727               if (flags == VSNUL)
   1728                 STPUTC(':', out);
   1729               if (BASESYNTAX[c] != CCTL)
   1730                 STPUTC(c, out);
   1731               subtype = VSERROR;
   1732             } else
   1733               subtype = p - types + VSNORMAL;
   1734             break;
   1735           case '%':
   1736           case '#': {
   1737             int cc  = c;
   1738             subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
   1739             c       = pgetc_linecont();
   1740             if (c == cc)
   1741               subtype++;
   1742             else
   1743               pungetc();
   1744             break;
   1745           }
   1746         }
   1747       } else if (subtype != VSERROR) {
   1748         if (subtype == VSLENGTH && c != '}')
   1749           subtype = VSERROR;
   1750         pungetc();
   1751       }
   1752       STPUTC('=', out);
   1753       if (state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX)
   1754         flags |= VSQUOTE;
   1755       *(stackblock() + typeloc) = subtype | flags;
   1756       if (subtype != VSNORMAL) {
   1757         if (level + 1 >= maxnest) {
   1758           maxnest *= 2;
   1759           if (state == state_static) {
   1760             state = parser_temp_alloc(maxnest * sizeof(*state));
   1761             memcpy(state, state_static, MAXNEST_static * sizeof(*state));
   1762           } else
   1763             state = parser_temp_realloc(state, maxnest * sizeof(*state));
   1764         }
   1765         level++;
   1766         state[level].parenlevel = 0;
   1767         if (subtype == VSMINUS || subtype == VSPLUS || subtype == VSQUESTION
   1768             || subtype == VSASSIGN) {
   1769           /*
   1770            * for operators that were in the bourne shell,
   1771            * inherit the double-quote state
   1772            */
   1773           state[level].syntax   = state[level - 1].syntax;
   1774           state[level].category = TSTATE_VAR_OLD;
   1775         } else {
   1776           /*
   1777            * the other operators take a pattern,
   1778            * so go to BASESYNTAX
   1779            * also, ' and " are now special, even
   1780            * in here documents
   1781            */
   1782           state[level].syntax   = BASESYNTAX;
   1783           state[level].category = TSTATE_VAR_NEW;
   1784           newvarnest++;
   1785         }
   1786       }
   1787     } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
   1788       /* $'cstylequotes' */
   1789       USTPUTC(CTLQUOTEMARK, out);
   1790       state[level].syntax = SQSYNTAX;
   1791       sqiscstyle          = 1;
   1792     } else {
   1793       USTPUTC('$', out);
   1794       pungetc();
   1795     }
   1796     goto parsesub_return;
   1797   }
   1798 
   1799 /*
   1800  * parse an arithmetic expansion (indicate start of one and set state)
   1801  */
   1802 parsearith:
   1803   {
   1804     if (level + 1 >= maxnest) {
   1805       maxnest *= 2;
   1806       if (state == state_static) {
   1807         state = parser_temp_alloc(maxnest * sizeof(*state));
   1808         memcpy(state, state_static, MAXNEST_static * sizeof(*state));
   1809       } else
   1810         state = parser_temp_realloc(state, maxnest * sizeof(*state));
   1811     }
   1812     level++;
   1813     state[level].syntax     = ARISYNTAX;
   1814     state[level].parenlevel = 0;
   1815     state[level].category   = TSTATE_ARITH;
   1816     USTPUTC(CTLARI, out);
   1817     if (state[level - 1].syntax == DQSYNTAX)
   1818       USTPUTC('"', out);
   1819     else
   1820       USTPUTC(' ', out);
   1821     goto parsearith_return;
   1822   }
   1823 
   1824 } /* end of readtoken */
   1825 
   1826 /*
   1827  * returns true if the text contains nothing to expand (no dollar signs
   1828  * or backquotes)
   1829  */
   1830 
   1831 static int
   1832 noexpand(char *text)
   1833 {
   1834   char *p;
   1835   char  c;
   1836 
   1837   p = text;
   1838   while ((c = *p++) != '\0') {
   1839     if (c == CTLQUOTEMARK)
   1840       continue;
   1841     if (c == CTLESC)
   1842       p++;
   1843     else if (BASESYNTAX[(int)c] == CCTL)
   1844       return 0;
   1845   }
   1846   return 1;
   1847 }
   1848 
   1849 /*
   1850  * return true if the argument is a legal variable name (a letter or
   1851  * underscore followed by zero or more letters, underscores, and digits)
   1852  */
   1853 
   1854 int
   1855 goodname(const char *name)
   1856 {
   1857   const char *p;
   1858 
   1859   p = name;
   1860   if (!is_name(*p))
   1861     return 0;
   1862   while (*++p) {
   1863     if (!is_in_name(*p))
   1864       return 0;
   1865   }
   1866   return 1;
   1867 }
   1868 
   1869 int
   1870 isassignment(const char *p)
   1871 {
   1872   if (!is_name(*p))
   1873     return 0;
   1874   p++;
   1875   for (;;) {
   1876     if (*p == '=')
   1877       return 1;
   1878     else if (!is_in_name(*p))
   1879       return 0;
   1880     p++;
   1881   }
   1882 }
   1883 
   1884 static void
   1885 consumetoken(int token)
   1886 {
   1887   if (readtoken() != token)
   1888     synexpect(token);
   1889 }
   1890 
   1891 /*
   1892  * called when an unexpected token is read during the parse. the argument
   1893  * is the token that is expected, or -1 if more than one type of token can
   1894  * occur at this point
   1895  */
   1896 
   1897 static void
   1898 synexpect(int token)
   1899 {
   1900   char msg[64];
   1901 
   1902   if (token >= 0) {
   1903     fmtstr(msg, 64, "%s unexpected (expecting %s)", tokname[lasttoken], tokname[token]);
   1904   } else {
   1905     fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
   1906   }
   1907   synerror(msg);
   1908 }
   1909 
   1910 static void
   1911 synerror(const char *msg)
   1912 {
   1913   if (commandname)
   1914     outfmt(out2, "%s: %d: ", commandname, startlinno);
   1915   else if (arg0)
   1916     outfmt(out2, "%s: ", arg0);
   1917   outfmt(out2, "Syntax error: %s\n", msg);
   1918   error((char *)NULL);
   1919 }
   1920 
   1921 static void
   1922 setprompt(int which)
   1923 {
   1924   whichprompt = which;
   1925   if (which == 0)
   1926     return;
   1927 
   1928 #ifndef NO_HISTORY
   1929   if (!sh_history_enabled)
   1930 #endif
   1931   {
   1932     out2str(getprompt(NULL));
   1933     flushout(out2);
   1934   }
   1935 }
   1936 
   1937 static int
   1938 pgetc_linecont(void)
   1939 {
   1940   int c;
   1941 
   1942   while ((c = pgetc_macro()) == '\\') {
   1943     c = pgetc();
   1944     if (c == '\n') {
   1945       plinno++;
   1946       if (doprompt)
   1947         setprompt(2);
   1948       else
   1949         setprompt(0);
   1950     } else {
   1951       pungetc();
   1952       /* allow the backslash to be pushed back */
   1953       pushstring("\\", 1, NULL);
   1954       return (pgetc());
   1955     }
   1956   }
   1957   return (c);
   1958 }
   1959 
   1960 static struct passwd *
   1961 getpwlogin(void)
   1962 {
   1963   const char *login;
   1964 
   1965   login = getlogin();
   1966   if (login == NULL)
   1967     return (NULL);
   1968 
   1969   return (getpwnam(login));
   1970 }
   1971 
   1972 static void
   1973 getusername(char *name, size_t namelen)
   1974 {
   1975   static char    cached_name[MAXLOGNAME];
   1976   struct passwd *pw;
   1977   uid_t          euid;
   1978 
   1979   if (cached_name[0] == '\0') {
   1980     euid = geteuid();
   1981 
   1982     /*
   1983      * handle the case when there is more than one
   1984      * login with the same UID, or when the login
   1985      * returned by getlogin(2) does no longer match
   1986      * the current UID
   1987      */
   1988     pw = getpwlogin();
   1989     if (pw == NULL || pw->pw_uid != euid)
   1990       pw = getpwuid(euid);
   1991 
   1992     if (pw != NULL) {
   1993       strlcpy(cached_name, pw->pw_name, sizeof(cached_name));
   1994     } else {
   1995       snprintf(cached_name, sizeof(cached_name), "%u", euid);
   1996     }
   1997   }
   1998 
   1999   strlcpy(name, cached_name, namelen);
   2000 }
   2001 
   2002 /*
   2003  * called by editline, any expansions to the prompt
   2004  * should be added here
   2005  */
   2006 char *
   2007 getprompt(void *unused __unused)
   2008 {
   2009   static char ps[PROMPTLEN];
   2010   const char *fmt;
   2011   const char *home;
   2012   const char *pwd;
   2013   size_t      homelen;
   2014   int         i, trim;
   2015   static char internal_error[] = "??";
   2016 
   2017   /*
   2018    * select prompt format
   2019    */
   2020   switch (whichprompt) {
   2021     case 0:
   2022       fmt = "";
   2023       break;
   2024     case 1:
   2025       fmt = expandstr(ps1val());
   2026       if (fmt == NULL)
   2027         fmt = ps1val();
   2028       break;
   2029     case 2:
   2030       fmt = ps2val();
   2031       break;
   2032     default:
   2033       return internal_error;
   2034   }
   2035 
   2036   /*
   2037    * format prompt string
   2038    */
   2039   for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++) {
   2040     if (*fmt == '$') {
   2041       const char *varname_start, *varname_end, *value;
   2042       char        varname[256];
   2043       int         namelen, braced = 0;
   2044 
   2045       fmt++; /* skip the '$' */
   2046 
   2047       /* check for ${VAR} syntax */
   2048       if (*fmt == '{') {
   2049         braced = 1;
   2050         fmt++;
   2051       }
   2052 
   2053       varname_start = fmt;
   2054 
   2055       /* extract variable name */
   2056       if (is_digit(*fmt)) {
   2057         /* positional parameter: $0, $1, etc */
   2058         fmt++;
   2059         varname_end = fmt;
   2060       } else if (is_special(*fmt)) {
   2061         /* special parameter: $?, $!, $$, etc */
   2062         fmt++;
   2063         varname_end = fmt;
   2064       } else if (is_name(*fmt)) {
   2065         /* regular variable name */
   2066         do
   2067           fmt++;
   2068         while (is_in_name(*fmt));
   2069         varname_end = fmt;
   2070       } else {
   2071         /*
   2072          * not a valid variable reference
   2073          * output literal '$'
   2074          */
   2075         ps[i] = '$';
   2076         if (braced && i < PROMPTLEN - 2)
   2077           ps[++i] = '{';
   2078         fmt = varname_start - 1;
   2079         continue;
   2080       }
   2081 
   2082       namelen = varname_end - varname_start;
   2083       if (namelen == 0 || namelen >= (int)sizeof(varname)) {
   2084         /* invalid or too long, output literal */
   2085         ps[i] = '$';
   2086         fmt   = varname_start - 1;
   2087         continue;
   2088       }
   2089 
   2090       /* copy variable name */
   2091       memcpy(varname, varname_start, namelen);
   2092       varname[namelen] = '\0';
   2093 
   2094       /* handle closing brace for ${VAR} */
   2095       if (braced) {
   2096         if (*fmt == '}') {
   2097           fmt++;
   2098         } else {
   2099           /* missing closing brace, treat as
   2100            * literal */
   2101           ps[i] = '$';
   2102           if (i < PROMPTLEN - 2)
   2103             ps[++i] = '{';
   2104           fmt = varname_start - 1;
   2105           continue;
   2106         }
   2107       }
   2108 
   2109       /* look up the variable */
   2110       if (namelen == 1 && is_digit(*varname)) {
   2111         /* positional parameters - check digits FIRST */
   2112         int num = *varname - '0';
   2113         if (num == 0)
   2114           value = arg0 ? arg0 : "";
   2115         else if (num > 0 && num <= shellparam.nparam)
   2116           value = shellparam.p[num - 1];
   2117         else
   2118           value = "";
   2119       } else if (namelen == 1 && is_special(*varname)) {
   2120         /* special parameters */
   2121         char valbuf[20];
   2122         int  num;
   2123 
   2124         switch (*varname) {
   2125           case '$':
   2126             num = rootpid;
   2127             break;
   2128           case '?':
   2129             num = exitstatus;
   2130             break;
   2131           case '#':
   2132             num = shellparam.nparam;
   2133             break;
   2134           case '!':
   2135             num = backgndpidval();
   2136             break;
   2137           default:
   2138             num = 0;
   2139             break;
   2140         }
   2141         snprintf(valbuf, sizeof(valbuf), "%d", num);
   2142         value = valbuf;
   2143       } else {
   2144         /* regular variables */
   2145         value = lookupvar(varname);
   2146         if (value == NULL)
   2147           value = "";
   2148       }
   2149 
   2150       /* copy value to output, respecting buffer size */
   2151       while (*value != '\0' && i < PROMPTLEN - 1) {
   2152         ps[i++] = *value++;
   2153       }
   2154 
   2155       /*
   2156        * adjust fmt and i for the loop increment
   2157        * fmt will be incremented by the for loop,
   2158        * so position it one before where we want
   2159        */
   2160       fmt--;
   2161       i--;
   2162       continue;
   2163     } else if (*fmt != '\\') {
   2164       ps[i] = *fmt;
   2165       continue;
   2166     }
   2167 
   2168     switch (*++fmt) {
   2169       /*
   2170        * non-printing sequence begin and end
   2171        */
   2172       case '[':
   2173       case ']':
   2174         ps[i] = '\001';
   2175         break;
   2176 
   2177       /*
   2178        * literal \ and some ASCII characters:
   2179        * \a bel
   2180        * \e esc
   2181        * \r cr
   2182        */
   2183       case '\\':
   2184       case 'a':
   2185       case 'e':
   2186       case 'r':
   2187         if (*fmt == 'a')
   2188           ps[i] = '\007';
   2189         else if (*fmt == 'e')
   2190           ps[i] = '\033';
   2191         else if (*fmt == 'r')
   2192           ps[i] = '\r';
   2193         else
   2194           ps[i] = '\\';
   2195         break;
   2196 
   2197       /*
   2198        * CRLF sequence
   2199        */
   2200       case 'n':
   2201         if (i < PROMPTLEN - 3) {
   2202           ps[i++] = '\r';
   2203           ps[i]   = '\n';
   2204         }
   2205         break;
   2206 
   2207       /*
   2208        * print the current time as per provided strftime format
   2209        */
   2210       case 'D': {
   2211         char       tfmt[128] = "%X"; /* \d{} means %x */
   2212         struct tm *now;
   2213 
   2214         if (fmt[1] != '{') {
   2215           /*
   2216            * "\d" but not "\d{", so treat the '\'
   2217            * literally and rewind fmt to treat 'd'
   2218            * literally next iteration
   2219            */
   2220           ps[i] = '\\';
   2221           fmt--;
   2222           break;
   2223         }
   2224         fmt += 2; /* consume "d{" */
   2225         if (fmt[0] != '}') {
   2226           char *end;
   2227 
   2228           end = memccpy(tfmt, fmt, '}', sizeof(tfmt));
   2229           if (end == NULL) {
   2230             /*
   2231              * format too long or no '}', so
   2232              * ignore "\d{" altogether
   2233              * the loop will do i++, but nothing
   2234              * was written to ps, so do i-- here
   2235              * rewind fmt for similar reason
   2236              */
   2237             i--;
   2238             fmt--;
   2239             break;
   2240           }
   2241           *--end = '\0'; /* ignore the copy of '}' */
   2242           fmt += end - tfmt;
   2243         }
   2244         now = localtime(&(time_t){time(NULL)});
   2245         i += strftime(&ps[i], PROMPTLEN - i - 1, tfmt, now);
   2246         i--; /* the loop will do i++ */
   2247         break;
   2248       }
   2249 
   2250       /*
   2251        * hostname
   2252        *
   2253        * \h specifies just the local hostname,
   2254        * \h specifies fully-qualified hostname
   2255        */
   2256       case 'h':
   2257       case 'H':
   2258         ps[i] = '\0';
   2259         gethostname(&ps[i], PROMPTLEN - i - 1);
   2260         ps[PROMPTLEN - 1] = '\0';
   2261         /* skip to end of hostname */
   2262         trim = (*fmt == 'h') ? '.' : '\0';
   2263         while ((ps[i] != '\0') && (ps[i] != trim))
   2264           i++;
   2265         --i;
   2266         break;
   2267 
   2268       /*
   2269        * user name
   2270        */
   2271       case 'u':
   2272         ps[i] = '\0';
   2273         getusername(&ps[i], PROMPTLEN - i);
   2274         /* skip to end of username */
   2275         while (ps[i + 1] != '\0')
   2276           i++;
   2277         break;
   2278 
   2279       /*
   2280        * working directory
   2281        *
   2282        * \w specifies just the final component,
   2283        * \w specifies the entire path
   2284        */
   2285       case 'W':
   2286       case 'w':
   2287         pwd = lookupvar("PWD");
   2288         if (pwd == NULL || *pwd == '\0')
   2289           pwd = "?";
   2290         if (*fmt == 'W' && *pwd == '/' && pwd[1] != '\0')
   2291           strlcpy(&ps[i], strrchr(pwd, '/') + 1, PROMPTLEN - i);
   2292         else {
   2293           home = lookupvar("HOME");
   2294           if (home != NULL)
   2295             homelen = strlen(home);
   2296           if (home != NULL && strcmp(home, "/") != 0 && strncmp(pwd, home, homelen) == 0
   2297               && (pwd[homelen] == '/' || pwd[homelen] == '\0')) {
   2298             strlcpy(&ps[i], "~", PROMPTLEN - i);
   2299             strlcpy(&ps[i + 1], pwd + homelen, PROMPTLEN - i - 1);
   2300           } else {
   2301             strlcpy(&ps[i], pwd, PROMPTLEN - i);
   2302           }
   2303         }
   2304         /* skip to end of path */
   2305         while (ps[i + 1] != '\0')
   2306           i++;
   2307         break;
   2308 
   2309       /*
   2310        * superuser status
   2311        *
   2312        * '$' for normal users, '#' for root
   2313        */
   2314       case '$':
   2315         ps[i] = (geteuid() != 0) ? '$' : '#';
   2316         break;
   2317 
   2318       /*
   2319        * emit unrecognized formats verbatim
   2320        */
   2321       default:
   2322         ps[i] = '\\';
   2323         if (i < PROMPTLEN - 2)
   2324           ps[++i] = *fmt;
   2325         break;
   2326     }
   2327   }
   2328   ps[i] = '\0';
   2329   return (ps);
   2330 }
   2331 
   2332 const char *
   2333 expandstr(const char *ps)
   2334 {
   2335   union node                n;
   2336   struct jmploc             jmploc;
   2337   struct jmploc *const      savehandler     = handler;
   2338   const int                 saveprompt      = doprompt;
   2339   struct parsefile *const   savetopfile     = getcurrentfile();
   2340   struct parser_temp *const saveparser_temp = parser_temp;
   2341   const char               *result          = NULL;
   2342 
   2343   if (!setjmp(jmploc.loc)) {
   2344     handler     = &jmploc;
   2345     parser_temp = NULL;
   2346     setinputstring(ps);
   2347     doprompt = 0;
   2348     readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
   2349     if (backquotelist != NULL)
   2350       error("Command substitution not allowed here");
   2351 
   2352     n.narg.type      = NARG;
   2353     n.narg.next      = NULL;
   2354     n.narg.text      = wordtext;
   2355     n.narg.backquote = backquotelist;
   2356 
   2357     expandarg(&n, NULL, 0);
   2358     result = stackblock();
   2359     INTOFF;
   2360   }
   2361   handler  = savehandler;
   2362   doprompt = saveprompt;
   2363   popfilesupto(savetopfile);
   2364   if (parser_temp != saveparser_temp) {
   2365     parser_temp_free_all();
   2366     parser_temp = saveparser_temp;
   2367   }
   2368   if (result != NULL) {
   2369     INTON;
   2370   } else if (exception == EXINT)
   2371     raise(SIGINT);
   2372   return result;
   2373 }