hush: fix "unterminated last line loops forever" bug
[oweals/busybox.git] / shell / ash.c
index 6f31429528c5075ac3993b1acdbb6e0865b502c8..4b37f403c73c171b4c9914d270f644b5d078e674 100644 (file)
 #endif
 
 
+/* ============ Misc helpers */
+
+#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
+
+/* C99 say: "char" declaration may be signed or unsigned default */
+#define signed_char2int(sc) ((int)((signed char)sc))
+
+
 /* ============ Shell options */
 
 static const char *const optletters_optnames[] = {
@@ -130,6 +138,8 @@ static const char homestr[] = "HOME";
 static const char snlfmt[] = "%s\n";
 static const char illnum[] = "Illegal number: %s";
 
+static char *minusc;                   /* argument to -c option */
+
 static int isloginsh;
 /* pid of main shell */
 static int rootpid;
@@ -145,8 +155,9 @@ static char gotsig[NSIG - 1];
 static char *arg0; /* value of $0 */
 
 
-/* ============ Interrupts / exceptions
- *
+/* ============ Interrupts / exceptions */
+
+/*
  * We enclose jmp_buf in a structure so that we can declare pointers to
  * jump locations.  The global variable handler contains the location to
  * jump to when an exception occurs, and the global variable exception
@@ -172,7 +183,7 @@ static volatile sig_atomic_t intpending;
 /* do we generate EXSIG events */
 static int exsig;
 /* last pending signal */
-static volatile sig_atomic_t pendingsigs;
+static volatile sig_atomic_t pendingsig;
 
 /*
  * Sigmode records the current value of the signal handlers for the various
@@ -192,13 +203,11 @@ static volatile sig_atomic_t pendingsigs;
  * much more efficient and portable.  (But hacking the kernel is so much
  * more fun than worrying about efficiency and portability. :-))
  */
-#define xbarrier() ({ __asm__ __volatile__ ("": : :"memory"); })
 #define INT_OFF \
-       ({ \
+       do { \
                suppressint++; \
                xbarrier(); \
-               0; \
-       })
+       } while (0)
 
 /*
  * Called to raise an exception.  Since C doesn't include exceptions, we
@@ -230,8 +239,15 @@ static void
 raise_interrupt(void)
 {
        int i;
+       sigset_t mask;
 
        intpending = 0;
+       /* Signal is not automatically re-enabled after it is raised,
+        * do it ourself */
+       sigemptyset(&mask);
+       sigprocmask(SIG_SETMASK, &mask, 0);
+       /* pendingsig = 0; - now done in onsig() */
+
        i = EXSIG;
        if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
                if (!(rootshell && iflag)) {
@@ -263,38 +279,37 @@ force_int_on(void)
 #define FORCE_INT_ON force_int_on()
 #else
 #define INT_ON \
-       ({ \
+       do { \
                xbarrier(); \
-               if (--suppressint == 0 && intpending) raise_interrupt(); \
-               0; \
-       })
+               if (--suppressint == 0 && intpending) \
+                       raise_interrupt(); \
+       } while (0)
 #define FORCE_INT_ON \
-       ({ \
+       do { \
                xbarrier(); \
                suppressint = 0; \
-               if (intpending) raise_interrupt(); \
-               0; \
-       })
+               if (intpending) \
+                       raise_interrupt(); \
+       } while (0)
 #endif /* ASH_OPTIMIZE_FOR_SIZE */
 
 #define SAVE_INT(v) ((v) = suppressint)
 
 #define RESTORE_INT(v) \
-       ({ \
+       do { \
                xbarrier(); \
                suppressint = (v); \
-               if (suppressint == 0 && intpending) raise_interrupt(); \
-               0; \
-       })
+               if (suppressint == 0 && intpending) \
+                       raise_interrupt(); \
+       } while (0)
 
 #define EXSIGON \
-       ({ \
+       do { \
                exsig++; \
                xbarrier(); \
-               if (pendingsigs) \
+               if (pendingsig) \
                        raise_exception(EXSIG); \
-               0; \
-       })
+       } while (0)
 /* EXSIG is turned off by evalbltin(). */
 
 /*
@@ -316,11 +331,13 @@ static void
 onsig(int signo)
 {
        gotsig[signo - 1] = 1;
-       pendingsigs = signo;
+       pendingsig = signo;
 
        if (exsig || (signo == SIGINT && !trap[SIGINT])) {
-               if (!suppressint)
+               if (!suppressint) {
+                       pendingsig = 0;
                        raise_interrupt();
+               }
                intpending = 1;
        }
 }
@@ -406,7 +423,7 @@ out2str(const char *p)
 }
 
 
-/* ============ Parsing structures */
+/* ============ Parser structures */
 
 /* control characters in argument strings */
 #define CTLESC '\201'           /* escape next character */
@@ -436,10 +453,7 @@ out2str(const char *p)
 #define VSTRIMLEFTMAX   0x9             /* ${var##pattern} */
 #define VSLENGTH        0xa             /* ${#var} */
 
-/* values of checkkwd variable */
-#define CHKALIAS        0x1
-#define CHKKWD          0x2
-#define CHKNL           0x4
+static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
 
 #define NCMD 0
 #define NPIPE 1
@@ -980,9 +994,10 @@ ash_vmsg(const char *msg, va_list ap)
 {
        fprintf(stderr, "%s: ", arg0);
        if (commandname) {
-               const char *fmt = (!iflag || parsefile->fd) ?
-                                       "%s: %d: " : "%s: ";
-               fprintf(stderr, fmt, commandname, startlinno);
+               if (strcmp(arg0, commandname))
+                       fprintf(stderr, "%s: ", commandname);
+               if (!iflag || parsefile->fd)
+                       fprintf(stderr, "line %d: ", startlinno);
        }
        vfprintf(stderr, msg, ap);
        outcslow('\n', stderr);
@@ -1210,6 +1225,9 @@ popstackmark(struct stackmark *mark)
 {
        struct stack_block *sp;
 
+       if (!mark->stackp)
+               return;
+
        INT_OFF;
        markp = mark->marknext;
        while (stackp != mark->stackp) {
@@ -1366,21 +1384,25 @@ _STPUTC(int c, char *p)
        return p;
 }
 
-#define STARTSTACKSTR(p) ((p) = stackblock())
-#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
+#define STARTSTACKSTR(p)        ((p) = stackblock())
+#define STPUTC(c, p)            ((p) = _STPUTC((c), (p)))
 #define CHECKSTRSPACE(n, p) \
-       ({ \
+       do { \
                char *q = (p); \
                size_t l = (n); \
                size_t m = sstrend - q; \
                if (l > m) \
                        (p) = makestrspace(l, q); \
-               0; \
-       })
+       } while (0)
 #define USTPUTC(c, p)           (*p++ = (c))
-#define STACKSTRNUL(p)          ((p) == sstrend ? (p = growstackstr(), *p = '\0') : (*p = '\0'))
+#define STACKSTRNUL(p) \
+       do { \
+               if ((p) == sstrend) \
+                       p = growstackstr(); \
+               *p = '\0'; \
+       } while (0)
 #define STUNPUTC(p)             (--p)
-#define STTOPC(p)               p[-1]
+#define STTOPC(p)               (p[-1])
 #define STADJUST(amount, p)     (p += (amount))
 
 #define grabstackstr(p)         stalloc((char *)(p) - (char *)stackblock())
@@ -1509,13 +1531,13 @@ nextopt(const char *optstring)
        c = *p++;
        for (q = optstring; *q != c; ) {
                if (*q == '\0')
-                       ash_msg_and_raise_error("Illegal option -%c", c);
+                       ash_msg_and_raise_error("illegal option -%c", c);
                if (*++q == ':')
                        q++;
        }
        if (*++q == ':') {
                if (*p == '\0' && (p = *argptr++) == NULL)
-                       ash_msg_and_raise_error("No arg for -%c option", c);
+                       ash_msg_and_raise_error("no arg for -%c option", c);
                optionarg = p;
                p = NULL;
        }
@@ -1524,6 +1546,29 @@ nextopt(const char *optstring)
 }
 
 
+/* ============ Math support definitions */
+
+#if ENABLE_ASH_MATH_SUPPORT_64
+typedef int64_t arith_t;
+#define arith_t_type long long
+#else
+typedef long arith_t;
+#define arith_t_type long
+#endif
+
+#if ENABLE_ASH_MATH_SUPPORT
+static arith_t dash_arith(const char *);
+static arith_t arith(const char *expr, int *perrcode);
+#endif
+
+#if ENABLE_ASH_RANDOM_SUPPORT
+static unsigned long rseed;
+#ifndef DYNAMIC_VAR
+#define DYNAMIC_VAR
+#endif
+#endif
+
+
 /* ============ Shell variables */
 
 /* flags */
@@ -1537,9 +1582,9 @@ nextopt(const char *optstring)
 #define VNOSET          0x80    /* do not set variable - just readonly test */
 #define VNOSAVE         0x100   /* when text is on the heap before setvareq */
 #ifdef DYNAMIC_VAR
-# define VDYNAMIC        0x200   /* dynamic variable */
-# else
-# define VDYNAMIC        0
+# define VDYNAMIC       0x200   /* dynamic variable */
+#else
+# define VDYNAMIC       0
 #endif
 
 static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
@@ -1562,6 +1607,21 @@ struct shparam {
 
 static struct shparam shellparam;      /* $@ current positional parameters */
 
+/*
+ * Free the list of positional parameters.
+ */
+static void
+freeparam(volatile struct shparam *param)
+{
+       char **ap;
+
+       if (param->malloc) {
+               for (ap = param->p; *ap; ap++)
+                       free(*ap);
+               free(param->p);
+       }
+}
+
 #if ENABLE_ASH_GETOPTS
 static void
 getoptsreset(const char *value)
@@ -1588,8 +1648,18 @@ struct localvar {
 
 /* Forward decls for varinit[] */
 #if ENABLE_LOCALE_SUPPORT
-static void change_lc_all(const char *value);
-static void change_lc_ctype(const char *value);
+static void
+change_lc_all(const char *value)
+{
+       if (value && *value != '\0')
+               setlocale(LC_ALL, value);
+}
+static void
+change_lc_ctype(const char *value)
+{
+       if (value && *value != '\0')
+               setlocale(LC_CTYPE, value);
+}
 #endif
 #if ENABLE_ASH_MAIL
 static void chkmail(void);
@@ -2099,7 +2169,7 @@ putprompt(const char *s)
 {
        if (ENABLE_ASH_EXPAND_PRMT) {
                free((char*)cmdedit_prompt);
-               cmdedit_prompt = xstrdup(s);
+               cmdedit_prompt = ckstrdup(s);
                return;
        }
        cmdedit_prompt = s;
@@ -2223,7 +2293,8 @@ updatepwd(const char *dir)
                                                break;
                                }
                                break;
-                       } else if (p[1] == '\0')
+                       }
+                       if (p[1] == '\0')
                                break;
                        /* fall through */
                default:
@@ -2393,48 +2464,9 @@ pwdcmd(int argc, char **argv)
 
 /* ============ ... */
 
-/*
- * NEOF is returned by parsecmd when it encounters an end of file.  It
- * must be distinct from NULL, so we use the address of a variable that
- * happens to be handy.
- */
-static int plinno = 1;                  /* input line number */
-
-/* number of characters left in input buffer */
-static int parsenleft;                  /* copy of parsefile->nleft */
-static int parselleft;                  /* copy of parsefile->lleft */
-
-/* next character in input buffer */
-static char *parsenextc;                /* copy of parsefile->nextc */
-
 #define IBUFSIZ (BUFSIZ + 1)
 #define basebuf bb_common_bufsiz1       /* buffer for top level input file */
 
-static int tokpushback;                 /* last token pushed back */
-#define NEOF ((union node *)&tokpushback)
-static int parsebackquote;             /* nonzero if we are inside backquotes */
-static int lasttoken;                  /* last token read */
-static char *wordtext;                 /* text of last word returned by readtoken */
-static int checkkwd;
-static struct nodelist *backquotelist;
-static union node *redirnode;
-static struct heredoc *heredoc;
-static int quoteflag;                  /* set if (part of) last token was quoted */
-
-static void fixredir(union node *, const char *, int);
-
-
-/*      shell.h   */
-
-static const char spcstr[] = " ";
-static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
-
-#if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
-#define __builtin_expect(x, expected_value) (x)
-#endif
-
-#define xlikely(x)       __builtin_expect((x),1)
-
 /* Syntax classes */
 #define CWORD 0                 /* character is nothing special */
 #define CNL 1                   /* newline character */
@@ -2463,77 +2495,64 @@ static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
 #define PEOA_OR_PEOF PEOF
 #endif
 
-/* C99 say: "char" declaration may be signed or unsigned default */
-#define SC2INT(chr2may_be_negative_int) (int)((signed char)chr2may_be_negative_int)
-
-/*
- * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
- * (assuming ascii char codes, as the original implementation did)
- */
-#define is_special(c) \
-       ( (((unsigned int)c) - 33 < 32) \
-                        && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
+/* number syntax index */
+#define BASESYNTAX 0    /* not in quotes */
+#define DQSYNTAX   1    /* in double quotes */
+#define SQSYNTAX   2    /* in single quotes */
+#define ARISYNTAX  3    /* in arithmetic */
 
 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
 #define USE_SIT_FUNCTION
 #endif
 
-/* number syntax index */
-#define  BASESYNTAX  0  /* not in quotes */
-#define  DQSYNTAX    1  /* in double quotes */
-#define  SQSYNTAX    2  /* in single quotes */
-#define  ARISYNTAX   3  /* in arithmetic */
-
 #if ENABLE_ASH_MATH_SUPPORT
 static const char S_I_T[][4] = {
 #if ENABLE_ASH_ALIAS
-       {CSPCL, CIGN, CIGN, CIGN},              /* 0, PEOA */
-#endif
-       {CSPCL, CWORD, CWORD, CWORD},           /* 1, ' ' */
-       {CNL, CNL, CNL, CNL},                   /* 2, \n */
-       {CWORD, CCTL, CCTL, CWORD},             /* 3, !*-/:=?[]~ */
-       {CDQUOTE, CENDQUOTE, CWORD, CWORD},     /* 4, '"' */
-       {CVAR, CVAR, CWORD, CVAR},              /* 5, $ */
-       {CSQUOTE, CWORD, CENDQUOTE, CWORD},     /* 6, "'" */
-       {CSPCL, CWORD, CWORD, CLP},             /* 7, ( */
-       {CSPCL, CWORD, CWORD, CRP},             /* 8, ) */
-       {CBACK, CBACK, CCTL, CBACK},            /* 9, \ */
-       {CBQUOTE, CBQUOTE, CWORD, CBQUOTE},     /* 10, ` */
-       {CENDVAR, CENDVAR, CWORD, CENDVAR},     /* 11, } */
+       { CSPCL, CIGN, CIGN, CIGN },            /* 0, PEOA */
+#endif
+       { CSPCL, CWORD, CWORD, CWORD },         /* 1, ' ' */
+       { CNL, CNL, CNL, CNL },                 /* 2, \n */
+       { CWORD, CCTL, CCTL, CWORD },           /* 3, !*-/:=?[]~ */
+       { CDQUOTE, CENDQUOTE, CWORD, CWORD },   /* 4, '"' */
+       { CVAR, CVAR, CWORD, CVAR },            /* 5, $ */
+       { CSQUOTE, CWORD, CENDQUOTE, CWORD },   /* 6, "'" */
+       { CSPCL, CWORD, CWORD, CLP },           /* 7, ( */
+       { CSPCL, CWORD, CWORD, CRP },           /* 8, ) */
+       { CBACK, CBACK, CCTL, CBACK },          /* 9, \ */
+       { CBQUOTE, CBQUOTE, CWORD, CBQUOTE },   /* 10, ` */
+       { CENDVAR, CENDVAR, CWORD, CENDVAR },   /* 11, } */
 #ifndef USE_SIT_FUNCTION
-       {CENDFILE, CENDFILE, CENDFILE, CENDFILE},       /* 12, PEOF */
-       {CWORD, CWORD, CWORD, CWORD},           /* 13, 0-9A-Za-z */
-       {CCTL, CCTL, CCTL, CCTL}                /* 14, CTLESC ... */
+       { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
+       { CWORD, CWORD, CWORD, CWORD },         /* 13, 0-9A-Za-z */
+       { CCTL, CCTL, CCTL, CCTL }              /* 14, CTLESC ... */
 #endif
 };
 #else
 static const char S_I_T[][3] = {
 #if ENABLE_ASH_ALIAS
-       {CSPCL, CIGN, CIGN},                    /* 0, PEOA */
-#endif
-       {CSPCL, CWORD, CWORD},                  /* 1, ' ' */
-       {CNL, CNL, CNL},                        /* 2, \n */
-       {CWORD, CCTL, CCTL},                    /* 3, !*-/:=?[]~ */
-       {CDQUOTE, CENDQUOTE, CWORD},            /* 4, '"' */
-       {CVAR, CVAR, CWORD},                    /* 5, $ */
-       {CSQUOTE, CWORD, CENDQUOTE},            /* 6, "'" */
-       {CSPCL, CWORD, CWORD},                  /* 7, ( */
-       {CSPCL, CWORD, CWORD},                  /* 8, ) */
-       {CBACK, CBACK, CCTL},                   /* 9, \ */
-       {CBQUOTE, CBQUOTE, CWORD},              /* 10, ` */
-       {CENDVAR, CENDVAR, CWORD},              /* 11, } */
+       { CSPCL, CIGN, CIGN },                  /* 0, PEOA */
+#endif
+       { CSPCL, CWORD, CWORD },                /* 1, ' ' */
+       { CNL, CNL, CNL },                      /* 2, \n */
+       { CWORD, CCTL, CCTL },                  /* 3, !*-/:=?[]~ */
+       { CDQUOTE, CENDQUOTE, CWORD },          /* 4, '"' */
+       { CVAR, CVAR, CWORD },                  /* 5, $ */
+       { CSQUOTE, CWORD, CENDQUOTE },          /* 6, "'" */
+       { CSPCL, CWORD, CWORD },                /* 7, ( */
+       { CSPCL, CWORD, CWORD },                /* 8, ) */
+       { CBACK, CBACK, CCTL },                 /* 9, \ */
+       { CBQUOTE, CBQUOTE, CWORD },            /* 10, ` */
+       { CENDVAR, CENDVAR, CWORD },            /* 11, } */
 #ifndef USE_SIT_FUNCTION
-       {CENDFILE, CENDFILE, CENDFILE},         /* 12, PEOF */
-       {CWORD, CWORD, CWORD},                  /* 13, 0-9A-Za-z */
-       {CCTL, CCTL, CCTL}                      /* 14, CTLESC ... */
+       { CENDFILE, CENDFILE, CENDFILE },       /* 12, PEOF */
+       { CWORD, CWORD, CWORD },                /* 13, 0-9A-Za-z */
+       { CCTL, CCTL, CCTL }                    /* 14, CTLESC ... */
 #endif
 };
 #endif /* ASH_MATH_SUPPORT */
 
 #ifdef USE_SIT_FUNCTION
 
-#define U_C(c) ((unsigned char)(c))
-
 static int
 SIT(int c, int syntax)
 {
@@ -2563,9 +2582,13 @@ SIT(int c, int syntax)
                indx = 0;
        else
 #endif
-       if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
+#define U_C(c) ((unsigned char)(c))
+
+       if ((unsigned char)c >= (unsigned char)(CTLESC)
+        && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
+       ) {
                return CCTL;
-       else {
+       else {
                s = strchr(spec_symbls, c);
                if (s == NULL || *s == '\0')
                        return CWORD;
@@ -2574,41 +2597,39 @@ SIT(int c, int syntax)
        return S_I_T[indx][syntax];
 }
 
-#else   /* USE_SIT_FUNCTION */
-
-#define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
+#else   /* !USE_SIT_FUNCTION */
 
 #if ENABLE_ASH_ALIAS
-#define CSPCL_CIGN_CIGN_CIGN                           0
-#define CSPCL_CWORD_CWORD_CWORD                        1
-#define CNL_CNL_CNL_CNL                                2
-#define CWORD_CCTL_CCTL_CWORD                          3
-#define CDQUOTE_CENDQUOTE_CWORD_CWORD                  4
-#define CVAR_CVAR_CWORD_CVAR                           5
-#define CSQUOTE_CWORD_CENDQUOTE_CWORD                  6
-#define CSPCL_CWORD_CWORD_CLP                          7
-#define CSPCL_CWORD_CWORD_CRP                          8
-#define CBACK_CBACK_CCTL_CBACK                         9
-#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE                 10
-#define CENDVAR_CENDVAR_CWORD_CENDVAR                 11
-#define CENDFILE_CENDFILE_CENDFILE_CENDFILE           12
-#define CWORD_CWORD_CWORD_CWORD                       13
-#define CCTL_CCTL_CCTL_CCTL                           14
+#define CSPCL_CIGN_CIGN_CIGN                     0
+#define CSPCL_CWORD_CWORD_CWORD                  1
+#define CNL_CNL_CNL_CNL                          2
+#define CWORD_CCTL_CCTL_CWORD                    3
+#define CDQUOTE_CENDQUOTE_CWORD_CWORD            4
+#define CVAR_CVAR_CWORD_CVAR                     5
+#define CSQUOTE_CWORD_CENDQUOTE_CWORD            6
+#define CSPCL_CWORD_CWORD_CLP                    7
+#define CSPCL_CWORD_CWORD_CRP                    8
+#define CBACK_CBACK_CCTL_CBACK                   9
+#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE           10
+#define CENDVAR_CENDVAR_CWORD_CENDVAR           11
+#define CENDFILE_CENDFILE_CENDFILE_CENDFILE     12
+#define CWORD_CWORD_CWORD_CWORD                 13
+#define CCTL_CCTL_CCTL_CCTL                     14
 #else
-#define CSPCL_CWORD_CWORD_CWORD                        0
-#define CNL_CNL_CNL_CNL                                1
-#define CWORD_CCTL_CCTL_CWORD                          2
-#define CDQUOTE_CENDQUOTE_CWORD_CWORD                  3
-#define CVAR_CVAR_CWORD_CVAR                           4
-#define CSQUOTE_CWORD_CENDQUOTE_CWORD                  5
-#define CSPCL_CWORD_CWORD_CLP                          6
-#define CSPCL_CWORD_CWORD_CRP                          7
-#define CBACK_CBACK_CCTL_CBACK                         8
-#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE                  9
-#define CENDVAR_CENDVAR_CWORD_CENDVAR                 10
-#define CENDFILE_CENDFILE_CENDFILE_CENDFILE           11
-#define CWORD_CWORD_CWORD_CWORD                       12
-#define CCTL_CCTL_CCTL_CCTL                           13
+#define CSPCL_CWORD_CWORD_CWORD                  0
+#define CNL_CNL_CNL_CNL                          1
+#define CWORD_CCTL_CCTL_CWORD                    2
+#define CDQUOTE_CENDQUOTE_CWORD_CWORD            3
+#define CVAR_CVAR_CWORD_CVAR                     4
+#define CSQUOTE_CWORD_CENDQUOTE_CWORD            5
+#define CSPCL_CWORD_CWORD_CLP                    6
+#define CSPCL_CWORD_CWORD_CRP                    7
+#define CBACK_CBACK_CCTL_CBACK                   8
+#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE            9
+#define CENDVAR_CENDVAR_CWORD_CENDVAR           10
+#define CENDFILE_CENDFILE_CENDFILE_CENDFILE     11
+#define CWORD_CWORD_CWORD_CWORD                 12
+#define CCTL_CCTL_CCTL_CCTL                     13
 #endif
 
 static const char syntax_index_table[258] = {
@@ -2875,160 +2896,9 @@ static const char syntax_index_table[258] = {
        /* 257   127      */ CWORD_CWORD_CWORD_CWORD,
 };
 
-#endif  /* USE_SIT_FUNCTION */
-
-
-/*      exec.h    */
-
-#if ENABLE_ASH_MATH_SUPPORT_64
-typedef int64_t arith_t;
-#define arith_t_type long long
-#else
-typedef long arith_t;
-#define arith_t_type long
-#endif
-
-#if ENABLE_ASH_MATH_SUPPORT
-static arith_t dash_arith(const char *);
-static arith_t arith(const char *expr, int *perrcode);
-#endif
-
-#if ENABLE_ASH_RANDOM_SUPPORT
-static unsigned long rseed;
-# ifndef DYNAMIC_VAR
-#  define DYNAMIC_VAR
-# endif
-#endif
-
-
-/*      jobs.h    */
-
-/* Mode argument to forkshell.  Don't change FORK_FG or FORK_BG. */
-#define FORK_FG 0
-#define FORK_BG 1
-#define FORK_NOJOB 2
-
-/* mode flags for showjob(s) */
-#define SHOW_PGID       0x01    /* only show pgid - for jobs -p */
-#define SHOW_PID        0x04    /* include process pid */
-#define SHOW_CHANGED    0x08    /* only jobs whose state has changed */
-
-
-/*
- * A job structure contains information about a job.  A job is either a
- * single process or a set of processes contained in a pipeline.  In the
- * latter case, pidlist will be non-NULL, and will point to a -1 terminated
- * array of pids.
- */
-
-struct procstat {
-       pid_t   pid;            /* process id */
-       int     status;         /* last process status from wait() */
-       char    *cmd;           /* text of command being run */
-};
-
-struct job {
-       struct procstat ps0;    /* status of process */
-       struct procstat *ps;    /* status or processes when more than one */
-#if JOBS
-       int stopstatus;         /* status of a stopped job */
-#endif
-       uint32_t
-               nprocs: 16,     /* number of processes */
-               state: 8,
-#define JOBRUNNING      0       /* at least one proc running */
-#define JOBSTOPPED      1       /* all procs are stopped */
-#define JOBDONE         2       /* all procs are completed */
-#if JOBS
-               sigint: 1,      /* job was killed by SIGINT */
-               jobctl: 1,      /* job running under job control */
-#endif
-               waited: 1,      /* true if this entry has been waited for */
-               used: 1,        /* true if this entry is in used */
-               changed: 1;     /* true if status has changed */
-       struct job *prev_job;   /* previous job */
-};
-
-static pid_t backgndpid;        /* pid of last background process */
-static int job_warning;         /* user was warned about stopped jobs */
-#if JOBS
-static int jobctl;              /* true if doing job control */
-#endif
-
-static struct job *makejob(union node *, int);
-static int forkshell(struct job *, union node *, int);
-static int waitforjob(struct job *);
-
-#if ! JOBS
-#define setjobctl(on)   /* do nothing */
-#else
-static void setjobctl(int);
-static void showjobs(FILE *, int);
-#endif
-
-
-/*      main.h        */
-
-static void readcmdfile(char *);
-
-/*      options.h */
-
-static char *minusc;                   /* argument to -c option */
+#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
 
-static void optschanged(void);
-static void setparam(char **);
-static void freeparam(volatile struct shparam *);
-static int shiftcmd(int, char **);
-static int setcmd(int, char **);
-static int nextopt(const char *);
-
-
-/*      redir.h      */
-
-/* flags passed to redirect */
-#define REDIR_PUSH 01           /* save previous values of file descriptors */
-#define REDIR_SAVEFD2 03       /* set preverrout */
-
-static void redirect(union node *, int);
-static void popredir(int);
-static void clearredir(int);
-static int copyfd(int, int);
-static int redirectsafe(union node *, int);
-
-static int is_safe_applet(char *name)
-{
-       /* It isn't a bug to have non-existent applet here... */
-       /* ...just a waste of space... */
-       static const char safe_applets[][8] = {
-               "["
-               USE_AWK    (, "awk"    )
-               USE_CAT    (, "cat"    )
-               USE_CHMOD  (, "chmod"  )
-               USE_CHOWN  (, "chown"  )
-               USE_CP     (, "cp"     )
-               USE_CUT    (, "cut"    )
-               USE_DD     (, "dd"     )
-               USE_ECHO   (, "echo"   )
-               USE_FIND   (, "find"   )
-               USE_HEXDUMP(, "hexdump")
-               USE_LN     (, "ln"     )
-               USE_LS     (, "ls"     )
-               USE_MKDIR  (, "mkdir"  )
-               USE_RM     (, "rm"     )
-               USE_SORT   (, "sort"   )
-               USE_TEST   (, "test"   )
-               USE_TOUCH  (, "touch"  )
-               USE_XARGS  (, "xargs"  )
-       };
-       int n = sizeof(safe_applets) / sizeof(safe_applets[0]);
-       int i;
-       for (i = 0; i < n; i++)
-               if (strcmp(safe_applets[i], name) == 0)
-                       return 1;
-
-       return 0;
-}
+#endif  /* USE_SIT_FUNCTION */
 
 
 /* ============ Alias handling */
@@ -3231,5586 +3101,5799 @@ unaliascmd(int argc, char **argv)
 #endif /* ASH_ALIAS */
 
 
-/* ============ Routines to expand arguments to commands
- *
- * We have to deal with backquotes, shell variables, and file metacharacters.
- */
+/* ============ jobs.c */
 
-/*
- * expandarg flags
- */
-#define EXP_FULL        0x1     /* perform word splitting & file globbing */
-#define EXP_TILDE       0x2     /* do normal tilde expansion */
-#define EXP_VARTILDE    0x4     /* expand tildes in an assignment */
-#define EXP_REDIR       0x8     /* file glob for a redirection (1 match only) */
-#define EXP_CASE        0x10    /* keeps quotes around for CASE pattern */
-#define EXP_RECORD      0x20    /* need to record arguments for ifs breakup */
-#define EXP_VARTILDE2   0x40    /* expand tildes after colons only */
-#define EXP_WORD        0x80    /* expand word in parameter expansion */
-#define EXP_QWORD       0x100   /* expand word in quoted parameter expansion */
-/*
- * _rmescape() flags
- */
-#define RMESCAPE_ALLOC  0x1     /* Allocate a new string */
-#define RMESCAPE_GLOB   0x2     /* Add backslashes for glob */
-#define RMESCAPE_QUOTED 0x4     /* Remove CTLESC unless in quotes */
-#define RMESCAPE_GROW   0x8     /* Grow strings instead of stalloc */
-#define RMESCAPE_HEAP   0x10    /* Malloc strings instead of stalloc */
+/* Mode argument to forkshell.  Don't change FORK_FG or FORK_BG. */
+#define FORK_FG 0
+#define FORK_BG 1
+#define FORK_NOJOB 2
+
+/* mode flags for showjob(s) */
+#define SHOW_PGID       0x01    /* only show pgid - for jobs -p */
+#define SHOW_PID        0x04    /* include process pid */
+#define SHOW_CHANGED    0x08    /* only jobs whose state has changed */
 
 /*
- * Structure specifying which parts of the string should be searched
- * for IFS characters.
+ * A job structure contains information about a job.  A job is either a
+ * single process or a set of processes contained in a pipeline.  In the
+ * latter case, pidlist will be non-NULL, and will point to a -1 terminated
+ * array of pids.
  */
-struct ifsregion {
-       struct ifsregion *next; /* next region in list */
-       int begoff;             /* offset of start of region */
-       int endoff;             /* offset of end of region */
-       int nulonly;            /* search for nul bytes only */
+
+struct procstat {
+       pid_t   pid;            /* process id */
+       int     status;         /* last process status from wait() */
+       char    *cmd;           /* text of command being run */
 };
 
-struct arglist {
-       struct strlist *list;
-       struct strlist **lastp;
+struct job {
+       struct procstat ps0;    /* status of process */
+       struct procstat *ps;    /* status or processes when more than one */
+#if JOBS
+       int stopstatus;         /* status of a stopped job */
+#endif
+       uint32_t
+               nprocs: 16,     /* number of processes */
+               state: 8,
+#define JOBRUNNING      0       /* at least one proc running */
+#define JOBSTOPPED      1       /* all procs are stopped */
+#define JOBDONE         2       /* all procs are completed */
+#if JOBS
+               sigint: 1,      /* job was killed by SIGINT */
+               jobctl: 1,      /* job running under job control */
+#endif
+               waited: 1,      /* true if this entry has been waited for */
+               used: 1,        /* true if this entry is in used */
+               changed: 1;     /* true if status has changed */
+       struct job *prev_job;   /* previous job */
 };
 
-/* output of current string */
-static char *expdest;
-/* list of back quote expressions */
-static struct nodelist *argbackq;
-/* first struct in list of ifs regions */
-static struct ifsregion ifsfirst;
-/* last struct in list */
-static struct ifsregion *ifslastp;
-/* holds expanded arg list */
-static struct arglist exparg;
+static pid_t backgndpid;        /* pid of last background process */
+static int job_warning;         /* user was warned about stopped jobs */
+#if JOBS
+static int jobctl;              /* true if doing job control */
+#endif
 
-/*
- * Our own itoa().
- */
-static int
-cvtnum(arith_t num)
-{
-       int len;
+static struct job *makejob(union node *, int);
+static int forkshell(struct job *, union node *, int);
+static int waitforjob(struct job *);
 
-       expdest = makestrspace(32, expdest);
-#if ENABLE_ASH_MATH_SUPPORT_64
-       len = fmtstr(expdest, 32, "%lld", (long long) num);
+#if ! JOBS
+#define setjobctl(on)   /* do nothing */
 #else
-       len = fmtstr(expdest, 32, "%ld", num);
+static void setjobctl(int);
+static void showjobs(FILE *, int);
 #endif
-       STADJUST(len, expdest);
-       return len;
-}
-
-static size_t
-esclen(const char *start, const char *p)
-{
-       size_t esc = 0;
-
-       while (p > start && *--p == CTLESC) {
-               esc++;
-       }
-       return esc;
-}
 
 /*
- * Remove any CTLESC characters from a string.
+ * Set the signal handler for the specified signal.  The routine figures
+ * out what it should be set to.
  */
-static char *
-_rmescapes(char *str, int flag)
+static void
+setsignal(int signo)
 {
-       char *p, *q, *r;
-       static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
-       unsigned inquotes;
-       int notescaped;
-       int globbing;
-
-       p = strpbrk(str, qchars);
-       if (!p) {
-               return str;
-       }
-       q = p;
-       r = str;
-       if (flag & RMESCAPE_ALLOC) {
-               size_t len = p - str;
-               size_t fulllen = len + strlen(p) + 1;
+       int action;
+       char *t, tsig;
+       struct sigaction act;
 
-               if (flag & RMESCAPE_GROW) {
-                       r = makestrspace(fulllen, expdest);
-               } else if (flag & RMESCAPE_HEAP) {
-                       r = ckmalloc(fulllen);
-               } else {
-                       r = stalloc(fulllen);
-               }
-               q = r;
-               if (len > 0) {
-                       q = memcpy(q, str, len) + len;
+       t = trap[signo];
+       if (t == NULL)
+               action = S_DFL;
+       else if (*t != '\0')
+               action = S_CATCH;
+       else
+               action = S_IGN;
+       if (rootshell && action == S_DFL) {
+               switch (signo) {
+               case SIGINT:
+                       if (iflag || minusc || sflag == 0)
+                               action = S_CATCH;
+                       break;
+               case SIGQUIT:
+#if DEBUG
+                       if (debug)
+                               break;
+#endif
+                       /* FALLTHROUGH */
+               case SIGTERM:
+                       if (iflag)
+                               action = S_IGN;
+                       break;
+#if JOBS
+               case SIGTSTP:
+               case SIGTTOU:
+                       if (mflag)
+                               action = S_IGN;
+                       break;
+#endif
                }
        }
-       inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
-       globbing = flag & RMESCAPE_GLOB;
-       notescaped = globbing;
-       while (*p) {
-               if (*p == CTLQUOTEMARK) {
-                       inquotes = ~inquotes;
-                       p++;
-                       notescaped = globbing;
-                       continue;
-               }
-               if (*p == '\\') {
-                       /* naked back slash */
-                       notescaped = 0;
-                       goto copy;
+
+       t = &sigmode[signo - 1];
+       tsig = *t;
+       if (tsig == 0) {
+               /*
+                * current setting unknown
+                */
+               if (sigaction(signo, 0, &act) == -1) {
+                       /*
+                        * Pretend it worked; maybe we should give a warning
+                        * here, but other shells don't. We don't alter
+                        * sigmode, so that we retry every time.
+                        */
+                       return;
                }
-               if (*p == CTLESC) {
-                       p++;
-                       if (notescaped && inquotes && *p != '/') {
-                               *q++ = '\\';
-                       }
+               if (act.sa_handler == SIG_IGN) {
+                       if (mflag
+                        && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
+                       ) {
+                               tsig = S_IGN;   /* don't hard ignore these */
+                       } else
+                               tsig = S_HARD_IGN;
+               } else {
+                       tsig = S_RESET; /* force to be set */
                }
-               notescaped = globbing;
- copy:
-               *q++ = *p++;
        }
-       *q = '\0';
-       if (flag & RMESCAPE_GROW) {
-               expdest = r;
-               STADJUST(q - r + 1, expdest);
+       if (tsig == S_HARD_IGN || tsig == action)
+               return;
+       switch (action) {
+       case S_CATCH:
+               act.sa_handler = onsig;
+               break;
+       case S_IGN:
+               act.sa_handler = SIG_IGN;
+               break;
+       default:
+               act.sa_handler = SIG_DFL;
        }
-       return r;
+       *t = action;
+       act.sa_flags = 0;
+       sigfillset(&act.sa_mask);
+       sigaction(signo, &act, 0);
 }
-#define rmescapes(p) _rmescapes((p), 0)
 
-#define pmatch(a, b) !fnmatch((a), (b), 0)
+/* mode flags for set_curjob */
+#define CUR_DELETE 2
+#define CUR_RUNNING 1
+#define CUR_STOPPED 0
 
-/*
- * Prepare a pattern for a expmeta (internal glob(3)) call.
- *
- * Returns an stalloced string.
- */
-static char *
-preglob(const char *pattern, int quoted, int flag)
-{
-       flag |= RMESCAPE_GLOB;
-       if (quoted) {
-               flag |= RMESCAPE_QUOTED;
-       }
-       return _rmescapes((char *)pattern, flag);
-}
+/* mode flags for dowait */
+#define DOWAIT_NORMAL 0
+#define DOWAIT_BLOCK 1
+
+#if JOBS
+/* pgrp of shell on invocation */
+static int initialpgrp;
+static int ttyfd = -1;
+#endif
+/* array of jobs */
+static struct job *jobtab;
+/* size of array */
+static unsigned njobs;
+/* current job */
+static struct job *curjob;
+/* number of presumed living untracked jobs */
+static int jobless;
 
-/*
- * Put a string on the stack.
- */
 static void
-memtodest(const char *p, size_t len, int syntax, int quotes)
+set_curjob(struct job *jp, unsigned mode)
 {
-       char *q = expdest;
+       struct job *jp1;
+       struct job **jpp, **curp;
 
-       q = makestrspace(len * 2, q);
+       /* first remove from list */
+       jpp = curp = &curjob;
+       do {
+               jp1 = *jpp;
+               if (jp1 == jp)
+                       break;
+               jpp = &jp1->prev_job;
+       } while (1);
+       *jpp = jp1->prev_job;
 
-       while (len--) {
-               int c = SC2INT(*p++);
-               if (!c)
-                       continue;
-               if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
-                       USTPUTC(CTLESC, q);
-               USTPUTC(c, q);
+       /* Then re-insert in correct position */
+       jpp = curp;
+       switch (mode) {
+       default:
+#if DEBUG
+               abort();
+#endif
+       case CUR_DELETE:
+               /* job being deleted */
+               break;
+       case CUR_RUNNING:
+               /* newly created job or backgrounded job,
+                  put after all stopped jobs. */
+               do {
+                       jp1 = *jpp;
+#if JOBS
+                       if (!jp1 || jp1->state != JOBSTOPPED)
+#endif
+                               break;
+                       jpp = &jp1->prev_job;
+               } while (1);
+               /* FALLTHROUGH */
+#if JOBS
+       case CUR_STOPPED:
+#endif
+               /* newly stopped job - becomes curjob */
+               jp->prev_job = *jpp;
+               *jpp = jp;
+               break;
        }
-
-       expdest = q;
 }
 
-static void
-strtodest(const char *p, int syntax, int quotes)
+#if JOBS || DEBUG
+static int
+jobno(const struct job *jp)
 {
-       memtodest(p, strlen(p), syntax, quotes);
+       return jp - jobtab + 1;
 }
+#endif
 
 /*
- * Record the fact that we have to scan this region of the
- * string for IFS characters.
+ * Convert a job name to a job structure.
  */
-static void
-recordregion(int start, int end, int nulonly)
+static struct job *
+getjob(const char *name, int getctl)
 {
-       struct ifsregion *ifsp;
+       struct job *jp;
+       struct job *found;
+       const char *err_msg = "No such job: %s";
+       unsigned num;
+       int c;
+       const char *p;
+       char *(*match)(const char *, const char *);
 
-       if (ifslastp == NULL) {
-               ifsp = &ifsfirst;
-       } else {
-               INT_OFF;
-               ifsp = ckmalloc(sizeof(*ifsp));
-               ifsp->next = NULL;
-               ifslastp->next = ifsp;
-               INT_ON;
-       }
-       ifslastp = ifsp;
-       ifslastp->begoff = start;
-       ifslastp->endoff = end;
-       ifslastp->nulonly = nulonly;
-}
+       jp = curjob;
+       p = name;
+       if (!p)
+               goto currentjob;
 
-static void
-removerecordregions(int endoff)
-{
-       if (ifslastp == NULL)
-               return;
+       if (*p != '%')
+               goto err;
 
-       if (ifsfirst.endoff > endoff) {
-               while (ifsfirst.next != NULL) {
-                       struct ifsregion *ifsp;
-                       INT_OFF;
-                       ifsp = ifsfirst.next->next;
-                       free(ifsfirst.next);
-                       ifsfirst.next = ifsp;
-                       INT_ON;
+       c = *++p;
+       if (!c)
+               goto currentjob;
+
+       if (!p[1]) {
+               if (c == '+' || c == '%') {
+ currentjob:
+                       err_msg = "No current job";
+                       goto check;
                }
-               if (ifsfirst.begoff > endoff)
-                       ifslastp = NULL;
-               else {
-                       ifslastp = &ifsfirst;
-                       ifsfirst.endoff = endoff;
+               if (c == '-') {
+                       if (jp)
+                               jp = jp->prev_job;
+                       err_msg = "No previous job";
+ check:
+                       if (!jp)
+                               goto err;
+                       goto gotit;
                }
-               return;
        }
 
-       ifslastp = &ifsfirst;
-       while (ifslastp->next && ifslastp->next->begoff < endoff)
-               ifslastp=ifslastp->next;
-       while (ifslastp->next != NULL) {
-               struct ifsregion *ifsp;
-               INT_OFF;
-               ifsp = ifslastp->next->next;
-               free(ifslastp->next);
-               ifslastp->next = ifsp;
-               INT_ON;
+       if (is_number(p)) {
+               num = atoi(p);
+               if (num < njobs) {
+                       jp = jobtab + num - 1;
+                       if (jp->used)
+                               goto gotit;
+                       goto err;
+               }
        }
-       if (ifslastp->endoff > endoff)
-               ifslastp->endoff = endoff;
-}
-
-static char *
-exptilde(char *startp, char *p, int flag)
-{
-       char c;
-       char *name;
-       struct passwd *pw;
-       const char *home;
-       int quotes = flag & (EXP_FULL | EXP_CASE);
-       int startloc;
 
-       name = p + 1;
+       match = prefix;
+       if (*p == '?') {
+               match = strstr;
+               p++;
+       }
 
-       while ((c = *++p) != '\0') {
-               switch (c) {
-               case CTLESC:
-                       return startp;
-               case CTLQUOTEMARK:
-                       return startp;
-               case ':':
-                       if (flag & EXP_VARTILDE)
-                               goto done;
-                       break;
-               case '/':
-               case CTLENDVAR:
-                       goto done;
+       found = 0;
+       while (1) {
+               if (!jp)
+                       goto err;
+               if (match(jp->ps[0].cmd, p)) {
+                       if (found)
+                               goto err;
+                       found = jp;
+                       err_msg = "%s: ambiguous";
                }
+               jp = jp->prev_job;
        }
- done:
-       *p = '\0';
-       if (*name == '\0') {
-               home = lookupvar(homestr);
-       } else {
-               pw = getpwnam(name);
-               if (pw == NULL)
-                       goto lose;
-               home = pw->pw_dir;
-       }
-       if (!home || !*home)
-               goto lose;
-       *p = c;
-       startloc = expdest - (char *)stackblock();
-       strtodest(home, SQSYNTAX, quotes);
-       recordregion(startloc, expdest - (char *)stackblock(), 0);
-       return p;
- lose:
-       *p = c;
-       return startp;
+
+ gotit:
+#if JOBS
+       err_msg = "job %s not created under job control";
+       if (getctl && jp->jobctl == 0)
+               goto err;
+#endif
+       return jp;
+ err:
+       ash_msg_and_raise_error(err_msg, name);
 }
 
 /*
- * Execute a command inside back quotes.  If it's a builtin command, we
- * want to save its output in a block obtained from malloc.  Otherwise
- * we fork off a subprocess and get the output of the command via a pipe.
- * Should be called with interrupts off.
+ * Mark a job structure as unused.
  */
-struct backcmd {                /* result of evalbackcmd */
-       int fd;                 /* file descriptor to read from */
-       char *buf;              /* buffer */
-       int nleft;              /* number of chars in buffer */
-       struct job *jp;         /* job structure for command */
-};
+static void
+freejob(struct job *jp)
+{
+       struct procstat *ps;
+       int i;
 
-/* These forward decls are needed to use "eval" code for backticks handling: */
-static int back_exitstatus; /* exit status of backquoted command */
-#define EV_EXIT 01              /* exit after evaluating tree */
-static void evaltree(union node *, int);
+       INT_OFF;
+       for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
+               if (ps->cmd != nullstr)
+                       free(ps->cmd);
+       }
+       if (jp->ps != &jp->ps0)
+               free(jp->ps);
+       jp->used = 0;
+       set_curjob(jp, CUR_DELETE);
+       INT_ON;
+}
 
+#if JOBS
 static void
-evalbackcmd(union node *n, struct backcmd *result)
+xtcsetpgrp(int fd, pid_t pgrp)
 {
-       int saveherefd;
-
-       result->fd = -1;
-       result->buf = NULL;
-       result->nleft = 0;
-       result->jp = NULL;
-       if (n == NULL) {
-               goto out;
-       }
-
-       saveherefd = herefd;
-       herefd = -1;
-
-       {
-               int pip[2];
-               struct job *jp;
-
-               if (pipe(pip) < 0)
-                       ash_msg_and_raise_error("Pipe call failed");
-               jp = makejob(n, 1);
-               if (forkshell(jp, n, FORK_NOJOB) == 0) {
-                       FORCE_INT_ON;
-                       close(pip[0]);
-                       if (pip[1] != 1) {
-                               close(1);
-                               copyfd(pip[1], 1);
-                               close(pip[1]);
-                       }
-                       eflag = 0;
-                       evaltree(n, EV_EXIT); /* actually evaltreenr... */
-                       /* NOTREACHED */
-               }
-               close(pip[1]);
-               result->fd = pip[0];
-               result->jp = jp;
-       }
-       herefd = saveherefd;
- out:
-       TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
-               result->fd, result->buf, result->nleft, result->jp));
-}
+       if (tcsetpgrp(fd, pgrp))
+               ash_msg_and_raise_error("cannot set tty process group (%m)");
+}
 
 /*
- * Expand stuff in backwards quotes.
+ * Turn job control on and off.
+ *
+ * Note:  This code assumes that the third arg to ioctl is a character
+ * pointer, which is true on Berkeley systems but not System V.  Since
+ * System V doesn't have job control yet, this isn't a problem now.
+ *
+ * Called with interrupts off.
  */
 static void
-expbackq(union node *cmd, int quoted, int quotes)
+setjobctl(int on)
 {
-       struct backcmd in;
-       int i;
-       char buf[128];
-       char *p;
-       char *dest;
-       int startloc;
-       int syntax = quoted? DQSYNTAX : BASESYNTAX;
-       struct stackmark smark;
+       int fd;
+       int pgrp;
 
-       INT_OFF;
-       setstackmark(&smark);
-       dest = expdest;
-       startloc = dest - (char *)stackblock();
-       grabstackstr(dest);
-       evalbackcmd(cmd, &in);
-       popstackmark(&smark);
+       if (on == jobctl || rootshell == 0)
+               return;
+       if (on) {
+               int ofd;
+               ofd = fd = open(_PATH_TTY, O_RDWR);
+               if (fd < 0) {
+       /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
+        * That sometimes helps to acquire controlling tty.
+        * Obviously, a workaround for bugs when someone
+        * failed to provide a controlling tty to bash! :) */
+                       fd += 3;
+                       while (!isatty(fd) && --fd >= 0)
+                               ;
+               }
+               fd = fcntl(fd, F_DUPFD, 10);
+               close(ofd);
+               if (fd < 0)
+                       goto out;
+               fcntl(fd, F_SETFD, FD_CLOEXEC);
+               do { /* while we are in the background */
+                       pgrp = tcgetpgrp(fd);
+                       if (pgrp < 0) {
+ out:
+                               ash_msg("can't access tty; job control turned off");
+                               mflag = on = 0;
+                               goto close;
+                       }
+                       if (pgrp == getpgrp())
+                               break;
+                       killpg(0, SIGTTIN);
+               } while (1);
+               initialpgrp = pgrp;
 
-       p = in.buf;
-       i = in.nleft;
-       if (i == 0)
-               goto read;
-       for (;;) {
-               memtodest(p, i, syntax, quotes);
- read:
-               if (in.fd < 0)
-                       break;
-               i = safe_read(in.fd, buf, sizeof(buf));
-               TRACE(("expbackq: read returns %d\n", i));
-               if (i <= 0)
-                       break;
-               p = buf;
+               setsignal(SIGTSTP);
+               setsignal(SIGTTOU);
+               setsignal(SIGTTIN);
+               pgrp = rootpid;
+               setpgid(0, pgrp);
+               xtcsetpgrp(fd, pgrp);
+       } else {
+               /* turning job control off */
+               fd = ttyfd;
+               pgrp = initialpgrp;
+               /* was xtcsetpgrp, but this can make exiting ash
+                * with pty already deleted loop forever */
+               tcsetpgrp(fd, pgrp);
+               setpgid(0, pgrp);
+               setsignal(SIGTSTP);
+               setsignal(SIGTTOU);
+               setsignal(SIGTTIN);
+ close:
+               close(fd);
+               fd = -1;
        }
+       ttyfd = fd;
+       jobctl = on;
+}
 
-       if (in.buf)
-               free(in.buf);
-       if (in.fd >= 0) {
-               close(in.fd);
-               back_exitstatus = waitforjob(in.jp);
+static int
+killcmd(int argc, char **argv)
+{
+       if (argv[1] && strcmp(argv[1], "-l") != 0) {
+               int i = 1;
+               do {
+                       if (argv[i][0] == '%') {
+                               struct job *jp = getjob(argv[i], 0);
+                               unsigned pid = jp->ps[0].pid;
+                               /* Enough space for ' -NNN<nul>' */
+                               argv[i] = alloca(sizeof(int)*3 + 3);
+                               /* kill_main has matching code to expect
+                                * leading space. Needed to not confuse
+                                * negative pids with "kill -SIGNAL_NO" syntax */
+                               sprintf(argv[i], " -%u", pid);
+                       }
+               } while (argv[++i]);
        }
-       INT_ON;
-
-       /* Eat all trailing newlines */
-       dest = expdest;
-       for (; dest > (char *)stackblock() && dest[-1] == '\n';)
-               STUNPUTC(dest);
-       expdest = dest;
-
-       if (quoted == 0)
-               recordregion(startloc, dest - (char *)stackblock(), 0);
-       TRACE(("evalbackq: size=%d: \"%.*s\"\n",
-               (dest - (char *)stackblock()) - startloc,
-               (dest - (char *)stackblock()) - startloc,
-               stackblock() + startloc));
+       return kill_main(argc, argv);
 }
 
-#if ENABLE_ASH_MATH_SUPPORT
-/*
- * Expand arithmetic expression.  Backup to start of expression,
- * evaluate, place result in (backed up) result, adjust string position.
- */
 static void
-expari(int quotes)
+showpipe(struct job *jp, FILE *out)
 {
-       char *p, *start;
-       int begoff;
-       int flag;
-       int len;
+       struct procstat *sp;
+       struct procstat *spend;
 
-       /*      ifsfree(); */
+       spend = jp->ps + jp->nprocs;
+       for (sp = jp->ps + 1; sp < spend; sp++)
+               fprintf(out, " | %s", sp->cmd);
+       outcslow('\n', out);
+       flush_stdout_stderr();
+}
 
-       /*
-        * This routine is slightly over-complicated for
-        * efficiency.  Next we scan backwards looking for the
-        * start of arithmetic.
-        */
-       start = stackblock();
-       p = expdest - 1;
-       *p = '\0';
-       p--;
-       do {
-               int esc;
 
-               while (*p != CTLARI) {
-                       p--;
-#if DEBUG
-                       if (p < start) {
-                               ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
-                       }
-#endif
-               }
+static int
+restartjob(struct job *jp, int mode)
+{
+       struct procstat *ps;
+       int i;
+       int status;
+       pid_t pgid;
 
-               esc = esclen(start, p);
-               if (!(esc % 2)) {
-                       break;
+       INT_OFF;
+       if (jp->state == JOBDONE)
+               goto out;
+       jp->state = JOBRUNNING;
+       pgid = jp->ps->pid;
+       if (mode == FORK_FG)
+               xtcsetpgrp(ttyfd, pgid);
+       killpg(pgid, SIGCONT);
+       ps = jp->ps;
+       i = jp->nprocs;
+       do {
+               if (WIFSTOPPED(ps->status)) {
+                       ps->status = -1;
                }
+               ps++;
+       } while (--i);
+ out:
+       status = (mode == FORK_FG) ? waitforjob(jp) : 0;
+       INT_ON;
+       return status;
+}
 
-               p -= esc + 1;
-       } while (1);
+static int
+fg_bgcmd(int argc, char **argv)
+{
+       struct job *jp;
+       FILE *out;
+       int mode;
+       int retval;
 
-       begoff = p - start;
+       mode = (**argv == 'f') ? FORK_FG : FORK_BG;
+       nextopt(nullstr);
+       argv = argptr;
+       out = stdout;
+       do {
+               jp = getjob(*argv, 1);
+               if (mode == FORK_BG) {
+                       set_curjob(jp, CUR_RUNNING);
+                       fprintf(out, "[%d] ", jobno(jp));
+               }
+               outstr(jp->ps->cmd, out);
+               showpipe(jp, out);
+               retval = restartjob(jp, mode);
+       } while (*argv && *++argv);
+       return retval;
+}
+#endif
 
-       removerecordregions(begoff);
+static int
+sprint_status(char *s, int status, int sigonly)
+{
+       int col;
+       int st;
 
-       flag = p[1];
-
-       expdest = p;
-
-       if (quotes)
-               rmescapes(p + 2);
-
-       len = cvtnum(dash_arith(p + 2));
-
-       if (flag != '"')
-               recordregion(begoff, begoff + len, 0);
-}
+       col = 0;
+       if (!WIFEXITED(status)) {
+#if JOBS
+               if (WIFSTOPPED(status))
+                       st = WSTOPSIG(status);
+               else
 #endif
-
-/* argstr needs it */
-static char *evalvar(char *p, int flag);
+                       st = WTERMSIG(status);
+               if (sigonly) {
+                       if (st == SIGINT || st == SIGPIPE)
+                               goto out;
+#if JOBS
+                       if (WIFSTOPPED(status))
+                               goto out;
+#endif
+               }
+               st &= 0x7f;
+               col = fmtstr(s, 32, strsignal(st));
+               if (WCOREDUMP(status)) {
+                       col += fmtstr(s + col, 16, " (core dumped)");
+               }
+       } else if (!sigonly) {
+               st = WEXITSTATUS(status);
+               if (st)
+                       col = fmtstr(s, 16, "Done(%d)", st);
+               else
+                       col = fmtstr(s, 16, "Done");
+       }
+ out:
+       return col;
+}
 
 /*
- * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
- * characters to allow for further processing.  Otherwise treat
- * $@ like $* since no splitting will be performed.
+ * Do a wait system call.  If job control is compiled in, we accept
+ * stopped processes.  If block is zero, we return a value of zero
+ * rather than blocking.
+ *
+ * System V doesn't have a non-blocking wait system call.  It does
+ * have a SIGCLD signal that is sent to a process when one of it's
+ * children dies.  The obvious way to use SIGCLD would be to install
+ * a handler for SIGCLD which simply bumped a counter when a SIGCLD
+ * was received, and have waitproc bump another counter when it got
+ * the status of a process.  Waitproc would then know that a wait
+ * system call would not block if the two counters were different.
+ * This approach doesn't work because if a process has children that
+ * have not been waited for, System V will send it a SIGCLD when it
+ * installs a signal handler for SIGCLD.  What this means is that when
+ * a child exits, the shell will be sent SIGCLD signals continuously
+ * until is runs out of stack space, unless it does a wait call before
+ * restoring the signal handler.  The code below takes advantage of
+ * this (mis)feature by installing a signal handler for SIGCLD and
+ * then checking to see whether it was called.  If there are any
+ * children to be waited for, it will be.
+ *
+ * If neither SYSV nor BSD is defined, we don't implement nonblocking
+ * waits at all.  In this case, the user will not be informed when
+ * a background process until the next time she runs a real program
+ * (as opposed to running a builtin command or just typing return),
+ * and the jobs command may give out of date information.
  */
-static void
-argstr(char *p, int flag)
+static int
+waitproc(int block, int *status)
 {
-       static const char spclchars[] = {
-               '=',
-               ':',
-               CTLQUOTEMARK,
-               CTLENDVAR,
-               CTLESC,
-               CTLVAR,
-               CTLBACKQ,
-               CTLBACKQ | CTLQUOTE,
-#if ENABLE_ASH_MATH_SUPPORT
-               CTLENDARI,
+       int flags = 0;
+
+#if JOBS
+       if (jobctl)
+               flags |= WUNTRACED;
 #endif
-               0
-       };
-       const char *reject = spclchars;
-       int c;
-       int quotes = flag & (EXP_FULL | EXP_CASE);      /* do CTLESC */
-       int breakall = flag & EXP_WORD;
-       int inquotes;
-       size_t length;
-       int startloc;
+       if (block == 0)
+               flags |= WNOHANG;
+       return wait3(status, flags, (struct rusage *)NULL);
+}
 
-       if (!(flag & EXP_VARTILDE)) {
-               reject += 2;
-       } else if (flag & EXP_VARTILDE2) {
-               reject++;
-       }
-       inquotes = 0;
-       length = 0;
-       if (flag & EXP_TILDE) {
-               char *q;
+/*
+ * Wait for a process to terminate.
+ */
+static int
+dowait(int block, struct job *job)
+{
+       int pid;
+       int status;
+       struct job *jp;
+       struct job *thisjob;
+       int state;
 
-               flag &= ~EXP_TILDE;
- tilde:
-               q = p;
-               if (*q == CTLESC && (flag & EXP_QWORD))
-                       q++;
-               if (*q == '~')
-                       p = exptilde(p, q, flag);
+       TRACE(("dowait(%d) called\n", block));
+       pid = waitproc(block, &status);
+       TRACE(("wait returns pid %d, status=%d\n", pid, status));
+       if (pid <= 0)
+               return pid;
+       INT_OFF;
+       thisjob = NULL;
+       for (jp = curjob; jp; jp = jp->prev_job) {
+               struct procstat *sp;
+               struct procstat *spend;
+               if (jp->state == JOBDONE)
+                       continue;
+               state = JOBDONE;
+               spend = jp->ps + jp->nprocs;
+               sp = jp->ps;
+               do {
+                       if (sp->pid == pid) {
+                               TRACE(("Job %d: changing status of proc %d "
+                                       "from 0x%x to 0x%x\n",
+                                       jobno(jp), pid, sp->status, status));
+                               sp->status = status;
+                               thisjob = jp;
+                       }
+                       if (sp->status == -1)
+                               state = JOBRUNNING;
+#if JOBS
+                       if (state == JOBRUNNING)
+                               continue;
+                       if (WIFSTOPPED(sp->status)) {
+                               jp->stopstatus = sp->status;
+                               state = JOBSTOPPED;
+                       }
+#endif
+               } while (++sp < spend);
+               if (thisjob)
+                       goto gotjob;
        }
- start:
-       startloc = expdest - (char *)stackblock();
-       for (;;) {
-               length += strcspn(p + length, reject);
-               c = p[length];
-               if (c && (!(c & 0x80)
-#if ENABLE_ASH_MATH_SUPPORT
-                                       || c == CTLENDARI
+#if JOBS
+       if (!WIFSTOPPED(status))
 #endif
-                  )) {
-                       /* c == '=' || c == ':' || c == CTLENDARI */
-                       length++;
-               }
-               if (length > 0) {
-                       int newloc;
-                       expdest = stack_nputstr(p, length, expdest);
-                       newloc = expdest - (char *)stackblock();
-                       if (breakall && !inquotes && newloc > startloc) {
-                               recordregion(startloc, newloc, 0);
+
+               jobless--;
+       goto out;
+
+ gotjob:
+       if (state != JOBRUNNING) {
+               thisjob->changed = 1;
+
+               if (thisjob->state != state) {
+                       TRACE(("Job %d: changing state from %d to %d\n",
+                               jobno(thisjob), thisjob->state, state));
+                       thisjob->state = state;
+#if JOBS
+                       if (state == JOBSTOPPED) {
+                               set_curjob(thisjob, CUR_STOPPED);
                        }
-                       startloc = newloc;
+#endif
                }
-               p += length + 1;
-               length = 0;
+       }
 
-               switch (c) {
-               case '\0':
-                       goto breakloop;
-               case '=':
-                       if (flag & EXP_VARTILDE2) {
-                               p--;
-                               continue;
-                       }
-                       flag |= EXP_VARTILDE2;
-                       reject++;
-                       /* fall through */
-               case ':':
-                       /*
-                        * sort of a hack - expand tildes in variable
-                        * assignments (after the first '=' and after ':'s).
-                        */
-                       if (*--p == '~') {
-                               goto tilde;
-                       }
-                       continue;
+ out:
+       INT_ON;
+
+       if (thisjob && thisjob == job) {
+               char s[48 + 1];
+               int len;
+
+               len = sprint_status(s, status, 1);
+               if (len) {
+                       s[len] = '\n';
+                       s[len + 1] = 0;
+                       out2str(s);
                }
+       }
+       return pid;
+}
 
-               switch (c) {
-               case CTLENDVAR: /* ??? */
-                       goto breakloop;
-               case CTLQUOTEMARK:
-                       /* "$@" syntax adherence hack */
-                       if (
-                               !inquotes &&
-                               !memcmp(p, dolatstr, 4) &&
-                               (p[4] == CTLQUOTEMARK || (
-                                       p[4] == CTLENDVAR &&
-                                       p[5] == CTLQUOTEMARK
-                               ))
-                       ) {
-                               p = evalvar(p + 1, flag) + 1;
-                               goto start;
-                       }
-                       inquotes = !inquotes;
- addquote:
-                       if (quotes) {
-                               p--;
-                               length++;
-                               startloc++;
-                       }
+#if JOBS
+static void
+showjob(FILE *out, struct job *jp, int mode)
+{
+       struct procstat *ps;
+       struct procstat *psend;
+       int col;
+       int indent;
+       char s[80];
+
+       ps = jp->ps;
+
+       if (mode & SHOW_PGID) {
+               /* just output process (group) id of pipeline */
+               fprintf(out, "%d\n", ps->pid);
+               return;
+       }
+
+       col = fmtstr(s, 16, "[%d]   ", jobno(jp));
+       indent = col;
+
+       if (jp == curjob)
+               s[col - 2] = '+';
+       else if (curjob && jp == curjob->prev_job)
+               s[col - 2] = '-';
+
+       if (mode & SHOW_PID)
+               col += fmtstr(s + col, 16, "%d ", ps->pid);
+
+       psend = ps + jp->nprocs;
+
+       if (jp->state == JOBRUNNING) {
+               strcpy(s + col, "Running");
+               col += sizeof("Running") - 1;
+       } else {
+               int status = psend[-1].status;
+               if (jp->state == JOBSTOPPED)
+                       status = jp->stopstatus;
+               col += sprint_status(s + col, status, 0);
+       }
+
+       goto start;
+
+       do {
+               /* for each process */
+               col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
+ start:
+               fprintf(out, "%s%*c%s",
+                       s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
+               );
+               if (!(mode & SHOW_PID)) {
+                       showpipe(jp, out);
+                       break;
+               }
+               if (++ps == psend) {
+                       outcslow('\n', out);
                        break;
-               case CTLESC:
-                       startloc++;
-                       length++;
-                       goto addquote;
-               case CTLVAR:
-                       p = evalvar(p, flag);
-                       goto start;
-               case CTLBACKQ:
-                       c = 0;
-               case CTLBACKQ|CTLQUOTE:
-                       expbackq(argbackq->n, c, quotes);
-                       argbackq = argbackq->next;
-                       goto start;
-#if ENABLE_ASH_MATH_SUPPORT
-               case CTLENDARI:
-                       p--;
-                       expari(quotes);
-                       goto start;
-#endif
                }
+       } while (1);
+
+       jp->changed = 0;
+
+       if (jp->state == JOBDONE) {
+               TRACE(("showjob: freeing job %d\n", jobno(jp)));
+               freejob(jp);
        }
- breakloop:
-       ;
 }
 
-static char *
-scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
-       int zero)
+static int
+jobscmd(int argc, char **argv)
 {
-       char *loc;
-       char *loc2;
-       char c;
+       int mode, m;
+       FILE *out;
+
+       mode = 0;
+       while ((m = nextopt("lp"))) {
+               if (m == 'l')
+                       mode = SHOW_PID;
+               else
+                       mode = SHOW_PGID;
+       }
+
+       out = stdout;
+       argv = argptr;
+       if (*argv) {
+               do
+                       showjob(out, getjob(*argv,0), mode);
+               while (*++argv);
+       } else
+               showjobs(out, mode);
 
-       loc = startp;
-       loc2 = rmesc;
-       do {
-               int match;
-               const char *s = loc2;
-               c = *loc2;
-               if (zero) {
-                       *loc2 = '\0';
-                       s = rmesc;
-               }
-               match = pmatch(str, s);
-               *loc2 = c;
-               if (match)
-                       return loc;
-               if (quotes && *loc == CTLESC)
-                       loc++;
-               loc++;
-               loc2++;
-       } while (c);
        return 0;
 }
 
-static char *
-scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
-       int zero)
+/*
+ * Print a list of jobs.  If "change" is nonzero, only print jobs whose
+ * statuses have changed since the last call to showjobs.
+ */
+static void
+showjobs(FILE *out, int mode)
 {
-       int esc = 0;
-       char *loc;
-       char *loc2;
+       struct job *jp;
 
-       for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
-               int match;
-               char c = *loc2;
-               const char *s = loc2;
-               if (zero) {
-                       *loc2 = '\0';
-                       s = rmesc;
-               }
-               match = pmatch(str, s);
-               *loc2 = c;
-               if (match)
-                       return loc;
-               loc--;
-               if (quotes) {
-                       if (--esc < 0) {
-                               esc = esclen(startp, loc);
-                       }
-                       if (esc % 2) {
-                               esc--;
-                               loc--;
-                       }
-               }
+       TRACE(("showjobs(%x) called\n", mode));
+
+       /* If not even one one job changed, there is nothing to do */
+       while (dowait(DOWAIT_NORMAL, NULL) > 0)
+               continue;
+
+       for (jp = curjob; jp; jp = jp->prev_job) {
+               if (!(mode & SHOW_CHANGED) || jp->changed)
+                       showjob(out, jp, mode);
        }
-       return 0;
 }
+#endif /* JOBS */
 
-static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
-static void
-varunset(const char *end, const char *var, const char *umsg, int varflags)
+static int
+getstatus(struct job *job)
 {
-       const char *msg;
-       const char *tail;
+       int status;
+       int retval;
 
-       tail = nullstr;
-       msg = "parameter not set";
-       if (umsg) {
-               if (*end == CTLENDVAR) {
-                       if (varflags & VSNUL)
-                               tail = " or null";
-               } else
-                       msg = umsg;
+       status = job->ps[job->nprocs - 1].status;
+       retval = WEXITSTATUS(status);
+       if (!WIFEXITED(status)) {
+#if JOBS
+               retval = WSTOPSIG(status);
+               if (!WIFSTOPPED(status))
+#endif
+               {
+                       /* XXX: limits number of signals */
+                       retval = WTERMSIG(status);
+#if JOBS
+                       if (retval == SIGINT)
+                               job->sigint = 1;
+#endif
+               }
+               retval += 128;
        }
-       ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
+       TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
+               jobno(job), job->nprocs, status, retval));
+       return retval;
 }
 
-static const char *
-subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
+static int
+waitcmd(int argc, char **argv)
 {
-       char *startp;
-       char *loc;
-       int saveherefd = herefd;
-       struct nodelist *saveargbackq = argbackq;
-       int amount;
-       char *rmesc, *rmescend;
-       int zero;
-       char *(*scan)(char *, char *, char *, char *, int , int);
+       struct job *job;
+       int retval;
+       struct job *jp;
 
-       herefd = -1;
-       argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
-       STPUTC('\0', expdest);
-       herefd = saveherefd;
-       argbackq = saveargbackq;
-       startp = stackblock() + startloc;
+       EXSIGON;
 
-       switch (subtype) {
-       case VSASSIGN:
-               setvar(str, startp, 0);
-               amount = startp - expdest;
-               STADJUST(amount, expdest);
-               return startp;
+       nextopt(nullstr);
+       retval = 0;
 
-       case VSQUESTION:
-               varunset(p, str, startp, varflags);
-               /* NOTREACHED */
+       argv = argptr;
+       if (!*argv) {
+               /* wait for all jobs */
+               for (;;) {
+                       jp = curjob;
+                       while (1) {
+                               if (!jp) {
+                                       /* no running procs */
+                                       goto out;
+                               }
+                               if (jp->state == JOBRUNNING)
+                                       break;
+                               jp->waited = 1;
+                               jp = jp->prev_job;
+                       }
+                       dowait(DOWAIT_BLOCK, 0);
+               }
        }
 
-       subtype -= VSTRIMRIGHT;
-#if DEBUG
-       if (subtype < 0 || subtype > 3)
-               abort();
-#endif
+       retval = 127;
+       do {
+               if (**argv != '%') {
+                       pid_t pid = number(*argv);
+                       job = curjob;
+                       goto start;
+                       do {
+                               if (job->ps[job->nprocs - 1].pid == pid)
+                                       break;
+                               job = job->prev_job;
+ start:
+                               if (!job)
+                                       goto repeat;
+                       } while (1);
+               } else
+                       job = getjob(*argv, 0);
+               /* loop until process terminated or stopped */
+               while (job->state == JOBRUNNING)
+                       dowait(DOWAIT_BLOCK, 0);
+               job->waited = 1;
+               retval = getstatus(job);
+ repeat:
+               ;
+       } while (*++argv);
 
-       rmesc = startp;
-       rmescend = stackblock() + strloc;
-       if (quotes) {
-               rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
-               if (rmesc != startp) {
-                       rmescend = expdest;
-                       startp = stackblock() + startloc;
-               }
-       }
-       rmescend--;
-       str = stackblock() + strloc;
-       preglob(str, varflags & VSQUOTE, 0);
+ out:
+       return retval;
+}
 
-       /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
-       zero = subtype >> 1;
-       /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
-       scan = (subtype & 1) ^ zero ? scanleft : scanright;
+static struct job *
+growjobtab(void)
+{
+       size_t len;
+       ptrdiff_t offset;
+       struct job *jp, *jq;
 
-       loc = scan(startp, rmesc, rmescend, str, quotes, zero);
-       if (loc) {
-               if (zero) {
-                       memmove(startp, loc, str - loc);
-                       loc = startp + (str - loc) - 1;
+       len = njobs * sizeof(*jp);
+       jq = jobtab;
+       jp = ckrealloc(jq, len + 4 * sizeof(*jp));
+
+       offset = (char *)jp - (char *)jq;
+       if (offset) {
+               /* Relocate pointers */
+               size_t l = len;
+
+               jq = (struct job *)((char *)jq + l);
+               while (l) {
+                       l -= sizeof(*jp);
+                       jq--;
+#define joff(p) ((struct job *)((char *)(p) + l))
+#define jmove(p) (p) = (void *)((char *)(p) + offset)
+                       if (joff(jp)->ps == &jq->ps0)
+                               jmove(joff(jp)->ps);
+                       if (joff(jp)->prev_job)
+                               jmove(joff(jp)->prev_job);
                }
-               *loc = '\0';
-               amount = loc - expdest;
-               STADJUST(amount, expdest);
+               if (curjob)
+                       jmove(curjob);
+#undef joff
+#undef jmove
        }
-       return loc;
+
+       njobs += 4;
+       jobtab = jp;
+       jp = (struct job *)((char *)jp + len);
+       jq = jp + 3;
+       do {
+               jq->used = 0;
+       } while (--jq >= jp);
+       return jp;
 }
 
 /*
- * Add the value of a specialized variable to the stack string.
+ * Return a new job structure.
+ * Called with interrupts off.
  */
-static ssize_t
-varvalue(char *name, int varflags, int flags)
+static struct job *
+makejob(union node *node, int nprocs)
 {
-       int num;
-       char *p;
        int i;
-       int sep = 0;
-       int sepq = 0;
-       ssize_t len = 0;
-       char **ap;
-       int syntax;
-       int quoted = varflags & VSQUOTE;
-       int subtype = varflags & VSTYPE;
-       int quotes = flags & (EXP_FULL | EXP_CASE);
-
-       if (quoted && (flags & EXP_FULL))
-               sep = 1 << CHAR_BIT;
+       struct job *jp;
 
-       syntax = quoted ? DQSYNTAX : BASESYNTAX;
-       switch (*name) {
-       case '$':
-               num = rootpid;
-               goto numvar;
-       case '?':
-               num = exitstatus;
-               goto numvar;
-       case '#':
-               num = shellparam.nparam;
-               goto numvar;
-       case '!':
-               num = backgndpid;
-               if (num == 0)
-                       return -1;
- numvar:
-               len = cvtnum(num);
-               break;
-       case '-':
-               p = makestrspace(NOPTS, expdest);
-               for (i = NOPTS - 1; i >= 0; i--) {
-                       if (optlist[i]) {
-                               USTPUTC(optletters(i), p);
-                               len++;
-                       }
+       for (i = njobs, jp = jobtab; ; jp++) {
+               if (--i < 0) {
+                       jp = growjobtab();
+                       break;
                }
-               expdest = p;
+               if (jp->used == 0)
+                       break;
+               if (jp->state != JOBDONE || !jp->waited)
+                       continue;
+#if JOBS
+               if (jobctl)
+                       continue;
+#endif
+               freejob(jp);
                break;
-       case '@':
-               if (sep)
-                       goto param;
-               /* fall through */
-       case '*':
-               sep = ifsset() ? SC2INT(ifsval()[0]) : ' ';
-               if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
-                       sepq = 1;
- param:
-               ap = shellparam.p;
-               if (!ap)
-                       return -1;
-               while ((p = *ap++)) {
-                       size_t partlen;
-
-                       partlen = strlen(p);
-                       len += partlen;
-
-                       if (!(subtype == VSPLUS || subtype == VSLENGTH))
-                               memtodest(p, partlen, syntax, quotes);
-
-                       if (*ap && sep) {
-                               char *q;
-
-                               len++;
-                               if (subtype == VSPLUS || subtype == VSLENGTH) {
-                                       continue;
-                               }
-                               q = expdest;
-                               if (sepq)
-                                       STPUTC(CTLESC, q);
-                               STPUTC(sep, q);
-                               expdest = q;
-                       }
-               }
-               return len;
-       case '0':
-       case '1':
-       case '2':
-       case '3':
-       case '4':
-       case '5':
-       case '6':
-       case '7':
-       case '8':
-       case '9':
-               num = atoi(name);
-               if (num < 0 || num > shellparam.nparam)
-                       return -1;
-               p = num ? shellparam.p[num - 1] : arg0;
-               goto value;
-       default:
-               p = lookupvar(name);
- value:
-               if (!p)
-                       return -1;
-
-               len = strlen(p);
-               if (!(subtype == VSPLUS || subtype == VSLENGTH))
-                       memtodest(p, len, syntax, quotes);
-               return len;
        }
-
-       if (subtype == VSPLUS || subtype == VSLENGTH)
-               STADJUST(-len, expdest);
-       return len;
+       memset(jp, 0, sizeof(*jp));
+#if JOBS
+       if (jobctl)
+               jp->jobctl = 1;
+#endif
+       jp->prev_job = curjob;
+       curjob = jp;
+       jp->used = 1;
+       jp->ps = &jp->ps0;
+       if (nprocs > 1) {
+               jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
+       }
+       TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
+                               jobno(jp)));
+       return jp;
 }
 
+#if JOBS
 /*
- * Expand a variable, and return a pointer to the next character in the
- * input string.
- */
-static char *
-evalvar(char *p, int flag)
-{
-       int subtype;
-       int varflags;
-       char *var;
-       int patloc;
-       int c;
-       int startloc;
-       ssize_t varlen;
-       int easy;
-       int quotes;
-       int quoted;
-
-       quotes = flag & (EXP_FULL | EXP_CASE);
-       varflags = *p++;
-       subtype = varflags & VSTYPE;
-       quoted = varflags & VSQUOTE;
-       var = p;
-       easy = (!quoted || (*var == '@' && shellparam.nparam));
-       startloc = expdest - (char *)stackblock();
-       p = strchr(p, '=') + 1;
-
- again:
-       varlen = varvalue(var, varflags, flag);
-       if (varflags & VSNUL)
-               varlen--;
+ * Return a string identifying a command (to be printed by the
+ * jobs command).
+ */
+static char *cmdnextc;
 
-       if (subtype == VSPLUS) {
-               varlen = -1 - varlen;
-               goto vsplus;
-       }
+static void
+cmdputs(const char *s)
+{
+       const char *p, *str;
+       char c, cc[2] = " ";
+       char *nextc;
+       int subtype = 0;
+       int quoted = 0;
+       static const char vstype[VSTYPE + 1][4] = {
+               "", "}", "-", "+", "?", "=",
+               "%", "%%", "#", "##"
+       };
 
-       if (subtype == VSMINUS) {
- vsplus:
-               if (varlen < 0) {
-                       argstr(
-                               p, flag | EXP_TILDE |
-                                       (quoted ?  EXP_QWORD : EXP_WORD)
-                       );
-                       goto end;
+       nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
+       p = s;
+       while ((c = *p++) != 0) {
+               str = 0;
+               switch (c) {
+               case CTLESC:
+                       c = *p++;
+                       break;
+               case CTLVAR:
+                       subtype = *p++;
+                       if ((subtype & VSTYPE) == VSLENGTH)
+                               str = "${#";
+                       else
+                               str = "${";
+                       if (!(subtype & VSQUOTE) == !(quoted & 1))
+                               goto dostr;
+                       quoted ^= 1;
+                       c = '"';
+                       break;
+               case CTLENDVAR:
+                       str = "\"}" + !(quoted & 1);
+                       quoted >>= 1;
+                       subtype = 0;
+                       goto dostr;
+               case CTLBACKQ:
+                       str = "$(...)";
+                       goto dostr;
+               case CTLBACKQ+CTLQUOTE:
+                       str = "\"$(...)\"";
+                       goto dostr;
+#if ENABLE_ASH_MATH_SUPPORT
+               case CTLARI:
+                       str = "$((";
+                       goto dostr;
+               case CTLENDARI:
+                       str = "))";
+                       goto dostr;
+#endif
+               case CTLQUOTEMARK:
+                       quoted ^= 1;
+                       c = '"';
+                       break;
+               case '=':
+                       if (subtype == 0)
+                               break;
+                       if ((subtype & VSTYPE) != VSNORMAL)
+                               quoted <<= 1;
+                       str = vstype[subtype & VSTYPE];
+                       if (subtype & VSNUL)
+                               c = ':';
+                       else
+                               goto checkstr;
+                       break;
+               case '\'':
+               case '\\':
+               case '"':
+               case '$':
+                       /* These can only happen inside quotes */
+                       cc[0] = c;
+                       str = cc;
+                       c = '\\';
+                       break;
+               default:
+                       break;
                }
-               if (easy)
-                       goto record;
-               goto end;
-       }
-
-       if (subtype == VSASSIGN || subtype == VSQUESTION) {
-               if (varlen < 0) {
-                       if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
-                               varflags &= ~VSNUL;
-                               /*
-                                * Remove any recorded regions beyond
-                                * start of variable
-                                */
-                               removerecordregions(startloc);
-                               goto again;
-                       }
-                       goto end;
+               USTPUTC(c, nextc);
+ checkstr:
+               if (!str)
+                       continue;
+ dostr:
+               while ((c = *str++)) {
+                       USTPUTC(c, nextc);
                }
-               if (easy)
-                       goto record;
-               goto end;
        }
+       if (quoted & 1) {
+               USTPUTC('"', nextc);
+       }
+       *nextc = 0;
+       cmdnextc = nextc;
+}
 
-       if (varlen < 0 && uflag)
-               varunset(p, var, 0, 0);
+/* cmdtxt() and cmdlist() call each other */
+static void cmdtxt(union node *n);
 
-       if (subtype == VSLENGTH) {
-               cvtnum(varlen > 0 ? varlen : 0);
-               goto record;
+static void
+cmdlist(union node *np, int sep)
+{
+       for (; np; np = np->narg.next) {
+               if (!sep)
+                       cmdputs(" ");
+               cmdtxt(np);
+               if (sep && np->narg.next)
+                       cmdputs(" ");
        }
+}
 
-       if (subtype == VSNORMAL) {
-               if (!easy)
-                       goto end;
- record:
-               recordregion(startloc, expdest - (char *)stackblock(), quoted);
-               goto end;
-       }
+static void
+cmdtxt(union node *n)
+{
+       union node *np;
+       struct nodelist *lp;
+       const char *p;
+       char s[2];
 
-#if DEBUG
-       switch (subtype) {
-       case VSTRIMLEFT:
-       case VSTRIMLEFTMAX:
-       case VSTRIMRIGHT:
-       case VSTRIMRIGHTMAX:
-               break;
+       if (!n)
+               return;
+       switch (n->type) {
        default:
+#if DEBUG
                abort();
-       }
 #endif
-
-       if (varlen >= 0) {
-               /*
-                * Terminate the string and start recording the pattern
-                * right after it
-                */
-               STPUTC('\0', expdest);
-               patloc = expdest - (char *)stackblock();
-               if (subevalvar(p, NULL, patloc, subtype,
-                               startloc, varflags, quotes) == 0) {
-                       int amount = expdest - (
-                               (char *)stackblock() + patloc - 1
-                       );
-                       STADJUST(-amount, expdest);
-               }
-               /* Remove any recorded regions beyond start of variable */
-               removerecordregions(startloc);
-               goto record;
-       }
-
- end:
-       if (subtype != VSNORMAL) {      /* skip to end of alternative */
-               int nesting = 1;
+       case NPIPE:
+               lp = n->npipe.cmdlist;
                for (;;) {
-                       c = *p++;
-                       if (c == CTLESC)
-                               p++;
-                       else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
-                               if (varlen >= 0)
-                                       argbackq = argbackq->next;
-                       } else if (c == CTLVAR) {
-                               if ((*p++ & VSTYPE) != VSNORMAL)
-                                       nesting++;
-                       } else if (c == CTLENDVAR) {
-                               if (--nesting == 0)
-                                       break;
-                       }
+                       cmdtxt(lp->n);
+                       lp = lp->next;
+                       if (!lp)
+                               break;
+                       cmdputs(" | ");
                }
+               break;
+       case NSEMI:
+               p = "; ";
+               goto binop;
+       case NAND:
+               p = " && ";
+               goto binop;
+       case NOR:
+               p = " || ";
+ binop:
+               cmdtxt(n->nbinary.ch1);
+               cmdputs(p);
+               n = n->nbinary.ch2;
+               goto donode;
+       case NREDIR:
+       case NBACKGND:
+               n = n->nredir.n;
+               goto donode;
+       case NNOT:
+               cmdputs("!");
+               n = n->nnot.com;
+ donode:
+               cmdtxt(n);
+               break;
+       case NIF:
+               cmdputs("if ");
+               cmdtxt(n->nif.test);
+               cmdputs("; then ");
+               n = n->nif.ifpart;
+               if (n->nif.elsepart) {
+                       cmdtxt(n);
+                       cmdputs("; else ");
+                       n = n->nif.elsepart;
+               }
+               p = "; fi";
+               goto dotail;
+       case NSUBSHELL:
+               cmdputs("(");
+               n = n->nredir.n;
+               p = ")";
+               goto dotail;
+       case NWHILE:
+               p = "while ";
+               goto until;
+       case NUNTIL:
+               p = "until ";
+ until:
+               cmdputs(p);
+               cmdtxt(n->nbinary.ch1);
+               n = n->nbinary.ch2;
+               p = "; done";
+ dodo:
+               cmdputs("; do ");
+ dotail:
+               cmdtxt(n);
+               goto dotail2;
+       case NFOR:
+               cmdputs("for ");
+               cmdputs(n->nfor.var);
+               cmdputs(" in ");
+               cmdlist(n->nfor.args, 1);
+               n = n->nfor.body;
+               p = "; done";
+               goto dodo;
+       case NDEFUN:
+               cmdputs(n->narg.text);
+               p = "() { ... }";
+               goto dotail2;
+       case NCMD:
+               cmdlist(n->ncmd.args, 1);
+               cmdlist(n->ncmd.redirect, 0);
+               break;
+       case NARG:
+               p = n->narg.text;
+ dotail2:
+               cmdputs(p);
+               break;
+       case NHERE:
+       case NXHERE:
+               p = "<<...";
+               goto dotail2;
+       case NCASE:
+               cmdputs("case ");
+               cmdputs(n->ncase.expr->narg.text);
+               cmdputs(" in ");
+               for (np = n->ncase.cases; np; np = np->nclist.next) {
+                       cmdtxt(np->nclist.pattern);
+                       cmdputs(") ");
+                       cmdtxt(np->nclist.body);
+                       cmdputs(";; ");
+               }
+               p = "esac";
+               goto dotail2;
+       case NTO:
+               p = ">";
+               goto redir;
+       case NCLOBBER:
+               p = ">|";
+               goto redir;
+       case NAPPEND:
+               p = ">>";
+               goto redir;
+       case NTOFD:
+               p = ">&";
+               goto redir;
+       case NFROM:
+               p = "<";
+               goto redir;
+       case NFROMFD:
+               p = "<&";
+               goto redir;
+       case NFROMTO:
+               p = "<>";
+ redir:
+               s[0] = n->nfile.fd + '0';
+               s[1] = '\0';
+               cmdputs(s);
+               cmdputs(p);
+               if (n->type == NTOFD || n->type == NFROMFD) {
+                       s[0] = n->ndup.dupfd + '0';
+                       p = s;
+                       goto dotail2;
+               }
+               n = n->nfile.fname;
+               goto donode;
        }
-       return p;
-}
-
-/*
- * Break the argument string into pieces based upon IFS and add the
- * strings to the argument list.  The regions of the string to be
- * searched for IFS characters have been stored by recordregion.
- */
-static void
-ifsbreakup(char *string, struct arglist *arglist)
-{
-       struct ifsregion *ifsp;
-       struct strlist *sp;
-       char *start;
-       char *p;
-       char *q;
-       const char *ifs, *realifs;
-       int ifsspc;
-       int nulonly;
-
-       start = string;
-       if (ifslastp != NULL) {
-               ifsspc = 0;
-               nulonly = 0;
-               realifs = ifsset() ? ifsval() : defifs;
-               ifsp = &ifsfirst;
-               do {
-                       p = string + ifsp->begoff;
-                       nulonly = ifsp->nulonly;
-                       ifs = nulonly ? nullstr : realifs;
-                       ifsspc = 0;
-                       while (p < string + ifsp->endoff) {
-                               q = p;
-                               if (*p == CTLESC)
-                                       p++;
-                               if (!strchr(ifs, *p)) {
-                                       p++;
-                                       continue;
-                               }
-                               if (!nulonly)
-                                       ifsspc = (strchr(defifs, *p) != NULL);
-                               /* Ignore IFS whitespace at start */
-                               if (q == start && ifsspc) {
-                                       p++;
-                                       start = p;
-                                       continue;
-                               }
-                               *q = '\0';
-                               sp = stalloc(sizeof(*sp));
-                               sp->text = start;
-                               *arglist->lastp = sp;
-                               arglist->lastp = &sp->next;
-                               p++;
-                               if (!nulonly) {
-                                       for (;;) {
-                                               if (p >= string + ifsp->endoff) {
-                                                       break;
-                                               }
-                                               q = p;
-                                               if (*p == CTLESC)
-                                                       p++;
-                                               if (strchr(ifs, *p) == NULL ) {
-                                                       p = q;
-                                                       break;
-                                               } else if (strchr(defifs, *p) == NULL) {
-                                                       if (ifsspc) {
-                                                               p++;
-                                                               ifsspc = 0;
-                                                       } else {
-                                                               p = q;
-                                                               break;
-                                                       }
-                                               } else
-                                                       p++;
-                                       }
-                               }
-                               start = p;
-                       } /* while */
-                       ifsp = ifsp->next;
-               } while (ifsp != NULL);
-               if (nulonly)
-                       goto add;
-       }
-
-       if (!*start)
-               return;
-
- add:
-       sp = stalloc(sizeof(*sp));
-       sp->text = start;
-       *arglist->lastp = sp;
-       arglist->lastp = &sp->next;
 }
 
-static void
-ifsfree(void)
+static char *
+commandtext(union node *n)
 {
-       struct ifsregion *p;
+       char *name;
 
-       INT_OFF;
-       p = ifsfirst.next;
-       do {
-               struct ifsregion *ifsp;
-               ifsp = p->next;
-               free(p);
-               p = ifsp;
-       } while (p);
-       ifslastp = NULL;
-       ifsfirst.next = NULL;
-       INT_ON;
+       STARTSTACKSTR(cmdnextc);
+       cmdtxt(n);
+       name = stackblock();
+       TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
+                       name, cmdnextc, cmdnextc));
+       return ckstrdup(name);
 }
+#endif /* JOBS */
 
 /*
- * Add a file name to the list.
+ * Fork off a subshell.  If we are doing job control, give the subshell its
+ * own process group.  Jp is a job structure that the job is to be added to.
+ * N is the command that will be evaluated by the child.  Both jp and n may
+ * be NULL.  The mode parameter can be one of the following:
+ *      FORK_FG - Fork off a foreground process.
+ *      FORK_BG - Fork off a background process.
+ *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
+ *                   process group even if job control is on.
+ *
+ * When job control is turned off, background processes have their standard
+ * input redirected to /dev/null (except for the second and later processes
+ * in a pipeline).
+ *
+ * Called with interrupts off.
  */
-static void
-addfname(const char *name)
-{
-       struct strlist *sp;
-
-       sp = stalloc(sizeof(*sp));
-       sp->text = ststrdup(name);
-       *exparg.lastp = sp;
-       exparg.lastp = &sp->next;
-}
-
-static char *expdir;
-
 /*
- * Do metacharacter (i.e. *, ?, [...]) expansion.
+ * Clear traps on a fork.
  */
 static void
-expmeta(char *enddir, char *name)
+clear_traps(void)
 {
-       char *p;
-       const char *cp;
-       char *start;
-       char *endname;
-       int metaflag;
-       struct stat statb;
-       DIR *dirp;
-       struct dirent *dp;
-       int atend;
-       int matchdot;
+       char **tp;
 
-       metaflag = 0;
-       start = name;
-       for (p = name; *p; p++) {
-               if (*p == '*' || *p == '?')
-                       metaflag = 1;
-               else if (*p == '[') {
-                       char *q = p + 1;
-                       if (*q == '!')
-                               q++;
-                       for (;;) {
-                               if (*q == '\\')
-                                       q++;
-                               if (*q == '/' || *q == '\0')
-                                       break;
-                               if (*++q == ']') {
-                                       metaflag = 1;
-                                       break;
-                               }
-                       }
-               } else if (*p == '\\')
-                       p++;
-               else if (*p == '/') {
-                       if (metaflag)
-                               goto out;
-                       start = p + 1;
+       for (tp = trap; tp < &trap[NSIG]; tp++) {
+               if (*tp && **tp) {      /* trap not NULL or SIG_IGN */
+                       INT_OFF;
+                       free(*tp);
+                       *tp = NULL;
+                       if (tp != &trap[0])
+                               setsignal(tp - trap);
+                       INT_ON;
                }
        }
- out:
-       if (metaflag == 0) {    /* we've reached the end of the file name */
-               if (enddir != expdir)
-                       metaflag++;
-               p = name;
-               do {
-                       if (*p == '\\')
-                               p++;
-                       *enddir++ = *p;
-               } while (*p++);
-               if (metaflag == 0 || lstat(expdir, &statb) >= 0)
-                       addfname(expdir);
-               return;
-       }
-       endname = p;
-       if (name < start) {
-               p = name;
-               do {
-                       if (*p == '\\')
-                               p++;
-                       *enddir++ = *p++;
-               } while (p < start);
-       }
-       if (enddir == expdir) {
-               cp = ".";
-       } else if (enddir == expdir + 1 && *expdir == '/') {
-               cp = "/";
-       } else {
-               cp = expdir;
-               enddir[-1] = '\0';
-       }
-       dirp = opendir(cp);
-       if (dirp == NULL)
-               return;
-       if (enddir != expdir)
-               enddir[-1] = '/';
-       if (*endname == 0) {
-               atend = 1;
-       } else {
-               atend = 0;
-               *endname++ = '\0';
-       }
-       matchdot = 0;
-       p = start;
-       if (*p == '\\')
-               p++;
-       if (*p == '.')
-               matchdot++;
-       while (! intpending && (dp = readdir(dirp)) != NULL) {
-               if (dp->d_name[0] == '.' && ! matchdot)
-                       continue;
-               if (pmatch(start, dp->d_name)) {
-                       if (atend) {
-                               strcpy(enddir, dp->d_name);
-                               addfname(expdir);
-                       } else {
-                               for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
-                                       continue;
-                               p[-1] = '/';
-                               expmeta(p, endname);
-                       }
+}
+/* lives far away from here, needed for forkchild */
+static void closescript(void);
+static void
+forkchild(struct job *jp, union node *n, int mode)
+{
+       int oldlvl;
+
+       TRACE(("Child shell %d\n", getpid()));
+       oldlvl = shlvl;
+       shlvl++;
+
+       closescript();
+       clear_traps();
+#if JOBS
+       /* do job control only in root shell */
+       jobctl = 0;
+       if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
+               pid_t pgrp;
+
+               if (jp->nprocs == 0)
+                       pgrp = getpid();
+               else
+                       pgrp = jp->ps[0].pid;
+               /* This can fail because we are doing it in the parent also */
+               (void)setpgid(0, pgrp);
+               if (mode == FORK_FG)
+                       xtcsetpgrp(ttyfd, pgrp);
+               setsignal(SIGTSTP);
+               setsignal(SIGTTOU);
+       } else
+#endif
+       if (mode == FORK_BG) {
+               ignoresig(SIGINT);
+               ignoresig(SIGQUIT);
+               if (jp->nprocs == 0) {
+                       close(0);
+                       if (open(bb_dev_null, O_RDONLY) != 0)
+                               ash_msg_and_raise_error("can't open %s", bb_dev_null);
                }
        }
-       closedir(dirp);
-       if (! atend)
-               endname[-1] = '/';
+       if (!oldlvl && iflag) {
+               setsignal(SIGINT);
+               setsignal(SIGQUIT);
+               setsignal(SIGTERM);
+       }
+       for (jp = curjob; jp; jp = jp->prev_job)
+               freejob(jp);
+       jobless = 0;
 }
 
-static struct strlist *
-msort(struct strlist *list, int len)
+static void
+forkparent(struct job *jp, union node *n, int mode, pid_t pid)
 {
-       struct strlist *p, *q = NULL;
-       struct strlist **lpp;
-       int half;
-       int n;
+       TRACE(("In parent shell: child = %d\n", pid));
+       if (!jp) {
+               while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
+               jobless++;
+               return;
+       }
+#if JOBS
+       if (mode != FORK_NOJOB && jp->jobctl) {
+               int pgrp;
 
-       if (len <= 1)
-               return list;
-       half = len >> 1;
-       p = list;
-       for (n = half; --n >= 0; ) {
-               q = p;
-               p = p->next;
+               if (jp->nprocs == 0)
+                       pgrp = pid;
+               else
+                       pgrp = jp->ps[0].pid;
+               /* This can fail because we are doing it in the child also */
+               setpgid(pid, pgrp);
        }
-       q->next = NULL;                 /* terminate first half of list */
-       q = msort(list, half);          /* sort first half of list */
-       p = msort(p, len - half);               /* sort second half */
-       lpp = &list;
-       for (;;) {
-#if ENABLE_LOCALE_SUPPORT
-               if (strcoll(p->text, q->text) < 0)
-#else
-               if (strcmp(p->text, q->text) < 0)
 #endif
-                                               {
-                       *lpp = p;
-                       lpp = &p->next;
-                       p = *lpp;
-                       if (p == NULL) {
-                               *lpp = q;
-                               break;
-                       }
-               } else {
-                       *lpp = q;
-                       lpp = &q->next;
-                       q = *lpp;
-                       if (q == NULL) {
-                               *lpp = p;
-                               break;
-                       }
-               }
+       if (mode == FORK_BG) {
+               backgndpid = pid;               /* set $! */
+               set_curjob(jp, CUR_RUNNING);
+       }
+       if (jp) {
+               struct procstat *ps = &jp->ps[jp->nprocs++];
+               ps->pid = pid;
+               ps->status = -1;
+               ps->cmd = nullstr;
+#if JOBS
+               if (jobctl && n)
+                       ps->cmd = commandtext(n);
+#endif
        }
-       return list;
 }
 
-/*
- * Sort the results of file name expansion.  It calculates the number of
- * strings to sort and then calls msort (short for merge sort) to do the
- * work.
- */
-static struct strlist *
-expsort(struct strlist *str)
+static int
+forkshell(struct job *jp, union node *n, int mode)
 {
-       int len;
-       struct strlist *sp;
+       int pid;
 
-       len = 0;
-       for (sp = str; sp; sp = sp->next)
-               len++;
-       return msort(str, len);
-}
-
-static void
-expandmeta(struct strlist *str, int flag)
-{
-       static const char metachars[] = {
-               '*', '?', '[', 0
-       };
-       /* TODO - EXP_REDIR */
-
-       while (str) {
-               struct strlist **savelastp;
-               struct strlist *sp;
-               char *p;
-
-               if (fflag)
-                       goto nometa;
-               if (!strpbrk(str->text, metachars))
-                       goto nometa;
-               savelastp = exparg.lastp;
-
-               INT_OFF;
-               p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
-               {
-                       int i = strlen(str->text);
-                       expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
-               }
-
-               expmeta(expdir, p);
-               free(expdir);
-               if (p != str->text)
-                       free(p);
-               INT_ON;
-               if (exparg.lastp == savelastp) {
-                       /*
-                        * no matches
-                        */
- nometa:
-                       *exparg.lastp = str;
-                       rmescapes(str->text);
-                       exparg.lastp = &str->next;
-               } else {
-                       *exparg.lastp = NULL;
-                       *savelastp = sp = expsort(*savelastp);
-                       while (sp->next != NULL)
-                               sp = sp->next;
-                       exparg.lastp = &sp->next;
-               }
-               str = str->next;
-       }
+       TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
+       pid = fork();
+       if (pid < 0) {
+               TRACE(("Fork failed, errno=%d", errno));
+               if (jp)
+                       freejob(jp);
+               ash_msg_and_raise_error("cannot fork");
+       }
+       if (pid == 0)
+               forkchild(jp, n, mode);
+       else
+               forkparent(jp, n, mode, pid);
+       return pid;
 }
 
 /*
- * Perform variable substitution and command substitution on an argument,
- * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
- * perform splitting and file name expansion.  When arglist is NULL, perform
- * here document expansion.
+ * Wait for job to finish.
+ *
+ * Under job control we have the problem that while a child process is
+ * running interrupts generated by the user are sent to the child but not
+ * to the shell.  This means that an infinite loop started by an inter-
+ * active user may be hard to kill.  With job control turned off, an
+ * interactive user may place an interactive program inside a loop.  If
+ * the interactive program catches interrupts, the user doesn't want
+ * these interrupts to also abort the loop.  The approach we take here
+ * is to have the shell ignore interrupt signals while waiting for a
+ * foreground process to terminate, and then send itself an interrupt
+ * signal if the child process was terminated by an interrupt signal.
+ * Unfortunately, some programs want to do a bit of cleanup and then
+ * exit on interrupt; unless these processes terminate themselves by
+ * sending a signal to themselves (instead of calling exit) they will
+ * confuse this approach.
+ *
+ * Called with interrupts off.
  */
-static void
-expandarg(union node *arg, struct arglist *arglist, int flag)
+static int
+waitforjob(struct job *jp)
 {
-       struct strlist *sp;
-       char *p;
+       int st;
 
-       argbackq = arg->narg.backquote;
-       STARTSTACKSTR(expdest);
-       ifsfirst.next = NULL;
-       ifslastp = NULL;
-       argstr(arg->narg.text, flag);
-       p = _STPUTC('\0', expdest);
-       expdest = p - 1;
-       if (arglist == NULL) {
-               return;                 /* here document expanded */
-       }
-       p = grabstackstr(p);
-       exparg.lastp = &exparg.list;
-       /*
-        * TODO - EXP_REDIR
-        */
-       if (flag & EXP_FULL) {
-               ifsbreakup(p, &exparg);
-               *exparg.lastp = NULL;
-               exparg.lastp = &exparg.list;
-               expandmeta(exparg.list, flag);
-       } else {
-               if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
-                       rmescapes(p);
-               sp = stalloc(sizeof(*sp));
-               sp->text = p;
-               *exparg.lastp = sp;
-               exparg.lastp = &sp->next;
+       TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
+       while (jp->state == JOBRUNNING) {
+               dowait(DOWAIT_BLOCK, jp);
        }
-       if (ifsfirst.next)
-               ifsfree();
-       *exparg.lastp = NULL;
-       if (exparg.list) {
-               *arglist->lastp = exparg.list;
-               arglist->lastp = exparg.lastp;
+       st = getstatus(jp);
+#if JOBS
+       if (jp->jobctl) {
+               xtcsetpgrp(ttyfd, rootpid);
+               /*
+                * This is truly gross.
+                * If we're doing job control, then we did a TIOCSPGRP which
+                * caused us (the shell) to no longer be in the controlling
+                * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
+                * intuit from the subprocess exit status whether a SIGINT
+                * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
+                */
+               if (jp->sigint)
+                       raise(SIGINT);
        }
+       if (jp->state == JOBDONE)
+#endif
+               freejob(jp);
+       return st;
 }
 
 /*
- * Expand shell variables and backquotes inside a here document.
+ * return 1 if there are stopped jobs, otherwise 0
  */
-static void
-expandhere(union node *arg, int fd)
+static int
+stoppedjobs(void)
 {
-       herefd = fd;
-       expandarg(arg, (struct arglist *)NULL, 0);
-       full_write(fd, stackblock(), expdest - (char *)stackblock());
+       struct job *jp;
+       int retval;
+
+       retval = 0;
+       if (job_warning)
+               goto out;
+       jp = curjob;
+       if (jp && jp->state == JOBSTOPPED) {
+               out2str("You have stopped jobs.\n");
+               job_warning = 2;
+               retval++;
+       }
+ out:
+       return retval;
 }
 
-/*
- * Returns true if the pattern matches the string.
+
+/* ============ redir.c
+ *
+ * Code for dealing with input/output redirection.
  */
-static int
-patmatch(char *pattern, const char *string)
-{
-       return pmatch(preglob(pattern, 0, 0), string);
-}
+
+#define EMPTY -2                /* marks an unused slot in redirtab */
+#ifndef PIPE_BUF
+# define PIPESIZE 4096          /* amount of buffering in a pipe */
+#else
+# define PIPESIZE PIPE_BUF
+#endif
 
 /*
- * See if a pattern matches in a case statement.
+ * Open a file in noclobber mode.
+ * The code was copied from bash.
  */
 static int
-casematch(union node *pattern, char *val)
+noclobberopen(const char *fname)
 {
-       struct stackmark smark;
-       int result;
-
-       setstackmark(&smark);
-       argbackq = pattern->narg.backquote;
-       STARTSTACKSTR(expdest);
-       ifslastp = NULL;
-       argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
-       STACKSTRNUL(expdest);
-       result = patmatch(stackblock(), val);
-       popstackmark(&smark);
-       return result;
-}
-
+       int r, fd;
+       struct stat finfo, finfo2;
 
-/* ============ find_command */
+       /*
+        * If the file exists and is a regular file, return an error
+        * immediately.
+        */
+       r = stat(fname, &finfo);
+       if (r == 0 && S_ISREG(finfo.st_mode)) {
+               errno = EEXIST;
+               return -1;
+       }
 
-struct builtincmd {
-       const char *name;
-       int (*builtin)(int, char **);
-       /* unsigned flags; */
-};
-#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
-#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
-#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
+       /*
+        * If the file was not present (r != 0), make sure we open it
+        * exclusively so that if it is created before we open it, our open
+        * will fail.  Make sure that we do not truncate an existing file.
+        * Note that we don't turn on O_EXCL unless the stat failed -- if the
+        * file was not a regular file, we leave O_EXCL off.
+        */
+       if (r != 0)
+               return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
+       fd = open(fname, O_WRONLY|O_CREAT, 0666);
 
-struct cmdentry {
-       int cmdtype;
-       union param {
-               int index;
-               const struct builtincmd *cmd;
-               struct funcnode *func;
-       } u;
-};
-/* values of cmdtype */
-#define CMDUNKNOWN      -1      /* no entry in table for command */
-#define CMDNORMAL       0       /* command is an executable program */
-#define CMDFUNCTION     1       /* command is a shell function */
-#define CMDBUILTIN      2       /* command is a shell builtin */
+       /* If the open failed, return the file descriptor right away. */
+       if (fd < 0)
+               return fd;
 
-/* action to find_command() */
-#define DO_ERR          0x01    /* prints errors */
-#define DO_ABS          0x02    /* checks absolute paths */
-#define DO_NOFUNC       0x04    /* don't return shell functions, for command */
-#define DO_ALTPATH      0x08    /* using alternate path */
-#define DO_ALTBLTIN     0x20    /* %builtin in alt. path */
+       /*
+        * OK, the open succeeded, but the file may have been changed from a
+        * non-regular file to a regular file between the stat and the open.
+        * We are assuming that the O_EXCL open handles the case where FILENAME
+        * did not exist and is symlinked to an existing file between the stat
+        * and open.
+        */
 
-static void find_command(char *, struct cmdentry *, int, const char *);
+       /*
+        * If we can open it and fstat the file descriptor, and neither check
+        * revealed that it was a regular file, and the file has not been
+        * replaced, return the file descriptor.
+        */
+       if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
+        && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
+               return fd;
 
-
-/* ============ Hashing commands */
+       /* The file has been replaced.  badness. */
+       close(fd);
+       errno = EEXIST;
+       return -1;
+}
 
 /*
- * When commands are first encountered, they are entered in a hash table.
- * This ensures that a full path search will not have to be done for them
- * on each invocation.
- *
- * We should investigate converting to a linear search, even though that
- * would make the command name "hash" a misnomer.
+ * Handle here documents.  Normally we fork off a process to write the
+ * data to a pipe.  If the document is short, we can stuff the data in
+ * the pipe without forking.
  */
-
-#define CMDTABLESIZE 31         /* should be prime */
-#define ARB 1                   /* actual size determined at run time */
-
-struct tblentry {
-       struct tblentry *next;  /* next entry in hash chain */
-       union param param;      /* definition of builtin function */
-       short cmdtype;          /* index identifying command */
-       char rehash;            /* if set, cd done since entry created */
-       char cmdname[ARB];      /* name of command */
-};
-
-static struct tblentry *cmdtable[CMDTABLESIZE];
-static int builtinloc = -1;             /* index in path of %builtin, or -1 */
-
-static void
-tryexec(char *cmd, char **argv, char **envp)
+/* openhere needs this forward reference */
+static void expandhere(union node *arg, int fd);
+static int
+openhere(union node *redir)
 {
-       int repeated = 0;
-       struct BB_applet *a;
-       int argc = 0;
-       char **c;
+       int pip[2];
+       size_t len = 0;
 
-       if (strchr(cmd, '/') == NULL
-        && (a = find_applet_by_name(cmd)) != NULL
-        && is_safe_applet(cmd)
-       ) {
-               c = argv;
-               while (*c != NULL) {
-                       c++; argc++;
+       if (pipe(pip) < 0)
+               ash_msg_and_raise_error("pipe call failed");
+       if (redir->type == NHERE) {
+               len = strlen(redir->nhere.doc->narg.text);
+               if (len <= PIPESIZE) {
+                       full_write(pip[1], redir->nhere.doc->narg.text, len);
+                       goto out;
                }
-               applet_name = cmd;
-               exit(a->main(argc, argv));
        }
-#if ENABLE_FEATURE_SH_STANDALONE_SHELL
-       if (find_applet_by_name(cmd) != NULL) {
-               /* re-exec ourselves with the new arguments */
-               execve(CONFIG_BUSYBOX_EXEC_PATH, argv, envp);
-               /* If they called chroot or otherwise made the binary no longer
-                * executable, fall through */
-       }
-#endif
-
- repeat:
-#ifdef SYSV
-       do {
-               execve(cmd, argv, envp);
-       } while (errno == EINTR);
-#else
-       execve(cmd, argv, envp);
+       if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
+               close(pip[0]);
+               signal(SIGINT, SIG_IGN);
+               signal(SIGQUIT, SIG_IGN);
+               signal(SIGHUP, SIG_IGN);
+#ifdef SIGTSTP
+               signal(SIGTSTP, SIG_IGN);
 #endif
-       if (repeated++) {
-               free(argv);
-       } else if (errno == ENOEXEC) {
-               char **ap;
-               char **new;
-
-               for (ap = argv; *ap; ap++)
-                       ;
-               ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
-               ap[1] = cmd;
-               *ap = cmd = (char *)DEFAULT_SHELL;
-               ap += 2;
-               argv++;
-               while ((*ap++ = *argv++))
-                       ;
-               argv = new;
-               goto repeat;
+               signal(SIGPIPE, SIG_DFL);
+               if (redir->type == NHERE)
+                       full_write(pip[1], redir->nhere.doc->narg.text, len);
+               else
+                       expandhere(redir->nhere.doc, pip[1]);
+               _exit(0);
        }
+ out:
+       close(pip[1]);
+       return pip[0];
 }
 
-/*
- * Exec a program.  Never returns.  If you change this routine, you may
- * have to change the find_command routine as well.
- */
-#define environment() listvars(VEXPORT, VUNSET, 0)
-static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
-static void
-shellexec(char **argv, const char *path, int idx)
+static int
+openredirect(union node *redir)
 {
-       char *cmdname;
-       int e;
-       char **envp;
-       int exerrno;
+       char *fname;
+       int f;
 
-       clearredir(1);
-       envp = environment();
-       if (strchr(argv[0], '/') || is_safe_applet(argv[0])
-#if ENABLE_FEATURE_SH_STANDALONE_SHELL
-        || find_applet_by_name(argv[0])
-#endif
-       ) {
-               tryexec(argv[0], argv, envp);
-               e = errno;
-       } else {
-               e = ENOENT;
-               while ((cmdname = padvance(&path, argv[0])) != NULL) {
-                       if (--idx < 0 && pathopt == NULL) {
-                               tryexec(cmdname, argv, envp);
-                               if (errno != ENOENT && errno != ENOTDIR)
-                                       e = errno;
-                       }
-                       stunalloc(cmdname);
+       switch (redir->nfile.type) {
+       case NFROM:
+               fname = redir->nfile.expfname;
+               f = open(fname, O_RDONLY);
+               if (f < 0)
+                       goto eopen;
+               break;
+       case NFROMTO:
+               fname = redir->nfile.expfname;
+               f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
+               if (f < 0)
+                       goto ecreate;
+               break;
+       case NTO:
+               /* Take care of noclobber mode. */
+               if (Cflag) {
+                       fname = redir->nfile.expfname;
+                       f = noclobberopen(fname);
+                       if (f < 0)
+                               goto ecreate;
+                       break;
                }
-       }
-
-       /* Map to POSIX errors */
-       switch (e) {
-       case EACCES:
-               exerrno = 126;
+               /* FALLTHROUGH */
+       case NCLOBBER:
+               fname = redir->nfile.expfname;
+               f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
+               if (f < 0)
+                       goto ecreate;
                break;
-       case ENOENT:
-               exerrno = 127;
+       case NAPPEND:
+               fname = redir->nfile.expfname;
+               f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
+               if (f < 0)
+                       goto ecreate;
                break;
        default:
-               exerrno = 2;
+#if DEBUG
+               abort();
+#endif
+               /* Fall through to eliminate warning. */
+       case NTOFD:
+       case NFROMFD:
+               f = -1;
+               break;
+       case NHERE:
+       case NXHERE:
+               f = openhere(redir);
                break;
        }
-       exitstatus = exerrno;
-       TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
-               argv[0], e, suppressint ));
-       ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
-       /* NOTREACHED */
+
+       return f;
+ ecreate:
+       ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
+ eopen:
+       ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
 }
 
-static void
-printentry(struct tblentry *cmdp)
+/*
+ * Copy a file descriptor to be >= to.  Returns -1
+ * if the source file descriptor is closed, EMPTY if there are no unused
+ * file descriptors left.
+ */
+static int
+copyfd(int from, int to)
 {
-       int idx;
-       const char *path;
-       char *name;
+       int newfd;
 
-       idx = cmdp->param.index;
-       path = pathval();
-       do {
-               name = padvance(&path, cmdp->cmdname);
-               stunalloc(name);
-       } while (--idx >= 0);
-       out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
+       newfd = fcntl(from, F_DUPFD, to);
+       if (newfd < 0) {
+               if (errno == EMFILE)
+                       return EMPTY;
+               ash_msg_and_raise_error("%d: %m", from);
+       }
+       return newfd;
 }
 
-/*
- * Clear out command entries.  The argument specifies the first entry in
- * PATH which has changed.
- */
 static void
-clearcmdentry(int firstchange)
+dupredirect(union node *redir, int f)
 {
-       struct tblentry **tblp;
-       struct tblentry **pp;
-       struct tblentry *cmdp;
+       int fd = redir->nfile.fd;
 
-       INT_OFF;
-       for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
-               pp = tblp;
-               while ((cmdp = *pp) != NULL) {
-                       if ((cmdp->cmdtype == CMDNORMAL &&
-                            cmdp->param.index >= firstchange)
-                        || (cmdp->cmdtype == CMDBUILTIN &&
-                            builtinloc >= firstchange)
-                       ) {
-                               *pp = cmdp->next;
-                               free(cmdp);
-                       } else {
-                               pp = &cmdp->next;
-                       }
+       if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
+               if (redir->ndup.dupfd >= 0) {   /* if not ">&-" */
+                       copyfd(redir->ndup.dupfd, fd);
                }
+               return;
+       }
+
+       if (f != fd) {
+               copyfd(f, fd);
+               close(f);
        }
-       INT_ON;
 }
 
 /*
- * Locate a command in the command hash table.  If "add" is nonzero,
- * add the command to the table if it is not already present.  The
- * variable "lastcmdentry" is set to point to the address of the link
- * pointing to the entry, so that delete_cmd_entry can delete the
- * entry.
- *
- * Interrupts must be off if called with add != 0.
+ * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
+ * old file descriptors are stashed away so that the redirection can be
+ * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
+ * standard output, and the standard error if it becomes a duplicate of
+ * stdout, is saved in memory.
  */
-static struct tblentry **lastcmdentry;
-
-static struct tblentry *
-cmdlookup(const char *name, int add)
+/* flags passed to redirect */
+#define REDIR_PUSH    01        /* save previous values of file descriptors */
+#define REDIR_SAVEFD2 03        /* set preverrout */
+static void
+redirect(union node *redir, int flags)
 {
-       unsigned int hashval;
-       const char *p;
-       struct tblentry *cmdp;
-       struct tblentry **pp;
-
-       p = name;
-       hashval = (unsigned char)*p << 4;
-       while (*p)
-               hashval += (unsigned char)*p++;
-       hashval &= 0x7FFF;
-       pp = &cmdtable[hashval % CMDTABLESIZE];
-       for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
-               if (strcmp(cmdp->cmdname, name) == 0)
-                       break;
-               pp = &cmdp->next;
+       union node *n;
+       struct redirtab *sv;
+       int i;
+       int fd;
+       int newfd;
+       int *p;
+       nullredirs++;
+       if (!redir) {
+               return;
        }
-       if (add && cmdp == NULL) {
-               cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
-                                       + strlen(name) + 1);
-               cmdp->next = NULL;
-               cmdp->cmdtype = CMDUNKNOWN;
-               strcpy(cmdp->cmdname, name);
+       sv = NULL;
+       INT_OFF;
+       if (flags & REDIR_PUSH) {
+               struct redirtab *q;
+               q = ckmalloc(sizeof(struct redirtab));
+               q->next = redirlist;
+               redirlist = q;
+               q->nullredirs = nullredirs - 1;
+               for (i = 0; i < 10; i++)
+                       q->renamed[i] = EMPTY;
+               nullredirs = 0;
+               sv = q;
        }
-       lastcmdentry = pp;
-       return cmdp;
+       n = redir;
+       do {
+               fd = n->nfile.fd;
+               if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
+                && n->ndup.dupfd == fd)
+                       continue; /* redirect from/to same file descriptor */
+
+               newfd = openredirect(n);
+               if (fd == newfd)
+                       continue;
+               if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
+                       i = fcntl(fd, F_DUPFD, 10);
+
+                       if (i == -1) {
+                               i = errno;
+                               if (i != EBADF) {
+                                       close(newfd);
+                                       errno = i;
+                                       ash_msg_and_raise_error("%d: %m", fd);
+                                       /* NOTREACHED */
+                               }
+                       } else {
+                               *p = i;
+                               close(fd);
+                       }
+               } else {
+                       close(fd);
+               }
+               dupredirect(n, newfd);
+       } while ((n = n->nfile.next));
+       INT_ON;
+       if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
+               preverrout_fd = sv->renamed[2];
 }
 
 /*
- * Delete the command entry returned on the last lookup.
+ * Undo the effects of the last redirection.
  */
 static void
-delete_cmd_entry(void)
+popredir(int drop)
 {
-       struct tblentry *cmdp;
+       struct redirtab *rp;
+       int i;
 
+       if (--nullredirs >= 0)
+               return;
        INT_OFF;
-       cmdp = *lastcmdentry;
-       *lastcmdentry = cmdp->next;
-       if (cmdp->cmdtype == CMDFUNCTION)
-               freefunc(cmdp->param.func);
-       free(cmdp);
+       rp = redirlist;
+       for (i = 0; i < 10; i++) {
+               if (rp->renamed[i] != EMPTY) {
+                       if (!drop) {
+                               close(i);
+                               copyfd(rp->renamed[i], i);
+                       }
+                       close(rp->renamed[i]);
+               }
+       }
+       redirlist = rp->next;
+       nullredirs = rp->nullredirs;
+       free(rp);
        INT_ON;
 }
 
 /*
- * Add a new command entry, replacing any existing command entry for
- * the same name - except special builtins.
+ * Undo all redirections.  Called on error or interrupt.
+ */
+
+/*
+ * Discard all saved file descriptors.
  */
 static void
-addcmdentry(char *name, struct cmdentry *entry)
+clearredir(int drop)
 {
-       struct tblentry *cmdp;
-
-       cmdp = cmdlookup(name, 1);
-       if (cmdp->cmdtype == CMDFUNCTION) {
-               freefunc(cmdp->param.func);
+       for (;;) {
+               nullredirs = 0;
+               if (!redirlist)
+                       break;
+               popredir(drop);
        }
-       cmdp->cmdtype = entry->cmdtype;
-       cmdp->param = entry->u;
-       cmdp->rehash = 0;
 }
 
 static int
-hashcmd(int argc, char **argv)
+redirectsafe(union node *redir, int flags)
 {
-       struct tblentry **pp;
-       struct tblentry *cmdp;
-       int c;
-       struct cmdentry entry;
-       char *name;
+       int err;
+       volatile int saveint;
+       struct jmploc *volatile savehandler = exception_handler;
+       struct jmploc jmploc;
 
-       while ((c = nextopt("r")) != '\0') {
-               clearcmdentry(0);
-               return 0;
-       }
-       if (*argptr == NULL) {
-               for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
-                       for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
-                               if (cmdp->cmdtype == CMDNORMAL)
-                                       printentry(cmdp);
-                       }
-               }
-               return 0;
-       }
-       c = 0;
-       while ((name = *argptr) != NULL) {
-               cmdp = cmdlookup(name, 0);
-               if (cmdp != NULL
-                && (cmdp->cmdtype == CMDNORMAL
-                    || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
-                       delete_cmd_entry();
-               find_command(name, &entry, DO_ERR, pathval());
-               if (entry.cmdtype == CMDUNKNOWN)
-                       c = 1;
-               argptr++;
+       SAVE_INT(saveint);
+       err = setjmp(jmploc.loc) * 2;
+       if (!err) {
+               exception_handler = &jmploc;
+               redirect(redir, flags);
        }
-       return c;
+       exception_handler = savehandler;
+       if (err && exception != EXERROR)
+               longjmp(exception_handler->loc, 1);
+       RESTORE_INT(saveint);
+       return err;
 }
 
+
+/* ============ Routines to expand arguments to commands
+ *
+ * We have to deal with backquotes, shell variables, and file metacharacters.
+ */
+
 /*
- * Called when a cd is done.  Marks all commands so the next time they
- * are executed they will be rehashed.
+ * expandarg flags
  */
-static void
-hashcd(void)
-{
-       struct tblentry **pp;
-       struct tblentry *cmdp;
+#define EXP_FULL        0x1     /* perform word splitting & file globbing */
+#define EXP_TILDE       0x2     /* do normal tilde expansion */
+#define EXP_VARTILDE    0x4     /* expand tildes in an assignment */
+#define EXP_REDIR       0x8     /* file glob for a redirection (1 match only) */
+#define EXP_CASE        0x10    /* keeps quotes around for CASE pattern */
+#define EXP_RECORD      0x20    /* need to record arguments for ifs breakup */
+#define EXP_VARTILDE2   0x40    /* expand tildes after colons only */
+#define EXP_WORD        0x80    /* expand word in parameter expansion */
+#define EXP_QWORD       0x100   /* expand word in quoted parameter expansion */
+/*
+ * _rmescape() flags
+ */
+#define RMESCAPE_ALLOC  0x1     /* Allocate a new string */
+#define RMESCAPE_GLOB   0x2     /* Add backslashes for glob */
+#define RMESCAPE_QUOTED 0x4     /* Remove CTLESC unless in quotes */
+#define RMESCAPE_GROW   0x8     /* Grow strings instead of stalloc */
+#define RMESCAPE_HEAP   0x10    /* Malloc strings instead of stalloc */
 
-       for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
-               for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
-                       if (cmdp->cmdtype == CMDNORMAL || (
-                               cmdp->cmdtype == CMDBUILTIN &&
-                               !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
-                               builtinloc > 0
-                       ))
-                               cmdp->rehash = 1;
-               }
-       }
-}
+/*
+ * Structure specifying which parts of the string should be searched
+ * for IFS characters.
+ */
+struct ifsregion {
+       struct ifsregion *next; /* next region in list */
+       int begoff;             /* offset of start of region */
+       int endoff;             /* offset of end of region */
+       int nulonly;            /* search for nul bytes only */
+};
+
+struct arglist {
+       struct strlist *list;
+       struct strlist **lastp;
+};
+
+/* output of current string */
+static char *expdest;
+/* list of back quote expressions */
+static struct nodelist *argbackq;
+/* first struct in list of ifs regions */
+static struct ifsregion ifsfirst;
+/* last struct in list */
+static struct ifsregion *ifslastp;
+/* holds expanded arg list */
+static struct arglist exparg;
 
 /*
- * Fix command hash table when PATH changed.
- * Called before PATH is changed.  The argument is the new value of PATH;
- * pathval() still returns the old value at this point.
- * Called with interrupts off.
+ * Our own itoa().
  */
-static void
-changepath(const char *newval)
+static int
+cvtnum(arith_t num)
 {
-       const char *old, *new;
-       int idx;
-       int firstchange;
-       int idx_bltin;
+       int len;
 
-       old = pathval();
-       new = newval;
-       firstchange = 9999;     /* assume no change */
-       idx = 0;
-       idx_bltin = -1;
-       for (;;) {
-               if (*old != *new) {
-                       firstchange = idx;
-                       if ((*old == '\0' && *new == ':')
-                        || (*old == ':' && *new == '\0'))
-                               firstchange++;
-                       old = new;      /* ignore subsequent differences */
-               }
-               if (*new == '\0')
-                       break;
-               if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
-                       idx_bltin = idx;
-               if (*new == ':') {
-                       idx++;
-               }
-               new++, old++;
-       }
-       if (builtinloc < 0 && idx_bltin >= 0)
-               builtinloc = idx_bltin;             /* zap builtins */
-       if (builtinloc >= 0 && idx_bltin < 0)
-               firstchange = 0;
-       clearcmdentry(firstchange);
-       builtinloc = idx_bltin;
-}
-
-#define TEOF 0
-#define TNL 1
-#define TREDIR 2
-#define TWORD 3
-#define TSEMI 4
-#define TBACKGND 5
-#define TAND 6
-#define TOR 7
-#define TPIPE 8
-#define TLP 9
-#define TRP 10
-#define TENDCASE 11
-#define TENDBQUOTE 12
-#define TNOT 13
-#define TCASE 14
-#define TDO 15
-#define TDONE 16
-#define TELIF 17
-#define TELSE 18
-#define TESAC 19
-#define TFI 20
-#define TFOR 21
-#define TIF 22
-#define TIN 23
-#define TTHEN 24
-#define TUNTIL 25
-#define TWHILE 26
-#define TBEGIN 27
-#define TEND 28
-
-/* first char is indicating which tokens mark the end of a list */
-static const char *const tokname_array[] = {
-       "\1end of file",
-       "\0newline",
-       "\0redirection",
-       "\0word",
-       "\0;",
-       "\0&",
-       "\0&&",
-       "\0||",
-       "\0|",
-       "\0(",
-       "\1)",
-       "\1;;",
-       "\1`",
-#define KWDOFFSET 13
-       /* the following are keywords */
-       "\0!",
-       "\0case",
-       "\1do",
-       "\1done",
-       "\1elif",
-       "\1else",
-       "\1esac",
-       "\1fi",
-       "\0for",
-       "\0if",
-       "\0in",
-       "\1then",
-       "\0until",
-       "\0while",
-       "\0{",
-       "\1}",
-};
-
-static const char *
-tokname(int tok)
-{
-       static char buf[16];
-
-       if (tok >= TSEMI)
-               buf[0] = '"';
-       sprintf(buf + (tok >= TSEMI), "%s%c",
-                       tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
-       return buf;
+       expdest = makestrspace(32, expdest);
+#if ENABLE_ASH_MATH_SUPPORT_64
+       len = fmtstr(expdest, 32, "%lld", (long long) num);
+#else
+       len = fmtstr(expdest, 32, "%ld", num);
+#endif
+       STADJUST(len, expdest);
+       return len;
 }
 
-/* Wrapper around strcmp for qsort/bsearch/... */
-static int
-pstrcmp(const void *a, const void *b)
+static size_t
+esclen(const char *start, const char *p)
 {
-       return strcmp((const char *) a, (*(const char *const *) b) + 1);
-}
+       size_t esc = 0;
 
-static const char *const *
-findkwd(const char *s)
-{
-       return bsearch(s, tokname_array + KWDOFFSET,
-                       (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
-                       sizeof(const char *), pstrcmp);
+       while (p > start && *--p == CTLESC) {
+               esc++;
+       }
+       return esc;
 }
 
 /*
- * Locate and print what a word is...
+ * Remove any CTLESC characters from a string.
  */
-#if ENABLE_ASH_CMDCMD
-static int
-describe_command(char *command, int describe_command_verbose)
-#else
-#define describe_command_verbose 1
-static int
-describe_command(char *command)
-#endif
+static char *
+_rmescapes(char *str, int flag)
 {
-       struct cmdentry entry;
-       struct tblentry *cmdp;
-#if ENABLE_ASH_ALIAS
-       const struct alias *ap;
-#endif
-       const char *path = pathval();
-
-       if (describe_command_verbose) {
-               out1str(command);
-       }
+       static const char qchars[] = { CTLESC, CTLQUOTEMARK, '\0' };
 
-       /* First look at the keywords */
-       if (findkwd(command)) {
-               out1str(describe_command_verbose ? " is a shell keyword" : command);
-               goto out;
-       }
+       char *p, *q, *r;
+       unsigned inquotes;
+       int notescaped;
+       int globbing;
 
-#if ENABLE_ASH_ALIAS
-       /* Then look at the aliases */
-       ap = lookupalias(command, 0);
-       if (ap != NULL) {
-               if (describe_command_verbose) {
-                       out1fmt(" is an alias for %s", ap->val);
-               } else {
-                       out1str("alias ");
-                       printalias(ap);
-                       return 0;
-               }
-               goto out;
-       }
-#endif
-       /* Then check if it is a tracked alias */
-       cmdp = cmdlookup(command, 0);
-       if (cmdp != NULL) {
-               entry.cmdtype = cmdp->cmdtype;
-               entry.u = cmdp->param;
-       } else {
-               /* Finally use brute force */
-               find_command(command, &entry, DO_ABS, path);
+       p = strpbrk(str, qchars);
+       if (!p) {
+               return str;
        }
+       q = p;
+       r = str;
+       if (flag & RMESCAPE_ALLOC) {
+               size_t len = p - str;
+               size_t fulllen = len + strlen(p) + 1;
 
-       switch (entry.cmdtype) {
-       case CMDNORMAL: {
-               int j = entry.u.index;
-               char *p;
-               if (j == -1) {
-                       p = command;
+               if (flag & RMESCAPE_GROW) {
+                       r = makestrspace(fulllen, expdest);
+               } else if (flag & RMESCAPE_HEAP) {
+                       r = ckmalloc(fulllen);
                } else {
-                       do {
-                               p = padvance(&path, command);
-                               stunalloc(p);
-                       } while (--j >= 0);
+                       r = stalloc(fulllen);
                }
-               if (describe_command_verbose) {
-                       out1fmt(" is%s %s",
-                               (cmdp ? " a tracked alias for" : nullstr), p
-                       );
-               } else {
-                       out1str(p);
+               q = r;
+               if (len > 0) {
+                       q = memcpy(q, str, len) + len;
                }
-               break;
        }
-
-       case CMDFUNCTION:
-               if (describe_command_verbose) {
-                       out1str(" is a shell function");
-               } else {
-                       out1str(command);
+       inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
+       globbing = flag & RMESCAPE_GLOB;
+       notescaped = globbing;
+       while (*p) {
+               if (*p == CTLQUOTEMARK) {
+                       inquotes = ~inquotes;
+                       p++;
+                       notescaped = globbing;
+                       continue;
                }
-               break;
-
-       case CMDBUILTIN:
-               if (describe_command_verbose) {
-                       out1fmt(" is a %sshell builtin",
-                               IS_BUILTIN_SPECIAL(entry.u.cmd) ?
-                                       "special " : nullstr
-                       );
-               } else {
-                       out1str(command);
+               if (*p == '\\') {
+                       /* naked back slash */
+                       notescaped = 0;
+                       goto copy;
                }
-               break;
-
-       default:
-               if (describe_command_verbose) {
-                       out1str(": not found\n");
+               if (*p == CTLESC) {
+                       p++;
+                       if (notescaped && inquotes && *p != '/') {
+                               *q++ = '\\';
+                       }
                }
-               return 127;
+               notescaped = globbing;
+ copy:
+               *q++ = *p++;
        }
- out:
-       outstr("\n", stdout);
-       return 0;
+       *q = '\0';
+       if (flag & RMESCAPE_GROW) {
+               expdest = r;
+               STADJUST(q - r + 1, expdest);
+       }
+       return r;
 }
+#define rmescapes(p) _rmescapes((p), 0)
 
-static int
-typecmd(int argc, char **argv)
-{
-       int i;
-       int err = 0;
+#define pmatch(a, b) !fnmatch((a), (b), 0)
 
-       for (i = 1; i < argc; i++) {
-#if ENABLE_ASH_CMDCMD
-               err |= describe_command(argv[i], 1);
-#else
-               err |= describe_command(argv[i]);
-#endif
+/*
+ * Prepare a pattern for a expmeta (internal glob(3)) call.
+ *
+ * Returns an stalloced string.
+ */
+static char *
+preglob(const char *pattern, int quoted, int flag)
+{
+       flag |= RMESCAPE_GLOB;
+       if (quoted) {
+               flag |= RMESCAPE_QUOTED;
        }
-       return err;
+       return _rmescapes((char *)pattern, flag);
 }
 
-#if ENABLE_ASH_CMDCMD
-static int
-commandcmd(int argc, char **argv)
+/*
+ * Put a string on the stack.
+ */
+static void
+memtodest(const char *p, size_t len, int syntax, int quotes)
 {
-       int c;
-       enum {
-               VERIFY_BRIEF = 1,
-               VERIFY_VERBOSE = 2,
-       } verify = 0;
-
-       while ((c = nextopt("pvV")) != '\0')
-               if (c == 'V')
-                       verify |= VERIFY_VERBOSE;
-               else if (c == 'v')
-                       verify |= VERIFY_BRIEF;
-#if DEBUG
-               else if (c != 'p')
-                       abort();
-#endif
-       if (verify)
-               return describe_command(*argptr, verify - VERIFY_BRIEF);
-
-       return 0;
-}
-#endif
-
-
-/* ============ eval.c */
+       char *q = expdest;
 
-static int funcblocksize;          /* size of structures in function */
-static int funcstringsize;         /* size of strings in node */
-static void *funcblock;            /* block to allocate function from */
-static char *funcstring;           /* block to allocate strings from */
+       q = makestrspace(len * 2, q);
 
-/* flags in argument to evaltree */
-#define EV_EXIT 01              /* exit after evaluating tree */
-#define EV_TESTED 02            /* exit status is checked; ignore -e flag */
-#define EV_BACKCMD 04           /* command executing within back quotes */
+       while (len--) {
+               int c = signed_char2int(*p++);
+               if (!c)
+                       continue;
+               if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
+                       USTPUTC(CTLESC, q);
+               USTPUTC(c, q);
+       }
 
-static const short nodesize[26] = {
-       SHELL_ALIGN(sizeof(struct ncmd)),
-       SHELL_ALIGN(sizeof(struct npipe)),
-       SHELL_ALIGN(sizeof(struct nredir)),
-       SHELL_ALIGN(sizeof(struct nredir)),
-       SHELL_ALIGN(sizeof(struct nredir)),
-       SHELL_ALIGN(sizeof(struct nbinary)),
-       SHELL_ALIGN(sizeof(struct nbinary)),
-       SHELL_ALIGN(sizeof(struct nbinary)),
-       SHELL_ALIGN(sizeof(struct nif)),
-       SHELL_ALIGN(sizeof(struct nbinary)),
-       SHELL_ALIGN(sizeof(struct nbinary)),
-       SHELL_ALIGN(sizeof(struct nfor)),
-       SHELL_ALIGN(sizeof(struct ncase)),
-       SHELL_ALIGN(sizeof(struct nclist)),
-       SHELL_ALIGN(sizeof(struct narg)),
-       SHELL_ALIGN(sizeof(struct narg)),
-       SHELL_ALIGN(sizeof(struct nfile)),
-       SHELL_ALIGN(sizeof(struct nfile)),
-       SHELL_ALIGN(sizeof(struct nfile)),
-       SHELL_ALIGN(sizeof(struct nfile)),
-       SHELL_ALIGN(sizeof(struct nfile)),
-       SHELL_ALIGN(sizeof(struct ndup)),
-       SHELL_ALIGN(sizeof(struct ndup)),
-       SHELL_ALIGN(sizeof(struct nhere)),
-       SHELL_ALIGN(sizeof(struct nhere)),
-       SHELL_ALIGN(sizeof(struct nnot)),
-};
+       expdest = q;
+}
 
-static void calcsize(union node *n);
+static void
+strtodest(const char *p, int syntax, int quotes)
+{
+       memtodest(p, strlen(p), syntax, quotes);
+}
 
+/*
+ * Record the fact that we have to scan this region of the
+ * string for IFS characters.
+ */
 static void
-sizenodelist(struct nodelist *lp)
+recordregion(int start, int end, int nulonly)
 {
-       while (lp) {
-               funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
-               calcsize(lp->n);
-               lp = lp->next;
+       struct ifsregion *ifsp;
+
+       if (ifslastp == NULL) {
+               ifsp = &ifsfirst;
+       } else {
+               INT_OFF;
+               ifsp = ckmalloc(sizeof(*ifsp));
+               ifsp->next = NULL;
+               ifslastp->next = ifsp;
+               INT_ON;
        }
+       ifslastp = ifsp;
+       ifslastp->begoff = start;
+       ifslastp->endoff = end;
+       ifslastp->nulonly = nulonly;
 }
 
 static void
-calcsize(union node *n)
+removerecordregions(int endoff)
 {
-       if (n == NULL)
+       if (ifslastp == NULL)
                return;
-       funcblocksize += nodesize[n->type];
-       switch (n->type) {
-       case NCMD:
-               calcsize(n->ncmd.redirect);
-               calcsize(n->ncmd.args);
-               calcsize(n->ncmd.assign);
-               break;
-       case NPIPE:
-               sizenodelist(n->npipe.cmdlist);
-               break;
-       case NREDIR:
-       case NBACKGND:
-       case NSUBSHELL:
-               calcsize(n->nredir.redirect);
-               calcsize(n->nredir.n);
-               break;
-       case NAND:
-       case NOR:
-       case NSEMI:
-       case NWHILE:
-       case NUNTIL:
-               calcsize(n->nbinary.ch2);
-               calcsize(n->nbinary.ch1);
-               break;
-       case NIF:
-               calcsize(n->nif.elsepart);
-               calcsize(n->nif.ifpart);
-               calcsize(n->nif.test);
-               break;
-       case NFOR:
-               funcstringsize += strlen(n->nfor.var) + 1;
-               calcsize(n->nfor.body);
-               calcsize(n->nfor.args);
-               break;
-       case NCASE:
-               calcsize(n->ncase.cases);
-               calcsize(n->ncase.expr);
-               break;
-       case NCLIST:
-               calcsize(n->nclist.body);
-               calcsize(n->nclist.pattern);
-               calcsize(n->nclist.next);
-               break;
-       case NDEFUN:
-       case NARG:
-               sizenodelist(n->narg.backquote);
-               funcstringsize += strlen(n->narg.text) + 1;
-               calcsize(n->narg.next);
-               break;
-       case NTO:
-       case NCLOBBER:
-       case NFROM:
-       case NFROMTO:
-       case NAPPEND:
-               calcsize(n->nfile.fname);
-               calcsize(n->nfile.next);
-               break;
-       case NTOFD:
-       case NFROMFD:
-               calcsize(n->ndup.vname);
-               calcsize(n->ndup.next);
-       break;
-       case NHERE:
-       case NXHERE:
-               calcsize(n->nhere.doc);
-               calcsize(n->nhere.next);
-               break;
-       case NNOT:
-               calcsize(n->nnot.com);
-               break;
-       };
-}
 
-static char *
-nodeckstrdup(char *s)
-{
-       char *rtn = funcstring;
+       if (ifsfirst.endoff > endoff) {
+               while (ifsfirst.next != NULL) {
+                       struct ifsregion *ifsp;
+                       INT_OFF;
+                       ifsp = ifsfirst.next->next;
+                       free(ifsfirst.next);
+                       ifsfirst.next = ifsp;
+                       INT_ON;
+               }
+               if (ifsfirst.begoff > endoff)
+                       ifslastp = NULL;
+               else {
+                       ifslastp = &ifsfirst;
+                       ifsfirst.endoff = endoff;
+               }
+               return;
+       }
 
-       strcpy(funcstring, s);
-       funcstring += strlen(s) + 1;
-       return rtn;
+       ifslastp = &ifsfirst;
+       while (ifslastp->next && ifslastp->next->begoff < endoff)
+               ifslastp=ifslastp->next;
+       while (ifslastp->next != NULL) {
+               struct ifsregion *ifsp;
+               INT_OFF;
+               ifsp = ifslastp->next->next;
+               free(ifslastp->next);
+               ifslastp->next = ifsp;
+               INT_ON;
+       }
+       if (ifslastp->endoff > endoff)
+               ifslastp->endoff = endoff;
 }
 
-static union node *copynode(union node *);
-
-static struct nodelist *
-copynodelist(struct nodelist *lp)
-{
-       struct nodelist *start;
-       struct nodelist **lpp;
-
-       lpp = &start;
-       while (lp) {
-               *lpp = funcblock;
-               funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
-               (*lpp)->n = copynode(lp->n);
-               lp = lp->next;
-               lpp = &(*lpp)->next;
-       }
-       *lpp = NULL;
-       return start;
-}
-
-static union node *
-copynode(union node *n)
+static char *
+exptilde(char *startp, char *p, int flag)
 {
-       union node *new;
+       char c;
+       char *name;
+       struct passwd *pw;
+       const char *home;
+       int quotes = flag & (EXP_FULL | EXP_CASE);
+       int startloc;
 
-       if (n == NULL)
-               return NULL;
-       new = funcblock;
-       funcblock = (char *) funcblock + nodesize[n->type];
+       name = p + 1;
 
-       switch (n->type) {
-       case NCMD:
-               new->ncmd.redirect = copynode(n->ncmd.redirect);
-               new->ncmd.args = copynode(n->ncmd.args);
-               new->ncmd.assign = copynode(n->ncmd.assign);
-               break;
-       case NPIPE:
-               new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
-               new->npipe.backgnd = n->npipe.backgnd;
-               break;
-       case NREDIR:
-       case NBACKGND:
-       case NSUBSHELL:
-               new->nredir.redirect = copynode(n->nredir.redirect);
-               new->nredir.n = copynode(n->nredir.n);
-               break;
-       case NAND:
-       case NOR:
-       case NSEMI:
-       case NWHILE:
-       case NUNTIL:
-               new->nbinary.ch2 = copynode(n->nbinary.ch2);
-               new->nbinary.ch1 = copynode(n->nbinary.ch1);
-               break;
-       case NIF:
-               new->nif.elsepart = copynode(n->nif.elsepart);
-               new->nif.ifpart = copynode(n->nif.ifpart);
-               new->nif.test = copynode(n->nif.test);
-               break;
-       case NFOR:
-               new->nfor.var = nodeckstrdup(n->nfor.var);
-               new->nfor.body = copynode(n->nfor.body);
-               new->nfor.args = copynode(n->nfor.args);
-               break;
-       case NCASE:
-               new->ncase.cases = copynode(n->ncase.cases);
-               new->ncase.expr = copynode(n->ncase.expr);
-               break;
-       case NCLIST:
-               new->nclist.body = copynode(n->nclist.body);
-               new->nclist.pattern = copynode(n->nclist.pattern);
-               new->nclist.next = copynode(n->nclist.next);
-               break;
-       case NDEFUN:
-       case NARG:
-               new->narg.backquote = copynodelist(n->narg.backquote);
-               new->narg.text = nodeckstrdup(n->narg.text);
-               new->narg.next = copynode(n->narg.next);
-               break;
-       case NTO:
-       case NCLOBBER:
-       case NFROM:
-       case NFROMTO:
-       case NAPPEND:
-               new->nfile.fname = copynode(n->nfile.fname);
-               new->nfile.fd = n->nfile.fd;
-               new->nfile.next = copynode(n->nfile.next);
-               break;
-       case NTOFD:
-       case NFROMFD:
-               new->ndup.vname = copynode(n->ndup.vname);
-               new->ndup.dupfd = n->ndup.dupfd;
-               new->ndup.fd = n->ndup.fd;
-               new->ndup.next = copynode(n->ndup.next);
-               break;
-       case NHERE:
-       case NXHERE:
-               new->nhere.doc = copynode(n->nhere.doc);
-               new->nhere.fd = n->nhere.fd;
-               new->nhere.next = copynode(n->nhere.next);
-               break;
-       case NNOT:
-               new->nnot.com = copynode(n->nnot.com);
-               break;
-       };
-       new->type = n->type;
-       return new;
+       while ((c = *++p) != '\0') {
+               switch (c) {
+               case CTLESC:
+                       return startp;
+               case CTLQUOTEMARK:
+                       return startp;
+               case ':':
+                       if (flag & EXP_VARTILDE)
+                               goto done;
+                       break;
+               case '/':
+               case CTLENDVAR:
+                       goto done;
+               }
+       }
+ done:
+       *p = '\0';
+       if (*name == '\0') {
+               home = lookupvar(homestr);
+       } else {
+               pw = getpwnam(name);
+               if (pw == NULL)
+                       goto lose;
+               home = pw->pw_dir;
+       }
+       if (!home || !*home)
+               goto lose;
+       *p = c;
+       startloc = expdest - (char *)stackblock();
+       strtodest(home, SQSYNTAX, quotes);
+       recordregion(startloc, expdest - (char *)stackblock(), 0);
+       return p;
+ lose:
+       *p = c;
+       return startp;
 }
 
 /*
- * Make a copy of a parse tree.
+ * Execute a command inside back quotes.  If it's a builtin command, we
+ * want to save its output in a block obtained from malloc.  Otherwise
+ * we fork off a subprocess and get the output of the command via a pipe.
+ * Should be called with interrupts off.
  */
-static struct funcnode *
-copyfunc(union node *n)
-{
-       struct funcnode *f;
-       size_t blocksize;
+struct backcmd {                /* result of evalbackcmd */
+       int fd;                 /* file descriptor to read from */
+       char *buf;              /* buffer */
+       int nleft;              /* number of chars in buffer */
+       struct job *jp;         /* job structure for command */
+};
 
-       funcblocksize = offsetof(struct funcnode, n);
-       funcstringsize = 0;
-       calcsize(n);
-       blocksize = funcblocksize;
-       f = ckmalloc(blocksize + funcstringsize);
-       funcblock = (char *) f + offsetof(struct funcnode, n);
-       funcstring = (char *) f + blocksize;
-       copynode(n);
-       f->count = 0;
-       return f;
-}
+/* These forward decls are needed to use "eval" code for backticks handling: */
+static int back_exitstatus; /* exit status of backquoted command */
+#define EV_EXIT 01              /* exit after evaluating tree */
+static void evaltree(union node *, int);
 
-/*
- * Define a shell function.
- */
 static void
-defun(char *name, union node *func)
+evalbackcmd(union node *n, struct backcmd *result)
 {
-       struct cmdentry entry;
+       int saveherefd;
 
-       INT_OFF;
-       entry.cmdtype = CMDFUNCTION;
-       entry.u.func = copyfunc(func);
-       addcmdentry(name, &entry);
-       INT_ON;
-}
+       result->fd = -1;
+       result->buf = NULL;
+       result->nleft = 0;
+       result->jp = NULL;
+       if (n == NULL) {
+               goto out;
+       }
 
-static int evalskip;            /* set if we are skipping commands */
-/* reasons for skipping commands (see comment on breakcmd routine) */
-#define SKIPBREAK      (1 << 0)
-#define SKIPCONT       (1 << 1)
-#define SKIPFUNC       (1 << 2)
-#define SKIPFILE       (1 << 3)
-#define SKIPEVAL       (1 << 4)
-static int skipcount;           /* number of levels to skip */
-static int funcnest;            /* depth of function calls */
+       saveherefd = herefd;
+       herefd = -1;
 
-/* forward decl way out to parsing code - dotrap needs it */
-static int evalstring(char *s, int mask);
+       {
+               int pip[2];
+               struct job *jp;
+
+               if (pipe(pip) < 0)
+                       ash_msg_and_raise_error("pipe call failed");
+               jp = makejob(n, 1);
+               if (forkshell(jp, n, FORK_NOJOB) == 0) {
+                       FORCE_INT_ON;
+                       close(pip[0]);
+                       if (pip[1] != 1) {
+                               close(1);
+                               copyfd(pip[1], 1);
+                               close(pip[1]);
+                       }
+                       eflag = 0;
+                       evaltree(n, EV_EXIT); /* actually evaltreenr... */
+                       /* NOTREACHED */
+               }
+               close(pip[1]);
+               result->fd = pip[0];
+               result->jp = jp;
+       }
+       herefd = saveherefd;
+ out:
+       TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
+               result->fd, result->buf, result->nleft, result->jp));
+}
 
 /*
- * Called to execute a trap.  Perhaps we should avoid entering new trap
- * handlers while we are executing a trap handler.
+ * Expand stuff in backwards quotes.
  */
-static int
-dotrap(void)
+static void
+expbackq(union node *cmd, int quoted, int quotes)
 {
-       char *p;
-       char *q;
+       struct backcmd in;
        int i;
-       int savestatus;
-       int skip = 0;
+       char buf[128];
+       char *p;
+       char *dest;
+       int startloc;
+       int syntax = quoted? DQSYNTAX : BASESYNTAX;
+       struct stackmark smark;
 
-       savestatus = exitstatus;
-       pendingsigs = 0;
-       xbarrier();
-
-       for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
-               if (!*q)
-                       continue;
-               *q = '\0';
+       INT_OFF;
+       setstackmark(&smark);
+       dest = expdest;
+       startloc = dest - (char *)stackblock();
+       grabstackstr(dest);
+       evalbackcmd(cmd, &in);
+       popstackmark(&smark);
 
-               p = trap[i + 1];
-               if (!p)
-                       continue;
-               skip = evalstring(p, SKIPEVAL);
-               exitstatus = savestatus;
-               if (skip)
+       p = in.buf;
+       i = in.nleft;
+       if (i == 0)
+               goto read;
+       for (;;) {
+               memtodest(p, i, syntax, quotes);
+ read:
+               if (in.fd < 0)
+                       break;
+               i = safe_read(in.fd, buf, sizeof(buf));
+               TRACE(("expbackq: read returns %d\n", i));
+               if (i <= 0)
                        break;
+               p = buf;
        }
 
-       return skip;
-}
+       if (in.buf)
+               free(in.buf);
+       if (in.fd >= 0) {
+               close(in.fd);
+               back_exitstatus = waitforjob(in.jp);
+       }
+       INT_ON;
 
-/* forward declarations - evaluation is fairly recursive business... */
-static void evalloop(union node *, int);
-static void evalfor(union node *, int);
-static void evalcase(union node *, int);
-static void evalsubshell(union node *, int);
-static void expredir(union node *);
-static void evalpipe(union node *, int);
-static void evalcommand(union node *, int);
-static int evalbltin(const struct builtincmd *, int, char **);
-static void prehash(union node *);
+       /* Eat all trailing newlines */
+       dest = expdest;
+       for (; dest > (char *)stackblock() && dest[-1] == '\n';)
+               STUNPUTC(dest);
+       expdest = dest;
+
+       if (quoted == 0)
+               recordregion(startloc, dest - (char *)stackblock(), 0);
+       TRACE(("evalbackq: size=%d: \"%.*s\"\n",
+               (dest - (char *)stackblock()) - startloc,
+               (dest - (char *)stackblock()) - startloc,
+               stackblock() + startloc));
+}
 
+#if ENABLE_ASH_MATH_SUPPORT
 /*
- * Evaluate a parse tree.  The value is left in the global variable
- * exitstatus.
+ * Expand arithmetic expression.  Backup to start of expression,
+ * evaluate, place result in (backed up) result, adjust string position.
  */
 static void
-evaltree(union node *n, int flags)
+expari(int quotes)
 {
-       int checkexit = 0;
-       void (*evalfn)(union node *, int);
-       unsigned isor;
-       int status;
-       if (n == NULL) {
-               TRACE(("evaltree(NULL) called\n"));
-               goto out;
-       }
-       TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
-                       getpid(), n, n->type, flags));
-       switch (n->type) {
-       default:
+       char *p, *start;
+       int begoff;
+       int flag;
+       int len;
+
+       /*      ifsfree(); */
+
+       /*
+        * This routine is slightly over-complicated for
+        * efficiency.  Next we scan backwards looking for the
+        * start of arithmetic.
+        */
+       start = stackblock();
+       p = expdest - 1;
+       *p = '\0';
+       p--;
+       do {
+               int esc;
+
+               while (*p != CTLARI) {
+                       p--;
 #if DEBUG
-               out1fmt("Node type = %d\n", n->type);
-               fflush(stdout);
-               break;
-#endif
-       case NNOT:
-               evaltree(n->nnot.com, EV_TESTED);
-               status = !exitstatus;
-               goto setstatus;
-       case NREDIR:
-               expredir(n->nredir.redirect);
-               status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
-               if (!status) {
-                       evaltree(n->nredir.n, flags & EV_TESTED);
-                       status = exitstatus;
-               }
-               popredir(0);
-               goto setstatus;
-       case NCMD:
-               evalfn = evalcommand;
- checkexit:
-               if (eflag && !(flags & EV_TESTED))
-                       checkexit = ~0;
-               goto calleval;
-       case NFOR:
-               evalfn = evalfor;
-               goto calleval;
-       case NWHILE:
-       case NUNTIL:
-               evalfn = evalloop;
-               goto calleval;
-       case NSUBSHELL:
-       case NBACKGND:
-               evalfn = evalsubshell;
-               goto calleval;
-       case NPIPE:
-               evalfn = evalpipe;
-               goto checkexit;
-       case NCASE:
-               evalfn = evalcase;
-               goto calleval;
-       case NAND:
-       case NOR:
-       case NSEMI:
-#if NAND + 1 != NOR
-#error NAND + 1 != NOR
-#endif
-#if NOR + 1 != NSEMI
-#error NOR + 1 != NSEMI
+                       if (p < start) {
+                               ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
+                       }
 #endif
-               isor = n->type - NAND;
-               evaltree(
-                       n->nbinary.ch1,
-                       (flags | ((isor >> 1) - 1)) & EV_TESTED
-               );
-               if (!exitstatus == isor)
-                       break;
-               if (!evalskip) {
-                       n = n->nbinary.ch2;
- evaln:
-                       evalfn = evaltree;
- calleval:
-                       evalfn(n, flags);
-                       break;
                }
-               break;
-       case NIF:
-               evaltree(n->nif.test, EV_TESTED);
-               if (evalskip)
+
+               esc = esclen(start, p);
+               if (!(esc % 2)) {
                        break;
-               if (exitstatus == 0) {
-                       n = n->nif.ifpart;
-                       goto evaln;
-               } else if (n->nif.elsepart) {
-                       n = n->nif.elsepart;
-                       goto evaln;
                }
-               goto success;
-       case NDEFUN:
-               defun(n->narg.text, n->narg.next);
- success:
-               status = 0;
- setstatus:
-               exitstatus = status;
-               break;
-       }
- out:
-       if ((checkexit & exitstatus))
-               evalskip |= SKIPEVAL;
-       else if (pendingsigs && dotrap())
-               goto exexit;
 
-       if (flags & EV_EXIT) {
- exexit:
-               raise_exception(EXEXIT);
-       }
-}
+               p -= esc + 1;
+       } while (1);
 
-#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
-static
-#endif
-void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
+       begoff = p - start;
 
-static int loopnest;            /* current loop nesting level */
+       removerecordregions(begoff);
 
-static void
-evalloop(union node *n, int flags)
-{
-       int status;
+       flag = p[1];
 
-       loopnest++;
-       status = 0;
-       flags &= EV_TESTED;
-       for (;;) {
-               int i;
+       expdest = p;
 
-               evaltree(n->nbinary.ch1, EV_TESTED);
-               if (evalskip) {
- skipping:
-                       if (evalskip == SKIPCONT && --skipcount <= 0) {
-                               evalskip = 0;
-                               continue;
-                       }
-                       if (evalskip == SKIPBREAK && --skipcount <= 0)
-                               evalskip = 0;
-                       break;
-               }
-               i = exitstatus;
-               if (n->type != NWHILE)
-                       i = !i;
-               if (i != 0)
-                       break;
-               evaltree(n->nbinary.ch2, flags);
-               status = exitstatus;
-               if (evalskip)
-                       goto skipping;
-       }
-       loopnest--;
-       exitstatus = status;
-}
+       if (quotes)
+               rmescapes(p + 2);
 
-static void
-evalfor(union node *n, int flags)
-{
-       struct arglist arglist;
-       union node *argp;
-       struct strlist *sp;
-       struct stackmark smark;
+       len = cvtnum(dash_arith(p + 2));
 
-       setstackmark(&smark);
-       arglist.lastp = &arglist.list;
-       for (argp = n->nfor.args; argp; argp = argp->narg.next) {
-               expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
-               /* XXX */
-               if (evalskip)
-                       goto out;
-       }
-       *arglist.lastp = NULL;
-
-       exitstatus = 0;
-       loopnest++;
-       flags &= EV_TESTED;
-       for (sp = arglist.list; sp; sp = sp->next) {
-               setvar(n->nfor.var, sp->text, 0);
-               evaltree(n->nfor.body, flags);
-               if (evalskip) {
-                       if (evalskip == SKIPCONT && --skipcount <= 0) {
-                               evalskip = 0;
-                               continue;
-                       }
-                       if (evalskip == SKIPBREAK && --skipcount <= 0)
-                               evalskip = 0;
-                       break;
-               }
-       }
-       loopnest--;
- out:
-       popstackmark(&smark);
+       if (flag != '"')
+               recordregion(begoff, begoff + len, 0);
 }
+#endif
 
-static void
-evalcase(union node *n, int flags)
-{
-       union node *cp;
-       union node *patp;
-       struct arglist arglist;
-       struct stackmark smark;
-
-       setstackmark(&smark);
-       arglist.lastp = &arglist.list;
-       expandarg(n->ncase.expr, &arglist, EXP_TILDE);
-       exitstatus = 0;
-       for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
-               for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
-                       if (casematch(patp, arglist.list->text)) {
-                               if (evalskip == 0) {
-                                       evaltree(cp->nclist.body, flags);
-                               }
-                               goto out;
-                       }
-               }
-       }
- out:
-       popstackmark(&smark);
-}
+/* argstr needs it */
+static char *evalvar(char *p, int flag);
 
 /*
- * Kick off a subshell to evaluate a tree.
+ * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
+ * characters to allow for further processing.  Otherwise treat
+ * $@ like $* since no splitting will be performed.
  */
 static void
-evalsubshell(union node *n, int flags)
+argstr(char *p, int flag)
 {
-       struct job *jp;
-       int backgnd = (n->type == NBACKGND);
-       int status;
+       static const char spclchars[] = {
+               '=',
+               ':',
+               CTLQUOTEMARK,
+               CTLENDVAR,
+               CTLESC,
+               CTLVAR,
+               CTLBACKQ,
+               CTLBACKQ | CTLQUOTE,
+#if ENABLE_ASH_MATH_SUPPORT
+               CTLENDARI,
+#endif
+               0
+       };
+       const char *reject = spclchars;
+       int c;
+       int quotes = flag & (EXP_FULL | EXP_CASE);      /* do CTLESC */
+       int breakall = flag & EXP_WORD;
+       int inquotes;
+       size_t length;
+       int startloc;
 
-       expredir(n->nredir.redirect);
-       if (!backgnd && flags & EV_EXIT && !trap[0])
-               goto nofork;
-       INT_OFF;
-       jp = makejob(n, 1);
-       if (forkshell(jp, n, backgnd) == 0) {
-               INT_ON;
-               flags |= EV_EXIT;
-               if (backgnd)
-                       flags &=~ EV_TESTED;
- nofork:
-               redirect(n->nredir.redirect, 0);
-               evaltreenr(n->nredir.n, flags);
-               /* never returns */
+       if (!(flag & EXP_VARTILDE)) {
+               reject += 2;
+       } else if (flag & EXP_VARTILDE2) {
+               reject++;
        }
-       status = 0;
-       if (! backgnd)
-               status = waitforjob(jp);
-       exitstatus = status;
-       INT_ON;
-}
+       inquotes = 0;
+       length = 0;
+       if (flag & EXP_TILDE) {
+               char *q;
 
-/*
- * Compute the names of the files in a redirection list.
- */
-static void
-expredir(union node *n)
-{
-       union node *redir;
+               flag &= ~EXP_TILDE;
+ tilde:
+               q = p;
+               if (*q == CTLESC && (flag & EXP_QWORD))
+                       q++;
+               if (*q == '~')
+                       p = exptilde(p, q, flag);
+       }
+ start:
+       startloc = expdest - (char *)stackblock();
+       for (;;) {
+               length += strcspn(p + length, reject);
+               c = p[length];
+               if (c && (!(c & 0x80)
+#if ENABLE_ASH_MATH_SUPPORT
+                                       || c == CTLENDARI
+#endif
+                  )) {
+                       /* c == '=' || c == ':' || c == CTLENDARI */
+                       length++;
+               }
+               if (length > 0) {
+                       int newloc;
+                       expdest = stack_nputstr(p, length, expdest);
+                       newloc = expdest - (char *)stackblock();
+                       if (breakall && !inquotes && newloc > startloc) {
+                               recordregion(startloc, newloc, 0);
+                       }
+                       startloc = newloc;
+               }
+               p += length + 1;
+               length = 0;
 
-       for (redir = n; redir; redir = redir->nfile.next) {
-               struct arglist fn;
+               switch (c) {
+               case '\0':
+                       goto breakloop;
+               case '=':
+                       if (flag & EXP_VARTILDE2) {
+                               p--;
+                               continue;
+                       }
+                       flag |= EXP_VARTILDE2;
+                       reject++;
+                       /* fall through */
+               case ':':
+                       /*
+                        * sort of a hack - expand tildes in variable
+                        * assignments (after the first '=' and after ':'s).
+                        */
+                       if (*--p == '~') {
+                               goto tilde;
+                       }
+                       continue;
+               }
 
-               memset(&fn, 0, sizeof(fn));
-               fn.lastp = &fn.list;
-               switch (redir->type) {
-               case NFROMTO:
-               case NFROM:
-               case NTO:
-               case NCLOBBER:
-               case NAPPEND:
-                       expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
-                       redir->nfile.expfname = fn.list->text;
-                       break;
-               case NFROMFD:
-               case NTOFD:
-                       if (redir->ndup.vname) {
-                               expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
-                               if (fn.list == NULL)
-                                       ash_msg_and_raise_error("redir error");
-                               fixredir(redir, fn.list->text, 1);
+               switch (c) {
+               case CTLENDVAR: /* ??? */
+                       goto breakloop;
+               case CTLQUOTEMARK:
+                       /* "$@" syntax adherence hack */
+                       if (
+                               !inquotes &&
+                               !memcmp(p, dolatstr, 4) &&
+                               (p[4] == CTLQUOTEMARK || (
+                                       p[4] == CTLENDVAR &&
+                                       p[5] == CTLQUOTEMARK
+                               ))
+                       ) {
+                               p = evalvar(p + 1, flag) + 1;
+                               goto start;
+                       }
+                       inquotes = !inquotes;
+ addquote:
+                       if (quotes) {
+                               p--;
+                               length++;
+                               startloc++;
                        }
                        break;
+               case CTLESC:
+                       startloc++;
+                       length++;
+                       goto addquote;
+               case CTLVAR:
+                       p = evalvar(p, flag);
+                       goto start;
+               case CTLBACKQ:
+                       c = 0;
+               case CTLBACKQ|CTLQUOTE:
+                       expbackq(argbackq->n, c, quotes);
+                       argbackq = argbackq->next;
+                       goto start;
+#if ENABLE_ASH_MATH_SUPPORT
+               case CTLENDARI:
+                       p--;
+                       expari(quotes);
+                       goto start;
+#endif
                }
        }
+ breakloop:
+       ;
 }
 
-/*
- * Evaluate a pipeline.  All the processes in the pipeline are children
- * of the process creating the pipeline.  (This differs from some versions
- * of the shell, which make the last process in a pipeline the parent
- * of all the rest.)
- */
-static void
-evalpipe(union node *n, int flags)
+static char *
+scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
+       int zero)
 {
-       struct job *jp;
-       struct nodelist *lp;
-       int pipelen;
-       int prevfd;
-       int pip[2];
-
-       TRACE(("evalpipe(0x%lx) called\n", (long)n));
-       pipelen = 0;
-       for (lp = n->npipe.cmdlist; lp; lp = lp->next)
-               pipelen++;
-       flags |= EV_EXIT;
-       INT_OFF;
-       jp = makejob(n, pipelen);
-       prevfd = -1;
-       for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
-               prehash(lp->n);
-               pip[1] = -1;
-               if (lp->next) {
-                       if (pipe(pip) < 0) {
-                               close(prevfd);
-                               ash_msg_and_raise_error("Pipe call failed");
-                       }
+       char *loc;
+       char *loc2;
+       char c;
+
+       loc = startp;
+       loc2 = rmesc;
+       do {
+               int match;
+               const char *s = loc2;
+               c = *loc2;
+               if (zero) {
+                       *loc2 = '\0';
+                       s = rmesc;
                }
-               if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
-                       INT_ON;
-                       if (pip[1] >= 0) {
-                               close(pip[0]);
-                       }
-                       if (prevfd > 0) {
-                               dup2(prevfd, 0);
-                               close(prevfd);
+               match = pmatch(str, s);
+               *loc2 = c;
+               if (match)
+                       return loc;
+               if (quotes && *loc == CTLESC)
+                       loc++;
+               loc++;
+               loc2++;
+       } while (c);
+       return 0;
+}
+
+static char *
+scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
+       int zero)
+{
+       int esc = 0;
+       char *loc;
+       char *loc2;
+
+       for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
+               int match;
+               char c = *loc2;
+               const char *s = loc2;
+               if (zero) {
+                       *loc2 = '\0';
+                       s = rmesc;
+               }
+               match = pmatch(str, s);
+               *loc2 = c;
+               if (match)
+                       return loc;
+               loc--;
+               if (quotes) {
+                       if (--esc < 0) {
+                               esc = esclen(startp, loc);
                        }
-                       if (pip[1] > 1) {
-                               dup2(pip[1], 1);
-                               close(pip[1]);
+                       if (esc % 2) {
+                               esc--;
+                               loc--;
                        }
-                       evaltreenr(lp->n, flags);
-                       /* never returns */
                }
-               if (prevfd >= 0)
-                       close(prevfd);
-               prevfd = pip[0];
-               close(pip[1]);
-       }
-       if (n->npipe.backgnd == 0) {
-               exitstatus = waitforjob(jp);
-               TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
        }
-       INT_ON;
+       return 0;
 }
 
-static struct localvar *localvars;
-
-/*
- * Called after a function returns.
- * Interrupts must be off.
- */
+static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
 static void
-poplocalvars(void)
+varunset(const char *end, const char *var, const char *umsg, int varflags)
 {
-       struct localvar *lvp;
-       struct var *vp;
+       const char *msg;
+       const char *tail;
 
-       while ((lvp = localvars) != NULL) {
-               localvars = lvp->next;
-               vp = lvp->vp;
-               TRACE(("poplocalvar %s", vp ? vp->text : "-"));
-               if (vp == NULL) {       /* $- saved */
-                       memcpy(optlist, lvp->text, sizeof(optlist));
-                       free((char*)lvp->text);
-                       optschanged();
-               } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
-                       unsetvar(vp->text);
-               } else {
-                       if (vp->func)
-                               (*vp->func)(strchrnul(lvp->text, '=') + 1);
-                       if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
-                               free((char*)vp->text);
-                       vp->flags = lvp->flags;
-                       vp->text = lvp->text;
-               }
-               free(lvp);
+       tail = nullstr;
+       msg = "parameter not set";
+       if (umsg) {
+               if (*end == CTLENDVAR) {
+                       if (varflags & VSNUL)
+                               tail = " or null";
+               } else
+                       msg = umsg;
        }
+       ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
 }
 
-static int
-evalfun(struct funcnode *func, int argc, char **argv, int flags)
+static const char *
+subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
 {
-       volatile struct shparam saveparam;
-       struct localvar *volatile savelocalvars;
-       struct jmploc *volatile savehandler;
-       struct jmploc jmploc;
-       int e;
+       char *startp;
+       char *loc;
+       int saveherefd = herefd;
+       struct nodelist *saveargbackq = argbackq;
+       int amount;
+       char *rmesc, *rmescend;
+       int zero;
+       char *(*scan)(char *, char *, char *, char *, int , int);
 
-       saveparam = shellparam;
-       savelocalvars = localvars;
-       e = setjmp(jmploc.loc);
-       if (e) {
-               goto funcdone;
+       herefd = -1;
+       argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
+       STPUTC('\0', expdest);
+       herefd = saveherefd;
+       argbackq = saveargbackq;
+       startp = stackblock() + startloc;
+
+       switch (subtype) {
+       case VSASSIGN:
+               setvar(str, startp, 0);
+               amount = startp - expdest;
+               STADJUST(amount, expdest);
+               return startp;
+
+       case VSQUESTION:
+               varunset(p, str, startp, varflags);
+               /* NOTREACHED */
        }
-       INT_OFF;
-       savehandler = exception_handler;
-       exception_handler = &jmploc;
-       localvars = NULL;
-       shellparam.malloc = 0;
-       func->count++;
-       funcnest++;
-       INT_ON;
-       shellparam.nparam = argc - 1;
-       shellparam.p = argv + 1;
-#if ENABLE_ASH_GETOPTS
-       shellparam.optind = 1;
-       shellparam.optoff = -1;
-#endif
-       evaltree(&func->n, flags & EV_TESTED);
-funcdone:
-       INT_OFF;
-       funcnest--;
-       freefunc(func);
-       poplocalvars();
-       localvars = savelocalvars;
-       freeparam(&shellparam);
-       shellparam = saveparam;
-       exception_handler = savehandler;
-       INT_ON;
-       evalskip &= ~SKIPFUNC;
-       return e;
-}
 
-#if ENABLE_ASH_CMDCMD
-static char **
-parse_command_args(char **argv, const char **path)
-{
-       char *cp, c;
+       subtype -= VSTRIMRIGHT;
+#if DEBUG
+       if (subtype < 0 || subtype > 3)
+               abort();
+#endif
 
-       for (;;) {
-               cp = *++argv;
-               if (!cp)
-                       return 0;
-               if (*cp++ != '-')
-                       break;
-               c = *cp++;
-               if (!c)
-                       break;
-               if (c == '-' && !*cp) {
-                       argv++;
-                       break;
+       rmesc = startp;
+       rmescend = stackblock() + strloc;
+       if (quotes) {
+               rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
+               if (rmesc != startp) {
+                       rmescend = expdest;
+                       startp = stackblock() + startloc;
                }
-               do {
-                       switch (c) {
-                       case 'p':
-                               *path = defpath;
-                               break;
-                       default:
-                               /* run 'typecmd' for other options */
-                               return 0;
-                       }
-                       c = *cp++;
-               } while (c);
        }
-       return argv;
-}
-#endif
+       rmescend--;
+       str = stackblock() + strloc;
+       preglob(str, varflags & VSQUOTE, 0);
 
-/*
- * Make a variable a local variable.  When a variable is made local, it's
- * value and flags are saved in a localvar structure.  The saved values
- * will be restored when the shell function returns.  We handle the name
- * "-" as a special case.
- */
-static void
-mklocal(char *name)
-{
-       struct localvar *lvp;
-       struct var **vpp;
-       struct var *vp;
-
-       INT_OFF;
-       lvp = ckmalloc(sizeof(struct localvar));
-       if (LONE_DASH(name)) {
-               char *p;
-               p = ckmalloc(sizeof(optlist));
-               lvp->text = memcpy(p, optlist, sizeof(optlist));
-               vp = NULL;
-       } else {
-               char *eq;
+       /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
+       zero = subtype >> 1;
+       /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
+       scan = (subtype & 1) ^ zero ? scanleft : scanright;
 
-               vpp = hashvar(name);
-               vp = *findvar(vpp, name);
-               eq = strchr(name, '=');
-               if (vp == NULL) {
-                       if (eq)
-                               setvareq(name, VSTRFIXED);
-                       else
-                               setvar(name, NULL, VSTRFIXED);
-                       vp = *vpp;      /* the new variable */
-                       lvp->flags = VUNSET;
-               } else {
-                       lvp->text = vp->text;
-                       lvp->flags = vp->flags;
-                       vp->flags |= VSTRFIXED|VTEXTFIXED;
-                       if (eq)
-                               setvareq(name, 0);
+       loc = scan(startp, rmesc, rmescend, str, quotes, zero);
+       if (loc) {
+               if (zero) {
+                       memmove(startp, loc, str - loc);
+                       loc = startp + (str - loc) - 1;
                }
+               *loc = '\0';
+               amount = loc - expdest;
+               STADJUST(amount, expdest);
        }
-       lvp->vp = vp;
-       lvp->next = localvars;
-       localvars = lvp;
-       INT_ON;
+       return loc;
 }
 
 /*
- * The "local" command.
+ * Add the value of a specialized variable to the stack string.
  */
-static int
-localcmd(int argc, char **argv)
+static ssize_t
+varvalue(char *name, int varflags, int flags)
 {
-       char *name;
-
-       argv = argptr;
-       while ((name = *argv++) != NULL) {
-               mklocal(name);
-       }
-       return 0;
-}
-
-/* Forward declarations for builtintab[] */
-#if JOBS
-static int fg_bgcmd(int, char **);
-#endif
-static int breakcmd(int, char **);
-#if ENABLE_ASH_CMDCMD
-static int commandcmd(int, char **);
-#endif
-static int dotcmd(int, char **);
-static int evalcmd(int, char **);
-#if ENABLE_ASH_BUILTIN_ECHO
-static int echocmd(int, char **);
-#endif
-#if ENABLE_ASH_BUILTIN_TEST
-static int testcmd(int, char **);
-#endif
-static int execcmd(int, char **);
-static int exitcmd(int, char **);
-static int exportcmd(int, char **);
-static int falsecmd(int, char **);
-#if ENABLE_ASH_GETOPTS
-static int getoptscmd(int, char **);
-#endif
-static int hashcmd(int, char **);
-#if !ENABLE_FEATURE_SH_EXTRA_QUIET
-static int helpcmd(int argc, char **argv);
-#endif
-#if JOBS
-static int jobscmd(int, char **);
-#endif
-#if ENABLE_ASH_MATH_SUPPORT
-static int letcmd(int, char **);
-#endif
-static int pwdcmd(int, char **);
-static int readcmd(int, char **);
-static int returncmd(int, char **);
-static int setcmd(int, char **);
-static int shiftcmd(int, char **);
-static int timescmd(int, char **);
-static int trapcmd(int, char **);
-static int truecmd(int, char **);
-static int typecmd(int, char **);
-static int umaskcmd(int, char **);
-static int unsetcmd(int, char **);
-static int waitcmd(int, char **);
-static int ulimitcmd(int, char **);
-#if JOBS
-static int killcmd(int, char **);
-#endif
+       int num;
+       char *p;
+       int i;
+       int sep = 0;
+       int sepq = 0;
+       ssize_t len = 0;
+       char **ap;
+       int syntax;
+       int quoted = varflags & VSQUOTE;
+       int subtype = varflags & VSTYPE;
+       int quotes = flags & (EXP_FULL | EXP_CASE);
 
-#define BUILTIN_NOSPEC          "0"
-#define BUILTIN_SPECIAL         "1"
-#define BUILTIN_REGULAR         "2"
-#define BUILTIN_SPEC_REG        "3"
-#define BUILTIN_ASSIGN          "4"
-#define BUILTIN_SPEC_ASSG       "5"
-#define BUILTIN_REG_ASSG        "6"
-#define BUILTIN_SPEC_REG_ASSG   "7"
+       if (quoted && (flags & EXP_FULL))
+               sep = 1 << CHAR_BIT;
 
-/* make sure to keep these in proper order since it is searched via bsearch() */
-static const struct builtincmd builtintab[] = {
-       { BUILTIN_SPEC_REG      ".", dotcmd },
-       { BUILTIN_SPEC_REG      ":", truecmd },
-#if ENABLE_ASH_BUILTIN_TEST
-       { BUILTIN_REGULAR       "[", testcmd },
-       { BUILTIN_REGULAR       "[[", testcmd },
-#endif
-#if ENABLE_ASH_ALIAS
-       { BUILTIN_REG_ASSG      "alias", aliascmd },
-#endif
-#if JOBS
-       { BUILTIN_REGULAR       "bg", fg_bgcmd },
-#endif
-       { BUILTIN_SPEC_REG      "break", breakcmd },
-       { BUILTIN_REGULAR       "cd", cdcmd },
-       { BUILTIN_NOSPEC        "chdir", cdcmd },
-#if ENABLE_ASH_CMDCMD
-       { BUILTIN_REGULAR       "command", commandcmd },
-#endif
-       { BUILTIN_SPEC_REG      "continue", breakcmd },
-#if ENABLE_ASH_BUILTIN_ECHO
-       { BUILTIN_REGULAR       "echo", echocmd },
-#endif
-       { BUILTIN_SPEC_REG      "eval", evalcmd },
-       { BUILTIN_SPEC_REG      "exec", execcmd },
-       { BUILTIN_SPEC_REG      "exit", exitcmd },
-       { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
-       { BUILTIN_REGULAR       "false", falsecmd },
-#if JOBS
-       { BUILTIN_REGULAR       "fg", fg_bgcmd },
-#endif
-#if ENABLE_ASH_GETOPTS
-       { BUILTIN_REGULAR       "getopts", getoptscmd },
-#endif
-       { BUILTIN_NOSPEC        "hash", hashcmd },
-#if !ENABLE_FEATURE_SH_EXTRA_QUIET
-       { BUILTIN_NOSPEC        "help", helpcmd },
-#endif
-#if JOBS
-       { BUILTIN_REGULAR       "jobs", jobscmd },
-       { BUILTIN_REGULAR       "kill", killcmd },
-#endif
-#if ENABLE_ASH_MATH_SUPPORT
-       { BUILTIN_NOSPEC        "let", letcmd },
-#endif
-       { BUILTIN_ASSIGN        "local", localcmd },
-       { BUILTIN_NOSPEC        "pwd", pwdcmd },
-       { BUILTIN_REGULAR       "read", readcmd },
-       { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
-       { BUILTIN_SPEC_REG      "return", returncmd },
-       { BUILTIN_SPEC_REG      "set", setcmd },
-       { BUILTIN_SPEC_REG      "shift", shiftcmd },
-       { BUILTIN_SPEC_REG      "source", dotcmd },
-#if ENABLE_ASH_BUILTIN_TEST
-       { BUILTIN_REGULAR       "test", testcmd },
-#endif
-       { BUILTIN_SPEC_REG      "times", timescmd },
-       { BUILTIN_SPEC_REG      "trap", trapcmd },
-       { BUILTIN_REGULAR       "true", truecmd },
-       { BUILTIN_NOSPEC        "type", typecmd },
-       { BUILTIN_NOSPEC        "ulimit", ulimitcmd },
-       { BUILTIN_REGULAR       "umask", umaskcmd },
-#if ENABLE_ASH_ALIAS
-       { BUILTIN_REGULAR       "unalias", unaliascmd },
-#endif
-       { BUILTIN_SPEC_REG      "unset", unsetcmd },
-       { BUILTIN_REGULAR       "wait", waitcmd },
-};
+       syntax = quoted ? DQSYNTAX : BASESYNTAX;
+       switch (*name) {
+       case '$':
+               num = rootpid;
+               goto numvar;
+       case '?':
+               num = exitstatus;
+               goto numvar;
+       case '#':
+               num = shellparam.nparam;
+               goto numvar;
+       case '!':
+               num = backgndpid;
+               if (num == 0)
+                       return -1;
+ numvar:
+               len = cvtnum(num);
+               break;
+       case '-':
+               p = makestrspace(NOPTS, expdest);
+               for (i = NOPTS - 1; i >= 0; i--) {
+                       if (optlist[i]) {
+                               USTPUTC(optletters(i), p);
+                               len++;
+                       }
+               }
+               expdest = p;
+               break;
+       case '@':
+               if (sep)
+                       goto param;
+               /* fall through */
+       case '*':
+               sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
+               if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
+                       sepq = 1;
+ param:
+               ap = shellparam.p;
+               if (!ap)
+                       return -1;
+               while ((p = *ap++)) {
+                       size_t partlen;
 
-#define NUMBUILTINS (sizeof(builtintab) / sizeof(builtintab[0]))
+                       partlen = strlen(p);
+                       len += partlen;
 
-#define COMMANDCMD (builtintab + 5 + \
-       2 * ENABLE_ASH_BUILTIN_TEST + \
-       ENABLE_ASH_ALIAS + \
-       ENABLE_ASH_JOB_CONTROL)
-#define EXECCMD (builtintab + 7 + \
-       2 * ENABLE_ASH_BUILTIN_TEST + \
-       ENABLE_ASH_ALIAS + \
-       ENABLE_ASH_JOB_CONTROL + \
-       ENABLE_ASH_CMDCMD + \
-       ENABLE_ASH_BUILTIN_ECHO)
+                       if (!(subtype == VSPLUS || subtype == VSLENGTH))
+                               memtodest(p, partlen, syntax, quotes);
 
-/*
- * Search the table of builtin commands.
- */
-static struct builtincmd *
-find_builtin(const char *name)
-{
-       struct builtincmd *bp;
+                       if (*ap && sep) {
+                               char *q;
 
-       bp = bsearch(
-               name, builtintab, NUMBUILTINS, sizeof(builtintab[0]),
-               pstrcmp
-       );
-       return bp;
-}
+                               len++;
+                               if (subtype == VSPLUS || subtype == VSLENGTH) {
+                                       continue;
+                               }
+                               q = expdest;
+                               if (sepq)
+                                       STPUTC(CTLESC, q);
+                               STPUTC(sep, q);
+                               expdest = q;
+                       }
+               }
+               return len;
+       case '0':
+       case '1':
+       case '2':
+       case '3':
+       case '4':
+       case '5':
+       case '6':
+       case '7':
+       case '8':
+       case '9':
+               num = atoi(name);
+               if (num < 0 || num > shellparam.nparam)
+                       return -1;
+               p = num ? shellparam.p[num - 1] : arg0;
+               goto value;
+       default:
+               p = lookupvar(name);
+ value:
+               if (!p)
+                       return -1;
+
+               len = strlen(p);
+               if (!(subtype == VSPLUS || subtype == VSLENGTH))
+                       memtodest(p, len, syntax, quotes);
+               return len;
+       }
+
+       if (subtype == VSPLUS || subtype == VSLENGTH)
+               STADJUST(-len, expdest);
+       return len;
+}
 
 /*
- * Resolve a command name.  If you change this routine, you may have to
- * change the shellexec routine as well.
+ * Expand a variable, and return a pointer to the next character in the
+ * input string.
  */
-static void
-find_command(char *name, struct cmdentry *entry, int act, const char *path)
+static char *
+evalvar(char *p, int flag)
 {
-       struct tblentry *cmdp;
-       int idx;
-       int prev;
-       char *fullname;
-       struct stat statb;
-       int e;
-       int updatetbl;
-       struct builtincmd *bcmd;
+       int subtype;
+       int varflags;
+       char *var;
+       int patloc;
+       int c;
+       int startloc;
+       ssize_t varlen;
+       int easy;
+       int quotes;
+       int quoted;
 
-       /* If name contains a slash, don't use PATH or hash table */
-       if (strchr(name, '/') != NULL) {
-               entry->u.index = -1;
-               if (act & DO_ABS) {
-                       while (stat(name, &statb) < 0) {
-#ifdef SYSV
-                               if (errno == EINTR)
-                                       continue;
-#endif
-                               entry->cmdtype = CMDUNKNOWN;
-                               return;
-                       }
-               }
-               entry->cmdtype = CMDNORMAL;
-               return;
+       quotes = flag & (EXP_FULL | EXP_CASE);
+       varflags = *p++;
+       subtype = varflags & VSTYPE;
+       quoted = varflags & VSQUOTE;
+       var = p;
+       easy = (!quoted || (*var == '@' && shellparam.nparam));
+       startloc = expdest - (char *)stackblock();
+       p = strchr(p, '=') + 1;
+
+ again:
+       varlen = varvalue(var, varflags, flag);
+       if (varflags & VSNUL)
+               varlen--;
+
+       if (subtype == VSPLUS) {
+               varlen = -1 - varlen;
+               goto vsplus;
        }
 
-#if ENABLE_FEATURE_SH_STANDALONE_SHELL
-       if (find_applet_by_name(name)) {
-               entry->cmdtype = CMDNORMAL;
-               entry->u.index = -1;
-               return;
+       if (subtype == VSMINUS) {
+ vsplus:
+               if (varlen < 0) {
+                       argstr(
+                               p, flag | EXP_TILDE |
+                                       (quoted ?  EXP_QWORD : EXP_WORD)
+                       );
+                       goto end;
+               }
+               if (easy)
+                       goto record;
+               goto end;
        }
-#endif
 
-       if (is_safe_applet(name)) {
-               entry->cmdtype = CMDNORMAL;
-               entry->u.index = -1;
-               return;
+       if (subtype == VSASSIGN || subtype == VSQUESTION) {
+               if (varlen < 0) {
+                       if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
+                               varflags &= ~VSNUL;
+                               /*
+                                * Remove any recorded regions beyond
+                                * start of variable
+                                */
+                               removerecordregions(startloc);
+                               goto again;
+                       }
+                       goto end;
+               }
+               if (easy)
+                       goto record;
+               goto end;
        }
 
-       updatetbl = (path == pathval());
-       if (!updatetbl) {
-               act |= DO_ALTPATH;
-               if (strstr(path, "%builtin") != NULL)
-                       act |= DO_ALTBLTIN;
+       if (varlen < 0 && uflag)
+               varunset(p, var, 0, 0);
+
+       if (subtype == VSLENGTH) {
+               cvtnum(varlen > 0 ? varlen : 0);
+               goto record;
        }
 
-       /* If name is in the table, check answer will be ok */
-       cmdp = cmdlookup(name, 0);
-       if (cmdp != NULL) {
-               int bit;
+       if (subtype == VSNORMAL) {
+               if (!easy)
+                       goto end;
+ record:
+               recordregion(startloc, expdest - (char *)stackblock(), quoted);
+               goto end;
+       }
 
-               switch (cmdp->cmdtype) {
-               default:
 #if DEBUG
-                       abort();
-#endif
-               case CMDNORMAL:
-                       bit = DO_ALTPATH;
-                       break;
-               case CMDFUNCTION:
-                       bit = DO_NOFUNC;
-                       break;
-               case CMDBUILTIN:
-                       bit = DO_ALTBLTIN;
-                       break;
-               }
-               if (act & bit) {
-                       updatetbl = 0;
-                       cmdp = NULL;
-               } else if (cmdp->rehash == 0)
-                       /* if not invalidated by cd, we're done */
-                       goto success;
+       switch (subtype) {
+       case VSTRIMLEFT:
+       case VSTRIMLEFTMAX:
+       case VSTRIMRIGHT:
+       case VSTRIMRIGHTMAX:
+               break;
+       default:
+               abort();
        }
+#endif
 
-       /* If %builtin not in path, check for builtin next */
-       bcmd = find_builtin(name);
-       if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
-               act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
-       )))
-               goto builtin_success;
-
-       /* We have to search path. */
-       prev = -1;              /* where to start */
-       if (cmdp && cmdp->rehash) {     /* doing a rehash */
-               if (cmdp->cmdtype == CMDBUILTIN)
-                       prev = builtinloc;
-               else
-                       prev = cmdp->param.index;
+       if (varlen >= 0) {
+               /*
+                * Terminate the string and start recording the pattern
+                * right after it
+                */
+               STPUTC('\0', expdest);
+               patloc = expdest - (char *)stackblock();
+               if (subevalvar(p, NULL, patloc, subtype,
+                               startloc, varflags, quotes) == 0) {
+                       int amount = expdest - (
+                               (char *)stackblock() + patloc - 1
+                       );
+                       STADJUST(-amount, expdest);
+               }
+               /* Remove any recorded regions beyond start of variable */
+               removerecordregions(startloc);
+               goto record;
        }
 
-       e = ENOENT;
-       idx = -1;
- loop:
-       while ((fullname = padvance(&path, name)) != NULL) {
-               stunalloc(fullname);
-               idx++;
-               if (pathopt) {
-                       if (prefix(pathopt, "builtin")) {
-                               if (bcmd)
-                                       goto builtin_success;
-                               continue;
-                       } else if (!(act & DO_NOFUNC) &&
-                                  prefix(pathopt, "func")) {
-                               /* handled below */
-                       } else {
-                               /* ignore unimplemented options */
-                               continue;
+ end:
+       if (subtype != VSNORMAL) {      /* skip to end of alternative */
+               int nesting = 1;
+               for (;;) {
+                       c = *p++;
+                       if (c == CTLESC)
+                               p++;
+                       else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
+                               if (varlen >= 0)
+                                       argbackq = argbackq->next;
+                       } else if (c == CTLVAR) {
+                               if ((*p++ & VSTYPE) != VSNORMAL)
+                                       nesting++;
+                       } else if (c == CTLENDVAR) {
+                               if (--nesting == 0)
+                                       break;
                        }
                }
-               /* if rehash, don't redo absolute path names */
-               if (fullname[0] == '/' && idx <= prev) {
-                       if (idx < prev)
-                               continue;
-                       TRACE(("searchexec \"%s\": no change\n", name));
-                       goto success;
-               }
-               while (stat(fullname, &statb) < 0) {
-#ifdef SYSV
-                       if (errno == EINTR)
-                               continue;
-#endif
-                       if (errno != ENOENT && errno != ENOTDIR)
-                               e = errno;
-                       goto loop;
-               }
-               e = EACCES;     /* if we fail, this will be the error */
-               if (!S_ISREG(statb.st_mode))
-                       continue;
-               if (pathopt) {          /* this is a %func directory */
-                       stalloc(strlen(fullname) + 1);
-                       readcmdfile(fullname);
-                       cmdp = cmdlookup(name, 0);
-                       if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
-                               ash_msg_and_raise_error("%s not defined in %s", name, fullname);
-                       stunalloc(fullname);
-                       goto success;
-               }
-               TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
-               if (!updatetbl) {
-                       entry->cmdtype = CMDNORMAL;
-                       entry->u.index = idx;
-                       return;
-               }
-               INT_OFF;
-               cmdp = cmdlookup(name, 1);
-               cmdp->cmdtype = CMDNORMAL;
-               cmdp->param.index = idx;
-               INT_ON;
-               goto success;
        }
-
-       /* We failed.  If there was an entry for this command, delete it */
-       if (cmdp && updatetbl)
-               delete_cmd_entry();
-       if (act & DO_ERR)
-               ash_msg("%s: %s", name, errmsg(e, "not found"));
-       entry->cmdtype = CMDUNKNOWN;
-       return;
-
- builtin_success:
-       if (!updatetbl) {
-               entry->cmdtype = CMDBUILTIN;
-               entry->u.cmd = bcmd;
-               return;
-       }
-       INT_OFF;
-       cmdp = cmdlookup(name, 1);
-       cmdp->cmdtype = CMDBUILTIN;
-       cmdp->param.cmd = bcmd;
-       INT_ON;
- success:
-       cmdp->rehash = 0;
-       entry->cmdtype = cmdp->cmdtype;
-       entry->u = cmdp->param;
+       return p;
 }
 
 /*
- * Execute a simple command.
+ * Break the argument string into pieces based upon IFS and add the
+ * strings to the argument list.  The regions of the string to be
+ * searched for IFS characters have been stored by recordregion.
  */
-static int back_exitstatus; /* exit status of backquoted command */
-static int
-isassignment(const char *p)
-{
-       const char *q = endofname(p);
-       if (p == q)
-               return 0;
-       return *q == '=';
-}
-static int
-bltincmd(int argc, char **argv)
-{
-       /* Preserve exitstatus of a previous possible redirection
-        * as POSIX mandates */
-       return back_exitstatus;
-}
 static void
-evalcommand(union node *cmd, int flags)
+ifsbreakup(char *string, struct arglist *arglist)
 {
-       static const struct builtincmd bltin = {
-               "\0\0", bltincmd
-       };
-       struct stackmark smark;
-       union node *argp;
-       struct arglist arglist;
-       struct arglist varlist;
-       char **argv;
-       int argc;
-       const struct strlist *sp;
-       struct cmdentry cmdentry;
-       struct job *jp;
-       char *lastarg;
-       const char *path;
-       int spclbltin;
-       int cmd_is_exec;
-       int status;
-       char **nargv;
-       struct builtincmd *bcmd;
-       int pseudovarflag = 0;
-
-       /* First expand the arguments. */
-       TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
-       setstackmark(&smark);
-       back_exitstatus = 0;
-
-       cmdentry.cmdtype = CMDBUILTIN;
-       cmdentry.u.cmd = &bltin;
-       varlist.lastp = &varlist.list;
-       *varlist.lastp = NULL;
-       arglist.lastp = &arglist.list;
-       *arglist.lastp = NULL;
+       struct ifsregion *ifsp;
+       struct strlist *sp;
+       char *start;
+       char *p;
+       char *q;
+       const char *ifs, *realifs;
+       int ifsspc;
+       int nulonly;
 
-       argc = 0;
-       if (cmd->ncmd.args) {
-               bcmd = find_builtin(cmd->ncmd.args->narg.text);
-               pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
+       start = string;
+       if (ifslastp != NULL) {
+               ifsspc = 0;
+               nulonly = 0;
+               realifs = ifsset() ? ifsval() : defifs;
+               ifsp = &ifsfirst;
+               do {
+                       p = string + ifsp->begoff;
+                       nulonly = ifsp->nulonly;
+                       ifs = nulonly ? nullstr : realifs;
+                       ifsspc = 0;
+                       while (p < string + ifsp->endoff) {
+                               q = p;
+                               if (*p == CTLESC)
+                                       p++;
+                               if (!strchr(ifs, *p)) {
+                                       p++;
+                                       continue;
+                               }
+                               if (!nulonly)
+                                       ifsspc = (strchr(defifs, *p) != NULL);
+                               /* Ignore IFS whitespace at start */
+                               if (q == start && ifsspc) {
+                                       p++;
+                                       start = p;
+                                       continue;
+                               }
+                               *q = '\0';
+                               sp = stalloc(sizeof(*sp));
+                               sp->text = start;
+                               *arglist->lastp = sp;
+                               arglist->lastp = &sp->next;
+                               p++;
+                               if (!nulonly) {
+                                       for (;;) {
+                                               if (p >= string + ifsp->endoff) {
+                                                       break;
+                                               }
+                                               q = p;
+                                               if (*p == CTLESC)
+                                                       p++;
+                                               if (strchr(ifs, *p) == NULL ) {
+                                                       p = q;
+                                                       break;
+                                               } else if (strchr(defifs, *p) == NULL) {
+                                                       if (ifsspc) {
+                                                               p++;
+                                                               ifsspc = 0;
+                                                       } else {
+                                                               p = q;
+                                                               break;
+                                                       }
+                                               } else
+                                                       p++;
+                                       }
+                               }
+                               start = p;
+                       } /* while */
+                       ifsp = ifsp->next;
+               } while (ifsp != NULL);
+               if (nulonly)
+                       goto add;
        }
 
-       for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
-               struct strlist **spp;
-
-               spp = arglist.lastp;
-               if (pseudovarflag && isassignment(argp->narg.text))
-                       expandarg(argp, &arglist, EXP_VARTILDE);
-               else
-                       expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
+       if (!*start)
+               return;
 
-               for (sp = *spp; sp; sp = sp->next)
-                       argc++;
-       }
+ add:
+       sp = stalloc(sizeof(*sp));
+       sp->text = start;
+       *arglist->lastp = sp;
+       arglist->lastp = &sp->next;
+}
 
-       argv = nargv = stalloc(sizeof(char *) * (argc + 1));
-       for (sp = arglist.list; sp; sp = sp->next) {
-               TRACE(("evalcommand arg: %s\n", sp->text));
-               *nargv++ = sp->text;
-       }
-       *nargv = NULL;
+static void
+ifsfree(void)
+{
+       struct ifsregion *p;
 
-       lastarg = NULL;
-       if (iflag && funcnest == 0 && argc > 0)
-               lastarg = nargv[-1];
+       INT_OFF;
+       p = ifsfirst.next;
+       do {
+               struct ifsregion *ifsp;
+               ifsp = p->next;
+               free(p);
+               p = ifsp;
+       } while (p);
+       ifslastp = NULL;
+       ifsfirst.next = NULL;
+       INT_ON;
+}
 
-       preverrout_fd = 2;
-       expredir(cmd->ncmd.redirect);
-       status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
+/*
+ * Add a file name to the list.
+ */
+static void
+addfname(const char *name)
+{
+       struct strlist *sp;
 
-       path = vpath.text;
-       for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
-               struct strlist **spp;
-               char *p;
+       sp = stalloc(sizeof(*sp));
+       sp->text = ststrdup(name);
+       *exparg.lastp = sp;
+       exparg.lastp = &sp->next;
+}
 
-               spp = varlist.lastp;
-               expandarg(argp, &varlist, EXP_VARTILDE);
+static char *expdir;
 
-               /*
-                * Modify the command lookup path, if a PATH= assignment
-                * is present
-                */
-               p = (*spp)->text;
-               if (varequal(p, path))
-                       path = p;
-       }
-
-       /* Print the command if xflag is set. */
-       if (xflag) {
-               int n;
-               const char *p = " %s";
-
-               p++;
-               dprintf(preverrout_fd, p, expandstr(ps4val()));
+/*
+ * Do metacharacter (i.e. *, ?, [...]) expansion.
+ */
+static void
+expmeta(char *enddir, char *name)
+{
+       char *p;
+       const char *cp;
+       char *start;
+       char *endname;
+       int metaflag;
+       struct stat statb;
+       DIR *dirp;
+       struct dirent *dp;
+       int atend;
+       int matchdot;
 
-               sp = varlist.list;
-               for (n = 0; n < 2; n++) {
-                       while (sp) {
-                               dprintf(preverrout_fd, p, sp->text);
-                               sp = sp->next;
-                               if (*p == '%') {
-                                       p--;
+       metaflag = 0;
+       start = name;
+       for (p = name; *p; p++) {
+               if (*p == '*' || *p == '?')
+                       metaflag = 1;
+               else if (*p == '[') {
+                       char *q = p + 1;
+                       if (*q == '!')
+                               q++;
+                       for (;;) {
+                               if (*q == '\\')
+                                       q++;
+                               if (*q == '/' || *q == '\0')
+                                       break;
+                               if (*++q == ']') {
+                                       metaflag = 1;
+                                       break;
                                }
                        }
-                       sp = arglist.list;
+               } else if (*p == '\\')
+                       p++;
+               else if (*p == '/') {
+                       if (metaflag)
+                               goto out;
+                       start = p + 1;
                }
-               full_write(preverrout_fd, "\n", 1);
        }
-
-       cmd_is_exec = 0;
-       spclbltin = -1;
-
-       /* Now locate the command. */
-       if (argc) {
-               const char *oldpath;
-               int cmd_flag = DO_ERR;
-
-               path += 5;
-               oldpath = path;
-               for (;;) {
-                       find_command(argv[0], &cmdentry, cmd_flag, path);
-                       if (cmdentry.cmdtype == CMDUNKNOWN) {
-                               status = 127;
-                               flush_stderr();
-                               goto bail;
+ out:
+       if (metaflag == 0) {    /* we've reached the end of the file name */
+               if (enddir != expdir)
+                       metaflag++;
+               p = name;
+               do {
+                       if (*p == '\\')
+                               p++;
+                       *enddir++ = *p;
+               } while (*p++);
+               if (metaflag == 0 || lstat(expdir, &statb) >= 0)
+                       addfname(expdir);
+               return;
+       }
+       endname = p;
+       if (name < start) {
+               p = name;
+               do {
+                       if (*p == '\\')
+                               p++;
+                       *enddir++ = *p++;
+               } while (p < start);
+       }
+       if (enddir == expdir) {
+               cp = ".";
+       } else if (enddir == expdir + 1 && *expdir == '/') {
+               cp = "/";
+       } else {
+               cp = expdir;
+               enddir[-1] = '\0';
+       }
+       dirp = opendir(cp);
+       if (dirp == NULL)
+               return;
+       if (enddir != expdir)
+               enddir[-1] = '/';
+       if (*endname == 0) {
+               atend = 1;
+       } else {
+               atend = 0;
+               *endname++ = '\0';
+       }
+       matchdot = 0;
+       p = start;
+       if (*p == '\\')
+               p++;
+       if (*p == '.')
+               matchdot++;
+       while (! intpending && (dp = readdir(dirp)) != NULL) {
+               if (dp->d_name[0] == '.' && ! matchdot)
+                       continue;
+               if (pmatch(start, dp->d_name)) {
+                       if (atend) {
+                               strcpy(enddir, dp->d_name);
+                               addfname(expdir);
+                       } else {
+                               for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
+                                       continue;
+                               p[-1] = '/';
+                               expmeta(p, endname);
                        }
-
-                       /* implement bltin and command here */
-                       if (cmdentry.cmdtype != CMDBUILTIN)
-                               break;
-                       if (spclbltin < 0)
-                               spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
-                       if (cmdentry.u.cmd == EXECCMD)
-                               cmd_is_exec++;
-#if ENABLE_ASH_CMDCMD
-                       if (cmdentry.u.cmd == COMMANDCMD) {
-                               path = oldpath;
-                               nargv = parse_command_args(argv, &path);
-                               if (!nargv)
-                                       break;
-                               argc -= nargv - argv;
-                               argv = nargv;
-                               cmd_flag |= DO_NOFUNC;
-                       } else
-#endif
-                               break;
                }
        }
+       closedir(dirp);
+       if (! atend)
+               endname[-1] = '/';
+}
 
-       if (status) {
-               /* We have a redirection error. */
-               if (spclbltin > 0)
-                       raise_exception(EXERROR);
- bail:
-               exitstatus = status;
-               goto out;
-       }
+static struct strlist *
+msort(struct strlist *list, int len)
+{
+       struct strlist *p, *q = NULL;
+       struct strlist **lpp;
+       int half;
+       int n;
 
-       /* Execute the command. */
-       switch (cmdentry.cmdtype) {
-       default:
-               /* Fork off a child process if necessary. */
-               if (!(flags & EV_EXIT) || trap[0]) {
-                       INT_OFF;
-                       jp = makejob(cmd, 1);
-                       if (forkshell(jp, cmd, FORK_FG) != 0) {
-                               exitstatus = waitforjob(jp);
-                               INT_ON;
+       if (len <= 1)
+               return list;
+       half = len >> 1;
+       p = list;
+       for (n = half; --n >= 0; ) {
+               q = p;
+               p = p->next;
+       }
+       q->next = NULL;                 /* terminate first half of list */
+       q = msort(list, half);          /* sort first half of list */
+       p = msort(p, len - half);               /* sort second half */
+       lpp = &list;
+       for (;;) {
+#if ENABLE_LOCALE_SUPPORT
+               if (strcoll(p->text, q->text) < 0)
+#else
+               if (strcmp(p->text, q->text) < 0)
+#endif
+                                               {
+                       *lpp = p;
+                       lpp = &p->next;
+                       p = *lpp;
+                       if (p == NULL) {
+                               *lpp = q;
                                break;
                        }
-                       FORCE_INT_ON;
-               }
-               listsetvar(varlist.list, VEXPORT|VSTACK);
-               shellexec(argv, path, cmdentry.u.index);
-               /* NOTREACHED */
-
-       case CMDBUILTIN:
-               cmdenviron = varlist.list;
-               if (cmdenviron) {
-                       struct strlist *list = cmdenviron;
-                       int i = VNOSET;
-                       if (spclbltin > 0 || argc == 0) {
-                               i = 0;
-                               if (cmd_is_exec && argc > 1)
-                                       i = VEXPORT;
+               } else {
+                       *lpp = q;
+                       lpp = &q->next;
+                       q = *lpp;
+                       if (q == NULL) {
+                               *lpp = p;
+                               break;
                        }
-                       listsetvar(list, i);
                }
-               if (evalbltin(cmdentry.u.cmd, argc, argv)) {
-                       int exit_status;
-                       int i, j;
+       }
+       return list;
+}
 
-                       i = exception;
-                       if (i == EXEXIT)
-                               goto raise;
+/*
+ * Sort the results of file name expansion.  It calculates the number of
+ * strings to sort and then calls msort (short for merge sort) to do the
+ * work.
+ */
+static struct strlist *
+expsort(struct strlist *str)
+{
+       int len;
+       struct strlist *sp;
 
-                       exit_status = 2;
-                       j = 0;
-                       if (i == EXINT)
-                               j = SIGINT;
-                       if (i == EXSIG)
-                               j = pendingsigs;
-                       if (j)
-                               exit_status = j + 128;
-                       exitstatus = exit_status;
-
-                       if (i == EXINT || spclbltin > 0) {
- raise:
-                               longjmp(exception_handler->loc, 1);
-                       }
-                       FORCE_INT_ON;
-               }
-               break;
-
-       case CMDFUNCTION:
-               listsetvar(varlist.list, 0);
-               if (evalfun(cmdentry.u.func, argc, argv, flags))
-                       goto raise;
-               break;
-       }
-
- out:
-       popredir(cmd_is_exec);
-       if (lastarg)
-               /* dsl: I think this is intended to be used to support
-                * '_' in 'vi' command mode during line editing...
-                * However I implemented that within libedit itself.
-                */
-               setvar("_", lastarg, 0);
-       popstackmark(&smark);
+       len = 0;
+       for (sp = str; sp; sp = sp->next)
+               len++;
+       return msort(str, len);
 }
 
-static int
-evalbltin(const struct builtincmd *cmd, int argc, char **argv)
+static void
+expandmeta(struct strlist *str, int flag)
 {
-       char *volatile savecmdname;
-       struct jmploc *volatile savehandler;
-       struct jmploc jmploc;
-       int i;
+       static const char metachars[] = {
+               '*', '?', '[', 0
+       };
+       /* TODO - EXP_REDIR */
 
-       savecmdname = commandname;
-       i = setjmp(jmploc.loc);
-       if (i)
-               goto cmddone;
-       savehandler = exception_handler;
-       exception_handler = &jmploc;
-       commandname = argv[0];
-       argptr = argv + 1;
-       optptr = NULL;                  /* initialize nextopt */
-       exitstatus = (*cmd->builtin)(argc, argv);
-       flush_stdout_stderr();
- cmddone:
-       exitstatus |= ferror(stdout);
-       clearerr(stdout);
-       commandname = savecmdname;
-       exsig = 0;
-       exception_handler = savehandler;
+       while (str) {
+               struct strlist **savelastp;
+               struct strlist *sp;
+               char *p;
 
-       return i;
-}
+               if (fflag)
+                       goto nometa;
+               if (!strpbrk(str->text, metachars))
+                       goto nometa;
+               savelastp = exparg.lastp;
 
-static int
-goodname(const char *p)
-{
-       return !*endofname(p);
-}
+               INT_OFF;
+               p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
+               {
+                       int i = strlen(str->text);
+                       expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
+               }
 
+               expmeta(expdir, p);
+               free(expdir);
+               if (p != str->text)
+                       free(p);
+               INT_ON;
+               if (exparg.lastp == savelastp) {
+                       /*
+                        * no matches
+                        */
+ nometa:
+                       *exparg.lastp = str;
+                       rmescapes(str->text);
+                       exparg.lastp = &str->next;
+               } else {
+                       *exparg.lastp = NULL;
+                       *savelastp = sp = expsort(*savelastp);
+                       while (sp->next != NULL)
+                               sp = sp->next;
+                       exparg.lastp = &sp->next;
+               }
+               str = str->next;
+       }
+}
 
 /*
- * Search for a command.  This is called before we fork so that the
- * location of the command will be available in the parent as well as
- * the child.  The check for "goodname" is an overly conservative
- * check that the name will not be subject to expansion.
+ * Perform variable substitution and command substitution on an argument,
+ * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
+ * perform splitting and file name expansion.  When arglist is NULL, perform
+ * here document expansion.
  */
 static void
-prehash(union node *n)
+expandarg(union node *arg, struct arglist *arglist, int flag)
 {
-       struct cmdentry entry;
+       struct strlist *sp;
+       char *p;
 
-       if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
-               find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
+       argbackq = arg->narg.backquote;
+       STARTSTACKSTR(expdest);
+       ifsfirst.next = NULL;
+       ifslastp = NULL;
+       argstr(arg->narg.text, flag);
+       p = _STPUTC('\0', expdest);
+       expdest = p - 1;
+       if (arglist == NULL) {
+               return;                 /* here document expanded */
+       }
+       p = grabstackstr(p);
+       exparg.lastp = &exparg.list;
+       /*
+        * TODO - EXP_REDIR
+        */
+       if (flag & EXP_FULL) {
+               ifsbreakup(p, &exparg);
+               *exparg.lastp = NULL;
+               exparg.lastp = &exparg.list;
+               expandmeta(exparg.list, flag);
+       } else {
+               if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
+                       rmescapes(p);
+               sp = stalloc(sizeof(*sp));
+               sp->text = p;
+               *exparg.lastp = sp;
+               exparg.lastp = &sp->next;
+       }
+       if (ifsfirst.next)
+               ifsfree();
+       *exparg.lastp = NULL;
+       if (exparg.list) {
+               *arglist->lastp = exparg.list;
+               arglist->lastp = exparg.lastp;
+       }
 }
 
-
 /*
- * Builtin commands.  Builtin commands whose functions are closely
- * tied to evaluation are implemented here.
- */
-
-/*
- * Handle break and continue commands.  Break, continue, and return are
- * all handled by setting the evalskip flag.  The evaluation routines
- * above all check this flag, and if it is set they start skipping
- * commands rather than executing them.  The variable skipcount is
- * the number of loops to break/continue, or the number of function
- * levels to return.  (The latter is always 1.)  It should probably
- * be an error to break out of more loops than exist, but it isn't
- * in the standard shell so we don't make it one here.
+ * Expand shell variables and backquotes inside a here document.
  */
-
-static int
-breakcmd(int argc, char **argv)
+static void
+expandhere(union node *arg, int fd)
 {
-       int n = argc > 1 ? number(argv[1]) : 1;
-
-       if (n <= 0)
-               ash_msg_and_raise_error(illnum, argv[1]);
-       if (n > loopnest)
-               n = loopnest;
-       if (n > 0) {
-               evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
-               skipcount = n;
-       }
-       return 0;
+       herefd = fd;
+       expandarg(arg, (struct arglist *)NULL, 0);
+       full_write(fd, stackblock(), expdest - (char *)stackblock());
 }
 
 /*
- * The return command.
+ * Returns true if the pattern matches the string.
  */
 static int
-returncmd(int argc, char **argv)
-{
-       /*
-        * If called outside a function, do what ksh does;
-        * skip the rest of the file.
-        */
-       evalskip = funcnest ? SKIPFUNC : SKIPFILE;
-       return argv[1] ? number(argv[1]) : exitstatus;
-}
-
-static int
-falsecmd(int argc, char **argv)
+patmatch(char *pattern, const char *string)
 {
-       return 1;
+       return pmatch(preglob(pattern, 0, 0), string);
 }
 
+/*
+ * See if a pattern matches in a case statement.
+ */
 static int
-truecmd(int argc, char **argv)
+casematch(union node *pattern, char *val)
 {
-       return 0;
-}
+       struct stackmark smark;
+       int result;
 
-static int
-execcmd(int argc, char **argv)
-{
-       if (argc > 1) {
-               iflag = 0;              /* exit on error */
-               mflag = 0;
-               optschanged();
-               shellexec(argv + 1, pathval(), 0);
-       }
-       return 0;
+       setstackmark(&smark);
+       argbackq = pattern->narg.backquote;
+       STARTSTACKSTR(expdest);
+       ifslastp = NULL;
+       argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
+       STACKSTRNUL(expdest);
+       result = patmatch(stackblock(), val);
+       popstackmark(&smark);
+       return result;
 }
 
 
-/* ============ input.c
- *
- * This implements the input routines used by the parser.
- */
-#define EOF_NLEFT -99           /* value of parsenleft when EOF pushed back */
+/* ============ find_command */
 
-enum {
-       INPUT_PUSH_FILE = 1,
-       INPUT_NOFILE_OK = 2,
+struct builtincmd {
+       const char *name;
+       int (*builtin)(int, char **);
+       /* unsigned flags; */
 };
+#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
+#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
+#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
 
-static void
-popstring(void)
-{
-       struct strpush *sp = parsefile->strpush;
-
-       INT_OFF;
-#if ENABLE_ASH_ALIAS
-       if (sp->ap) {
-               if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
-                       checkkwd |= CHKALIAS;
-               }
-               if (sp->string != sp->ap->val) {
-                       free(sp->string);
-               }
-               sp->ap->flag &= ~ALIASINUSE;
-               if (sp->ap->flag & ALIASDEAD) {
-                       unalias(sp->ap->name);
-               }
-       }
-#endif
-       parsenextc = sp->prevstring;
-       parsenleft = sp->prevnleft;
-/*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
-       parsefile->strpush = sp->prev;
-       if (sp != &(parsefile->basestrpush))
-               free(sp);
-       INT_ON;
-}
+struct cmdentry {
+       int cmdtype;
+       union param {
+               int index;
+               const struct builtincmd *cmd;
+               struct funcnode *func;
+       } u;
+};
+/* values of cmdtype */
+#define CMDUNKNOWN      -1      /* no entry in table for command */
+#define CMDNORMAL       0       /* command is an executable program */
+#define CMDFUNCTION     1       /* command is a shell function */
+#define CMDBUILTIN      2       /* command is a shell builtin */
 
-static int
-preadfd(void)
-{
-       int nr;
-       char *buf =  parsefile->buf;
-       parsenextc = buf;
+/* action to find_command() */
+#define DO_ERR          0x01    /* prints errors */
+#define DO_ABS          0x02    /* checks absolute paths */
+#define DO_NOFUNC       0x04    /* don't return shell functions, for command */
+#define DO_ALTPATH      0x08    /* using alternate path */
+#define DO_ALTBLTIN     0x20    /* %builtin in alt. path */
 
- retry:
-#if ENABLE_FEATURE_EDITING
-       if (!iflag || parsefile->fd)
-               nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
-       else {
-#if ENABLE_FEATURE_TAB_COMPLETION
-               line_input_state->path_lookup = pathval();
-#endif
-               nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
-               if (nr == 0) {
-                       /* Ctrl+C pressed */
-                       if (trap[SIGINT]) {
-                               buf[0] = '\n';
-                               buf[1] = '\0';
-                               raise(SIGINT);
-                               return 1;
-                       }
-                       goto retry;
-               }
-               if (nr < 0 && errno == 0) {
-                       /* Ctrl+D presend */
-                       nr = 0;
-               }
-       }
-#else
-       nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
-#endif
+static void find_command(char *, struct cmdentry *, int, const char *);
 
-       if (nr < 0) {
-               if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
-                       int flags = fcntl(0, F_GETFL, 0);
-                       if (flags >= 0 && flags & O_NONBLOCK) {
-                               flags &=~ O_NONBLOCK;
-                               if (fcntl(0, F_SETFL, flags) >= 0) {
-                                       out2str("sh: turning off NDELAY mode\n");
-                                       goto retry;
-                               }
-                       }
-               }
-       }
-       return nr;
-}
+
+/* ============ Hashing commands */
 
 /*
- * Refill the input buffer and return the next input character:
+ * When commands are first encountered, they are entered in a hash table.
+ * This ensures that a full path search will not have to be done for them
+ * on each invocation.
  *
- * 1) If a string was pushed back on the input, pop it;
- * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
- *    from a string so we can't refill the buffer, return EOF.
- * 3) If the is more stuff in this buffer, use it else call read to fill it.
- * 4) Process input up to the next newline, deleting nul characters.
+ * We should investigate converting to a linear search, even though that
+ * would make the command name "hash" a misnomer.
  */
-static int
-preadbuffer(void)
-{
-       char *q;
-       int more;
-       char savec;
 
-       while (parsefile->strpush) {
-#if ENABLE_ASH_ALIAS
-               if (parsenleft == -1 && parsefile->strpush->ap &&
-                       parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
-                       return PEOA;
-               }
-#endif
-               popstring();
-               if (--parsenleft >= 0)
-                       return SC2INT(*parsenextc++);
-       }
-       if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
-               return PEOF;
-       flush_stdout_stderr();
+#define CMDTABLESIZE 31         /* should be prime */
+#define ARB 1                   /* actual size determined at run time */
 
-       more = parselleft;
-       if (more <= 0) {
- again:
-               more = preadfd();
-               if (more <= 0) {
-                       parselleft = parsenleft = EOF_NLEFT;
-                       return PEOF;
-               }
-       }
+struct tblentry {
+       struct tblentry *next;  /* next entry in hash chain */
+       union param param;      /* definition of builtin function */
+       short cmdtype;          /* index identifying command */
+       char rehash;            /* if set, cd done since entry created */
+       char cmdname[ARB];      /* name of command */
+};
 
-       q = parsenextc;
+static struct tblentry *cmdtable[CMDTABLESIZE];
+static int builtinloc = -1;             /* index in path of %builtin, or -1 */
 
-       /* delete nul characters */
-       for (;;) {
-               int c;
+static void
+tryexec(char *cmd, char **argv, char **envp)
+{
+       int repeated = 0;
 
-               more--;
-               c = *q;
+#if ENABLE_FEATURE_SH_STANDALONE
+       if (strchr(cmd, '/') == NULL) {
+               const struct bb_applet *a;
 
-               if (!c)
-                       memmove(q, q + 1, more);
-               else {
-                       q++;
-                       if (c == '\n') {
-                               parsenleft = q - parsenextc - 1;
-                               break;
+               a = find_applet_by_name(cmd);
+               if (a) {
+                       if (a->noexec) {
+                               current_applet = a;
+                               run_current_applet_and_exit(argv);
                        }
+                       /* re-exec ourselves with the new arguments */
+                       execve(CONFIG_BUSYBOX_EXEC_PATH, argv, envp);
+                       /* If they called chroot or otherwise made the binary no longer
+                        * executable, fall through */
                }
-
-               if (more <= 0) {
-                       parsenleft = q - parsenextc - 1;
-                       if (parsenleft < 0)
-                               goto again;
-                       break;
-               }
-       }
-       parselleft = more;
-
-       savec = *q;
-       *q = '\0';
-
-       if (vflag) {
-               out2str(parsenextc);
        }
-
-       *q = savec;
-
-       return SC2INT(*parsenextc++);
-}
-
-#define pgetc_as_macro()   (--parsenleft >= 0? SC2INT(*parsenextc++) : preadbuffer())
-
-#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
-#define pgetc_macro() pgetc()
-static int
-pgetc(void)
-{
-       return pgetc_as_macro();
-}
-#else
-#define pgetc_macro()   pgetc_as_macro()
-static int
-pgetc(void)
-{
-       return pgetc_macro();
-}
 #endif
 
-/*
- * Same as pgetc(), but ignores PEOA.
- */
-#if ENABLE_ASH_ALIAS
-static int
-pgetc2(void)
-{
-       int c;
-
+ repeat:
+#ifdef SYSV
        do {
-               c = pgetc_macro();
-       } while (c == PEOA);
-       return c;
-}
+               execve(cmd, argv, envp);
+       } while (errno == EINTR);
 #else
-static int
-pgetc2(void)
-{
-       return pgetc_macro();
-}
+       execve(cmd, argv, envp);
 #endif
+       if (repeated++) {
+               free(argv);
+       } else if (errno == ENOEXEC) {
+               char **ap;
+               char **new;
 
-/*
- * Read a line from the script.
- */
-static char *
-pfgets(char *line, int len)
-{
-       char *p = line;
-       int nleft = len;
-       int c;
-
-       while (--nleft > 0) {
-               c = pgetc2();
-               if (c == PEOF) {
-                       if (p == line)
-                               return NULL;
-                       break;
-               }
-               *p++ = c;
-               if (c == '\n')
-                       break;
+               for (ap = argv; *ap; ap++)
+                       ;
+               ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
+               ap[1] = cmd;
+               ap[0] = cmd = (char *)DEFAULT_SHELL;
+               ap += 2;
+               argv++;
+               while ((*ap++ = *argv++))
+                       ;
+               argv = new;
+               goto repeat;
        }
-       *p = '\0';
-       return line;
 }
 
 /*
- * Undo the last call to pgetc.  Only one character may be pushed back.
- * PEOF may be pushed back.
+ * Exec a program.  Never returns.  If you change this routine, you may
+ * have to change the find_command routine as well.
  */
+#define environment() listvars(VEXPORT, VUNSET, 0)
+static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
 static void
-pungetc(void)
-{
-       parsenleft++;
-       parsenextc--;
-}
-
-/*
- * Push a string back onto the input at this current parsefile level.
- * We handle aliases this way.
- */
-static void
-pushstring(char *s, void *ap)
+shellexec(char **argv, const char *path, int idx)
 {
-       struct strpush *sp;
-       size_t len;
+       char *cmdname;
+       int e;
+       char **envp;
+       int exerrno;
 
-       len = strlen(s);
-       INT_OFF;
-/*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
-       if (parsefile->strpush) {
-               sp = ckmalloc(sizeof(struct strpush));
-               sp->prev = parsefile->strpush;
-               parsefile->strpush = sp;
-       } else
-               sp = parsefile->strpush = &(parsefile->basestrpush);
-       sp->prevstring = parsenextc;
-       sp->prevnleft = parsenleft;
-#if ENABLE_ASH_ALIAS
-       sp->ap = (struct alias *)ap;
-       if (ap) {
-               ((struct alias *)ap)->flag |= ALIASINUSE;
-               sp->string = s;
-       }
+       clearredir(1);
+       envp = environment();
+       if (strchr(argv[0], '/')
+#if ENABLE_FEATURE_SH_STANDALONE
+        || find_applet_by_name(argv[0])
 #endif
-       parsenextc = s;
-       parsenleft = len;
-       INT_ON;
-}
-
-/*
- * To handle the "." command, a stack of input files is used.  Pushfile
- * adds a new entry to the stack and popfile restores the previous level.
- */
-static void
-pushfile(void)
-{
-       struct parsefile *pf;
+       ) {
+               tryexec(argv[0], argv, envp);
+               e = errno;
+       } else {
+               e = ENOENT;
+               while ((cmdname = padvance(&path, argv[0])) != NULL) {
+                       if (--idx < 0 && pathopt == NULL) {
+                               tryexec(cmdname, argv, envp);
+                               if (errno != ENOENT && errno != ENOTDIR)
+                                       e = errno;
+                       }
+                       stunalloc(cmdname);
+               }
+       }
 
-       parsefile->nleft = parsenleft;
-       parsefile->lleft = parselleft;
-       parsefile->nextc = parsenextc;
-       parsefile->linno = plinno;
-       pf = ckmalloc(sizeof(*pf));
-       pf->prev = parsefile;
-       pf->fd = -1;
-       pf->strpush = NULL;
-       pf->basestrpush.prev = NULL;
-       parsefile = pf;
+       /* Map to POSIX errors */
+       switch (e) {
+       case EACCES:
+               exerrno = 126;
+               break;
+       case ENOENT:
+               exerrno = 127;
+               break;
+       default:
+               exerrno = 2;
+               break;
+       }
+       exitstatus = exerrno;
+       TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
+               argv[0], e, suppressint ));
+       ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
+       /* NOTREACHED */
 }
 
 static void
-popfile(void)
+printentry(struct tblentry *cmdp)
 {
-       struct parsefile *pf = parsefile;
+       int idx;
+       const char *path;
+       char *name;
 
-       INT_OFF;
-       if (pf->fd >= 0)
-               close(pf->fd);
-       if (pf->buf)
-               free(pf->buf);
-       while (pf->strpush)
-               popstring();
-       parsefile = pf->prev;
-       free(pf);
-       parsenleft = parsefile->nleft;
-       parselleft = parsefile->lleft;
-       parsenextc = parsefile->nextc;
-       plinno = parsefile->linno;
-       INT_ON;
+       idx = cmdp->param.index;
+       path = pathval();
+       do {
+               name = padvance(&path, cmdp->cmdname);
+               stunalloc(name);
+       } while (--idx >= 0);
+       out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
 }
 
 /*
- * Return to top level.
+ * Clear out command entries.  The argument specifies the first entry in
+ * PATH which has changed.
  */
 static void
-popallfiles(void)
+clearcmdentry(int firstchange)
 {
-       while (parsefile != &basepf)
-               popfile();
-}
+       struct tblentry **tblp;
+       struct tblentry **pp;
+       struct tblentry *cmdp;
 
-/*
- * Close the file(s) that the shell is reading commands from.  Called
- * after a fork is done.
- */
-static void
-closescript(void)
-{
-       popallfiles();
-       if (parsefile->fd > 0) {
-               close(parsefile->fd);
-               parsefile->fd = 0;
+       INT_OFF;
+       for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
+               pp = tblp;
+               while ((cmdp = *pp) != NULL) {
+                       if ((cmdp->cmdtype == CMDNORMAL &&
+                            cmdp->param.index >= firstchange)
+                        || (cmdp->cmdtype == CMDBUILTIN &&
+                            builtinloc >= firstchange)
+                       ) {
+                               *pp = cmdp->next;
+                               free(cmdp);
+                       } else {
+                               pp = &cmdp->next;
+                       }
+               }
        }
+       INT_ON;
 }
 
 /*
- * Like setinputfile, but takes an open file descriptor.  Call this with
- * interrupts off.
+ * Locate a command in the command hash table.  If "add" is nonzero,
+ * add the command to the table if it is not already present.  The
+ * variable "lastcmdentry" is set to point to the address of the link
+ * pointing to the entry, so that delete_cmd_entry can delete the
+ * entry.
+ *
+ * Interrupts must be off if called with add != 0.
  */
-static void
-setinputfd(int fd, int push)
-{
-       fcntl(fd, F_SETFD, FD_CLOEXEC);
-       if (push) {
-               pushfile();
-               parsefile->buf = 0;
-       }
-       parsefile->fd = fd;
-       if (parsefile->buf == NULL)
-               parsefile->buf = ckmalloc(IBUFSIZ);
-       parselleft = parsenleft = 0;
-       plinno = 1;
-}
+static struct tblentry **lastcmdentry;
 
-/*
- * Set the input to take input from a file.  If push is set, push the
- * old input onto the stack first.
- */
-static int
-setinputfile(const char *fname, int flags)
+static struct tblentry *
+cmdlookup(const char *name, int add)
 {
-       int fd;
-       int fd2;
+       unsigned int hashval;
+       const char *p;
+       struct tblentry *cmdp;
+       struct tblentry **pp;
 
-       INT_OFF;
-       fd = open(fname, O_RDONLY);
-       if (fd < 0) {
-               if (flags & INPUT_NOFILE_OK)
-                       goto out;
-               ash_msg_and_raise_error("Can't open %s", fname);
+       p = name;
+       hashval = (unsigned char)*p << 4;
+       while (*p)
+               hashval += (unsigned char)*p++;
+       hashval &= 0x7FFF;
+       pp = &cmdtable[hashval % CMDTABLESIZE];
+       for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
+               if (strcmp(cmdp->cmdname, name) == 0)
+                       break;
+               pp = &cmdp->next;
        }
-       if (fd < 10) {
-               fd2 = copyfd(fd, 10);
-               close(fd);
-               if (fd2 < 0)
-                       ash_msg_and_raise_error("Out of file descriptors");
-               fd = fd2;
+       if (add && cmdp == NULL) {
+               cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
+                                       + strlen(name) + 1);
+               cmdp->next = NULL;
+               cmdp->cmdtype = CMDUNKNOWN;
+               strcpy(cmdp->cmdname, name);
        }
-       setinputfd(fd, flags & INPUT_PUSH_FILE);
- out:
-       INT_ON;
-       return fd;
+       lastcmdentry = pp;
+       return cmdp;
 }
 
 /*
- * Like setinputfile, but takes input from a string.
+ * Delete the command entry returned on the last lookup.
  */
 static void
-setinputstring(char *string)
+delete_cmd_entry(void)
 {
+       struct tblentry *cmdp;
+
        INT_OFF;
-       pushfile();
-       parsenextc = string;
-       parsenleft = strlen(string);
-       parsefile->buf = NULL;
-       plinno = 1;
+       cmdp = *lastcmdentry;
+       *lastcmdentry = cmdp->next;
+       if (cmdp->cmdtype == CMDFUNCTION)
+               freefunc(cmdp->param.func);
+       free(cmdp);
        INT_ON;
 }
 
-
-/* ============ jobs.c */
-
 /*
- * Set the signal handler for the specified signal.  The routine figures
- * out what it should be set to.
+ * Add a new command entry, replacing any existing command entry for
+ * the same name - except special builtins.
  */
 static void
-setsignal(int signo)
+addcmdentry(char *name, struct cmdentry *entry)
 {
-       int action;
-       char *t, tsig;
-       struct sigaction act;
+       struct tblentry *cmdp;
 
-       t = trap[signo];
-       if (t == NULL)
-               action = S_DFL;
-       else if (*t != '\0')
-               action = S_CATCH;
-       else
-               action = S_IGN;
-       if (rootshell && action == S_DFL) {
-               switch (signo) {
-               case SIGINT:
-                       if (iflag || minusc || sflag == 0)
-                               action = S_CATCH;
-                       break;
-               case SIGQUIT:
-#if DEBUG
-                       if (debug)
-                               break;
-#endif
-                       /* FALLTHROUGH */
-               case SIGTERM:
-                       if (iflag)
-                               action = S_IGN;
-                       break;
-#if JOBS
-               case SIGTSTP:
-               case SIGTTOU:
-                       if (mflag)
-                               action = S_IGN;
-                       break;
-#endif
-               }
+       cmdp = cmdlookup(name, 1);
+       if (cmdp->cmdtype == CMDFUNCTION) {
+               freefunc(cmdp->param.func);
        }
+       cmdp->cmdtype = entry->cmdtype;
+       cmdp->param = entry->u;
+       cmdp->rehash = 0;
+}
 
-       t = &sigmode[signo - 1];
-       tsig = *t;
-       if (tsig == 0) {
-               /*
-                * current setting unknown
-                */
-               if (sigaction(signo, 0, &act) == -1) {
-                       /*
-                        * Pretend it worked; maybe we should give a warning
-                        * here, but other shells don't. We don't alter
-                        * sigmode, so that we retry every time.
-                        */
-                       return;
-               }
-               if (act.sa_handler == SIG_IGN) {
-                       if (mflag
-                        && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
-                       ) {
-                               tsig = S_IGN;   /* don't hard ignore these */
-                       } else
-                               tsig = S_HARD_IGN;
-               } else {
-                       tsig = S_RESET; /* force to be set */
+static int
+hashcmd(int argc, char **argv)
+{
+       struct tblentry **pp;
+       struct tblentry *cmdp;
+       int c;
+       struct cmdentry entry;
+       char *name;
+
+       while ((c = nextopt("r")) != '\0') {
+               clearcmdentry(0);
+               return 0;
+       }
+       if (*argptr == NULL) {
+               for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
+                       for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
+                               if (cmdp->cmdtype == CMDNORMAL)
+                                       printentry(cmdp);
+                       }
                }
+               return 0;
        }
-       if (tsig == S_HARD_IGN || tsig == action)
-               return;
-       switch (action) {
-       case S_CATCH:
-               act.sa_handler = onsig;
-               break;
-       case S_IGN:
-               act.sa_handler = SIG_IGN;
-               break;
-       default:
-               act.sa_handler = SIG_DFL;
+       c = 0;
+       while ((name = *argptr) != NULL) {
+               cmdp = cmdlookup(name, 0);
+               if (cmdp != NULL
+                && (cmdp->cmdtype == CMDNORMAL
+                    || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
+                       delete_cmd_entry();
+               find_command(name, &entry, DO_ERR, pathval());
+               if (entry.cmdtype == CMDUNKNOWN)
+                       c = 1;
+               argptr++;
        }
-       *t = action;
-       act.sa_flags = 0;
-       sigfillset(&act.sa_mask);
-       sigaction(signo, &act, 0);
+       return c;
 }
 
-/* mode flags for set_curjob */
-#define CUR_DELETE 2
-#define CUR_RUNNING 1
-#define CUR_STOPPED 0
-
-/* mode flags for dowait */
-#define DOWAIT_NORMAL 0
-#define DOWAIT_BLOCK 1
-
-#if JOBS
-/* pgrp of shell on invocation */
-static int initialpgrp;
-static int ttyfd = -1;
-#endif
-/* array of jobs */
-static struct job *jobtab;
-/* size of array */
-static unsigned njobs;
-/* current job */
-static struct job *curjob;
-/* number of presumed living untracked jobs */
-static int jobless;
-
+/*
+ * Called when a cd is done.  Marks all commands so the next time they
+ * are executed they will be rehashed.
+ */
 static void
-set_curjob(struct job *jp, unsigned mode)
+hashcd(void)
 {
-       struct job *jp1;
-       struct job **jpp, **curp;
-
-       /* first remove from list */
-       jpp = curp = &curjob;
-       do {
-               jp1 = *jpp;
-               if (jp1 == jp)
-                       break;
-               jpp = &jp1->prev_job;
-       } while (1);
-       *jpp = jp1->prev_job;
+       struct tblentry **pp;
+       struct tblentry *cmdp;
 
-       /* Then re-insert in correct position */
-       jpp = curp;
-       switch (mode) {
-       default:
-#if DEBUG
-               abort();
-#endif
-       case CUR_DELETE:
-               /* job being deleted */
-               break;
-       case CUR_RUNNING:
-               /* newly created job or backgrounded job,
-                  put after all stopped jobs. */
-               do {
-                       jp1 = *jpp;
-#if JOBS
-                       if (!jp1 || jp1->state != JOBSTOPPED)
-#endif
-                               break;
-                       jpp = &jp1->prev_job;
-               } while (1);
-               /* FALLTHROUGH */
-#if JOBS
-       case CUR_STOPPED:
-#endif
-               /* newly stopped job - becomes curjob */
-               jp->prev_job = *jpp;
-               *jpp = jp;
-               break;
+       for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
+               for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
+                       if (cmdp->cmdtype == CMDNORMAL || (
+                               cmdp->cmdtype == CMDBUILTIN &&
+                               !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
+                               builtinloc > 0
+                       ))
+                               cmdp->rehash = 1;
+               }
        }
 }
 
-#if JOBS || DEBUG
-static int
-jobno(const struct job *jp)
-{
-       return jp - jobtab + 1;
-}
-#endif
-
 /*
- * Convert a job name to a job structure.
+ * Fix command hash table when PATH changed.
+ * Called before PATH is changed.  The argument is the new value of PATH;
+ * pathval() still returns the old value at this point.
+ * Called with interrupts off.
  */
-static struct job *
-getjob(const char *name, int getctl)
+static void
+changepath(const char *newval)
 {
-       struct job *jp;
-       struct job *found;
-       const char *err_msg = "No such job: %s";
-       unsigned num;
-       int c;
-       const char *p;
-       char *(*match)(const char *, const char *);
-
-       jp = curjob;
-       p = name;
-       if (!p)
-               goto currentjob;
-
-       if (*p != '%')
-               goto err;
-
-       c = *++p;
-       if (!c)
-               goto currentjob;
+       const char *old, *new;
+       int idx;
+       int firstchange;
+       int idx_bltin;
 
-       if (!p[1]) {
-               if (c == '+' || c == '%') {
- currentjob:
-                       err_msg = "No current job";
-                       goto check;
-               }
-               if (c == '-') {
-                       if (jp)
-                               jp = jp->prev_job;
-                       err_msg = "No previous job";
- check:
-                       if (!jp)
-                               goto err;
-                       goto gotit;
+       old = pathval();
+       new = newval;
+       firstchange = 9999;     /* assume no change */
+       idx = 0;
+       idx_bltin = -1;
+       for (;;) {
+               if (*old != *new) {
+                       firstchange = idx;
+                       if ((*old == '\0' && *new == ':')
+                        || (*old == ':' && *new == '\0'))
+                               firstchange++;
+                       old = new;      /* ignore subsequent differences */
                }
-       }
-
-       if (is_number(p)) {
-               num = atoi(p);
-               if (num < njobs) {
-                       jp = jobtab + num - 1;
-                       if (jp->used)
-                               goto gotit;
-                       goto err;
+               if (*new == '\0')
+                       break;
+               if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
+                       idx_bltin = idx;
+               if (*new == ':') {
+                       idx++;
                }
+               new++, old++;
        }
+       if (builtinloc < 0 && idx_bltin >= 0)
+               builtinloc = idx_bltin;             /* zap builtins */
+       if (builtinloc >= 0 && idx_bltin < 0)
+               firstchange = 0;
+       clearcmdentry(firstchange);
+       builtinloc = idx_bltin;
+}
 
-       match = prefix;
-       if (*p == '?') {
-               match = strstr;
-               p++;
-       }
-
-       found = 0;
-       while (1) {
-               if (!jp)
-                       goto err;
-               if (match(jp->ps[0].cmd, p)) {
-                       if (found)
-                               goto err;
-                       found = jp;
-                       err_msg = "%s: ambiguous";
-               }
-               jp = jp->prev_job;
-       }
+#define TEOF 0
+#define TNL 1
+#define TREDIR 2
+#define TWORD 3
+#define TSEMI 4
+#define TBACKGND 5
+#define TAND 6
+#define TOR 7
+#define TPIPE 8
+#define TLP 9
+#define TRP 10
+#define TENDCASE 11
+#define TENDBQUOTE 12
+#define TNOT 13
+#define TCASE 14
+#define TDO 15
+#define TDONE 16
+#define TELIF 17
+#define TELSE 18
+#define TESAC 19
+#define TFI 20
+#define TFOR 21
+#define TIF 22
+#define TIN 23
+#define TTHEN 24
+#define TUNTIL 25
+#define TWHILE 26
+#define TBEGIN 27
+#define TEND 28
 
- gotit:
-#if JOBS
-       err_msg = "job %s not created under job control";
-       if (getctl && jp->jobctl == 0)
-               goto err;
-#endif
-       return jp;
- err:
-       ash_msg_and_raise_error(err_msg, name);
-}
+/* first char is indicating which tokens mark the end of a list */
+static const char *const tokname_array[] = {
+       "\1end of file",
+       "\0newline",
+       "\0redirection",
+       "\0word",
+       "\0;",
+       "\0&",
+       "\0&&",
+       "\0||",
+       "\0|",
+       "\0(",
+       "\1)",
+       "\1;;",
+       "\1`",
+#define KWDOFFSET 13
+       /* the following are keywords */
+       "\0!",
+       "\0case",
+       "\1do",
+       "\1done",
+       "\1elif",
+       "\1else",
+       "\1esac",
+       "\1fi",
+       "\0for",
+       "\0if",
+       "\0in",
+       "\1then",
+       "\0until",
+       "\0while",
+       "\0{",
+       "\1}",
+};
 
-/*
- * Mark a job structure as unused.
- */
-static void
-freejob(struct job *jp)
+static const char *
+tokname(int tok)
 {
-       struct procstat *ps;
-       int i;
+       static char buf[16];
 
-       INT_OFF;
-       for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
-               if (ps->cmd != nullstr)
-                       free(ps->cmd);
-       }
-       if (jp->ps != &jp->ps0)
-               free(jp->ps);
-       jp->used = 0;
-       set_curjob(jp, CUR_DELETE);
-       INT_ON;
+//try this:
+//if (tok < TSEMI) return tokname_array[tok] + 1;
+//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
+//return buf;
+
+       if (tok >= TSEMI)
+               buf[0] = '"';
+       sprintf(buf + (tok >= TSEMI), "%s%c",
+                       tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
+       return buf;
 }
 
-#if JOBS
-static void
-xtcsetpgrp(int fd, pid_t pgrp)
+/* Wrapper around strcmp for qsort/bsearch/... */
+static int
+pstrcmp(const void *a, const void *b)
 {
-       if (tcsetpgrp(fd, pgrp))
-               ash_msg_and_raise_error("Cannot set tty process group (%m)");
+       return strcmp((char*) a, (*(char**) b) + 1);
 }
 
-/*
- * Turn job control on and off.
- *
- * Note:  This code assumes that the third arg to ioctl is a character
- * pointer, which is true on Berkeley systems but not System V.  Since
- * System V doesn't have job control yet, this isn't a problem now.
- *
- * Called with interrupts off.
- */
-static void
-setjobctl(int on)
+static const char *const *
+findkwd(const char *s)
 {
-       int fd;
-       int pgrp;
-
-       if (on == jobctl || rootshell == 0)
-               return;
-       if (on) {
-               int ofd;
-               ofd = fd = open(_PATH_TTY, O_RDWR);
-               if (fd < 0) {
-       /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
-        * That sometimes helps to acquire controlling tty.
-        * Obviously, a workaround for bugs when someone
-        * failed to provide a controlling tty to bash! :) */
-                       fd += 3;
-                       while (!isatty(fd) && --fd >= 0)
-                               ;
-               }
-               fd = fcntl(fd, F_DUPFD, 10);
-               close(ofd);
-               if (fd < 0)
-                       goto out;
-               fcntl(fd, F_SETFD, FD_CLOEXEC);
-               do { /* while we are in the background */
-                       pgrp = tcgetpgrp(fd);
-                       if (pgrp < 0) {
- out:
-                               ash_msg("can't access tty; job control turned off");
-                               mflag = on = 0;
-                               goto close;
-                       }
-                       if (pgrp == getpgrp())
-                               break;
-                       killpg(0, SIGTTIN);
-               } while (1);
-               initialpgrp = pgrp;
-
-               setsignal(SIGTSTP);
-               setsignal(SIGTTOU);
-               setsignal(SIGTTIN);
-               pgrp = rootpid;
-               setpgid(0, pgrp);
-               xtcsetpgrp(fd, pgrp);
-       } else {
-               /* turning job control off */
-               fd = ttyfd;
-               pgrp = initialpgrp;
-               xtcsetpgrp(fd, pgrp);
-               setpgid(0, pgrp);
-               setsignal(SIGTSTP);
-               setsignal(SIGTTOU);
-               setsignal(SIGTTIN);
- close:
-               close(fd);
-               fd = -1;
-       }
-       ttyfd = fd;
-       jobctl = on;
+       return bsearch(s, tokname_array + KWDOFFSET,
+                       (sizeof(tokname_array) / sizeof(char *)) - KWDOFFSET,
+                       sizeof(char *), pstrcmp);
 }
 
+/*
+ * Locate and print what a word is...
+ */
+#if ENABLE_ASH_CMDCMD
 static int
-killcmd(int argc, char **argv)
+describe_command(char *command, int describe_command_verbose)
+#else
+#define describe_command_verbose 1
+static int
+describe_command(char *command)
+#endif
 {
-       int signo = -1;
-       int list = 0;
-       int i;
-       pid_t pid;
-       struct job *jp;
-
-       if (argc <= 1) {
- usage:
-               ash_msg_and_raise_error(
-"Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
-"kill -l [exitstatus]"
-               );
-       }
-
-       if (**++argv == '-') {
-               signo = get_signum(*argv + 1);
-               if (signo < 0) {
-                       int c;
-
-                       while ((c = nextopt("ls:")) != '\0') {
-                               switch (c) {
-                               default:
-#if DEBUG
-                                       abort();
+       struct cmdentry entry;
+       struct tblentry *cmdp;
+#if ENABLE_ASH_ALIAS
+       const struct alias *ap;
 #endif
-                               case 'l':
-                                       list = 1;
-                                       break;
-                               case 's':
-                                       signo = get_signum(optionarg);
-                                       if (signo < 0) {
-                                               ash_msg_and_raise_error(
-                                                       "invalid signal number or name: %s",
-                                                       optionarg
-                                               );
-                                       }
-                                       break;
-                               }
-                       }
-                       argv = argptr;
-               } else
-                       argv++;
-       }
+       const char *path = pathval();
 
-       if (!list && signo < 0)
-               signo = SIGTERM;
+       if (describe_command_verbose) {
+               out1str(command);
+       }
 
-       if ((signo < 0 || !*argv) ^ list) {
-               goto usage;
+       /* First look at the keywords */
+       if (findkwd(command)) {
+               out1str(describe_command_verbose ? " is a shell keyword" : command);
+               goto out;
        }
 
-       if (list) {
-               const char *name;
-
-               if (!*argv) {
-                       for (i = 1; i < NSIG; i++) {
-                               name = get_signame(i);
-                               if (isdigit(*name))
-                                       out1fmt(snlfmt, name);
-                       }
+#if ENABLE_ASH_ALIAS
+       /* Then look at the aliases */
+       ap = lookupalias(command, 0);
+       if (ap != NULL) {
+               if (describe_command_verbose) {
+                       out1fmt(" is an alias for %s", ap->val);
+               } else {
+                       out1str("alias ");
+                       printalias(ap);
                        return 0;
                }
-               name = get_signame(signo);
-               if (!isdigit(*name))
-                       ash_msg_and_raise_error("invalid signal number or exit status: %s", *argptr);
-               out1fmt(snlfmt, name);
-               return 0;
+               goto out;
+       }
+#endif
+       /* Then check if it is a tracked alias */
+       cmdp = cmdlookup(command, 0);
+       if (cmdp != NULL) {
+               entry.cmdtype = cmdp->cmdtype;
+               entry.u = cmdp->param;
+       } else {
+               /* Finally use brute force */
+               find_command(command, &entry, DO_ABS, path);
        }
 
-       i = 0;
-       do {
-               if (**argv == '%') {
-                       jp = getjob(*argv, 0);
-                       pid = -jp->ps[0].pid;
+       switch (entry.cmdtype) {
+       case CMDNORMAL: {
+               int j = entry.u.index;
+               char *p;
+               if (j == -1) {
+                       p = command;
                } else {
-                       pid = **argv == '-' ?
-                               -number(*argv + 1) : number(*argv);
+                       do {
+                               p = padvance(&path, command);
+                               stunalloc(p);
+                       } while (--j >= 0);
                }
-               if (kill(pid, signo) != 0) {
-                       ash_msg("(%d) - %m", pid);
-                       i = 1;
+               if (describe_command_verbose) {
+                       out1fmt(" is%s %s",
+                               (cmdp ? " a tracked alias for" : nullstr), p
+                       );
+               } else {
+                       out1str(p);
                }
-       } while (*++argv);
-
-       return i;
-}
-
-static void
-showpipe(struct job *jp, FILE *out)
-{
-       struct procstat *sp;
-       struct procstat *spend;
-
-       spend = jp->ps + jp->nprocs;
-       for (sp = jp->ps + 1; sp < spend; sp++)
-               fprintf(out, " | %s", sp->cmd);
-       outcslow('\n', out);
-       flush_stdout_stderr();
-}
-
-
-static int
-restartjob(struct job *jp, int mode)
-{
-       struct procstat *ps;
-       int i;
-       int status;
-       pid_t pgid;
+               break;
+       }
 
-       INT_OFF;
-       if (jp->state == JOBDONE)
-               goto out;
-       jp->state = JOBRUNNING;
-       pgid = jp->ps->pid;
-       if (mode == FORK_FG)
-               xtcsetpgrp(ttyfd, pgid);
-       killpg(pgid, SIGCONT);
-       ps = jp->ps;
-       i = jp->nprocs;
-       do {
-               if (WIFSTOPPED(ps->status)) {
-                       ps->status = -1;
+       case CMDFUNCTION:
+               if (describe_command_verbose) {
+                       out1str(" is a shell function");
+               } else {
+                       out1str(command);
                }
-       } while (ps++, --i);
- out:
-       status = (mode == FORK_FG) ? waitforjob(jp) : 0;
-       INT_ON;
-       return status;
-}
+               break;
 
-static int
-fg_bgcmd(int argc, char **argv)
-{
-       struct job *jp;
-       FILE *out;
-       int mode;
-       int retval;
+       case CMDBUILTIN:
+               if (describe_command_verbose) {
+                       out1fmt(" is a %sshell builtin",
+                               IS_BUILTIN_SPECIAL(entry.u.cmd) ?
+                                       "special " : nullstr
+                       );
+               } else {
+                       out1str(command);
+               }
+               break;
 
-       mode = (**argv == 'f') ? FORK_FG : FORK_BG;
-       nextopt(nullstr);
-       argv = argptr;
-       out = stdout;
-       do {
-               jp = getjob(*argv, 1);
-               if (mode == FORK_BG) {
-                       set_curjob(jp, CUR_RUNNING);
-                       fprintf(out, "[%d] ", jobno(jp));
+       default:
+               if (describe_command_verbose) {
+                       out1str(": not found\n");
                }
-               outstr(jp->ps->cmd, out);
-               showpipe(jp, out);
-               retval = restartjob(jp, mode);
-       } while (*argv && *++argv);
-       return retval;
+               return 127;
+       }
+ out:
+       outstr("\n", stdout);
+       return 0;
 }
-#endif
 
 static int
-sprint_status(char *s, int status, int sigonly)
+typecmd(int argc, char **argv)
 {
-       int col;
-       int st;
+       int i;
+       int err = 0;
 
-       col = 0;
-       if (!WIFEXITED(status)) {
-#if JOBS
-               if (WIFSTOPPED(status))
-                       st = WSTOPSIG(status);
-               else
-#endif
-                       st = WTERMSIG(status);
-               if (sigonly) {
-                       if (st == SIGINT || st == SIGPIPE)
-                               goto out;
-#if JOBS
-                       if (WIFSTOPPED(status))
-                               goto out;
+       for (i = 1; i < argc; i++) {
+#if ENABLE_ASH_CMDCMD
+               err |= describe_command(argv[i], 1);
+#else
+               err |= describe_command(argv[i]);
 #endif
-               }
-               st &= 0x7f;
-               col = fmtstr(s, 32, strsignal(st));
-               if (WCOREDUMP(status)) {
-                       col += fmtstr(s + col, 16, " (core dumped)");
-               }
-       } else if (!sigonly) {
-               st = WEXITSTATUS(status);
-               if (st)
-                       col = fmtstr(s, 16, "Done(%d)", st);
-               else
-                       col = fmtstr(s, 16, "Done");
        }
- out:
-       return col;
+       return err;
 }
 
-/*
- * Do a wait system call.  If job control is compiled in, we accept
- * stopped processes.  If block is zero, we return a value of zero
- * rather than blocking.
- *
- * System V doesn't have a non-blocking wait system call.  It does
- * have a SIGCLD signal that is sent to a process when one of it's
- * children dies.  The obvious way to use SIGCLD would be to install
- * a handler for SIGCLD which simply bumped a counter when a SIGCLD
- * was received, and have waitproc bump another counter when it got
- * the status of a process.  Waitproc would then know that a wait
- * system call would not block if the two counters were different.
- * This approach doesn't work because if a process has children that
- * have not been waited for, System V will send it a SIGCLD when it
- * installs a signal handler for SIGCLD.  What this means is that when
- * a child exits, the shell will be sent SIGCLD signals continuously
- * until is runs out of stack space, unless it does a wait call before
- * restoring the signal handler.  The code below takes advantage of
- * this (mis)feature by installing a signal handler for SIGCLD and
- * then checking to see whether it was called.  If there are any
- * children to be waited for, it will be.
- *
- * If neither SYSV nor BSD is defined, we don't implement nonblocking
- * waits at all.  In this case, the user will not be informed when
- * a background process until the next time she runs a real program
- * (as opposed to running a builtin command or just typing return),
- * and the jobs command may give out of date information.
- */
+#if ENABLE_ASH_CMDCMD
 static int
-waitproc(int block, int *status)
+commandcmd(int argc, char **argv)
 {
-       int flags = 0;
+       int c;
+       enum {
+               VERIFY_BRIEF = 1,
+               VERIFY_VERBOSE = 2,
+       } verify = 0;
 
-#if JOBS
-       if (jobctl)
-               flags |= WUNTRACED;
+       while ((c = nextopt("pvV")) != '\0')
+               if (c == 'V')
+                       verify |= VERIFY_VERBOSE;
+               else if (c == 'v')
+                       verify |= VERIFY_BRIEF;
+#if DEBUG
+               else if (c != 'p')
+                       abort();
 #endif
-       if (block == 0)
-               flags |= WNOHANG;
-       return wait3(status, flags, (struct rusage *)NULL);
+       if (verify)
+               return describe_command(*argptr, verify - VERIFY_BRIEF);
+
+       return 0;
 }
+#endif
 
-/*
- * Wait for a process to terminate.
- */
-static int
-dowait(int block, struct job *job)
-{
-       int pid;
-       int status;
-       struct job *jp;
-       struct job *thisjob;
-       int state;
 
-       TRACE(("dowait(%d) called\n", block));
-       pid = waitproc(block, &status);
-       TRACE(("wait returns pid %d, status=%d\n", pid, status));
-       if (pid <= 0)
-               return pid;
-       INT_OFF;
-       thisjob = NULL;
-       for (jp = curjob; jp; jp = jp->prev_job) {
-               struct procstat *sp;
-               struct procstat *spend;
-               if (jp->state == JOBDONE)
-                       continue;
-               state = JOBDONE;
-               spend = jp->ps + jp->nprocs;
-               sp = jp->ps;
-               do {
-                       if (sp->pid == pid) {
-                               TRACE(("Job %d: changing status of proc %d "
-                                       "from 0x%x to 0x%x\n",
-                                       jobno(jp), pid, sp->status, status));
-                               sp->status = status;
-                               thisjob = jp;
-                       }
-                       if (sp->status == -1)
-                               state = JOBRUNNING;
-#if JOBS
-                       if (state == JOBRUNNING)
-                               continue;
-                       if (WIFSTOPPED(sp->status)) {
-                               jp->stopstatus = sp->status;
-                               state = JOBSTOPPED;
-                       }
-#endif
-               } while (++sp < spend);
-               if (thisjob)
-                       goto gotjob;
-       }
-#if JOBS
-       if (!WIFSTOPPED(status))
-#endif
-
-               jobless--;
-       goto out;
+/* ============ eval.c */
 
- gotjob:
-       if (state != JOBRUNNING) {
-               thisjob->changed = 1;
+static int funcblocksize;          /* size of structures in function */
+static int funcstringsize;         /* size of strings in node */
+static void *funcblock;            /* block to allocate function from */
+static char *funcstring;           /* block to allocate strings from */
 
-               if (thisjob->state != state) {
-                       TRACE(("Job %d: changing state from %d to %d\n",
-                               jobno(thisjob), thisjob->state, state));
-                       thisjob->state = state;
-#if JOBS
-                       if (state == JOBSTOPPED) {
-                               set_curjob(thisjob, CUR_STOPPED);
-                       }
-#endif
-               }
-       }
+/* flags in argument to evaltree */
+#define EV_EXIT 01              /* exit after evaluating tree */
+#define EV_TESTED 02            /* exit status is checked; ignore -e flag */
+#define EV_BACKCMD 04           /* command executing within back quotes */
 
- out:
-       INT_ON;
+static const short nodesize[26] = {
+       SHELL_ALIGN(sizeof(struct ncmd)),
+       SHELL_ALIGN(sizeof(struct npipe)),
+       SHELL_ALIGN(sizeof(struct nredir)),
+       SHELL_ALIGN(sizeof(struct nredir)),
+       SHELL_ALIGN(sizeof(struct nredir)),
+       SHELL_ALIGN(sizeof(struct nbinary)),
+       SHELL_ALIGN(sizeof(struct nbinary)),
+       SHELL_ALIGN(sizeof(struct nbinary)),
+       SHELL_ALIGN(sizeof(struct nif)),
+       SHELL_ALIGN(sizeof(struct nbinary)),
+       SHELL_ALIGN(sizeof(struct nbinary)),
+       SHELL_ALIGN(sizeof(struct nfor)),
+       SHELL_ALIGN(sizeof(struct ncase)),
+       SHELL_ALIGN(sizeof(struct nclist)),
+       SHELL_ALIGN(sizeof(struct narg)),
+       SHELL_ALIGN(sizeof(struct narg)),
+       SHELL_ALIGN(sizeof(struct nfile)),
+       SHELL_ALIGN(sizeof(struct nfile)),
+       SHELL_ALIGN(sizeof(struct nfile)),
+       SHELL_ALIGN(sizeof(struct nfile)),
+       SHELL_ALIGN(sizeof(struct nfile)),
+       SHELL_ALIGN(sizeof(struct ndup)),
+       SHELL_ALIGN(sizeof(struct ndup)),
+       SHELL_ALIGN(sizeof(struct nhere)),
+       SHELL_ALIGN(sizeof(struct nhere)),
+       SHELL_ALIGN(sizeof(struct nnot)),
+};
 
-       if (thisjob && thisjob == job) {
-               char s[48 + 1];
-               int len;
+static void calcsize(union node *n);
 
-               len = sprint_status(s, status, 1);
-               if (len) {
-                       s[len] = '\n';
-                       s[len + 1] = 0;
-                       out2str(s);
-               }
+static void
+sizenodelist(struct nodelist *lp)
+{
+       while (lp) {
+               funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
+               calcsize(lp->n);
+               lp = lp->next;
        }
-       return pid;
 }
 
-#if JOBS
 static void
-showjob(FILE *out, struct job *jp, int mode)
+calcsize(union node *n)
 {
-       struct procstat *ps;
-       struct procstat *psend;
-       int col;
-       int indent;
-       char s[80];
-
-       ps = jp->ps;
-
-       if (mode & SHOW_PGID) {
-               /* just output process (group) id of pipeline */
-               fprintf(out, "%d\n", ps->pid);
+       if (n == NULL)
                return;
-       }
-
-       col = fmtstr(s, 16, "[%d]   ", jobno(jp));
-       indent = col;
-
-       if (jp == curjob)
-               s[col - 2] = '+';
-       else if (curjob && jp == curjob->prev_job)
-               s[col - 2] = '-';
-
-       if (mode & SHOW_PID)
-               col += fmtstr(s + col, 16, "%d ", ps->pid);
-
-       psend = ps + jp->nprocs;
+       funcblocksize += nodesize[n->type];
+       switch (n->type) {
+       case NCMD:
+               calcsize(n->ncmd.redirect);
+               calcsize(n->ncmd.args);
+               calcsize(n->ncmd.assign);
+               break;
+       case NPIPE:
+               sizenodelist(n->npipe.cmdlist);
+               break;
+       case NREDIR:
+       case NBACKGND:
+       case NSUBSHELL:
+               calcsize(n->nredir.redirect);
+               calcsize(n->nredir.n);
+               break;
+       case NAND:
+       case NOR:
+       case NSEMI:
+       case NWHILE:
+       case NUNTIL:
+               calcsize(n->nbinary.ch2);
+               calcsize(n->nbinary.ch1);
+               break;
+       case NIF:
+               calcsize(n->nif.elsepart);
+               calcsize(n->nif.ifpart);
+               calcsize(n->nif.test);
+               break;
+       case NFOR:
+               funcstringsize += strlen(n->nfor.var) + 1;
+               calcsize(n->nfor.body);
+               calcsize(n->nfor.args);
+               break;
+       case NCASE:
+               calcsize(n->ncase.cases);
+               calcsize(n->ncase.expr);
+               break;
+       case NCLIST:
+               calcsize(n->nclist.body);
+               calcsize(n->nclist.pattern);
+               calcsize(n->nclist.next);
+               break;
+       case NDEFUN:
+       case NARG:
+               sizenodelist(n->narg.backquote);
+               funcstringsize += strlen(n->narg.text) + 1;
+               calcsize(n->narg.next);
+               break;
+       case NTO:
+       case NCLOBBER:
+       case NFROM:
+       case NFROMTO:
+       case NAPPEND:
+               calcsize(n->nfile.fname);
+               calcsize(n->nfile.next);
+               break;
+       case NTOFD:
+       case NFROMFD:
+               calcsize(n->ndup.vname);
+               calcsize(n->ndup.next);
+       break;
+       case NHERE:
+       case NXHERE:
+               calcsize(n->nhere.doc);
+               calcsize(n->nhere.next);
+               break;
+       case NNOT:
+               calcsize(n->nnot.com);
+               break;
+       };
+}
 
-       if (jp->state == JOBRUNNING) {
-               strcpy(s + col, "Running");
-               col += sizeof("Running") - 1;
-       } else {
-               int status = psend[-1].status;
-               if (jp->state == JOBSTOPPED)
-                       status = jp->stopstatus;
-               col += sprint_status(s + col, status, 0);
-       }
+static char *
+nodeckstrdup(char *s)
+{
+       char *rtn = funcstring;
 
-       goto start;
+       strcpy(funcstring, s);
+       funcstring += strlen(s) + 1;
+       return rtn;
+}
 
-       do {
-               /* for each process */
-               col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
- start:
-               fprintf(out, "%s%*c%s",
-                       s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
-               );
-               if (!(mode & SHOW_PID)) {
-                       showpipe(jp, out);
-                       break;
-               }
-               if (++ps == psend) {
-                       outcslow('\n', out);
-                       break;
-               }
-       } while (1);
+static union node *copynode(union node *);
 
-       jp->changed = 0;
+static struct nodelist *
+copynodelist(struct nodelist *lp)
+{
+       struct nodelist *start;
+       struct nodelist **lpp;
 
-       if (jp->state == JOBDONE) {
-               TRACE(("showjob: freeing job %d\n", jobno(jp)));
-               freejob(jp);
+       lpp = &start;
+       while (lp) {
+               *lpp = funcblock;
+               funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
+               (*lpp)->n = copynode(lp->n);
+               lp = lp->next;
+               lpp = &(*lpp)->next;
        }
+       *lpp = NULL;
+       return start;
 }
 
-static int
-jobscmd(int argc, char **argv)
+static union node *
+copynode(union node *n)
 {
-       int mode, m;
-       FILE *out;
-
-       mode = 0;
-       while ((m = nextopt("lp"))) {
-               if (m == 'l')
-                       mode = SHOW_PID;
-               else
-                       mode = SHOW_PGID;
-       }
+       union node *new;
 
-       out = stdout;
-       argv = argptr;
-       if (*argv) {
-               do
-                       showjob(out, getjob(*argv,0), mode);
-               while (*++argv);
-       } else
-               showjobs(out, mode);
+       if (n == NULL)
+               return NULL;
+       new = funcblock;
+       funcblock = (char *) funcblock + nodesize[n->type];
 
-       return 0;
+       switch (n->type) {
+       case NCMD:
+               new->ncmd.redirect = copynode(n->ncmd.redirect);
+               new->ncmd.args = copynode(n->ncmd.args);
+               new->ncmd.assign = copynode(n->ncmd.assign);
+               break;
+       case NPIPE:
+               new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
+               new->npipe.backgnd = n->npipe.backgnd;
+               break;
+       case NREDIR:
+       case NBACKGND:
+       case NSUBSHELL:
+               new->nredir.redirect = copynode(n->nredir.redirect);
+               new->nredir.n = copynode(n->nredir.n);
+               break;
+       case NAND:
+       case NOR:
+       case NSEMI:
+       case NWHILE:
+       case NUNTIL:
+               new->nbinary.ch2 = copynode(n->nbinary.ch2);
+               new->nbinary.ch1 = copynode(n->nbinary.ch1);
+               break;
+       case NIF:
+               new->nif.elsepart = copynode(n->nif.elsepart);
+               new->nif.ifpart = copynode(n->nif.ifpart);
+               new->nif.test = copynode(n->nif.test);
+               break;
+       case NFOR:
+               new->nfor.var = nodeckstrdup(n->nfor.var);
+               new->nfor.body = copynode(n->nfor.body);
+               new->nfor.args = copynode(n->nfor.args);
+               break;
+       case NCASE:
+               new->ncase.cases = copynode(n->ncase.cases);
+               new->ncase.expr = copynode(n->ncase.expr);
+               break;
+       case NCLIST:
+               new->nclist.body = copynode(n->nclist.body);
+               new->nclist.pattern = copynode(n->nclist.pattern);
+               new->nclist.next = copynode(n->nclist.next);
+               break;
+       case NDEFUN:
+       case NARG:
+               new->narg.backquote = copynodelist(n->narg.backquote);
+               new->narg.text = nodeckstrdup(n->narg.text);
+               new->narg.next = copynode(n->narg.next);
+               break;
+       case NTO:
+       case NCLOBBER:
+       case NFROM:
+       case NFROMTO:
+       case NAPPEND:
+               new->nfile.fname = copynode(n->nfile.fname);
+               new->nfile.fd = n->nfile.fd;
+               new->nfile.next = copynode(n->nfile.next);
+               break;
+       case NTOFD:
+       case NFROMFD:
+               new->ndup.vname = copynode(n->ndup.vname);
+               new->ndup.dupfd = n->ndup.dupfd;
+               new->ndup.fd = n->ndup.fd;
+               new->ndup.next = copynode(n->ndup.next);
+               break;
+       case NHERE:
+       case NXHERE:
+               new->nhere.doc = copynode(n->nhere.doc);
+               new->nhere.fd = n->nhere.fd;
+               new->nhere.next = copynode(n->nhere.next);
+               break;
+       case NNOT:
+               new->nnot.com = copynode(n->nnot.com);
+               break;
+       };
+       new->type = n->type;
+       return new;
 }
 
 /*
- * Print a list of jobs.  If "change" is nonzero, only print jobs whose
- * statuses have changed since the last call to showjobs.
+ * Make a copy of a parse tree.
  */
-static void
-showjobs(FILE *out, int mode)
+static struct funcnode *
+copyfunc(union node *n)
 {
-       struct job *jp;
-
-       TRACE(("showjobs(%x) called\n", mode));
-
-       /* If not even one one job changed, there is nothing to do */
-       while (dowait(DOWAIT_NORMAL, NULL) > 0)
-               continue;
+       struct funcnode *f;
+       size_t blocksize;
 
-       for (jp = curjob; jp; jp = jp->prev_job) {
-               if (!(mode & SHOW_CHANGED) || jp->changed)
-                       showjob(out, jp, mode);
-       }
+       funcblocksize = offsetof(struct funcnode, n);
+       funcstringsize = 0;
+       calcsize(n);
+       blocksize = funcblocksize;
+       f = ckmalloc(blocksize + funcstringsize);
+       funcblock = (char *) f + offsetof(struct funcnode, n);
+       funcstring = (char *) f + blocksize;
+       copynode(n);
+       f->count = 0;
+       return f;
 }
-#endif /* JOBS */
 
-static int
-getstatus(struct job *job)
+/*
+ * Define a shell function.
+ */
+static void
+defun(char *name, union node *func)
 {
-       int status;
-       int retval;
+       struct cmdentry entry;
 
-       status = job->ps[job->nprocs - 1].status;
-       retval = WEXITSTATUS(status);
-       if (!WIFEXITED(status)) {
-#if JOBS
-               retval = WSTOPSIG(status);
-               if (!WIFSTOPPED(status))
-#endif
-               {
-                       /* XXX: limits number of signals */
-                       retval = WTERMSIG(status);
-#if JOBS
-                       if (retval == SIGINT)
-                               job->sigint = 1;
-#endif
-               }
-               retval += 128;
-       }
-       TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
-               jobno(job), job->nprocs, status, retval));
-       return retval;
+       INT_OFF;
+       entry.cmdtype = CMDFUNCTION;
+       entry.u.func = copyfunc(func);
+       addcmdentry(name, &entry);
+       INT_ON;
 }
 
+static int evalskip;            /* set if we are skipping commands */
+/* reasons for skipping commands (see comment on breakcmd routine) */
+#define SKIPBREAK      (1 << 0)
+#define SKIPCONT       (1 << 1)
+#define SKIPFUNC       (1 << 2)
+#define SKIPFILE       (1 << 3)
+#define SKIPEVAL       (1 << 4)
+static int skipcount;           /* number of levels to skip */
+static int funcnest;            /* depth of function calls */
+
+/* forward decl way out to parsing code - dotrap needs it */
+static int evalstring(char *s, int mask);
+
+/*
+ * Called to execute a trap.  Perhaps we should avoid entering new trap
+ * handlers while we are executing a trap handler.
+ */
 static int
-waitcmd(int argc, char **argv)
+dotrap(void)
 {
-       struct job *job;
-       int retval;
-       struct job *jp;
+       char *p;
+       char *q;
+       int i;
+       int savestatus;
+       int skip = 0;
 
-       EXSIGON;
+       savestatus = exitstatus;
+       pendingsig = 0;
+       xbarrier();
 
-       nextopt(nullstr);
-       retval = 0;
+       for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
+               if (!*q)
+                       continue;
+               *q = '\0';
 
-       argv = argptr;
-       if (!*argv) {
-               /* wait for all jobs */
-               for (;;) {
-                       jp = curjob;
-                       while (1) {
-                               if (!jp) {
-                                       /* no running procs */
-                                       goto out;
-                               }
-                               if (jp->state == JOBRUNNING)
-                                       break;
-                               jp->waited = 1;
-                               jp = jp->prev_job;
-                       }
-                       dowait(DOWAIT_BLOCK, 0);
-               }
+               p = trap[i + 1];
+               if (!p)
+                       continue;
+               skip = evalstring(p, SKIPEVAL);
+               exitstatus = savestatus;
+               if (skip)
+                       break;
        }
 
-       retval = 127;
-       do {
-               if (**argv != '%') {
-                       pid_t pid = number(*argv);
-                       job = curjob;
-                       goto start;
-                       do {
-                               if (job->ps[job->nprocs - 1].pid == pid)
-                                       break;
-                               job = job->prev_job;
- start:
-                               if (!job)
-                                       goto repeat;
-                       } while (1);
-               } else
-                       job = getjob(*argv, 0);
-               /* loop until process terminated or stopped */
-               while (job->state == JOBRUNNING)
-                       dowait(DOWAIT_BLOCK, 0);
-               job->waited = 1;
-               retval = getstatus(job);
- repeat:
-               ;
-       } while (*++argv);
-
- out:
-       return retval;
+       return skip;
 }
 
-static struct job *
-growjobtab(void)
-{
-       size_t len;
-       ptrdiff_t offset;
-       struct job *jp, *jq;
-
-       len = njobs * sizeof(*jp);
-       jq = jobtab;
-       jp = ckrealloc(jq, len + 4 * sizeof(*jp));
-
-       offset = (char *)jp - (char *)jq;
-       if (offset) {
-               /* Relocate pointers */
-               size_t l = len;
-
-               jq = (struct job *)((char *)jq + l);
-               while (l) {
-                       l -= sizeof(*jp);
-                       jq--;
-#define joff(p) ((struct job *)((char *)(p) + l))
-#define jmove(p) (p) = (void *)((char *)(p) + offset)
-                       if (xlikely(joff(jp)->ps == &jq->ps0))
-                               jmove(joff(jp)->ps);
-                       if (joff(jp)->prev_job)
-                               jmove(joff(jp)->prev_job);
-               }
-               if (curjob)
-                       jmove(curjob);
-#undef joff
-#undef jmove
-       }
-
-       njobs += 4;
-       jobtab = jp;
-       jp = (struct job *)((char *)jp + len);
-       jq = jp + 3;
-       do {
-               jq->used = 0;
-       } while (--jq >= jp);
-       return jp;
-}
+/* forward declarations - evaluation is fairly recursive business... */
+static void evalloop(union node *, int);
+static void evalfor(union node *, int);
+static void evalcase(union node *, int);
+static void evalsubshell(union node *, int);
+static void expredir(union node *);
+static void evalpipe(union node *, int);
+static void evalcommand(union node *, int);
+static int evalbltin(const struct builtincmd *, int, char **);
+static void prehash(union node *);
 
 /*
- * Return a new job structure.
- * Called with interrupts off.
+ * Evaluate a parse tree.  The value is left in the global variable
+ * exitstatus.
  */
-static struct job *
-makejob(union node *node, int nprocs)
+static void
+evaltree(union node *n, int flags)
 {
-       int i;
-       struct job *jp;
-
-       for (i = njobs, jp = jobtab; ; jp++) {
-               if (--i < 0) {
-                       jp = growjobtab();
+       int checkexit = 0;
+       void (*evalfn)(union node *, int);
+       unsigned isor;
+       int status;
+       if (n == NULL) {
+               TRACE(("evaltree(NULL) called\n"));
+               goto out;
+       }
+       TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
+                       getpid(), n, n->type, flags));
+       switch (n->type) {
+       default:
+#if DEBUG
+               out1fmt("Node type = %d\n", n->type);
+               fflush(stdout);
+               break;
+#endif
+       case NNOT:
+               evaltree(n->nnot.com, EV_TESTED);
+               status = !exitstatus;
+               goto setstatus;
+       case NREDIR:
+               expredir(n->nredir.redirect);
+               status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
+               if (!status) {
+                       evaltree(n->nredir.n, flags & EV_TESTED);
+                       status = exitstatus;
+               }
+               popredir(0);
+               goto setstatus;
+       case NCMD:
+               evalfn = evalcommand;
+ checkexit:
+               if (eflag && !(flags & EV_TESTED))
+                       checkexit = ~0;
+               goto calleval;
+       case NFOR:
+               evalfn = evalfor;
+               goto calleval;
+       case NWHILE:
+       case NUNTIL:
+               evalfn = evalloop;
+               goto calleval;
+       case NSUBSHELL:
+       case NBACKGND:
+               evalfn = evalsubshell;
+               goto calleval;
+       case NPIPE:
+               evalfn = evalpipe;
+               goto checkexit;
+       case NCASE:
+               evalfn = evalcase;
+               goto calleval;
+       case NAND:
+       case NOR:
+       case NSEMI:
+#if NAND + 1 != NOR
+#error NAND + 1 != NOR
+#endif
+#if NOR + 1 != NSEMI
+#error NOR + 1 != NSEMI
+#endif
+               isor = n->type - NAND;
+               evaltree(
+                       n->nbinary.ch1,
+                       (flags | ((isor >> 1) - 1)) & EV_TESTED
+               );
+               if (!exitstatus == isor)
+                       break;
+               if (!evalskip) {
+                       n = n->nbinary.ch2;
+ evaln:
+                       evalfn = evaltree;
+ calleval:
+                       evalfn(n, flags);
                        break;
                }
-               if (jp->used == 0)
+               break;
+       case NIF:
+               evaltree(n->nif.test, EV_TESTED);
+               if (evalskip)
                        break;
-               if (jp->state != JOBDONE || !jp->waited)
-                       continue;
-#if JOBS
-               if (jobctl)
-                       continue;
-#endif
-               freejob(jp);
+               if (exitstatus == 0) {
+                       n = n->nif.ifpart;
+                       goto evaln;
+               } else if (n->nif.elsepart) {
+                       n = n->nif.elsepart;
+                       goto evaln;
+               }
+               goto success;
+       case NDEFUN:
+               defun(n->narg.text, n->narg.next);
+ success:
+               status = 0;
+ setstatus:
+               exitstatus = status;
                break;
        }
-       memset(jp, 0, sizeof(*jp));
-#if JOBS
-       if (jobctl)
-               jp->jobctl = 1;
-#endif
-       jp->prev_job = curjob;
-       curjob = jp;
-       jp->used = 1;
-       jp->ps = &jp->ps0;
-       if (nprocs > 1) {
-               jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
+ out:
+       if ((checkexit & exitstatus))
+               evalskip |= SKIPEVAL;
+       else if (pendingsig && dotrap())
+               goto exexit;
+
+       if (flags & EV_EXIT) {
+ exexit:
+               raise_exception(EXEXIT);
        }
-       TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
-                               jobno(jp)));
-       return jp;
 }
 
-#if JOBS
-/*
- * Return a string identifying a command (to be printed by the
- * jobs command).
- */
-static char *cmdnextc;
+#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
+static
+#endif
+void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
+
+static int loopnest;            /* current loop nesting level */
 
 static void
-cmdputs(const char *s)
+evalloop(union node *n, int flags)
 {
-       const char *p, *str;
-       char c, cc[2] = " ";
-       char *nextc;
-       int subtype = 0;
-       int quoted = 0;
-       static const char vstype[VSTYPE + 1][4] = {
-               "", "}", "-", "+", "?", "=",
-               "%", "%%", "#", "##"
-       };
+       int status;
 
-       nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
-       p = s;
-       while ((c = *p++) != 0) {
-               str = 0;
-               switch (c) {
-               case CTLESC:
-                       c = *p++;
+       loopnest++;
+       status = 0;
+       flags &= EV_TESTED;
+       for (;;) {
+               int i;
+
+               evaltree(n->nbinary.ch1, EV_TESTED);
+               if (evalskip) {
+ skipping:
+                       if (evalskip == SKIPCONT && --skipcount <= 0) {
+                               evalskip = 0;
+                               continue;
+                       }
+                       if (evalskip == SKIPBREAK && --skipcount <= 0)
+                               evalskip = 0;
                        break;
-               case CTLVAR:
-                       subtype = *p++;
-                       if ((subtype & VSTYPE) == VSLENGTH)
-                               str = "${#";
-                       else
-                               str = "${";
-                       if (!(subtype & VSQUOTE) == !(quoted & 1))
-                               goto dostr;
-                       quoted ^= 1;
-                       c = '"';
+               }
+               i = exitstatus;
+               if (n->type != NWHILE)
+                       i = !i;
+               if (i != 0)
                        break;
-               case CTLENDVAR:
-                       str = "\"}" + !(quoted & 1);
-                       quoted >>= 1;
-                       subtype = 0;
-                       goto dostr;
-               case CTLBACKQ:
-                       str = "$(...)";
-                       goto dostr;
-               case CTLBACKQ+CTLQUOTE:
-                       str = "\"$(...)\"";
-                       goto dostr;
-#if ENABLE_ASH_MATH_SUPPORT
-               case CTLARI:
-                       str = "$((";
-                       goto dostr;
-               case CTLENDARI:
-                       str = "))";
-                       goto dostr;
-#endif
-               case CTLQUOTEMARK:
-                       quoted ^= 1;
-                       c = '"';
-                       break;
-               case '=':
-                       if (subtype == 0)
-                               break;
-                       if ((subtype & VSTYPE) != VSNORMAL)
-                               quoted <<= 1;
-                       str = vstype[subtype & VSTYPE];
-                       if (subtype & VSNUL)
-                               c = ':';
-                       else
-                               goto checkstr;
-                       break;
-               case '\'':
-               case '\\':
-               case '"':
-               case '$':
-                       /* These can only happen inside quotes */
-                       cc[0] = c;
-                       str = cc;
-                       c = '\\';
-                       break;
-               default:
+               evaltree(n->nbinary.ch2, flags);
+               status = exitstatus;
+               if (evalskip)
+                       goto skipping;
+       }
+       loopnest--;
+       exitstatus = status;
+}
+
+static void
+evalfor(union node *n, int flags)
+{
+       struct arglist arglist;
+       union node *argp;
+       struct strlist *sp;
+       struct stackmark smark;
+
+       setstackmark(&smark);
+       arglist.lastp = &arglist.list;
+       for (argp = n->nfor.args; argp; argp = argp->narg.next) {
+               expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
+               /* XXX */
+               if (evalskip)
+                       goto out;
+       }
+       *arglist.lastp = NULL;
+
+       exitstatus = 0;
+       loopnest++;
+       flags &= EV_TESTED;
+       for (sp = arglist.list; sp; sp = sp->next) {
+               setvar(n->nfor.var, sp->text, 0);
+               evaltree(n->nfor.body, flags);
+               if (evalskip) {
+                       if (evalskip == SKIPCONT && --skipcount <= 0) {
+                               evalskip = 0;
+                               continue;
+                       }
+                       if (evalskip == SKIPBREAK && --skipcount <= 0)
+                               evalskip = 0;
                        break;
                }
-               USTPUTC(c, nextc);
- checkstr:
-               if (!str)
-                       continue;
- dostr:
-               while ((c = *str++)) {
-                       USTPUTC(c, nextc);
-               }
        }
-       if (quoted & 1) {
-               USTPUTC('"', nextc);
+       loopnest--;
+ out:
+       popstackmark(&smark);
+}
+
+static void
+evalcase(union node *n, int flags)
+{
+       union node *cp;
+       union node *patp;
+       struct arglist arglist;
+       struct stackmark smark;
+
+       setstackmark(&smark);
+       arglist.lastp = &arglist.list;
+       expandarg(n->ncase.expr, &arglist, EXP_TILDE);
+       exitstatus = 0;
+       for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
+               for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
+                       if (casematch(patp, arglist.list->text)) {
+                               if (evalskip == 0) {
+                                       evaltree(cp->nclist.body, flags);
+                               }
+                               goto out;
+                       }
+               }
        }
-       *nextc = 0;
-       cmdnextc = nextc;
+ out:
+       popstackmark(&smark);
 }
 
-/* cmdtxt() and cmdlist() call each other */
-static void cmdtxt(union node *n);
+/*
+ * Kick off a subshell to evaluate a tree.
+ */
+static void
+evalsubshell(union node *n, int flags)
+{
+       struct job *jp;
+       int backgnd = (n->type == NBACKGND);
+       int status;
+
+       expredir(n->nredir.redirect);
+       if (!backgnd && flags & EV_EXIT && !trap[0])
+               goto nofork;
+       INT_OFF;
+       jp = makejob(n, 1);
+       if (forkshell(jp, n, backgnd) == 0) {
+               INT_ON;
+               flags |= EV_EXIT;
+               if (backgnd)
+                       flags &=~ EV_TESTED;
+ nofork:
+               redirect(n->nredir.redirect, 0);
+               evaltreenr(n->nredir.n, flags);
+               /* never returns */
+       }
+       status = 0;
+       if (! backgnd)
+               status = waitforjob(jp);
+       exitstatus = status;
+       INT_ON;
+}
 
+/*
+ * Compute the names of the files in a redirection list.
+ */
+static void fixredir(union node *, const char *, int);
 static void
-cmdlist(union node *np, int sep)
+expredir(union node *n)
 {
-       for (; np; np = np->narg.next) {
-               if (!sep)
-                       cmdputs(spcstr);
-               cmdtxt(np);
-               if (sep && np->narg.next)
-                       cmdputs(spcstr);
+       union node *redir;
+
+       for (redir = n; redir; redir = redir->nfile.next) {
+               struct arglist fn;
+
+               memset(&fn, 0, sizeof(fn));
+               fn.lastp = &fn.list;
+               switch (redir->type) {
+               case NFROMTO:
+               case NFROM:
+               case NTO:
+               case NCLOBBER:
+               case NAPPEND:
+                       expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
+                       redir->nfile.expfname = fn.list->text;
+                       break;
+               case NFROMFD:
+               case NTOFD:
+                       if (redir->ndup.vname) {
+                               expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
+                               if (fn.list == NULL)
+                                       ash_msg_and_raise_error("redir error");
+                               fixredir(redir, fn.list->text, 1);
+                       }
+                       break;
+               }
        }
 }
 
+/*
+ * Evaluate a pipeline.  All the processes in the pipeline are children
+ * of the process creating the pipeline.  (This differs from some versions
+ * of the shell, which make the last process in a pipeline the parent
+ * of all the rest.)
+ */
 static void
-cmdtxt(union node *n)
+evalpipe(union node *n, int flags)
 {
-       union node *np;
+       struct job *jp;
        struct nodelist *lp;
-       const char *p;
-       char s[2];
+       int pipelen;
+       int prevfd;
+       int pip[2];
 
-       if (!n)
-               return;
-       switch (n->type) {
-       default:
-#if DEBUG
-               abort();
-#endif
-       case NPIPE:
-               lp = n->npipe.cmdlist;
-               for (;;) {
-                       cmdtxt(lp->n);
-                       lp = lp->next;
-                       if (!lp)
-                               break;
-                       cmdputs(" | ");
+       TRACE(("evalpipe(0x%lx) called\n", (long)n));
+       pipelen = 0;
+       for (lp = n->npipe.cmdlist; lp; lp = lp->next)
+               pipelen++;
+       flags |= EV_EXIT;
+       INT_OFF;
+       jp = makejob(n, pipelen);
+       prevfd = -1;
+       for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
+               prehash(lp->n);
+               pip[1] = -1;
+               if (lp->next) {
+                       if (pipe(pip) < 0) {
+                               close(prevfd);
+                               ash_msg_and_raise_error("pipe call failed");
+                       }
                }
-               break;
-       case NSEMI:
-               p = "; ";
-               goto binop;
-       case NAND:
-               p = " && ";
-               goto binop;
-       case NOR:
-               p = " || ";
- binop:
-               cmdtxt(n->nbinary.ch1);
-               cmdputs(p);
-               n = n->nbinary.ch2;
-               goto donode;
-       case NREDIR:
-       case NBACKGND:
-               n = n->nredir.n;
-               goto donode;
-       case NNOT:
-               cmdputs("!");
-               n = n->nnot.com;
- donode:
-               cmdtxt(n);
-               break;
-       case NIF:
-               cmdputs("if ");
-               cmdtxt(n->nif.test);
-               cmdputs("; then ");
-               n = n->nif.ifpart;
-               if (n->nif.elsepart) {
-                       cmdtxt(n);
-                       cmdputs("; else ");
-                       n = n->nif.elsepart;
+               if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
+                       INT_ON;
+                       if (pip[1] >= 0) {
+                               close(pip[0]);
+                       }
+                       if (prevfd > 0) {
+                               dup2(prevfd, 0);
+                               close(prevfd);
+                       }
+                       if (pip[1] > 1) {
+                               dup2(pip[1], 1);
+                               close(pip[1]);
+                       }
+                       evaltreenr(lp->n, flags);
+                       /* never returns */
+               }
+               if (prevfd >= 0)
+                       close(prevfd);
+               prevfd = pip[0];
+               close(pip[1]);
+       }
+       if (n->npipe.backgnd == 0) {
+               exitstatus = waitforjob(jp);
+               TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
+       }
+       INT_ON;
+}
+
+/*
+ * Controls whether the shell is interactive or not.
+ */
+static void
+setinteractive(int on)
+{
+       static int is_interactive;
+
+       if (++on == is_interactive)
+               return;
+       is_interactive = on;
+       setsignal(SIGINT);
+       setsignal(SIGQUIT);
+       setsignal(SIGTERM);
+#if !ENABLE_FEATURE_SH_EXTRA_QUIET
+       if (is_interactive > 1) {
+               /* Looks like they want an interactive shell */
+               static smallint do_banner;
+
+               if (!do_banner) {
+                       out1fmt(
+                               "\n\n"
+                               "%s Built-in shell (ash)\n"
+                               "Enter 'help' for a list of built-in commands."
+                               "\n\n",
+                               BB_BANNER);
+                       do_banner = 1;
+               }
+       }
+#endif
+}
+
+#if ENABLE_FEATURE_EDITING_VI
+#define setvimode(on) do { \
+       if (on) line_input_state->flags |= VI_MODE; \
+       else line_input_state->flags &= ~VI_MODE; \
+} while (0)
+#else
+#define setvimode(on) viflag = 0   /* forcibly keep the option off */
+#endif
+
+static void
+optschanged(void)
+{
+#if DEBUG
+       opentrace();
+#endif
+       setinteractive(iflag);
+       setjobctl(mflag);
+       setvimode(viflag);
+}
+
+static struct localvar *localvars;
+
+/*
+ * Called after a function returns.
+ * Interrupts must be off.
+ */
+static void
+poplocalvars(void)
+{
+       struct localvar *lvp;
+       struct var *vp;
+
+       while ((lvp = localvars) != NULL) {
+               localvars = lvp->next;
+               vp = lvp->vp;
+               TRACE(("poplocalvar %s", vp ? vp->text : "-"));
+               if (vp == NULL) {       /* $- saved */
+                       memcpy(optlist, lvp->text, sizeof(optlist));
+                       free((char*)lvp->text);
+                       optschanged();
+               } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
+                       unsetvar(vp->text);
+               } else {
+                       if (vp->func)
+                               (*vp->func)(strchrnul(lvp->text, '=') + 1);
+                       if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
+                               free((char*)vp->text);
+                       vp->flags = lvp->flags;
+                       vp->text = lvp->text;
+               }
+               free(lvp);
+       }
+}
+
+static int
+evalfun(struct funcnode *func, int argc, char **argv, int flags)
+{
+       volatile struct shparam saveparam;
+       struct localvar *volatile savelocalvars;
+       struct jmploc *volatile savehandler;
+       struct jmploc jmploc;
+       int e;
+
+       saveparam = shellparam;
+       savelocalvars = localvars;
+       e = setjmp(jmploc.loc);
+       if (e) {
+               goto funcdone;
+       }
+       INT_OFF;
+       savehandler = exception_handler;
+       exception_handler = &jmploc;
+       localvars = NULL;
+       shellparam.malloc = 0;
+       func->count++;
+       funcnest++;
+       INT_ON;
+       shellparam.nparam = argc - 1;
+       shellparam.p = argv + 1;
+#if ENABLE_ASH_GETOPTS
+       shellparam.optind = 1;
+       shellparam.optoff = -1;
+#endif
+       evaltree(&func->n, flags & EV_TESTED);
+funcdone:
+       INT_OFF;
+       funcnest--;
+       freefunc(func);
+       poplocalvars();
+       localvars = savelocalvars;
+       freeparam(&shellparam);
+       shellparam = saveparam;
+       exception_handler = savehandler;
+       INT_ON;
+       evalskip &= ~SKIPFUNC;
+       return e;
+}
+
+#if ENABLE_ASH_CMDCMD
+static char **
+parse_command_args(char **argv, const char **path)
+{
+       char *cp, c;
+
+       for (;;) {
+               cp = *++argv;
+               if (!cp)
+                       return 0;
+               if (*cp++ != '-')
+                       break;
+               c = *cp++;
+               if (!c)
+                       break;
+               if (c == '-' && !*cp) {
+                       argv++;
+                       break;
+               }
+               do {
+                       switch (c) {
+                       case 'p':
+                               *path = defpath;
+                               break;
+                       default:
+                               /* run 'typecmd' for other options */
+                               return 0;
+                       }
+                       c = *cp++;
+               } while (c);
+       }
+       return argv;
+}
+#endif
+
+/*
+ * Make a variable a local variable.  When a variable is made local, it's
+ * value and flags are saved in a localvar structure.  The saved values
+ * will be restored when the shell function returns.  We handle the name
+ * "-" as a special case.
+ */
+static void
+mklocal(char *name)
+{
+       struct localvar *lvp;
+       struct var **vpp;
+       struct var *vp;
+
+       INT_OFF;
+       lvp = ckmalloc(sizeof(struct localvar));
+       if (LONE_DASH(name)) {
+               char *p;
+               p = ckmalloc(sizeof(optlist));
+               lvp->text = memcpy(p, optlist, sizeof(optlist));
+               vp = NULL;
+       } else {
+               char *eq;
+
+               vpp = hashvar(name);
+               vp = *findvar(vpp, name);
+               eq = strchr(name, '=');
+               if (vp == NULL) {
+                       if (eq)
+                               setvareq(name, VSTRFIXED);
+                       else
+                               setvar(name, NULL, VSTRFIXED);
+                       vp = *vpp;      /* the new variable */
+                       lvp->flags = VUNSET;
+               } else {
+                       lvp->text = vp->text;
+                       lvp->flags = vp->flags;
+                       vp->flags |= VSTRFIXED|VTEXTFIXED;
+                       if (eq)
+                               setvareq(name, 0);
+               }
+       }
+       lvp->vp = vp;
+       lvp->next = localvars;
+       localvars = lvp;
+       INT_ON;
+}
+
+/*
+ * The "local" command.
+ */
+static int
+localcmd(int argc, char **argv)
+{
+       char *name;
+
+       argv = argptr;
+       while ((name = *argv++) != NULL) {
+               mklocal(name);
+       }
+       return 0;
+}
+
+static int
+falsecmd(int argc, char **argv)
+{
+       return 1;
+}
+
+static int
+truecmd(int argc, char **argv)
+{
+       return 0;
+}
+
+static int
+execcmd(int argc, char **argv)
+{
+       if (argc > 1) {
+               iflag = 0;              /* exit on error */
+               mflag = 0;
+               optschanged();
+               shellexec(argv + 1, pathval(), 0);
+       }
+       return 0;
+}
+
+/*
+ * The return command.
+ */
+static int
+returncmd(int argc, char **argv)
+{
+       /*
+        * If called outside a function, do what ksh does;
+        * skip the rest of the file.
+        */
+       evalskip = funcnest ? SKIPFUNC : SKIPFILE;
+       return argv[1] ? number(argv[1]) : exitstatus;
+}
+
+/* Forward declarations for builtintab[] */
+static int breakcmd(int, char **);
+static int dotcmd(int, char **);
+static int evalcmd(int, char **);
+#if ENABLE_ASH_BUILTIN_ECHO
+static int echocmd(int, char **);
+#endif
+#if ENABLE_ASH_BUILTIN_TEST
+static int testcmd(int, char **);
+#endif
+static int exitcmd(int, char **);
+static int exportcmd(int, char **);
+#if ENABLE_ASH_GETOPTS
+static int getoptscmd(int, char **);
+#endif
+#if !ENABLE_FEATURE_SH_EXTRA_QUIET
+static int helpcmd(int argc, char **argv);
+#endif
+#if ENABLE_ASH_MATH_SUPPORT
+static int letcmd(int, char **);
+#endif
+static int readcmd(int, char **);
+static int setcmd(int, char **);
+static int shiftcmd(int, char **);
+static int timescmd(int, char **);
+static int trapcmd(int, char **);
+static int umaskcmd(int, char **);
+static int unsetcmd(int, char **);
+static int ulimitcmd(int, char **);
+
+#define BUILTIN_NOSPEC          "0"
+#define BUILTIN_SPECIAL         "1"
+#define BUILTIN_REGULAR         "2"
+#define BUILTIN_SPEC_REG        "3"
+#define BUILTIN_ASSIGN          "4"
+#define BUILTIN_SPEC_ASSG       "5"
+#define BUILTIN_REG_ASSG        "6"
+#define BUILTIN_SPEC_REG_ASSG   "7"
+
+/* make sure to keep these in proper order since it is searched via bsearch() */
+static const struct builtincmd builtintab[] = {
+       { BUILTIN_SPEC_REG      ".", dotcmd },
+       { BUILTIN_SPEC_REG      ":", truecmd },
+#if ENABLE_ASH_BUILTIN_TEST
+       { BUILTIN_REGULAR       "[", testcmd },
+       { BUILTIN_REGULAR       "[[", testcmd },
+#endif
+#if ENABLE_ASH_ALIAS
+       { BUILTIN_REG_ASSG      "alias", aliascmd },
+#endif
+#if JOBS
+       { BUILTIN_REGULAR       "bg", fg_bgcmd },
+#endif
+       { BUILTIN_SPEC_REG      "break", breakcmd },
+       { BUILTIN_REGULAR       "cd", cdcmd },
+       { BUILTIN_NOSPEC        "chdir", cdcmd },
+#if ENABLE_ASH_CMDCMD
+       { BUILTIN_REGULAR       "command", commandcmd },
+#endif
+       { BUILTIN_SPEC_REG      "continue", breakcmd },
+#if ENABLE_ASH_BUILTIN_ECHO
+       { BUILTIN_REGULAR       "echo", echocmd },
+#endif
+       { BUILTIN_SPEC_REG      "eval", evalcmd },
+       { BUILTIN_SPEC_REG      "exec", execcmd },
+       { BUILTIN_SPEC_REG      "exit", exitcmd },
+       { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
+       { BUILTIN_REGULAR       "false", falsecmd },
+#if JOBS
+       { BUILTIN_REGULAR       "fg", fg_bgcmd },
+#endif
+#if ENABLE_ASH_GETOPTS
+       { BUILTIN_REGULAR       "getopts", getoptscmd },
+#endif
+       { BUILTIN_NOSPEC        "hash", hashcmd },
+#if !ENABLE_FEATURE_SH_EXTRA_QUIET
+       { BUILTIN_NOSPEC        "help", helpcmd },
+#endif
+#if JOBS
+       { BUILTIN_REGULAR       "jobs", jobscmd },
+       { BUILTIN_REGULAR       "kill", killcmd },
+#endif
+#if ENABLE_ASH_MATH_SUPPORT
+       { BUILTIN_NOSPEC        "let", letcmd },
+#endif
+       { BUILTIN_ASSIGN        "local", localcmd },
+       { BUILTIN_NOSPEC        "pwd", pwdcmd },
+       { BUILTIN_REGULAR       "read", readcmd },
+       { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
+       { BUILTIN_SPEC_REG      "return", returncmd },
+       { BUILTIN_SPEC_REG      "set", setcmd },
+       { BUILTIN_SPEC_REG      "shift", shiftcmd },
+       { BUILTIN_SPEC_REG      "source", dotcmd },
+#if ENABLE_ASH_BUILTIN_TEST
+       { BUILTIN_REGULAR       "test", testcmd },
+#endif
+       { BUILTIN_SPEC_REG      "times", timescmd },
+       { BUILTIN_SPEC_REG      "trap", trapcmd },
+       { BUILTIN_REGULAR       "true", truecmd },
+       { BUILTIN_NOSPEC        "type", typecmd },
+       { BUILTIN_NOSPEC        "ulimit", ulimitcmd },
+       { BUILTIN_REGULAR       "umask", umaskcmd },
+#if ENABLE_ASH_ALIAS
+       { BUILTIN_REGULAR       "unalias", unaliascmd },
+#endif
+       { BUILTIN_SPEC_REG      "unset", unsetcmd },
+       { BUILTIN_REGULAR       "wait", waitcmd },
+};
+
+#define NUMBUILTINS (sizeof(builtintab) / sizeof(builtintab[0]))
+
+#define COMMANDCMD (builtintab + 5 + \
+       2 * ENABLE_ASH_BUILTIN_TEST + \
+       ENABLE_ASH_ALIAS + \
+       ENABLE_ASH_JOB_CONTROL)
+#define EXECCMD (builtintab + 7 + \
+       2 * ENABLE_ASH_BUILTIN_TEST + \
+       ENABLE_ASH_ALIAS + \
+       ENABLE_ASH_JOB_CONTROL + \
+       ENABLE_ASH_CMDCMD + \
+       ENABLE_ASH_BUILTIN_ECHO)
+
+/*
+ * Search the table of builtin commands.
+ */
+static struct builtincmd *
+find_builtin(const char *name)
+{
+       struct builtincmd *bp;
+
+       bp = bsearch(
+               name, builtintab, NUMBUILTINS, sizeof(builtintab[0]),
+               pstrcmp
+       );
+       return bp;
+}
+
+/*
+ * Execute a simple command.
+ */
+static int back_exitstatus; /* exit status of backquoted command */
+static int
+isassignment(const char *p)
+{
+       const char *q = endofname(p);
+       if (p == q)
+               return 0;
+       return *q == '=';
+}
+static int
+bltincmd(int argc, char **argv)
+{
+       /* Preserve exitstatus of a previous possible redirection
+        * as POSIX mandates */
+       return back_exitstatus;
+}
+static void
+evalcommand(union node *cmd, int flags)
+{
+       static const struct builtincmd bltin = {
+               "\0\0", bltincmd
+       };
+       struct stackmark smark;
+       union node *argp;
+       struct arglist arglist;
+       struct arglist varlist;
+       char **argv;
+       int argc;
+       const struct strlist *sp;
+       struct cmdentry cmdentry;
+       struct job *jp;
+       char *lastarg;
+       const char *path;
+       int spclbltin;
+       int cmd_is_exec;
+       int status;
+       char **nargv;
+       struct builtincmd *bcmd;
+       int pseudovarflag = 0;
+
+       /* First expand the arguments. */
+       TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
+       setstackmark(&smark);
+       back_exitstatus = 0;
+
+       cmdentry.cmdtype = CMDBUILTIN;
+       cmdentry.u.cmd = &bltin;
+       varlist.lastp = &varlist.list;
+       *varlist.lastp = NULL;
+       arglist.lastp = &arglist.list;
+       *arglist.lastp = NULL;
+
+       argc = 0;
+       if (cmd->ncmd.args) {
+               bcmd = find_builtin(cmd->ncmd.args->narg.text);
+               pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
+       }
+
+       for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
+               struct strlist **spp;
+
+               spp = arglist.lastp;
+               if (pseudovarflag && isassignment(argp->narg.text))
+                       expandarg(argp, &arglist, EXP_VARTILDE);
+               else
+                       expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
+
+               for (sp = *spp; sp; sp = sp->next)
+                       argc++;
+       }
+
+       argv = nargv = stalloc(sizeof(char *) * (argc + 1));
+       for (sp = arglist.list; sp; sp = sp->next) {
+               TRACE(("evalcommand arg: %s\n", sp->text));
+               *nargv++ = sp->text;
+       }
+       *nargv = NULL;
+
+       lastarg = NULL;
+       if (iflag && funcnest == 0 && argc > 0)
+               lastarg = nargv[-1];
+
+       preverrout_fd = 2;
+       expredir(cmd->ncmd.redirect);
+       status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
+
+       path = vpath.text;
+       for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
+               struct strlist **spp;
+               char *p;
+
+               spp = varlist.lastp;
+               expandarg(argp, &varlist, EXP_VARTILDE);
+
+               /*
+                * Modify the command lookup path, if a PATH= assignment
+                * is present
+                */
+               p = (*spp)->text;
+               if (varequal(p, path))
+                       path = p;
+       }
+
+       /* Print the command if xflag is set. */
+       if (xflag) {
+               int n;
+               const char *p = " %s";
+
+               p++;
+               dprintf(preverrout_fd, p, expandstr(ps4val()));
+
+               sp = varlist.list;
+               for (n = 0; n < 2; n++) {
+                       while (sp) {
+                               dprintf(preverrout_fd, p, sp->text);
+                               sp = sp->next;
+                               if (*p == '%') {
+                                       p--;
+                               }
+                       }
+                       sp = arglist.list;
+               }
+               full_write(preverrout_fd, "\n", 1);
+       }
+
+       cmd_is_exec = 0;
+       spclbltin = -1;
+
+       /* Now locate the command. */
+       if (argc) {
+               const char *oldpath;
+               int cmd_flag = DO_ERR;
+
+               path += 5;
+               oldpath = path;
+               for (;;) {
+                       find_command(argv[0], &cmdentry, cmd_flag, path);
+                       if (cmdentry.cmdtype == CMDUNKNOWN) {
+                               status = 127;
+                               flush_stderr();
+                               goto bail;
+                       }
+
+                       /* implement bltin and command here */
+                       if (cmdentry.cmdtype != CMDBUILTIN)
+                               break;
+                       if (spclbltin < 0)
+                               spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
+                       if (cmdentry.u.cmd == EXECCMD)
+                               cmd_is_exec++;
+#if ENABLE_ASH_CMDCMD
+                       if (cmdentry.u.cmd == COMMANDCMD) {
+                               path = oldpath;
+                               nargv = parse_command_args(argv, &path);
+                               if (!nargv)
+                                       break;
+                               argc -= nargv - argv;
+                               argv = nargv;
+                               cmd_flag |= DO_NOFUNC;
+                       } else
+#endif
+                               break;
+               }
+       }
+
+       if (status) {
+               /* We have a redirection error. */
+               if (spclbltin > 0)
+                       raise_exception(EXERROR);
+ bail:
+               exitstatus = status;
+               goto out;
+       }
+
+       /* Execute the command. */
+       switch (cmdentry.cmdtype) {
+       default:
+               /* Fork off a child process if necessary. */
+               if (!(flags & EV_EXIT) || trap[0]) {
+                       INT_OFF;
+                       jp = makejob(cmd, 1);
+                       if (forkshell(jp, cmd, FORK_FG) != 0) {
+                               exitstatus = waitforjob(jp);
+                               INT_ON;
+                               break;
+                       }
+                       FORCE_INT_ON;
+               }
+               listsetvar(varlist.list, VEXPORT|VSTACK);
+               shellexec(argv, path, cmdentry.u.index);
+               /* NOTREACHED */
+
+       case CMDBUILTIN:
+               cmdenviron = varlist.list;
+               if (cmdenviron) {
+                       struct strlist *list = cmdenviron;
+                       int i = VNOSET;
+                       if (spclbltin > 0 || argc == 0) {
+                               i = 0;
+                               if (cmd_is_exec && argc > 1)
+                                       i = VEXPORT;
+                       }
+                       listsetvar(list, i);
+               }
+               if (evalbltin(cmdentry.u.cmd, argc, argv)) {
+                       int exit_status;
+                       int i, j;
+
+                       i = exception;
+                       if (i == EXEXIT)
+                               goto raise;
+
+                       exit_status = 2;
+                       j = 0;
+                       if (i == EXINT)
+                               j = SIGINT;
+                       if (i == EXSIG)
+                               j = pendingsig;
+                       if (j)
+                               exit_status = j + 128;
+                       exitstatus = exit_status;
+
+                       if (i == EXINT || spclbltin > 0) {
+ raise:
+                               longjmp(exception_handler->loc, 1);
+                       }
+                       FORCE_INT_ON;
+               }
+               break;
+
+       case CMDFUNCTION:
+               listsetvar(varlist.list, 0);
+               if (evalfun(cmdentry.u.func, argc, argv, flags))
+                       goto raise;
+               break;
+       }
+
+ out:
+       popredir(cmd_is_exec);
+       if (lastarg)
+               /* dsl: I think this is intended to be used to support
+                * '_' in 'vi' command mode during line editing...
+                * However I implemented that within libedit itself.
+                */
+               setvar("_", lastarg, 0);
+       popstackmark(&smark);
+}
+
+static int
+evalbltin(const struct builtincmd *cmd, int argc, char **argv)
+{
+       char *volatile savecmdname;
+       struct jmploc *volatile savehandler;
+       struct jmploc jmploc;
+       int i;
+
+       savecmdname = commandname;
+       i = setjmp(jmploc.loc);
+       if (i)
+               goto cmddone;
+       savehandler = exception_handler;
+       exception_handler = &jmploc;
+       commandname = argv[0];
+       argptr = argv + 1;
+       optptr = NULL;                  /* initialize nextopt */
+       exitstatus = (*cmd->builtin)(argc, argv);
+       flush_stdout_stderr();
+ cmddone:
+       exitstatus |= ferror(stdout);
+       clearerr(stdout);
+       commandname = savecmdname;
+       exsig = 0;
+       exception_handler = savehandler;
+
+       return i;
+}
+
+static int
+goodname(const char *p)
+{
+       return !*endofname(p);
+}
+
+
+/*
+ * Search for a command.  This is called before we fork so that the
+ * location of the command will be available in the parent as well as
+ * the child.  The check for "goodname" is an overly conservative
+ * check that the name will not be subject to expansion.
+ */
+static void
+prehash(union node *n)
+{
+       struct cmdentry entry;
+
+       if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
+               find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
+}
+
+
+/* ============ Builtin commands
+ *
+ * Builtin commands whose functions are closely tied to evaluation
+ * are implemented here.
+ */
+
+/*
+ * Handle break and continue commands.  Break, continue, and return are
+ * all handled by setting the evalskip flag.  The evaluation routines
+ * above all check this flag, and if it is set they start skipping
+ * commands rather than executing them.  The variable skipcount is
+ * the number of loops to break/continue, or the number of function
+ * levels to return.  (The latter is always 1.)  It should probably
+ * be an error to break out of more loops than exist, but it isn't
+ * in the standard shell so we don't make it one here.
+ */
+static int
+breakcmd(int argc, char **argv)
+{
+       int n = argc > 1 ? number(argv[1]) : 1;
+
+       if (n <= 0)
+               ash_msg_and_raise_error(illnum, argv[1]);
+       if (n > loopnest)
+               n = loopnest;
+       if (n > 0) {
+               evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
+               skipcount = n;
+       }
+       return 0;
+}
+
+
+/* ============ input.c
+ *
+ * This implements the input routines used by the parser.
+ */
+
+#define EOF_NLEFT -99           /* value of parsenleft when EOF pushed back */
+
+enum {
+       INPUT_PUSH_FILE = 1,
+       INPUT_NOFILE_OK = 2,
+};
+
+/*
+ * NEOF is returned by parsecmd when it encounters an end of file.  It
+ * must be distinct from NULL, so we use the address of a variable that
+ * happens to be handy.
+ */
+static int plinno = 1;                  /* input line number */
+/* number of characters left in input buffer */
+static int parsenleft;                  /* copy of parsefile->nleft */
+static int parselleft;                  /* copy of parsefile->lleft */
+/* next character in input buffer */
+static char *parsenextc;                /* copy of parsefile->nextc */
+
+static int checkkwd;
+/* values of checkkwd variable */
+#define CHKALIAS        0x1
+#define CHKKWD          0x2
+#define CHKNL           0x4
+
+static void
+popstring(void)
+{
+       struct strpush *sp = parsefile->strpush;
+
+       INT_OFF;
+#if ENABLE_ASH_ALIAS
+       if (sp->ap) {
+               if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
+                       checkkwd |= CHKALIAS;
                }
-               p = "; fi";
-               goto dotail;
-       case NSUBSHELL:
-               cmdputs("(");
-               n = n->nredir.n;
-               p = ")";
-               goto dotail;
-       case NWHILE:
-               p = "while ";
-               goto until;
-       case NUNTIL:
-               p = "until ";
- until:
-               cmdputs(p);
-               cmdtxt(n->nbinary.ch1);
-               n = n->nbinary.ch2;
-               p = "; done";
- dodo:
-               cmdputs("; do ");
- dotail:
-               cmdtxt(n);
-               goto dotail2;
-       case NFOR:
-               cmdputs("for ");
-               cmdputs(n->nfor.var);
-               cmdputs(" in ");
-               cmdlist(n->nfor.args, 1);
-               n = n->nfor.body;
-               p = "; done";
-               goto dodo;
-       case NDEFUN:
-               cmdputs(n->narg.text);
-               p = "() { ... }";
-               goto dotail2;
-       case NCMD:
-               cmdlist(n->ncmd.args, 1);
-               cmdlist(n->ncmd.redirect, 0);
-               break;
-       case NARG:
-               p = n->narg.text;
- dotail2:
-               cmdputs(p);
-               break;
-       case NHERE:
-       case NXHERE:
-               p = "<<...";
-               goto dotail2;
-       case NCASE:
-               cmdputs("case ");
-               cmdputs(n->ncase.expr->narg.text);
-               cmdputs(" in ");
-               for (np = n->ncase.cases; np; np = np->nclist.next) {
-                       cmdtxt(np->nclist.pattern);
-                       cmdputs(") ");
-                       cmdtxt(np->nclist.body);
-                       cmdputs(";; ");
+               if (sp->string != sp->ap->val) {
+                       free(sp->string);
                }
-               p = "esac";
-               goto dotail2;
-       case NTO:
-               p = ">";
-               goto redir;
-       case NCLOBBER:
-               p = ">|";
-               goto redir;
-       case NAPPEND:
-               p = ">>";
-               goto redir;
-       case NTOFD:
-               p = ">&";
-               goto redir;
-       case NFROM:
-               p = "<";
-               goto redir;
-       case NFROMFD:
-               p = "<&";
-               goto redir;
-       case NFROMTO:
-               p = "<>";
- redir:
-               s[0] = n->nfile.fd + '0';
-               s[1] = '\0';
-               cmdputs(s);
-               cmdputs(p);
-               if (n->type == NTOFD || n->type == NFROMFD) {
-                       s[0] = n->ndup.dupfd + '0';
-                       p = s;
-                       goto dotail2;
+               sp->ap->flag &= ~ALIASINUSE;
+               if (sp->ap->flag & ALIASDEAD) {
+                       unalias(sp->ap->name);
+               }
+       }
+#endif
+       parsenextc = sp->prevstring;
+       parsenleft = sp->prevnleft;
+/*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
+       parsefile->strpush = sp->prev;
+       if (sp != &(parsefile->basestrpush))
+               free(sp);
+       INT_ON;
+}
+
+static int
+preadfd(void)
+{
+       int nr;
+       char *buf =  parsefile->buf;
+       parsenextc = buf;
+
+ retry:
+#if ENABLE_FEATURE_EDITING
+       if (!iflag || parsefile->fd)
+               nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
+       else {
+#if ENABLE_FEATURE_TAB_COMPLETION
+               line_input_state->path_lookup = pathval();
+#endif
+               nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
+               if (nr == 0) {
+                       /* Ctrl+C pressed */
+                       if (trap[SIGINT]) {
+                               buf[0] = '\n';
+                               buf[1] = '\0';
+                               raise(SIGINT);
+                               return 1;
+                       }
+                       goto retry;
+               }
+               if (nr < 0 && errno == 0) {
+                       /* Ctrl+D presend */
+                       nr = 0;
+               }
+       }
+#else
+       nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
+#endif
+
+       if (nr < 0) {
+               if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
+                       int flags = fcntl(0, F_GETFL, 0);
+                       if (flags >= 0 && flags & O_NONBLOCK) {
+                               flags &=~ O_NONBLOCK;
+                               if (fcntl(0, F_SETFL, flags) >= 0) {
+                                       out2str("sh: turning off NDELAY mode\n");
+                                       goto retry;
+                               }
+                       }
+               }
+       }
+       return nr;
+}
+
+/*
+ * Refill the input buffer and return the next input character:
+ *
+ * 1) If a string was pushed back on the input, pop it;
+ * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
+ *    from a string so we can't refill the buffer, return EOF.
+ * 3) If the is more stuff in this buffer, use it else call read to fill it.
+ * 4) Process input up to the next newline, deleting nul characters.
+ */
+static int
+preadbuffer(void)
+{
+       char *q;
+       int more;
+       char savec;
+
+       while (parsefile->strpush) {
+#if ENABLE_ASH_ALIAS
+               if (parsenleft == -1 && parsefile->strpush->ap &&
+                       parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
+                       return PEOA;
+               }
+#endif
+               popstring();
+               if (--parsenleft >= 0)
+                       return signed_char2int(*parsenextc++);
+       }
+       if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
+               return PEOF;
+       flush_stdout_stderr();
+
+       more = parselleft;
+       if (more <= 0) {
+ again:
+               more = preadfd();
+               if (more <= 0) {
+                       parselleft = parsenleft = EOF_NLEFT;
+                       return PEOF;
+               }
+       }
+
+       q = parsenextc;
+
+       /* delete nul characters */
+       for (;;) {
+               int c;
+
+               more--;
+               c = *q;
+
+               if (!c)
+                       memmove(q, q + 1, more);
+               else {
+                       q++;
+                       if (c == '\n') {
+                               parsenleft = q - parsenextc - 1;
+                               break;
+                       }
+               }
+
+               if (more <= 0) {
+                       parsenleft = q - parsenextc - 1;
+                       if (parsenleft < 0)
+                               goto again;
+                       break;
                }
-               n = n->nfile.fname;
-               goto donode;
        }
+       parselleft = more;
+
+       savec = *q;
+       *q = '\0';
+
+       if (vflag) {
+               out2str(parsenextc);
+       }
+
+       *q = savec;
+
+       return signed_char2int(*parsenextc++);
+}
+
+#define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
+static int
+pgetc(void)
+{
+       return pgetc_as_macro();
+}
+
+#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
+#define pgetc_macro() pgetc()
+#else
+#define pgetc_macro() pgetc_as_macro()
+#endif
+
+/*
+ * Same as pgetc(), but ignores PEOA.
+ */
+#if ENABLE_ASH_ALIAS
+static int
+pgetc2(void)
+{
+       int c;
+
+       do {
+               c = pgetc_macro();
+       } while (c == PEOA);
+       return c;
+}
+#else
+static int
+pgetc2(void)
+{
+       return pgetc_macro();
 }
+#endif
 
+/*
+ * Read a line from the script.
+ */
 static char *
-commandtext(union node *n)
+pfgets(char *line, int len)
 {
-       char *name;
+       char *p = line;
+       int nleft = len;
+       int c;
 
-       STARTSTACKSTR(cmdnextc);
-       cmdtxt(n);
-       name = stackblock();
-       TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
-                       name, cmdnextc, cmdnextc));
-       return ckstrdup(name);
+       while (--nleft > 0) {
+               c = pgetc2();
+               if (c == PEOF) {
+                       if (p == line)
+                               return NULL;
+                       break;
+               }
+               *p++ = c;
+               if (c == '\n')
+                       break;
+       }
+       *p = '\0';
+       return line;
 }
-#endif /* JOBS */
 
 /*
- * Fork off a subshell.  If we are doing job control, give the subshell its
- * own process group.  Jp is a job structure that the job is to be added to.
- * N is the command that will be evaluated by the child.  Both jp and n may
- * be NULL.  The mode parameter can be one of the following:
- *      FORK_FG - Fork off a foreground process.
- *      FORK_BG - Fork off a background process.
- *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
- *                   process group even if job control is on.
- *
- * When job control is turned off, background processes have their standard
- * input redirected to /dev/null (except for the second and later processes
- * in a pipeline).
- *
- * Called with interrupts off.
+ * Undo the last call to pgetc.  Only one character may be pushed back.
+ * PEOF may be pushed back.
  */
+static void
+pungetc(void)
+{
+       parsenleft++;
+       parsenextc--;
+}
+
 /*
- * Clear traps on a fork.
+ * Push a string back onto the input at this current parsefile level.
+ * We handle aliases this way.
  */
 static void
-clear_traps(void)
+pushstring(char *s, void *ap)
 {
-       char **tp;
+       struct strpush *sp;
+       size_t len;
 
-       for (tp = trap; tp < &trap[NSIG]; tp++) {
-               if (*tp && **tp) {      /* trap not NULL or SIG_IGN */
-                       INT_OFF;
-                       free(*tp);
-                       *tp = NULL;
-                       if (tp != &trap[0])
-                               setsignal(tp - trap);
-                       INT_ON;
-               }
+       len = strlen(s);
+       INT_OFF;
+/*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
+       if (parsefile->strpush) {
+               sp = ckmalloc(sizeof(struct strpush));
+               sp->prev = parsefile->strpush;
+               parsefile->strpush = sp;
+       } else
+               sp = parsefile->strpush = &(parsefile->basestrpush);
+       sp->prevstring = parsenextc;
+       sp->prevnleft = parsenleft;
+#if ENABLE_ASH_ALIAS
+       sp->ap = (struct alias *)ap;
+       if (ap) {
+               ((struct alias *)ap)->flag |= ALIASINUSE;
+               sp->string = s;
        }
+#endif
+       parsenextc = s;
+       parsenleft = len;
+       INT_ON;
 }
+
+/*
+ * To handle the "." command, a stack of input files is used.  Pushfile
+ * adds a new entry to the stack and popfile restores the previous level.
+ */
 static void
-forkchild(struct job *jp, union node *n, int mode)
+pushfile(void)
 {
-       int oldlvl;
+       struct parsefile *pf;
 
-       TRACE(("Child shell %d\n", getpid()));
-       oldlvl = shlvl;
-       shlvl++;
+       parsefile->nleft = parsenleft;
+       parsefile->lleft = parselleft;
+       parsefile->nextc = parsenextc;
+       parsefile->linno = plinno;
+       pf = ckmalloc(sizeof(*pf));
+       pf->prev = parsefile;
+       pf->fd = -1;
+       pf->strpush = NULL;
+       pf->basestrpush.prev = NULL;
+       parsefile = pf;
+}
 
-       closescript();
-       clear_traps();
-#if JOBS
-       /* do job control only in root shell */
-       jobctl = 0;
-       if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
-               pid_t pgrp;
+static void
+popfile(void)
+{
+       struct parsefile *pf = parsefile;
 
-               if (jp->nprocs == 0)
-                       pgrp = getpid();
-               else
-                       pgrp = jp->ps[0].pid;
-               /* This can fail because we are doing it in the parent also */
-               (void)setpgid(0, pgrp);
-               if (mode == FORK_FG)
-                       xtcsetpgrp(ttyfd, pgrp);
-               setsignal(SIGTSTP);
-               setsignal(SIGTTOU);
-       } else
-#endif
-       if (mode == FORK_BG) {
-               ignoresig(SIGINT);
-               ignoresig(SIGQUIT);
-               if (jp->nprocs == 0) {
-                       close(0);
-                       if (open(bb_dev_null, O_RDONLY) != 0)
-                               ash_msg_and_raise_error("Can't open %s", bb_dev_null);
-               }
-       }
-       if (!oldlvl && iflag) {
-               setsignal(SIGINT);
-               setsignal(SIGQUIT);
-               setsignal(SIGTERM);
-       }
-       for (jp = curjob; jp; jp = jp->prev_job)
-               freejob(jp);
-       jobless = 0;
+       INT_OFF;
+       if (pf->fd >= 0)
+               close(pf->fd);
+       if (pf->buf)
+               free(pf->buf);
+       while (pf->strpush)
+               popstring();
+       parsefile = pf->prev;
+       free(pf);
+       parsenleft = parsefile->nleft;
+       parselleft = parsefile->lleft;
+       parsenextc = parsefile->nextc;
+       plinno = parsefile->linno;
+       INT_ON;
 }
 
+/*
+ * Return to top level.
+ */
 static void
-forkparent(struct job *jp, union node *n, int mode, pid_t pid)
+popallfiles(void)
 {
-       TRACE(("In parent shell: child = %d\n", pid));
-       if (!jp) {
-               while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
-               jobless++;
-               return;
-       }
-#if JOBS
-       if (mode != FORK_NOJOB && jp->jobctl) {
-               int pgrp;
+       while (parsefile != &basepf)
+               popfile();
+}
 
-               if (jp->nprocs == 0)
-                       pgrp = pid;
-               else
-                       pgrp = jp->ps[0].pid;
-               /* This can fail because we are doing it in the child also */
-               setpgid(pid, pgrp);
-       }
-#endif
-       if (mode == FORK_BG) {
-               backgndpid = pid;               /* set $! */
-               set_curjob(jp, CUR_RUNNING);
-       }
-       if (jp) {
-               struct procstat *ps = &jp->ps[jp->nprocs++];
-               ps->pid = pid;
-               ps->status = -1;
-               ps->cmd = nullstr;
-#if JOBS
-               if (jobctl && n)
-                       ps->cmd = commandtext(n);
-#endif
+/*
+ * Close the file(s) that the shell is reading commands from.  Called
+ * after a fork is done.
+ */
+static void
+closescript(void)
+{
+       popallfiles();
+       if (parsefile->fd > 0) {
+               close(parsefile->fd);
+               parsefile->fd = 0;
        }
 }
 
-static int
-forkshell(struct job *jp, union node *n, int mode)
+/*
+ * Like setinputfile, but takes an open file descriptor.  Call this with
+ * interrupts off.
+ */
+static void
+setinputfd(int fd, int push)
 {
-       int pid;
-
-       TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
-       pid = fork();
-       if (pid < 0) {
-               TRACE(("Fork failed, errno=%d", errno));
-               if (jp)
-                       freejob(jp);
-               ash_msg_and_raise_error("Cannot fork");
+       fcntl(fd, F_SETFD, FD_CLOEXEC);
+       if (push) {
+               pushfile();
+               parsefile->buf = 0;
        }
-       if (pid == 0)
-               forkchild(jp, n, mode);
-       else
-               forkparent(jp, n, mode, pid);
-       return pid;
+       parsefile->fd = fd;
+       if (parsefile->buf == NULL)
+               parsefile->buf = ckmalloc(IBUFSIZ);
+       parselleft = parsenleft = 0;
+       plinno = 1;
 }
 
 /*
- * Wait for job to finish.
- *
- * Under job control we have the problem that while a child process is
- * running interrupts generated by the user are sent to the child but not
- * to the shell.  This means that an infinite loop started by an inter-
- * active user may be hard to kill.  With job control turned off, an
- * interactive user may place an interactive program inside a loop.  If
- * the interactive program catches interrupts, the user doesn't want
- * these interrupts to also abort the loop.  The approach we take here
- * is to have the shell ignore interrupt signals while waiting for a
- * foreground process to terminate, and then send itself an interrupt
- * signal if the child process was terminated by an interrupt signal.
- * Unfortunately, some programs want to do a bit of cleanup and then
- * exit on interrupt; unless these processes terminate themselves by
- * sending a signal to themselves (instead of calling exit) they will
- * confuse this approach.
- *
- * Called with interrupts off.
+ * Set the input to take input from a file.  If push is set, push the
+ * old input onto the stack first.
  */
 static int
-waitforjob(struct job *jp)
+setinputfile(const char *fname, int flags)
 {
-       int st;
+       int fd;
+       int fd2;
 
-       TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
-       while (jp->state == JOBRUNNING) {
-               dowait(DOWAIT_BLOCK, jp);
+       INT_OFF;
+       fd = open(fname, O_RDONLY);
+       if (fd < 0) {
+               if (flags & INPUT_NOFILE_OK)
+                       goto out;
+               ash_msg_and_raise_error("can't open %s", fname);
        }
-       st = getstatus(jp);
-#if JOBS
-       if (jp->jobctl) {
-               xtcsetpgrp(ttyfd, rootpid);
-               /*
-                * This is truly gross.
-                * If we're doing job control, then we did a TIOCSPGRP which
-                * caused us (the shell) to no longer be in the controlling
-                * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
-                * intuit from the subprocess exit status whether a SIGINT
-                * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
-                */
-               if (jp->sigint)
-                       raise(SIGINT);
+       if (fd < 10) {
+               fd2 = copyfd(fd, 10);
+               close(fd);
+               if (fd2 < 0)
+                       ash_msg_and_raise_error("out of file descriptors");
+               fd = fd2;
        }
-       if (jp->state == JOBDONE)
-#endif
-               freejob(jp);
-       return st;
+       setinputfd(fd, flags & INPUT_PUSH_FILE);
+ out:
+       INT_ON;
+       return fd;
 }
 
 /*
- * return 1 if there are stopped jobs, otherwise 0
+ * Like setinputfile, but takes input from a string.
  */
-static int
-stoppedjobs(void)
+static void
+setinputstring(char *string)
 {
-       struct job *jp;
-       int retval;
-
-       retval = 0;
-       if (job_warning)
-               goto out;
-       jp = curjob;
-       if (jp && jp->state == JOBSTOPPED) {
-               out2str("You have stopped jobs.\n");
-               job_warning = 2;
-               retval++;
-       }
- out:
-       return retval;
+       INT_OFF;
+       pushfile();
+       parsenextc = string;
+       parsenleft = strlen(string);
+       parsefile->buf = NULL;
+       plinno = 1;
+       INT_ON;
 }
 
 
@@ -8818,6 +8901,7 @@ stoppedjobs(void)
  *
  * Routines to check for mail.
  */
+
 #if ENABLE_ASH_MAIL
 
 #define MAXMBOXES 10
@@ -8878,94 +8962,42 @@ changemail(const char *val)
 {
        mail_var_path_changed++;
 }
+
 #endif /* ASH_MAIL */
 
 
 /* ============ ??? */
 
 /*
- * Take commands from a file.  To be compatible we should do a path
- * search for the file, which is necessary to find sub-commands.
- */
-static char *
-find_dot_file(char *name)
-{
-       char *fullname;
-       const char *path = pathval();
-       struct stat statb;
-
-       /* don't try this for absolute or relative paths */
-       if (strchr(name, '/'))
-               return name;
-
-       while ((fullname = padvance(&path, name)) != NULL) {
-               if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
-                       /*
-                        * Don't bother freeing here, since it will
-                        * be freed by the caller.
-                        */
-                       return fullname;
-               }
-               stunalloc(fullname);
-       }
-
-       /* not found in the PATH */
-       ash_msg_and_raise_error("%s: not found", name);
-       /* NOTREACHED */
-}
-
-/*
- * Controls whether the shell is interactive or not.
+ * Set the shell parameters.
  */
 static void
-setinteractive(int on)
+setparam(char **argv)
 {
-       static int is_interactive;
-
-       if (++on == is_interactive)
-               return;
-       is_interactive = on;
-       setsignal(SIGINT);
-       setsignal(SIGQUIT);
-       setsignal(SIGTERM);
-#if !ENABLE_FEATURE_SH_EXTRA_QUIET
-       if (is_interactive > 1) {
-               /* Looks like they want an interactive shell */
-               static smallint do_banner;
+       char **newparam;
+       char **ap;
+       int nparam;
 
-               if (!do_banner) {
-                       out1fmt(
-                               "\n\n"
-                               "%s Built-in shell (ash)\n"
-                               "Enter 'help' for a list of built-in commands."
-                               "\n\n",
-                               BB_BANNER);
-                       do_banner = 1;
-               }
+       for (nparam = 0; argv[nparam]; nparam++);
+       ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
+       while (*argv) {
+               *ap++ = ckstrdup(*argv++);
        }
+       *ap = NULL;
+       freeparam(&shellparam);
+       shellparam.malloc = 1;
+       shellparam.nparam = nparam;
+       shellparam.p = newparam;
+#if ENABLE_ASH_GETOPTS
+       shellparam.optind = 1;
+       shellparam.optoff = -1;
 #endif
 }
 
-#if ENABLE_FEATURE_EDITING_VI
-#define setvimode(on) do { \
-       if (on) line_input_state->flags |= VI_MODE; \
-       else line_input_state->flags &= ~VI_MODE; \
-} while (0)
-#else
-#define setvimode(on) viflag = 0   /* forcibly keep the option off */
-#endif
-
-static void
-optschanged(void)
-{
-#if DEBUG
-       opentrace();
-#endif
-       setinteractive(iflag);
-       setjobctl(mflag);
-       setvimode(viflag);
-}
-
+/*
+ * Process shell options.  The global variable argptr contains a pointer
+ * to the argument list; we advance it past the options.
+ */
 static void
 minus_o(char *name, int val)
 {
@@ -8978,14 +9010,13 @@ minus_o(char *name, int val)
                                return;
                        }
                }
-               ash_msg_and_raise_error("Illegal option -o %s", name);
+               ash_msg_and_raise_error("illegal option -o %s", name);
        }
        out1str("Current option settings\n");
        for (i = 0; i < NOPTS; i++)
                out1fmt("%-16s%s\n", optnames(i),
                                optlist[i] ? "on" : "off");
 }
-
 static void
 setoption(int flag, int val)
 {
@@ -8997,14 +9028,9 @@ setoption(int flag, int val)
                        return;
                }
        }
-       ash_msg_and_raise_error("Illegal option -%c", flag);
+       ash_msg_and_raise_error("illegal option -%c", flag);
        /* NOTREACHED */
 }
-
-/*
- * Process shell options.  The global variable argptr contains a pointer
- * to the argument list; we advance it past the options.
- */
 static void
 options(int cmdline)
 {
@@ -9054,47 +9080,6 @@ options(int cmdline)
        }
 }
 
-/*
- * Set the shell parameters.
- */
-static void
-setparam(char **argv)
-{
-       char **newparam;
-       char **ap;
-       int nparam;
-
-       for (nparam = 0; argv[nparam]; nparam++);
-       ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
-       while (*argv) {
-               *ap++ = ckstrdup(*argv++);
-       }
-       *ap = NULL;
-       freeparam(&shellparam);
-       shellparam.malloc = 1;
-       shellparam.nparam = nparam;
-       shellparam.p = newparam;
-#if ENABLE_ASH_GETOPTS
-       shellparam.optind = 1;
-       shellparam.optoff = -1;
-#endif
-}
-
-/*
- * Free the list of positional parameters.
- */
-static void
-freeparam(volatile struct shparam *param)
-{
-       char **ap;
-
-       if (param->malloc) {
-               for (ap = param->p; *ap; ap++)
-                       free(*ap);
-               free(param->p);
-       }
-}
-
 /*
  * The shift builtin command.
  */
@@ -9141,7 +9126,7 @@ showvars(const char *sep_prefix, int on, int off)
        ep = listvars(on, off, &epend);
        qsort(ep, epend - ep, sizeof(char *), vpcmp);
 
-       sep = *sep_prefix ? spcstr : sep_prefix;
+       sep = *sep_prefix ? " " : sep_prefix;
 
        for (; ep < epend; ep++) {
                const char *p;
@@ -9159,36 +9144,20 @@ showvars(const char *sep_prefix, int on, int off)
 /*
  * The set command builtin.
  */
-static int
-setcmd(int argc, char **argv)
-{
-       if (argc == 1)
-               return showvars(nullstr, 0, VUNSET);
-       INT_OFF;
-       options(0);
-       optschanged();
-       if (*argptr != NULL) {
-               setparam(argptr);
-       }
-       INT_ON;
-       return 0;
-}
-
-#if ENABLE_LOCALE_SUPPORT
-static void
-change_lc_all(const char *value)
-{
-       if (value && *value != '\0')
-               setlocale(LC_ALL, value);
-}
-
-static void
-change_lc_ctype(const char *value)
+static int
+setcmd(int argc, char **argv)
 {
-       if (value && *value != '\0')
-               setlocale(LC_CTYPE, value);
+       if (argc == 1)
+               return showvars(nullstr, 0, VUNSET);
+       INT_OFF;
+       options(0);
+       optschanged();
+       if (*argptr != NULL) {
+               setparam(argptr);
+       }
+       INT_ON;
+       return 0;
 }
-#endif
 
 #if ENABLE_ASH_RANDOM_SUPPORT
 /* Roughly copied from bash.. */
@@ -9312,7 +9281,7 @@ getoptscmd(int argc, char **argv)
        char **optbase;
 
        if (argc < 3)
-               ash_msg_and_raise_error("Usage: getopts optstring var [arg]");
+               ash_msg_and_raise_error("usage: getopts optstring var [arg]");
        if (argc == 3) {
                optbase = shellparam.p;
                if (shellparam.optind > shellparam.nparam + 1) {
@@ -9335,11 +9304,21 @@ getoptscmd(int argc, char **argv)
 
 /* ============ Shell parser */
 
+static int tokpushback;                /* last token pushed back */
+#define NEOF ((union node *)&tokpushback)
+static int parsebackquote;             /* nonzero if we are inside backquotes */
+static int lasttoken;                  /* last token read */
+static char *wordtext;                 /* text of last word returned by readtoken */
+static struct nodelist *backquotelist;
+static union node *redirnode;
+static struct heredoc *heredoc;
+static int quoteflag;                  /* set if (part of) last token was quoted */
+
 static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
 static void
 raise_error_syntax(const char *msg)
 {
-       ash_msg_and_raise_error("Syntax error: %s", msg);
+       ash_msg_and_raise_error("syntax error: %s", msg);
        /* NOTREACHED */
 }
 
@@ -9887,6 +9866,8 @@ parse_command(void)
  * will run code that appears at the end of readtoken1.
  */
 
+static int parsebackquote;             /* nonzero if we are inside backquotes */
+
 #define CHECKEND()      {goto checkend; checkend_return:;}
 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
 #define PARSESUB()      {goto parsesub; parsesub_return:;}
@@ -10077,7 +10058,7 @@ readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
        if (syntax == ARISYNTAX)
                raise_error_syntax("Missing '))'");
 #endif
-       if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
+       if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
                raise_error_syntax("Unterminated quoted string");
        if (varnest != 0) {
                startlinno = plinno;
@@ -10106,7 +10087,6 @@ readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
        return lasttoken;
 /* end of readtoken routine */
 
-
 /*
  * Check to see whether we are at the end of the here document.  When this
  * is called, c is set to the first character of the next input line.  If
@@ -10143,7 +10123,6 @@ checkend: {
        goto checkend_return;
 }
 
-
 /*
  * Parse a redirection operator.  The variable "out" points to a string
  * specifying the fd to be redirected.  The variable "c" contains the
@@ -10208,11 +10187,16 @@ parseredir: {
        goto parseredir_return;
 }
 
-
 /*
  * Parse a substitution.  At this point, we have read the dollar sign
  * and nothing else.
  */
+
+/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
+ * (assuming ascii char codes, as the original implementation did) */
+#define is_special(c) \
+       ((((unsigned int)c) - 33 < 32) \
+                       && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
 parsesub: {
        int subtype;
        int typeloc;
@@ -10314,7 +10298,6 @@ parsesub: {
        goto parsesub_return;
 }
 
-
 /*
  * Called to parse command substitutions.  Newstyle is set if the command
  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
@@ -10789,8 +10772,7 @@ parseheredoc(void)
 
 
 /*
- * called by editline -- any expansions to the prompt
- *    should be added here.
+ * called by editline -- any expansions to the prompt should be added here.
  */
 #if ENABLE_ASH_EXPAND_PRMT
 static const char *
@@ -10813,7 +10795,6 @@ expandstr(const char *ps)
 }
 #endif
 
-
 /*
  * Execute a command or commands contained in a string.
  */
@@ -10867,487 +10848,359 @@ evalcmd(int argc, char **argv)
                        STPUTC('\0', concat);
                        p = grabstackstr(concat);
                }
-               evalstring(p, ~SKIPEVAL);
-
-       }
-       return exitstatus;
-}
-
-/*
- * Read and execute commands.  "Top" is nonzero for the top level command
- * loop; it turns on prompting if the shell is interactive.
- */
-static int
-cmdloop(int top)
-{
-       union node *n;
-       struct stackmark smark;
-       int inter;
-       int numeof = 0;
-
-       TRACE(("cmdloop(%d) called\n", top));
-       for (;;) {
-               int skip;
-
-               setstackmark(&smark);
-#if JOBS
-               if (jobctl)
-                       showjobs(stderr, SHOW_CHANGED);
-#endif
-               inter = 0;
-               if (iflag && top) {
-                       inter++;
-#if ENABLE_ASH_MAIL
-                       chkmail();
-#endif
-               }
-               n = parsecmd(inter);
-               /* showtree(n); DEBUG */
-               if (n == NEOF) {
-                       if (!top || numeof >= 50)
-                               break;
-                       if (!stoppedjobs()) {
-                               if (!Iflag)
-                                       break;
-                               out2str("\nUse \"exit\" to leave shell.\n");
-                       }
-                       numeof++;
-               } else if (nflag == 0) {
-                       job_warning = (job_warning == 2) ? 1 : 0;
-                       numeof = 0;
-                       evaltree(n, 0);
-               }
-               popstackmark(&smark);
-               skip = evalskip;
-
-               if (skip) {
-                       evalskip = 0;
-                       return skip & SKIPEVAL;
-               }
-       }
-       return 0;
-}
-
-static int
-dotcmd(int argc, char **argv)
-{
-       struct strlist *sp;
-       volatile struct shparam saveparam;
-       int status = 0;
-
-       for (sp = cmdenviron; sp; sp = sp->next)
-               setvareq(xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
-
-       if (argc >= 2) {        /* That's what SVR2 does */
-               char *fullname;
-
-               fullname = find_dot_file(argv[1]);
-
-               if (argc > 2) {
-                       saveparam = shellparam;
-                       shellparam.malloc = 0;
-                       shellparam.nparam = argc - 2;
-                       shellparam.p = argv + 2;
-               };
-
-               setinputfile(fullname, INPUT_PUSH_FILE);
-               commandname = fullname;
-               cmdloop(0);
-               popfile();
-
-               if (argc > 2) {
-                       freeparam(&shellparam);
-                       shellparam = saveparam;
-               };
-               status = exitstatus;
-       }
-       return status;
-}
-
-static int
-exitcmd(int argc, char **argv)
-{
-       if (stoppedjobs())
-               return 0;
-       if (argc > 1)
-               exitstatus = number(argv[1]);
-       raise_exception(EXEXIT);
-       /* NOTREACHED */
-}
-
-#if ENABLE_ASH_BUILTIN_ECHO
-static int
-echocmd(int argc, char **argv)
-{
-       return bb_echo(argv);
-}
-#endif
-
-#if ENABLE_ASH_BUILTIN_TEST
-static int
-testcmd(int argc, char **argv)
-{
-       return bb_test(argc, argv);
-}
-#endif
-
-/*
- * Read a file containing shell functions.
- */
-static void
-readcmdfile(char *name)
-{
-       setinputfile(name, INPUT_PUSH_FILE);
-       cmdloop(0);
-       popfile();
-}
-
-
-/* ============ redir.c */
-
-/*
- * Code for dealing with input/output redirection.
- */
-
-#define EMPTY -2                /* marks an unused slot in redirtab */
-#ifndef PIPE_BUF
-# define PIPESIZE 4096          /* amount of buffering in a pipe */
-#else
-# define PIPESIZE PIPE_BUF
-#endif
-
-/*
- * Open a file in noclobber mode.
- * The code was copied from bash.
- */
-static int
-noclobberopen(const char *fname)
-{
-       int r, fd;
-       struct stat finfo, finfo2;
-
-       /*
-        * If the file exists and is a regular file, return an error
-        * immediately.
-        */
-       r = stat(fname, &finfo);
-       if (r == 0 && S_ISREG(finfo.st_mode)) {
-               errno = EEXIST;
-               return -1;
-       }
-
-       /*
-        * If the file was not present (r != 0), make sure we open it
-        * exclusively so that if it is created before we open it, our open
-        * will fail.  Make sure that we do not truncate an existing file.
-        * Note that we don't turn on O_EXCL unless the stat failed -- if the
-        * file was not a regular file, we leave O_EXCL off.
-        */
-       if (r != 0)
-               return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
-       fd = open(fname, O_WRONLY|O_CREAT, 0666);
-
-       /* If the open failed, return the file descriptor right away. */
-       if (fd < 0)
-               return fd;
-
-       /*
-        * OK, the open succeeded, but the file may have been changed from a
-        * non-regular file to a regular file between the stat and the open.
-        * We are assuming that the O_EXCL open handles the case where FILENAME
-        * did not exist and is symlinked to an existing file between the stat
-        * and open.
-        */
-
-       /*
-        * If we can open it and fstat the file descriptor, and neither check
-        * revealed that it was a regular file, and the file has not been
-        * replaced, return the file descriptor.
-        */
-       if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
-        && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
-               return fd;
-
-       /* The file has been replaced.  badness. */
-       close(fd);
-       errno = EEXIST;
-       return -1;
-}
-
-/*
- * Handle here documents.  Normally we fork off a process to write the
- * data to a pipe.  If the document is short, we can stuff the data in
- * the pipe without forking.
- */
-static int
-openhere(union node *redir)
-{
-       int pip[2];
-       size_t len = 0;
-
-       if (pipe(pip) < 0)
-               ash_msg_and_raise_error("Pipe call failed");
-       if (redir->type == NHERE) {
-               len = strlen(redir->nhere.doc->narg.text);
-               if (len <= PIPESIZE) {
-                       full_write(pip[1], redir->nhere.doc->narg.text, len);
-                       goto out;
-               }
-       }
-       if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
-               close(pip[0]);
-               signal(SIGINT, SIG_IGN);
-               signal(SIGQUIT, SIG_IGN);
-               signal(SIGHUP, SIG_IGN);
-#ifdef SIGTSTP
-               signal(SIGTSTP, SIG_IGN);
-#endif
-               signal(SIGPIPE, SIG_DFL);
-               if (redir->type == NHERE)
-                       full_write(pip[1], redir->nhere.doc->narg.text, len);
-               else
-                       expandhere(redir->nhere.doc, pip[1]);
-               _exit(0);
+               evalstring(p, ~SKIPEVAL);
+
        }
- out:
-       close(pip[1]);
-       return pip[0];
+       return exitstatus;
 }
 
+/*
+ * Read and execute commands.  "Top" is nonzero for the top level command
+ * loop; it turns on prompting if the shell is interactive.
+ */
 static int
-openredirect(union node *redir)
+cmdloop(int top)
 {
-       char *fname;
-       int f;
+       union node *n;
+       struct stackmark smark;
+       int inter;
+       int numeof = 0;
 
-       switch (redir->nfile.type) {
-       case NFROM:
-               fname = redir->nfile.expfname;
-               f = open(fname, O_RDONLY);
-               if (f < 0)
-                       goto eopen;
-               break;
-       case NFROMTO:
-               fname = redir->nfile.expfname;
-               f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
-               if (f < 0)
-                       goto ecreate;
-               break;
-       case NTO:
-               /* Take care of noclobber mode. */
-               if (Cflag) {
-                       fname = redir->nfile.expfname;
-                       f = noclobberopen(fname);
-                       if (f < 0)
-                               goto ecreate;
-                       break;
-               }
-               /* FALLTHROUGH */
-       case NCLOBBER:
-               fname = redir->nfile.expfname;
-               f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
-               if (f < 0)
-                       goto ecreate;
-               break;
-       case NAPPEND:
-               fname = redir->nfile.expfname;
-               f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
-               if (f < 0)
-                       goto ecreate;
-               break;
-       default:
-#if DEBUG
-               abort();
+       TRACE(("cmdloop(%d) called\n", top));
+       for (;;) {
+               int skip;
+
+               setstackmark(&smark);
+#if JOBS
+               if (jobctl)
+                       showjobs(stderr, SHOW_CHANGED);
 #endif
-               /* Fall through to eliminate warning. */
-       case NTOFD:
-       case NFROMFD:
-               f = -1;
-               break;
-       case NHERE:
-       case NXHERE:
-               f = openhere(redir);
-               break;
-       }
+               inter = 0;
+               if (iflag && top) {
+                       inter++;
+#if ENABLE_ASH_MAIL
+                       chkmail();
+#endif
+               }
+               n = parsecmd(inter);
+               /* showtree(n); DEBUG */
+               if (n == NEOF) {
+                       if (!top || numeof >= 50)
+                               break;
+                       if (!stoppedjobs()) {
+                               if (!Iflag)
+                                       break;
+                               out2str("\nUse \"exit\" to leave shell.\n");
+                       }
+                       numeof++;
+               } else if (nflag == 0) {
+                       job_warning = (job_warning == 2) ? 1 : 0;
+                       numeof = 0;
+                       evaltree(n, 0);
+               }
+               popstackmark(&smark);
+               skip = evalskip;
 
-       return f;
- ecreate:
-       ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "Directory nonexistent"));
- eopen:
-       ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "No such file"));
+               if (skip) {
+                       evalskip = 0;
+                       return skip & SKIPEVAL;
+               }
+       }
+       return 0;
 }
 
-static void
-dupredirect(union node *redir, int f)
+/*
+ * Take commands from a file.  To be compatible we should do a path
+ * search for the file, which is necessary to find sub-commands.
+ */
+static char *
+find_dot_file(char *name)
 {
-       int fd = redir->nfile.fd;
+       char *fullname;
+       const char *path = pathval();
+       struct stat statb;
 
-       if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
-               if (redir->ndup.dupfd >= 0) {   /* if not ">&-" */
-                       copyfd(redir->ndup.dupfd, fd);
+       /* don't try this for absolute or relative paths */
+       if (strchr(name, '/'))
+               return name;
+
+       while ((fullname = padvance(&path, name)) != NULL) {
+               if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
+                       /*
+                        * Don't bother freeing here, since it will
+                        * be freed by the caller.
+                        */
+                       return fullname;
                }
-               return;
+               stunalloc(fullname);
        }
 
-       if (f != fd) {
-               copyfd(f, fd);
-               close(f);
-       }
+       /* not found in the PATH */
+       ash_msg_and_raise_error("%s: not found", name);
+       /* NOTREACHED */
 }
 
-
-/*
- * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
- * old file descriptors are stashed away so that the redirection can be
- * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
- * standard output, and the standard error if it becomes a duplicate of
- * stdout, is saved in memory.
- */
-static void
-redirect(union node *redir, int flags)
+static int
+dotcmd(int argc, char **argv)
 {
-       union node *n;
-       struct redirtab *sv;
-       int i;
-       int fd;
-       int newfd;
-       int *p;
-       nullredirs++;
-       if (!redir) {
-               return;
-       }
-       sv = NULL;
-       INT_OFF;
-       if (flags & REDIR_PUSH) {
-               struct redirtab *q;
-               q = ckmalloc(sizeof(struct redirtab));
-               q->next = redirlist;
-               redirlist = q;
-               q->nullredirs = nullredirs - 1;
-               for (i = 0; i < 10; i++)
-                       q->renamed[i] = EMPTY;
-               nullredirs = 0;
-               sv = q;
-       }
-       n = redir;
-       do {
-               fd = n->nfile.fd;
-               if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
-                && n->ndup.dupfd == fd)
-                       continue; /* redirect from/to same file descriptor */
+       struct strlist *sp;
+       volatile struct shparam saveparam;
+       int status = 0;
 
-               newfd = openredirect(n);
-               if (fd == newfd)
-                       continue;
-               if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
-                       i = fcntl(fd, F_DUPFD, 10);
+       for (sp = cmdenviron; sp; sp = sp->next)
+               setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
 
-                       if (i == -1) {
-                               i = errno;
-                               if (i != EBADF) {
-                                       close(newfd);
-                                       errno = i;
-                                       ash_msg_and_raise_error("%d: %m", fd);
-                                       /* NOTREACHED */
-                               }
-                       } else {
-                               *p = i;
-                               close(fd);
-                       }
-               } else {
-                       close(fd);
-               }
-               dupredirect(n, newfd);
-       } while ((n = n->nfile.next));
-       INT_ON;
-       if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
-               preverrout_fd = sv->renamed[2];
+       if (argc >= 2) {        /* That's what SVR2 does */
+               char *fullname;
+
+               fullname = find_dot_file(argv[1]);
+
+               if (argc > 2) {
+                       saveparam = shellparam;
+                       shellparam.malloc = 0;
+                       shellparam.nparam = argc - 2;
+                       shellparam.p = argv + 2;
+               };
+
+               setinputfile(fullname, INPUT_PUSH_FILE);
+               commandname = fullname;
+               cmdloop(0);
+               popfile();
+
+               if (argc > 2) {
+                       freeparam(&shellparam);
+                       shellparam = saveparam;
+               };
+               status = exitstatus;
+       }
+       return status;
+}
+
+static int
+exitcmd(int argc, char **argv)
+{
+       if (stoppedjobs())
+               return 0;
+       if (argc > 1)
+               exitstatus = number(argv[1]);
+       raise_exception(EXEXIT);
+       /* NOTREACHED */
 }
 
-/*
- * Undo the effects of the last redirection.
- */
-static void
-popredir(int drop)
+#if ENABLE_ASH_BUILTIN_ECHO
+static int
+echocmd(int argc, char **argv)
 {
-       struct redirtab *rp;
-       int i;
+       return bb_echo(argv);
+}
+#endif
 
-       if (--nullredirs >= 0)
-               return;
-       INT_OFF;
-       rp = redirlist;
-       for (i = 0; i < 10; i++) {
-               if (rp->renamed[i] != EMPTY) {
-                       if (!drop) {
-                               close(i);
-                               copyfd(rp->renamed[i], i);
-                       }
-                       close(rp->renamed[i]);
-               }
-       }
-       redirlist = rp->next;
-       nullredirs = rp->nullredirs;
-       free(rp);
-       INT_ON;
+#if ENABLE_ASH_BUILTIN_TEST
+static int
+testcmd(int argc, char **argv)
+{
+       return bb_test(argc, argv);
 }
+#endif
 
 /*
- * Undo all redirections.  Called on error or interrupt.
+ * Read a file containing shell functions.
  */
+static void
+readcmdfile(char *name)
+{
+       setinputfile(name, INPUT_PUSH_FILE);
+       cmdloop(0);
+       popfile();
+}
+
+
+/* ============ find_command inplementation */
 
 /*
- * Discard all saved file descriptors.
+ * Resolve a command name.  If you change this routine, you may have to
+ * change the shellexec routine as well.
  */
 static void
-clearredir(int drop)
+find_command(char *name, struct cmdentry *entry, int act, const char *path)
 {
-       for (;;) {
-               nullredirs = 0;
-               if (!redirlist)
+       struct tblentry *cmdp;
+       int idx;
+       int prev;
+       char *fullname;
+       struct stat statb;
+       int e;
+       int updatetbl;
+       struct builtincmd *bcmd;
+
+       /* If name contains a slash, don't use PATH or hash table */
+       if (strchr(name, '/') != NULL) {
+               entry->u.index = -1;
+               if (act & DO_ABS) {
+                       while (stat(name, &statb) < 0) {
+#ifdef SYSV
+                               if (errno == EINTR)
+                                       continue;
+#endif
+                               entry->cmdtype = CMDUNKNOWN;
+                               return;
+                       }
+               }
+               entry->cmdtype = CMDNORMAL;
+               return;
+       }
+
+/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
+
+       updatetbl = (path == pathval());
+       if (!updatetbl) {
+               act |= DO_ALTPATH;
+               if (strstr(path, "%builtin") != NULL)
+                       act |= DO_ALTBLTIN;
+       }
+
+       /* If name is in the table, check answer will be ok */
+       cmdp = cmdlookup(name, 0);
+       if (cmdp != NULL) {
+               int bit;
+
+               switch (cmdp->cmdtype) {
+               default:
+#if DEBUG
+                       abort();
+#endif
+               case CMDNORMAL:
+                       bit = DO_ALTPATH;
                        break;
-               popredir(drop);
+               case CMDFUNCTION:
+                       bit = DO_NOFUNC;
+                       break;
+               case CMDBUILTIN:
+                       bit = DO_ALTBLTIN;
+                       break;
+               }
+               if (act & bit) {
+                       updatetbl = 0;
+                       cmdp = NULL;
+               } else if (cmdp->rehash == 0)
+                       /* if not invalidated by cd, we're done */
+                       goto success;
        }
-}
 
-/*
- * Copy a file descriptor to be >= to.  Returns -1
- * if the source file descriptor is closed, EMPTY if there are no unused
- * file descriptors left.
- */
-static int
-copyfd(int from, int to)
-{
-       int newfd;
+       /* If %builtin not in path, check for builtin next */
+       bcmd = find_builtin(name);
+       if (bcmd) {
+               if (IS_BUILTIN_REGULAR(bcmd))
+                       goto builtin_success;
+               if (act & DO_ALTPATH) {
+                       if (!(act & DO_ALTBLTIN))
+                               goto builtin_success;
+               } else if (builtinloc <= 0) {
+                       goto builtin_success;
+               }
+       }
 
-       newfd = fcntl(from, F_DUPFD, to);
-       if (newfd < 0) {
-               if (errno == EMFILE)
-                       return EMPTY;
-               ash_msg_and_raise_error("%d: %m", from);
+#if ENABLE_FEATURE_SH_STANDALONE
+       if (find_applet_by_name(name)) {
+               entry->cmdtype = CMDNORMAL;
+               entry->u.index = -1;
+               return;
        }
-       return newfd;
-}
+#endif
 
-static int
-redirectsafe(union node *redir, int flags)
-{
-       int err;
-       volatile int saveint;
-       struct jmploc *volatile savehandler = exception_handler;
-       struct jmploc jmploc;
+       /* We have to search path. */
+       prev = -1;              /* where to start */
+       if (cmdp && cmdp->rehash) {     /* doing a rehash */
+               if (cmdp->cmdtype == CMDBUILTIN)
+                       prev = builtinloc;
+               else
+                       prev = cmdp->param.index;
+       }
 
-       SAVE_INT(saveint);
-       err = setjmp(jmploc.loc) * 2;
-       if (!err) {
-               exception_handler = &jmploc;
-               redirect(redir, flags);
+       e = ENOENT;
+       idx = -1;
+ loop:
+       while ((fullname = padvance(&path, name)) != NULL) {
+               stunalloc(fullname);
+               idx++;
+               if (pathopt) {
+                       if (prefix(pathopt, "builtin")) {
+                               if (bcmd)
+                                       goto builtin_success;
+                               continue;
+                       } else if (!(act & DO_NOFUNC) &&
+                                  prefix(pathopt, "func")) {
+                               /* handled below */
+                       } else {
+                               /* ignore unimplemented options */
+                               continue;
+                       }
+               }
+               /* if rehash, don't redo absolute path names */
+               if (fullname[0] == '/' && idx <= prev) {
+                       if (idx < prev)
+                               continue;
+                       TRACE(("searchexec \"%s\": no change\n", name));
+                       goto success;
+               }
+               while (stat(fullname, &statb) < 0) {
+#ifdef SYSV
+                       if (errno == EINTR)
+                               continue;
+#endif
+                       if (errno != ENOENT && errno != ENOTDIR)
+                               e = errno;
+                       goto loop;
+               }
+               e = EACCES;     /* if we fail, this will be the error */
+               if (!S_ISREG(statb.st_mode))
+                       continue;
+               if (pathopt) {          /* this is a %func directory */
+                       stalloc(strlen(fullname) + 1);
+                       readcmdfile(fullname);
+                       cmdp = cmdlookup(name, 0);
+                       if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
+                               ash_msg_and_raise_error("%s not defined in %s", name, fullname);
+                       stunalloc(fullname);
+                       goto success;
+               }
+               TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
+               if (!updatetbl) {
+                       entry->cmdtype = CMDNORMAL;
+                       entry->u.index = idx;
+                       return;
+               }
+               INT_OFF;
+               cmdp = cmdlookup(name, 1);
+               cmdp->cmdtype = CMDNORMAL;
+               cmdp->param.index = idx;
+               INT_ON;
+               goto success;
        }
-       exception_handler = savehandler;
-       if (err && exception != EXERROR)
-               longjmp(exception_handler->loc, 1);
-       RESTORE_INT(saveint);
-       return err;
+
+       /* We failed.  If there was an entry for this command, delete it */
+       if (cmdp && updatetbl)
+               delete_cmd_entry();
+       if (act & DO_ERR)
+               ash_msg("%s: %s", name, errmsg(e, "not found"));
+       entry->cmdtype = CMDUNKNOWN;
+       return;
+
+ builtin_success:
+       if (!updatetbl) {
+               entry->cmdtype = CMDBUILTIN;
+               entry->u.cmd = bcmd;
+               return;
+       }
+       INT_OFF;
+       cmdp = cmdlookup(name, 1);
+       cmdp->cmdtype = CMDBUILTIN;
+       cmdp->param.cmd = bcmd;
+       INT_ON;
+ success:
+       cmdp->rehash = 0;
+       entry->cmdtype = cmdp->cmdtype;
+       entry->u = cmdp->param;
 }
 
 
@@ -11418,13 +11271,13 @@ helpcmd(int argc, char **argv)
        out1fmt("\nBuilt-in commands:\n-------------------\n");
        for (col = 0, i = 0; i < NUMBUILTINS; i++) {
                col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
-                                         builtincmd[i].name + 1);
+                                       builtintab[i].name + 1);
                if (col > 60) {
                        out1fmt("\n");
                        col = 0;
                }
        }
-#if ENABLE_FEATURE_SH_STANDALONE_SHELL
+#if ENABLE_FEATURE_SH_STANDALONE
        for (i = 0; i < NUM_APPLETS; i++) {
                col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
                if (col > 60) {
@@ -11859,7 +11712,7 @@ umaskcmd(int argc, char **argv)
                } else {
                        mask = ~mask & 0777;
                        if (!bb_parse_mode(ap, &mask)) {
-                               ash_msg_and_raise_error("Illegal mode: %s", ap);
+                               ash_msg_and_raise_error("illegal mode: %s", ap);
                        }
                        umask(~mask & 0777);
                }