pointless whitespace/comment fixes, no code changes
[oweals/busybox.git] / shell / hush.c
index 0bddc92130ed487ae158261606e012dd708da1b7..b6e49db99f9b5a13989359ac11af27966e24dcfe 100644 (file)
@@ -5,7 +5,8 @@
  * "small and simple is beautiful" philosophy, which
  * incidentally is a good match to today's BusyBox.
  *
- * Copyright (C) 2000,2001  Larry Doolittle  <larry@doolittle.boa.org>
+ * Copyright (C) 2000,2001  Larry Doolittle <larry@doolittle.boa.org>
+ * Copyright (C) 2008,2009  Denys Vlasenko <vda.linux@googlemail.com>
  *
  * Credits:
  *      The parser routines proper are all original material, first
@@ -20,8 +21,8 @@
  *      rewrites.
  *
  * Other credits:
- *      o_addchr() derived from similar w_addchar function in glibc-2.2.
- *      setup_redirect(), redirect_opt_num(), and big chunks of main()
+ *      o_addchr derived from similar w_addchar function in glibc-2.2.
+ *      parse_redirect, redirect_opt_num, and big chunks of main
  *      and many builtins derived from contributions by Erik Andersen.
  *      Miscellaneous bugfixes from Matt Kraai.
  *
  *
  * POSIX syntax not implemented:
  *      aliases
- *      Arithmetic Expansion
  *      <(list) and >(list) Process Substitution
- *      Here Documents ( << word )
- *      Functions
  *      Tilde Expansion
