hush: delete hush-bugs/glob_and_vars.tests for real
[oweals/busybox.git] / shell / hush.c
index 58100d4d162dd185947554a81a6dcb5b85e5e62f..7c5a442747ccacd0471a86dc96c149e7b78a47f0 100644 (file)
  *      rewrites.
  *
  * Other credits:
- *      b_addchr() derived from similar w_addchar function in glibc-2.2
+ *      o_addchr() derived from similar w_addchar function in glibc-2.2.
  *      setup_redirect(), redirect_opt_num(), and big chunks of main()
  *      and many builtins derived from contributions by Erik Andersen
- *      miscellaneous bugfixes from Matt Kraai
+ *      miscellaneous bugfixes from Matt Kraai.
  *
  * There are two big (and related) architecture differences between
  * this parser and the lash parser.  One is that this version is
@@ -38,7 +38,6 @@
  *
  * Bash grammar not implemented: (how many of these were in original sh?)
  *      $_
- *      ! negation operator for pipes
  *      &> and >& redirection of stdout+stderr
  *      Brace Expansion
  *      Tilde Expansion
  *      reserved word execution woefully incomplete and buggy
  * to-do:
  *      port selected bugfixes from post-0.49 busybox lash - done?
- *      finish implementing reserved words: for, while, until, do, done
  *      change { and } from special chars to reserved words
  *      builtins: break, continue, eval, return, set, trap, ulimit
  *      test magic exec
- *      handle children going into background
- *      clean up recognition of null pipes
  *      check setting of global_argc and global_argv
- *      control-C handling, probably with longjmp
  *      follow IFS rules more precisely, including update semantics
  *      figure out what to do with backslash-newline
- *      explain why we use signal instead of sigaction
  *      propagate syntax errors, die on resource errors?
  *      continuation lines, both explicit and implicit - done?
  *      memory leak finding and plugging - done?
- *      more testing, especially quoting rules and redirection
- *      document how quoting rules not precisely followed for variable assignments
  *      maybe change charmap[] to use 2-bit entries
- *      (eventually) remove all the printf's
  *
  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  */
@@ -187,11 +178,8 @@ void xxfree(void *ptr)
 #endif
 
 
-#define SPECIAL_VAR_SYMBOL   3
-
+#define SPECIAL_VAR_SYMBOL       3
 #define PARSEFLAG_EXIT_FROM_LOOP 1
