pointless whitespace/comment fixes, no code changes
[oweals/busybox.git] / shell / hush.c
index 422fc63f650d720b949c1d5a827ca3f4b42f3c90..b6e49db99f9b5a13989359ac11af27966e24dcfe 100644 (file)
@@ -5,7 +5,7 @@
  * "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:
@@ -40,7 +40,6 @@
  * POSIX syntax not implemented:
  *      aliases
  *      <(list) and >(list) Process Substitution
- *      Functions
  *      Tilde Expansion
  *
  * Bash stuff (maybe optionally enable?):
@@ -60,7 +59,6 @@
  *      ^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))
- *      functions
  *
  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  */
@@ -68,7 +66,7 @@
 #include <glob.h>
 /* #include <dmalloc.h> */
 #if ENABLE_HUSH_CASE
-#include <fnmatch.h>
+# include <fnmatch.h>
 #endif
 #include "math.h"
 #include "match.h"
@@ -85,8 +83,6 @@
  * Keeping 1 for now even in released versions.
  */
 #define HUSH_DEBUG 1
-/* In progress... */
-#define ENABLE_HUSH_FUNCTIONS 0
 
 
 #if BUILD_AS_NOMMU
 
 #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__
+# 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
 
 /* If you comment out one of these below, it will be #defined later
 #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
-
-#ifndef debug_printf_list
-#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#ifndef debug_printf_subst
-#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#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
-#else
-#define DEBUG_CLEAN 0
-#endif
-
-#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
-
 #define ERR_PTR ((void*)(long)1)
 
 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
@@ -330,7 +256,7 @@ struct redir_struct {
        /* 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 (<<'dleim' syntax) ?
+        * 2: is heredoc quoted (<<'delim' syntax) ?
         */
 };
 typedef enum redir_type {
@@ -344,7 +270,8 @@ typedef enum redir_type {
 
        REDIRFD_CLOSE      = -3,
        REDIRFD_SYNTAX_ERR = -2,
-       REDIRFD_TO_FILE    = -1, /* otherwise, rd_fd if redirected to rd_dup */
+       REDIRFD_TO_FILE    = -1,
+       /* otherwise, rd_fd is redirected to rd_dup */
 
        HEREDOC_SKIPTABS = 1,
        HEREDOC_QUOTED   = 2,
@@ -356,29 +283,46 @@ struct command {
        int assignment_cnt;         /* how many argv[i] are assignments? */
        smallint is_stopped;        /* is the command currently running? */
        smallint grp_type;          /* GRP_xxx */
+#define GRP_NORMAL   0
+#define GRP_SUBSHELL 1
+#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
@@ -451,6 +395,18 @@ enum {
        BC_CONTINUE = 2,
 };
 
+#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
+};
+#endif
+
 
 /* "Globals" within this file */
 /* Sorted roughly by size (smaller offsets == smaller code) */
@@ -503,6 +459,9 @@ struct globals {
        const char *cwd;
        struct variable *top_var; /* = &G.shell_ver (set in main()) */
        struct variable shell_ver;
+#if ENABLE_HUSH_FUNCTIONS
+       struct function *top_func;
+#endif
        /* Signal and trap handling */
 //     unsigned count_SIGCHLD;
 //     unsigned handled_SIGCHLD;
@@ -513,6 +472,7 @@ struct globals {
        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
@@ -628,6 +588,84 @@ static const struct built_in_command bltins[] = {
 };
 
 
+/* 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)
+{
+       indent();
+       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.
  */
 #if LEAK_HUNTING
@@ -667,11 +705,12 @@ static void xxfree(void *ptr)
  * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  */
 #if HUSH_DEBUG < 2
-# define die_if_script(lineno, fmt...)      die_if_script(fmt)
-# define 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 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, ...)
@@ -701,12 +740,19 @@ 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)
@@ -714,18 +760,28 @@ 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 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
-# 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 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
 
 
@@ -1433,7 +1489,7 @@ 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->o_quoted = 0;
@@ -1590,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);
@@ -1600,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));
        }
 }