- *      Parameter Expansion for substring processing ${var#word} ${var%word}
  *
- * Bash stuff maybe optional enable:
+ * Bash stuff (maybe optionally enable?):
  *      &> and >& redirection of stdout+stderr
  *      Brace expansion
  *      reserved words: [[ ]] function select
  *      substrings ${var:1:5}
  *
- * Major bugs:
- *      job handling woefully incomplete and buggy (improved --vda)
- * to-do:
- *      port selected bugfixes from post-0.49 busybox lash - done?
+ * TODOs:
+ *      grep for "TODO" and fix (some of them are easy)
  *      change { and } from special chars to reserved words
- *      builtins: return, trap, ulimit
- *      test magic exec with redirection only
+ *      builtins: return, ulimit
  *      follow IFS rules more precisely, including update semantics
  *      figure out what to do with backslash-newline
- *      propagate syntax errors, die on resource errors?
  *      continuation lines, both explicit and implicit - done?
- *      maybe change charmap[] to use 2-bit entries
+ *      SIGHUP handling
+ *      ^Z handling (and explain it in comments for mere humans)
+ *      separate job control from interactiveness
+ *      (testcase: booting with init=/bin/hush does not show prompt (2009-04))
  *
  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  */
-
 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
-//TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
-//#include "applet_tables.h" doesn't work
 #include <glob.h>
 /* #include <dmalloc.h> */
 #if ENABLE_HUSH_CASE
-#include <fnmatch.h>
+# include <fnmatch.h>
 #endif
-
 #include "math.h"
+#include "match.h"
+#ifndef PIPE_BUF
+# define PIPE_BUF 4096           /* amount of buffering in a pipe */
+#endif
 
-#define HUSH_VER_STR "0.92"
 
-#if defined SINGLE_APPLET_MAIN
-/* STANDALONE does not make sense, and won't compile */
-#undef CONFIG_FEATURE_SH_STANDALONE
-#undef ENABLE_FEATURE_SH_STANDALONE
-#undef USE_FEATURE_SH_STANDALONE
-#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
-#define ENABLE_FEATURE_SH_STANDALONE 0
-#define USE_FEATURE_SH_STANDALONE(...)
-#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
+/* Debug build knobs */
+#define LEAK_HUNTING 0
+#define BUILD_AS_NOMMU 0
+/* Enable/disable sanity checks. Ok to enable in production,
+ * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
+ * Keeping 1 for now even in released versions.
+ */
+#define HUSH_DEBUG 1
+
+
+#if BUILD_AS_NOMMU
+# undef BB_MMU
+# undef USE_FOR_NOMMU
+# undef USE_FOR_MMU
+# define BB_MMU 0
+# define USE_FOR_NOMMU(...) __VA_ARGS__
+# define USE_FOR_MMU(...)
 #endif
 
-#if !BB_MMU && ENABLE_HUSH_TICK
-//#undef ENABLE_HUSH_TICK
-//#define ENABLE_HUSH_TICK 0
-#warning On NOMMU, hush command substitution is dangerous.
-#warning Dont use it for commands which produce lots of output.
-#warning For more info see shell/hush.c, generate_stream_from_list().
+#if defined SINGLE_APPLET_MAIN
+/* STANDALONE does not make sense, and won't compile */
+# undef CONFIG_FEATURE_SH_STANDALONE
+# undef ENABLE_FEATURE_SH_STANDALONE
+# undef USE_FEATURE_SH_STANDALONE
+# define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
+# define ENABLE_FEATURE_SH_STANDALONE 0
+# define USE_FEATURE_SH_STANDALONE(...)
+# define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
 #endif
 
 #if !ENABLE_HUSH_INTERACTIVE
-#undef ENABLE_FEATURE_EDITING
-#define ENABLE_FEATURE_EDITING 0
-#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
-#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
+# undef ENABLE_FEATURE_EDITING
+# define ENABLE_FEATURE_EDITING 0
+# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
+# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
 #endif
 
 /* Do we support ANY keywords? */
 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
-#define HAS_KEYWORDS 1
-#define IF_HAS_KEYWORDS(...) __VA_ARGS__
-#define IF_HAS_NO_KEYWORDS(...)
+# define HAS_KEYWORDS 1
+# define IF_HAS_KEYWORDS(...) __VA_ARGS__
+# define IF_HAS_NO_KEYWORDS(...)
 #else
-#define HAS_KEYWORDS 0
-#define IF_HAS_KEYWORDS(...)
-#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
+# define HAS_KEYWORDS 0
+# define IF_HAS_KEYWORDS(...)
+# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
 #endif
 
-/* Keep unconditionally on for now */
-#define HUSH_DEBUG 1
-/* In progress... */
-#define ENABLE_HUSH_FUNCTIONS 0
-
-
 /* If you comment out one of these below, it will be #defined later
  * to perform debug printfs to stderr: */
 #define debug_printf(...)        do {} while (0)
 #define debug_printf_subst(...)  do {} while (0)
 #define debug_printf_clean(...)  do {} while (0)
 
-#ifndef debug_printf
-#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#ifndef debug_printf_parse
-#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#ifndef debug_printf_exec
-#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#ifndef debug_printf_env
-#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#ifndef debug_printf_jobs
-#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
-#define DEBUG_JOBS 1
-#else
-#define DEBUG_JOBS 0
-#endif
-
-#ifndef debug_printf_expand
-#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
-#define DEBUG_EXPAND 1
-#else
-#define DEBUG_EXPAND 0
-#endif
-
-#ifndef debug_printf_glob
-#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
-#define DEBUG_GLOB 1
-#else
-#define DEBUG_GLOB 0
-#endif
+#define ERR_PTR ((void*)(long)1)
 
-#ifndef debug_printf_list
-#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
-#endif
+#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
 
-#ifndef debug_printf_subst
-#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
-#endif
+#define SPECIAL_VAR_SYMBOL 3
 
-#ifndef debug_printf_clean
-/* broken, of course, but OK for testing */
-static const char *indenter(int i)
-{
-       static const char blanks[] ALIGN1 =
-               "                                    ";
-       return &blanks[sizeof(blanks) - i - 1];
-}
-#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
-#define DEBUG_CLEAN 1
-#endif
+static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
 
-#if DEBUG_EXPAND
-static void debug_print_strings(const char *prefix, char **vv)
-{
-       fprintf(stderr, "%s:\n", prefix);
-       while (*vv)
-               fprintf(stderr, " '%s'\n", *vv++);
-}
-#else
-#define debug_print_strings(prefix, vv) ((void)0)
-#endif
-
-/*
- * Leak hunting. Use hush_leaktool.sh for post-processing.
+/* This supports saving pointers malloced in vfork child,
+ * to be freed in the parent. One pointer is saved in
+ * G.argv_from_re_execing global var instead. TODO: unify.
  */
-#ifdef FOR_HUSH_LEAKTOOL
-/* suppress "warning: no previous prototype..." */
-void *xxmalloc(int lineno, size_t size);
-void *xxrealloc(int lineno, void *ptr, size_t size);
-char *xxstrdup(int lineno, const char *str);
-void xxfree(void *ptr);
-void *xxmalloc(int lineno, size_t size)
-{
-       void *ptr = xmalloc((size + 0xff) & ~0xff);
-       fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
-       return ptr;
-}
-void *xxrealloc(int lineno, void *ptr, size_t size)
-{
-       ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
-       fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
-       return ptr;
-}
-char *xxstrdup(int lineno, const char *str)
-{
-       char *ptr = xstrdup(str);
-       fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
-       return ptr;
-}
-void xxfree(void *ptr)
-{
-       fprintf(stderr, "free %p\n", ptr);
-       free(ptr);
-}
-#define xmalloc(s)     xxmalloc(__LINE__, s)
-#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
-#define xstrdup(s)     xxstrdup(__LINE__, s)
-#define free(p)        xxfree(p)
+#if !BB_MMU
+typedef struct nommu_save_t {
+       char **new_env;
+       char **old_env;
+       char **argv;
+} nommu_save_t;
 #endif
 
-
-static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
-
-#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
-
-#define SPECIAL_VAR_SYMBOL       3
-#define PARSEFLAG_EXIT_FROM_LOOP 1
-
-typedef enum redir_type {
-       REDIRECT_INPUT     = 1,
-       REDIRECT_OVERWRITE = 2,
-       REDIRECT_APPEND    = 3,
-       REDIRECT_HEREIS    = 4,
-       REDIRECT_IO        = 5
-} redir_type;
-
 /* The descrip member of this structure is only used to make
  * debugging output pretty */
 static const struct {
@@ -267,21 +165,16 @@ static const struct {
        signed char default_fd;
        char descrip[3];
 } redir_table[] = {
-       { 0,                         0, "()" },
+       { 0,                         0, "??" },
        { O_RDONLY,                  0, "<"  },
        { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
        { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
-       { O_RDONLY,                 -1, "<<" },
-       { O_RDWR,                    1, "<>" }
+       { O_RDONLY,                  0, "<<" },
+       { O_CREAT|O_RDWR,            1, "<>" },
+/* Should not be needed. Bogus default_fd helps in debugging */
+/*     { O_RDONLY,                 77, "<<" }, */
 };
 
-typedef enum pipe_style {
-       PIPE_SEQ = 1,
-       PIPE_AND = 2,
-       PIPE_OR  = 3,
-       PIPE_BG  = 4,
-} pipe_style;
-
 typedef enum reserved_style {
        RES_NONE  = 0,
 #if ENABLE_HUSH_IF
@@ -312,39 +205,124 @@ typedef enum reserved_style {
        RES_SNTX
 } reserved_style;
 
+typedef struct o_string {
+       char *data;
+       int length; /* position where data is appended */
+       int maxlen;
+       /* Protect newly added chars against globbing
+        * (by prepending \ to *, ?, [, \) */
+       smallint o_escape;
+       smallint o_glob;
+       /* At least some part of the string was inside '' or "",
+        * possibly empty one: word"", wo''rd etc. */
+       smallint o_quoted;
+       smallint has_empty_slot;
+       smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
+} o_string;
+enum {
+       MAYBE_ASSIGNMENT = 0,
+       DEFINITELY_ASSIGNMENT = 1,
+       NOT_ASSIGNMENT = 2,
+       WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
+};
+/* Used for initialization: o_string foo = NULL_O_STRING; */
+#define NULL_O_STRING { NULL }
+
+/* I can almost use ordinary FILE*.  Is open_memstream() universally
+ * available?  Where is it documented? */
+typedef struct in_str {
+       const char *p;
+       /* eof_flag=1: last char in ->p is really an EOF */
+       char eof_flag; /* meaningless if ->p == NULL */
+       char peek_buf[2];
+#if ENABLE_HUSH_INTERACTIVE
+       smallint promptme;
+       smallint promptmode; /* 0: PS1, 1: PS2 */
+#endif
+       FILE *file;
+       int (*get) (struct in_str *);
+       int (*peek) (struct in_str *);
+} in_str;
+#define i_getch(input) ((input)->get(input))
+#define i_peek(input) ((input)->peek(input))
+
 struct redir_struct {
        struct redir_struct *next;
        char *rd_filename;          /* filename */
-       int fd;                     /* file descriptor being redirected */
-       int dup;                    /* -1, or file descriptor being duplicated */
-       smallint /*enum redir_type*/ rd_type;
+       int rd_fd;                  /* fd to redirect */
+       /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
+       int rd_dup;
+       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) ?
+        */
 };
+typedef enum redir_type {
+       REDIRECT_INVALID   = 0,
+       REDIRECT_INPUT     = 1,
+       REDIRECT_OVERWRITE = 2,
+       REDIRECT_APPEND    = 3,
+       REDIRECT_HEREDOC   = 4,
+       REDIRECT_IO        = 5,
+       REDIRECT_HEREDOC2  = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
+
+       REDIRFD_CLOSE      = -3,
+       REDIRFD_SYNTAX_ERR = -2,
+       REDIRFD_TO_FILE    = -1,
+       /* otherwise, rd_fd is redirected to rd_dup */
+
+       HEREDOC_SKIPTABS = 1,
+       HEREDOC_QUOTED   = 2,
+} redir_type;
+
 
 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 */
-       struct pipe *group;         /* if non-NULL, this "prog" is {} group,
-                                    * subshell, or a compound statement */
+#define GRP_NORMAL   0
+#define GRP_SUBSHELL 1
+#if ENABLE_HUSH_FUNCTIONS
+# define GRP_FUNCTION 2
+#endif
+       struct pipe *group;         /* if non-NULL, this "command" is { list },
+                                    * ( list ), or a compound statement */
+#if !BB_MMU
+       char *group_as_string;
+#endif
+#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
+ * 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",
+ * 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.
+ * Without this trick, loop would execute a;b;b;b;...
+ * instead of correct sequence a;b;a;b;...
+ * When command is freed, it severs the link
+ * (sets ->child_func->parent_cmd to NULL).
+ */
+#endif
        char **argv;                /* command name and arguments */
-       struct redir_struct *redirects; /* I/O redirections */
-};
 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  * and on execution these are substituted with their values.
  * Substitution can make _several_ words out of one argv[n]!
  * Example: argv[0]=='.^C*^C.' here: echo .$*.
  * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  */
-#define GRP_NORMAL   0
-#define GRP_SUBSHELL 1
-#if ENABLE_HUSH_FUNCTIONS
-#define GRP_FUNCTION 2
-#endif
+       struct redir_struct *redirects; /* I/O redirections */
+};
 
 struct pipe {
        struct pipe *next;
-       int num_cmds;               /* total number of commands in job */
+       int num_cmds;               /* total number of commands in pipe */
        int alive_cmds;             /* number of commands running (not exited) */
        int stopped_cmds;           /* number of commands alive, but stopped */
 #if ENABLE_HUSH_JOB
@@ -357,20 +335,43 @@ struct pipe {
        IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
        IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
 };
+typedef enum pipe_style {
+       PIPE_SEQ = 1,
+       PIPE_AND = 2,
+       PIPE_OR  = 3,
+       PIPE_BG  = 4,
+} pipe_style;
 
 /* This holds pointers to the various results of parsing */
 struct parse_context {
-       struct command *command;
+       /* linked list of pipes */
        struct pipe *list_head;
+       /* last pipe (being constructed right now) */
        struct pipe *pipe;
+       /* last command in pipe (being constructed right now) */
+       struct command *command;
+       /* last redirect in command->redirects list */
        struct redir_struct *pending_redirect;
+#if !BB_MMU
+       o_string as_string;
+#endif
 #if HAS_KEYWORDS
        smallint ctx_res_w;
        smallint ctx_inverted; /* "! cmd | cmd" */
 #if ENABLE_HUSH_CASE
        smallint ctx_dsemicolon; /* ";;" seen */
 #endif
-       int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
+       /* bitmask of FLAG_xxx, for figuring out valid reserved words */
+       int old_flag;
+       /* group we are enclosed in:
+        * example: "if pipe1; pipe2; then pipe3; fi"
+        * when we see "if" or "then", we malloc and copy current context,
+        * and make ->stack point to it. then we parse pipeN.
+        * when closing "then" / fi" / whatever is found,
+        * we move list_head into ->stack->command->group,
+        * copy ->stack into current context, and delete ->stack.
+        * (parsing of { list } and ( list ) doesn't use this method)
+        */
        struct parse_context *stack;
 #endif
 };
@@ -389,56 +390,22 @@ struct variable {
        smallint flg_read_only;
 };
 
-typedef struct o_string {
-       char *data;
-       int length; /* position where data is appended */
-       int maxlen;
-       /* Misnomer! it's not "quoting", it's "protection against globbing"!
-        * (by prepending \ to *, ?, [ and to \ too) */
-       smallint o_quote;
-       smallint o_glob;
-       smallint nonnull;
-       smallint has_empty_slot;
-       smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
-} o_string;
 enum {
-       MAYBE_ASSIGNMENT = 0,
-       DEFINITELY_ASSIGNMENT = 1,
-       NOT_ASSIGNMENT = 2,
-       WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
+       BC_BREAK = 1,
+       BC_CONTINUE = 2,
 };
-/* Used for initialization: o_string foo = NULL_O_STRING; */
-#define NULL_O_STRING { NULL }
 
-/* I can almost use ordinary FILE*.  Is open_memstream() universally
- * available?  Where is it documented? */
-typedef struct in_str {
-       const char *p;
-       /* eof_flag=1: last char in ->p is really an EOF */
-       char eof_flag; /* meaningless if ->p == NULL */
-       char peek_buf[2];
-#if ENABLE_HUSH_INTERACTIVE
-       smallint promptme;
-       smallint promptmode; /* 0: PS1, 1: PS2 */
+#if ENABLE_HUSH_FUNCTIONS
+struct function {
+       struct function *next;
+       char *name;
+       struct command *parent_cmd;
+       struct pipe *body;
+#if !BB_MMU
+       char *body_as_string;
 #endif
-       FILE *file;
-       int (*get) (struct in_str *);
-       int (*peek) (struct in_str *);
-} in_str;
-#define i_getch(input) ((input)->get(input))
-#define i_peek(input) ((input)->peek(input))
-
-enum {
-       CHAR_ORDINARY           = 0,
-       CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
-       CHAR_IFS                = 2, /* treated as ordinary if quoted */
-       CHAR_SPECIAL            = 3, /* \, $, ", maybe ` */
-};
-
-enum {
-       BC_BREAK = 1,
-       BC_CONTINUE = 2,
 };
+#endif
 
 
 /* "Globals" within this file */
@@ -450,6 +417,9 @@ struct globals {
        int interactive_fd;
        const char *PS1;
        const char *PS2;
+#define G_interactive_fd (G.interactive_fd)
+#else
+#define G_interactive_fd 0
 #endif
 #if ENABLE_FEATURE_EDITING
        line_input_t *line_input_state;
@@ -469,13 +439,18 @@ struct globals {
        smallint flag_break_continue;
 #endif
        smallint fake_mode;
+       smallint exiting; /* used to prevent EXIT trap recursion */
        /* These four support $?, $#, and $1 */
-       smalluint last_return_code;
-       /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
+       smalluint last_exitcode;
+       /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
        smalluint global_args_malloced;
        /* how many non-NULL argv's we have. NB: $# + 1 */
        int global_argc;
        char **global_argv;
+#if !BB_MMU
+       char *argv0_for_re_execing;
+       char **argv_from_re_execing;
+#endif
 #if ENABLE_HUSH_LOOPS
        unsigned depth_break_continue;
        unsigned depth_of_loop;
@@ -484,14 +459,9 @@ struct globals {
        const char *cwd;
        struct variable *top_var; /* = &G.shell_ver (set in main()) */
        struct variable shell_ver;
-#if ENABLE_FEATURE_SH_STANDALONE
-       struct nofork_save_area nofork_save;
-#endif
-#if ENABLE_HUSH_JOB
-       sigjmp_buf toplevel_jb;
+#if ENABLE_HUSH_FUNCTIONS
+       struct function *top_func;
 #endif
-       unsigned char charmap[256];
-       char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
        /* Signal and trap handling */
 //     unsigned count_SIGCHLD;
 //     unsigned handled_SIGCHLD;
@@ -500,6 +470,17 @@ struct globals {
        char **traps; /* char *traps[NSIG] */
        sigset_t blocked_set;
        sigset_t inherited_set;
+#if HUSH_DEBUG
+       unsigned long memleak_value;
+       int debug_indent;
+#endif
+       char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
+#if ENABLE_FEATURE_SH_STANDALONE
+       struct nofork_save_area nofork_save;
+#endif
+#if ENABLE_HUSH_JOB
+       sigjmp_buf toplevel_jb;
+#endif
 };
 #define G (*ptr_to_globals)
 /* Not #defining name to G.name - this quickly gets unwieldy
@@ -524,14 +505,17 @@ static int builtin_jobs(char **argv);
 #if ENABLE_HUSH_HELP
 static int builtin_help(char **argv);
 #endif
+#if HUSH_DEBUG
+static int builtin_memleak(char **argv);
+#endif
 static int builtin_pwd(char **argv);
 static int builtin_read(char **argv);
-static int builtin_test(char **argv);
-static int builtin_trap(char **argv);
-static int builtin_true(char **argv);
 static int builtin_set(char **argv);
 static int builtin_shift(char **argv);
 static int builtin_source(char **argv);
+static int builtin_test(char **argv);
+static int builtin_trap(char **argv);
+static int builtin_true(char **argv);
 static int builtin_umask(char **argv);
 static int builtin_unset(char **argv);
 static int builtin_wait(char **argv);
@@ -539,7 +523,6 @@ static int builtin_wait(char **argv);
 static int builtin_break(char **argv);
 static int builtin_continue(char **argv);
 #endif
-//static int builtin_not_written(char **argv);
 
 /* Table of built-in functions.  They can be forked or not, depending on
  * context: within pipes, they fork.  As simple commands, they do not.
@@ -561,66 +544,249 @@ struct built_in_command {
 /* For now, echo and test are unconditionally enabled.
  * Maybe make it configurable? */
 static const struct built_in_command bltins[] = {
-       BLTIN("."     , builtin_source, "Run commands in a file"),
-       BLTIN(":"     , builtin_true, "No-op"),
-       BLTIN("["     , builtin_test, "Test condition"),
+       BLTIN("."       , builtin_source  , "Run commands in a file"),
+       BLTIN(":"       , builtin_true    , "No-op"),
+       BLTIN("["       , builtin_test    , "Test condition"),
 #if ENABLE_HUSH_JOB
-       BLTIN("bg"    , builtin_fg_bg, "Resume a job in the background"),
+       BLTIN("bg"      , builtin_fg_bg   , "Resume a job in the background"),
 #endif
 #if ENABLE_HUSH_LOOPS
-       BLTIN("break" , builtin_break, "Exit from a loop"),
+       BLTIN("break"   , builtin_break   , "Exit from a loop"),
 #endif
-       BLTIN("cd"    , builtin_cd, "Change directory"),
+       BLTIN("cd"      , builtin_cd      , "Change directory"),
 #if ENABLE_HUSH_LOOPS
        BLTIN("continue", builtin_continue, "Start new loop iteration"),
 #endif
-       BLTIN("echo"  , builtin_echo, "Write to stdout"),
-       BLTIN("eval"  , builtin_eval, "Construct and run shell command"),
-       BLTIN("exec"  , builtin_exec, "Execute command, don't return to shell"),
-       BLTIN("exit"  , builtin_exit, "Exit"),
-       BLTIN("export", builtin_export, "Set environment variable"),
+       BLTIN("echo"    , builtin_echo    , "Write to stdout"),
+       BLTIN("eval"    , builtin_eval    , "Construct and run shell command"),
+       BLTIN("exec"    , builtin_exec    , "Execute command, don't return to shell"),
+       BLTIN("exit"    , builtin_exit    , "Exit"),
+       BLTIN("export"  , builtin_export  , "Set environment variable"),
 #if ENABLE_HUSH_JOB
-       BLTIN("fg"    , builtin_fg_bg, "Bring job into the foreground"),
-       BLTIN("jobs"  , builtin_jobs, "List active jobs"),
-#endif
-       BLTIN("pwd"   , builtin_pwd, "Print current directory"),
-       BLTIN("read"  , builtin_read, "Input environment variable"),
-//     BLTIN("return", builtin_not_written, "Return from a function"),
-       BLTIN("set"   , builtin_set, "Set/unset shell local variables"),
-       BLTIN("shift" , builtin_shift, "Shift positional parameters"),
-       BLTIN("test"  , builtin_test, "Test condition"),
-       BLTIN("trap"  , builtin_trap, "Trap signals"),
-//     BLTIN("ulimit", builtin_not_written, "Control resource limits"),
-       BLTIN("umask" , builtin_umask, "Set file creation mask"),
-       BLTIN("unset" , builtin_unset, "Unset environment variable"),
-       BLTIN("wait"  , builtin_wait, "Wait for process"),
+       BLTIN("fg"      , builtin_fg_bg   , "Bring job into the foreground"),
+#endif
 #if ENABLE_HUSH_HELP
-       BLTIN("help"  , builtin_help, "List shell built-in commands"),
+       BLTIN("help"    , builtin_help    , "List shell built-in commands"),
 #endif
+#if ENABLE_HUSH_JOB
+       BLTIN("jobs"    , builtin_jobs    , "List active jobs"),
+#endif
+#if HUSH_DEBUG
+       BLTIN("memleak" , builtin_memleak , "Debug tool"),
+#endif
+       BLTIN("pwd"     , builtin_pwd     , "Print current directory"),
+       BLTIN("read"    , builtin_read    , "Input environment variable"),
+//     BLTIN("return"  , builtin_return  , "Return from a function"),
+       BLTIN("set"     , builtin_set     , "Set/unset shell local variables"),
+       BLTIN("shift"   , builtin_shift   , "Shift positional parameters"),
+       BLTIN("test"    , builtin_test    , "Test condition"),
+       BLTIN("trap"    , builtin_trap    , "Trap signals"),
+//     BLTIN("ulimit"  , builtin_return  , "Control resource limits"),
+       BLTIN("umask"   , builtin_umask   , "Set file creation mask"),
+       BLTIN("unset"   , builtin_unset   , "Unset environment variable"),
+       BLTIN("wait"    , builtin_wait    , "Wait for process"),
 };
 
 
-/* Normal */
-static void maybe_die(const char *notice, const char *msg)
+/* Debug printouts.
+ */
+#if HUSH_DEBUG
+/* prevent disasters with G.debug_indent < 0 */
+# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
+# define debug_enter() (G.debug_indent++)
+# define debug_leave() (G.debug_indent--)
+#else
+# define indent()    ((void)0)
+# define debug_enter() ((void)0)
+# define debug_leave() ((void)0)
+#endif
+
+#ifndef debug_printf
+# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
+#endif
+
+#ifndef debug_printf_parse
+# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
+#endif
+
+#ifndef debug_printf_exec
+#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
+#endif
+
+#ifndef debug_printf_env
+# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
+#endif
+
+#ifndef debug_printf_jobs
+# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
+# define DEBUG_JOBS 1
+#else
+# define DEBUG_JOBS 0
+#endif
+
+#ifndef debug_printf_expand
+# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
+# define DEBUG_EXPAND 1
+#else
+# define DEBUG_EXPAND 0
+#endif
+
+#ifndef debug_printf_glob
+# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
+# define DEBUG_GLOB 1
+#else
+# define DEBUG_GLOB 0
+#endif
+
+#ifndef debug_printf_list
+# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
+#endif
+
+#ifndef debug_printf_subst
+# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
+#endif
+
+#ifndef debug_printf_clean
+# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
+# define DEBUG_CLEAN 1
+#else
+# define DEBUG_CLEAN 0
+#endif
+
+#if DEBUG_EXPAND
+static void debug_print_strings(const char *prefix, char **vv)
 {
-       /* Was using fancy stuff:
-        * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
-        * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
-       void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
-#if ENABLE_HUSH_INTERACTIVE
-       fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
+       indent();
+       fprintf(stderr, "%s:\n", prefix);
+       while (*vv)
+               fprintf(stderr, " '%s'\n", *vv++);
+}
+#else
+#define debug_print_strings(prefix, vv) ((void)0)
 #endif
-       fp(msg ? "%s: %s" : notice, notice, msg);
+
+
+/* Leak hunting. Use hush_leaktool.sh for post-processing.
+ */
+#if LEAK_HUNTING
+static void *xxmalloc(int lineno, size_t size)
+{
+       void *ptr = xmalloc((size + 0xff) & ~0xff);
+       fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
+       return ptr;
+}
+static void *xxrealloc(int lineno, void *ptr, size_t size)
+{
+       ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
+       fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
+       return ptr;
+}
+static char *xxstrdup(int lineno, const char *str)
+{
+       char *ptr = xstrdup(str);
+       fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
+       return ptr;
+}
+static void xxfree(void *ptr)
+{
+       fdprintf(2, "free %p\n", ptr);
+       free(ptr);
+}
+#define xmalloc(s)     xxmalloc(__LINE__, s)
+#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
+#define xstrdup(s)     xxstrdup(__LINE__, s)
+#define free(p)        xxfree(p)
+#endif
+
+
+/* Syntax and runtime errors. They always abort scripts.
+ * In interactive use they usually discard unparsed and/or unexecuted commands
+ * and return to the prompt.
+ * 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 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)
+# define syntax_error_unterm_str(lineno, s)     syntax_error_unterm_str(s)
+# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
+#endif
+
+static void die_if_script(unsigned lineno, const char *fmt, ...)
+{
+       va_list p;
+
+#if HUSH_DEBUG >= 2
+       bb_error_msg("hush.c:%u", lineno);
+#endif
+       va_start(p, fmt);
+       bb_verror_msg(fmt, p, NULL);
+       va_end(p);
+       if (!G_interactive_fd)
+               xfunc_die();
+}
+
+static void syntax_error(unsigned lineno, const char *msg)
+{
+       if (msg)
+               die_if_script(lineno, "syntax error: %s", msg);
+       else
+               die_if_script(lineno, "syntax error", NULL);
+}
+
+static void syntax_error_at(unsigned lineno, const char *msg)
+{
+       die_if_script(lineno, "syntax error at '%s'", msg);
+}
+
+/* It so happens that all such cases are totally fatal
+ * even if shell is interactive: EOF while looking for closing
+ * delimiter. There is nowhere to read stuff from after that,
+ * it's EOF! The only choice is to terminate.
+ */
+static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
+static void syntax_error_unterm_ch(unsigned lineno, char ch)
+{
+       char msg[2];
+       msg[0] = ch;
+       msg[1] = '\0';
+       die_if_script(lineno, "syntax error: unterminated %s", msg);
+       xfunc_die();
+}
+
+static void syntax_error_unterm_str(unsigned lineno, const char *s)
+{
+       die_if_script(lineno, "syntax error: unterminated %s", s);
+}
+
+static void syntax_error_unexpected_ch(unsigned lineno, char ch)
+{
+       char msg[2];
+       msg[0] = ch;
+       msg[1] = '\0';
+       die_if_script(lineno, "syntax error: unexpected %s", msg);
 }
-#if 1
-#define syntax(msg) maybe_die("syntax error", msg);
+
+#if HUSH_DEBUG < 2
+# undef die_if_script
+# undef syntax_error
+# undef syntax_error_at
+# undef syntax_error_unterm_ch
+# undef syntax_error_unterm_str
+# undef syntax_error_unexpected_ch
 #else
-/* Debug -- trick gcc to expand __LINE__ and convert to string */
-#define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
-#define _syntax(msg, line) __syntax(msg, line)
-#define syntax(msg) _syntax(msg, __LINE__)
+# define die_if_script(fmt...)          die_if_script(__LINE__, fmt)
+# 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)
+# define syntax_error_unterm_str(s)     syntax_error_unterm_str(__LINE__, s)
+# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
 #endif
 
+
+/* Utility functions
+ */
 static int glob_needed(const char *s)
 {
        while (*s) {
@@ -633,14 +799,14 @@ static int glob_needed(const char *s)
        return 0;
 }
 
-static int is_assignment(const char *s)
+static int is_well_formed_var_name(const char *s, char terminator)
 {
        if (!s || !(isalpha(*s) || *s == '_'))
                return 0;
        s++;
        while (isalnum(*s) || *s == '_')
                s++;
-       return *s == '=';
+       return *s == terminator;
 }
 
 /* Replace each \x with x in place, return ptr past NUL. */
@@ -684,6 +850,16 @@ static char **add_strings_to_strings(char **strings, char **add, int need_to_dup
                v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
        return v;
 }
+#if LEAK_HUNTING
+static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
+{
+       char **ptr = add_strings_to_strings(strings, add, need_to_dup);
+       fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
+       return ptr;
+}
+#define add_strings_to_strings(strings, add, need_to_dup) \
+       xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
+#endif
 
 static char **add_string_to_strings(char **strings, char *add)
 {
@@ -692,6 +868,16 @@ static char **add_string_to_strings(char **strings, char *add)
        v[1] = NULL;
        return add_strings_to_strings(strings, v, /*dup:*/ 0);
 }
+#if LEAK_HUNTING
+static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
+{
+       char **ptr = add_string_to_strings(strings, add);
+       fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
+       return ptr;
+}
+#define add_string_to_strings(strings, add) \
+       xx_add_string_to_strings(__LINE__, strings, add)
+#endif
 
 static void putenv_all(char **strings)
 {
@@ -773,7 +959,7 @@ static void free_strings(char **strings)
  *
  * Trap handlers will execute even within trap handlers. (right?)
  *
- * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
+ * User trap handlers are forgotten when subshell ("(cmd)") is entered.
  *
  * If job control is off, backgrounded commands ("cmd &")
  * have SIGINT, SIGQUIT set to SIG_IGN.
@@ -822,12 +1008,12 @@ static void free_strings(char **strings)
  * sigset_t blocked_set:  current blocked signal set
  *
  * "trap - SIGxxx":
- *    clear bit in blocked_set unless it is also in non_DFL
+ *    clear bit in blocked_set unless it is also in non_DFL_mask
  * "trap 'cmd' SIGxxx":
  *    set bit in blocked_set (even if 'cmd' is '')
  * after [v]fork, if we plan to be a shell:
  *    nothing for {} child shell (say, "true | { true; true; } | true")
- *    unset all traps if () shell. [TODO]
+ *    unset all traps if () shell.
  * after [v]fork, if we plan to exec:
  *    POSIX says pending signal mask is cleared in child - no need to clear it.
  *    Restore blocked signal set to one inherited by shell just prior to exec.
@@ -835,46 +1021,12 @@ static void free_strings(char **strings)
  * Note: as a result, we do not use signal handlers much. The only uses
  * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
  * and to restore tty pgrp on signal-induced exit.
- *
- * TODO: check/fix wait builtin to be interruptible.
  */
 
 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
-//{
-//     G.count_SIGCHLD++;
-//}
-
-/* called once at shell init */
-static void init_signal_mask(void)
-{
-       unsigned sig;
-       unsigned mask = (1 << SIGQUIT);
-#if ENABLE_HUSH_INTERACTIVE
-       if (G.interactive_fd) {
-               mask = 0
-                       | (1 << SIGQUIT)
-                       | (1 << SIGTERM)
-                       | (1 << SIGHUP)
-#if ENABLE_HUSH_JOB
-                       | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
-#endif
-                       | (1 << SIGINT)
-               ;
-       }
-#endif
-       G.non_DFL_mask = mask;
-
-       sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
-       sig = 0;
-       while (mask) {
-               if (mask & 1)
-                       sigaddset(&G.blocked_set, sig);
-               mask >>= 1;
-               sig++;
-       }
-       sigdelset(&G.blocked_set, SIGCHLD);
-       sigprocmask(SIG_SETMASK, &G.blocked_set, &G.inherited_set);
-}
+//{
+//     G.count_SIGCHLD++;
+//}
 
 static int check_and_run_traps(int sig)
 {
@@ -894,10 +1046,10 @@ static int check_and_run_traps(int sig)
                        if (G.traps[sig][0]) {
                                /* We have user-defined handler */
                                char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
-                               save_rcode = G.last_return_code;
+                               save_rcode = G.last_exitcode;
                                builtin_eval(argv);
                                free(argv[1]);
-                               G.last_return_code = save_rcode;
+                               G.last_exitcode = save_rcode;
                        } /* else: "" trap, ignoring signal */
                        continue;
                }
@@ -913,7 +1065,8 @@ static int check_and_run_traps(int sig)
 //TODO
 //             case SIGHUP: ...
 //                     break;
-               default: /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
+               default: /* ignored: */
+                       /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
                        break;
                }
        }
@@ -922,6 +1075,11 @@ static int check_and_run_traps(int sig)
 
 #if ENABLE_HUSH_JOB
 
+/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
+#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
+/* After [v]fork, in parent: restore tty pgrp on xfunc death */
+#define enable_restore_tty_pgrp_on_exit()  (die_sleep = -1)
+
 /* Restores tty foreground process group, and exits.
  * May be called as signal handler for fatal signal
  * (will faithfully resend signal to itself, producing correct exit state)
@@ -933,12 +1091,10 @@ static void sigexit(int sig)
        /* Disable all signals: job control, SIGPIPE, etc. */
        sigprocmask_allsigs(SIG_BLOCK);
 
-#if ENABLE_HUSH_INTERACTIVE
        /* Careful: we can end up here after [v]fork. Do not restore
         * tty pgrp then, only top-level shell process does that */
-       if (G.interactive_fd && getpid() == G.root_pid)
-               tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
-#endif
+       if (G_interactive_fd && getpid() == G.root_pid)
+               tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
 
        /* Not a signal, just exit */
        if (sig <= 0)
@@ -946,66 +1102,24 @@ static void sigexit(int sig)
 
        kill_myself_with_sig(sig); /* does not return */
 }
+#else
 
-/* helper */
-static void maybe_set_sighandler(int sig)
-{
-       void (*handler)(int);
-       /* non_DFL_mask'ed signals are, well, masked,
-        * no need to set handler for them.
-        */
-       if (!((G.non_DFL_mask >> sig) & 1)) {
-               handler = signal(sig, sigexit);
-               if (handler == SIG_IGN) /* oops... restore back to IGN! */
-                       signal(sig, handler);
-       }
-}
-/* Used only to set handler to restore pgrp on exit */
-static void set_fatal_signals_to_sigexit(void)
-{
-       if (HUSH_DEBUG) {
-               maybe_set_sighandler(SIGILL );
-               maybe_set_sighandler(SIGFPE );
-               maybe_set_sighandler(SIGBUS );
-               maybe_set_sighandler(SIGSEGV);
-               maybe_set_sighandler(SIGTRAP);
-       } /* else: hush is perfect. what SEGV? */
-
-       maybe_set_sighandler(SIGABRT);
-
-       /* bash 3.2 seems to handle these just like 'fatal' ones */
-       maybe_set_sighandler(SIGPIPE);
-       maybe_set_sighandler(SIGALRM);
-       maybe_set_sighandler(SIGHUP );
-
-       /* if we aren't interactive... but in this case
-        * we never want to restore pgrp on exit, and this fn is not called */
-       /*maybe_set_sighandler(SIGTERM);*/
-       /*maybe_set_sighandler(SIGINT );*/
-}
-/* Used only to suppress ^Z in `cmd` */
-static void set_jobctrl_signals_to_IGN(void)
-{
-       bb_signals(0
-               + (1 << SIGTSTP)
-               + (1 << SIGTTIN)
-               + (1 << SIGTTOU)
-               , SIG_IGN);
-}
-
-#else /* !JOB */
-
-#define set_fatal_signals_to_sigexit(handler) ((void)0)
-#define set_jobctrl_signals_to_IGN(handler)  ((void)0)
+#define disable_restore_tty_pgrp_on_exit() ((void)0)
+#define enable_restore_tty_pgrp_on_exit()  ((void)0)
 
-#endif /* JOB */
+#endif
 
 /* Restores tty foreground process group, and exits. */
 static void hush_exit(int exitcode) NORETURN;
 static void hush_exit(int exitcode)
 {
-       if (G.traps && G.traps[0] && G.traps[0][0]) {
-               char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
+       if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
+               /* Prevent recursion:
+                * trap "echo Hi; exit" EXIT; exit
+                */
+               char *argv[] = { NULL, G.traps[0], NULL };
+               G.traps[0] = NULL;
+               G.exiting = 1;
                builtin_eval(argv);
                free(argv[1]);
        }
@@ -1048,9 +1162,7 @@ static struct variable *get_local_var(const char *name)
        return NULL;
 }
 
-/* Basically useful version until someone wants to get fancier,
- * see the bash man page under "Parameter Expansion" */
-static const char *lookup_param(const char *src)
+static const char *get_local_var_value(const char *src)
 {
        struct variable *var = get_local_var(src);
        if (var)
@@ -1060,13 +1172,18 @@ static const char *lookup_param(const char *src)
 
 /* str holds "NAME=VAL" and is expected to be malloced.
  * We take ownership of it.
- * flg_export is used by:
+ * flg_export:
  *  0: do not export
  *  1: export
  * -1: if NAME is set, leave export status alone
  *     if NAME is not set, do not export
+ * flg_read_only is set only when we handle -R var=val
  */
-static int set_local_var(char *str, int flg_export)
+#if BB_MMU
+#define set_local_var(str, flg_export, flg_read_only) \
+       set_local_var(str, flg_export)
+#endif
+static int set_local_var(char *str, int flg_export, int flg_read_only)
 {
        struct variable *cur;
        char *value;
@@ -1093,7 +1210,10 @@ static int set_local_var(char *str, int flg_export)
                /* We found an existing var with this name */
                *value = '\0';
                if (cur->flg_read_only) {
-                       bb_error_msg("%s: readonly variable", str);
+#if !BB_MMU
+                       if (!flg_read_only)
+#endif
+                               bb_error_msg("%s: readonly variable", str);
                        free(str);
                        return -1;
                }
@@ -1124,6 +1244,9 @@ static int set_local_var(char *str, int flg_export)
 
  set_str_and_exp:
        cur->varstr = str;
+#if !BB_MMU
+       cur->flg_read_only = flg_read_only;
+#endif
  exp:
        if (flg_export == 1)
                cur->flg_export = 1;
@@ -1187,7 +1310,7 @@ static void arith_set_local_var(const char *name, const char *val, int flags)
 {
        /* arith code doesnt malloc space, so do it for it */
        char *var = xasprintf("%s=%s", name, val);
-       set_local_var(var, flags);
+       set_local_var(var, flags, 0);
 }
 #endif
 
@@ -1198,8 +1321,10 @@ static void arith_set_local_var(const char *name, const char *val, int flags)
 static int static_get(struct in_str *i)
 {
        int ch = *i->p++;
-       if (ch == '\0') return EOF;
-       return ch;
+       if (ch != '\0')
+               return ch;
+       i->p--;
+       return EOF;
 }
 
 static int static_peek(struct in_str *i)
@@ -1289,11 +1414,12 @@ static int file_get(struct in_str *i)
                ch = *i->p++;
                if (i->eof_flag && !*i->p)
                        ch = EOF;
+               /* note: ch is never NUL */
        } else {
                /* need to double check i->file because we might be doing something
                 * more complicated by now, like sourcing or substituting. */
 #if ENABLE_HUSH_INTERACTIVE
-               if (G.interactive_fd && i->promptme && i->file == stdin) {
+               if (G_interactive_fd && i->promptme && i->file == stdin) {
                        do {
                                get_user_input(i);
                        } while (!*i->p); /* need non-empty line */
@@ -1302,9 +1428,9 @@ static int file_get(struct in_str *i)
                        goto take_cached;
                }
 #endif
-               ch = fgetc(i->file);
+               do ch = fgetc(i->file); while (ch == '\0');
        }
-       debug_printf("file_get: got '%c' %d\n", ch, ch);
+       debug_printf("file_get: got '%c' %d\n", ch, ch);
 #if ENABLE_HUSH_INTERACTIVE
        if (ch == '\n')
                i->promptme = 1;
@@ -1312,8 +1438,8 @@ static int file_get(struct in_str *i)
        return ch;
 }
 
-/* All the callers guarantee this routine will never be
- * used right after a newline, so prompting is not needed.
+/* All callers guarantee this routine will never
+ * be used right after a newline, so prompting is not needed.
  */
 static int file_peek(struct in_str *i)
 {
@@ -1322,13 +1448,14 @@ static int file_peek(struct in_str *i)
                if (i->eof_flag && !i->p[1])
                        return EOF;
                return *i->p;
+               /* note: ch is never NUL */
        }
-       ch = fgetc(i->file);
+       do ch = fgetc(i->file); while (ch == '\0');
        i->eof_flag = (ch == EOF);
        i->peek_buf[0] = ch;
        i->peek_buf[1] = '\0';
        i->p = i->peek_buf;
-       debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
+       debug_printf("file_peek: got '%c' %d\n", ch, ch);
        return ch;
 }
 
@@ -1362,10 +1489,10 @@ static void setup_string_in_str(struct in_str *i, const char *s)
  */
 #define B_CHUNK  (32 * sizeof(char*))
 
-static void o_reset(o_string *o)
+static void o_reset_to_empty_unquoted(o_string *o)
 {
        o->length = 0;
-       o->nonnull = 0;
+       o->o_quoted = 0;
        if (o->data)
                o->data[0] = '\0';
 }
@@ -1376,6 +1503,11 @@ static void o_free(o_string *o)
        memset(o, 0, sizeof(*o));
 }
 
+static ALWAYS_INLINE void o_free_unsafe(o_string *o)
+{
+       free(o->data);
+}
+
 static void o_grow_by(o_string *o, int len)
 {
        if (o->length + len > o->maxlen) {
@@ -1393,7 +1525,7 @@ static void o_addchr(o_string *o, int ch)
        o->data[o->length] = '\0';
 }
 
-static void o_addstr(o_string *o, const char *str, int len)
+static void o_addblock(o_string *o, const char *str, int len)
 {
        o_grow_by(o, len);
        memcpy(&o->data[o->length], str, len);
@@ -1401,12 +1533,26 @@ static void o_addstr(o_string *o, const char *str, int len)
        o->data[o->length] = '\0';
 }
 
-static void o_addstrauto(o_string *o, const char *str)
+#if !BB_MMU
+static void o_addstr(o_string *o, const char *str)
+{
+       o_addblock(o, str, strlen(str));
+}
+static void nommu_addchr(o_string *o, int ch)
+{
+       if (o)
+               o_addchr(o, ch);
+}
+#else
+#define nommu_addchr(o, str) ((void)0)
+#endif
+
+static void o_addstr_with_NUL(o_string *o, const char *str)
 {
-       o_addstr(o, str, strlen(str) + 1);
+       o_addblock(o, str, strlen(str) + 1);
 }
 
-static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
+static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
 {
        while (len) {
                o_addchr(o, *str);
@@ -1441,7 +1587,7 @@ static void o_addqchr(o_string *o, int ch)
 static void o_addQchr(o_string *o, int ch)
 {
        int sz = 1;
-       if (o->o_quote && strchr("*?[\\", ch)) {
+       if (o->o_escape && strchr("*?[\\", ch)) {
                sz++;
                o->data[o->length] = '\\';
                o->length++;
@@ -1454,8 +1600,8 @@ static void o_addQchr(o_string *o, int ch)
 
 static void o_addQstr(o_string *o, const char *str, int len)
 {
-       if (!o->o_quote) {
-               o_addstr(o, str, len);
+       if (!o->o_escape) {
+               o_addblock(o, str, len);
                return;
        }
        while (len) {
@@ -1464,7 +1610,7 @@ static void o_addQstr(o_string *o, const char *str, int len)
                int ordinary_cnt = strcspn(str, "*?[\\");
                if (ordinary_cnt > len) /* paranoia */
                        ordinary_cnt = len;
-               o_addstr(o, str, ordinary_cnt);
+               o_addblock(o, str, ordinary_cnt);
                if (ordinary_cnt == len)
                        return;
                str += ordinary_cnt;
@@ -1500,9 +1646,12 @@ static void debug_print_list(const char *prefix, o_string *o, int n)
        char **list = (char**)o->data;
        int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
        int i = 0;
+
+       indent();
        fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
                        prefix, list, n, string_start, o->length, o->maxlen);
        while (i < n) {
+               indent();
                fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
                                o->data + (int)list[i] + string_start,
                                o->data + (int)list[i] + string_start);
@@ -1510,6 +1659,7 @@ static void debug_print_list(const char *prefix, o_string *o, int n)
        }
        if (n) {
                const char *p = o->data + (int)list[n - 1] + string_start;
+               indent();
                fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
        }
 }
@@ -1537,13 +1687,16 @@ static int o_save_ptr_helper(o_string *o, int n)
                        list = (char**)o->data;
                        memmove(list + n + 0x10, list + n, string_len);
                        o->length += 0x10 * sizeof(list[0]);
-               } else
-                       debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
+               } else {
+                       debug_printf_list("list[%d]=%d string_start=%d\n",
+                                       n, string_len, string_start);
+               }
        } else {
                /* We have empty slot at list[n], reuse without growth */
                string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
                string_len = o->length - string_start;
-               debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
+               debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
+                               n, string_len, string_start);
                o->has_empty_slot = 0;
        }
        list[n] = (char*)(ptrdiff_t)string_len;
@@ -1596,7 +1749,7 @@ static int o_glob(o_string *o, int n)
                char **argv = globdata.gl_pathv;
                o->length = pattern - o->data; /* "forget" pattern */
                while (1) {
-                       o_addstrauto(o, *argv);
+                       o_addstr_with_NUL(o, *argv);
                        n = o_save_ptr_helper(o, n);
                        argv++;
                        if (!*argv)
@@ -1646,11 +1799,17 @@ static char **o_finalize_list(o_string *o, int n)
 
 /* Expansion can recurse */
 #if ENABLE_HUSH_TICK
-static int process_command_subs(o_string *dest,
-               struct in_str *input, const char *subst_end);
+static int process_command_subs(o_string *dest, const char *s);
 #endif
 static char *expand_string_to_string(const char *str);
-static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end);
+#if BB_MMU
+#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
+       parse_stream_dquoted(dest, input, dquote_end)
+#endif
+static int parse_stream_dquoted(o_string *as_string,
+               o_string *dest,
+               struct in_str *input,
+               int dquote_end);
 
 /* expand_strvec_to_strvec() takes a list of strings, expands
  * all variable references within and returns a pointer to
@@ -1669,10 +1828,10 @@ static int expand_on_ifs(o_string *output, int n, const char *str)
        while (1) {
                int word_len = strcspn(str, G.ifs);
                if (word_len) {
-                       if (output->o_quote || !output->o_glob)
+                       if (output->o_escape || !output->o_glob)
                                o_addQstr(output, str, word_len);
                        else /* protect backslashes against globbing up :) */
-                               o_addstr_duplicate_backslash(output, str, word_len);
+                               o_addblock_duplicate_backslash(output, str, word_len);
                        str += word_len;
                }
                if (!*str)  /* EOL - do not finalize word */
@@ -1686,6 +1845,39 @@ static int expand_on_ifs(o_string *output, int n, const char *str)
        return n;
 }
 
+/* Helper to expand $((...)) and heredoc body. These act as if
+ * they are in double quotes, with the exception that they are not :).
+ * Just the rules are similar: "expand only $var and `cmd`"
+ *
+ * Returns malloced string.
+ * As an optimization, we return NULL if expansion is not needed.
+ */
+static char *expand_pseudo_dquoted(const char *str)
+{
+       char *exp_str;
+       struct in_str input;
+       o_string dest = NULL_O_STRING;
+
+       if (strchr(str, '$') == NULL
+#if ENABLE_HUSH_TICK
+        && strchr(str, '`') == NULL
+#endif
+       ) {
+               return NULL;
+       }
+
+       /* We need to expand. Example:
+        * echo $(($a + `echo 1`)) $((1 + $((2)) ))
+        */
+       setup_string_in_str(&input, str);
+       parse_stream_dquoted(NULL, &dest, &input, EOF);
+       //bb_error_msg("'%s' -> '%s'", str, dest.data);
+       exp_str = expand_string_to_string(dest.data);
+       //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
+       o_free_unsafe(&dest);
+       return exp_str;
+}
+
 /* Expand all variable references in given string, adding words to list[]
  * at n, n+1,... positions. Return updated n (so that list[n] is next one
  * to be filled). This routine is extremely tricky: has to deal with
@@ -1700,8 +1892,9 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
        char first_ch, ored_ch;
        int i;
        const char *val;
-       char *p;
+       char *dyn_val, *p;
 
+       dyn_val = NULL;
        ored_ch = 0;
 
        debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
@@ -1716,7 +1909,7 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
 #if ENABLE_SH_MATH_SUPPORT
                char arith_buf[sizeof(arith_t)*3 + 2];
 #endif
-               o_addstr(output, arg, p - arg);
+               o_addblock(output, arg, p - arg);
                debug_print_list("expand_vars_to_list[1]", output, n);
                arg = ++p;
                p = strchr(p, SPECIAL_VAR_SYMBOL);
@@ -1737,7 +1930,7 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                        val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
                        break;
                case '?': /* exitcode */
-                       val = utoa(G.last_return_code);
+                       val = utoa(G.last_exitcode);
                        break;
                case '#': /* argc */
                        if (arg[1] != SPECIAL_VAR_SYMBOL)
@@ -1752,9 +1945,9 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                break;
                        ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
                        if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
-                               smallint sv = output->o_quote;
-                               /* unquoted var's contents should be globbed, so don't quote */
-                               output->o_quote = 0;
+                               smallint sv = output->o_escape;
+                               /* unquoted var's contents should be globbed, so don't escape */
+                               output->o_escape = 0;
                                while (G.global_argv[i]) {
                                        n = expand_on_ifs(output, n, G.global_argv[i]);
                                        debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
@@ -1767,7 +1960,7 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                                debug_print_list("expand_vars_to_list[3]", output, n);
                                        }
                                }
-                               output->o_quote = sv;
+                               output->o_escape = sv;
                        } else
                        /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
                         * and in this case should treat it like '$*' - see 'else...' below */
@@ -1796,18 +1989,15 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                        ored_ch = 0x80;
                        break;
 #if ENABLE_HUSH_TICK
-               case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
-                       struct in_str input;
+               case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
                        *p = '\0';
                        arg++;
 //TODO: can we just stuff it into "output" directly?
                        debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
-                       setup_string_in_str(&input, arg);
-                       process_command_subs(&subst_result, &input, NULL);
+                       process_command_subs(&subst_result, arg);
                        debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
                        val = subst_result.data;
                        goto store_val;
-               }
 #endif
 #if ENABLE_SH_MATH_SUPPORT
                case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
@@ -1820,49 +2010,27 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                        *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
                        debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
 
-                       /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
-                       exp_str = arg;
-                       while (1) {
-                               unsigned char c = *exp_str++;
-                               if (c == '\0') {
-                                       exp_str = NULL;
-                                       goto skip_expand;
-                               }
-                               if (isdigit(c))
-                                       continue;
-                               if (strchr(" \t+-*/%_", c) != NULL)
-                                       continue;
-                               c |= 0x20; /* tolower */
-                               if (c >= 'a' && c <= 'z')
-                                       continue;
-                               break;
-                       }
-                       /* We need to expand. Example: "echo $(($a + 1)) $((1 + $((2)) ))" */
-                       {
-                               struct in_str input;
-                               o_string dest = NULL_O_STRING;
-
-                               setup_string_in_str(&input, arg);
-                               parse_stream_dquoted(&dest, &input, EOF);
-                               //bb_error_msg("'%s' -> '%s'", arg, dest.data);
-                               exp_str = expand_string_to_string(dest.data);
-                               //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
-                               o_free(&dest);
-                       }
- skip_expand:
-                       hooks.lookupvar = lookup_param;
+                       exp_str = expand_pseudo_dquoted(arg);
+                       hooks.lookupvar = get_local_var_value;
                        hooks.setvar = arith_set_local_var;
                        hooks.endofname = endofname;
                        res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
                        free(exp_str);
 
                        if (errcode < 0) {
+                               const char *msg = "error in arithmetic";
                                switch (errcode) {
-                               case -3: maybe_die("arith", "exponent less than 0"); break;
-                               case -2: maybe_die("arith", "divide by zero"); break;
-                               case -5: maybe_die("arith", "expression recursion loop detected"); break;
-                               default: maybe_die("arith", "syntax error"); break;
+                               case -3:
+                                       msg = "exponent less than 0";
+                                       break;
+                               case -2:
+                                       msg = "divide by 0";
+                                       break;
+                               case -5:
+                                       msg = "expression recursion loop detected";
+                                       break;
                                }
+                               die_if_script(msg);
                        }
                        debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
                        sprintf(arith_buf, arith_t_fmt, res);
@@ -1872,9 +2040,14 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
 #endif
                default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
                case_default: {
-                       bool exp_len = false, exp_null = false;
-                       char *var = arg, exp_save, exp_op, *exp_word;
+                       bool exp_len = false;
+                       bool exp_null = false;
+                       char *var = arg;
+                       char exp_save = exp_save; /* for compiler */
+                       char exp_op = exp_op; /* for compiler */
+                       char *exp_word = exp_word; /* for compiler */
                        size_t exp_off = 0;
+
                        *p = '\0';
                        arg[0] = first_ch & 0x7f;
 
@@ -1885,14 +2058,15 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                ++var;
                        } else {
                                /* maybe handle parameter expansion */
-                               exp_off = strcspn(var, ":-=+?");
+                               exp_off = strcspn(var, ":-=+?%#");
                                if (!var[exp_off])
                                        exp_off = 0;
                                if (exp_off) {
                                        exp_save = var[exp_off];
                                        exp_null = exp_save == ':';
                                        exp_word = var + exp_off;
-                                       if (exp_null) ++exp_word;
+                                       if (exp_null)
+                                               ++exp_word;
                                        exp_op = *exp_word++;
                                        var[exp_off] = '\0';
                                }
@@ -1906,7 +2080,7 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                        val = G.global_argv[i];
                                /* else val remains NULL: $N with too big N */
                        } else
-                               val = lookup_param(var);
+                               val = get_local_var_value(var);
 
                        /* handle any expansions */
                        if (exp_len) {
@@ -1914,56 +2088,83 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                val = utoa(val ? strlen(val) : 0);
                                debug_printf_expand("%s\n", val);
                        } else if (exp_off) {
-                               /* we need to do an expansion */
-                               int exp_test = (!val || (exp_null && !val[0]));
-                               if (exp_op == '+')
-                                       exp_test = !exp_test;
-                               debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
-                                       exp_null ? "true" : "false", exp_test);
-                               if (exp_test) {
-                                       if (exp_op == '?')
-                                               maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
-                                       else
-                                               val = exp_word;
-
-                                       if (exp_op == '=') {
-                                               if (isdigit(var[0]) || var[0] == '#') {
-                                                       maybe_die(var, "special vars cannot assign in this way");
-                                                       val = NULL;
+                               if (exp_op == '%' || exp_op == '#') {
+                                       if (val) {
+                                               /* we need to do a pattern match */
+                                               bool zero;
+                                               char *loc;
+                                               scan_t scan = pick_scan(exp_op, *exp_word, &zero);
+                                               if (exp_op == *exp_word)        /* ## or %% */
+                                                       ++exp_word;
+                                               val = dyn_val = xstrdup(val);
+                                               loc = scan(dyn_val, exp_word, zero);
+                                               if (zero)
+                                                       val = loc;
+                                               else
+                                                       *loc = '\0';
+                                       }
+                               } else {
+                                       /* we need to do an expansion */
+                                       int exp_test = (!val || (exp_null && !val[0]));
+                                       if (exp_op == '+')
+                                               exp_test = !exp_test;
+                                       debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
+                                               exp_null ? "true" : "false", exp_test);
+                                       if (exp_test) {
+                                               if (exp_op == '?') {
+//TODO: how interactive bash aborts expansion mid-command?
+                                                       /* ${var?[error_msg_if_unset]} */
+                                                       /* ${var:?[error_msg_if_unset_or_null]} */
+                                                       /* mimic bash message */
+                                                       die_if_script("%s: %s",
+                                                               var,
+                                                               exp_word[0] ? exp_word : "parameter null or not set"
+                                                       );
                                                } else {
-                                                       char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
-                                                       sprintf(new_var, "%s=%s", var, val);
-                                                       set_local_var(new_var, -1);
+                                                       val = exp_word;
+                                               }
+
+                                               if (exp_op == '=') {
+                                                       /* ${var=[word]} or ${var:=[word]} */
+                                                       if (isdigit(var[0]) || var[0] == '#') {
+                                                               /* mimic bash message */
+                                                               die_if_script("$%s: cannot assign in this way", var);
+                                                               val = NULL;
+                                                       } else {
+                                                               char *new_var = xasprintf("%s=%s", var, val);
+                                                               set_local_var(new_var, -1, 0);
+                                                       }
                                                }
                                        }
                                }
+
                                var[exp_off] = exp_save;
                        }
 
                        arg[0] = first_ch;
-
 #if ENABLE_HUSH_TICK
  store_val:
 #endif
                        if (!(first_ch & 0x80)) { /* unquoted $VAR */
-                               debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
+                               debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
                                if (val) {
-                                       /* unquoted var's contents should be globbed, so don't quote */
-                                       smallint sv = output->o_quote;
-                                       output->o_quote = 0;
+                                       /* unquoted var's contents should be globbed, so don't escape */
+                                       smallint sv = output->o_escape;
+                                       output->o_escape = 0;
                                        n = expand_on_ifs(output, n, val);
                                        val = NULL;
-                                       output->o_quote = sv;
+                                       output->o_escape = sv;
                                }
                        } else { /* quoted $VAR, val will be appended below */
-                               debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
+                               debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
                        }
                } /* default: */
                } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
-
                if (val) {
                        o_addQstr(output, val, strlen(val));
                }
+               free(dyn_val);
+               dyn_val = NULL;
                /* Do the check to avoid writing to a const string */
                if (*p != SPECIAL_VAR_SYMBOL)
                        *p = SPECIAL_VAR_SYMBOL;
@@ -1978,7 +2179,7 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                debug_print_list("expand_vars_to_list[a]", output, n);
                /* this part is literal, and it was already pre-quoted
                 * if needed (much earlier), do not use o_addQstr here! */
-               o_addstrauto(output, arg);
+               o_addstr_with_NUL(output, arg);
                debug_print_list("expand_vars_to_list[b]", output, n);
        } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
         && !(ored_ch & 0x80) /* and all vars were not quoted. */
@@ -2000,7 +2201,7 @@ static char **expand_variables(char **argv, int or_mask)
        o_string output = NULL_O_STRING;
 
        if (or_mask & 0x100) {
-               output.o_quote = 1; /* protect against globbing for "$var" */
+               output.o_escape = 1; /* protect against globbing for "$var" */
                /* (unquoted $var will temporarily switch it off) */
                output.o_glob = 1;
        }
@@ -2077,6 +2278,229 @@ static char **expand_assignments(char **argv, int count)
 }
 
 