-#define PARSEFLAG_SEMICOLON      (1 << 1)  /* symbol ';' is special for parser */
-#define PARSEFLAG_REPARSING      (1 << 2)  /* >= 2nd pass */
 
 typedef enum {
        REDIRECT_INPUT     = 1,
@@ -244,26 +232,6 @@ typedef enum {
        RES_XXXX  = 12,
        RES_SNTX  = 13
 } reserved_style;
-enum {
-       FLAG_END   = (1 << RES_NONE ),
-#if ENABLE_HUSH_IF
-       FLAG_IF    = (1 << RES_IF   ),
-       FLAG_THEN  = (1 << RES_THEN ),
-       FLAG_ELIF  = (1 << RES_ELIF ),
-       FLAG_ELSE  = (1 << RES_ELSE ),
-       FLAG_FI    = (1 << RES_FI   ),
-#endif
-#if ENABLE_HUSH_LOOPS
-       FLAG_FOR   = (1 << RES_FOR  ),
-       FLAG_WHILE = (1 << RES_WHILE),
-       FLAG_UNTIL = (1 << RES_UNTIL),
-       FLAG_DO    = (1 << RES_DO   ),
-       FLAG_DONE  = (1 << RES_DONE ),
-       FLAG_IN    = (1 << RES_IN   ),
-#endif
-       FLAG_START = (1 << RES_XXXX ),
-};
-
 /* This holds pointers to the various results of parsing */
 struct p_context {
        struct child_prog *child;
@@ -271,10 +239,9 @@ struct p_context {
        struct pipe *pipe;
        struct redir_struct *pending_redirect;
        smallint res_w;
-       smallint parse_type;        /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
+       smallint ctx_inverted;      /* "! cmd | cmd" */
        int old_flag;               /* bitmask of FLAG_xxx, for figuring out valid reserved words */
        struct p_context *stack;
-       /* How about quoting status? */
 };
 
 struct redir_struct {
@@ -293,10 +260,6 @@ struct child_prog {
        smallint is_stopped;        /* is the program currently running? */
        struct redir_struct *redirects; /* I/O redirections */
        struct pipe *family;        /* pointer back to the child's parent pipe */
-       //sp counting seems to be broken... so commented out, grep for '//sp:'
-       //sp: int sp;               /* number of SPECIAL_VAR_SYMBOL */
-       //seems to be unused, grep for '//pt:'
-       //pt: int parse_type;
 };
 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  * and on execution these are substituted with their values.
@@ -317,6 +280,7 @@ struct pipe {
        char *cmdbuf;               /* buffer various argv's point into */
        struct child_prog *progs;   /* array of commands in pipe */
        int job_context;            /* bitmask defining current context */
+       smallint pi_inverted;       /* "! cmd | cmd" */
        smallint followup;          /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
        smallint res_word;          /* needed for if, for, while, until... */
 };
@@ -361,8 +325,8 @@ struct in_str {
        int (*get) (struct in_str *);
        int (*peek) (struct in_str *);
 };
-#define b_getch(input) ((input)->get(input))
-#define b_peek(input) ((input)->peek(input))
+#define i_getch(input) ((input)->get(input))
+#define i_peek(input) ((input)->peek(input))
 
 enum {
        CHAR_ORDINARY           = 0,
@@ -517,10 +481,6 @@ static int run_list(struct pipe *pi);
 static void pseudo_exec_argv(char **ptrs2free, char **argv) ATTRIBUTE_NORETURN;
 static void pseudo_exec(char **ptrs2free, struct child_prog *child) ATTRIBUTE_NORETURN;
 static int run_pipe(struct pipe *pi);
-/*   extended glob support: */
-static char **globhack(const char *src, char **strings);
-static int glob_needed(const char *s);
-static int xglob(o_string *dest, char ***pglob);
 /*   variable assignment: */
 static int is_assignment(const char *s);
 /*   data structure manipulation: */
@@ -528,17 +488,17 @@ static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struc
 static void initialize_context(struct p_context *ctx);
 static int done_word(o_string *dest, struct p_context *ctx);
 static int done_command(struct p_context *ctx);
-static int done_pipe(struct p_context *ctx, pipe_style type);
+static void done_pipe(struct p_context *ctx, pipe_style type);
 /*   primary string parsing: */
 static int redirect_dup_num(struct in_str *input);
 static int redirect_opt_num(o_string *o);
 #if ENABLE_HUSH_TICK
-static int process_command_subs(o_string *dest, /*struct p_context *ctx,*/
+static int process_command_subs(o_string *dest,
                struct in_str *input, const char *subst_end);
 #endif
 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
 static const char *lookup_param(const char *src);
-static int handle_dollar(o_string *dest, /*struct p_context *ctx,*/
+static int handle_dollar(o_string *dest,
                struct in_str *input);
 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
 /*   setup: */
@@ -616,7 +576,6 @@ static void free_strings(char **strings)
        }
 }
 
-
 #if !BB_MMU
 #define EXTRA_PTRS 5 /* 1 for NULL, 1 for args, 3 for paranoid reasons */
 static char **alloc_ptrs(char **argv)
@@ -628,6 +587,17 @@ static char **alloc_ptrs(char **argv)
 }
 #endif
 
+#ifdef 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
+
 
 /* Function prototypes for builtins */
 static int builtin_cd(char **argv);
@@ -646,6 +616,7 @@ static int builtin_help(char **argv);
 static int builtin_pwd(char **argv);
 static int builtin_read(char **argv);
 static int builtin_test(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);
@@ -660,10 +631,10 @@ static int builtin_unset(char **argv);
  * For example, 'unset foo | whatever' will parse and run, but foo will
  * still be set at the end. */
 struct built_in_command {
-       const char *cmd;                /* name */
-       int (*function) (char **argv);  /* function ptr */
+       const char *cmd;
+       int (*function)(char **argv);
 #if ENABLE_HUSH_HELP
-       const char *descr;              /* description */
+       const char *descr;
 #define BLTIN(cmd, func, help) { cmd, func, help }
 #else
 #define BLTIN(cmd, func, help) { cmd, func }
@@ -673,24 +644,25 @@ 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_test, "Test condition"),
 #if ENABLE_HUSH_JOB
        BLTIN("bg"    , builtin_fg_bg, "Resume a job in the background"),
 #endif
 //     BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
-       BLTIN("cd"    , builtin_cd, "Change working directory"),
+       BLTIN("cd"    , builtin_cd, "Change directory"),
 //     BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
        BLTIN("echo"  , builtin_echo, "Write strings to stdout"),
        BLTIN("eval"  , builtin_eval, "Construct and run shell command"),
-       BLTIN("exec"  , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
-       BLTIN("exit"  , builtin_exit, "Exit from shell"),
+       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, "Lists the active jobs"),
+       BLTIN("jobs"  , builtin_jobs, "List active jobs"),
 #endif
-// TODO: remove pwd? we have it as an applet...
        BLTIN("pwd"   , builtin_pwd, "Print current directory"),
        BLTIN("read"  , builtin_read, "Input environment variable"),
 //     BLTIN("return", builtin_not_written, "Return from a function"),
@@ -698,14 +670,12 @@ static const struct built_in_command bltins[] = {
        BLTIN("shift" , builtin_shift, "Shift positional parameters"),
 //     BLTIN("trap"  , builtin_not_written, "Trap signals"),
        BLTIN("test"  , builtin_test, "Test condition"),
-//     BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
-       BLTIN("umask" , builtin_umask, "Sets file creation mask"),
+//     BLTIN("ulimit", builtin_not_written, "Control resource limits"),
+       BLTIN("umask" , builtin_umask, "Set file creation mask"),
        BLTIN("unset" , builtin_unset, "Unset environment variable"),
-       BLTIN("."     , builtin_source, "Source-in and run commands in a file"),
 #if ENABLE_HUSH_HELP
        BLTIN("help"  , builtin_help, "List shell built-in commands"),
 #endif
-       BLTIN(NULL, NULL, NULL)
 };
 
 /* Signals are grouped, we handle them in batches */
@@ -841,6 +811,12 @@ static const char *set_cwd(void)
 }
 
 
+/* built-in 'true' handler */
+static int builtin_true(char **argv ATTRIBUTE_UNUSED)
+{
+       return 0;
+}
+
 /* built-in 'test' handler */
 static int builtin_test(char **argv)
 {
@@ -870,8 +846,7 @@ static int builtin_eval(char **argv)
 
        if (argv[1]) {
                char *str = expand_strvec_to_string(argv + 1);
-               parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
-                                       PARSEFLAG_SEMICOLON);
+               parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
                free(str);
                rcode = last_return_code;
        }
@@ -918,7 +893,6 @@ static int builtin_exit(char **argv)
        //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(last_return_code);
        /* mimic bash: exit 123abc == exit 255 + error msg */
@@ -1036,7 +1010,7 @@ static int builtin_help(char **argv ATTRIBUTE_UNUSED)
 
        printf("\nBuilt-in commands:\n");
        printf("-------------------\n");
-       for (x = bltins; x->cmd; x++) {
+       for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
                printf("%s\t%s\n", x->cmd, x->descr);
        }
        printf("\n\n");
@@ -1164,18 +1138,12 @@ static int builtin_unset(char **argv)
        return EXIT_SUCCESS;
 }
 
-//static int builtin_not_written(char **argv)
-//{
-//     printf("builtin_%s not written\n", argv[0]);
-//     return EXIT_FAILURE;
-//}
-
 /*
  * o_string support
  */
 #define B_CHUNK  (32 * sizeof(char*))
 
-static void b_reset(o_string *o)
+static void o_reset(o_string *o)
 {
        o->length = 0;
        o->nonnull = 0;
@@ -1183,13 +1151,13 @@ static void b_reset(o_string *o)
                o->data[0] = '\0';
 }
 
-static void b_free(o_string *o)
+static void o_free(o_string *o)
 {
        free(o->data);
        memset(o, 0, sizeof(*o));
 }
 
-static void b_grow_by(o_string *o, int len)
+static void o_grow_by(o_string *o, int len)
 {
        if (o->length + len > o->maxlen) {
                o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
@@ -1197,18 +1165,18 @@ static void b_grow_by(o_string *o, int len)
        }
 }
 
-static void b_addchr(o_string *o, int ch)
+static void o_addchr(o_string *o, int ch)
 {
-       debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
-       b_grow_by(o, 1);
+       debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
+       o_grow_by(o, 1);
        o->data[o->length] = ch;
        o->length++;
        o->data[o->length] = '\0';
 }
 
-static void b_addstr(o_string *o, const char *str, int len)
+static void o_addstr(o_string *o, const char *str, int len)
 {
-       b_grow_by(o, len);
+       o_grow_by(o, len);
        memcpy(&o->data[o->length], str, len);
        o->length += len;
        o->data[o->length] = '\0';
@@ -1217,12 +1185,64 @@ static void b_addstr(o_string *o, const char *str, int len)
 /* My analysis of quoting semantics tells me that state information
  * is associated with a destination, not a source.
  */
-static void b_addqchr(o_string *o, int ch, int quote)
+static void o_addqchr(o_string *o, int ch)
+{
+       int sz = 1;
+       if (strchr("*?[\\", ch)) {
+               sz++;
+               o->data[o->length] = '\\';
+               o->length++;
+       }
+       o_grow_by(o, sz);
+       o->data[o->length] = ch;
+       o->length++;
+       o->data[o->length] = '\0';
+}
+
+static void o_addQchr(o_string *o, int ch)
+{
+       int sz = 1;
+       if (o->o_quote && strchr("*?[\\", ch)) {
+               sz++;
+               o->data[o->length] = '\\';
+               o->length++;
+       }
+       o_grow_by(o, sz);
+       o->data[o->length] = ch;
+       o->length++;
+       o->data[o->length] = '\0';
+}
+
+static void o_addQstr(o_string *o, const char *str, int len)
 {
-       if (quote && strchr("*?[\\", ch)) {
-               b_addchr(o, '\\');
+       if (!o->o_quote) {
+               o_addstr(o, str, len);
+               return;
+       }
+       while (len) {
+               char ch;
+               int sz;
+               int ordinary_cnt = strcspn(str, "*?[\\");
+               if (ordinary_cnt > len) /* paranoia */
+                       ordinary_cnt = len;
+               o_addstr(o, str, ordinary_cnt);
+               if (ordinary_cnt == len)
+                       return;
+               str += ordinary_cnt;
+               len -= ordinary_cnt - 1; /* we are processing + 1 char below */
+
+               ch = *str++;
+               sz = 1;
+               if (ch) { /* it is necessarily one of "*?[\\" */
+                       sz++;
+                       o->data[o->length] = '\\';
+                       o->length++;
+               }
+               o_grow_by(o, sz);
+               o->data[o->length] = ch;
+               o->length++;
+               o->data[o->length] = '\0';
        }
-       b_addchr(o, ch);
 }
 
 /* A special kind of o_string for $VAR and `cmd` expansion.
@@ -1232,17 +1252,20 @@ static void b_addqchr(o_string *o, int ch, int quote)
  * It means that if list[] needs to grow, data needs to be moved higher up
  * but list[i]'s need not be modified.
  * NB: remembering how many list[i]'s you have there is crucial.
- * b_finalize_list() operation post-processes this structure - calculates
+ * o_finalize_list() operation post-processes this structure - calculates
  * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  */
-static int b_addptr(o_string *o, int n)
+static int o_save_ptr(o_string *o, int n)
 {
        char **list = (char**)o->data;
-       int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
-       int string_len = o->length - string_start;
+       int string_start;
+       int string_len;
 
        if (!o->has_empty_slot) {
+               string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
+               string_len = o->length - string_start;
                if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
+                       //bb_error_msg("list[%d]=%d string_start=%d (growing)", n, string_len, string_start);
                        /* list[n] points to string_start, make space for 16 more pointers */
                        o->maxlen += 0x10 * sizeof(list[0]);
                        o->data = xrealloc(o->data, o->maxlen + 1);
@@ -1250,15 +1273,19 @@ static int b_addptr(o_string *o, int n)
                        memmove(list + n + 0x10, list + n, string_len);
                        o->length += 0x10 * sizeof(list[0]);
                }
+               //else bb_error_msg("list[%d]=%d string_start=%d", 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;
+               //bb_error_msg("list[%d]=%d string_start=%d (empty slot)", n, string_len, string_start);
                o->has_empty_slot = 0;
        }
        list[n] = (char*)string_len;
        return n + 1;
 }
 
-static int b_get_last_ptr(o_string *o, int n)
+static int o_get_last_ptr(o_string *o, int n)
 {
        char **list = (char**)o->data;
        int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
@@ -1266,12 +1293,12 @@ static int b_get_last_ptr(o_string *o, int n)
        return ((int)list[n-1]) + string_start;
 }
 
-static char **b_finalize_list(o_string *o, int n)
+static char **o_finalize_list(o_string *o, int n)
 {
        char **list = (char**)o->data;
        int string_start;
 
-       b_addptr(o, n); /* force growth for list[n] if necessary */
+       o_save_ptr(o, n); /* force growth for list[n] if necessary */
        string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]);
        list[n] = NULL;
        while (n) {
@@ -1282,7 +1309,7 @@ static char **b_finalize_list(o_string *o, int n)
 }
 
 #ifdef DEBUG_EXPAND
-static void b_debug_list(const char *prefix, o_string *o, int n)
+static void o_debug_list(const char *prefix, o_string *o, int n)
 {
        char **list = (char**)o->data;
        int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
@@ -1300,7 +1327,7 @@ static void b_debug_list(const char *prefix, o_string *o, int n)
        }
 }
 #else