@@ -2219,8 +2279,11 @@ static char **expand_assignments(char **argv, int count)
 
 
 #if BB_MMU
-void re_execute_shell(const char *s, int is_heredoc); /* never called */
+/* 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;
@@ -2251,16 +2314,19 @@ static void reset_traps_to_defaults(void)
 
 #else /* !BB_MMU */
 
-static void re_execute_shell(const char *s, int is_heredoc) NORETURN;
-static void re_execute_shell(const char *s, int is_heredoc)
+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;
-       char **argv, **pp, **pp2;
+#if ENABLE_HUSH_FUNCTIONS
+       struct function *funcp;
+#endif
+       char **argv, **pp;
        unsigned cnt;
 
-       if (is_heredoc) {
+       if (!g_argv0) { /* heredoc */
                argv = heredoc_argv;
                argv[0] = (char *) G.argv0_for_re_execing;
                argv[1] = (char *) "-<";
@@ -2276,14 +2342,21 @@ static void re_execute_shell(const char *s, int is_heredoc)
                        , (unsigned) G.last_exitcode
                        USE_HUSH_LOOPS(, G.depth_of_loop)
                        );
-       /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
-        * 3:-c 4:<cmd> <argN...> 5:NULL
+       /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
+        * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
         */
-       cnt = 5 + G.global_argc;
+       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;
@@ -2298,7 +2371,13 @@ static void re_execute_shell(const char *s, int is_heredoc)
                        *pp++ = cur->varstr;
                }
        }
-//TODO: pass functions
+#if ENABLE_HUSH_FUNCTIONS
+       for (funcp = G.top_func; funcp; funcp = funcp->next) {
+               *pp++ = (char *) "-F";
+               *pp++ = funcp->name;
+               *pp++ = funcp->body_as_string;
+       }
+#endif
        /* We can pass activated traps here. Say, -Tnn:trap_string
         *
         * However, POSIX says that subshells reset signals with traps
@@ -2320,9 +2399,9 @@ static void re_execute_shell(const char *s, int is_heredoc)
         */
        *pp++ = (char *) "-c";
        *pp++ = (char *) s;
-       pp2 = G.global_argv;
-       while (*pp2)
-               *pp++ = *pp2++;
+       *pp++ = g_argv0;
+       while (*g_argv)
+               *pp++ = *g_argv++;
        /* *pp = NULL; - is already there */
        pp = environ;
 
@@ -2411,7 +2490,7 @@ static void setup_heredoc(struct redir_struct *redir)
                /* Delegate blocking writes to another process */
                disable_restore_tty_pgrp_on_exit();
                xmove_fd(pair.wr, STDOUT_FILENO);
-               re_execute_shell(heredoc, 1);
+               re_execute_shell(heredoc, NULL, NULL);
 #endif
        }
        /* parent */
@@ -2497,14 +2576,10 @@ static void restore_redirects(int squirrel[])
 }
 
 
-#if !DEBUG_CLEAN
-#define free_pipe_list(head, indent) free_pipe_list(head)
-#define free_pipe(pi, indent)        free_pipe(pi)
-#endif
-static void 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 void free_pipe(struct pipe *pi, int indent)
+static void free_pipe(struct pipe *pi)
 {
        char **p;
        struct command *command;
@@ -2513,33 +2588,40 @@ static void free_pipe(struct pipe *pi, int indent)
 
        if (pi->stopped_cmds > 0) /* why? */
                return;
-       debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
+       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;
                }
                /* not "else if": on syntax error, we may have both! */
                if (command->group) {
-                       debug_printf_clean("%s   begin group (grp_type:%d)\n",
-                                       indenter(indent), command->grp_type);
-                       free_pipe_list(command->group, indent+3);
-                       debug_printf_clean("%s   end group\n", indenter(indent));
+                       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);
+                       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);
@@ -2560,16 +2642,16 @@ static void free_pipe(struct pipe *pi, int indent)
 #endif
 }
 