+#if BB_MMU
+/* never called */
+void re_execute_shell(const char *s, char *argv0, char **argv);
+
+#define clean_up_after_re_execute() ((void)0)
+
+static void reset_traps_to_defaults(void)
+{
+       unsigned sig;
+       int dirty;
+
+       if (!G.traps)
+               return;
+       dirty = 0;
+       for (sig = 0; sig < NSIG; sig++) {
+               if (!G.traps[sig])
+                       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
+                * (if sig has non-DFL handling,
+                * we don't need to do anything) */
+               if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
+                       continue;
+               sigdelset(&G.blocked_set, sig);
+               dirty = 1;
+       }
+       if (dirty)
+               sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
+}
+
+#else /* !BB_MMU */
+
+static void re_execute_shell(const char *s, char *g_argv0, char **g_argv) NORETURN;
+static void re_execute_shell(const char *s, char *g_argv0, char **g_argv)
+{
+       char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
+       char *heredoc_argv[4];
+       struct variable *cur;
+#if ENABLE_HUSH_FUNCTIONS
+       struct function *funcp;
+#endif
+       char **argv, **pp;
+       unsigned cnt;
+
+       if (!g_argv0) { /* heredoc */
+               argv = heredoc_argv;
+               argv[0] = (char *) G.argv0_for_re_execing;
+               argv[1] = (char *) "-<";
+               argv[2] = (char *) s;
+               argv[3] = NULL;
+               pp = &argv[3]; /* used as pointer to empty environment */
+               goto do_exec;
+       }
+
+       sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
+                       , (unsigned) G.root_pid
+                       , (unsigned) G.last_bg_pid
+                       , (unsigned) G.last_exitcode
+                       USE_HUSH_LOOPS(, G.depth_of_loop)
+                       );
+       /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
+        * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
+        */
+       cnt = 6;
+       for (cur = G.top_var; cur; cur = cur->next) {
+               if (!cur->flg_export || cur->flg_read_only)
+                       cnt += 2;
+       }
+#if ENABLE_HUSH_FUNCTIONS
+       for (funcp = G.top_func; funcp; funcp = funcp->next)
+               cnt += 3;
+#endif
+       pp = g_argv;
+       while (*pp++)
+               cnt++;
+       G.argv_from_re_execing = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
+       *pp++ = (char *) G.argv0_for_re_execing;
+       *pp++ = param_buf;
+       for (cur = G.top_var; cur; cur = cur->next) {
+               if (cur->varstr == hush_version_str)
+                       continue;
+               if (cur->flg_read_only) {
+                       *pp++ = (char *) "-R";
+                       *pp++ = cur->varstr;
+               } else if (!cur->flg_export) {
+                       *pp++ = (char *) "-V";
+                       *pp++ = cur->varstr;
+               }
+       }
+#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
+       /* We can pass activated traps here. Say, -Tnn:trap_string
+        *
+        * However, POSIX says that subshells reset signals with traps
+        * to SIG_DFL.
+        * I tested bash-3.2 and it not only does that with true subshells
+        * of the form ( list ), but with any forked children shells.
+        * I set trap "echo W" WINCH; and then tried:
+        *
+        * { echo 1; sleep 20; echo 2; } &
+        * while true; do echo 1; sleep 20; echo 2; break; done &
+        * true | { echo 1; sleep 20; echo 2; } | cat
+        *
+        * In all these cases sending SIGWINCH to the child shell
+        * did not run the trap. If I add trap "echo V" WINCH;
+        * _inside_ group (just before echo 1), it works.
+        *
+        * I conclude it means we don't need to pass active traps here.
+        * exec syscall below resets them to SIG_DFL for us.
+        */
+       *pp++ = (char *) "-c";
+       *pp++ = (char *) s;
+       *pp++ = g_argv0;
+       while (*g_argv)
+               *pp++ = *g_argv++;
+       /* *pp = NULL; - is already there */
+       pp = environ;
+
+ do_exec:
+       debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
+       sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
+       execve(bb_busybox_exec_path, argv, pp);
+       /* Fallback. Useful for init=/bin/hush usage etc */
+       if (argv[0][0] == '/')
+               execve(argv[0], argv, pp);
+       xfunc_error_retval = 127;
+       bb_error_msg_and_die("can't re-execute the shell");
+}
+
+static void clean_up_after_re_execute(void)
+{
+       char **pp = G.argv_from_re_execing;
+       if (pp) {
+               /* Must match re_execute_shell's allocations (if any) */
+               free(pp);
+               G.argv_from_re_execing = NULL;
+       }
+}
+#endif  /* !BB_MMU */
+
+
+static void setup_heredoc(struct redir_struct *redir)
+{
+       struct fd_pair pair;
+       pid_t pid;
+       int len, written;
+       /* the _body_ of heredoc (misleading field name) */
+       const char *heredoc = redir->rd_filename;
+       char *expanded;
+
+       expanded = NULL;
+       if (!(redir->rd_dup & HEREDOC_QUOTED)) {
+               expanded = expand_pseudo_dquoted(heredoc);
+               if (expanded)
+                       heredoc = expanded;
+       }
+       len = strlen(heredoc);
+
+       close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
+       xpiped_pair(pair);
+       xmove_fd(pair.rd, redir->rd_fd);
+
+       /* Try writing without forking. Newer kernels have
+        * dynamically growing pipes. Must use non-blocking write! */
+       ndelay_on(pair.wr);
+       while (1) {
+               written = write(pair.wr, heredoc, len);
+               if (written <= 0)
+                       break;
+               len -= written;
+               if (len == 0) {
+                       close(pair.wr);
+                       free(expanded);
+                       return;
+               }
+               heredoc += written;
+       }
+       ndelay_off(pair.wr);
+
+       /* Okay, pipe buffer was not big enough */
+       /* Note: we must not create a stray child (bastard? :)
+        * for the unsuspecting parent process. Child creates a grandchild
+        * and exits before parent execs the process which consumes heredoc
+        * (that exec happens after we return from this function) */
+       pid = vfork();
+       if (pid < 0)
+               bb_perror_msg_and_die("vfork");
+       if (pid == 0) {
+               /* child */
+               pid = BB_MMU ? fork() : vfork();
+               if (pid < 0)
+                       bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
+               if (pid != 0)
+                       _exit(0);
+               /* grandchild */
+               close(redir->rd_fd); /* read side of the pipe */
+#if BB_MMU
+               full_write(pair.wr, heredoc, len); /* may loop or block */
+               _exit(0);
+#else
+               /* Delegate blocking writes to another process */
+               disable_restore_tty_pgrp_on_exit();
+               xmove_fd(pair.wr, STDOUT_FILENO);
+               re_execute_shell(heredoc, NULL, NULL);
+#endif
+       }
+       /* parent */
+       enable_restore_tty_pgrp_on_exit();
+       clean_up_after_re_execute();
+       close(pair.wr);
+       free(expanded);
+       wait(NULL); /* wait till child has died */
+}
+
 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  * and stderr if they are redirected. */
 static int setup_redirects(struct command *prog, int squirrel[])