-#define b_debug_list(prefix, o, n) ((void)0)
+#define o_debug_list(prefix, o, n) ((void)0)
 #endif
 
 
@@ -1555,7 +1582,7 @@ static void pseudo_exec_argv(char **ptrs2free, char **argv)
         * easier to waste a few CPU cycles than it is to figure out
         * if this is one of those cases.
         */
-       for (x = bltins; x->cmd; x++) {
+       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]);
                        rcode = x->function(argv);
@@ -1593,9 +1620,6 @@ static void pseudo_exec_argv(char **ptrs2free, char **argv)
  */
 static void pseudo_exec(char **ptrs2free, struct child_prog *child)
 {
-// FIXME: buggy wrt NOMMU! Must not modify any global data
-// until it does exec/_exit, but currently it does
-// (puts malloc'ed stuff into environment)
        if (child->argv)
                pseudo_exec_argv(ptrs2free, child->argv);
 
@@ -1604,12 +1628,6 @@ static void pseudo_exec(char **ptrs2free, struct child_prog *child)
                bb_error_msg_and_die("nested lists are not supported on NOMMU");
 #else
                int rcode;
-
-#if ENABLE_HUSH_INTERACTIVE
-// run_list_level now takes care of it?
-//             debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
-//             interactive_fd = 0;    /* crucial!!!! */
-#endif
                debug_printf_exec("pseudo_exec: run_list\n");
                rcode = run_list(child->group);
                /* OK to leak memory by not calling free_pipe_list,
@@ -1636,8 +1654,10 @@ static const char *get_cmdtext(struct pipe *pi)
        if (pi->cmdtext)
                return pi->cmdtext;
        argv = pi->progs[0].argv;
-       if (!argv || !argv[0])
-               return (pi->cmdtext = xzalloc(1));
+       if (!argv || !argv[0]) {
+               pi->cmdtext = xzalloc(1);
+               return pi->cmdtext;
+       }
 
        len = 0;
        do len += strlen(*argv) + 1; while (*++argv);
@@ -1778,9 +1798,12 @@ static int checkjobs(struct pipe* fg_pipe)
                                        if (dead) {
                                                fg_pipe->progs[i].pid = 0;
                                                fg_pipe->running_progs--;
-                                               if (i == fg_pipe->num_progs - 1)
+                                               if (i == fg_pipe->num_progs - 1) {
                                                        /* last process gives overall exitstatus */
                                                        rcode = WEXITSTATUS(status);
+                                                       if (fg_pipe->pi_inverted)
+                                                               rcode = !rcode;
+                                               }
                                        } else {
                                                fg_pipe->progs[i].is_stopped = 1;
                                                fg_pipe->stopped_progs++;
@@ -1911,6 +1934,8 @@ static int run_pipe(struct pipe *pi)
                rcode = run_list(child->group) & 0xff;
                restore_redirects(squirrel);
                debug_printf_exec("run_pipe return %d\n", rcode);
+               if (pi->pi_inverted)
+                       rcode = !rcode;
                return rcode;
        }
 
@@ -1931,10 +1956,9 @@ static int run_pipe(struct pipe *pi)
                }
                for (i = 0; is_assignment(argv[i]); i++) {
                        p = expand_string_to_string(argv[i]);
-                       //sp: child->sp--;
                        putenv(p);
                }
-               for (x = bltins; x->cmd; x++) {
+               for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
                        if (strcmp(argv[i], x->cmd) == 0) {
                                if (x->function == builtin_exec && argv[i+1] == NULL) {
                                        debug_printf("magic exec\n");
@@ -1948,12 +1972,13 @@ static int run_pipe(struct pipe *pi)
                                 * things seem to work with glibc. */
                                setup_redirects(child, squirrel);
                                debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
-                               //sp: if (child->sp) /* btw we can do it unconditionally... */
                                argv_expanded = expand_strvec_to_strvec(argv + i);
                                rcode = x->function(argv_expanded) & 0xff;
                                free(argv_expanded);
                                restore_redirects(squirrel);
                                debug_printf_exec("run_pipe return %d\n", rcode);
+                               if (pi->pi_inverted)
+                                       rcode = !rcode;
                                return rcode;
                        }
                }
@@ -1964,13 +1989,14 @@ static int run_pipe(struct pipe *pi)
                                setup_redirects(child, squirrel);
                                save_nofork_data(&nofork_save);
                                argv_expanded = argv + i;
-                               //sp: if (child->sp)
                                argv_expanded = expand_strvec_to_strvec(argv + i);
                                debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
                                rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
                                free(argv_expanded);
                                restore_redirects(squirrel);
                                debug_printf_exec("run_pipe return %d\n", rcode);
+                               if (pi->pi_inverted)
+                                       rcode = !rcode;
                                return rcode;
                        }
                }
@@ -2224,7 +2250,6 @@ static int run_list(struct pipe *pi)
 #endif /* JOB */
 
        for (; pi; pi = flag_restore ? rpipe : pi->next) {
-//why?         int save_num_progs;
                rword = pi->res_word;
 #if ENABLE_HUSH_LOOPS
                if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
@@ -2262,7 +2287,9 @@ static int run_list(struct pipe *pi)
                                if (!pi->next->progs->argv)
                                        continue;
                                /* create list of variable values */
+                               debug_print_strings("for_list made from", pi->next->progs->argv);
                                for_list = expand_strvec_to_strvec(pi->next->progs->argv);
+                               debug_print_strings("for_list", for_list);
                                for_lcur = for_list;
                                for_varname = pi->progs->argv[0];
                                pi->progs->argv[0] = NULL;
@@ -2297,7 +2324,6 @@ static int run_list(struct pipe *pi)
 #endif
                if (pi->num_progs == 0)
                        continue;
-//why?         save_num_progs = pi->num_progs;
                debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
                rcode = run_pipe(pi);
                if (rcode != -1) {
@@ -2328,7 +2354,6 @@ static int run_list(struct pipe *pi)
                }
                debug_printf_exec(": setting last_return_code=%d\n", rcode);
                last_return_code = rcode;
-//why?         pi->num_progs = save_num_progs;
 #if ENABLE_HUSH_IF
                if (rword == RES_IF || rword == RES_ELIF)
                        next_if_code = rcode;  /* can be overwritten a number of times */
@@ -2445,21 +2470,14 @@ static int run_and_free_list(struct pipe *pi)
         * 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);