-static void free_pipe_list(struct pipe *head, int indent)
+static void free_pipe_list(struct pipe *head)
 {
        struct pipe *pi, *next;
 
        for (pi = head; pi; pi = next) {
 #if HAS_KEYWORDS
-               debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
+               debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
 #endif
-               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);
@@ -2577,6 +2659,163 @@ static void free_pipe_list(struct pipe *head, int indent)
 }
 
 
+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
+                               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)
@@ -2619,6 +2858,11 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
 #endif
        }
 
+#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
@@ -2632,30 +2876,35 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
         */
        {
                int rcode;
-               const struct built_in_command *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);
-                               fflush(NULL);
-                               _exit(rcode);
-                       }
+               const struct built_in_command *x = find_builtin(argv[0]);
+               if (x) {
+                       rcode = x->function(argv);
+                       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
 
 #if ENABLE_FEATURE_SH_STANDALONE
        /* Check if the command matches any busybox applets */
-       if (strchr(argv[0], '/') == NULL) {
+       {
                int a = find_applet_by_name(argv[0]);
                if (a >= 0) {
-#if BB_MMU /* see above why on NOMMU it is not allowed */
+# 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]);
                                run_applet_no_and_exit(a, argv);
                        }
-#endif
+# endif
                        /* Re-exec ourselves */
                        debug_printf_exec("re-execing applet '%s'\n", argv[0]);
                        sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
@@ -2666,6 +2915,9 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
        }
 #endif
 
+#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);
@@ -2673,8 +2925,6 @@ static void pseudo_exec_argv(nommu_save_t *nommu_save,
        _exit(EXIT_FAILURE);
 }
 
-static int run_list(struct pipe *pi);
-
 /* Called after [v]fork() in run_pipe
  */
 static void pseudo_exec(nommu_save_t *nommu_save,
@@ -2705,7 +2955,9 @@ static void pseudo_exec(nommu_save_t *nommu_save,
                 * since this process is about to exit */
                _exit(rcode);
 #else
-               re_execute_shell(command->group_as_string, 0);
+               re_execute_shell(command->group_as_string,
+                               G.global_argv[0],
+                               G.global_argv + 1);
 #endif
        }
 
@@ -2811,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 */
@@ -3002,6 +3254,7 @@ static int run_pipe(struct pipe *pi)
        int rcode;
 
        debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
+       debug_enter();
 
        USE_HUSH_JOB(pi->pgrp = -1;)
        pi->stopped_cmds = 0;
@@ -3023,8 +3276,24 @@ static int run_pipe(struct pipe *pi)
        if (command->group) {
 #if ENABLE_HUSH_FUNCTIONS
                if (command->grp_type == GRP_FUNCTION) {
-                       /* func () { list } */
-                       bb_error_msg("here we ought to remember function definition, and go on");
+                       /* "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;
+
+                       debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
+                       debug_leave();
                        return EXIT_SUCCESS;
                }
 #endif
@@ -3034,16 +3303,22 @@ static int run_pipe(struct pipe *pi)
                if (setup_redirects(command, squirrel) == 0) {
                        debug_printf_exec(": run_list\n");
                        rcode = run_list(command->group) & 0xff;
-                       debug_printf_exec("run_pipe return %d\n", rcode);
                }
                restore_redirects(squirrel);
                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 ? 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;
 
@@ -3064,21 +3339,28 @@ static int run_pipe(struct pipe *pi)
                         * "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 + 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");
-                               rcode = setup_redirects(command, NULL);
-                               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,
@@ -3087,9 +3369,18 @@ static int run_pipe(struct pipe *pi)
                        if (rcode == 0) {
                                new_env = expand_assignments(argv, command->assignment_cnt);
                                old_env = putenv_all_and_save_old(new_env);
-                               debug_printf_exec(": builtin '%s' '%s'...\n",
+                               if (!funcp) {
+                                       debug_printf_exec(": builtin '%s' '%s'...\n",
                                                x->cmd, argv_expanded[1]);
-                               rcode = x->function(argv_expanded) & 0xff;
+                                       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:
@@ -3103,9 +3394,11 @@ static int run_pipe(struct pipe *pi)
  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)) {
@@ -3227,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;
 }
@@ -3341,6 +3636,7 @@ static int run_list(struct pipe *pi)
 #endif
 
        debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
+       debug_enter();
 
 #if ENABLE_HUSH_LOOPS
        /* Check syntax for "for" */
@@ -3350,6 +3646,7 @@ static int run_list(struct pipe *pi)
                /* current word is FOR or IN (BOLD in comments below) */
                if (cpipe->next == NULL) {
                        syntax_error("malformed for");
+                       debug_leave();
                        debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
                        return 1;
                }
@@ -3361,6 +3658,7 @@ static int run_list(struct pipe *pi)
                 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
                ) {
                        syntax_error("malformed for");
+                       debug_leave();
                        debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
                        return 1;
                }
@@ -3578,7 +3876,7 @@ static int run_list(struct pipe *pi)
                                /* 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 exitcode %d\n", rcode);
+                               debug_printf_exec(": builtin/func exitcode %d\n", rcode);
                                check_and_run_traps(0);
 #if ENABLE_HUSH_LOOPS
                                /* Was it "break" or "continue"? */
@@ -3674,7 +3972,6 @@ static int run_list(struct pipe *pi)
 ////           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--;
@@ -3683,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;
 }
 
@@ -3698,7 +3997,7 @@ static int run_and_free_list(struct pipe *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;
 }
@@ -3770,11 +4069,15 @@ static void done_pipe(struct parse_context *ctx, pipe_style type)
         * RES_NONE case is for "for a in; do ..." (empty IN set)
         * and other cases to work. */
        if (not_null
-#if HAS_KEYWORDS
+#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
        ) {
@@ -4043,7 +4346,7 @@ static int done_word(o_string *word, struct parse_context *ctx)
                ) {
                        debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
                        if (reserved_word(word, ctx)) {
-                               o_reset(word);
+                               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);
@@ -4073,6 +4376,10 @@ 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);
        }
 
@@ -4081,7 +4388,7 @@ static int done_word(o_string *word, struct parse_context *ctx)
                if (word->o_quoted
                 || !is_well_formed_var_name(command->argv[0], '\0')
                ) {
-                       /* bash says "not a valid identifier" */
+                       /* bash says just "not a valid identifier" */
                        syntax_error("not a valid identifier in for");
                        return 1;
                }
@@ -4099,7 +4406,7 @@ static int done_word(o_string *word, struct parse_context *ctx)
        }
 #endif
 
-       o_reset(word);
+       o_reset_to_empty_unquoted(word);
 
        debug_printf_parse("done_word return 0\n");
        return 0;
@@ -4249,7 +4556,7 @@ static int redirect_opt_num(o_string *o)
        num = bb_strtou(o->data, NULL, 10);
        if (errno || num < 0)
                return -1;
-       o_reset(o);
+       o_reset_to_empty_unquoted(o);
        return num;
 }
 