@@ -2085,35 +2509,53 @@ static int setup_redirects(struct command *prog, int squirrel[])
        struct redir_struct *redir;
 
        for (redir = prog->redirects; redir; redir = redir->next) {
-               if (redir->dup == -1 && redir->rd_filename == NULL) {
-                       /* something went wrong in the parse.  Pretend it didn't happen */
+               if (redir->rd_type == REDIRECT_HEREDOC2) {
+                       /* rd_fd<<HERE case */
+                       if (squirrel && redir->rd_fd < 3) {
+                               squirrel[redir->rd_fd] = dup(redir->rd_fd);
+                       }
+                       /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
+                        * of the heredoc */
+                       debug_printf_parse("set heredoc '%s'\n",
+                                       redir->rd_filename);
+                       setup_heredoc(redir);
                        continue;
                }
-               if (redir->dup == -1) {
+
+               if (redir->rd_dup == REDIRFD_TO_FILE) {
+                       /* rd_fd<*>file case (<*> is <,>,>>,<>) */
                        char *p;
+                       if (redir->rd_filename == NULL) {
+                               /* Something went wrong in the parse.
+                                * Pretend it didn't happen */
+                               bb_error_msg("bug in redirect parse");
+                               continue;
+                       }
                        mode = redir_table[redir->rd_type].mode;
-//TODO: check redir for names like '\\'
                        p = expand_string_to_string(redir->rd_filename);
                        openfd = open_or_warn(p, mode);
                        free(p);
                        if (openfd < 0) {
                        /* this could get lost if stderr has been redirected, but
-                          bash and ash both lose it as well (though zsh doesn't!) */
+                        * bash and ash both lose it as well (though zsh doesn't!) */
+//what the above comment tries to say?
                                return 1;
                        }
                } else {
-                       openfd = redir->dup;
+                       /* rd_fd<*>rd_dup or rd_fd<*>- cases */
+                       openfd = redir->rd_dup;
                }
 
-               if (openfd != redir->fd) {
-                       if (squirrel && redir->fd < 3) {
-                               squirrel[redir->fd] = dup(redir->fd);
+               if (openfd != redir->rd_fd) {
+                       if (squirrel && redir->rd_fd < 3) {
+                               squirrel[redir->rd_fd] = dup(redir->rd_fd);
                        }
-                       if (openfd == -3) {
-                               //close(openfd); // close(-3) ??!
+                       if (openfd == REDIRFD_CLOSE) {
+                               /* "n>-" means "close me" */
+                               close(redir->rd_fd);
                        } else {
-                               dup2(openfd, redir->fd);
-                               if (redir->dup == -1)
+                               xdup2(openfd, redir->rd_fd);
+                               if (redir->rd_dup == REDIRFD_TO_FILE)
                                        close(openfd);
                        }
                }
@@ -2134,51 +2576,59 @@ static void restore_redirects(int squirrel[])
 }
 
 
-#if !defined(DEBUG_CLEAN)
-#define free_pipe_list(head, indent) free_pipe_list(head)
-#define free_pipe(pi, indent)        free_pipe(pi)
-#endif
-static int free_pipe_list(struct pipe *head, int indent);
+static void free_pipe_list(struct pipe *head);
 
-/* return code is the exit status of the pipe */
-static int free_pipe(struct pipe *pi, int indent)
+/* Return code is the exit status of the pipe */
+static void free_pipe(struct pipe *pi)
 {
        char **p;
        struct command *command;
        struct redir_struct *r, *rnext;
-       int a, i, ret_code = 0;
+       int a, i;
 
-       if (pi->stopped_cmds > 0)
-               return ret_code;
-       debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
+       if (pi->stopped_cmds > 0) /* why? */
+               return;
+       debug_printf_clean("run pipe: (pid %d)\n", getpid());
        for (i = 0; i < pi->num_cmds; i++) {
                command = &pi->cmds[i];
-               debug_printf_clean("%s  command %d:\n", indenter(indent), i);
+               debug_printf_clean("  command %d:\n", i);
                if (command->argv) {
                        for (a = 0, p = command->argv; *p; a++, p++) {
-                               debug_printf_clean("%s   argv[%d] = %s\n", indenter(indent), a, *p);
+                               debug_printf_clean("   argv[%d] = %s\n", a, *p);
                        }
                        free_strings(command->argv);
                        command->argv = NULL;
-               } else if (command->group) {
-                       debug_printf_clean("%s   begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
-                       ret_code = free_pipe_list(command->group, indent+3);
-                       debug_printf_clean("%s   end group\n", indenter(indent));
-               } else {
-                       debug_printf_clean("%s   (nil)\n", indenter(indent));
                }
+               /* 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);
+                       free_pipe_list(command->group);
+                       debug_printf_clean("   end group\n");
+                       command->group = NULL;
+               }
+               /* else is crucial here.
+                * If group != NULL, child_func is meaningless */
+#if ENABLE_HUSH_FUNCTIONS
+               else if (command->child_func) {
+                       debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
+                       command->child_func->parent_cmd = NULL;
+               }
+#endif
+#if !BB_MMU
+               free(command->group_as_string);
+               command->group_as_string = NULL;
+#endif
                for (r = command->redirects; r; r = rnext) {
-                       debug_printf_clean("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
-                       if (r->dup == -1) {
-                               /* guard against the case >$FOO, where foo is unset or blank */
-                               if (r->rd_filename) {
-                                       debug_printf_clean(" %s\n", r->rd_filename);
-                                       free(r->rd_filename);
-                                       r->rd_filename = NULL;
-                               }
-                       } else {
-                               debug_printf_clean("&%d\n", r->dup);
+                       debug_printf_clean("   redirect %d%s",
+                                       r->rd_fd, redir_table[r->rd_type].descrip);
+                       /* guard against the case >$FOO, where foo is unset or blank */
+                       if (r->rd_filename) {
+                               debug_printf_clean(" fname:'%s'\n", r->rd_filename);
+                               free(r->rd_filename);
+                               r->rd_filename = NULL;
                        }
+                       debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
                        rnext = r->next;
                        free(r);
                }
@@ -2190,56 +2640,204 @@ static int free_pipe(struct pipe *pi, int indent)
        free(pi->cmdtext);
        pi->cmdtext = NULL;
 #endif
-       return ret_code;
 }
 
-static int free_pipe_list(struct pipe *head, int indent)
+static void free_pipe_list(struct pipe *head)
 {
-       int rcode = 0;   /* if list has no members */
        struct pipe *pi, *next;
 
        for (pi = head; pi; pi = next) {
 #if HAS_KEYWORDS
-               debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
+               debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
 #endif
-               rcode = free_pipe(pi, indent);
-               debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
+               free_pipe(pi);
+               debug_printf_clean("pipe followup code %d\n", pi->followup);
                next = pi->next;
                /*pi->next = NULL;*/
                free(pi);
        }
-       return rcode;
 }
 
 
+static int run_list(struct pipe *pi);
+#if BB_MMU
+#define parse_stream(pstring, input, end_trigger) \
+       parse_stream(input, end_trigger)
+#endif
+static struct pipe *parse_stream(char **pstring,
+               struct in_str *input,
+               int end_trigger);
+static void parse_and_run_string(const char *s);
+
+
+static const struct built_in_command* find_builtin(const char *name)
+{
+       const struct built_in_command *x;
+       for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
+               if (strcmp(name, x->cmd) != 0)
+                       continue;
+               debug_printf_exec("found builtin '%s'\n", name);
+               return x;
+       }
+       return NULL;
+}
+
+#if ENABLE_HUSH_FUNCTIONS
+static const struct function *find_function(const char *name)
+{
+       const struct function *funcp = G.top_func;
+       while (funcp) {
+               if (strcmp(name, funcp->name) == 0) {
+                       break;
+               }
+               funcp = funcp->next;
+       }
+       debug_printf_exec("found function '%s'\n", name);
+       return funcp;
+}
+
+/* Note: takes ownership on name ptr */
+static struct function *new_function(char *name)
+{
+       struct function *funcp;
+       struct function **funcpp = &G.top_func;
+
+       while ((funcp = *funcpp) != NULL) {
+               struct command *cmd;
+
+               if (strcmp(funcp->name, name) != 0) {
+                       funcpp = &funcp->next;
+                       continue;
+               }
+
+               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);
+                       free(funcp->name);
+                       /* Note: if !funcp->body, do not free body_as_string!
+                        * This is a special case of "-F name body" function:
+                        * body_as_string was not malloced! */
+                       if (funcp->body) {
+                               free_pipe_list(funcp->body);
 #if !BB_MMU
-typedef struct nommu_save_t {
-       char **new_env;
-       char **old_env;
-       char **argv;
-} nommu_save_t;
-#else
+                               free(funcp->body_as_string);
+#endif
+                       }
+               } else {
+                       debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
+                       cmd->argv[0] = funcp->name;
+                       cmd->group = funcp->body;
+#if !BB_MMU
+                       cmd->group_as_string = funcp->body_as_string;
+#endif
+               }
+               goto skip;
+       }
+       debug_printf_exec("remembering new function '%s'\n", command->argv[0]);
+       funcp = *funcpp = xzalloc(sizeof(*funcp));
+       /*funcp->next = NULL;*/
+ skip:
+       funcp->name = name;
+       return funcp;
+}
+
+static void exec_function(const struct function *funcp, char **argv) NORETURN;
+static void exec_function(const struct function *funcp, char **argv)
+{
+# if BB_MMU
+       int n = 1;
+
+       argv[0] = G.global_argv[0];
+       G.global_argv = argv;
+       while (*++argv)
+               n++;
+       G.global_argc = n;
+       /* On MMU, funcp->body is always non-NULL */
+       n = run_list(funcp->body);
+       fflush(NULL);
+       _exit(n);
+# else
+       re_execute_shell(funcp->body_as_string, G.global_argv[0], argv + 1);
+# endif
+}
+
+static int run_function(const struct function *funcp, char **argv)
+{
+       int n;
+       char **pp;
+       char *sv_argv0;
+       smallint sv_g_malloced;
+       int sv_g_argc;
+       char **sv_g_argv;
+
+       sv_argv0 = argv[0];
+       sv_g_malloced = G.global_args_malloced;
+       sv_g_argc = G.global_argc;
+       sv_g_argv = G.global_argv;
+
+       pp = argv;
+       n = 1;
+       while (*++pp)
+               n++;
+
+       argv[0] = G.global_argv[0]; /* retain $0 */
+       G.global_args_malloced = 0;
+       G.global_argc = n;
+       G.global_argv = argv;
+
+       /* On MMU, funcp->body is always non-NULL */
+#if !BB_MMU
+       if (!funcp->body) {
+               /* Function defined by -F */
+               parse_and_run_string(funcp->body_as_string);
+               n = G.last_exitcode;
+       } else
+#endif
+       {
+               n = run_list(funcp->body);
+       }
+
+       if (G.global_args_malloced) {
+               /* function ran "set -- arg1 arg2 ..." */
+               pp = G.global_argv;
+               while (*++pp)
+                       free(*pp);
+               free(G.global_argv);
+       }
+
+       argv[0] = sv_argv0;
+       G.global_args_malloced = sv_g_malloced;
+       G.global_argc = sv_g_argc;
+       G.global_argv = sv_g_argv;
+
+       return n;
+}
+#endif
+
+
+#if BB_MMU
 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
        pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
 #define pseudo_exec(nommu_save, command, argv_expanded) \
        pseudo_exec(command, argv_expanded)
 #endif
 
-/* Called after [v]fork() in run_pipe(), or from builtin_exec().
+/* Called after [v]fork() in run_pipe, or from builtin_exec.
  * Never returns.
  * XXX no exit() here.  If you don't exec, use _exit instead.
  * The at_exit handlers apparently confuse the calling process,
  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
-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, char **argv, int assignment_cnt, char **argv_expanded)
+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,
+               char **argv, int assignment_cnt,
+               char **argv_expanded)
 {
-       int rcode;
        char **new_env;
-       const struct built_in_command *x;
 
-       /* If a variable is assigned in a forest, and nobody listens,
-        * was it ever really set?
-        */
+       /* Case when we are here: ... | var=val | ... */
        if (!argv[assignment_cnt])
                _exit(EXIT_SUCCESS);
 
@@ -2254,79 +2852,117 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignme
        if (argv_expanded) {
                argv = argv_expanded;
        } else {
-               argv = expand_strvec_to_strvec(argv);
+               argv = expand_strvec_to_strvec(argv + assignment_cnt);
 #if !BB_MMU
                nommu_save->argv = argv;
 #endif
        }
 
-       /*
-        * Check if the command matches any of the builtins.
+#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
+       if (strchr(argv[0], '/') != NULL)
+               goto skip;
+#endif
+
+       /* On NOMMU, we must never block!
+        * Example: { sleep 99999 | read line } & echo Ok
+        * read builtin will block on read syscall, leaving parent blocked
+        * in vfork. Therefore we can't do this:
+        */
+#if BB_MMU
+       /* Check if the command matches any of the builtins.
         * Depending on context, this might be redundant.  But it's
         * easier to waste a few CPU cycles than it is to figure out
         * if this is one of those cases.
         */
-       for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
-               if (strcmp(argv[0], x->cmd) == 0) {
-                       debug_printf_exec("running builtin '%s'\n", argv[0]);
+       {
+               int rcode;
+               const struct built_in_command *x = find_builtin(argv[0]);
+               if (x) {
                        rcode = x->function(argv);
-                       fflush(stdout);
+                       fflush(NULL);
                        _exit(rcode);
                }
        }
+#endif
+#if ENABLE_HUSH_FUNCTIONS
+       /* Check if the command matches any functions */
+       {
+               const struct function *funcp = find_function(argv[0]);
+               if (funcp) {
+                       exec_function(funcp, argv);
+               }
+       }
+#endif
 
-       /* Check if the command matches any busybox applets */
 #if ENABLE_FEATURE_SH_STANDALONE
-       if (strchr(argv[0], '/') == NULL) {
+       /* Check if the command matches any busybox applets */
+       {
                int a = find_applet_by_name(argv[0]);
                if (a >= 0) {
+# if BB_MMU /* see above why on NOMMU it is not allowed */
                        if (APPLET_IS_NOEXEC(a)) {
                                debug_printf_exec("running applet '%s'\n", argv[0]);
-// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
                                run_applet_no_and_exit(a, argv);
                        }
-                       /* re-exec ourselves with the new arguments */
+# endif
+                       /* Re-exec ourselves */
                        debug_printf_exec("re-execing applet '%s'\n", argv[0]);
-                       execvp(bb_busybox_exec_path, argv);
+                       sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
+                       execv(bb_busybox_exec_path, argv);
                        /* If they called chroot or otherwise made the binary no longer
                         * executable, fall through */
                }
        }
 #endif
 
-       sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
-
+#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 exec '%s'", argv[0]);
        _exit(EXIT_FAILURE);
 }
 
-static int run_list(struct pipe *pi);
-
-/* Called after [v]fork() in run_pipe()
+/* Called after [v]fork() in run_pipe
  */
-static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
-static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
+static void pseudo_exec(nommu_save_t *nommu_save,
+               struct command *command,
+               char **argv_expanded) NORETURN;
+static void pseudo_exec(nommu_save_t *nommu_save,
+               struct command *command,
+               char **argv_expanded)
 {
-       if (command->argv)
-               pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
+       if (command->argv) {
+               pseudo_exec_argv(nommu_save, command->argv,
+                               command->assignment_cnt, argv_expanded);
+       }
 
        if (command->group) {
-#if !BB_MMU
-               bb_error_msg_and_die("nested lists are not supported on NOMMU");
-#else
+               /* Cases when we are here:
+                * ( list )
+                * { list } &
+                * ... | ( list ) | ...
+                * ... | { list } | ...
+                */
+#if BB_MMU
                int rcode;
                debug_printf_exec("pseudo_exec: run_list\n");
+               reset_traps_to_defaults();
                rcode = run_list(command->group);
                /* OK to leak memory by not calling free_pipe_list,
                 * since this process is about to exit */
                _exit(rcode);
+#else
+               re_execute_shell(command->group_as_string,
+                               G.global_argv[0],
+                               G.global_argv + 1);
 #endif
        }
 
-       /* Can happen.  See what bash does with ">foo" by itself. */
-       debug_printf("trying to pseudo_exec null command\n");
+       /* Case when we are here: ... | >file */
+       debug_printf_exec("pseudo_exec'ed null command\n");
        _exit(EXIT_SUCCESS);
 }
 
@@ -2398,7 +3034,7 @@ static void insert_bg_job(struct pipe *pi)
 
        /* We don't wait for background thejobs to return -- append it
           to the list of backgrounded thejobs and leave it alone */
-       if (G.interactive_fd)
+       if (G_interactive_fd)
                printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
        G.last_bg_pid = thejob->cmds[0].pid;
        G.last_jobid = thejob->jobid;
@@ -2427,7 +3063,7 @@ static void delete_finished_bg_job(struct pipe *pi)
 {
        remove_bg_job(pi);
        pi->stopped_cmds = 0;
-       free_pipe(pi, 0);
+       free_pipe(pi);
        free(pi);
 }
 #endif /* JOB */
@@ -2548,7 +3184,7 @@ static int checkjobs(struct pipe* fg_pipe)
                        pi->cmds[i].pid = 0;
                        pi->alive_cmds--;
                        if (!pi->alive_cmds) {
-                               if (G.interactive_fd)
+                               if (G_interactive_fd)
                                        printf(JOB_STATUS_FORMAT, pi->jobid,
                                                        "Done", pi->cmdtext);
                                delete_finished_bg_job(pi);
@@ -2572,145 +3208,216 @@ static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
        /* Job finished, move the shell to the foreground */
        p = getpgid(0); /* pgid of our process */
        debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
-       tcsetpgrp(G.interactive_fd, p);
+       tcsetpgrp(G_interactive_fd, p);
        return rcode;
 }
 #endif
 
-/* run_pipe() starts all the jobs, but doesn't wait for anything
- * to finish.  See checkjobs().
+/* Start all the jobs, but don't wait for anything to finish.
+ * See checkjobs().
  *
- * return code is normally -1, when the caller has to wait for children
+ * Return code is normally -1, when the caller has to wait for children
  * to finish to determine the exit status of the pipe.  If the pipe
  * is a simple builtin command, however, the action is done by the
  * time run_pipe returns, and the exit code is provided as the
  * return value.
  *
- * The input of the pipe is always stdin, the output is always
- * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
- * because it tries to avoid running the command substitution in
- * subshell, when that is in fact necessary.  The subshell process
- * now has its stdout directed to the input of the appropriate pipe,
- * so this routine is noticeably simpler.
- *
  * Returns -1 only if started some children. IOW: we have to
  * mask out retvals of builtins etc with 0xff!
+ *
+ * The only case when we do not need to [v]fork is when the pipe
+ * is single, non-backgrounded, non-subshell command. Examples:
+ * cmd ; ...   { list } ; ...
+ * cmd && ...  { list } && ...
+ * cmd || ...  { list } || ...
+ * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
+ * or (if SH_STANDALONE) an applet, and we can run the { list }
+ * with run_list(). If it isn't one of these, we fork and exec cmd.
+ *
+ * Cases when we must fork:
+ * non-single:   cmd | cmd
+ * backgrounded: cmd &     { list } &
+ * subshell:     ( list ) [&]
  */
 static int run_pipe(struct pipe *pi)
 {
+       static const char *const null_ptr = NULL;
        int i;
        int nextin;
        int pipefds[2];         /* pipefds[0] is for reading */
        struct command *command;
        char **argv_expanded;
        char **argv;
-       const struct built_in_command *x;
        char *p;
        /* it is not always needed, but we aim to smaller code */
        int squirrel[] = { -1, -1, -1 };
        int rcode;
-       const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
 
-       debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
+       debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
+       debug_enter();
 
-#if ENABLE_HUSH_JOB
-       pi->pgrp = -1;
-#endif
-       pi->alive_cmds = 1;
+       USE_HUSH_JOB(pi->pgrp = -1;)
        pi->stopped_cmds = 0;
-
-       /* Check if this is a simple builtin (not part of a pipe).
-        * Builtins within pipes have to fork anyway, and are handled in
-        * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
-        */
        command = &(pi->cmds[0]);
+       argv_expanded = NULL;
 
-#if ENABLE_HUSH_FUNCTIONS
-       if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
-               /* We "execute" function definition */
-               bb_error_msg("here we ought to remember function definition, and go on");
-               return EXIT_SUCCESS;
+       if (pi->num_cmds != 1
+        || pi->followup == PIPE_BG
+        || command->grp_type == GRP_SUBSHELL
+       ) {
+               goto must_fork;
        }
+
+       pi->alive_cmds = 1;
+
+       debug_printf_exec(": group:%p argv:'%s'\n",
+               command->group, command->argv ? command->argv[0] : "NONE");
+
+       if (command->group) {
+#if ENABLE_HUSH_FUNCTIONS
+               if (command->grp_type == GRP_FUNCTION) {
+                       /* "executing" func () { list } */
+                       struct function *funcp;
+
+                       funcp = new_function(command->argv[0]);
+                       /* funcp->name is already set to argv[0] */
+                       funcp->body = command->group;
+#if !BB_MMU
+                       funcp->body_as_string = command->group_as_string;
+                       command->group_as_string = NULL;
 #endif
+                       command->group = NULL;
+                       command->argv[0] = NULL;
+                       debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
+                       funcp->parent_cmd = command;
+                       command->child_func = funcp;
 
-       if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
-               debug_printf("non-subshell grouping\n");
-               setup_redirects(command, squirrel);
-               debug_printf_exec(": run_list\n");
-               rcode = run_list(command->group) & 0xff;
+                       debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
+                       debug_leave();
+                       return EXIT_SUCCESS;
+               }
+#endif
+               /* { list } */
+               debug_printf("non-subshell group\n");
+               rcode = 1; /* exitcode if redir failed */
+               if (setup_redirects(command, squirrel) == 0) {
+                       debug_printf_exec(": run_list\n");
+                       rcode = run_list(command->group) & 0xff;
+               }
                restore_redirects(squirrel);
-               debug_printf_exec("run_pipe return %d\n", rcode);
                IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
+               debug_leave();
+               debug_printf_exec("run_pipe: return %d\n", rcode);
                return rcode;
        }
 
-       argv = command->argv;
-       argv_expanded = NULL;
-
-       if (single_and_fg && argv != NULL) {
+       argv = command->argv ? command->argv : (char **) &null_ptr;
+       {
+               const struct built_in_command *x;
+#if ENABLE_HUSH_FUNCTIONS
+               const struct function *funcp;
+#else
+               enum { funcp = 0 };
+#endif
                char **new_env = NULL;
                char **old_env = NULL;
 
-               i = command->assignment_cnt;
-               if (i != 0 && argv[i] == NULL) {
-                       /* assignments, but no command: set local environment */
-                       for (i = 0; argv[i] != NULL; i++) {
-                               debug_printf("local environment set: %s\n", argv[i]);
-                               p = expand_string_to_string(argv[i]);
-                               set_local_var(p, 0);
+               if (argv[command->assignment_cnt] == NULL) {
+                       /* Assignments, but no command */
+                       /* Ensure redirects take effect. Try "a=t >file" */
+                       rcode = setup_redirects(command, squirrel);
+                       restore_redirects(squirrel);
+                       /* Set shell variables */
+                       while (*argv) {
+                               p = expand_string_to_string(*argv);
+                               debug_printf_exec("set shell var:'%s'->'%s'\n",
+                                               *argv, p);
+                               set_local_var(p, 0, 0);
+                               argv++;
                        }
-                       return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
+                       /* Do we need to flag set_local_var() errors?
+                        * "assignment to readonly var" and "putenv error"
+                        */
+                       IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
+                       debug_leave();
+                       debug_printf_exec("run_pipe: return %d\n", rcode);
+                       return rcode;
                }
 
                /* Expand the rest into (possibly) many strings each */
-               argv_expanded = expand_strvec_to_strvec(argv + i);
+               argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
 
-               for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
-                       if (strcmp(argv_expanded[0], x->cmd) != 0)
-                               continue;
-                       if (x->function == builtin_exec && argv_expanded[1] == NULL) {
-                               debug_printf("exec with redirects only\n");
-                               setup_redirects(command, NULL);
-                               rcode = EXIT_SUCCESS;
-                               goto clean_up_and_ret1;
+               x = find_builtin(argv_expanded[0]);
+#if ENABLE_HUSH_FUNCTIONS
+               funcp = NULL;
+               if (!x)
+                       funcp = find_function(argv_expanded[0]);
+#endif
+               if (x || funcp) {
+                       if (!funcp) {
+                               if (x->function == builtin_exec && argv_expanded[1] == NULL) {
+                                       debug_printf("exec with redirects only\n");
+                                       rcode = setup_redirects(command, NULL);
+                                       goto clean_up_and_ret1;
+                               }
                        }
-                       debug_printf("builtin inline %s\n", argv_expanded[0]);
                        /* XXX setup_redirects acts on file descriptors, not FILEs.
                         * This is perfect for work that comes after exec().
                         * Is it really safe for inline use?  Experimentally,
                         * things seem to work with glibc. */
-                       setup_redirects(command, squirrel);
-                       new_env = expand_assignments(argv, command->assignment_cnt);
-                       old_env = putenv_all_and_save_old(new_env);
-                       debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
-                       rcode = x->function(argv_expanded) & 0xff;
+                       rcode = setup_redirects(command, squirrel);
+                       if (rcode == 0) {
+                               new_env = expand_assignments(argv, command->assignment_cnt);
+                               old_env = putenv_all_and_save_old(new_env);
+                               if (!funcp) {
+                                       debug_printf_exec(": builtin '%s' '%s'...\n",
+                                               x->cmd, argv_expanded[1]);
+                                       rcode = x->function(argv_expanded) & 0xff;
+                               }
+#if ENABLE_HUSH_FUNCTIONS
+                               else {
+                                       debug_printf_exec(": function '%s' '%s'...\n",
+                                               funcp->name, argv_expanded[1]);
+                                       rcode = run_function(funcp, argv_expanded) & 0xff;
+                               }
+#endif
+                       }
 #if ENABLE_FEATURE_SH_STANDALONE
  clean_up_and_ret:
 #endif
                        restore_redirects(squirrel);
                        free_strings_and_unsetenv(new_env, 1);
                        putenv_all(old_env);
-                       free(old_env); /* not free_strings()! */
+                       /* Free the pointers, but the strings themselves
+                        * are in environ now, don't use free_strings! */
+                       free(old_env);
  clean_up_and_ret1:
                        free(argv_expanded);
                        IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
+                       debug_leave();
                        debug_printf_exec("run_pipe return %d\n", rcode);
                        return rcode;
                }
+
 #if ENABLE_FEATURE_SH_STANDALONE
                i = find_applet_by_name(argv_expanded[0]);
                if (i >= 0 && APPLET_IS_NOFORK(i)) {
-                       setup_redirects(command, squirrel);
-                       save_nofork_data(&G.nofork_save);
-                       new_env = expand_assignments(argv, command->assignment_cnt);
-                       old_env = putenv_all_and_save_old(new_env);
-                       debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
-                       rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
+                       rcode = setup_redirects(command, squirrel);
+                       if (rcode == 0) {
+                               save_nofork_data(&G.nofork_save);
+                               new_env = expand_assignments(argv, command->assignment_cnt);
+                               old_env = putenv_all_and_save_old(new_env);
+                               debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
+                                       argv_expanded[0], argv_expanded[1]);
+                               rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
+                       }
                        goto clean_up_and_ret;
                }
 #endif
+               /* It is neither builtin nor applet. We must fork. */
        }
 
+ must_fork:
        /* NB: argv_expanded may already be created, and that
         * might include `cmd` runs! Do not rerun it! We *must*
         * use argv_expanded if it's non-NULL */
@@ -2728,9 +3435,11 @@ static int run_pipe(struct pipe *pi)
 #endif
                command = &(pi->cmds[i]);
                if (command->argv) {
-                       debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
-               } else
+                       debug_printf_exec(": pipe member '%s' '%s'...\n",
+                                       command->argv[0], command->argv[1]);
+               } else {
                        debug_printf_exec(": pipe member with no argv\n");
+               }
 
                /* pipes are inserted between pairs of commands */
                pipefds[0] = 0;
@@ -2741,11 +3450,11 @@ static int run_pipe(struct pipe *pi)
                command->pid = BB_MMU ? fork() : vfork();
                if (!command->pid) { /* child */
 #if ENABLE_HUSH_JOB
-                       die_sleep = 0; /* let nofork's xfuncs die */
+                       disable_restore_tty_pgrp_on_exit();
 
                        /* Every child adds itself to new process group
                         * with pgid == pid_of_first_child_in_pipe */
-                       if (G.run_list_level == 1 && G.interactive_fd) {
+                       if (G.run_list_level == 1 && G_interactive_fd) {
                                pid_t pgrp;
                                pgrp = pi->pgrp;
                                if (pgrp < 0) /* true for 1st process only */
@@ -2753,7 +3462,7 @@ static int run_pipe(struct pipe *pi)
                                if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
                                        /* We do it in *every* child, not just first,
                                         * to avoid races */
-                                       tcsetpgrp(G.interactive_fd, pgrp);
+                                       tcsetpgrp(G_interactive_fd, pgrp);
                                }
                        }
 #endif
@@ -2763,7 +3472,8 @@ static int run_pipe(struct pipe *pi)
                                close(pipefds[0]); /* read end */
                        /* Like bash, explicit redirects override pipes,
                         * and the pipe fd is available for dup'ing. */
-                       setup_redirects(command, NULL);
+                       if (setup_redirects(command, NULL))
+                               _exit(1);
 
                        /* Restore default handlers just prior to exec */
                        /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
@@ -2774,12 +3484,18 @@ static int run_pipe(struct pipe *pi)
                        pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
                        /* pseudo_exec() does not return */
                }
-               /* parent */
+
+               /* parent or error */
+               enable_restore_tty_pgrp_on_exit();
 #if !BB_MMU
                /* Clean up after vforked child */
+               clean_up_after_re_execute();
                free(nommu_save.argv);
                free_strings_and_unsetenv(nommu_save.new_env, 1);
                putenv_all(nommu_save.old_env);
+               /* Free the pointers, but the strings themselves
+                * are in environ now, don't use free_strings! */
+               free(nommu_save.old_env);
 #endif
                free(argv_expanded);
                argv_expanded = NULL;
@@ -2804,10 +3520,12 @@ static int run_pipe(struct pipe *pi)
        }
 
        if (!pi->alive_cmds) {
+               debug_leave();
                debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
                return 1;
        }
 
+       debug_leave();
        debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
        return -1;
 }
@@ -2850,8 +3568,8 @@ static void debug_print_tree(struct pipe *pi, int lvl)
                [RES_SNTX ] = "SNTX" ,
        };
        static const char *const GRPTYPE[] = {
-               "()",
                "{}",
+               "()",
 #if ENABLE_HUSH_FUNCTIONS
                "func()",
 #endif
@@ -2868,7 +3586,9 @@ static void debug_print_tree(struct pipe *pi, int lvl)
                        struct command *command = &pi->cmds[prn];
                        char **argv = command->argv;
 
-                       fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
+                       fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
+                                       lvl*2, "", prn,
+                                       command->assignment_cnt);
                        if (command->group) {
                                fprintf(stderr, " group %s: (argv=%p)\n",
                                                GRPTYPE[command->grp_type],
@@ -2903,17 +3623,20 @@ static int run_list(struct pipe *pi)
        char **for_lcur = NULL;
        char **for_list = NULL;
 #endif
-       smallint flag_skip = 1;
-       smalluint rcode = 0; /* probably just for compiler */
+       smallint last_followup;
+       smalluint rcode;
 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
        smalluint cond_code = 0;
 #else
-       enum { cond_code = 0, };
+       enum { cond_code = 0 };
+#endif
+#if HAS_KEYWORDS
+       smallint rword; /* enum reserved_style */
+       smallint last_rword; /* ditto */
 #endif
-       /*enum reserved_style*/ smallint rword = RES_NONE;
-       /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
 
        debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
+       debug_enter();
 
 #if ENABLE_HUSH_LOOPS
        /* Check syntax for "for" */
@@ -2922,7 +3645,8 @@ static int run_list(struct pipe *pi)
                        continue;
                /* current word is FOR or IN (BOLD in comments below) */
                if (cpipe->next == NULL) {
-                       syntax("malformed for");
+                       syntax_error("malformed for");
+                       debug_leave();
                        debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
                        return 1;
                }
@@ -2933,7 +3657,8 @@ static int run_list(struct pipe *pi)
                if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
                 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
                ) {
-                       syntax("malformed for");
+                       syntax_error("malformed for");
+                       debug_leave();
                        debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
                        return 1;
                }
@@ -2951,7 +3676,7 @@ static int run_list(struct pipe *pi)
         * We are saving state before entering outermost list ("while...done")
         * so that ctrl-Z will correctly background _entire_ outermost list,
         * not just a part of it (like "sleep 1 | exit 2") */
-       if (++G.run_list_level == 1 && G.interactive_fd) {
+       if (++G.run_list_level == 1 && G_interactive_fd) {
                if (sigsetjmp(G.toplevel_jb, 1)) {
                        /* ctrl-Z forked and we are parent; or ctrl-C.
                         * Sighandler has longjmped us here */
@@ -2982,23 +3707,29 @@ static int run_list(struct pipe *pi)
 ////           /* ctrl-Z handler will store pid etc in pi */
 ////           G.toplevel_list = pi;
 ////           G.ctrl_z_flag = 0;
-////#if ENABLE_FEATURE_SH_STANDALONE
-////           G.nofork_save.saved = 0; /* in case we will run a nofork later */
-////#endif
+#if ENABLE_FEATURE_SH_STANDALONE
+               G.nofork_save.saved = 0; /* in case we will run a nofork later */
+#endif
 ////           signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
 ////           signal(SIGINT, handler_ctrl_c);
        }
 #endif /* JOB */
 
+#if HAS_KEYWORDS
+       rword = RES_NONE;
+       last_rword = RES_XXXX;
+#endif
+       last_followup = PIPE_SEQ;
+       rcode = G.last_exitcode;
+
        /* Go through list of pipes, (maybe) executing them. */
        for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
                if (G.flag_SIGINT)
                        break;
 
                IF_HAS_KEYWORDS(rword = pi->res_word;)
-               IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
-               debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
-                               rword, cond_code, skip_more_for_this_rword);
+               debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
+                               rword, cond_code, last_rword);
 #if ENABLE_HUSH_LOOPS
                if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
                 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
@@ -3008,18 +3739,25 @@ static int run_list(struct pipe *pi)
                        G.depth_of_loop++;
                }
 #endif
-               if (rword == skip_more_for_this_rword && flag_skip) {
-                       if (pi->followup == PIPE_SEQ)
-                               flag_skip = 0;
-                       /* it is "<false> && CMD" or "<true> || CMD"
-                        * and we should not execute CMD */
-                       continue;
+               /* Still in the same "if...", "then..." or "do..." branch? */
+               if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
+                       if ((rcode == 0 && last_followup == PIPE_OR)
+                        || (rcode != 0 && last_followup == PIPE_AND)
+                       ) {
+                               /* It is "<true> || CMD" or "<false> && CMD"
+                                * and we should not execute CMD */
+                               debug_printf_exec("skipped cmd because of || or &&\n");
+                               last_followup = pi->followup;
+                               continue;
+                       }
                }
-               flag_skip = 1;
-               skip_more_for_this_rword = RES_XXXX;
+               last_followup = pi->followup;
+               IF_HAS_KEYWORDS(last_rword = rword;)
 #if ENABLE_HUSH_IF
                if (cond_code) {
                        if (rword == RES_THEN) {
+                               /* if false; then ... fi has exitcode 0! */
+                               G.last_exitcode = rcode = EXIT_SUCCESS;
                                /* "if <false> THEN cmd": skip cmd */
                                continue;
                        }
@@ -3047,8 +3785,11 @@ static int run_list(struct pipe *pi)
                                vals = (char**)encoded_dollar_at_argv;
                                if (pi->next->res_word == RES_IN) {
                                        /* if no variable values after "in" we skip "for" */
-                                       if (!pi->next->cmds[0].argv)
+                                       if (!pi->next->cmds[0].argv) {
+                                               G.last_exitcode = rcode = EXIT_SUCCESS;
+                                               debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
                                                break;
+                                       }
                                        vals = pi->next->cmds[0].argv;
                                } /* else: "for var; do..." -> assume "$@" list */
                                /* create list of variable values */
@@ -3068,13 +3809,14 @@ static int run_list(struct pipe *pi)
                                pi->cmds[0].argv[0] = for_varname;
                                break;
                        }
-                       /* insert next value from for_lcur */
-//TODO: does it need escaping?
+                       /* Insert next value from for_lcur */
+                       /* note: *for_lcur already has quotes removed, $var expanded, etc */
                        pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
                        pi->cmds[0].assignment_cnt = 1;
                }
-               if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
-                       continue;
+               if (rword == RES_IN) {
+                       continue; /* "for v IN list;..." - "in" has no cmds anyway */
+               }
                if (rword == RES_DONE) {
                        continue; /* "done" has no cmds too */
                }
@@ -3114,14 +3856,14 @@ static int run_list(struct pipe *pi)
                 * OTOH, in non-interactive shell this is useless
                 * and only leads to extra job checks */
                if (pi->num_cmds == 0) {
-                       if (G.interactive_fd)
+                       if (G_interactive_fd)
                                goto check_jobs_and_continue;
                        continue;
                }
 
                /* After analyzing all keywords and conditions, we decided
                 * to execute this pipe. NB: have to do checkjobs(NULL)
-                * after run_pipe() to collect any background children,
+                * after run_pipe to collect any background children,
                 * even if list execution is to be stopped. */
                debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
                {
@@ -3131,14 +3873,16 @@ static int run_list(struct pipe *pi)
 #endif
                        rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
                        if (r != -1) {
-                               /* we only ran a builtin: rcode is already known
+                               /* We only ran a builtin: rcode is already known
                                 * and we don't need to wait for anything. */
+                               G.last_exitcode = rcode;
+                               debug_printf_exec(": builtin/func exitcode %d\n", rcode);
                                check_and_run_traps(0);
 #if ENABLE_HUSH_LOOPS
-                               /* was it "break" or "continue"? */
+                               /* Was it "break" or "continue"? */
                                if (G.flag_break_continue) {
                                        smallint fbc = G.flag_break_continue;
-                                       /* we might fall into outer *loop*,
+                                       /* We might fall into outer *loop*,
                                         * don't want to break it too */
                                        if (loop_top) {
                                                G.depth_break_continue--;
@@ -3154,7 +3898,7 @@ static int run_list(struct pipe *pi)
                                }
 #endif
                        } else if (pi->followup == PIPE_BG) {
-                               /* what does bash do with attempts to background builtins? */
+                               /* What does bash do with attempts to background builtins? */
                                /* even bash 3.2 doesn't do that well with nested bg:
                                 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
                                 * I'm NOT treating inner &'s as jobs */
@@ -3163,25 +3907,25 @@ static int run_list(struct pipe *pi)
                                if (G.run_list_level == 1)
                                        insert_bg_job(pi);
 #endif
-                               rcode = 0; /* EXIT_SUCCESS */
+                               G.last_exitcode = rcode = EXIT_SUCCESS;
+                               debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
                        } else {
 #if ENABLE_HUSH_JOB
-                               if (G.run_list_level == 1 && G.interactive_fd) {
-                                       /* waits for completion, then fg's main shell */
+                               if (G.run_list_level == 1 && G_interactive_fd) {
+                                       /* Waits for completion, then fg's main shell */
                                        rcode = checkjobs_and_fg_shell(pi);
+                                       debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
                                        check_and_run_traps(0);
-                                       debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
                                } else
 #endif
-                               { /* this one just waits for completion */
+                               { /* This one just waits for completion */
                                        rcode = checkjobs(pi);
+                                       debug_printf_exec(": checkjobs exitcode %d\n", rcode);
                                        check_and_run_traps(0);
-                                       debug_printf_exec(": checkjobs returned %d\n", rcode);
                                }
+                               G.last_exitcode = rcode;
                        }
                }
-               debug_printf_exec(": setting last_return_code=%d\n", rcode);
-               G.last_return_code = rcode;
 
                /* Analyze how result affects subsequent commands */
 #if ENABLE_HUSH_IF
@@ -3189,25 +3933,26 @@ static int run_list(struct pipe *pi)
                        cond_code = rcode;
 #endif
 #if ENABLE_HUSH_LOOPS
-               if (rword == RES_WHILE) {
-                       if (rcode) {
-                               rcode = 0; /* "while false; do...done" - exitcode 0 */
-                               goto check_jobs_and_break;
+               /* Beware of "while false; true; do ..."! */
+               if (pi->next && pi->next->res_word == RES_DO) {
+                       if (rword == RES_WHILE) {
+                               if (rcode) {
+                                       /* "while false; do...done" - exitcode 0 */
+                                       G.last_exitcode = rcode = EXIT_SUCCESS;
+                                       debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
+                                       goto check_jobs_and_break;
+                               }
                        }
-               }
-               if (rword == RES_UNTIL) {
-                       if (!rcode) {
+                       if (rword == RES_UNTIL) {
+                               if (!rcode) {
+                                       debug_printf_exec(": until expr is true: breaking\n");
  check_jobs_and_break:
-                               checkjobs(NULL);
-                               break;
+                                       checkjobs(NULL);
+                                       break;
+                               }
                        }
                }
 #endif
-               if ((rcode == 0 && pi->followup == PIPE_OR)
-                || (rcode != 0 && pi->followup == PIPE_AND)
-               ) {
-                       skip_more_for_this_rword = rword;
-               }
 
  check_jobs_and_continue:
                checkjobs(NULL);
@@ -3222,12 +3967,11 @@ static int run_list(struct pipe *pi)
 ////   }
  ret:
        G.run_list_level--;
-////   if (!G.run_list_level && G.interactive_fd) {
+////   if (!G.run_list_level && G_interactive_fd) {
 ////           signal(SIGTSTP, SIG_IGN);
 ////           signal(SIGINT, SIG_IGN);
 ////   }
 #endif
-       debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
 #if ENABLE_HUSH_LOOPS
        if (loop_top)
                G.depth_of_loop--;
@@ -3236,6 +3980,8 @@ static int run_list(struct pipe *pi)
 #if ENABLE_HUSH_CASE
        free(case_word);
 #endif
+       debug_leave();
+       debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
        return rcode;
 }
 
@@ -3245,96 +3991,18 @@ static int run_and_free_list(struct pipe *pi)
        int rcode = 0;
        debug_printf_exec("run_and_free_list entered\n");
        if (!G.fake_mode) {
-               debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
+               debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
                rcode = run_list(pi);
        }
        /* free_pipe_list has the side effect of clearing memory.
         * In the long run that function can be merged with run_list,
         * but doing that now would hobble the debugging effort. */
-       free_pipe_list(pi, /* indent: */ 0);
+       free_pipe_list(pi);
        debug_printf_exec("run_and_free_list return %d\n", rcode);
        return rcode;
 }
 
 
-/* Peek ahead in the in_str to find out if we have a "&n" construct,
- * as in "2>&1", that represents duplicating a file descriptor.
- * Return either -2 (syntax error), -1 (no &), or the number found.
- */
-static int redirect_dup_num(struct in_str *input)
-{
-       int ch, d = 0, ok = 0;
-       ch = i_peek(input);
-       if (ch != '&') return -1;
-
-       i_getch(input);  /* get the & */
-       ch = i_peek(input);
-       if (ch == '-') {
-               i_getch(input);
-               return -3;  /* "-" represents "close me" */
-       }
-       while (isdigit(ch)) {
-               d = d*10 + (ch-'0');
-               ok = 1;
-               i_getch(input);
-               ch = i_peek(input);
-       }
-       if (ok) return d;
-
-       bb_error_msg("ambiguous redirect");
-       return -2;
-}
-
-/* The src parameter allows us to peek forward to a possible &n syntax
- * for file descriptor duplication, e.g., "2>&1".
- * Return code is 0 normally, 1 if a syntax error is detected in src.
- * Resource errors (in xmalloc) cause the process to exit */
-static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
-       struct in_str *input)
-{
-       struct command *command = ctx->command;
-       struct redir_struct *redir = command->redirects;
-       struct redir_struct *last_redir = NULL;
-
-       /* Create a new redir_struct and drop it onto the end of the linked list */
-       while (redir) {
-               last_redir = redir;
-               redir = redir->next;
-       }
-       redir = xzalloc(sizeof(struct redir_struct));
-       /* redir->next = NULL; */
-       /* redir->rd_filename = NULL; */
-       if (last_redir) {
-               last_redir->next = redir;
-       } else {
-               command->redirects = redir;
-       }
-
-       redir->rd_type = style;
-       redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
-
-       debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
-
-       /* Check for a '2>&1' type redirect */
-       redir->dup = redirect_dup_num(input);
-       if (redir->dup == -2)
-               return 1;  /* syntax error */
-       if (redir->dup != -1) {
-               /* Erik had a check here that the file descriptor in question
-                * is legit; I postpone that to "run time"
-                * A "-" representation of "close me" shows up as a -3 here */
-               debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
-       } else {
-               /* We do _not_ try to open the file that src points to,
-                * since we need to return and let src be expanded first.
-                * Set ctx->pending_redirect, so we know what to do at the
-                * end of the next parsed word. */
-               ctx->pending_redirect = redir;
-       }
-       return 0;
-}
-
-
 static struct pipe *new_pipe(void)
 {
        struct pipe *pi;
@@ -3359,10 +4027,12 @@ static int done_command(struct parse_context *ctx)
                 && command->redirects == NULL
                ) {
                        debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
+                       memset(command, 0, sizeof(*command)); /* paranoia */
                        return pi->num_cmds;
                }
                pi->num_cmds++;
                debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
+               //debug_print_tree(ctx->list_head, 20);
        } else {
                debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
        }
@@ -3387,16 +4057,30 @@ static void done_pipe(struct parse_context *ctx, pipe_style type)
        /* Close previous command */
        not_null = done_command(ctx);
        ctx->pipe->followup = type;
-       IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
-       IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
-       IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
+#if HAS_KEYWORDS
+       ctx->pipe->pi_inverted = ctx->ctx_inverted;
+       ctx->ctx_inverted = 0;
+       ctx->pipe->res_word = ctx->ctx_res_w;
+#endif
 
        /* Without this check, even just <enter> on command line generates
         * tree of three NOPs (!). Which is harmless but annoying.
         * IOW: it is safe to do it unconditionally.
         * RES_NONE case is for "for a in; do ..." (empty IN set)
-        * to work, possibly other cases too. */
-       if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
+        * and other cases to work. */
+       if (not_null
+#if ENABLE_HUSH_IF
+        || ctx->ctx_res_w == RES_FI
+#endif
+#if ENABLE_HUSH_LOOPS
+        || ctx->ctx_res_w == RES_DONE
+        || ctx->ctx_res_w == RES_FOR
+        || ctx->ctx_res_w == RES_IN
+#endif
+#if ENABLE_HUSH_CASE
+        || ctx->ctx_res_w == RES_ESAC
+#endif
+       ) {
                struct pipe *new_p;
                debug_printf_parse("done_pipe: adding new pipe: "
                                "not_null:%d ctx->ctx_res_w:%d\n",
@@ -3404,7 +4088,6 @@ static void done_pipe(struct parse_context *ctx, pipe_style type)
                new_p = new_pipe();
                ctx->pipe->next = new_p;
                ctx->pipe = new_p;
-               ctx->command = NULL; /* needed! */
                /* RES_THEN, RES_DO etc are "sticky" -
                 * they remain set for commands inside if/while.
                 * This is used to control execution.
@@ -3420,11 +4103,13 @@ static void done_pipe(struct parse_context *ctx, pipe_style type)
                if (ctx->ctx_res_w == RES_MATCH)
                        ctx->ctx_res_w = RES_CASEI;
 #endif
+               ctx->command = NULL; /* trick done_command below */
                /* Create the memory for command, roughly:
                 * ctx->pipe->cmds = new struct command;
                 * ctx->command = &ctx->pipe->cmds[0];
                 */
                done_command(ctx);
+               //debug_print_tree(ctx->list_head, 10);
        }
        debug_printf_parse("done_pipe return\n");
 }
@@ -3440,7 +4125,6 @@ static void initialize_context(struct parse_context *ctx)
        done_command(ctx);
 }
 
-
 /* If a reserved word is found and processed, parse context is modified
  * and 1 is returned.
  */
@@ -3534,21 +4218,21 @@ static int reserved_word(o_string *word, struct parse_context *ctx)
 #endif
        if (r->flag == 0) { /* '!' */
                if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
-                       syntax(NULL);
+                       syntax_error("! ! command");
                        IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
                }
                ctx->ctx_inverted = 1;
                return 1;
        }
        if (r->flag & FLAG_START) {
-               struct parse_context *new;
-               debug_printf("push stack\n");
-               new = xmalloc(sizeof(*new));
-               *new = *ctx;   /* physical copy */
+               struct parse_context *old;
+               old = xmalloc(sizeof(*old));
+               debug_printf_parse("push stack %p\n", old);
+               *old = *ctx;   /* physical copy */
                initialize_context(ctx);
-               ctx->stack = new;
+               ctx->stack = old;
        } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
-               syntax(NULL);
+               syntax_error_at(word->data);
                ctx->ctx_res_w = RES_SNTX;
                return 1;
        }
@@ -3556,11 +4240,18 @@ static int reserved_word(o_string *word, struct parse_context *ctx)
        ctx->old_flag = r->flag;
        if (ctx->old_flag & FLAG_END) {
                struct parse_context *old;
-               debug_printf("pop stack\n");
                done_pipe(ctx, PIPE_SEQ);
+               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
+               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
                *ctx = *old;   /* physical copy */
                free(old);
        }
@@ -3569,47 +4260,76 @@ static int reserved_word(o_string *word, struct parse_context *ctx)
 }
 #endif
 
-//TODO: many, many callers don't check error from done_word()
-
 /* Word is complete, look at it and update parsing context.
- * Normal return is 0. Syntax errors return 1. */
+ * Normal return is 0. Syntax errors return 1.
+ * Note: on return, word is reset, but not o_free'd!
+ */
 static int done_word(o_string *word, struct parse_context *ctx)
 {
        struct command *command = ctx->command;
 
        debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
-       if (word->length == 0 && word->nonnull == 0) {
+       if (word->length == 0 && word->o_quoted == 0) {
                debug_printf_parse("done_word return 0: true null, ignored\n");
                return 0;
        }
-       /* If this word wasn't an assignment, next ones definitely
-        * can't be assignments. Even if they look like ones. */
-       if (word->o_assignment != DEFINITELY_ASSIGNMENT
-        && word->o_assignment != WORD_IS_KEYWORD
-       ) {
-               word->o_assignment = NOT_ASSIGNMENT;
-       } else {
-               if (word->o_assignment == DEFINITELY_ASSIGNMENT)
-                       command->assignment_cnt++;
-               word->o_assignment = MAYBE_ASSIGNMENT;
-       }
 
        if (ctx->pending_redirect) {
                /* We do not glob in e.g. >*.tmp case. bash seems to glob here
                 * only if run as "bash", not "sh" */
+               /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
+                * "2.7 Redirection
+                * ...the word that follows the redirection operator
+                * shall be subjected to tilde expansion, parameter expansion,
+                * command substitution, arithmetic expansion, and quote
+                * removal. Pathname expansion shall not be performed
+                * on the word by a non-interactive shell; an interactive
+                * shell may perform it, but shall do so only when
+                * the expansion would result in one word."
+                */
                ctx->pending_redirect->rd_filename = xstrdup(word->data);
-               word->o_assignment = NOT_ASSIGNMENT;
-               debug_printf("word stored in rd_filename: '%s'\n", word->data);
+               /* Cater for >\file case:
+                * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
+                * Same with heredocs:
+                * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
+                */
+               unbackslash(ctx->pending_redirect->rd_filename);
+               /* Is it <<"HEREDOC"? */
+               if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
+                && word->o_quoted
+               ) {
+                       ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
+               }
+               debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
+               ctx->pending_redirect = NULL;
        } else {
-               /* "{ echo foo; } echo bar" - bad */
-               /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
+               /* If this word wasn't an assignment, next ones definitely
+                * can't be assignments. Even if they look like ones. */
+               if (word->o_assignment != DEFINITELY_ASSIGNMENT
+                && word->o_assignment != WORD_IS_KEYWORD
+               ) {
+                       word->o_assignment = NOT_ASSIGNMENT;
+               } else {
+                       if (word->o_assignment == DEFINITELY_ASSIGNMENT)
+                               command->assignment_cnt++;
+                       word->o_assignment = MAYBE_ASSIGNMENT;
+               }
+
                if (command->group) {
-                       syntax(NULL);
-                       debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
+                       /* "{ echo foo; } echo bar" - bad */
+                       /* NB: bash allows e.g.:
+                        * if true; then { echo foo; } fi
+                        * while if false; then false; fi do break; done
+                        * and disallows:
+                        * while if false; then false; fi; do; break; done
+                        * TODO? */
+                       syntax_error_at(word->data);
+                       debug_printf_parse("done_word return 1: syntax error, "
+                                       "groups and arglists don't mix\n");
                        return 1;
                }
 #if HAS_KEYWORDS
-#if ENABLE_HUSH_CASE
+# if ENABLE_HUSH_CASE
                if (ctx->ctx_dsemicolon
                 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
                ) {
@@ -3617,23 +4337,23 @@ static int done_word(o_string *word, struct parse_context *ctx)
                        /* ctx->ctx_res_w = RES_MATCH; */
                        ctx->ctx_dsemicolon = 0;
                } else
-#endif
-
+# endif
                if (!command->argv /* if it's the first word... */
-#if ENABLE_HUSH_LOOPS
+# if ENABLE_HUSH_LOOPS
                 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
                 && ctx->ctx_res_w != RES_IN
-#endif
+# endif
                ) {
                        debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
                        if (reserved_word(word, ctx)) {
-                               o_reset(word);
-                               debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
+                               o_reset_to_empty_unquoted(word);
+                               debug_printf_parse("done_word return %d\n",
+                                               (ctx->ctx_res_w == RES_SNTX));
                                return (ctx->ctx_res_w == RES_SNTX);
                        }
                }
 #endif
-               if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
+               if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
                 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
                 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
                 /* (otherwise it's known to be not empty and is already safe) */
@@ -3656,19 +4376,26 @@ static int done_word(o_string *word, struct parse_context *ctx)
                        }
                }
                command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
+//SEGV, but good idea.
+//             command->argv = add_string_to_strings(command->argv, word->data);
+//             word->data = NULL;
+//             word->length = 0;
                debug_print_strings("word appended to argv", command->argv);
        }
 
-       o_reset(word);
-       ctx->pending_redirect = NULL;
-
 #if ENABLE_HUSH_LOOPS
-       /* Force FOR to have just one word (variable name) */
-       /* NB: basically, this makes hush see "for v in ..." syntax as if
-        * as it is "for v; in ...". FOR and IN become two pipe structs
-        * in parse tree. */
        if (ctx->ctx_res_w == RES_FOR) {
-//TODO: check that command->argv[0] is a valid variable name!
+               if (word->o_quoted
+                || !is_well_formed_var_name(command->argv[0], '\0')
+               ) {
+                       /* bash says just "not a valid identifier" */
+                       syntax_error("not a valid identifier in for");
+                       return 1;
+               }
+               /* Force FOR to have just one word (variable name) */
+               /* NB: basically, this makes hush see "for v in ..."
+                * syntax as if it is "for v; in ...". FOR and IN become
+                * two pipe structs in parse tree. */
                done_pipe(ctx, PIPE_SEQ);
        }
 #endif
@@ -3678,10 +4405,128 @@ static int done_word(o_string *word, struct parse_context *ctx)
                done_pipe(ctx, PIPE_SEQ);
        }
 #endif
+
+       o_reset_to_empty_unquoted(word);
+
        debug_printf_parse("done_word return 0\n");
        return 0;
 }
 
+
+/* Peek ahead in the input to find out if we have a "&n" construct,
+ * as in "2>&1", that represents duplicating a file descriptor.
+ * Return:
+ * REDIRFD_CLOSE if >&- "close fd" construct is seen,
+ * REDIRFD_SYNTAX_ERR if syntax error,
+ * REDIRFD_TO_FILE if no & was seen,
+ * or the number found.
+ */
+#if BB_MMU
+#define parse_redir_right_fd(as_string, input) \
+       parse_redir_right_fd(input)
+#endif
+static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
+{
+       int ch, d, ok;
+
+       ch = i_peek(input);
+       if (ch != '&')
+               return REDIRFD_TO_FILE;
+
+       ch = i_getch(input);  /* get the & */
+       nommu_addchr(as_string, ch);
+       ch = i_peek(input);
+       if (ch == '-') {
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
+               return REDIRFD_CLOSE;
+       }
+       d = 0;
+       ok = 0;
+       while (ch != EOF && isdigit(ch)) {
+               d = d*10 + (ch-'0');
+               ok = 1;
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
+               ch = i_peek(input);
+       }
+       if (ok) return d;
+
+//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
+
+       bb_error_msg("ambiguous redirect");
+       return REDIRFD_SYNTAX_ERR;
+}
+
+/* Return code is 0 normal, 1 if a syntax error is detected
+ */
+static int parse_redirect(struct parse_context *ctx,
+               int fd,
+               redir_type style,
+               struct in_str *input)
+{
+       struct command *command = ctx->command;
+       struct redir_struct *redir;
+       struct redir_struct **redirp;
+       int dup_num;
+
+       dup_num = REDIRFD_TO_FILE;
+       if (style != REDIRECT_HEREDOC) {
+               /* Check for a '>&1' type redirect */
+               dup_num = parse_redir_right_fd(&ctx->as_string, input);
+               if (dup_num == REDIRFD_SYNTAX_ERR)
+                       return 1;
+       } else {
+               int ch = i_peek(input);
+               dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
+               if (dup_num) { /* <<-... */
+                       ch = i_getch(input);
+                       nommu_addchr(&ctx->as_string, ch);
+                       ch = i_peek(input);
+               }
+       }
+
+       if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
+               int ch = i_peek(input);
+               if (ch == '|') {
+                       /* >|FILE redirect ("clobbering" >).
+                        * Since we do not support "set -o noclobber" yet,
+                        * >| and > are the same for now. Just eat |.
+                        */
+                       ch = i_getch(input);
+                       nommu_addchr(&ctx->as_string, ch);
+               }
+       }
+
+       /* Create a new redir_struct and append it to the linked list */
+       redirp = &command->redirects;
+       while ((redir = *redirp) != NULL) {
+               redirp = &(redir->next);
+       }
+       *redirp = redir = xzalloc(sizeof(*redir));
+       /* redir->next = NULL; */
+       /* redir->rd_filename = NULL; */
+       redir->rd_type = style;
+       redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
+
+       debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
+                               redir_table[style].descrip);
+
+       redir->rd_dup = dup_num;
+       if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
+               /* Erik had a check here that the file descriptor in question
+                * is legit; I postpone that to "run time"
+                * A "-" representation of "close me" shows up as a -3 here */
+               debug_printf_parse("duplicating redirect '%d>&%d'\n",
+                               redir->rd_fd, redir->rd_dup);
+       } else {
+               /* Set ctx->pending_redirect, so we know what to do at the
+                * end of the next parsed word. */
+               ctx->pending_redirect = redir;
+       }
+       return 0;
+}
+
 /* If a redirect is immediately preceded by a number, that number is
  * supposed to tell which file descriptor to redirect.  This routine
  * looks for such preceding numbers.  In an ideal world this routine
@@ -3690,99 +4535,187 @@ static int done_word(o_string *word, struct parse_context *ctx)
  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
- * A -1 output from this program means no valid number was found, so the
- * caller should use the appropriate default for this redirection.
+ *
+ * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
+ * "2.7 Redirection
+ * ... If n is quoted, the number shall not be recognized as part of
+ * the redirection expression. For example:
+ * echo \2>a
+ * writes the character 2 into file a"
+ * We are getting it right by setting ->o_quoted on any \<char>
+ *
+ * A -1 return means no valid number was found,
+ * the caller should use the appropriate default for this redirection.
+ */
+static int redirect_opt_num(o_string *o)
+{
+       int num;
+
+       if (o->data == NULL)
+               return -1;
+       num = bb_strtou(o->data, NULL, 10);
+       if (errno || num < 0)
+               return -1;
+       o_reset_to_empty_unquoted(o);
+       return num;
+}
+
+#if BB_MMU
+#define fetch_till_str(as_string, input, word, skip_tabs) \
+       fetch_till_str(input, word, skip_tabs)
+#endif
+static char *fetch_till_str(o_string *as_string,
+               struct in_str *input,
+               const char *word,
+               int skip_tabs)
+{
+       o_string heredoc = NULL_O_STRING;
+       int past_EOL = 0;
+       int ch;
+
+       goto jump_in;
+       while (1) {
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
+               if (ch == '\n') {
+                       if (strcmp(heredoc.data + past_EOL, word) == 0) {
+                               heredoc.data[past_EOL] = '\0';
+                               debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
+                               return heredoc.data;
+                       }
+                       do {
+                               o_addchr(&heredoc, ch);
+                               past_EOL = heredoc.length;
+ jump_in:
+                               do {
+                                       ch = i_getch(input);
+                                       nommu_addchr(as_string, ch);
+                               } while (skip_tabs && ch == '\t');
+                       } while (ch == '\n');
+               }
+               if (ch == EOF) {
+                       o_free_unsafe(&heredoc);
+                       return NULL;
+               }
+               o_addchr(&heredoc, ch);
+               nommu_addchr(as_string, ch);
+       }
+}
+
+/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
+ * and load them all. There should be exactly heredoc_cnt of them.
  */