-       debug_printf_exec("run_nad_free_list return %d\n", rcode);
+       debug_printf_exec("run_and_free_list return %d\n", rcode);
        return rcode;
 }
 
-/* Whoever decided to muck with glob internal data is AN IDIOT! */
-/* uclibc happily changed the way it works (and it has rights to do so!),
-   all hell broke loose (SEGVs) */
-
-/* The API for glob is arguably broken.  This routine pushes a non-matching
- * string into the output structure, removing non-backslashed backslashes.
- * If someone can prove me wrong, by performing this function within the
- * original glob(3) api, feel free to rewrite this routine into oblivion.
+/* Remove non-backslashed backslashes and add to "strings" vector.
  * XXX broken if the last character is '\\', check that before calling.
  */
-static char **globhack(const char *src, char **strings)
+static char **add_unq_string_to_strings(char **strings, const char *src)
 {
        int cnt;
        const char *s;
@@ -2491,33 +2509,20 @@ static int glob_needed(const char *s)
        return 0;
 }
 
-static int xglob(o_string *dest, char ***pglob)
+static int xglob(char ***pglob, const char *pattern)
 {
-       /* short-circuit for null word */
-       /* we can code this better when the debug_printf's are gone */
-       if (dest->length == 0) {
-               if (dest->nonnull) {
-                       /* bash man page calls this an "explicit" null */
-                       *pglob = globhack(dest->data, *pglob);
-               }
-               return 0;
-       }
-
-       if (glob_needed(dest->data)) {
+       if (glob_needed(pattern)) {
                glob_t globdata;
                int gr;
 
                memset(&globdata, 0, sizeof(globdata));
-               gr = glob(dest->data, 0, NULL, &globdata);
+               gr = glob(pattern, 0, NULL, &globdata);
                debug_printf("glob returned %d\n", gr);
                if (gr == GLOB_NOSPACE)
                        bb_error_msg_and_die("out of memory during glob");
                if (gr == GLOB_NOMATCH) {
-                       debug_printf("globhack returned %d\n", gr);
-                       /* quote removal, or more accurately, backslash removal */
-                       *pglob = globhack(dest->data, *pglob);
                        globfree(&globdata);
-                       return 0;
+                       goto literal;
                }
                if (gr != 0) { /* GLOB_ABORTED ? */
                        bb_error_msg("glob(3) error %d", gr);
@@ -2528,7 +2533,10 @@ static int xglob(o_string *dest, char ***pglob)
                return gr;
        }
 
-       *pglob = globhack(dest->data, *pglob);
+ literal:
+       /* quote removal, or more accurately, backslash removal */
+       *pglob = add_unq_string_to_strings(*pglob, pattern);
+       debug_print_strings("after xglob", *pglob);
        return 0;
 }
 
@@ -2549,17 +2557,17 @@ static int expand_on_ifs(o_string *output, int n, const char *str)
        while (1) {
                int word_len = strcspn(str, ifs);
                if (word_len) {
-                       b_addstr(output, str, word_len); /* store non-ifs chars */
+                       o_addQstr(output, str, word_len);
                        str += word_len;
                }
                if (!*str)  /* EOL - do not finalize word */
                        break;
-               b_addchr(output, '\0');
-               b_debug_list("expand_on_ifs", output, n);
-               n = b_addptr(output, n);
+               o_addchr(output, '\0');
+               o_debug_list("expand_on_ifs", output, n);
+               n = o_save_ptr(output, n);
                str += strspn(str, ifs); /* skip ifs chars */
        }
-       b_debug_list("expand_on_ifs[1]", output, n);
+       o_debug_list("expand_on_ifs[1]", output, n);
        return n;
 }
 
@@ -2583,15 +2591,15 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
        ored_ch = 0;
 
        debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
-       b_debug_list("expand_vars_to_list", output, n);
-       n = b_addptr(output, n);
-       b_debug_list("expand_vars_to_list[0]", output, n);
+       o_debug_list("expand_vars_to_list", output, n);
+       n = o_save_ptr(output, n);
+       o_debug_list("expand_vars_to_list[0]", output, n);
 
        while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
                o_string subst_result = NULL_O_STRING;
 
-               b_addstr(output, arg, p - arg);
-               b_debug_list("expand_vars_to_list[1]", output, n);
+               o_addQstr(output, arg, p - arg);
+               o_debug_list("expand_vars_to_list[1]", output, n);
                arg = ++p;
                p = strchr(p, SPECIAL_VAR_SYMBOL);
 
@@ -2625,10 +2633,10 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                        if (global_argv[i++][0] && global_argv[i]) {
                                                /* this argv[] is not empty and not last:
                                                 * put terminating NUL, start new word */
-                                               b_addchr(output, '\0');
-                                               b_debug_list("expand_vars_to_list[2]", output, n);
-                                               n = b_addptr(output, n);
-                                               b_debug_list("expand_vars_to_list[3]", output, n);
+                                               o_addchr(output, '\0');
+                                               o_debug_list("expand_vars_to_list[2]", output, n);
+                                               n = o_save_ptr(output, n);
+                                               o_debug_list("expand_vars_to_list[3]", output, n);
                                        }
                                }
                        } else
@@ -2636,20 +2644,20 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                         * and in this case should treat it like '$*' - see 'else...' below */
                        if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
                                while (1) {
-                                       b_addstr(output, global_argv[i], strlen(global_argv[i]));
+                                       o_addQstr(output, global_argv[i], strlen(global_argv[i]));
                                        if (++i >= global_argc)
                                                break;
-                                       b_addchr(output, '\0');
-                                       b_debug_list("expand_vars_to_list[4]", output, n);
-                                       n = b_addptr(output, n);
+                                       o_addchr(output, '\0');
+                                       o_debug_list("expand_vars_to_list[4]", output, n);
+                                       n = o_save_ptr(output, n);
                                }
                        } else { /* quoted $*: add as one word */
                                while (1) {
-                                       b_addstr(output, global_argv[i], strlen(global_argv[i]));
+                                       o_addQstr(output, global_argv[i], strlen(global_argv[i]));
                                        if (!global_argv[++i])
                                                break;
                                        if (ifs[0])
-                                               b_addchr(output, ifs[0]);
+                                               o_addchr(output, ifs[0]);
                                }
                        }
                        break;
@@ -2684,25 +2692,27 @@ static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
                                }
                        } /* else: quoted $VAR, val will be appended below */
                }
-               if (val)
-                       b_addstr(output, val, strlen(val));
+               if (val) {
+                       o_addQstr(output, val, strlen(val));
+               }
 
-               b_free(&subst_result);
+               o_free(&subst_result);
                arg = ++p;
        } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
 
-       b_debug_list("expand_vars_to_list[a]", output, n);
-       b_addstr(output, arg, strlen(arg) + 1);
-       b_debug_list("expand_vars_to_list[b]", output, n);
-//TESTME
-       if (output->length - 1 == b_get_last_ptr(output, n)) { /* expansion is empty */
-               if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
-                       n--;
-                       /* allow to reuse list[n] later without re-growth */
-                       output->has_empty_slot = 1;
-               }
+       if (arg[0]) {
+               o_debug_list("expand_vars_to_list[a]", output, n);
+               o_addQstr(output, arg, strlen(arg) + 1);
+               o_debug_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. */
+       ) {
+               n--;
+               /* allow to reuse list[n] later without re-growth */
+               output->has_empty_slot = 1;
+       } else {
+               o_addchr(output, '\0');
        }