@@ -4345,15 +4652,6 @@ static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_
 }
 
 
-#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);
-
 #if ENABLE_HUSH_TICK
 static FILE *generate_stream_from_string(const char *s)
 {
@@ -4390,7 +4688,9 @@ static FILE *generate_stream_from_string(const char *s)
         * huge=`cat BIG` # was blocking here forever
         * echo OK
         */
-               re_execute_shell(s, 0);
+               re_execute_shell(s,
+                               G.global_argv[0],
+                               G.global_argv + 1);
 #endif
        }
 
@@ -4454,28 +4754,55 @@ static int parse_group(o_string *dest, struct parse_context *ctx,
 
        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->o_quoted /* ""(... */
+       if (command->argv /* word [word]{... */
+        || dest->length /* word{... */
+        || dest->o_quoted /* ""{... */
        ) {
                syntax_error(NULL);
                debug_printf_parse("parse_group return 1: "
                        "syntax error, groups and arglists don't mix\n");
                return 1;
        }
+
+#if ENABLE_HUSH_FUNCTIONS
+ skip:
+#endif
        endch = '}';
        if (ch == '(') {
                endch = ')';
                command->grp_type = GRP_SUBSHELL;
        }
+
        {
 #if !BB_MMU
                char *as_string = NULL;
@@ -4510,40 +4837,39 @@ static int parse_group(o_string *dest, struct parse_context *ctx,
 
 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
 /* Subroutines for copying $(...) and `...` things */
-static int add_till_backquote(o_string *dest, struct in_str *input);
+static void add_till_backquote(o_string *dest, struct in_str *input);
 /* '...' */
-static int add_till_single_quote(o_string *dest, struct in_str *input)
+static void add_till_single_quote(o_string *dest, struct in_str *input)
 {
        while (1) {
                int ch = i_getch(input);
                if (ch == EOF) {
                        syntax_error_unterm_ch('\'');
-                       return 1;
+                       /*xfunc_die(); - redundant */
                }
                if (ch == '\'')
-                       return 0;
+                       return;
                o_addchr(dest, ch);
        }
 }
 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
-static int add_till_double_quote(o_string *dest, struct in_str *input)
+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('"');
-                       return 1;
+                       /*xfunc_die(); - redundant */
                }
                if (ch == '"')
-                       return 0;
+                       return;
                if (ch == '\\') {  /* \x. Copy both chars. */
                        o_addchr(dest, ch);
                        ch = i_getch(input);
                }
                o_addchr(dest, ch);
                if (ch == '`') {
-                       if (add_till_backquote(dest, input))
-                               return 1;
+                       add_till_backquote(dest, input);
                        o_addchr(dest, ch);
                        continue;
                }
@@ -4564,22 +4890,22 @@ static int add_till_double_quote(o_string *dest, struct in_str *input)
  * Example                               Output
  * echo `echo '\'TEST\`echo ZZ\`BEST`    \TESTZZBEST
  */
-static int add_till_backquote(o_string *dest, struct in_str *input)
+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('`');
-                       return 1;
+                       /*xfunc_die(); - redundant */
                }
                if (ch == '`')
-                       return 0;
+                       return;
                if (ch == '\\') {
                        /* \x. Copy both chars unless it is \` */
                        int ch2 = i_getch(input);
                        if (ch2 == EOF) {
                                syntax_error_unterm_ch('`');
-                               return 1;
+                               /*xfunc_die(); - redundant */
                        }
                        if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
                                o_addchr(dest, ch);
@@ -4600,14 +4926,14 @@ static int add_till_backquote(o_string *dest, struct in_str *input)
  * echo $(echo 'TEST)' BEST)            TEST) BEST
  * echo $(echo \(\(TEST\) BEST)         ((TEST) BEST
  */
-static int add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
+static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
 {
        int count = 0;
        while (1) {
                int ch = i_getch(input);
                if (ch == EOF) {
                        syntax_error_unterm_ch(')');
-                       return 1;
+                       /*xfunc_die(); - redundant */
                }
                if (ch == '(')
                        count++;
@@ -4623,14 +4949,12 @@ static int add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl
                }
                o_addchr(dest, ch);
                if (ch == '\'') {
-                       if (add_till_single_quote(dest, input))
-                               return 1;
+                       add_till_single_quote(dest, input);
                        o_addchr(dest, ch);
                        continue;
                }
                if (ch == '"') {
-                       if (add_till_double_quote(dest, input))
-                               return 1;
+                       add_till_double_quote(dest, input);
                        o_addchr(dest, ch);
                        continue;
                }
@@ -4639,13 +4963,12 @@ static int add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl
                        ch = i_getch(input);
                        if (ch == EOF) {
                                syntax_error_unterm_ch(')');
-                               return 1;
+                               /*xfunc_die(); - redundant */
                        }
                        o_addchr(dest, ch);
                        continue;
                }
        }
-       return 0;
 }
 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
 
@@ -4786,8 +5109,7 @@ static int handle_dollar(o_string *as_string,
 #  if !BB_MMU
                        pos = dest->length;
 #  endif
-                       if (add_till_closing_paren(dest, input, true))
-                               return 1;
+                       add_till_closing_paren(dest, input, true);
 #  if !BB_MMU
                        if (as_string) {
                                o_addstr(as_string, dest->data + pos);
@@ -4805,8 +5127,7 @@ static int handle_dollar(o_string *as_string,
 #  if !BB_MMU
                pos = dest->length;
 #  endif
-               if (add_till_closing_paren(dest, input, false))
-                       return 1;
+               add_till_closing_paren(dest, input, false);
 #  if !BB_MMU
                if (as_string) {
                        o_addstr(as_string, dest->data + pos);
@@ -4862,8 +5183,7 @@ static int parse_stream_dquoted(o_string *as_string,
        /* note: can't move it above ch == dquote_end check! */
        if (ch == EOF) {
                syntax_error_unterm_ch('"');
-               debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
-               return 1;
+               /*xfunc_die(); - redundant */
        }
        next = '\0';
        if (ch != '\n') {
@@ -4872,11 +5192,9 @@ static int parse_stream_dquoted(o_string *as_string,
        debug_printf_parse(": ch=%c (%d) escape=%d\n",
                                        ch, ch, dest->o_escape);
        if (ch == '\\') {
-//TODO: check interactive behavior
                if (next == EOF) {
                        syntax_error("\\<eof>");
-                       debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
-                       return 1;
+                       xfunc_die();
                }
                /* bash:
                 * "The backslash retains its special meaning [in "..."]
@@ -4904,8 +5222,7 @@ static int parse_stream_dquoted(o_string *as_string,
                //int pos = dest->length;
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
                o_addchr(dest, 0x80 | '`');
-               if (add_till_backquote(dest, input))
-                       return 1;
+               add_till_backquote(dest, input);
                o_addchr(dest, SPECIAL_VAR_SYMBOL);
                //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
                goto again;
@@ -4945,6 +5262,7 @@ static struct pipe *parse_stream(char **pstring,
         */
        debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
                        end_trigger ? : 'X');
+       debug_enter();
 
        G.ifs = get_local_var_value("IFS");
        if (G.ifs == NULL)
@@ -4982,23 +5300,23 @@ static struct pipe *parse_stream(char **pstring,
 
                        if (heredoc_cnt) {
                                syntax_error_unterm_str("here document");
-                               goto parse_error;
+                               xfunc_die();
                        }
                        if (done_word(&dest, &ctx)) {
-                               goto parse_error;
+                               xfunc_die();
                        }
                        o_free(&dest);
                        done_pipe(&ctx, PIPE_SEQ);
                        pi = ctx.list_head;
                        /* If we got nothing... */
-// TODO: test script consisting of just "&"
+                       /* (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, 0);
+                               free_pipe_list(pi);
                                pi = NULL;
                        }
-                       debug_printf_parse("parse_stream return %p\n", pi);
 #if !BB_MMU
                        debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
                        if (pstring)
@@ -5006,6 +5324,8 @@ static struct pipe *parse_stream(char **pstring,
                        else
                                o_free_unsafe(&ctx.as_string);
 #endif
+                       debug_leave();
+                       debug_printf_parse("parse_stream return %p\n", pi);
                        return pi;
                }
                nommu_addchr(&ctx.as_string, ch);
@@ -5082,9 +5402,6 @@ static struct pipe *parse_stream(char **pstring,
                        if (!HAS_KEYWORDS
                         IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
                        ) {
-                               debug_printf_parse("parse_stream return %p: "
-                                               "end_trigger char found\n",
-                                               ctx.list_head);
                                o_free(&dest);
 #if !BB_MMU
                                debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
@@ -5093,6 +5410,10 @@ static struct pipe *parse_stream(char **pstring,
                                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;
                        }
                }
@@ -5182,7 +5503,7 @@ static struct pipe *parse_stream(char **pstring,
                case '\\':
                        if (next == EOF) {
                                syntax_error("\\<eof>");
-                               goto parse_error;
+                               xfunc_die();
                        }
                        o_addchr(&dest, '\\');
                        ch = i_getch(input);
@@ -5205,7 +5526,7 @@ static struct pipe *parse_stream(char **pstring,
                                ch = i_getch(input);
                                if (ch == EOF) {
                                        syntax_error_unterm_ch('\'');
-                                       goto parse_error;
+                                       /*xfunc_die(); - redundant */
                                }
                                nommu_addchr(&ctx.as_string, ch);
                                if (ch == '\'')
@@ -5232,8 +5553,7 @@ static struct pipe *parse_stream(char **pstring,
 #if !BB_MMU
                        pos = dest.length;
 #endif
-                       if (add_till_backquote(&dest, input))
-                               goto parse_error;
+                       add_till_backquote(&dest, input);
 #if !BB_MMU
                        o_addstr(&ctx.as_string, dest.data + pos);
                        o_addchr(&ctx.as_string, '`');
@@ -5313,28 +5633,6 @@ static struct pipe *parse_stream(char **pstring,
                        ) {
                                continue;
                        }
-#endif
-#if ENABLE_HUSH_FUNCTIONS
-                       if (dest.length != 0 /* not just () but word() */
-                        && dest.o_quoted == 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);
-//if !BB_MMU o_addchr(&ctx.as_string...
-                               do {
-//TODO: do it properly.
-                                       ch = i_getch(input);
-                               } while (ch == ' ' || ch == '\n');
-                               if (ch != '{') {
-                                       syntax_error("was expecting {");
-                                       goto parse_error;
-                               }
-                               ch = 'F'; /* magic value */
-                       }
 #endif
                case '{':
                        if (parse_group(&dest, &ctx, input, ch) != 0) {
@@ -5350,7 +5648,7 @@ static struct pipe *parse_stream(char **pstring,
                        /* 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_error("unexpected } or )");
+                       syntax_error_unexpected_ch(ch);
                        goto parse_error;
                default:
                        if (HUSH_DEBUG)
@@ -5381,7 +5679,7 @@ static struct pipe *parse_stream(char **pstring,
                        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, 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);
@@ -5402,6 +5700,7 @@ static struct pipe *parse_stream(char **pstring,
                        if (pstring)
                                *pstring = NULL;
 #endif
+                       debug_leave();
                        return ERR_PTR;
                }
                /* Discard cached input, force prompt */
@@ -5611,7 +5910,10 @@ int hush_main(int argc, char **argv)
        while (1) {
                opt = getopt(argc, argv, "c:xins"
 #if !BB_MMU
-                               "<:$:!:?:D:R:V:"
+                               "<:$:R:V:"
+# if ENABLE_HUSH_FUNCTIONS
+                               "F:"
+# endif
 #endif
                );
                if (opt <= 0)
@@ -5658,6 +5960,16 @@ int hush_main(int argc, char **argv)
                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':
@@ -5976,7 +6288,8 @@ static int builtin_cd(char **argv)
        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)
+                * bash says "bash: cd: HOME not set" and does nothing
+                * (exitcode 1)
                 */
                newdir = getenv("HOME") ? : "/";
        }
@@ -6024,14 +6337,42 @@ static int builtin_exit(char **argv)
 static int builtin_export(char **argv)
 {
        if (*++argv == NULL) {
-               // TODO:
-               // ash emits: export VAR='VAL'
-               // bash: declare -x VAR="VAL"
-               // (both also escape as needed (quotes, $, etc))
                char **e = environ;
-               if (e)
-                       while (*e)
+               if (e) {
+                       while (*e) {
+#if 0
                                puts(*e++);
+#else
+                               /* ash emits: export VAR='VAL'
+                                * bash: declare -x VAR="VAL"
+                                * we follow ash example */
+                               const char *s = *e++;
+                               const char *p = strchr(s, '=');
+
+                               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);
+               }
                return EXIT_SUCCESS;
        }
 
@@ -6254,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:
@@ -6401,11 +6737,11 @@ static int builtin_unset(char **argv)
                                ret = EXIT_FAILURE;
                        }
                }
-#if ENABLE_HUSH_FUNCTIONS
-               else {
-                       unset_local_func(*argv);
-               }
-#endif
+//#if ENABLE_HUSH_FUNCTIONS
+//             else {
+//                     unset_local_func(*argv);
+//             }
+//#endif
                argv++;
        }
        return ret;