libbb/bb_do_delay.c: shrink
[oweals/busybox.git] / shell / hush.c
index 6c20615fa58487228477f1f2c3222abddfff8c5b..1187cbe8fb60b7e5a9acd6af06a68c091c94e038 100644 (file)
  *      <(list) and >(list) Process Substitution
  *      Tilde Expansion
  *
- * Bash stuff (maybe optionally enable?):
+ * Bash stuff (optionally enabled):
  *      &> and >& redirection of stdout+stderr
  *      Brace Expansion
  *      reserved words: [[ ]] function select
  *      substrings ${var:1:5}
+ *      let EXPR [EXPR...]
+ *        Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
+ *        If the last arg evaluates to 0, let returns 1; 0 otherwise.
+ *        NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
+ *      ((EXPR))
+ *        The EXPR is evaluated according to ARITHMETIC EVALUATION.
+ *        This is exactly equivalent to let "expression".
  *
  * TODOs:
  *      grep for "TODO" and fix (some of them are easy)
  *      builtins: ulimit
+ *      special variables (done: PWD)
  *      follow IFS rules more precisely, including update semantics
  *      export builtin should be special, its arguments are assignments
  *          and therefore expansion of them should be "one-word" expansion:
@@ -59,7 +67,7 @@
  *              $ ls i=`echo 'a  b'`     # ls has two args: "i=a" and "b"
  *              ls: cannot access i=a: No such file or directory
  *              ls: cannot access b: No such file or directory
- *          Note1: same applies to local builtin when we'll have it.
+ *          Note1: same applies to local builtin.
  *          Note2: bash 3.2.33(1) does this only if export word itself
  *          is not quoted:
  *              $ export i=`echo 'aaa  bbb'`; echo "$i"
@@ -70,6 +78,7 @@
  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  */
 #include "busybox.h"  /* for APPLET_IS_NOFORK/NOEXEC */
+#include <malloc.h>   /* for malloc_trim */
 #include <glob.h>
 /* #include <dmalloc.h> */
 #if ENABLE_HUSH_CASE
 #endif
 #include "math.h"
 #include "match.h"
+#if ENABLE_HUSH_RANDOM_SUPPORT
+# include "random.h"
+#else
+# define CLEAR_RANDOM_T(rnd) ((void)0)
+#endif
 #ifndef PIPE_BUF
 # define PIPE_BUF 4096  /* amount of buffering in a pipe */
 #endif
@@ -173,23 +187,6 @@ typedef struct nommu_save_t {
 } nommu_save_t;
 #endif
 