-
        return n;
 }
 
@@ -2717,10 +2727,10 @@ static char **expand_variables(char **argv, char or_mask)
        v = argv;
        while (*v)
                n = expand_vars_to_list(&output, n, *v++, or_mask);
-       b_debug_list("expand_variables", &output, n);
+       o_debug_list("expand_variables", &output, n);
 
-       /* output.data (malloced) gets returned in "list" */
-       list = b_finalize_list(&output, n);
+       /* output.data (malloced in one block) gets returned in "list" */
+       list = o_finalize_list(&output, n);
 
 #ifdef DEBUG_EXPAND
        {
@@ -2736,9 +2746,27 @@ static char **expand_variables(char **argv, char or_mask)
 
 static char **expand_strvec_to_strvec(char **argv)
 {
-       return expand_variables(argv, 0);
+       char **exp;
+       char **res = NULL;
+
+       debug_print_strings("expand_strvec_to_strvec: pre expand", argv);
+       exp = argv = expand_variables(argv, 0);
+       debug_print_strings("expand_strvec_to_strvec: post expand", argv);
+       while (*argv) {
+               int r = xglob(&res, *argv);
+               if (r)
+                       bb_error_msg("xglob returned %d on '%s'", r, *argv);
+//TODO: testcase for bad glob pattern behavior
+               argv++;
+       }
+       free(exp);
+       debug_print_strings("expand_strvec_to_strvec: res", res);
+       return res;
 }
 
+/* used for expansion of right hand of assignments */
+/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
+ * "v=/bin/c*" */
 static char *expand_string_to_string(const char *str)
 {
        char *argv[2], **list;
@@ -2755,6 +2783,7 @@ static char *expand_string_to_string(const char *str)
        return (char*)list;
 }
 
+/* used for eval */
 static char* expand_strvec_to_string(char **argv)
 {
        char **list;
@@ -2931,7 +2960,8 @@ static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
 
        /* Check for a '2>&1' type redirect */
        redir->dup = redirect_dup_num(input);
-       if (redir->dup == -2) return 1;  /* syntax error */
+       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"
@@ -2951,10 +2981,7 @@ static struct pipe *new_pipe(void)
 {
        struct pipe *pi;
        pi = xzalloc(sizeof(struct pipe));
-       /*pi->num_progs = 0;*/
-       /*pi->progs = NULL;*/
-       /*pi->next = NULL;*/
-       /*pi->followup = 0;  invalid */
+       /*pi->followup = 0; - deliberately invalid value */
        if (RES_NONE)
                pi->res_word = RES_NONE;
        return pi;
@@ -2962,29 +2989,48 @@ static struct pipe *new_pipe(void)
 
 static void initialize_context(struct p_context *ctx)
 {
-       ctx->child = NULL;
+       memset(ctx, 0, sizeof(*ctx));
        ctx->pipe = ctx->list_head = new_pipe();
-       ctx->pending_redirect = NULL;
-       ctx->res_w = RES_NONE;
-       //only ctx->parse_type is not touched... is this intentional?
-       ctx->old_flag = 0;
-       ctx->stack = NULL;
-       done_command(ctx);   /* creates the memory for working child */
+       /* Create the memory for child, roughly:
+        * ctx->pipe->progs = new struct child_prog;
+        * ctx->pipe->progs[0].family = ctx->pipe;
+        * ctx->child = &ctx->pipe->progs[0];
+        */
+       done_command(ctx);
 }
 
-/* normal return is 0
- * if a reserved word is found, and processed, return 1
- * should handle if, then, elif, else, fi, for, while, until, do, done.
+/* If a reserved word is found and processed, parse context is modified
+ * and 1 is returned.
+ * Handles if, then, elif, else, fi, for, while, until, do, done.
  * case, function, and select are obnoxious, save those for later.
  */
 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
-static int reserved_word(o_string *dest, struct p_context *ctx)
+static int reserved_word(const o_string *word, struct p_context *ctx)
 {
        struct reserved_combo {
                char literal[7];
-               unsigned char code;
+               unsigned char res;
                int flag;
        };
+       enum {
+               FLAG_END   = (1 << RES_NONE ),
+#if ENABLE_HUSH_IF
+               FLAG_IF    = (1 << RES_IF   ),
+               FLAG_THEN  = (1 << RES_THEN ),
+               FLAG_ELIF  = (1 << RES_ELIF ),
+               FLAG_ELSE  = (1 << RES_ELSE ),
+               FLAG_FI    = (1 << RES_FI   ),
+#endif
+#if ENABLE_HUSH_LOOPS
+               FLAG_FOR   = (1 << RES_FOR  ),
+               FLAG_WHILE = (1 << RES_WHILE),
+               FLAG_UNTIL = (1 << RES_UNTIL),
+               FLAG_DO    = (1 << RES_DO   ),
+               FLAG_DONE  = (1 << RES_DONE ),
+               FLAG_IN    = (1 << RES_IN   ),
+#endif
+               FLAG_START = (1 << RES_XXXX ),
+       };
        /* Mostly a list of accepted follow-up reserved words.
         * FLAG_END means we are done with the sequence, and are ready
         * to turn the compound list into a command.
@@ -2992,6 +3038,7 @@ static int reserved_word(o_string *dest, struct p_context *ctx)
         */
        static const struct reserved_combo reserved_list[] = {
 #if ENABLE_HUSH_IF
+               { "!",     RES_NONE,  0 },
                { "if",    RES_IF,    FLAG_THEN | FLAG_START },
                { "then",  RES_THEN,  FLAG_ELIF | FLAG_ELSE | FLAG_FI },
                { "elif",  RES_ELIF,  FLAG_THEN },
@@ -2999,9 +3046,9 @@ static int reserved_word(o_string *dest, struct p_context *ctx)
                { "fi",    RES_FI,    FLAG_END  },
 #endif
 #if ENABLE_HUSH_LOOPS
-               { "for",   RES_FOR,   FLAG_IN   | FLAG_START },
-               { "while", RES_WHILE, FLAG_DO   | FLAG_START },
-               { "until", RES_UNTIL, FLAG_DO   | FLAG_START },
+               { "for",   RES_FOR,   FLAG_IN | FLAG_START },
+               { "while", RES_WHILE, FLAG_DO | FLAG_START },
+               { "until", RES_UNTIL, FLAG_DO | FLAG_START },
                { "in",    RES_IN,    FLAG_DO   },
                { "do",    RES_DO,    FLAG_DONE },
                { "done",  RES_DONE,  FLAG_END  }
@@ -3011,9 +3058,23 @@ static int reserved_word(o_string *dest, struct p_context *ctx)
        const struct reserved_combo *r;
 
        for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
-               if (strcmp(dest->data, r->literal) != 0)
+               if (strcmp(word->data, r->literal) != 0)
                        continue;
-               debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
+               debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
+               if (r->flag == 0) { /* '!' */
+                       if (ctx->res_w == RES_IN) {
+                               /* 'for a in ! a b c; ...' - ! isn't a keyword here */
+                               break;
+                       }
+                       if (ctx->res_w == RES_FOR /* example: 'for ! a' */
+                        || ctx->ctx_inverted /* bash doesn't accept '! ! true' */
+                       ) {
+                               syntax(NULL);
+                               ctx->res_w = RES_SNTX;
+                       }
+                       ctx->ctx_inverted = 1;
+                       return 1;
+               }
                if (r->flag & FLAG_START) {
                        struct p_context *new;
                        debug_printf("push stack\n");
@@ -3021,7 +3082,6 @@ static int reserved_word(o_string *dest, struct p_context *ctx)
                        if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
                                syntax("malformed for"); /* example: 'for if' */
                                ctx->res_w = RES_SNTX;
-                               b_reset(dest);
                                return 1;
                        }
 #endif
@@ -3029,13 +3089,12 @@ static int reserved_word(o_string *dest, struct p_context *ctx)
                        *new = *ctx;   /* physical copy */
                        initialize_context(ctx);
                        ctx->stack = new;
-               } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
+               } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->res))) {
                        syntax(NULL);
                        ctx->res_w = RES_SNTX;
-                       b_reset(dest);
                        return 1;
                }
