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