-/* The descrip member of this structure is only used to make
- * debugging output pretty */
-static const struct {
-       int mode;
-       signed char default_fd;
-       char descrip[3];
-} redir_table[] = {
-       { 0,                         0, "??" },
-       { O_RDONLY,                  0, "<"  },
-       { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
-       { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
-       { O_RDONLY,                  0, "<<" },
-       { O_CREAT|O_RDWR,            1, "<>" },
-/* Should not be needed. Bogus default_fd helps in debugging */
-/*     { O_RDONLY,                 77, "<<" }, */
-};
-
 typedef enum reserved_style {
        RES_NONE  = 0,
 #if ENABLE_HUSH_IF
@@ -262,6 +259,22 @@ typedef struct in_str {
 #define i_getch(input) ((input)->get(input))
 #define i_peek(input) ((input)->peek(input))
 
+/* The descrip member of this structure is only used to make
+ * debugging output pretty */
+static const struct {
+       int mode;
+       signed char default_fd;
+       char descrip[3];
+} redir_table[] = {
+       { O_RDONLY,                  0, "<"  },
+       { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
+       { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
+       { O_CREAT|O_RDWR,            1, "<>" },
+       { O_RDONLY,                  0, "<<" },
+/* Should not be needed. Bogus default_fd helps in debugging */
+/*     { O_RDONLY,                 77, "<<" }, */
+};
+
 struct redir_struct {
        struct redir_struct *next;
        char *rd_filename;          /* filename */
@@ -271,18 +284,17 @@ struct redir_struct {
        smallint rd_type;           /* (enum redir_type) */
        /* note: for heredocs, rd_filename contains heredoc delimiter,
         * and subsequently heredoc itself; and rd_dup is a bitmask:
-        * 1: do we need to trim leading tabs?
-        * 2: is heredoc quoted (<<'delim' syntax) ?
+        * bit 0: do we need to trim leading tabs?
+        * bit 1: is heredoc quoted (<<'delim' syntax) ?
         */
 };
 typedef enum redir_type {
-       REDIRECT_INVALID   = 0,
-       REDIRECT_INPUT     = 1,
-       REDIRECT_OVERWRITE = 2,
-       REDIRECT_APPEND    = 3,
+       REDIRECT_INPUT     = 0,
+       REDIRECT_OVERWRITE = 1,
+       REDIRECT_APPEND    = 2,
+       REDIRECT_IO        = 3,
        REDIRECT_HEREDOC   = 4,
-       REDIRECT_IO        = 5,
-       REDIRECT_HEREDOC2  = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
+       REDIRECT_HEREDOC2  = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
 
        REDIRFD_CLOSE      = -3,
        REDIRFD_SYNTAX_ERR = -2,
@@ -298,12 +310,27 @@ struct command {
        pid_t pid;                  /* 0 if exited */
        int assignment_cnt;         /* how many argv[i] are assignments? */
        smallint is_stopped;        /* is the command currently running? */
-       smallint grp_type;          /* GRP_xxx */
-#define GRP_NORMAL   0
-#define GRP_SUBSHELL 1
+       smallint cmd_type;          /* CMD_xxx */
+#define CMD_NORMAL   0
+#define CMD_SUBSHELL 1
+
+/* used for "[[ EXPR ]]" */
+#if ENABLE_HUSH_BASH_COMPAT
+# define CMD_SINGLEWORD_NOGLOB 2
+#endif
+
+/* used for "export noglob=* glob* a=`echo a b`" */
+//#define CMD_SINGLEWORD_NOGLOB_COND 3
+// It is hard to implement correctly, it adds significant amounts of tricky code,
+// and all this is only useful for really obscure export statements
+// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
+// guards the code which implements it, but I have doubts it works
+// in all cases (especially with mixed globbed/non-globbed arguments)
+
 #if ENABLE_HUSH_FUNCTIONS
-# define GRP_FUNCTION 2
+# define CMD_FUNCDEF 3
 #endif
+
        /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
        struct pipe *group;
 #if !BB_MMU
@@ -312,11 +339,11 @@ struct command {
 #if ENABLE_HUSH_FUNCTIONS
        struct function *child_func;
 /* This field is used to prevent a bug here:
- * while...do f1() {a;}; f1; f1 {b;}; f1; done
+ * while...do f1() {a;}; f1; f1() {b;}; f1; done
  * When we execute "f1() {a;}" cmd, we create new function and clear
  * cmd->group, cmd->group_as_string, cmd->argv[0].
- * when we execute "f1 {b;}", we notice that f1 exists,
- * and that it's "parent cmd" struct is still "alive",
+ * When we execute "f1() {b;}", we notice that f1 exists,
+ * and that its "parent cmd" struct is still "alive",
  * we put those fields back into cmd->xxx
  * (struct function has ->parent_cmd ptr to facilitate that).
  * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
@@ -427,9 +454,9 @@ struct function {
        char *name;
        struct command *parent_cmd;
        struct pipe *body;
-#if !BB_MMU
+# if !BB_MMU
        char *body_as_string;
-#endif
+# endif
 };
 #endif
 
@@ -462,7 +489,11 @@ struct globals {
        line_input_t *line_input_state;
 #endif
        pid_t root_pid;
+       pid_t root_ppid;
        pid_t last_bg_pid;
+#if ENABLE_HUSH_RANDOM_SUPPORT
+       random_t random_gen;
+#endif
 #if ENABLE_HUSH_JOB
        int run_list_level;
        int last_jobid;
@@ -525,7 +556,7 @@ struct globals {
        unsigned long memleak_value;
        int debug_indent;
 #endif
-       char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
+       char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
 };
 #define G (*ptr_to_globals)
 /* Not #defining name to G.name - this quickly gets unwieldy
@@ -556,6 +587,9 @@ static int builtin_local(char **argv) FAST_FUNC;
 #if HUSH_DEBUG
 static int builtin_memleak(char **argv) FAST_FUNC;
 #endif
+#if ENABLE_PRINTF
+static int builtin_printf(char **argv) FAST_FUNC;
+#endif
 static int builtin_pwd(char **argv) FAST_FUNC;
 static int builtin_read(char **argv) FAST_FUNC;
 static int builtin_set(char **argv) FAST_FUNC;
@@ -643,6 +677,9 @@ static const struct built_in_command bltins1[] = {
 static const struct built_in_command bltins2[] = {
        BLTIN("["        , builtin_test    , NULL),
        BLTIN("echo"     , builtin_echo    , NULL),
+#if ENABLE_PRINTF
+       BLTIN("printf"   , builtin_printf  , NULL),
+#endif
        BLTIN("pwd"      , builtin_pwd     , NULL),
        BLTIN("test"     , builtin_test    , NULL),
 };
@@ -765,7 +802,7 @@ static void xxfree(void *ptr)
  * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  */
 #if HUSH_DEBUG < 2
-# define die_if_script(lineno, fmt...)          die_if_script(fmt)
+# define die_if_script(lineno, ...)             die_if_script(__VA_ARGS__)
 # define syntax_error(lineno, msg)              syntax_error(msg)
 # define syntax_error_at(lineno, msg)           syntax_error_at(msg)
 # define syntax_error_unterm_ch(lineno, ch)     syntax_error_unterm_ch(ch)
@@ -834,7 +871,7 @@ static void syntax_error_unexpected_ch(unsigned lineno, int ch)
 # undef syntax_error_unterm_str
 # undef syntax_error_unexpected_ch
 #else
-# define die_if_script(fmt...)          die_if_script(__LINE__, fmt)
+# define die_if_script(...)             die_if_script(__LINE__, __VA_ARGS__)
 # define syntax_error(msg)              syntax_error(__LINE__, msg)
 # define syntax_error_at(msg)           syntax_error_at(__LINE__, msg)
 # define syntax_error_unterm_ch(ch)     syntax_error_unterm_ch(__LINE__, ch)
@@ -877,7 +914,7 @@ static int is_well_formed_var_name(const char *s, char terminator)
 /* Replace each \x with x in place, return ptr past NUL. */
 static char *unbackslash(char *src)
 {
-       char *dst = src;
+       char *dst = src = strchrnul(src, '\\');
        while (1) {
                if (*src == '\\')
                        src++;
@@ -1016,7 +1053,7 @@ static void restore_G_args(save_arg_t *sv, char **argv)
  * is finished or backgrounded. It is the same in interactive and
  * non-interactive shells, and is the same regardless of whether
  * a user trap handler is installed or a shell special one is in effect.
- * ^C or ^Z from keyboard seem to execute "at once" because it usually
+ * ^C or ^Z from keyboard seems to execute "at once" because it usually
  * backgrounds (i.e. stops) or kills all members of currently running
  * pipe.
  *
@@ -1083,12 +1120,17 @@ static void restore_G_args(save_arg_t *sv, char **argv)
  *    (child shell is not interactive),
  *    unset all traps (note: regardless of child shell's type - {}, (), etc)
  * after [v]fork, if we plan to exec:
- *    POSIX says pending signal mask is cleared in child - no need to clear it.
+ *    POSIX says fork clears pending signal mask in child - no need to clear it.
  *    Restore blocked signal set to one inherited by shell just prior to exec.
  *
  * Note: as a result, we do not use signal handlers much. The only uses
  * are to count SIGCHLDs
  * and to restore tty pgrp on signal-induced exit.
+ *
+ * Note 2 (compat):
+ * Standard says "When a subshell is entered, traps that are not being ignored
+ * are set to the default actions". bash interprets it so that traps which
+ * are set to "" (ignore) are NOT reset to defaults. We do the same.
  */
 enum {
        SPECIAL_INTERACTIVE_SIGS = 0
@@ -1280,6 +1322,14 @@ static const char *get_local_var_value(const char *name)
        struct variable **pp = get_ptr_to_local_var(name);
        if (pp)
                return strchr((*pp)->varstr, '=') + 1;
+       if (strcmp(name, "PPID") == 0)
+               return utoa(G.root_ppid);
+       // bash compat: UID? EUID?
+#if ENABLE_HUSH_RANDOM_SUPPORT
+       if (strcmp(name, "RANDOM") == 0) {
+               return utoa(next_random(&G.random_gen));
+       }
+#endif
        return NULL;
 }
 
@@ -1411,6 +1461,13 @@ static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_
        return 0;
 }
 
+/* Used at startup and after each cd */
+static void set_pwd_var(int exp)
+{
+       set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
+               /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
+}
+
 static int unset_local_var_len(const char *name, int name_len)
 {
        struct variable *cur;
@@ -1583,6 +1640,9 @@ static const char* setup_prompt_string(int promptmode)
                /* Set up the prompt */
                if (promptmode == 0) { /* PS1 */
                        free((char*)G.PS1);
+                       /* bash uses $PWD value, even if it is set by user.
+                        * It uses current dir only if PWD is unset.
+                        * We always use current dir. */
                        G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
                        prompt_str = G.PS1;
                } else
@@ -1606,7 +1666,7 @@ static void get_user_input(struct in_str *i)
                G.flag_SIGINT = 0;
                /* buglet: SIGINT will not make new prompt to appear _at once_,
                 * only after <Enter>. (^C will work) */
-               r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
+               r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
                /* catch *SIGINT* etc (^C is handled by read_line_input) */
                check_and_run_traps(0);
        } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
@@ -2114,7 +2174,7 @@ static char *expand_pseudo_dquoted(const char *str)
  * to be filled). This routine is extremely tricky: has to deal with
  * variables/parameters with whitespace, $* and $@, and constructs like
  * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
-static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
+static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
 {
        /* or_mask is either 0 (normal case) or 0x80 -
         * expansion of right-hand side of assignment == 1-element expand.
@@ -2125,7 +2185,7 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
 
        ored_ch = 0;
 
-       debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
+       debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
        debug_print_list("expand_vars_to_list", output, n);
        n = o_save_ptr(output, n);
        debug_print_list("expand_vars_to_list[0]", output, n);
@@ -2442,7 +2502,7 @@ static char **expand_variables(char **argv, int or_mask)
        n = 0;
        v = argv;
        while (*v) {
-               n = expand_vars_to_list(&output, n, *v, (char)or_mask);
+               n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
                v++;
        }
        debug_print_list("expand_variables", &output, n);
@@ -2458,6 +2518,48 @@ static char **expand_strvec_to_strvec(char **argv)
        return expand_variables(argv, 0x100);
 }
 
+#if ENABLE_HUSH_BASH_COMPAT
+static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
+{
+       return expand_variables(argv, 0x80);
+}
+#endif
+
+#ifdef CMD_SINGLEWORD_NOGLOB_COND
+static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
+{
+       int n;
+       char **list;
+       char **v;
+       o_string output = NULL_O_STRING;
+
+       n = 0;
+       v = argv;
+       while (*v) {
+               int is_var = is_well_formed_var_name(*v, '=');
+               /* is_var * 0x80: singleword expansion for vars */
+               n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
+
+               /* Subtle! expand_vars_to_list did not glob last word yet.
+                * It does this only when fed with further data.
+                * Therefore we set globbing flags AFTER it, not before:
+                */
+
+               /* if it is not recognizably abc=...; then: */
+               output.o_escape = !is_var; /* protect against globbing for "$var" */
+               /* (unquoted $var will temporarily switch it off) */
+               output.o_glob = !is_var; /* and indeed do globbing */
+               v++;
+       }
+       debug_print_list("expand_cond", &output, n);
+
+       /* output.data (malloced in one block) gets returned in "list" */
+       list = o_finalize_list(&output, n);
+       debug_print_strings("expand_cond[1]", list);
+       return list;
+}
+#endif
+
 /* Used for expansion of right hand of assignments */
 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
  * "v=/bin/c*" */
@@ -2467,7 +2569,7 @@ static char *expand_string_to_string(const char *str)
 
        argv[0] = (char*)str;
        argv[1] = NULL;
-       list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
+       list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
        if (HUSH_DEBUG)
                if (!list[0] || list[1])
                        bb_error_msg_and_die("BUG in varexp2");
@@ -2523,43 +2625,51 @@ static void reset_traps_to_defaults(void)
 {
        /* This function is always called in a child shell
         * after fork (not vfork, NOMMU doesn't use this function).
-        * Child shells are not interactive.
-        * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
-        * Testcase: (while :; do :; done) + ^Z should background.
-        * Same goes for SIGTERM, SIGHUP, SIGINT.
         */
        unsigned sig;
        unsigned mask;
 
+       /* Child shells are not interactive.
+        * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
+        * Testcase: (while :; do :; done) + ^Z should background.
+        * Same goes for SIGTERM, SIGHUP, SIGINT.
+        */
        if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
-               return;
+               return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
 
-       /* Stupid. It can be done with *single* &= op, but we can't use
-        * the fact that G.blocked_set is implemented as a bitmask... */
+       /* Switching off SPECIAL_INTERACTIVE_SIGS.
+        * Stupid. It can be done with *single* &= op, but we can't use
+        * the fact that G.blocked_set is implemented as a bitmask
+        * in libc... */
        mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
        sig = 1;
        while (1) {
-               if (mask & 1)
-                       sigdelset(&G.blocked_set, sig);
+               if (mask & 1) {
+                       /* Careful. Only if no trap or trap is not "" */
+                       if (!G.traps || !G.traps[sig] || G.traps[sig][0])
+                               sigdelset(&G.blocked_set, sig);
+               }
                mask >>= 1;
                if (!mask)
                        break;
                sig++;
        }
-
+       /* Our homegrown sig mask is saner to work with :) */
        G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
+
+       /* Resetting all traps to default except empty ones */
        mask = G.non_DFL_mask;
        if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
-               if (!G.traps[sig])
+               if (!G.traps[sig] || !G.traps[sig][0])
                        continue;
                free(G.traps[sig]);
                G.traps[sig] = NULL;
                /* There is no signal for 0 (EXIT) */
                if (sig == 0)
                        continue;
-               /* There was a trap handler, we are removing it.
+               /* There was a trap handler, we just removed it.
                 * But if sig still has non-DFL handling,
-                * we should not unblock it. */
+                * we should not unblock the sig. */
                if (mask & 1)
                        continue;
                sigdelset(&G.blocked_set, sig);
@@ -2579,9 +2689,9 @@ static void re_execute_shell(char ***to_free, const char *s,
        char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
        char *heredoc_argv[4];
        struct variable *cur;
-#if ENABLE_HUSH_FUNCTIONS
+# if ENABLE_HUSH_FUNCTIONS
        struct function *funcp;
-#endif
+# endif
        char **argv, **pp;
        unsigned cnt;
 
@@ -2600,8 +2710,9 @@ static void re_execute_shell(char ***to_free, const char *s,
        if (pp) while (*pp++)
                cnt++;
 
-       sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
+       sprintf(param_buf, "-$%x:%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
                        , (unsigned) G.root_pid
+                       , (unsigned) G.root_ppid
                        , (unsigned) G.last_bg_pid
                        , (unsigned) G.last_exitcode
                        , cnt
@@ -2615,10 +2726,10 @@ static void re_execute_shell(char ***to_free, const char *s,
                if (!cur->flg_export || cur->flg_read_only)
                        cnt += 2;
        }
-#if ENABLE_HUSH_FUNCTIONS
+# if ENABLE_HUSH_FUNCTIONS
        for (funcp = G.top_func; funcp; funcp = funcp->next)
                cnt += 3;
-#endif
+# endif
        pp = g_argv;
        while (*pp++)
                cnt++;
@@ -2636,13 +2747,13 @@ static void re_execute_shell(char ***to_free, const char *s,
                        *pp++ = cur->varstr;
                }
        }
-#if ENABLE_HUSH_FUNCTIONS
+# if ENABLE_HUSH_FUNCTIONS
        for (funcp = G.top_func; funcp; funcp = funcp->next) {
                *pp++ = (char *) "-F";
                *pp++ = funcp->name;
                *pp++ = funcp->body_as_string;
        }
-#endif
+# endif
        /* We can pass activated traps here. Say, -Tnn:trap_string
         *
         * However, POSIX says that subshells reset signals with traps
@@ -2877,8 +2988,8 @@ static void free_pipe(struct pipe *pi)
                }
                /* not "else if": on syntax error, we may have both! */
                if (command->group) {
-                       debug_printf_clean("   begin group (grp_type:%d)\n",
-                                       command->grp_type);
+                       debug_printf_clean("   begin group (cmd_type:%d)\n",
+                                       command->cmd_type);
                        free_pipe_list(command->group);
                        debug_printf_clean("   end group\n");
                        command->group = NULL;
@@ -3006,15 +3117,21 @@ static const struct built_in_command* find_builtin(const char *name)
 }
 
 #if ENABLE_HUSH_FUNCTIONS
-static const struct function *find_function(const char *name)
+static struct function **find_function_slot(const char *name)
 {
-       const struct function *funcp = G.top_func;
-       while (funcp) {
-               if (strcmp(name, funcp->name) == 0) {
+       struct function **funcpp = &G.top_func;
+       while (*funcpp) {
+               if (strcmp(name, (*funcpp)->name) == 0) {
                        break;
                }
-               funcp = funcp->next;
+               funcpp = &(*funcpp)->next;
        }
+       return funcpp;
+}
+
+static const struct function *find_function(const char *name)
+{
+       const struct function *funcp = *find_function_slot(name);
        if (funcp)
                debug_printf_exec("found function '%s'\n", name);
        return funcp;
@@ -3023,18 +3140,11 @@ static const struct function *find_function(const char *name)
 /* Note: takes ownership on name ptr */
 static struct function *new_function(char *name)
 {
-       struct function *funcp;
-       struct function **funcpp = &G.top_func;
+       struct function **funcpp = find_function_slot(name);
+       struct function *funcp = *funcpp;
 
-       while ((funcp = *funcpp) != NULL) {
-               struct command *cmd;
-
-               if (strcmp(funcp->name, name) != 0) {
-                       funcpp = &funcp->next;
-                       continue;
-               }
-
-               cmd = funcp->parent_cmd;
+       if (funcp != NULL) {
+               struct command *cmd = funcp->parent_cmd;
                debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
                if (!cmd) {
                        debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
@@ -3056,50 +3166,47 @@ static struct function *new_function(char *name)
                        cmd->group_as_string = funcp->body_as_string;
 # endif
                }
-               goto skip;
+       } else {
+               debug_printf_exec("remembering new function '%s'\n", name);
+               funcp = *funcpp = xzalloc(sizeof(*funcp));
+               /*funcp->next = NULL;*/
        }
-       debug_printf_exec("remembering new function '%s'\n", name);
-       funcp = *funcpp = xzalloc(sizeof(*funcp));
-       /*funcp->next = NULL;*/
- skip:
+
        funcp->name = name;
        return funcp;
 }
 
 static void unset_func(const char *name)
 {
-       struct function *funcp;
-       struct function **funcpp = &G.top_func;
-
-       while ((funcp = *funcpp) != NULL) {
-               if (strcmp(funcp->name, name) == 0) {
-                       *funcpp = funcp->next;
-                       /* funcp is unlinked now, deleting it.
-                        * Note: if !funcp->body, the function was created by
-                        * "-F name body", do not free ->body_as_string
-                        * and ->name as they were not malloced. */
-                       if (funcp->body) {
-                               free_pipe_list(funcp->body);
-                               free(funcp->name);
+       struct function **funcpp = find_function_slot(name);
+       struct function *funcp = *funcpp;
+
+       if (funcp != NULL) {
+               debug_printf_exec("freeing function '%s'\n", funcp->name);
+               *funcpp = funcp->next;
+               /* funcp is unlinked now, deleting it.
+                * Note: if !funcp->body, the function was created by
+                * "-F name body", do not free ->body_as_string
+                * and ->name as they were not malloced. */
+               if (funcp->body) {
+                       free_pipe_list(funcp->body);
+                       free(funcp->name);
 # if !BB_MMU
-                               free(funcp->body_as_string);
+                       free(funcp->body_as_string);
 # endif
-                       }
-                       free(funcp);
-                       break;
                }
-               funcpp = &funcp->next;
+               free(funcp);
        }
 }
 
 # if BB_MMU
-#define exec_function(nommu_save, funcp, argv) \
+#define exec_function(to_free, funcp, argv) \
        exec_function(funcp, argv)
 # endif
-static void exec_function(nommu_save_t *nommu_save,
+static void exec_function(char ***to_free,
                const struct function *funcp,
                char **argv) NORETURN;
-static void exec_function(nommu_save_t *nommu_save,
+static void exec_function(char ***to_free,
                const struct function *funcp,
                char **argv)
 {
@@ -3116,7 +3223,7 @@ static void exec_function(nommu_save_t *nommu_save,
        fflush(NULL);
        _exit(n);
 # else
-       re_execute_shell(&nommu_save->argv_from_re_execing,
+       re_execute_shell(to_free,
                        funcp->body_as_string,
                        G.global_argv[0],
                        argv + 1,
@@ -3135,9 +3242,9 @@ static int run_function(const struct function *funcp, char **argv)
        /* "we are in function, ok to use return" */
        sv_flg = G.flag_return_in_progress;
        G.flag_return_in_progress = -1;
-#if ENABLE_HUSH_LOCAL
+# if ENABLE_HUSH_LOCAL
        G.func_nest_level++;
-#endif
+# endif
 
        /* On MMU, funcp->body is always non-NULL */
 # if !BB_MMU
@@ -3151,7 +3258,7 @@ static int run_function(const struct function *funcp, char **argv)
                rc = run_list(funcp->body);
        }
 
-#if ENABLE_HUSH_LOCAL
+# if ENABLE_HUSH_LOCAL
        {
                struct variable *var;
                struct variable **var_pp;
@@ -3174,7 +3281,7 @@ static int run_function(const struct function *funcp, char **argv)
                }
                G.func_nest_level--;
        }
-#endif
+# endif
        G.flag_return_in_progress = sv_flg;
 
        restore_G_args(&sv, argv);
@@ -3184,37 +3291,47 @@ static int run_function(const struct function *funcp, char **argv)
 #endif /* ENABLE_HUSH_FUNCTIONS */
 
 
-# if BB_MMU
-#define exec_builtin(nommu_save, x, argv) \
+#if BB_MMU
+#define exec_builtin(to_free, x, argv) \
        exec_builtin(x, argv)
-# else
-#define exec_builtin(nommu_save, x, argv) \
-       exec_builtin(nommu_save, argv)
-# endif
-static void exec_builtin(nommu_save_t *nommu_save,
+#else
+#define exec_builtin(to_free, x, argv) \
+       exec_builtin(to_free, argv)
+#endif
+static void exec_builtin(char ***to_free,
                const struct built_in_command *x,
                char **argv) NORETURN;
-static void exec_builtin(nommu_save_t *nommu_save,
+static void exec_builtin(char ***to_free,
                const struct built_in_command *x,
                char **argv)
 {
-# if BB_MMU
+#if BB_MMU
        int rcode = x->function(argv);
        fflush(NULL);
        _exit(rcode);
-# else
+#else
        /* On NOMMU, we must never block!
         * Example: { sleep 99 | read line; } & echo Ok
         */
-       re_execute_shell(&nommu_save->argv_from_re_execing,
+       re_execute_shell(to_free,
                        argv[0],
                        G.global_argv[0],
                        G.global_argv + 1,
                        argv);
-# endif
+#endif
 }
 
 
+static void execvp_or_die(char **argv) NORETURN;
+static void execvp_or_die(char **argv)
+{
+       debug_printf_exec("execing '%s'\n", argv[0]);
+       sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
+       execvp(argv[0], argv);
+       bb_perror_msg("can't execute '%s'", argv[0]);
+       _exit(127); /* bash compat */
+}
+
 #if BB_MMU
 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
        pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
@@ -3230,7 +3347,7 @@ static void exec_builtin(nommu_save_t *nommu_save,
 static void pseudo_exec_argv(nommu_save_t *nommu_save,
                char **argv, int assignment_cnt,
                char **argv_expanded) NORETURN;
-static void pseudo_exec_argv(nommu_save_t *nommu_save,
+static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
                char **argv, int assignment_cnt,
                char **argv_expanded)
 {
@@ -3277,7 +3394,7 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
                const struct built_in_command *x;
                x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
                if (x) {
-                       exec_builtin(nommu_save, x, argv);
+                       exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
                }
        }
 #if ENABLE_HUSH_FUNCTIONS
@@ -3285,7 +3402,7 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
        {
                const struct function *funcp = find_function(argv[0]);
                if (funcp) {
-                       exec_function(nommu_save, funcp, argv);
+                       exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
                }
        }
 #endif
@@ -3314,11 +3431,7 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  skip:
 #endif
-       debug_printf_exec("execing '%s'\n", argv[0]);
-       sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
-       execvp(argv[0], argv);
-       bb_perror_msg("can't execute '%s'", argv[0]);
-       _exit(EXIT_FAILURE);
+       execvp_or_die(argv);
 }
 
 /* Called after [v]fork() in run_pipe
@@ -3555,9 +3668,9 @@ static int checkjobs(struct pipe* fg_pipe)
                                                /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
                                                rcode = WEXITSTATUS(status);
                                                IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
-                                               /* bash prints killing signal's name for *last*
+                                               /* bash prints killer signal's name for *last*
                                                 * process in pipe (prints just newline for SIGINT).
-                                                * Mimic this. Example: "sleep 5" + ^\
+                                                * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
                                                 */
                                                if (WIFSIGNALED(status)) {
                                                        int sig = WTERMSIG(status);
@@ -3667,7 +3780,7 @@ static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
  * backgrounded: cmd &     { list } &
  * subshell:     ( list ) [&]
  */
-static int run_pipe(struct pipe *pi)
+static NOINLINE int run_pipe(struct pipe *pi)
 {
        static const char *const null_ptr = NULL;
        int i;
@@ -3690,7 +3803,7 @@ static int run_pipe(struct pipe *pi)
 
        if (pi->num_cmds != 1
         || pi->followup == PIPE_BG
-        || command->grp_type == GRP_SUBSHELL
+        || command->cmd_type == CMD_SUBSHELL
        ) {
                goto must_fork;
        }
@@ -3702,7 +3815,7 @@ static int run_pipe(struct pipe *pi)
 
        if (command->group) {
 #if ENABLE_HUSH_FUNCTIONS
-               if (command->grp_type == GRP_FUNCTION) {
+               if (command->cmd_type == CMD_FUNCDEF) {
                        /* "executing" func () { list } */
                        struct function *funcp;
 
@@ -3772,7 +3885,27 @@ static int run_pipe(struct pipe *pi)
                }
 
                /* Expand the rest into (possibly) many strings each */
-               argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
+               if (0) {}
+#if ENABLE_HUSH_BASH_COMPAT
+               else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
+                       argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
+               }
+#endif
+#ifdef CMD_SINGLEWORD_NOGLOB_COND
+               else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
+                       argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
+
+               }
+#endif
+               else {
+                       argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
+               }
+
+               /* if someone gives us an empty string: `cmd with empty output` */
+               if (!argv_expanded[0]) {
+                       debug_leave();
+                       return 0;
+               }
 
                x = find_builtin(argv_expanded[0]);
 #if ENABLE_HUSH_FUNCTIONS
@@ -3885,6 +4018,7 @@ static int run_pipe(struct pipe *pi)
                if (!command->pid) { /* child */
 #if ENABLE_HUSH_JOB
                        disable_restore_tty_pgrp_on_exit();
+                       CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
 
                        /* Every child adds itself to new process group
                         * with pgid == pid_of_first_child_in_pipe */
@@ -3987,39 +4121,40 @@ static void debug_print_tree(struct pipe *pi, int lvl)
        };
        static const char *RES[] = {
                [RES_NONE ] = "NONE" ,
-#if ENABLE_HUSH_IF
+# if ENABLE_HUSH_IF
                [RES_IF   ] = "IF"   ,
                [RES_THEN ] = "THEN" ,
                [RES_ELIF ] = "ELIF" ,
                [RES_ELSE ] = "ELSE" ,
                [RES_FI   ] = "FI"   ,
-#endif
-#if ENABLE_HUSH_LOOPS
+# endif
+# if ENABLE_HUSH_LOOPS
                [RES_FOR  ] = "FOR"  ,
                [RES_WHILE] = "WHILE",
                [RES_UNTIL] = "UNTIL",
                [RES_DO   ] = "DO"   ,
                [RES_DONE ] = "DONE" ,
-#endif
-#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
+# endif
+# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
                [RES_IN   ] = "IN"   ,
-#endif
-#if ENABLE_HUSH_CASE
+# endif
+# if ENABLE_HUSH_CASE
                [RES_CASE ] = "CASE" ,
                [RES_CASE_IN ] = "CASE_IN" ,
                [RES_MATCH] = "MATCH",
                [RES_CASE_BODY] = "CASE_BODY",
                [RES_ESAC ] = "ESAC" ,
-#endif
+# endif
                [RES_XXXX ] = "XXXX" ,
                [RES_SNTX ] = "SNTX" ,
        };
-       static const char *const GRPTYPE[] = {
+       static const char *const CMDTYPE[] = {
                "{}",
                "()",
-#if ENABLE_HUSH_FUNCTIONS
+               "[noglob]",
+# if ENABLE_HUSH_FUNCTIONS
                "func()",
-#endif
+# endif
        };
 
        int pin, prn;
@@ -4038,7 +4173,7 @@ static void debug_print_tree(struct pipe *pi, int lvl)
                                        command->assignment_cnt);
                        if (command->group) {
                                fprintf(stderr, " group %s: (argv=%p)\n",
-                                               GRPTYPE[command->grp_type],
+                                               CMDTYPE[command->cmd_type],
                                                argv);
                                debug_print_tree(command->group, lvl+1);
                                prn++;
@@ -4055,7 +4190,7 @@ static void debug_print_tree(struct pipe *pi, int lvl)
                pin++;
        }
 }
-#endif
+#endif /* debug_print_tree */
 
 /* NB: called by pseudo_exec, and therefore must not modify any
  * global data until exec/_exit (we can be a child after vfork!) */
@@ -4529,25 +4664,25 @@ struct reserved_combo {
 };
 enum {
        FLAG_END   = (1 << RES_NONE ),
-#if ENABLE_HUSH_IF
+# if ENABLE_HUSH_IF
        FLAG_IF    = (1 << RES_IF   ),
        FLAG_THEN  = (1 << RES_THEN ),
        FLAG_ELIF  = (1 << RES_ELIF ),
        FLAG_ELSE  = (1 << RES_ELSE ),
        FLAG_FI    = (1 << RES_FI   ),
-#endif
-#if ENABLE_HUSH_LOOPS
+# endif
+# if ENABLE_HUSH_LOOPS
        FLAG_FOR   = (1 << RES_FOR  ),
        FLAG_WHILE = (1 << RES_WHILE),
        FLAG_UNTIL = (1 << RES_UNTIL),
        FLAG_DO    = (1 << RES_DO   ),
        FLAG_DONE  = (1 << RES_DONE ),
        FLAG_IN    = (1 << RES_IN   ),
-#endif
-#if ENABLE_HUSH_CASE
+# endif
+# if ENABLE_HUSH_CASE
        FLAG_MATCH = (1 << RES_MATCH),
        FLAG_ESAC  = (1 << RES_ESAC ),
-#endif
+# endif
        FLAG_START = (1 << RES_XXXX ),
 };
 
@@ -4559,26 +4694,26 @@ static const struct reserved_combo* match_reserved_word(o_string *word)
         * FLAG_START means the word must start a new compound list.
         */
        static const struct reserved_combo reserved_list[] = {
-#if ENABLE_HUSH_IF
+# if ENABLE_HUSH_IF
                { "!",     RES_NONE,  NOT_ASSIGNMENT , 0 },
                { "if",    RES_IF,    WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
                { "then",  RES_THEN,  WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
                { "elif",  RES_ELIF,  WORD_IS_KEYWORD, FLAG_THEN },
                { "else",  RES_ELSE,  WORD_IS_KEYWORD, FLAG_FI   },
                { "fi",    RES_FI,    NOT_ASSIGNMENT , FLAG_END  },
-#endif
-#if ENABLE_HUSH_LOOPS
+# endif
+# if ENABLE_HUSH_LOOPS
                { "for",   RES_FOR,   NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
                { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
                { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
                { "in",    RES_IN,    NOT_ASSIGNMENT , FLAG_DO   },
                { "do",    RES_DO,    WORD_IS_KEYWORD, FLAG_DONE },
                { "done",  RES_DONE,  NOT_ASSIGNMENT , FLAG_END  },
-#endif
-#if ENABLE_HUSH_CASE
+# endif
+# if ENABLE_HUSH_CASE
                { "case",  RES_CASE,  NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
                { "esac",  RES_ESAC,  NOT_ASSIGNMENT , FLAG_END  },
-#endif
+# endif
        };
        const struct reserved_combo *r;
 
@@ -4592,11 +4727,11 @@ static const struct reserved_combo* match_reserved_word(o_string *word)
  */
 static int reserved_word(o_string *word, struct parse_context *ctx)
 {
-#if ENABLE_HUSH_CASE
+# if ENABLE_HUSH_CASE
        static const struct reserved_combo reserved_match = {
                "",        RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
        };
-#endif
+# endif
        const struct reserved_combo *r;
 
        if (word->o_quoted)
@@ -4606,12 +4741,12 @@ static int reserved_word(o_string *word, struct parse_context *ctx)
                return 0;
 
        debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
-#if ENABLE_HUSH_CASE
+# if ENABLE_HUSH_CASE
        if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
                /* "case word IN ..." - IN part starts first MATCH part */
                r = &reserved_match;
        } else
-#endif
+# endif
        if (r->flag == 0) { /* '!' */
                if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
                        syntax_error("! ! command");
@@ -4651,20 +4786,20 @@ static int reserved_word(o_string *word, struct parse_context *ctx)
                debug_printf_parse("pop stack %p\n", ctx->stack);
                old = ctx->stack;
                old->command->group = ctx->list_head;
-               old->command->grp_type = GRP_NORMAL;
-#if !BB_MMU
+               old->command->cmd_type = CMD_NORMAL;
+# if !BB_MMU
                o_addstr(&old->as_string, ctx->as_string.data);
                o_free_unsafe(&ctx->as_string);
                old->command->group_as_string = xstrdup(old->as_string.data);
                debug_printf_parse("pop, remembering as:'%s'\n",
                                old->command->group_as_string);
-#endif
+# endif
                *ctx = *old;   /* physical copy */
                free(old);
        }
        return 1;
 }
-#endif
+#endif /* HAS_KEYWORDS */
 
 /* Word is complete, look at it and update parsing context.
  * Normal return is 0. Syntax errors return 1.
@@ -4747,6 +4882,21 @@ static int done_word(o_string *word, struct parse_context *ctx)
                                                (ctx->ctx_res_w == RES_SNTX));
                                return (ctx->ctx_res_w == RES_SNTX);
                        }
+# ifdef CMD_SINGLEWORD_NOGLOB_COND
+                       if (strcmp(word->data, "export") == 0
+#  if ENABLE_HUSH_LOCAL
+                        || strcmp(word->data, "local") == 0
+#  endif
+                       ) {
+                               command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
+                       } else
+# endif
+# if ENABLE_HUSH_BASH_COMPAT
+                       if (strcmp(word->data, "[[") == 0) {
+                               command->cmd_type = CMD_SINGLEWORD_NOGLOB;
+                       }
+                       /* fall through */
+# endif
                }
 #endif
                if (command->group) {
@@ -5025,7 +5175,7 @@ static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_
                                        char *p;
 
                                        redir->rd_type = REDIRECT_HEREDOC2;
-                                       /* redir->dup is (ab)used to indicate <<- */
+                                       /* redir->rd_dup is (ab)used to indicate <<- */
                                        p = fetch_till_str(&ctx->as_string, input,
                                                redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
                                        if (!p) {
@@ -5056,9 +5206,9 @@ static FILE *generate_stream_from_string(const char *s)
 {
        FILE *pf;
        int pid, channel[2];
-#if !BB_MMU
+# if !BB_MMU
        char **to_free;
-#endif
+# endif
 
        xpipe(channel);
        pid = BB_MMU ? fork() : vfork();
@@ -5076,15 +5226,57 @@ static FILE *generate_stream_from_string(const char *s)
                        + (1 << SIGTTIN)
                        + (1 << SIGTTOU)
                        , SIG_IGN);
+               CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
                close(channel[0]); /* NB: close _first_, then move fd! */
                xmove_fd(channel[1], 1);
                /* Prevent it from trying to handle ctrl-z etc */
                IF_HUSH_JOB(G.run_list_level = 1;)
-#if BB_MMU
+               /* Awful hack for `trap` or $(trap).
+                *
+                * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
+                * contains an example where "trap" is executed in a subshell:
+                *
+                * save_traps=$(trap)
+                * ...
+                * eval "$save_traps"
+                *
+                * Standard does not say that "trap" in subshell shall print
+                * parent shell's traps. It only says that its output
+                * must have suitable form, but then, in the above example
+                * (which is not supposed to be normative), it implies that.
+                *
+                * bash (and probably other shell) does implement it
+                * (traps are reset to defaults, but "trap" still shows them),
+                * but as a result, "trap" logic is hopelessly messed up:
+                *
+                * # trap
+                * trap -- 'echo Ho' SIGWINCH  <--- we have a handler
+                * # (trap)        <--- trap is in subshell - no output (correct, traps are reset)
+                * # true | trap   <--- trap is in subshell - no output (ditto)
+                * # echo `true | trap`    <--- in subshell - output (but traps are reset!)
+                * trap -- 'echo Ho' SIGWINCH
+                * # echo `(trap)`         <--- in subshell in subshell - output
+                * trap -- 'echo Ho' SIGWINCH
+                * # echo `true | (trap)`  <--- in subshell in subshell in subshell - output!
+                * trap -- 'echo Ho' SIGWINCH
+                *
+                * The rules when to forget and when to not forget traps
+                * get really complex and nonsensical.
+                *
+                * Our solution: ONLY bare $(trap) or `trap` is special.
+                */
+               s = skip_whitespace(s);
+               if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
+               {
+                       static const char *const argv[] = { NULL, NULL };
+                       builtin_trap((char**)argv);
+                       exit(0); /* not _exit() - we need to fflush */
+               }
+# if BB_MMU
                reset_traps_to_defaults();
                parse_and_run_string(s);
                _exit(G.last_exitcode);
-#else
+# else
        /* We re-execute after vfork on NOMMU. This makes this script safe:
         * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
         * huge=`cat BIG` # was blocking here forever
@@ -5095,18 +5287,18 @@ static FILE *generate_stream_from_string(const char *s)
                                G.global_argv[0],
                                G.global_argv + 1,
                                NULL);
-#endif
+# endif
        }
 
        /* parent */
-#if ENABLE_HUSH_FAST
+# if ENABLE_HUSH_FAST
        G.count_SIGCHLD++;
 //bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
-#endif
+# endif
        enable_restore_tty_pgrp_on_exit();
-#if !BB_MMU
+# if !BB_MMU
        free(to_free);
-#endif
+# endif
        close(channel[1]);
        pf = fdopen(channel[0], "r");
        return pf;
@@ -5150,7 +5342,7 @@ static int process_command_subs(o_string *dest, const char *s)
        debug_printf("closed FILE from child. return 0\n");
        return 0;
 }
-#endif
+#endif /* ENABLE_HUSH_TICK */
 
 static int parse_group(o_string *dest, struct parse_context *ctx,
        struct in_str *input, int ch)
@@ -5191,7 +5383,7 @@ static int parse_group(o_string *dest, struct parse_context *ctx,
                        return 1;
                }
                nommu_addchr(&ctx->as_string, ch);
-               command->grp_type = GRP_FUNCTION;
+               command->cmd_type = CMD_FUNCDEF;
                goto skip;
        }
 #endif
@@ -5211,7 +5403,7 @@ static int parse_group(o_string *dest, struct parse_context *ctx,
        endch = '}';
        if (ch == '(') {
                endch = ')';
-               command->grp_type = GRP_SUBSHELL;
+               command->cmd_type = CMD_SUBSHELL;
        } else {
                /* bash does not allow "{echo...", requires whitespace */
                ch = i_getch(input);
@@ -5518,7 +5710,7 @@ static int handle_dollar(o_string *as_string,
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
                break;
        }
-#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
+#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
        case '(': {
 # if !BB_MMU
                int pos;
@@ -5573,8 +5765,10 @@ static int handle_dollar(o_string *as_string,
                        goto make_var;
                }
                /* else: it's $_ */
-       /* TODO: */
-       /* $_ Shell or shell script name; or last cmd name */
+       /* TODO: $_ and $-: */
+       /* $_ Shell or shell script name; or last argument of last command
+        * (if last command wasn't a pipe; if it was, bash sets $_ to "");
+        * but in command's env, set to full pathname used to invoke it */
        /* $- Option flags set by set builtin or shell options (-i etc) */
        default:
                o_addQchr(dest, '$');
@@ -5614,7 +5808,7 @@ static int parse_stream_dquoted(o_string *as_string,
        if (ch != '\n') {
                next = i_peek(input);
        }
-       debug_printf_parse(": ch=%c (%d) escape=%d\n",
+       debug_printf_parse("\" ch=%c (%d) escape=%d\n",
                                        ch, ch, dest->o_escape);
        if (ch == '\\') {
                if (next == EOF) {
@@ -5691,9 +5885,14 @@ static struct pipe *parse_stream(char **pstring,
         * found.  When recursing, quote state is passed in via dest->o_escape.
         */
        debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
-                       end_trigger ? : 'X');
+                       end_trigger ? end_trigger : 'X');
        debug_enter();
 
+       /* If very first arg is "" or '', dest.data may end up NULL.
+        * Preventing this: */
+       o_addchr(&dest, '\0');
+       dest.length = 0;
+
        G.ifs = get_local_var_value("IFS");
        if (G.ifs == NULL)
                G.ifs = " \t\n";
@@ -5945,6 +6144,8 @@ static struct pipe *parse_stream(char **pstring,
                        dest.o_assignment = NOT_ASSIGNMENT;
                }
 
+               /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
+
                switch (ch) {
                case '#':
                        if (dest.length == 0) {
@@ -5968,13 +6169,19 @@ static struct pipe *parse_stream(char **pstring,
                        ch = i_getch(input);
                        if (ch != '\n') {
                                o_addchr(&dest, '\\');
-                               nommu_addchr(&ctx.as_string, '\\');
+                               /*nommu_addchr(&ctx.as_string, '\\'); - already done */
                                o_addchr(&dest, ch);
                                nommu_addchr(&ctx.as_string, ch);
                                /* Example: echo Hello \2>file
                                 * we need to know that word 2 is quoted */
                                dest.o_quoted = 1;
                        }
+#if !BB_MMU
+                       else {
+                               /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
+                               ctx.as_string.data[--ctx.as_string.length] = '\0';
+                       }
+#endif
                        break;
                case '$':
                        if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
@@ -6122,10 +6329,8 @@ static struct pipe *parse_stream(char **pstring,
                IF_HAS_KEYWORDS(struct parse_context *p2;)
 
                /* Clean up allocated tree.
-                * Samples for finding leaks on syntax error recovery path.
-                * Run them from interactive shell, watch pmap `pidof hush`.
-                * while if false; then false; fi do break; done
-                * (bash accepts it)
+                * Sample for finding leaks on syntax error recovery path.
+                * Run it from interactive shell, watch pmap `pidof hush`.
                 * while if false; then false; fi; do break; fi
                 * Samples to catch leaks at execution:
                 * while if (true | {true;}); then echo ok; fi; do break; done
@@ -6334,8 +6539,49 @@ int hush_main(int argc, char **argv)
                }
                e++;
        }
+       /* reinstate HUSH_VERSION */
        debug_printf_env("putenv '%s'\n", hush_version_str);
-       putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
+       putenv((char *)hush_version_str);
+
+       /* Export PWD */
+       set_pwd_var(/*exp:*/ 1);
+       /* bash also exports SHLVL and _,
+        * and sets (but doesn't export) the following variables:
+        * BASH=/bin/bash
+        * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
+        * BASH_VERSION='3.2.0(1)-release'
+        * HOSTTYPE=i386
+        * MACHTYPE=i386-pc-linux-gnu
+        * OSTYPE=linux-gnu
+        * HOSTNAME=<xxxxxxxxxx>
+        * PPID=<NNNNN> - we also do it elsewhere
+        * EUID=<NNNNN>
+        * UID=<NNNNN>
+        * GROUPS=()
+        * LINES=<NNN>
+        * COLUMNS=<NNN>
+        * BASH_ARGC=()
+        * BASH_ARGV=()
+        * BASH_LINENO=()
+        * BASH_SOURCE=()
+        * DIRSTACK=()
+        * PIPESTATUS=([0]="0")
+        * HISTFILE=/<xxx>/.bash_history
+        * HISTFILESIZE=500
+        * HISTSIZE=500
+        * MAILCHECK=60
+        * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
+        * SHELL=/bin/bash
+        * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
+        * TERM=dumb
+        * OPTERR=1
+        * OPTIND=1
+        * IFS=$' \t\n'
+        * PS1='\s-\v\$ '
+        * PS2='> '
+        * PS4='+ '
+        */
+
 #if ENABLE_FEATURE_EDITING
        G.line_input_state = new_line_input_t(FOR_SHELL);
 #endif
@@ -6363,7 +6609,7 @@ int hush_main(int argc, char **argv)
        /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
        builtin_argc = 0;
        while (1) {
-               opt = getopt(argc, argv, "c:xins"
+               opt = getopt(argc, argv, "+c:xins"
 #if !BB_MMU
                                "<:$:R:V:"
 # if ENABLE_HUSH_FUNCTIONS
@@ -6385,8 +6631,10 @@ int hush_main(int argc, char **argv)
                         * Note: this form never happens:
                         * sh ... -c 'builtin' [BARGV...] ""
                         */
-                       if (!G.root_pid)
+                       if (!G.root_pid) {
                                G.root_pid = getpid();
+                               G.root_ppid = getppid();
+                       }
                        G.global_argv = argv + optind;
                        G.global_argc = argc - optind;
                        if (builtin_argc) {
@@ -6428,6 +6676,8 @@ int hush_main(int argc, char **argv)
                case '$':
                        G.root_pid = bb_strtou(optarg, &optarg, 16);
                        optarg++;
+                       G.root_ppid = bb_strtou(optarg, &optarg, 16);
+                       optarg++;
                        G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
                        optarg++;
                        G.last_exitcode = bb_strtou(optarg, &optarg, 16);
@@ -6468,8 +6718,10 @@ int hush_main(int argc, char **argv)
                }
        } /* option parsing loop */
 
-       if (!G.root_pid)
+       if (!G.root_pid) {
                G.root_pid = getpid();
+               G.root_ppid = getppid();
+       }
 
        /* If we are login shell... */
        if (argv[0] && argv[0][0] == '-') {
@@ -6614,10 +6866,13 @@ int hush_main(int argc, char **argv)
         */
 
        if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
-               printf("\n\n%s hush - the humble shell\n", bb_banner);
-               if (ENABLE_HUSH_HELP)
-                       puts("Enter 'help' for a list of built-in commands.");
-               puts("");
+               /* note: ash and hush share this string */
+               printf("\n\n%s %s\n"
+                       IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
+                       "\n",
+                       bb_banner,
+                       "hush - the humble shell"
+               );
        }
 
        parse_and_run_file(stdin);
@@ -6643,7 +6898,16 @@ int hush_main(int argc, char **argv)
 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 int lash_main(int argc, char **argv)
 {
-       //bb_error_msg("lash is deprecated, please use hush instead");
+       bb_error_msg("lash is deprecated, please use hush instead");
+       return hush_main(argc, argv);
+}
+#endif
+
+#if ENABLE_MSH
+int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int msh_main(int argc, char **argv)
+{
+       //bb_error_msg("msh is deprecated, please use hush instead");
        return hush_main(argc, argv);
 }
 #endif
@@ -6657,26 +6921,33 @@ static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
        return 0;
 }
 
-static int FAST_FUNC builtin_test(char **argv)
+static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
 {
        int argc = 0;
        while (*argv) {
                argc++;
                argv++;
        }
-       return test_main(argc, argv - argc);
+       return applet_main_func(argc, argv - argc);
+}
+
+static int FAST_FUNC builtin_test(char **argv)
+{
+       return run_applet_main(argv, test_main);
 }
 
 static int FAST_FUNC builtin_echo(char **argv)
 {
-       int argc = 0;
-       while (*argv) {
-               argc++;
-               argv++;
-       }
-       return echo_main(argc, argv - argc);
+       return run_applet_main(argv, echo_main);
 }
 
+#if ENABLE_PRINTF
+static int FAST_FUNC builtin_printf(char **argv)
+{
+       return run_applet_main(argv, printf_main);
+}
+#endif
+
 static int FAST_FUNC builtin_eval(char **argv)
 {
        int rcode = EXIT_SUCCESS;
@@ -6702,14 +6973,19 @@ static int FAST_FUNC builtin_cd(char **argv)
                 * bash says "bash: cd: HOME not set" and does nothing
                 * (exitcode 1)
                 */
-               newdir = get_local_var_value("HOME") ? : "/";
+               const char *home = get_local_var_value("HOME");
+               newdir = home ? home : "/";
        }
        if (chdir(newdir)) {
                /* Mimic bash message exactly */
                bb_perror_msg("cd: %s", newdir);
                return EXIT_FAILURE;
        }
-       get_cwd(1);
+       /* Read current dir (get_cwd(1) is inside) and set PWD.
+        * Note: do not enforce exporting. If PWD was unset or unexported,
+        * set it again, but do not export. bash does the same.
+        */
+       set_pwd_var(/*exp:*/ 0);
        return EXIT_SUCCESS;
 }
 
@@ -6717,14 +6993,17 @@ static int FAST_FUNC builtin_exec(char **argv)
 {
        if (*++argv == NULL)
                return EXIT_SUCCESS; /* bash does this */
-       {
-#if !BB_MMU
-               nommu_save_t dummy;
-#endif
-               /* TODO: if exec fails, bash does NOT exit! We do... */
-               pseudo_exec_argv(&dummy, argv, 0, NULL);
-               /* never returns */
-       }
+
+       /* Careful: we can end up here after [v]fork. Do not restore
+        * tty pgrp then, only top-level shell process does that */
+       if (G_saved_tty_pgrp && getpid() == G.root_pid)
+               tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
+
+       /* TODO: if exec fails, bash does NOT exit! We do.
+        * We'll need to undo sigprocmask (it's inside execvp_or_die)
+        * and tcsetpgrp, and this is inherently racy.
+        */
+       execvp_or_die(argv);
 }
 
 static int FAST_FUNC builtin_exit(char **argv)
@@ -6895,6 +7174,10 @@ static int FAST_FUNC builtin_trap(char **argv)
                        if (G.traps[i]) {
                                printf("trap -- ");
                                print_escaped(G.traps[i]);
+                               /* note: bash adds "SIG", but only if invoked
+                                * as "bash". If called as "sh", or if set -o posix,
+                                * then it prints short signal names.
+                                * We are printing short names: */
                                printf(" %s\n", get_signame(i));
                        }
                }
@@ -7106,6 +7389,10 @@ static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
        void *p;
        unsigned long l;
 
+# ifdef M_TRIM_THRESHOLD
+       /* Optional. Reduces probability of false positives */
+       malloc_trim(0);
+# endif
        /* Crude attempt to find where "free memory" starts,
         * sans fragmentation. */
        p = malloc(240);
@@ -7117,7 +7404,7 @@ static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
 
        if (!G.memleak_value)
                G.memleak_value = l;
-       
+
        l -= G.memleak_value;
        if ((long)l < 0)
                l = 0;