-               ctx->res_w = r->code;
+               ctx->res_w = r->res;
                ctx->old_flag = r->flag;
                if (ctx->old_flag & FLAG_END) {
                        struct p_context *old;
@@ -3047,52 +3106,52 @@ static int reserved_word(o_string *dest, struct p_context *ctx)
                        *ctx = *old;   /* physical copy */
                        free(old);
                }
-               b_reset(dest);
                return 1;
        }
        return 0;
 }
 #else
-#define reserved_word(dest, ctx) ((int)0)
+#define reserved_word(word, ctx) ((int)0)
 #endif
 
-/* Normal return is 0.
+/* Word is complete, look at it and update parsing context.
+ * Normal return is 0.
  * Syntax or xglob errors return 1. */
-static int done_word(o_string *dest, struct p_context *ctx)
+static int done_word(o_string *word, struct p_context *ctx)
 {
        struct child_prog *child = ctx->child;
        char ***glob_target;
-       int gr;
 
-       debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
-       if (dest->length == 0 && !dest->nonnull) {
+       debug_printf_parse("done_word entered: '%s' %p\n", word->data, child);
+       if (word->length == 0 && !word->nonnull) {
                debug_printf_parse("done_word return 0: true null, ignored\n");
                return 0;
        }
        if (ctx->pending_redirect) {
                glob_target = &ctx->pending_redirect->glob_word;
        } else {
-               if (child->group) {
+               if (child->group) { /* TODO: example how to trigger? */
                        syntax(NULL);
                        debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
                        return 1;
                }
-               if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
-                       debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
-                       if (reserved_word(dest, ctx)) {
+               if (!child->argv) {
+                       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->res_w == RES_SNTX));
                                return (ctx->res_w == RES_SNTX);
                        }
                }
                glob_target = &child->argv;
        }
-       gr = xglob(dest, glob_target);
-       if (gr != 0) {
-               debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
-               return 1;
+
+       if (word->length || word->nonnull) {
+               *glob_target = add_string_to_strings(*glob_target, xstrdup(word->data));
+               debug_print_strings("glob_target appended", *glob_target);
        }
 
-       b_reset(dest);
+       o_reset(word);
        if (ctx->pending_redirect) {
                /* NB: don't free_strings(ctx->pending_redirect->glob_word) here */
                if (ctx->pending_redirect->glob_word
@@ -3108,8 +3167,11 @@ static int done_word(o_string *dest, struct p_context *ctx)
                ctx->pending_redirect = NULL;
        }
 #if ENABLE_HUSH_LOOPS
-       if (ctx->res_w == RES_FOR) {
-               done_word(dest, ctx);
+       if (ctx->res_w == RES_FOR) { /* comment? */
+//TESTING
+//looks like (word->length == 0 && !word->nonnull) is true here, always
+//(due to o_reset). done_word would return at once. Why then?
+//             done_word(word, ctx);
                done_pipe(ctx, PIPE_SEQ);
        }
 #endif
@@ -3146,13 +3208,7 @@ static int done_command(struct p_context *ctx)
        child = &pi->progs[pi->num_progs];
 
        memset(child, 0, sizeof(*child));
-       /*child->redirects = NULL;*/
-       /*child->argv = NULL;*/
-       /*child->is_stopped = 0;*/
-       /*child->group = NULL;*/
        child->family = pi;
-       //sp: /*child->sp = 0;*/
-       //pt: child->parse_type = ctx->parse_type;
 
        ctx->child = child;
        /* but ctx->pipe and ctx->list_head remain unchanged */
@@ -3160,7 +3216,7 @@ static int done_command(struct p_context *ctx)
        return pi->num_progs; /* used only for 0/nonzero check */
 }
 
-static int done_pipe(struct p_context *ctx, pipe_style type)
+static void done_pipe(struct p_context *ctx, pipe_style type)
 {
        struct pipe *new_p;
        int not_null;
@@ -3169,6 +3225,8 @@ static int done_pipe(struct p_context *ctx, pipe_style type)
        not_null = done_command(ctx);  /* implicit closure of previous command */
        ctx->pipe->followup = type;
        ctx->pipe->res_word = ctx->res_w;
+       ctx->pipe->pi_inverted = ctx->ctx_inverted;
+       ctx->ctx_inverted = 0;
        /* 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. */
@@ -3176,11 +3234,15 @@ static int done_pipe(struct p_context *ctx, pipe_style type)
                new_p = new_pipe();
                ctx->pipe->next = new_p;
                ctx->pipe = new_p;
-               ctx->child = NULL;
-               done_command(ctx);  /* set up new pipe to accept commands */
+               ctx->child = NULL; /* needed! */
+               /* Create the memory for child, roughly:
+                * ctx->pipe->progs = new struct child_prog;
+                * ctx->pipe->progs[0].family = ctx->pipe;
+                * ctx->child = &ctx->pipe->progs[0];
+                */
+               done_command(ctx);
        }
-       debug_printf_parse("done_pipe return 0\n");
-       return 0;
+       debug_printf_parse("done_pipe return\n");
 }
 
 /* peek ahead in the in_str to find out if we have a "&n" construct,
@@ -3190,20 +3252,20 @@ static int done_pipe(struct p_context *ctx, pipe_style type)
 static int redirect_dup_num(struct in_str *input)
 {
        int ch, d = 0, ok = 0;
-       ch = b_peek(input);
+       ch = i_peek(input);
        if (ch != '&') return -1;
 
-       b_getch(input);  /* get the & */
-       ch = b_peek(input);
+       i_getch(input);  /* get the & */
+       ch = i_peek(input);
        if (ch == '-') {
-               b_getch(input);
+               i_getch(input);
                return -3;  /* "-" represents "close me" */
        }
        while (isdigit(ch)) {
                d = d*10 + (ch-'0');
                ok = 1;
-               b_getch(input);
-               ch = b_peek(input);
+               i_getch(input);
+               ch = i_peek(input);
        }
        if (ok) return d;
 
@@ -3235,7 +3297,7 @@ static int redirect_opt_num(o_string *o)
        }
        /* reuse num (and save an int) */
        num = atoi(o->data);
-       b_reset(o);
+       o_reset(o);
        return num;
 }
 