-static int redirect_opt_num(o_string *o)
+static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
 {
-       int num;
+       struct pipe *pi = ctx->list_head;
 
-       if (o->length == 0)
-               return -1;
-       for (num = 0; num < o->length; num++) {
-               if (!isdigit(o->data[num])) {
-                       return -1;
+       while (pi && heredoc_cnt) {
+               int i;
+               struct command *cmd = pi->cmds;
+
+               debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
+                               pi->num_cmds,
+                               cmd->argv ? cmd->argv[0] : "NONE");
+               for (i = 0; i < pi->num_cmds; i++) {
+                       struct redir_struct *redir = cmd->redirects;
+
+                       debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
+                                       i, cmd->argv ? cmd->argv[0] : "NONE");
+                       while (redir) {
+                               if (redir->rd_type == REDIRECT_HEREDOC) {
+                                       char *p;
+
+                                       redir->rd_type = REDIRECT_HEREDOC2;
+                                       /* redir->dup is (ab)used to indicate <<- */
+                                       p = fetch_till_str(&ctx->as_string, input,
+                                               redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
+                                       if (!p) {
+                                               syntax_error("unexpected EOF in here document");
+                                               return 1;
+                                       }
+                                       free(redir->rd_filename);
+                                       redir->rd_filename = p;
+                                       heredoc_cnt--;
+                               }
+                               redir = redir->next;
+                       }
+                       cmd++;
                }
+               pi = pi->next;
        }
-       num = atoi(o->data);
-       o_reset(o);
-       return num;
+#if 0
+       /* Should be 0. If it isn't, it's a parse error */
+       if (heredoc_cnt)
+               bb_error_msg_and_die("heredoc BUG 2");
+#endif
+       return 0;
 }
 
-static int parse_stream(o_string *dest, struct parse_context *ctx,
-               struct in_str *input0, const char *end_trigger);
 
 #if ENABLE_HUSH_TICK
-static FILE *generate_stream_from_list(struct pipe *head)
+static FILE *generate_stream_from_string(const char *s)
 {
        FILE *pf;
        int pid, channel[2];
 
        xpipe(channel);
-/* *** NOMMU WARNING *** */
-/* By using vfork here, we suspend parent till child exits or execs.
- * If child will not do it before it fills the pipe, it can block forever
- * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
- * Try this script:
- * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
- * huge=`cat TESTFILE` # will block here forever
- * echo OK
- */
        pid = BB_MMU ? fork() : vfork();
        if (pid < 0)
                bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
+
        if (pid == 0) { /* child */
-               if (ENABLE_HUSH_JOB)
-                       die_sleep = 0; /* let nofork's xfuncs die */
-               close(channel[0]); /* NB: close _first_, then move fd! */
-               xmove_fd(channel[1], 1);
-               /* Prevent it from trying to handle ctrl-z etc */
-#if ENABLE_HUSH_JOB
-               G.run_list_level = 1;
-#endif
+               disable_restore_tty_pgrp_on_exit();
                /* Process substitution is not considered to be usual
                 * 'command execution'.
                 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
                 */
-               set_jobctrl_signals_to_IGN();
-
-               /* Note: freeing 'head' here would break NOMMU. */
-               _exit(run_list(head));
+               bb_signals(0
+                       + (1 << SIGTSTP)
+                       + (1 << SIGTTIN)
+                       + (1 << SIGTTOU)
+                       , SIG_IGN);
+               close(channel[0]); /* NB: close _first_, then move fd! */
+               xmove_fd(channel[1], 1);
+               /* Prevent it from trying to handle ctrl-z etc */
+               USE_HUSH_JOB(G.run_list_level = 1;)
+#if BB_MMU
+               reset_traps_to_defaults();
+               parse_and_run_string(s);
+               _exit(G.last_exitcode);
+#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
+        * echo OK
+        */
+               re_execute_shell(s,
+                               G.global_argv[0],
+                               G.global_argv + 1);
+#endif
        }
+
+       /* parent */
+       enable_restore_tty_pgrp_on_exit();
+       clean_up_after_re_execute();
        close(channel[1]);
        pf = fdopen(channel[0], "r");
        return pf;
-       /* 'head' is freed by the caller */
 }
 
 /* Return code is exit status of the process that is run. */
-static int process_command_subs(o_string *dest,
-               struct in_str *input,
-               const char *subst_end)
+static int process_command_subs(o_string *dest, const char *s)
 {
-       int retcode, ch, eol_cnt;
-       o_string result = NULL_O_STRING;
-       struct parse_context inner;
-       FILE *p;
+       FILE *pf;
        struct in_str pipe_str;
+       int ch, eol_cnt;
 
-       initialize_context(&inner);
-
-       /* Recursion to generate command */
-       retcode = parse_stream(&result, &inner, input, subst_end);
-       if (retcode != 0)
-               return retcode;  /* syntax error or EOF */
-       done_word(&result, &inner);
-       done_pipe(&inner, PIPE_SEQ);
-       o_free(&result);
-
-       p = generate_stream_from_list(inner.list_head);
-       if (p == NULL)
+       pf = generate_stream_from_string(s);
+       if (pf == NULL)
                return 1;
-       close_on_exec_on(fileno(p));
-       setup_file_in_str(&pipe_str, p);
+       close_on_exec_on(fileno(pf));
 
        /* Now send results of command back into original context */
+       setup_file_in_str(&pipe_str, pf);
        eol_cnt = 0;
        while ((ch = i_getch(&pipe_str)) != EOF) {
                if (ch == '\n') {
@@ -3799,13 +4732,13 @@ static int process_command_subs(o_string *dest,
        debug_printf("done reading from pipe, pclose()ing\n");
        /* Note: we got EOF, and we just close the read end of the pipe.
         * We do not wait for the `cmd` child to terminate. bash and ash do.
-        * Try this:
-        * echo `echo Hi; exec 1>&-; sleep 2`
+        * Try these:
+        * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
+        * `false`; echo $? - bash outputs "1"
         */
-       retcode = fclose(p);
-       free_pipe_list(inner.list_head, /* indent: */ 0);
-       debug_printf("closed FILE from child, retcode=%d\n", retcode);
-       return retcode;
+       fclose(pf);
+       debug_printf("closed FILE from child. return 0\n");
+       return 0;
 }
 #endif
 
@@ -3813,45 +4746,92 @@ static int parse_group(o_string *dest, struct parse_context *ctx,
        struct in_str *input, int ch)
 {
        /* dest contains characters seen prior to ( or {.
-        * Typically it's empty, but for functions defs,
+        * Typically it's empty, but for function defs,
         * it contains function name (without '()'). */
-       int rcode;
-       const char *endch = NULL;
-       struct parse_context sub;
+       struct pipe *pipe_list;
+       int endch;
        struct command *command = ctx->command;
 
        debug_printf_parse("parse_group entered\n");
 #if ENABLE_HUSH_FUNCTIONS
-       if (ch == 'F') { /* function definition? */
-               bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
-               //command->fname = dest->data;
+       if (ch == '(' && !dest->o_quoted) {
+               if (dest->length)
+                       done_word(dest, ctx);
+               if (!command->argv)
+                       goto skip; /* (... */
+               if (command->argv[1]) { /* word word ... (... */
+                       syntax_error_unexpected_ch('(');
+                       return 1;
+               }
+               /* it is "word(..." or "word (..." */
+               do
+                       ch = i_getch(input);
+               while (ch == ' ' || ch == '\t');
+               if (ch != ')') {
+                       syntax_error_unexpected_ch(ch);
+                       return 1;
+               }
+               nommu_addchr(&ctx->as_string, ch);
+               do
+                       ch = i_getch(input);
+               while (ch == ' ' || ch == '\t' || ch == '\n');
+               if (ch != '{') {
+                       syntax_error_unexpected_ch(ch);
+                       return 1;
+               }
+               nommu_addchr(&ctx->as_string, ch);
                command->grp_type = GRP_FUNCTION;
-//TODO: review every o_reset() location... do they handle all o_string fields correctly?
-               memset(dest, 0, sizeof(*dest));
+               goto skip;
        }
 #endif
-       if (command->argv /* word [word](... */
-        || dest->length /* word(... */
-        || dest->nonnull /* ""(... */
+       if (command->argv /* word [word]{... */
+        || dest->length /* word{... */
+        || dest->o_quoted /* ""{... */
        ) {
-               syntax(NULL);
-               debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
+               syntax_error(NULL);
+               debug_printf_parse("parse_group return 1: "
+                       "syntax error, groups and arglists don't mix\n");
                return 1;
        }
-       initialize_context(&sub);
-       endch = "}";
+
+#if ENABLE_HUSH_FUNCTIONS
+ skip:
+#endif
+       endch = '}';
        if (ch == '(') {
-               endch = ")";
+               endch = ')';
                command->grp_type = GRP_SUBSHELL;
        }
-       rcode = parse_stream(dest, &sub, input, endch);
-       if (rcode == 0) {
-               done_word(dest, &sub); /* finish off the final word in the subcontext */
-               done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
-               command->group = sub.list_head;
+
+       {
+#if !BB_MMU
+               char *as_string = NULL;
+#endif
+               pipe_list = parse_stream(&as_string, input, endch);
+#if !BB_MMU
+               if (as_string)
+                       o_addstr(&ctx->as_string, as_string);
+#endif
+               /* empty ()/{} or parse error? */
+               if (!pipe_list || pipe_list == ERR_PTR) {
+#if !BB_MMU
+                       free(as_string);
+#endif
+                       syntax_error(NULL);
+                       debug_printf_parse("parse_group return 1: "
+                               "parse_stream returned %p\n", pipe_list);
+                       return 1;
+               }
+               command->group = pipe_list;
+#if !BB_MMU
+               as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
+               command->group_as_string = as_string;
+               debug_printf_parse("end of group, remembering as:'%s'\n",
+                               command->group_as_string);
+#endif
        }
-       debug_printf_parse("parse_group return %d\n", rcode);
-       return rcode;
+       debug_printf_parse("parse_group return 0\n");
+       return 0;
        /* command remains "open", available for possible redirects */
 }
 
@@ -3863,10 +4843,12 @@ static void add_till_single_quote(o_string *dest, struct in_str *input)
 {
        while (1) {
                int ch = i_getch(input);
-               if (ch == EOF)
-                       break;
+               if (ch == EOF) {
+                       syntax_error_unterm_ch('\'');
+                       /*xfunc_die(); - redundant */
+               }
                if (ch == '\'')
-                       break;
+                       return;
                o_addchr(dest, ch);
        }
 }
@@ -3875,14 +4857,16 @@ static void add_till_double_quote(o_string *dest, struct in_str *input)
 {
        while (1) {
                int ch = i_getch(input);
+               if (ch == EOF) {
+                       syntax_error_unterm_ch('"');
+                       /*xfunc_die(); - redundant */
+               }
                if (ch == '"')
-                       break;
+                       return;
                if (ch == '\\') {  /* \x. Copy both chars. */
                        o_addchr(dest, ch);
                        ch = i_getch(input);
                }
-               if (ch == EOF)
-                       break;
                o_addchr(dest, ch);
                if (ch == '`') {
                        add_till_backquote(dest, input);
@@ -3910,16 +4894,23 @@ static void add_till_backquote(o_string *dest, struct in_str *input)
 {
        while (1) {
                int ch = i_getch(input);
+               if (ch == EOF) {
+                       syntax_error_unterm_ch('`');
+                       /*xfunc_die(); - redundant */
+               }
                if (ch == '`')
-                       break;
-               if (ch == '\\') {  /* \x. Copy both chars unless it is \` */
+                       return;
+               if (ch == '\\') {
+                       /* \x. Copy both chars unless it is \` */
                        int ch2 = i_getch(input);
+                       if (ch2 == EOF) {
+                               syntax_error_unterm_ch('`');
+                               /*xfunc_die(); - redundant */
+                       }
                        if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
                                o_addchr(dest, ch);
                        ch = ch2;
                }
-               if (ch == EOF)
-                       break;
                o_addchr(dest, ch);
        }
 }
@@ -3940,11 +4931,13 @@ static void add_till_closing_paren(o_string *dest, struct in_str *input, bool db
        int count = 0;
        while (1) {
                int ch = i_getch(input);
-               if (ch == EOF)
-                       break;
+               if (ch == EOF) {
+                       syntax_error_unterm_ch(')');
+                       /*xfunc_die(); - redundant */
+               }
                if (ch == '(')
                        count++;
-               if (ch == ')')
+               if (ch == ')') {
                        if (--count < 0) {
                                if (!dbl)
                                        break;
@@ -3953,6 +4946,7 @@ static void add_till_closing_paren(o_string *dest, struct in_str *input, bool db
                                        break;
                                }
                        }
+               }
                o_addchr(dest, ch);
                if (ch == '\'') {
                        add_till_single_quote(dest, input);
@@ -3964,10 +4958,13 @@ static void add_till_closing_paren(o_string *dest, struct in_str *input, bool db
                        o_addchr(dest, ch);
                        continue;
                }
-               if (ch == '\\') { /* \x. Copy verbatim. Important for  \(, \) */
+               if (ch == '\\') {
+                       /* \x. Copy verbatim. Important for  \(, \) */
                        ch = i_getch(input);
-                       if (ch == EOF)
-                               break;
+                       if (ch == EOF) {
+                               syntax_error_unterm_ch(')');
+                               /*xfunc_die(); - redundant */
+                       }
                        o_addchr(dest, ch);
                        continue;
                }
@@ -3976,15 +4973,22 @@ static void add_till_closing_paren(o_string *dest, struct in_str *input, bool db
 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
 
 /* Return code: 0 for OK, 1 for syntax error */
-static int handle_dollar(o_string *dest, struct in_str *input)
+#if BB_MMU
+#define handle_dollar(as_string, dest, input) \
+       handle_dollar(dest, input)
+#endif
+static int handle_dollar(o_string *as_string,
+               o_string *dest,
+               struct in_str *input)
 {
        int expansion;
        int ch = i_peek(input);  /* first character after the $ */
-       unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
+       unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
 
        debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
        if (isalpha(ch)) {
-               i_getch(input);
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
  make_var:
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
                while (1) {
@@ -3994,187 +4998,209 @@ static int handle_dollar(o_string *dest, struct in_str *input)
                        ch = i_peek(input);
                        if (!isalnum(ch) && ch != '_')
                                break;
-                       i_getch(input);
+                       ch = i_getch(input);
+                       nommu_addchr(as_string, ch);
                }
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
        } else if (isdigit(ch)) {
  make_one_char_var:
-               i_getch(input);
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
                debug_printf_parse(": '%c'\n", ch);
                o_addchr(dest, ch | quote_mask);
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
        } else switch (ch) {
-               case '$': /* pid */
-               case '!': /* last bg pid */
-               case '?': /* last exit code */
-               case '#': /* number of args */
-               case '*': /* args */
-               case '@': /* args */
-                       goto make_one_char_var;
-               case '{': {
-                       bool first_char, all_digits;
+       case '$': /* pid */
+       case '!': /* last bg pid */
+       case '?': /* last exit code */
+       case '#': /* number of args */
+       case '*': /* args */
+       case '@': /* args */
+               goto make_one_char_var;
+       case '{': {
+               bool first_char, all_digits;
 
-                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       i_getch(input);
-                       /* XXX maybe someone will try to escape the '}' */
-                       expansion = 0;
-                       first_char = true;
-                       all_digits = false;
-                       while (1) {
-                               ch = i_getch(input);
-                               if (ch == '}')
-                                       break;
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
+               /* XXX maybe someone will try to escape the '}' */
+               expansion = 0;
+               first_char = true;
+               all_digits = false;
+               while (1) {
+                       ch = i_getch(input);
+                       nommu_addchr(as_string, ch);
+                       if (ch == '}')
+                               break;
 
-                               if (first_char) {
-                                       if (ch == '#')
-                                               /* ${#var}: length of var contents */
-                                               goto char_ok;
-                                       else if (isdigit(ch)) {
-                                               all_digits = true;
-                                               goto char_ok;
-                                       }
+                       if (first_char) {
+                               if (ch == '#')
+                                       /* ${#var}: length of var contents */
+                                       goto char_ok;
+                               else if (isdigit(ch)) {
+                                       all_digits = true;
+                                       goto char_ok;
                                }
+                       }
 
-                               if (expansion < 2 &&
-                                   ((all_digits && !isdigit(ch)) ||
-                                    (!all_digits && !isalnum(ch) && ch != '_')))
-                               {
-                                       /* handle parameter expansions
-                                        * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
-                                        */
-                                       if (first_char)
-                                               goto case_default;
-                                       switch (ch) {
-                                               case ':': /* null modifier */
-                                                       if (expansion == 0) {
-                                                               debug_printf_parse(": null modifier\n");
-                                                               ++expansion;
-                                                               break;
-                                                       }
-                                                       goto case_default;
-
-#if 0 /* not implemented yet :( */
-                                               case '#': /* remove prefix */
-                                               case '%': /* remove suffix */
-                                                       if (expansion == 0) {
-                                                               debug_printf_parse(": remove suffix/prefix\n");
-                                                               expansion = 2;
-                                                               break;
-                                                       }
-                                                       goto case_default;
-#endif
-
-                                               case '-': /* default value */
-                                               case '=': /* assign default */
-                                               case '+': /* alternative */
-                                               case '?': /* error indicate */
-                                                       debug_printf_parse(": parameter expansion\n");
-                                                       expansion = 2;
-                                                       break;
-
-                                               default:
-                                               case_default:
-                                                       syntax("unterminated ${name}");
-                                                       debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
-                                                       return 1;
-                                               }
+                       if (expansion < 2
+                        && (  (all_digits && !isdigit(ch))
+                           || (!all_digits && !isalnum(ch) && ch != '_')
+                           )
+                       ) {
+                               /* handle parameter expansions
+                                * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
+                                */
+                               if (first_char)
+                                       goto case_default;
+                               switch (ch) {
+                               case ':': /* null modifier */
+                                       if (expansion == 0) {
+                                               debug_printf_parse(": null modifier\n");
+                                               ++expansion;
+                                               break;
+                                       }
+                                       goto case_default;
+                               case '#': /* remove prefix */
+                               case '%': /* remove suffix */
+                                       if (expansion == 0) {
+                                               debug_printf_parse(": remove suffix/prefix\n");
+                                               expansion = 2;
+                                               break;
+                                       }
+                                       goto case_default;
+                               case '-': /* default value */
+                               case '=': /* assign default */
+                               case '+': /* alternative */
+                               case '?': /* error indicate */
+                                       debug_printf_parse(": parameter expansion\n");
+                                       expansion = 2;
+                                       break;
+                               default:
+                               case_default:
+                                       syntax_error_unterm_str("${name}");
+                                       debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
+                                       return 1;
                                }
-
+                       }
  char_ok:
-                               debug_printf_parse(": '%c'\n", ch);
-                               o_addchr(dest, ch | quote_mask);
-                               quote_mask = 0;
-                               first_char = false;
+                       debug_printf_parse(": '%c'\n", ch);
+                       o_addchr(dest, ch | quote_mask);
+                       quote_mask = 0;
+                       first_char = false;
+               }
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
+               break;
+       }
+#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
+       case '(': {
+# if !BB_MMU
+               int pos;
+# endif
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
+# if ENABLE_SH_MATH_SUPPORT
+               if (i_peek(input) == '(') {
+                       ch = i_getch(input);
+                       nommu_addchr(as_string, ch);
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       o_addchr(dest, /*quote_mask |*/ '+');
+#  if !BB_MMU
+                       pos = dest->length;
+#  endif
+                       add_till_closing_paren(dest, input, true);
+#  if !BB_MMU
+                       if (as_string) {
+                               o_addstr(as_string, dest->data + pos);
+                               o_addchr(as_string, ')');
+                               o_addchr(as_string, ')');
                        }
+#  endif
                        o_addchr(dest, SPECIAL_VAR_SYMBOL);
                        break;
                }
-               case '(': {
-                       i_getch(input);
-
-#if ENABLE_SH_MATH_SUPPORT
-                       if (i_peek(input) == '(') {
-                               i_getch(input);
-                               o_addchr(dest, SPECIAL_VAR_SYMBOL);
-                               o_addchr(dest, /*quote_mask |*/ '+');
-                               add_till_closing_paren(dest, input, true);
-                               o_addchr(dest, SPECIAL_VAR_SYMBOL);
-                               break;
-                       }
-#endif
-
-#if ENABLE_HUSH_TICK
-                       //int pos = dest->length;
-                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       o_addchr(dest, quote_mask | '`');
-                       add_till_closing_paren(dest, input, false);
-                       //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
-                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
+# endif
+# if ENABLE_HUSH_TICK
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
+               o_addchr(dest, quote_mask | '`');
+#  if !BB_MMU
+               pos = dest->length;
+#  endif
+               add_till_closing_paren(dest, input, false);
+#  if !BB_MMU
+               if (as_string) {
+                       o_addstr(as_string, dest->data + pos);
+                       o_addchr(as_string, '`');
+               }
+#  endif
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
+# endif
+               break;
+       }
 #endif
-                       break;
+       case '_':
+               ch = i_getch(input);
+               nommu_addchr(as_string, ch);
+               ch = i_peek(input);
+               if (isalnum(ch)) { /* it's $_name or $_123 */
+                       ch = '_';
+                       goto make_var;
                }
-               case '_':
-                       i_getch(input);
-                       ch = i_peek(input);
-                       if (isalnum(ch)) { /* it's $_name or $_123 */
-                               ch = '_';
-                               goto make_var;
-                       }
-                       /* else: it's $_ */
-               case '-':
-                       /* still unhandled, but should be eventually */
-                       bb_error_msg("unhandled syntax: $%c", ch);
-                       return 1;
-                       break;
-               default:
-                       o_addQchr(dest, '$');
+               /* else: it's $_ */
+       /* TODO: */
+       /* $_ Shell or shell script name; or last cmd name */
+       /* $- Option flags set by set builtin or shell options (-i etc) */
+       default:
+               o_addQchr(dest, '$');
        }
        debug_printf_parse("handle_dollar return 0\n");
        return 0;
 }
 
-static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end)
+#if BB_MMU
+#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
+       parse_stream_dquoted(dest, input, dquote_end)
+#endif
+static int parse_stream_dquoted(o_string *as_string,
+               o_string *dest,
+               struct in_str *input,
+               int dquote_end)
 {
-       int ch, m;
+       int ch;
        int next;
 
  again:
        ch = i_getch(input);
+       if (ch != EOF)
+               nommu_addchr(as_string, ch);
        if (ch == dquote_end) { /* may be only '"' or EOF */
-               dest->nonnull = 1;
                if (dest->o_assignment == NOT_ASSIGNMENT)
-                       dest->o_quote ^= 1;
+                       dest->o_escape ^= 1;
                debug_printf_parse("parse_stream_dquoted return 0\n");
                return 0;
        }
+       /* note: can't move it above ch == dquote_end check! */
        if (ch == EOF) {
-               syntax("unterminated \"");
-               debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
-               return 1;
+               syntax_error_unterm_ch('"');
+               /*xfunc_die(); - redundant */
        }
        next = '\0';
-       m = G.charmap[ch];
        if (ch != '\n') {
                next = i_peek(input);
        }
-       debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
-                                       ch, ch, m, dest->o_quote);
-       /* Basically, checking every CHAR_SPECIAL char except '"' */
+       debug_printf_parse(": ch=%c (%d) escape=%d\n",
+                                       ch, ch, dest->o_escape);
        if (ch == '\\') {
                if (next == EOF) {
-                       syntax("\\<eof>");
-                       debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
-                       return 1;
+                       syntax_error("\\<eof>");
+                       xfunc_die();
                }
                /* bash:
                 * "The backslash retains its special meaning [in "..."]
                 * only when followed by one of the following characters:
                 * $, `, ", \, or <newline>.  A double quote may be quoted
                 * within double quotes by preceding it with a backslash.
-                * If enabled, history expansion will be performed unless
-                * an ! appearing in double quotes is escaped using
-                * a backslash. The backslash preceding the ! is not removed."
                 */
                if (strchr("$`\"\\", next) != NULL) {
                        o_addqchr(dest, i_getch(input));
@@ -4184,8 +5210,9 @@ static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote
                goto again;
        }
        if (ch == '$') {
-               if (handle_dollar(dest, input) != 0) {
-                       debug_printf_parse("parse_stream_dquoted return 1: handle_dollar returned non-0\n");
+               if (handle_dollar(as_string, dest, input) != 0) {
+                       debug_printf_parse("parse_stream_dquoted return 1: "
+                                       "handle_dollar returned non-0\n");
                        return 1;
                }
                goto again;
@@ -4205,223 +5232,345 @@ static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote
        if (ch == '='
         && (dest->o_assignment == MAYBE_ASSIGNMENT
            || dest->o_assignment == WORD_IS_KEYWORD)
-        && is_assignment(dest->data)
+        && is_well_formed_var_name(dest->data, '=')
        ) {
                dest->o_assignment = DEFINITELY_ASSIGNMENT;
        }
        goto again;
 }
 
-/* Scan input, call done_word() whenever full IFS delimited word was seen.
- * Call done_pipe if '\n' was seen (and end_trigger != NULL).
- * Return code is 0 if end_trigger char is met,
- * -1 on EOF (but if end_trigger == NULL then return 0),
- * 1 for syntax error */
-static int parse_stream(o_string *dest, struct parse_context *ctx,
-               struct in_str *input, const char *end_trigger)
+/*
+ * Scan input until EOF or end_trigger char.
+ * Return a list of pipes to execute, or NULL on EOF
+ * or if end_trigger character is met.
+ * On syntax error, exit is shell is not interactive,
+ * reset parsing machinery and start parsing anew,
+ * or return ERR_PTR.
+ */
+static struct pipe *parse_stream(char **pstring,
+               struct in_str *input,
+               int end_trigger)
 {
-       int ch, m;
-       int redir_fd;
-       redir_type redir_style;
+       struct parse_context ctx;
+       o_string dest = NULL_O_STRING;
        int is_in_dquote;
-       int next;
+       int heredoc_cnt;
 
-       /* Only double-quote state is handled in the state variable dest->o_quote.
+       /* Double-quote state is handled in the state variable is_in_dquote.
         * A single-quote triggers a bypass of the main loop until its mate is
-        * found.  When recursing, quote state is passed in via dest->o_quote. */
+        * 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');
+       debug_enter();
 
-       debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
+       G.ifs = get_local_var_value("IFS");
+       if (G.ifs == NULL)
+               G.ifs = " \t\n";
 
-       is_in_dquote = dest->o_quote;
+ reset:
+#if ENABLE_HUSH_INTERACTIVE
+       input->promptmode = 0; /* PS1 */
+#endif
+       /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
+       initialize_context(&ctx);
+       is_in_dquote = 0;
+       heredoc_cnt = 0;
        while (1) {
+               const char *is_ifs;
+               const char *is_special;
+               int ch;
+               int next;
+               int redir_fd;
+               redir_type redir_style;
+
                if (is_in_dquote) {
-                       if (parse_stream_dquoted(dest, input, '"'))
-                               return 1; /* propagate parse error */
-                       /* If we're here, we reached closing '"' */
+                       /* dest.o_quoted = 1; - already is (see below) */
+                       if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
+                               goto parse_error;
+                       }
+                       /* We reached closing '"' */
                        is_in_dquote = 0;
                }
-               m = CHAR_IFS;
-               next = '\0';
                ch = i_getch(input);
-               if (ch != EOF) {
-                       m = G.charmap[ch];
-                       if (ch != '\n') {
-                               next = i_peek(input);
+               debug_printf_parse(": ch=%c (%d) escape=%d\n",
+                                               ch, ch, dest.o_escape);
+               if (ch == EOF) {
+                       struct pipe *pi;
+
+                       if (heredoc_cnt) {
+                               syntax_error_unterm_str("here document");
+                               xfunc_die();
+                       }
+                       if (done_word(&dest, &ctx)) {
+                               xfunc_die();
+                       }
+                       o_free(&dest);
+                       done_pipe(&ctx, PIPE_SEQ);
+                       pi = ctx.list_head;
+                       /* If we got nothing... */
+                       /* (this makes bare "&" cmd a no-op.
+                        * bash says: "syntax error near unexpected token '&'") */
+                       if (pi->num_cmds == 0
+                           IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
+                       ) {
+                               free_pipe_list(pi);
+                               pi = NULL;
                        }
+#if !BB_MMU
+                       debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
+                       if (pstring)
+                               *pstring = ctx.as_string.data;
+                       else
+                               o_free_unsafe(&ctx.as_string);
+#endif
+                       debug_leave();
+                       debug_printf_parse("parse_stream return %p\n", pi);
+                       return pi;
                }
-               debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
-                                               ch, ch, m, dest->o_quote);
-               if (m == CHAR_ORDINARY) {
-                       o_addQchr(dest, ch);
-                       if ((dest->o_assignment == MAYBE_ASSIGNMENT
-                           || dest->o_assignment == WORD_IS_KEYWORD)
+               nommu_addchr(&ctx.as_string, ch);
+               is_ifs = strchr(G.ifs, ch);
+               is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
+                               "\\$\"" USE_HUSH_TICK("`") /* always special */
+                               , ch);
+
+               if (!is_special && !is_ifs) { /* ordinary char */
+                       o_addQchr(&dest, ch);
+                       if ((dest.o_assignment == MAYBE_ASSIGNMENT
+                           || dest.o_assignment == WORD_IS_KEYWORD)
                         && ch == '='
-                        && is_assignment(dest->data)
+                        && is_well_formed_var_name(dest.data, '=')
                        ) {
-                               dest->o_assignment = DEFINITELY_ASSIGNMENT;
+                               dest.o_assignment = DEFINITELY_ASSIGNMENT;
                        }
                        continue;
                }
-               /* m is SPECIAL ($,`), IFS, or ORDINARY_IF_QUOTED (*,#)
-                */
-               if (m == CHAR_IFS) {
-                       if (done_word(dest, ctx)) {
-                               debug_printf_parse("parse_stream return 1: done_word!=0\n");
-                               return 1;
+
+               if (is_ifs) {
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
                        }
-                       if (ch == EOF)
-                               break;
-                       /* If we aren't performing a substitution, treat
-                        * a newline as a command separator.
-                        * [why don't we handle it exactly like ';'? --vda] */
-                       if (end_trigger && ch == '\n') {
+                       if (ch == '\n') {
 #if ENABLE_HUSH_CASE
                                /* "case ... in <newline> word) ..." -
                                 * newlines are ignored (but ';' wouldn't be) */
-                               if (dest->length == 0 // && argv[0] == NULL
-                                && ctx->ctx_res_w == RES_MATCH
+                               if (ctx.command->argv == NULL
+                                && ctx.ctx_res_w == RES_MATCH
                                ) {
                                        continue;
                                }
 #endif
-                               done_pipe(ctx, PIPE_SEQ);
-                               dest->o_assignment = MAYBE_ASSIGNMENT;
+                               /* Treat newline as a command separator. */
+                               done_pipe(&ctx, PIPE_SEQ);
+                               debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
+                               if (heredoc_cnt) {
+                                       if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
+                                               goto parse_error;
+                                       }
+                                       heredoc_cnt = 0;
+                               }
+                               dest.o_assignment = MAYBE_ASSIGNMENT;
+                               ch = ';';
+                               /* note: if (is_ifs) continue;
+                                * will still trigger for us */
                        }
                }
-               if (end_trigger) {
-                       if (strchr(end_trigger, ch)) {
-                               /* Special case: (...word) makes last word terminate,
-                                * as if ';' is seen */
-                               if (ch == ')') {
-                                       done_word(dest, ctx);
-//err chk?
-                                       done_pipe(ctx, PIPE_SEQ);
-                                       dest->o_assignment = MAYBE_ASSIGNMENT;
-                               }
-                               if (!HAS_KEYWORDS
-                                IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
-                               ) {
-                                       debug_printf_parse("parse_stream return 0: end_trigger char found\n");
-                                       return 0;
-                               }
+               if (end_trigger && end_trigger == ch
+                && (heredoc_cnt == 0 || end_trigger != ';')
+               ) {
+//TODO: disallow "{ cmd }" without semicolon
+                       if (heredoc_cnt) {
+                               /* This is technically valid:
+                                * { cat <<HERE; }; echo Ok
+                                * heredoc
+                                * heredoc
+                                * heredoc
+                                * HERE
+                                * but we don't support this.
+                                * We require heredoc to be in enclosing {}/(),
+                                * if any.
+                                */
+                               syntax_error_unterm_str("here document");
+                               goto parse_error;
+                       }
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
+                       }
+                       done_pipe(&ctx, PIPE_SEQ);
+                       dest.o_assignment = MAYBE_ASSIGNMENT;
+                       /* Do we sit outside of any if's, loops or case's? */
+                       if (!HAS_KEYWORDS
+                        IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
+                       ) {
+                               o_free(&dest);
+#if !BB_MMU
+                               debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
+                               if (pstring)
+                                       *pstring = ctx.as_string.data;
+                               else
+                                       o_free_unsafe(&ctx.as_string);
+#endif
+                               debug_leave();
+                               debug_printf_parse("parse_stream return %p: "
+                                               "end_trigger char found\n",
+                                               ctx.list_head);
+                               return ctx.list_head;
                        }
                }
-               if (m == CHAR_IFS)
+               if (is_ifs)
                        continue;
 
-               /* m is SPECIAL (e.g. $,`) or ORDINARY_IF_QUOTED (*,#) */
+               next = '\0';
+               if (ch != '\n') {
+                       next = i_peek(input);
+               }
+
+               /* Catch <, > before deciding whether this word is
+                * an assignment. a=1 2>z b=2: b=2 is still assignment */
+               switch (ch) {
+               case '>':
+                       redir_fd = redirect_opt_num(&dest);
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
+                       }
+                       redir_style = REDIRECT_OVERWRITE;
+                       if (next == '>') {
+                               redir_style = REDIRECT_APPEND;
+                               ch = i_getch(input);
+                               nommu_addchr(&ctx.as_string, ch);
+                       }
+#if 0
+                       else if (next == '(') {
+                               syntax_error(">(process) not supported");
+                               goto parse_error;
+                       }
+#endif
+                       if (parse_redirect(&ctx, redir_fd, redir_style, input))
+                               goto parse_error;
+                       continue; /* back to top of while (1) */
+               case '<':
+                       redir_fd = redirect_opt_num(&dest);
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
+                       }
+                       redir_style = REDIRECT_INPUT;
+                       if (next == '<') {
+                               redir_style = REDIRECT_HEREDOC;
+                               heredoc_cnt++;
+                               debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
+                               ch = i_getch(input);
+                               nommu_addchr(&ctx.as_string, ch);
+                       } else if (next == '>') {
+                               redir_style = REDIRECT_IO;
+                               ch = i_getch(input);
+                               nommu_addchr(&ctx.as_string, ch);
+                       }
+#if 0
+                       else if (next == '(') {
+                               syntax_error("<(process) not supported");
+                               goto parse_error;
+                       }
+#endif
+                       if (parse_redirect(&ctx, redir_fd, redir_style, input))
+                               goto parse_error;
+                       continue; /* back to top of while (1) */
+               }
 
-               if (dest->o_assignment == MAYBE_ASSIGNMENT) {
+               if (dest.o_assignment == MAYBE_ASSIGNMENT
+                /* check that we are not in word in "a=1 2>word b=1": */
+                && !ctx.pending_redirect
+               ) {
                        /* ch is a special char and thus this word
                         * cannot be an assignment */
-                       dest->o_assignment = NOT_ASSIGNMENT;
+                       dest.o_assignment = NOT_ASSIGNMENT;
                }
 
                switch (ch) {
                case '#':
-                       if (dest->length == 0) {
+                       if (dest.length == 0) {
                                while (1) {
                                        ch = i_peek(input);
                                        if (ch == EOF || ch == '\n')
                                                break;
                                        i_getch(input);
+                                       /* note: we do not add it to &ctx.as_string */
                                }
+                               nommu_addchr(&ctx.as_string, '\n');
                        } else {
-                               o_addQchr(dest, ch);
+                               o_addQchr(&dest, ch);
                        }
                        break;
                case '\\':
                        if (next == EOF) {
-                               syntax("\\<eof>");
-                               debug_printf_parse("parse_stream return 1: \\<eof>\n");
-                               return 1;
+                               syntax_error("\\<eof>");
+                               xfunc_die();
                        }
-                       o_addchr(dest, '\\');
-                       o_addchr(dest, i_getch(input));
+                       o_addchr(&dest, '\\');
+                       ch = i_getch(input);
+                       nommu_addchr(&ctx.as_string, ch);
+                       o_addchr(&dest, ch);
+                       /* Example: echo Hello \2>file
+                        * we need to know that word 2 is quoted */
+                       dest.o_quoted = 1;
                        break;
                case '$':
-                       if (handle_dollar(dest, input) != 0) {
-                               debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
-                               return 1;
+                       if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
+                               debug_printf_parse("parse_stream parse error: "
+                                       "handle_dollar returned non-0\n");
+                               goto parse_error;
                        }
                        break;
                case '\'':
-                       dest->nonnull = 1;
+                       dest.o_quoted = 1;
                        while (1) {
                                ch = i_getch(input);
                                if (ch == EOF) {
-                                       syntax("unterminated '");
-                                       debug_printf_parse("parse_stream return 1: unterminated '\n");
-                                       return 1;
+                                       syntax_error_unterm_ch('\'');
+                                       /*xfunc_die(); - redundant */
                                }
+                               nommu_addchr(&ctx.as_string, ch);
                                if (ch == '\'')
                                        break;
-                               if (dest->o_assignment == NOT_ASSIGNMENT)
-                                       o_addqchr(dest, ch);
+                               if (dest.o_assignment == NOT_ASSIGNMENT)
+                                       o_addqchr(&dest, ch);
                                else
-                                       o_addchr(dest, ch);
+                                       o_addchr(&dest, ch);
                        }
                        break;
                case '"':
-                       dest->nonnull = 1;
+                       dest.o_quoted = 1;
                        is_in_dquote ^= 1; /* invert */
-                       if (dest->o_assignment == NOT_ASSIGNMENT)
-                               dest->o_quote ^= 1;
+                       if (dest.o_assignment == NOT_ASSIGNMENT)
+                               dest.o_escape ^= 1;
                        break;
 #if ENABLE_HUSH_TICK
-               case '`': {
-                       //int pos = dest->length;
-                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       o_addchr(dest, '`');
-                       add_till_backquote(dest, input);
-                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
-                       break;
-               }
-#endif
-               case '>':
-                       redir_fd = redirect_opt_num(dest);
-                       done_word(dest, ctx);
-                       redir_style = REDIRECT_OVERWRITE;
-                       if (next == '>') {
-                               redir_style = REDIRECT_APPEND;
-                               i_getch(input);
-                       }
-#if 0
-                       else if (next == '(') {
-                               syntax(">(process) not supported");
-                               debug_printf_parse("parse_stream return 1: >(process) not supported\n");
-                               return 1;
-                       }
-#endif
-                       setup_redirect(ctx, redir_fd, redir_style, input);
-                       break;
-               case '<':
-                       redir_fd = redirect_opt_num(dest);
-                       done_word(dest, ctx);
-                       redir_style = REDIRECT_INPUT;
-                       if (next == '<') {
-                               redir_style = REDIRECT_HEREIS;
-                               i_getch(input);
-                       } else if (next == '>') {
-                               redir_style = REDIRECT_IO;
-                               i_getch(input);
-                       }
-#if 0
-                       else if (next == '(') {
-                               syntax("<(process) not supported");
-                               debug_printf_parse("parse_stream return 1: <(process) not supported\n");
-                               return 1;
-                       }
+               case '`': {
+#if !BB_MMU
+                       int pos;
+#endif
+                       o_addchr(&dest, SPECIAL_VAR_SYMBOL);
+                       o_addchr(&dest, '`');
+#if !BB_MMU
+                       pos = dest.length;
 #endif
-                       setup_redirect(ctx, redir_fd, redir_style, input);
+                       add_till_backquote(&dest, input);
+#if !BB_MMU
+                       o_addstr(&ctx.as_string, dest.data + pos);
+                       o_addchr(&ctx.as_string, '`');
+#endif
+                       o_addchr(&dest, SPECIAL_VAR_SYMBOL);
+                       //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
                        break;
+               }
+#endif
                case ';':
 #if ENABLE_HUSH_CASE
  case_semi:
 #endif
-                       done_word(dest, ctx);
-                       done_pipe(ctx, PIPE_SEQ);
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
+                       }
+                       done_pipe(&ctx, PIPE_SEQ);
 #if ENABLE_HUSH_CASE
                        /* Eat multiple semicolons, detect
                         * whether it means something special */
@@ -4429,10 +5578,11 @@ static int parse_stream(o_string *dest, struct parse_context *ctx,
                                ch = i_peek(input);
                                if (ch != ';')
                                        break;
-                               i_getch(input);
-                               if (ctx->ctx_res_w == RES_CASEI) {
-                                       ctx->ctx_dsemicolon = 1;
-                                       ctx->ctx_res_w = RES_MATCH;
+                               ch = i_getch(input);
+                               nommu_addchr(&ctx.as_string, ch);
+                               if (ctx.ctx_res_w == RES_CASEI) {
+                                       ctx.ctx_dsemicolon = 1;
+                                       ctx.ctx_res_w = RES_MATCH;
                                        break;
                                }
                        }
@@ -4440,216 +5590,236 @@ static int parse_stream(o_string *dest, struct parse_context *ctx,
  new_cmd:
                        /* We just finished a cmd. New one may start
                         * with an assignment */
-                       dest->o_assignment = MAYBE_ASSIGNMENT;
+                       dest.o_assignment = MAYBE_ASSIGNMENT;
                        break;
                case '&':
-                       done_word(dest, ctx);
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
+                       }
                        if (next == '&') {
-                               i_getch(input);
-                               done_pipe(ctx, PIPE_AND);
+                               ch = i_getch(input);
+                               nommu_addchr(&ctx.as_string, ch);
+                               done_pipe(&ctx, PIPE_AND);
                        } else {
-                               done_pipe(ctx, PIPE_BG);
+                               done_pipe(&ctx, PIPE_BG);
                        }
                        goto new_cmd;
                case '|':
-                       done_word(dest, ctx);
+                       if (done_word(&dest, &ctx)) {
+                               goto parse_error;
+                       }
 #if ENABLE_HUSH_CASE
-                       if (ctx->ctx_res_w == RES_MATCH)
+                       if (ctx.ctx_res_w == RES_MATCH)
                                break; /* we are in case's "word | word)" */
 #endif
                        if (next == '|') { /* || */
-                               i_getch(input);
-                               done_pipe(ctx, PIPE_OR);
+                               ch = i_getch(input);
+                               nommu_addchr(&ctx.as_string, ch);
+                               done_pipe(&ctx, PIPE_OR);
                        } else {
                                /* we could pick up a file descriptor choice here
                                 * with redirect_opt_num(), but bash doesn't do it.
                                 * "echo foo 2| cat" yields "foo 2". */
-                               done_command(ctx);
+                               done_command(&ctx);
                        }
                        goto new_cmd;
                case '(':
 #if ENABLE_HUSH_CASE
                        /* "case... in [(]word)..." - skip '(' */
-                       if (ctx->ctx_res_w == RES_MATCH
-                        && ctx->command->argv == NULL /* not (word|(... */
-                        && dest->length == 0 /* not word(... */
-                        && dest->nonnull == 0 /* not ""(... */
+                       if (ctx.ctx_res_w == RES_MATCH
+                        && ctx.command->argv == NULL /* not (word|(... */
+                        && dest.length == 0 /* not word(... */
+                        && dest.o_quoted == 0 /* not ""(... */
                        ) {
                                continue;
                        }
-#endif
-#if ENABLE_HUSH_FUNCTIONS
-                       if (dest->length != 0 /* not just () but word() */
-                        && dest->nonnull == 0 /* not a"b"c() */
-                        && ctx->command->argv == NULL /* it's the first word */
-//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
-                        && i_peek(input) == ')'
-                        && !match_reserved_word(dest)
-                       ) {
-                               bb_error_msg("seems like a function definition");
-                               i_getch(input);
-                               do {
-//TODO: do it properly.
-                                       ch = i_getch(input);
-                               } while (ch == ' ' || ch == '\n');
-                               if (ch != '{') {
-                                       syntax("was expecting {");
-                                       debug_printf_parse("parse_stream return 1\n");
-                                       return 1;
-                               }
-                               ch = 'F'; /* magic value */
-                       }
 #endif
                case '{':
-                       if (parse_group(dest, ctx, input, ch) != 0) {
-                               debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
-                               return 1;
+                       if (parse_group(&dest, &ctx, input, ch) != 0) {
+                               goto parse_error;
                        }
                        goto new_cmd;
                case ')':
 #if ENABLE_HUSH_CASE
-                       if (ctx->ctx_res_w == RES_MATCH)
+                       if (ctx.ctx_res_w == RES_MATCH)
                                goto case_semi;
 #endif
                case '}':
                        /* proper use of this character is caught by end_trigger:
                         * if we see {, we call parse_group(..., end_trigger='}')
                         * and it will match } earlier (not here). */
-                       syntax("unexpected } or )");
-                       debug_printf_parse("parse_stream return 1: unexpected '}'\n");
-                       return 1;
+                       syntax_error_unexpected_ch(ch);
+                       goto parse_error;
                default:
                        if (HUSH_DEBUG)
                                bb_error_msg_and_die("BUG: unexpected %c\n", ch);
                }
        } /* while (1) */
-       debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
-       if (end_trigger)
-               return -1;
-       return 0;
-}
-
-static void set_in_charmap(const char *set, int code)
-{
-       while (*set)
-               G.charmap[(unsigned char)*set++] = code;
-}
 
-static void update_charmap(void)
-{
-       G.ifs = getenv("IFS");
-       if (G.ifs == NULL)
-               G.ifs = " \t\n";
-       /* Precompute a list of 'flow through' behavior so it can be treated
-        * quickly up front.  Computation is necessary because of IFS.
-        * Special case handling of IFS == " \t\n" is not implemented.
-        * The charmap[] array only really needs two bits each,
-        * and on most machines that would be faster (reduced L1 cache use).
-        */
-       memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
-#if ENABLE_HUSH_TICK
-       set_in_charmap("\\$\"`", CHAR_SPECIAL);
-#else
-       set_in_charmap("\\$\"", CHAR_SPECIAL);
+ parse_error:
+       {
+               struct parse_context *pctx;
+               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)
+                * 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
+                * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
+                */
+               pctx = &ctx;
+               do {
+                       /* Update pipe/command counts,
+                        * otherwise freeing may miss some */
+                       done_pipe(pctx, PIPE_SEQ);
+                       debug_printf_clean("freeing list %p from ctx %p\n",
+                                       pctx->list_head, pctx);
+                       debug_print_tree(pctx->list_head, 0);
+                       free_pipe_list(pctx->list_head);
+                       debug_printf_clean("freed list %p\n", pctx->list_head);
+#if !BB_MMU
+                       o_free_unsafe(&pctx->as_string);
+#endif
+                       IF_HAS_KEYWORDS(p2 = pctx->stack;)
+                       if (pctx != &ctx) {
+                               free(pctx);
+                       }
+                       IF_HAS_KEYWORDS(pctx = p2;)
+               } while (HAS_KEYWORDS && pctx);
+               /* Free text, clear all dest fields */
+               o_free(&dest);
+               /* If we are not in top-level parse, we return,
+                * our caller will propagate error.
+                */
+               if (end_trigger != ';') {
+#if !BB_MMU
+                       if (pstring)
+                               *pstring = NULL;
 #endif
-       set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
-       set_in_charmap(G.ifs, CHAR_IFS);  /* are ordinary if quoted */
+                       debug_leave();
+                       return ERR_PTR;
+               }
+               /* Discard cached input, force prompt */
+               input->p = NULL;
+               USE_HUSH_INTERACTIVE(input->promptme = 1;)
+               goto reset;
+       }
 }
 
-/* Most recursion does not come through here, the exception is
- * from builtin_source() and builtin_eval() */
-static int parse_and_run_stream(struct in_str *inp, int parse_flag)
+/* Executing from string: eval, sh -c '...'
+ *          or from file: /etc/profile, . file, sh <script>, sh (intereactive)
+ * end_trigger controls how often we stop parsing
+ * NUL: parse all, execute, return
+ * ';': parse till ';' or newline, execute, repeat till EOF
+ */
+static void parse_and_run_stream(struct in_str *inp, int end_trigger)
 {
-       struct parse_context ctx;
-       o_string temp = NULL_O_STRING;
-       int rcode;
+       while (1) {
+               struct pipe *pipe_list;
 
-       do {
-               initialize_context(&ctx);
-               update_charmap();
-#if ENABLE_HUSH_INTERACTIVE
-               inp->promptmode = 0; /* PS1 */
-#endif
-               /* We will stop & execute after each ';' or '\n'.
-                * Example: "sleep 9999; echo TEST" + ctrl-C:
-                * TEST should be printed */
-               temp.o_assignment = MAYBE_ASSIGNMENT;
-               rcode = parse_stream(&temp, &ctx, inp, ";\n");
-#if HAS_KEYWORDS
-               if (rcode != 1 && ctx.old_flag != 0) {
-                       syntax(NULL);
-               }
-#endif
-               if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
-                       done_word(&temp, &ctx);
-                       done_pipe(&ctx, PIPE_SEQ);
-                       debug_print_tree(ctx.list_head, 0);
-                       debug_printf_exec("parse_stream_outer: run_and_free_list\n");
-                       run_and_free_list(ctx.list_head);
-               } else {
-                       /* We arrive here also if rcode == 1 (error in parse_stream) */
-#if HAS_KEYWORDS
-                       if (ctx.old_flag != 0) {
-                               free(ctx.stack);
-                               o_reset(&temp);
-                       }
-#endif
-                       /*temp.nonnull = 0; - o_free does it below */
-                       /*temp.o_quote = 0; - o_free does it below */
-                       free_pipe_list(ctx.list_head, /* indent: */ 0);
-                       /* Discard all unprocessed line input, force prompt on */
-                       inp->p = NULL;
-#if ENABLE_HUSH_INTERACTIVE
-                       inp->promptme = 1;
-#endif
-               }
-               o_free(&temp);
-               /* loop on syntax errors, return on EOF: */
-       } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
-       return 0;
+               pipe_list = parse_stream(NULL, inp, end_trigger);
+               if (!pipe_list) /* EOF */
+                       break;
+               debug_print_tree(pipe_list, 0);
+               debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
+               run_and_free_list(pipe_list);
+       }
 }
 
-static int parse_and_run_string(const char *s, int parse_flag)
+static void parse_and_run_string(const char *s)
 {
        struct in_str input;
        setup_string_in_str(&input, s);
-       return parse_and_run_stream(&input, parse_flag);
+       parse_and_run_stream(&input, '\0');
 }
 
-static int parse_and_run_file(FILE *f)
+static void parse_and_run_file(FILE *f)
 {
-       int rcode;
        struct in_str input;
        setup_file_in_str(&input, f);
-       rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
-       return rcode;
+       parse_and_run_stream(&input, ';');
 }
 
-#if ENABLE_HUSH_JOB
-/* Make sure we have a controlling tty.  If we get started under a job
- * aware app (like bash for example), make sure we are now in charge so
- * we don't fight over who gets the foreground */
-static void setup_job_control(void)
+/* Called a few times only (or even once if "sh -c") */
+static void block_signals(int second_time)
 {
-       pid_t shell_pgrp;
+       unsigned sig;
+       unsigned mask;
 
-       shell_pgrp = getpgrp();
+       mask = (1 << SIGQUIT);
+       if (G_interactive_fd) {
+               mask = 0
+                       | (1 << SIGQUIT)
+                       | (1 << SIGTERM)
+//TODO                 | (1 << SIGHUP)
+#if ENABLE_HUSH_JOB
+                       | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
+#endif
+                       | (1 << SIGINT)
+               ;
+       }
+       G.non_DFL_mask = mask;
 
-       /* If we were ran as 'hush &',
-        * sleep until we are in the foreground.  */
-       while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
-               /* Send TTIN to ourself (should stop us) */
-               kill(- shell_pgrp, SIGTTIN);
-               shell_pgrp = getpgrp();
+       if (!second_time)
+               sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
+       sig = 0;
+       while (mask) {
+               if (mask & 1)
+                       sigaddset(&G.blocked_set, sig);
+               mask >>= 1;
+               sig++;
        }
+       sigdelset(&G.blocked_set, SIGCHLD);
 
-       /* We _must_ restore tty pgrp on fatal signals */
-       set_fatal_signals_to_sigexit();
+       sigprocmask(SIG_SETMASK, &G.blocked_set,
+                       second_time ? NULL : &G.inherited_set);
+       /* POSIX allows shell to re-enable SIGCHLD
+        * even if it was SIG_IGN on entry */
+//     G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
+       if (!second_time)
+               signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
+}
 
-       /* Put ourselves in our own process group.  */
-       bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
-       /* Grab control of the terminal.  */
-       tcsetpgrp(G.interactive_fd, getpid());
+#if ENABLE_HUSH_JOB
+/* helper */
+static void maybe_set_to_sigexit(int sig)
+{
+       void (*handler)(int);
+       /* non_DFL_mask'ed signals are, well, masked,
+        * no need to set handler for them.
+        */
+       if (!((G.non_DFL_mask >> sig) & 1)) {
+               handler = signal(sig, sigexit);
+               if (handler == SIG_IGN) /* oops... restore back to IGN! */
+                       signal(sig, handler);
+       }
+}
+/* Set handlers to restore tty pgrp and exit */
+static void set_fatal_handlers(void)
+{
+       /* We _must_ restore tty pgrp on fatal signals */
+       if (HUSH_DEBUG) {
+               maybe_set_to_sigexit(SIGILL );
+               maybe_set_to_sigexit(SIGFPE );
+               maybe_set_to_sigexit(SIGBUS );
+               maybe_set_to_sigexit(SIGSEGV);
+               maybe_set_to_sigexit(SIGTRAP);
+       } /* else: hush is perfect. what SEGV? */
+       maybe_set_to_sigexit(SIGABRT);
+       /* bash 3.2 seems to handle these just like 'fatal' ones */
+       maybe_set_to_sigexit(SIGPIPE);
+       maybe_set_to_sigexit(SIGALRM);
+//TODO: disable and move down when proper SIGHUP handling is added
+       maybe_set_to_sigexit(SIGHUP );
+       /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
+        * if we aren't interactive... but in this case
+        * we never want to restore pgrp on exit, and this fn is not called */
+       /*maybe_set_to_sigexit(SIGTERM);*/
+       /*maybe_set_to_sigexit(SIGINT );*/
 }
 #endif
 
@@ -4674,16 +5844,17 @@ int hush_main(int argc, char **argv)
                .flg_export = 1,
                .flg_read_only = 1,
        };
-
+       int signal_mask_is_inited = 0;
        int opt;
-       FILE *input;
        char **e;
        struct variable *cur_var;
 
        INIT_G();
-
-       G.root_pid = getpid();
-
+       if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
+               G.last_exitcode = EXIT_SUCCESS;
+#if !BB_MMU
+       G.argv0_for_re_execing = argv[0];
+#endif
        /* Deal with HUSH_VERSION */
        G.shell_ver = const_shell_ver; /* copying struct here */
        G.top_var = &G.shell_ver;
@@ -4706,11 +5877,9 @@ int hush_main(int argc, char **argv)
        }
        debug_printf_env("putenv '%s'\n", hush_version_str);
        putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
-
 #if ENABLE_FEATURE_EDITING
        G.line_input_state = new_line_input_t(FOR_SHELL);
 #endif
-       /* XXX what should these be while sourcing /etc/profile? */
        G.global_argc = argc;
        G.global_argv = argv;
        /* Initialize some more globals to non-zero values */
@@ -4721,24 +5890,38 @@ int hush_main(int argc, char **argv)
        G.PS2 = "> ";
 #endif
 
-       if (EXIT_SUCCESS) /* otherwise is already done */
-               G.last_return_code = EXIT_SUCCESS;
-
-       if (argv[0] && argv[0][0] == '-') {
-               debug_printf("sourcing /etc/profile\n");
-               input = fopen_for_read("/etc/profile");
-               if (input != NULL) {
-                       close_on_exec_on(fileno(input));
-                       parse_and_run_file(input);
-                       fclose(input);
-               }
+       if (setjmp(die_jmp)) {
+               /* xfunc has failed! die die die */
+               /* no EXIT traps, this is an escape hatch! */
+               G.exiting = 1;
+               hush_exit(xfunc_error_retval);
        }
-       input = stdin;
 
+       /* Shell is non-interactive at first. We need to call
+        * block_signals(0) if we are going to execute "sh <script>",
+        * "sh -c <cmds>" or login shell's /etc/profile and friends.
+        * If we later decide that we are interactive, we run block_signals(0)
+        * (or re-run block_signals(1) if we ran block_signals(0) before)
+        * in order to intercept (more) signals.
+        */
+
+       /* Parse options */
        /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
-       while ((opt = getopt(argc, argv, "c:xins")) > 0) {
+       while (1) {
+               opt = getopt(argc, argv, "c:xins"
+#if !BB_MMU
+                               "<:$:R:V:"
+# if ENABLE_HUSH_FUNCTIONS
+                               "F:"
+# endif
+#endif
+               );
+               if (opt <= 0)
+                       break;
                switch (opt) {
                case 'c':
+                       if (!G.root_pid)
+                               G.root_pid = getpid();
                        G.global_argv = argv + optind;
                        if (!argv[optind]) {
                                /* -c 'script' (no params): prevent empty $0 */
@@ -4746,17 +5929,48 @@ int hush_main(int argc, char **argv)
                                optind--;
                        } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
                        G.global_argc = argc - optind;
-                       opt = parse_and_run_string(optarg, 0 /* parse_flag */);
+                       block_signals(0); /* 0: called 1st time */
+                       parse_and_run_string(optarg);
                        goto final_return;
                case 'i':
                        /* Well, we cannot just declare interactiveness,
                         * we have to have some stuff (ctty, etc) */
-                       /* G.interactive_fd++; */
+                       /* G_interactive_fd++; */
                        break;
                case 's':
                        /* "-s" means "read from stdin", but this is how we always
                         * operate, so simply do nothing here. */
                        break;
+#if !BB_MMU
+               case '<': /* "big heredoc" support */
+                       full_write(STDOUT_FILENO, optarg, strlen(optarg));
+                       _exit(0);
+               case '$':
+                       G.root_pid = bb_strtou(optarg, &optarg, 16);
+                       optarg++;
+                       G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
+                       optarg++;
+                       G.last_exitcode = bb_strtou(optarg, &optarg, 16);
+# if ENABLE_HUSH_LOOPS
+                       optarg++;
+                       G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
+# endif
+                       break;
+               case 'R':
+               case 'V':
+                       set_local_var(xstrdup(optarg), 0, opt == 'R');
+                       break;
+# if ENABLE_HUSH_FUNCTIONS
+               case 'F': {
+                       struct function *funcp = new_function(optarg);
+                       /* funcp->name is already set to optarg */
+                       /* funcp->body is set to NULL. It's a special case. */
+                       funcp->body_as_string = argv[optind];
+                       optind++;
+                       break;
+               }
+# endif
+#endif
                case 'n':
                case 'x':
                        if (!set_mode('-', opt))
@@ -4770,94 +5984,160 @@ int hush_main(int argc, char **argv)
                        bb_show_usage();
 #endif
                }
+       } /* option parsing loop */
+
+       if (!G.root_pid)
+               G.root_pid = getpid();
+
+       /* If we are login shell... */
+       if (argv[0] && argv[0][0] == '-') {
+               FILE *input;
+               /* XXX what should argv be while sourcing /etc/profile? */
+               debug_printf("sourcing /etc/profile\n");
+               input = fopen_for_read("/etc/profile");
+               if (input != NULL) {
+                       close_on_exec_on(fileno(input));
+                       block_signals(0); /* 0: called 1st time */
+                       signal_mask_is_inited = 1;
+                       parse_and_run_file(input);
+                       fclose(input);
+               }
+               /* bash: after sourcing /etc/profile,
+                * tries to source (in the given order):
+                * ~/.bash_profile, ~/.bash_login, ~/.profile,
+                * stopping of first found. --noprofile turns this off.
+                * bash also sources ~/.bash_logout on exit.
+                * If called as sh, skips .bash_XXX files.
+                */
        }
-#if ENABLE_HUSH_JOB
+
+       if (argv[optind]) {
+               FILE *input;
+               /*
+                * "bash <script>" (which is never interactive (unless -i?))
+                * sources $BASH_ENV here (without scanning $PATH).
+                * If called as sh, does the same but with $ENV.
+                */
+               debug_printf("running script '%s'\n", argv[optind]);
+               G.global_argv = argv + optind;
+               G.global_argc = argc - optind;
+               input = xfopen_for_read(argv[optind]);
+               close_on_exec_on(fileno(input));
+               if (!signal_mask_is_inited)
+                       block_signals(0); /* 0: called 1st time */
+               parse_and_run_file(input);
+#if ENABLE_FEATURE_CLEAN_UP
+               fclose(input);
+#endif
+               goto final_return;
+       }
+
+       /* Up to here, shell was non-interactive. Now it may become one.
+        * NB: don't forget to (re)run block_signals(0/1) as needed.
+        */
+
        /* A shell is interactive if the '-i' flag was given, or if all of
         * the following conditions are met:
         *    no -c command
         *    no arguments remaining or the -s flag given
         *    standard input is a terminal
         *    standard output is a terminal
-        *    Refer to Posix.2, the description of the 'sh' utility. */
-       if (argv[optind] == NULL && input == stdin
-        && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
-       ) {
+        * Refer to Posix.2, the description of the 'sh' utility.
+        */
+#if ENABLE_HUSH_JOB
+       if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
                G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
-               debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
+               debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
+//TODO: "interactive" and "have job control" are two different things.
+//If tcgetpgrp fails here, "have job control" is false, but "interactive"
+//should stay on! Currently, we mix these into one.
                if (G.saved_tty_pgrp >= 0) {
-                       /* try to dup to high fd#, >= 255 */
-                       G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
-                       if (G.interactive_fd < 0) {
+                       /* try to dup stdin to high fd#, >= 255 */
+                       G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
+                       if (G_interactive_fd < 0) {
                                /* try to dup to any fd */
-                               G.interactive_fd = dup(STDIN_FILENO);
-                               if (G.interactive_fd < 0)
+                               G_interactive_fd = dup(STDIN_FILENO);
+                               if (G_interactive_fd < 0)
                                        /* give up */
-                                       G.interactive_fd = 0;
+                                       G_interactive_fd = 0;
                        }
-                       // TODO: track & disallow any attempts of user
-                       // to (inadvertently) close/redirect it
+// TODO: track & disallow any attempts of user
+// to (inadvertently) close/redirect it
                }
        }
-       init_signal_mask(); /* note: ensures SIGCHLD is not masked */
-       debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
-       if (G.interactive_fd) {
-               fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
-               /* Looks like they want an interactive shell */
-               setup_job_control();
+       debug_printf("interactive_fd:%d\n", G_interactive_fd);
+       if (G_interactive_fd) {
+               pid_t shell_pgrp;
+
+               /* We are indeed interactive shell, and we will perform
+                * job control. Setting up for that. */
+
+               close_on_exec_on(G_interactive_fd);
+               /* If we were run as 'hush &', sleep until we are
+                * in the foreground (tty pgrp == our pgrp).
+                * If we get started under a job aware app (like bash),
+                * make sure we are now in charge so we don't fight over
+                * who gets the foreground */
+               while (1) {
+                       shell_pgrp = getpgrp();
+                       G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
+                       if (G.saved_tty_pgrp == shell_pgrp)
+                               break;
+                       /* send TTIN to ourself (should stop us) */
+                       kill(- shell_pgrp, SIGTTIN);
+               }
+               /* Block some signals */
+               block_signals(signal_mask_is_inited);
+               /* Set other signals to restore saved_tty_pgrp */
+               set_fatal_handlers();
+               /* Put ourselves in our own process group */
+               bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
+               /* Grab control of the terminal */
+               tcsetpgrp(G_interactive_fd, getpid());
                /* -1 is special - makes xfuncs longjmp, not exit
                 * (we reset die_sleep = 0 whereever we [v]fork) */
-               die_sleep = -1;
-               if (setjmp(die_jmp)) {
-                       /* xfunc has failed! die die die */
-                       hush_exit(xfunc_error_retval);
-               }
-       }
+               enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
+       } else if (!signal_mask_is_inited) {
+               block_signals(0); /* 0: called 1st time */
+       } /* else: block_signals(0) was done before */
 #elif ENABLE_HUSH_INTERACTIVE
-/* no job control compiled, only prompt/line editing */
-       if (argv[optind] == NULL && input == stdin
-        && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
-       ) {
-               G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
-               if (G.interactive_fd < 0) {
+       /* No job control compiled in, only prompt/line editing */
+       if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
+               G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
+               if (G_interactive_fd < 0) {
                        /* try to dup to any fd */
-                       G.interactive_fd = dup(STDIN_FILENO);
-                       if (G.interactive_fd < 0)
+                       G_interactive_fd = dup(STDIN_FILENO);
+                       if (G_interactive_fd < 0)
                                /* give up */
-                               G.interactive_fd = 0;
-               }
-               if (G.interactive_fd) {
-                       fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
+                               G_interactive_fd = 0;
                }
        }
-       init_signal_mask(); /* note: ensures SIGCHLD is not masked */
+       if (G_interactive_fd) {
+               close_on_exec_on(G_interactive_fd);
+               block_signals(signal_mask_is_inited);
+       } else if (!signal_mask_is_inited) {
+               block_signals(0);
+       }
+#else
+       /* We have interactiveness code disabled */
+       if (!signal_mask_is_inited) {
+               block_signals(0);
+       }
 #endif
-       /* POSIX allows shell to re-enable SIGCHLD
-        * even if it was SIG_IGN on entry */
-//     G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
-       signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
+       /* bash:
+        * if interactive but not a login shell, sources ~/.bashrc
+        * (--norc turns this off, --rcfile <file> overrides)
+        */
 
-#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
-       if (G.interactive_fd) {
-               printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
+       if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
+               printf("\n\n%s hush - the humble shell\n", bb_banner);
                printf("Enter 'help' for a list of built-in commands.\n\n");
        }
-#endif
 
-       if (argv[optind] == NULL) {
-               opt = parse_and_run_file(stdin);
-       } else {
-               debug_printf("\nrunning script '%s'\n", argv[optind]);
-               G.global_argv = argv + optind;
-               G.global_argc = argc - optind;
-               input = xfopen_for_read(argv[optind]);
-               fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
-               opt = parse_and_run_file(input);
-       }
+       parse_and_run_file(stdin);
 
  final_return:
-
 #if ENABLE_FEATURE_CLEAN_UP
-       fclose(input);
        if (G.cwd != bb_msg_unknown)
                free((char*)G.cwd);
        cur_var = G.top_var->next;
@@ -4869,7 +6149,7 @@ int hush_main(int argc, char **argv)
                free(tmp);
        }
 #endif
-       hush_exit(opt ? opt : G.last_return_code);
+       hush_exit(G.last_exitcode);
 }
 
 
@@ -4895,9 +6175,10 @@ static int builtin_trap(char **argv)
        if (!G.traps)
                G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
 
-       if (!argv[1]) {
-               /* No args: print all trapped.  This isn't 100% correct as we should
-                * be escaping the cmd so that it can be pasted back in ...
+       argv++;
+       if (!*argv) {
+               /* No args: print all trapped. This isn't 100% correct as we
+                * should be escaping the cmd so that it can be pasted back in
                 */
                for (i = 0; i < NSIG; ++i)
                        if (G.traps[i])
@@ -4907,8 +6188,8 @@ static int builtin_trap(char **argv)
 
        new_cmd = NULL;
        i = 0;
-       /* if first arg is decimal: reset all specified */
-       sig = bb_strtou(*++argv, NULL, 10);
+       /* If first arg is decimal: reset all specified signals */
+       sig = bb_strtou(*argv, NULL, 10);
        if (errno == 0) {
                int ret;
  set_all:
@@ -4917,7 +6198,7 @@ static int builtin_trap(char **argv)
                        sig = get_signum(*argv++);
                        if (sig < 0 || sig >= NSIG) {
                                ret = EXIT_FAILURE;
-                               /* mimic bash message exactly */
+                               /* Mimic bash message exactly */
                                bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
                                continue;
                        }
@@ -4935,7 +6216,7 @@ static int builtin_trap(char **argv)
                        if (new_cmd) {
                                sigaddset(&G.blocked_set, sig);
                        } else {
-                               /* there was a trap handler, we are removing it
+                               /* There was a trap handler, we are removing it
                                 * (if sig has non-DFL handling,
                                 * we don't need to do anything) */
                                if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
@@ -4947,16 +6228,14 @@ static int builtin_trap(char **argv)
                return ret;
        }
 
-       /* first arg is "-": reset all specified to default */
-       /* first arg is "": ignore all specified */
-       /* everything else: execute first arg upon signal */
+       /* First arg is "-": reset all specified to default */
+       /* First arg is "": ignore all specified */
+       /* Everything else: execute first arg upon signal */
        if (!argv[1]) {
                bb_error_msg("trap: invalid arguments");
                return EXIT_FAILURE;
        }
-       if (LONE_DASH(*argv))
-               /* nothing! */;
-       else
+       if (NOT_LONE_DASH(*argv))
                new_cmd = *argv;
        argv++;
        goto set_all;
@@ -4991,26 +6270,32 @@ static int builtin_eval(char **argv)
 {
        int rcode = EXIT_SUCCESS;
 
-       if (argv[1]) {
-               char *str = expand_strvec_to_string(argv + 1);
-               parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
+       if (*++argv) {
+               char *str = expand_strvec_to_string(argv);
+               /* bash:
+                * eval "echo Hi; done" ("done" is syntax error):
+                * "echo Hi" will not execute too.
+                */
+               parse_and_run_string(str);
                free(str);
-               rcode = G.last_return_code;
+               rcode = G.last_exitcode;
        }
        return rcode;
 }
 
 static int builtin_cd(char **argv)
 {
-       const char *newdir;
-       if (argv[1] == NULL) {
-               // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
-               // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
+       const char *newdir = argv[1];
+       if (newdir == NULL) {
+               /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
+                * bash says "bash: cd: HOME not set" and does nothing
+                * (exitcode 1)
+                */
                newdir = getenv("HOME") ? : "/";
-       } else
-               newdir = argv[1];
+       }
        if (chdir(newdir)) {
-               printf("cd: %s: %s\n", newdir, strerror(errno));
+               /* Mimic bash message exactly */
+               bb_perror_msg("cd: %s", newdir);
                return EXIT_FAILURE;
        }
        set_cwd();
@@ -5019,66 +6304,100 @@ static int builtin_cd(char **argv)
 
 static int builtin_exec(char **argv)
 {
-       if (argv[1] == NULL)
+       if (*++argv == NULL)
                return EXIT_SUCCESS; /* bash does this */
        {
 #if !BB_MMU
                nommu_save_t dummy;
 #endif
 // FIXME: if exec fails, bash does NOT exit! We do...
-               pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
+               pseudo_exec_argv(&dummy, argv, 0, NULL);
                /* never returns */
        }
 }
 
 static int builtin_exit(char **argv)
 {
+       debug_printf_exec("%s()\n", __func__);
 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
        //puts("exit"); /* bash does it */
 // TODO: warn if we have background jobs: "There are stopped jobs"
 // On second consecutive 'exit', exit anyway.
-       if (argv[1] == NULL)
-               hush_exit(G.last_return_code);
+// perhaps use G.exiting = -1 as indicator "last cmd was exit"
+
+       /* note: EXIT trap is run by hush_exit */
+       if (*++argv == NULL)
+               hush_exit(G.last_exitcode);
        /* mimic bash: exit 123abc == exit 255 + error msg */
        xfunc_error_retval = 255;
        /* bash: exit -2 == exit 254, no error msg */
-       hush_exit(xatoi(argv[1]) & 0xff);
+       hush_exit(xatoi(*argv) & 0xff);
 }
 
 static int builtin_export(char **argv)
 {
-       const char *value;
-       char *name = argv[1];
-
-       if (name == NULL) {
-               // TODO:
-               // ash emits: export VAR='VAL'
-               // bash: declare -x VAR="VAL"
-               // (both also escape as needed (quotes, $, etc))
+       if (*++argv == NULL) {
                char **e = environ;
-               if (e)
-                       while (*e)
+               if (e) {
+                       while (*e) {
+#if 0
                                puts(*e++);
-               return EXIT_SUCCESS;
-       }
-
-       value = strchr(name, '=');
-       if (!value) {
-               /* They are exporting something without a =VALUE */
-               struct variable *var;
+#else
+                               /* ash emits: export VAR='VAL'
+                                * bash: declare -x VAR="VAL"
+                                * we follow ash example */
+                               const char *s = *e++;
+                               const char *p = strchr(s, '=');
 
-               var = get_local_var(name);
-               if (var) {
-                       var->flg_export = 1;
-                       debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
-                       putenv(var->varstr);
+                               if (!p) /* wtf? take next variable */
+                                       continue;
+                               /* export var= */
+                               printf("export %.*s", (int)(p - s) + 1, s);
+                               s = p + 1;
+                               while (*s) {
+                                       if (*s != '\'') {
+                                               p = strchrnul(s, '\'');
+                                               /* print 'xxxx' */
+                                               printf("'%.*s'", (int)(p - s), s);
+                                               if (*p == '\0')
+                                                       break;
+                                               s = p;
+                                       }
+                                       /* s points to '; print ''...'''" */
+                                       putchar('"');
+                                       do putchar('\''); while (*++s == '\'');
+                                       putchar('"');
+                               }
+                               putchar('\n');
+#endif
+                       }
+                       fflush(stdout);
                }
-               /* bash does not return an error when trying to export
-                * an undefined variable.  Do likewise. */
                return EXIT_SUCCESS;
        }
 
-       set_local_var(xstrdup(name), 1);
+       do {
+               const char *value;
+               char *name = *argv;
+
+               value = strchr(name, '=');
+               if (!value) {
+                       /* They are exporting something without a =VALUE */
+                       struct variable *var;
+
+                       var = get_local_var(name);
+                       if (var) {
+                               var->flg_export = 1;
+                               debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
+                               putenv(var->varstr);
+                       }
+                       /* bash does not return an error when trying to export
+                        * an undefined variable.  Do likewise. */
+                       continue;
+               }
+               set_local_var(xstrdup(name), 1, 0);
+       } while (*++argv);
+
        return EXIT_SUCCESS;
 }
 
@@ -5089,7 +6408,7 @@ static int builtin_fg_bg(char **argv)
        int i, jobnum;
        struct pipe *pi;
 
-       if (!G.interactive_fd)
+       if (!G_interactive_fd)
                return EXIT_FAILURE;
        /* If they gave us no args, assume they want the last backgrounded task */
        if (!argv[1]) {
@@ -5115,9 +6434,9 @@ static int builtin_fg_bg(char **argv)
  found:
        // TODO: bash prints a string representation
        // of job being foregrounded (like "sleep 1 | cat")
-       if (*argv[0] == 'f') {
+       if (argv[0][0] == 'f') {
                /* Put the job into the foreground.  */
-               tcsetpgrp(G.interactive_fd, pi->pgrp);
+               tcsetpgrp(G_interactive_fd, pi->pgrp);
        }
 
        /* Restart the processes in the job */
@@ -5133,12 +6452,11 @@ static int builtin_fg_bg(char **argv)
                if (errno == ESRCH) {
                        delete_finished_bg_job(pi);
                        return EXIT_SUCCESS;
-               } else {
-                       bb_perror_msg("kill (SIGCONT)");
                }
+               bb_perror_msg("kill (SIGCONT)");
        }
 
-       if (*argv[0] == 'f') {
+       if (argv[0][0] == 'f') {
                remove_bg_job(pi);
                return checkjobs_and_fg_shell(pi);
        }
@@ -5151,8 +6469,9 @@ static int builtin_help(char **argv UNUSED_PARAM)
 {
        const struct built_in_command *x;
 
-       printf("\nBuilt-in commands:\n");
-       printf("-------------------\n");
+       printf("\n"
+               "Built-in commands:\n"
+               "------------------\n");
        for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
                printf("%s\t%s\n", x->cmd, x->descr);
        }
@@ -5179,6 +6498,36 @@ static int builtin_jobs(char **argv UNUSED_PARAM)
 }
 #endif
 
+#if HUSH_DEBUG
+static int builtin_memleak(char **argv UNUSED_PARAM)
+{
+       void *p;
+       unsigned long l;
+
+       /* Crude attempt to find where "free memory" starts,
+        * sans fragmentation. */
+       p = malloc(240);
+       l = (unsigned long)p;
+       free(p);
+       p = malloc(3400);
+       if (l < (unsigned long)p) l = (unsigned long)p;
+       free(p);
+
+       if (!G.memleak_value)
+               G.memleak_value = l;
+       
+       l -= G.memleak_value;
+       if ((long)l < 0)
+               l = 0;
+       l /= 1024;
+       if (l > 127)
+               l = 127;
+
+       /* Exitcode is "how many kilobytes we leaked since 1st call" */
+       return l;
+}
+#endif
+
 static int builtin_pwd(char **argv UNUSED_PARAM)
 {
        puts(set_cwd());
@@ -5188,10 +6537,23 @@ static int builtin_pwd(char **argv UNUSED_PARAM)
 static int builtin_read(char **argv)
 {
        char *string;
-       const char *name = argv[1] ? argv[1] : "REPLY";
+       const char *name = "REPLY";
+
+       if (argv[1]) {
+               name = argv[1];
+               /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
+                * and _after_ that_ it will complain */
+               if (!is_well_formed_var_name(name, '\0')) {
+                       /* Mimic bash message */
+                       bb_error_msg("read: '%s': not a valid identifier", name);
+                       return 1;
+               }
+       }
+
+//TODO: bash unbackslashes input, splits words and puts them in argv[i]
 
        string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
-       return set_local_var(string, 0);
+       return set_local_var(string, 0, 0);
 }
 
 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
@@ -5233,19 +6595,14 @@ static int builtin_set(char **argv)
                        ++argv;
                        goto set_argv;
                }
-
-               if (arg[0] == '+' || arg[0] == '-') {
-                       for (n = 1; arg[n]; ++n)
-                               if (set_mode(arg[0], arg[n]))
-                                       goto error;
-                       continue;
-               }
-
-               break;
+               if (arg[0] != '+' && arg[0] != '-')
+                       break;
+               for (n = 1; arg[n]; ++n)
+                       if (set_mode(arg[0], arg[n]))
+                               goto error;
        } while ((arg = *++argv) != NULL);
        /* Now argv[0] is 1st argument */
 
-       /* Only reset global_argv if we didn't process anything */
        if (arg == NULL)
                return EXIT_SUCCESS;
  set_argv:
@@ -5302,26 +6659,26 @@ static int builtin_shift(char **argv)
 static int builtin_source(char **argv)
 {
        FILE *input;
-       int status;
 
-       if (argv[1] == NULL)
+       if (*++argv == NULL)
                return EXIT_FAILURE;
 
        /* XXX search through $PATH is missing */
-       input = fopen_for_read(argv[1]);
+       input = fopen_or_warn(*argv, "r");
        if (!input) {
-               bb_error_msg("can't open '%s'", argv[1]);
+               /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
                return EXIT_FAILURE;
        }
        close_on_exec_on(fileno(input));
 
        /* Now run the file */
+//TODO:
        /* XXX argv and argc are broken; need to save old G.global_argv
         * (pointer only is OK!) on this stack frame,
         * set G.global_argv=argv+1, recurse, and restore. */
-       status = parse_and_run_file(input);
+       parse_and_run_file(input);
        fclose(input);
-       return status;
+       return G.last_exitcode;
 }
 
 static int builtin_umask(char **argv)
@@ -5329,12 +6686,18 @@ static int builtin_umask(char **argv)
        mode_t new_umask;
        const char *arg = argv[1];
        if (arg) {
+//TODO: umask may take chmod-like symbolic masks
                new_umask = bb_strtou(arg, NULL, 8);
-               if (errno)
+               if (errno) {
+                       //Message? bash examples:
+                       //bash: umask: 'q': invalid symbolic mode operator
+                       //bash: umask: 999: octal number out of range
                        return EXIT_FAILURE;
+               }
        } else {
                new_umask = umask(0);
                printf("%.3o\n", (unsigned) new_umask);
+               /* fall through and restore new_umask which we set to 0 */
        }
        umask(new_umask);
        return EXIT_SUCCESS;
@@ -5343,35 +6706,43 @@ static int builtin_umask(char **argv)
 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
 static int builtin_unset(char **argv)
 {
-       size_t i;
        int ret;
-       bool var = true;
+       char var;
 
-       if (!argv[1])
+       if (!*++argv)
                return EXIT_SUCCESS;
 
-       i = 0;
-       if (argv[1][0] == '-') {
-               switch (argv[1][1]) {
-               case 'v': break;
-               case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
+       var = 'v';
+       if (argv[0][0] == '-') {
+               switch (argv[0][1]) {
+               case 'v':
+               case 'f':
+                       var = argv[0][1];
+                       break;
                default:
-                       bb_error_msg("unset: %s: invalid option", argv[1]);
+                       bb_error_msg("unset: %s: invalid option", *argv);
                        return EXIT_FAILURE;
                }
-               ++i;
+//TODO: disallow "unset -vf ..." too
+               argv++;
        }
 
        ret = EXIT_SUCCESS;
-       while (argv[++i]) {
-               if (var) {
-                       if (unset_local_var(argv[i]))
+       while (*argv) {
+               if (var == 'v') {
+                       if (unset_local_var(*argv)) {
+                               /* unset <nonexistent_var> doesn't fail.
+                                * Error is when one tries to unset RO var.
+                                * Message was printed by unset_local_var. */
                                ret = EXIT_FAILURE;
+                       }
                }
-#if ENABLE_HUSH_FUNCTIONS
-               else
-                       unset_local_func(argv[i]);
-#endif
+//#if ENABLE_HUSH_FUNCTIONS
+//             else {
+//                     unset_local_func(*argv);
+//             }
+//#endif
+               argv++;
        }
        return ret;
 }