@@ -3285,7 +3347,6 @@ static FILE *generate_stream_from_list(struct pipe *head)
 
 /* Return code is exit status of the process that is run. */
 static int process_command_subs(o_string *dest,
-               /*struct p_context *ctx,*/
                struct in_str *input,
                const char *subst_end)
 {
@@ -3303,7 +3364,7 @@ static int process_command_subs(o_string *dest,
                return retcode;  /* syntax error or EOF */
        done_word(&result, &inner);
        done_pipe(&inner, PIPE_SEQ);
-       b_free(&result);
+       o_free(&result);
 
        p = generate_stream_from_list(inner.list_head);
        if (p == NULL)
@@ -3313,16 +3374,21 @@ static int process_command_subs(o_string *dest,
 
        /* now send results of command back into original context */
        eol_cnt = 0;
-       while ((ch = b_getch(&pipe_str)) != EOF) {
+       while ((ch = i_getch(&pipe_str)) != EOF) {
                if (ch == '\n') {
                        eol_cnt++;
                        continue;
                }
                while (eol_cnt) {
-                       b_addqchr(dest, '\n', dest->o_quote);
+                       o_addQchr(dest, '\n');
                        eol_cnt--;
                }
-               b_addqchr(dest, ch, dest->o_quote);
+               /* Even unquoted `echo '\'` results in two backslashes
+                * (which are converted into one by globbing later) */
+               if (!dest->o_quote && ch == '\\') {
+                       o_addchr(dest, ch);
+               }
+               o_addQchr(dest, ch);
        }
 
        debug_printf("done reading from pipe, pclose()ing\n");
@@ -3359,11 +3425,11 @@ static int parse_group(o_string *dest, struct p_context *ctx,
                child->subshell = 1;
        }
        rcode = parse_stream(dest, &sub, input, endch);
-//vda: err chk?
-       done_word(dest, &sub); /* finish off the final word in the subcontext */
-       done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
-       child->group = sub.list_head;
-
+       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 */
+               child->group = sub.list_head;
+       }
        debug_printf_parse("parse_group return %d\n", rcode);
        return rcode;
        /* child remains "open", available for possible redirects */
@@ -3386,34 +3452,34 @@ static void add_till_backquote(o_string *dest, struct in_str *input);
 static void add_till_single_quote(o_string *dest, struct in_str *input)
 {
        while (1) {
-               int ch = b_getch(input);
+               int ch = i_getch(input);
                if (ch == EOF)
                        break;
                if (ch == '\'')
                        break;
-               b_addchr(dest, ch);
+               o_addchr(dest, ch);
        }
 }
 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
 static void add_till_double_quote(o_string *dest, struct in_str *input)
 {
        while (1) {
-               int ch = b_getch(input);
+               int ch = i_getch(input);
                if (ch == '"')
                        break;
                if (ch == '\\') {  /* \x. Copy both chars. */
-                       b_addchr(dest, ch);
-                       ch = b_getch(input);
+                       o_addchr(dest, ch);
+                       ch = i_getch(input);
                }
                if (ch == EOF)
                        break;
-               b_addchr(dest, ch);
+               o_addchr(dest, ch);
                if (ch == '`') {
                        add_till_backquote(dest, input);
-                       b_addchr(dest, ch);
+                       o_addchr(dest, ch);
                        continue;
                }
-//             if (ch == '$') ...
+               //if (ch == '$') ...
        }
 }
 /* Process `cmd` - copy contents until "`" is seen. Complicated by
@@ -3433,19 +3499,18 @@ static void add_till_double_quote(o_string *dest, struct in_str *input)
 static void add_till_backquote(o_string *dest, struct in_str *input)
 {
        while (1) {
-               int ch = b_getch(input);
-//bb_error_msg("ADD '%c'", ch);
+               int ch = i_getch(input);
                if (ch == '`')
                        break;
                if (ch == '\\') {  /* \x. Copy both chars unless it is \` */
-                       int ch2 = b_getch(input);
+                       int ch2 = i_getch(input);
                        if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
-                               b_addchr(dest, ch);
+                               o_addchr(dest, ch);
                        ch = ch2;
                }
                if (ch == EOF)
                        break;
-               b_addchr(dest, ch);
+               o_addchr(dest, ch);
        }
 }
 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
@@ -3464,7 +3529,7 @@ static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
 {
        int count = 0;
        while (1) {
-               int ch = b_getch(input);
+               int ch = i_getch(input);
                if (ch == EOF)
                        break;
                if (ch == '(')
@@ -3472,51 +3537,54 @@ static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
                if (ch == ')')
                        if (--count < 0)
                                break;
-               b_addchr(dest, ch);
+               o_addchr(dest, ch);
                if (ch == '\'') {
                        add_till_single_quote(dest, input);
-                       b_addchr(dest, ch);
+                       o_addchr(dest, ch);
                        continue;
                }
                if (ch == '"') {
                        add_till_double_quote(dest, input);
-                       b_addchr(dest, ch);
+                       o_addchr(dest, ch);
+                       continue;
+               }
+               if (ch == '\\') { /* \x. Copy verbatim. Important for  \(, \) */
+                       ch = i_getch(input);
+                       if (ch == EOF)
+                               break;
+                       o_addchr(dest, ch);
                        continue;
                }
        }
 }
 #endif /* ENABLE_HUSH_TICK */
 
-//FIXME: remove ctx and sp
-
 /* return code: 0 for OK, 1 for syntax error */
-static int handle_dollar(o_string *dest, /*struct p_context *ctx,*/ struct in_str *input)
+static int handle_dollar(o_string *dest, struct in_str *input)
 {
-       int ch = b_peek(input);  /* first character after the $ */
+       int ch = i_peek(input);  /* first character after the $ */
        unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
 
        debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
        if (isalpha(ch)) {
-               b_addchr(dest, SPECIAL_VAR_SYMBOL);
-               //sp: ctx->child->sp++;
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
                while (1) {
                        debug_printf_parse(": '%c'\n", ch);
-                       b_getch(input);
-                       b_addchr(dest, ch | quote_mask);
+                       i_getch(input);
+                       o_addchr(dest, ch | quote_mask);
                        quote_mask = 0;
-                       ch = b_peek(input);
+                       ch = i_peek(input);
                        if (!isalnum(ch) && ch != '_')
                                break;
                }
-               b_addchr(dest, SPECIAL_VAR_SYMBOL);
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
        } else if (isdigit(ch)) {
  make_one_char_var:
-               b_addchr(dest, SPECIAL_VAR_SYMBOL);
-               //sp: ctx->child->sp++;
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
                debug_printf_parse(": '%c'\n", ch);
-               b_getch(input);
-               b_addchr(dest, ch | quote_mask);
-               b_addchr(dest, SPECIAL_VAR_SYMBOL);
+               i_getch(input);
+               o_addchr(dest, ch | quote_mask);
+               o_addchr(dest, SPECIAL_VAR_SYMBOL);
        } else switch (ch) {
                case '$': /* pid */
                case '!': /* last bg pid */
@@ -3526,12 +3594,11 @@ static int handle_dollar(o_string *dest, /*struct p_context *ctx,*/ struct in_st
                case '@': /* args */
                        goto make_one_char_var;
                case '{':
-                       b_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       //sp: ctx->child->sp++;
-                       b_getch(input);
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       i_getch(input);
                        /* XXX maybe someone will try to escape the '}' */
                        while (1) {
-                               ch = b_getch(input);
+                               ch = i_getch(input);
                                if (ch == '}')
                                        break;
                                if (!isalnum(ch) && ch != '_') {
@@ -3540,19 +3607,22 @@ static int handle_dollar(o_string *dest, /*struct p_context *ctx,*/ struct in_st
                                        return 1;
                                }
                                debug_printf_parse(": '%c'\n", ch);
-                               b_addchr(dest, ch | quote_mask);
+                               o_addchr(dest, ch | quote_mask);
                                quote_mask = 0;
                        }
-                       b_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
                        break;
 #if ENABLE_HUSH_TICK
-               case '(':
-                       b_getch(input);
-                       b_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       b_addchr(dest, quote_mask | '`');
+               case '(': {
+                       //int pos = dest->length;
+                       i_getch(input);
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       o_addchr(dest, quote_mask | '`');
                        add_till_closing_curly_brace(dest, input);
-                       b_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       //bb_error_msg("RES '%s'", dest->data + pos);
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
                        break;
+               }
 #endif
                case '-':
                case '_':
@@ -3561,7 +3631,7 @@ static int handle_dollar(o_string *dest, /*struct p_context *ctx,*/ struct in_st
                        return 1;
                        break;
                default:
-                       b_addqchr(dest, '$', dest->o_quote);
+                       o_addQchr(dest, '$');
        }
        debug_printf_parse("handle_dollar return 0\n");
        return 0;
@@ -3585,11 +3655,11 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
        while (1) {
                m = CHAR_IFS;
                next = '\0';
-               ch = b_getch(input);
+               ch = i_getch(input);
                if (ch != EOF) {
                        m = charmap[ch];
                        if (ch != '\n')
-                               next = b_peek(input);
+                               next = i_peek(input);
                }
                debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
                                                ch, ch, m, dest->o_quote);
@@ -3601,7 +3671,7 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                                debug_printf_parse("parse_stream return 1: unterminated \"\n");
                                return 1;
                        }
-                       b_addqchr(dest, ch, dest->o_quote);
+                       o_addQchr(dest, ch);
                        continue;
                }
                if (m == CHAR_IFS) {
@@ -3618,11 +3688,19 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                                done_pipe(ctx, PIPE_SEQ);
                        }
                }
-               if ((end_trigger && strchr(end_trigger, ch))
-                && !dest->o_quote && ctx->res_w == RES_NONE
-               ) {
-                       debug_printf_parse("parse_stream return 0: end_trigger char found\n");
-                       return 0;
+               if (end_trigger) {
+                       if (!dest->o_quote && strchr(end_trigger, ch)) {
+                               /* Special case: (...word) makes last word terminate,
+                                * as if ';' is seen */
+                               if (ch == ')') {
+                                       done_word(dest, ctx);
+                                       done_pipe(ctx, PIPE_SEQ);
+                               }
+                               if (ctx->res_w == RES_NONE) {
+                                       debug_printf_parse("parse_stream return 0: end_trigger char found\n");
+                                       return 0;
+                               }
+                       }
                }
                if (m == CHAR_IFS)
                        continue;
@@ -3630,13 +3708,13 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                case '#':
                        if (dest->length == 0 && !dest->o_quote) {
                                while (1) {
-                                       ch = b_peek(input);
+                                       ch = i_peek(input);
                                        if (ch == EOF || ch == '\n')
                                                break;
-                                       b_getch(input);
+                                       i_getch(input);
                                }
                        } else {
-                               b_addqchr(dest, ch, dest->o_quote);
+                               o_addQchr(dest, ch);
                        }
                        break;
                case '\\':
@@ -3645,11 +3723,28 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                                debug_printf_parse("parse_stream return 1: \\<eof>\n");
                                return 1;
                        }
-                       b_addqchr(dest, '\\', dest->o_quote);
-                       b_addqchr(dest, b_getch(input), dest->o_quote);
+                       /* 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 (dest->o_quote) {
+                               if (strchr("$`\"\\", next) != NULL) {
+                                       o_addqchr(dest, i_getch(input));
+                               } else {
+                                       o_addqchr(dest, '\\');
+                               }
+                       } else {
+                               o_addchr(dest, '\\');
+                               o_addchr(dest, i_getch(input));
+                       }
                        break;
                case '$':
-                       if (handle_dollar(dest, /*ctx,*/ input) != 0) {
+                       if (handle_dollar(dest, input) != 0) {
                                debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
                                return 1;
                        }
@@ -3657,15 +3752,15 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                case '\'':
                        dest->nonnull = 1;
                        while (1) {
-                               ch = b_getch(input);
-                               if (ch == EOF || ch == '\'')
+                               ch = i_getch(input);
+                               if (ch == EOF) {
+                                       syntax("unterminated '");
+                                       debug_printf_parse("parse_stream return 1: unterminated '\n");
+                                       return 1;
+                               }
+                               if (ch == '\'')
                                        break;
-                               b_addchr(dest, ch);
-                       }
-                       if (ch == EOF) {
-                               syntax("unterminated '");
-                               debug_printf_parse("parse_stream return 1: unterminated '\n");
-                               return 1;
+                               o_addqchr(dest, ch);
                        }
                        break;
                case '"':
@@ -3675,10 +3770,10 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
 #if ENABLE_HUSH_TICK
                case '`': {
                        //int pos = dest->length;
-                       b_addchr(dest, SPECIAL_VAR_SYMBOL);
-                       b_addchr(dest, dest->o_quote ? 0x80 | '`' : '`');
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       o_addchr(dest, dest->o_quote ? 0x80 | '`' : '`');
                        add_till_backquote(dest, input);
-                       b_addchr(dest, SPECIAL_VAR_SYMBOL);
+                       o_addchr(dest, SPECIAL_VAR_SYMBOL);
                        //bb_error_msg("RES '%s'", dest->data + pos);
                        break;
                }
@@ -3689,7 +3784,7 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                        redir_style = REDIRECT_OVERWRITE;
                        if (next == '>') {
                                redir_style = REDIRECT_APPEND;
-                               b_getch(input);
+                               i_getch(input);
                        }
 #if 0
                        else if (next == '(') {
@@ -3706,10 +3801,10 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                        redir_style = REDIRECT_INPUT;
                        if (next == '<') {
                                redir_style = REDIRECT_HEREIS;
-                               b_getch(input);
+                               i_getch(input);
                        } else if (next == '>') {
                                redir_style = REDIRECT_IO;
-                               b_getch(input);
+                               i_getch(input);
                        }
 #if 0
                        else if (next == '(') {
@@ -3727,7 +3822,7 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                case '&':
                        done_word(dest, ctx);
                        if (next == '&') {
-                               b_getch(input);
+                               i_getch(input);
                                done_pipe(ctx, PIPE_AND);
                        } else {
                                done_pipe(ctx, PIPE_BG);
@@ -3736,7 +3831,7 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                case '|':
                        done_word(dest, ctx);
                        if (next == '|') {
-                               b_getch(input);
+                               i_getch(input);
                                done_pipe(ctx, PIPE_OR);
                        } else {
                                /* we could pick up a file descriptor choice here
@@ -3754,14 +3849,15 @@ static int parse_stream(o_string *dest, struct p_context *ctx,
                        break;
                case ')':
                case '}':
-                       syntax("unexpected }");   /* Proper use of this character is caught by end_trigger */
+                       /* proper use of this character is caught by end_trigger */
+                       syntax("unexpected } or )");
                        debug_printf_parse("parse_stream return 1: unexpected '}'\n");
                        return 1;
                default:
                        if (ENABLE_HUSH_DEBUG)
                                bb_error_msg_and_die("BUG: unexpected %c\n", ch);
                }
-       }
+       } /* while (1) */
        /* Complain if quote?  No, maybe we just finished a command substitution
         * that was quoted.  Example:
         * $ echo "`cat foo` plus more"
@@ -3811,12 +3907,10 @@ static int parse_and_run_stream(struct in_str *inp, int parse_flag)
        struct p_context ctx;
        o_string temp = NULL_O_STRING;
        int rcode;
+
        do {
-               ctx.parse_type = parse_flag;
                initialize_context(&ctx);
                update_charmap();
-               if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
-                       set_in_charmap(";$&|", CHAR_ORDINARY);
 #if ENABLE_HUSH_INTERACTIVE
                inp->promptmode = 0; /* PS1 */
 #endif
@@ -3834,17 +3928,21 @@ static int parse_and_run_stream(struct in_str *inp, int parse_flag)
                        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 (ctx.old_flag != 0) {
                                free(ctx.stack);
-                               b_reset(&temp);
+                               o_reset(&temp);
                        }
                        temp.nonnull = 0;
                        temp.o_quote = 0;
-                       inp->p = NULL;
                        free_pipe_list(ctx.list_head, /* indent: */ 0);
+                       /* Discard all unprocessed line input, force prompt on */
+                       inp->p = NULL;
+                       inp->promptme = 1;
                }
-               b_free(&temp);
-       } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));   /* loop on syntax errors, return on EOF */
+               o_free(&temp);
+               /* loop on syntax errors, return on EOF: */
+       } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
        return 0;
 }
 
@@ -3860,7 +3958,7 @@ static int parse_and_run_file(FILE *f)
        int rcode;
        struct in_str input;
        setup_file_in_str(&input, f);
-       rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
+       rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
        return rcode;
 }
 
@@ -3973,7 +4071,7 @@ int hush_main(int argc, char **argv)
                case 'c':
                        global_argv = argv + optind;
                        global_argc = argc - optind;
-                       opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
+                       opt = parse_and_run_string(optarg, 0 /* parse_flag */);
                        goto final_return;
                case 'i':
                        /* Well, we cannot just declare interactiveness,