* rewrites.
*
* Other credits:
- * b_addchr() derived from similar w_addchar function in glibc-2.2
+ * o_addchr() derived from similar w_addchar function in glibc-2.2.
* setup_redirect(), redirect_opt_num(), and big chunks of main()
* and many builtins derived from contributions by Erik Andersen
- * miscellaneous bugfixes from Matt Kraai
+ * miscellaneous bugfixes from Matt Kraai.
*
* There are two big (and related) architecture differences between
* this parser and the lash parser. One is that this version is
*
* Bash grammar not implemented: (how many of these were in original sh?)
* $_
- * ! negation operator for pipes
* &> and >& redirection of stdout+stderr
* Brace Expansion
* Tilde Expansion
* reserved word execution woefully incomplete and buggy
* to-do:
* port selected bugfixes from post-0.49 busybox lash - done?
- * finish implementing reserved words: for, while, until, do, done
* change { and } from special chars to reserved words
* builtins: break, continue, eval, return, set, trap, ulimit
* test magic exec
- * handle children going into background
- * clean up recognition of null pipes
* check setting of global_argc and global_argv
- * control-C handling, probably with longjmp
* follow IFS rules more precisely, including update semantics
* figure out what to do with backslash-newline
- * explain why we use signal instead of sigaction
* propagate syntax errors, die on resource errors?
* continuation lines, both explicit and implicit - done?
* memory leak finding and plugging - done?
- * more testing, especially quoting rules and redirection
- * document how quoting rules not precisely followed for variable assignments
* maybe change charmap[] to use 2-bit entries
- * (eventually) remove all the printf's
*
* Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
*/
#include <glob.h> /* glob, of course */
-#include <getopt.h> /* should be pretty obvious */
/* #include <dmalloc.h> */
#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
RES_XXXX = 12,
RES_SNTX = 13
} reserved_style;
-enum {
- FLAG_END = (1 << RES_NONE ),
-#if ENABLE_HUSH_IF
- FLAG_IF = (1 << RES_IF ),
- FLAG_THEN = (1 << RES_THEN ),
- FLAG_ELIF = (1 << RES_ELIF ),
- FLAG_ELSE = (1 << RES_ELSE ),
- FLAG_FI = (1 << RES_FI ),
-#endif
-#if ENABLE_HUSH_LOOPS
- FLAG_FOR = (1 << RES_FOR ),
- FLAG_WHILE = (1 << RES_WHILE),
- FLAG_UNTIL = (1 << RES_UNTIL),
- FLAG_DO = (1 << RES_DO ),
- FLAG_DONE = (1 << RES_DONE ),
- FLAG_IN = (1 << RES_IN ),
-#endif
- FLAG_START = (1 << RES_XXXX ),
-};
-
/* This holds pointers to the various results of parsing */
struct p_context {
struct child_prog *child;
struct pipe *pipe;
struct redir_struct *pending_redirect;
smallint res_w;
- smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
+ smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser: ";$" common or special symbol */
+ smallint ctx_inverted; /* "! cmd | cmd" */
int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
struct p_context *stack;
/* How about quoting status? */
smallint is_stopped; /* is the program currently running? */
struct redir_struct *redirects; /* I/O redirections */
struct pipe *family; /* pointer back to the child's parent pipe */
- //sp counting seems to be broken... so commented out, grep for '//sp:'
- //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
- //seems to be unused, grep for '//pt:'
- //pt: int parse_type;
};
/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
* and on execution these are substituted with their values.
char *cmdbuf; /* buffer various argv's point into */
struct child_prog *progs; /* array of commands in pipe */
int job_context; /* bitmask defining current context */
+ smallint pi_inverted; /* "! cmd | cmd" */
smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
smallint res_word; /* needed for if, for, while, until... */
};
int maxlen;
smallint o_quote;
smallint nonnull;
+ smallint has_empty_slot;
} o_string;
-#define NULL_O_STRING {NULL,0,0,0,0}
+#define NULL_O_STRING { NULL }
/* used for initialization: o_string foo = NULL_O_STRING; */
/* I can almost use ordinary FILE *. Is open_memstream() universally
int (*get) (struct in_str *);
int (*peek) (struct in_str *);
};
-#define b_getch(input) ((input)->get(input))
-#define b_peek(input) ((input)->peek(input))
+#define i_getch(input) ((input)->get(input))
+#define i_peek(input) ((input)->peek(input))
enum {
CHAR_ORDINARY = 0,
#endif
#define charmap (G.charmap )
#define user_input_buf (G.user_input_buf )
+#define INIT_G() do { \
+ SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
+} while (0)
-#define B_CHUNK 100
-#define B_NOSPAC 1
#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
#if 1
#endif
/* Index of subroutines: */
-/* o_string manipulation: */
-static int b_check_space(o_string *o, int len);
-static int b_addchr(o_string *o, int ch);
-static void b_reset(o_string *o);
-static int b_addqchr(o_string *o, int ch, int quote);
/* in_str manipulations: */
static int static_get(struct in_str *i);
static int static_peek(struct in_str *i);
/* really run the final data structures: */
static int setup_redirects(struct child_prog *prog, int squirrel[]);
static int run_list(struct pipe *pi);
-static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
-static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
+#if BB_MMU
+#define pseudo_exec_argv(ptrs2free, argv) pseudo_exec_argv(argv)
+#define pseudo_exec(ptrs2free, child) pseudo_exec(child)
+#endif
+static void pseudo_exec_argv(char **ptrs2free, char **argv) ATTRIBUTE_NORETURN;
+static void pseudo_exec(char **ptrs2free, struct child_prog *child) ATTRIBUTE_NORETURN;
static int run_pipe(struct pipe *pi);
/* extended glob support: */
static char **globhack(const char *src, char **strings);
static void initialize_context(struct p_context *ctx);
static int done_word(o_string *dest, struct p_context *ctx);
static int done_command(struct p_context *ctx);
-static int done_pipe(struct p_context *ctx, pipe_style type);
+static void done_pipe(struct p_context *ctx, pipe_style type);
/* primary string parsing: */
static int redirect_dup_num(struct in_str *input);
static int redirect_opt_num(o_string *o);
#if ENABLE_HUSH_TICK
-static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
+static int process_command_subs(o_string *dest,
+ struct in_str *input, const char *subst_end);
#endif
static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
static const char *lookup_param(const char *src);
-static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
+static int handle_dollar(o_string *dest,
+ struct in_str *input);
static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
/* setup: */
static int parse_and_run_stream(struct in_str *inp, int parse_flag);
}
+#if !BB_MMU
+#define EXTRA_PTRS 5 /* 1 for NULL, 1 for args, 3 for paranoid reasons */
+static char **alloc_ptrs(char **argv)
+{
+ char **v = argv;
+ while (*v)
+ v++;
+ return xzalloc((v - argv + EXTRA_PTRS) * sizeof(v[0]));
+}
+#endif
+
+
/* Function prototypes for builtins */
static int builtin_cd(char **argv);
static int builtin_echo(char **argv);
static int builtin_pwd(char **argv);
static int builtin_read(char **argv);
static int builtin_test(char **argv);
+static int builtin_true(char **argv);
static int builtin_set(char **argv);
static int builtin_shift(char **argv);
static int builtin_source(char **argv);
* For example, 'unset foo | whatever' will parse and run, but foo will
* still be set at the end. */
struct built_in_command {
- const char *cmd; /* name */
- int (*function) (char **argv); /* function ptr */
+ const char *cmd;
+ int (*function)(char **argv);
#if ENABLE_HUSH_HELP
- const char *descr; /* description */
+ const char *descr;
#define BLTIN(cmd, func, help) { cmd, func, help }
#else
#define BLTIN(cmd, func, help) { cmd, func }
/* For now, echo and test are unconditionally enabled.
* Maybe make it configurable? */
static const struct built_in_command bltins[] = {
+ BLTIN("." , builtin_source, "Run commands in a file"),
+ BLTIN(":" , builtin_true, "No-op"),
BLTIN("[" , builtin_test, "Test condition"),
BLTIN("[[" , builtin_test, "Test condition"),
#if ENABLE_HUSH_JOB
BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
#endif
// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
- BLTIN("cd" , builtin_cd, "Change working directory"),
+ BLTIN("cd" , builtin_cd, "Change directory"),
// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
BLTIN("echo" , builtin_echo, "Write strings to stdout"),
BLTIN("eval" , builtin_eval, "Construct and run shell command"),
- BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
- BLTIN("exit" , builtin_exit, "Exit from shell"),
+ BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
+ BLTIN("exit" , builtin_exit, "Exit"),
BLTIN("export", builtin_export, "Set environment variable"),
#if ENABLE_HUSH_JOB
BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
- BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
+ BLTIN("jobs" , builtin_jobs, "List active jobs"),
#endif
-// TODO: remove pwd? we have it as an applet...
BLTIN("pwd" , builtin_pwd, "Print current directory"),
BLTIN("read" , builtin_read, "Input environment variable"),
// BLTIN("return", builtin_not_written, "Return from a function"),
BLTIN("shift" , builtin_shift, "Shift positional parameters"),
// BLTIN("trap" , builtin_not_written, "Trap signals"),
BLTIN("test" , builtin_test, "Test condition"),
-// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
- BLTIN("umask" , builtin_umask, "Sets file creation mask"),
+// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
+ BLTIN("umask" , builtin_umask, "Set file creation mask"),
BLTIN("unset" , builtin_unset, "Unset environment variable"),
- BLTIN("." , builtin_source, "Source-in and run commands in a file"),
#if ENABLE_HUSH_HELP
BLTIN("help" , builtin_help, "List shell built-in commands"),
#endif
- BLTIN(NULL, NULL, NULL)
};
-#if ENABLE_HUSH_JOB
-
-/* move to libbb? */
-static void signal_SA_RESTART(int sig, void (*handler)(int))
+/* Signals are grouped, we handle them in batches */
+static void set_misc_sighandler(void (*handler)(int))
{
- struct sigaction sa;
- sa.sa_handler = handler;
- sa.sa_flags = SA_RESTART;
- sigemptyset(&sa.sa_mask);
- sigaction(sig, &sa, NULL);
+ bb_signals(0
+ + (1 << SIGINT)
+ + (1 << SIGQUIT)
+ + (1 << SIGTERM)
+ , handler);
}
-/* Signals are grouped, we handle them in batches */
+#if ENABLE_HUSH_JOB
+
static void set_fatal_sighandler(void (*handler)(int))
{
- signal(SIGILL , handler);
- signal(SIGTRAP, handler);
- signal(SIGABRT, handler);
- signal(SIGFPE , handler);
- signal(SIGBUS , handler);
- signal(SIGSEGV, handler);
+ bb_signals(0
+ + (1 << SIGILL)
+ + (1 << SIGTRAP)
+ + (1 << SIGABRT)
+ + (1 << SIGFPE)
+ + (1 << SIGBUS)
+ + (1 << SIGSEGV)
/* bash 3.2 seems to handle these just like 'fatal' ones */
- signal(SIGHUP , handler);
- signal(SIGPIPE, handler);
- signal(SIGALRM, handler);
+ + (1 << SIGHUP)
+ + (1 << SIGPIPE)
+ + (1 << SIGALRM)
+ , handler);
}
static void set_jobctrl_sighandler(void (*handler)(int))
{
- signal(SIGTSTP, handler);
- signal(SIGTTIN, handler);
- signal(SIGTTOU, handler);
-}
-static void set_misc_sighandler(void (*handler)(int))
-{
- signal(SIGINT , handler);
- signal(SIGQUIT, handler);
- signal(SIGTERM, handler);
+ bb_signals(0
+ + (1 << SIGTSTP)
+ + (1 << SIGTTIN)
+ + (1 << SIGTTOU)
+ , handler);
}
/* SIGCHLD is special and handled separately */
signal(SIGCHLD, handler);
}
-static void handler_ctrl_c(int sig)
+static void handler_ctrl_c(int sig ATTRIBUTE_UNUSED)
{
debug_printf_jobs("got sig %d\n", sig);
// as usual we can have all kinds of nasty problems with leaked malloc data here
siglongjmp(toplevel_jb, 1);
}
-static void handler_ctrl_z(int sig)
+static void handler_ctrl_z(int sig ATTRIBUTE_UNUSED)
{
pid_t pid;
return;
ctrl_z_flag = 1;
if (!pid) { /* child */
- die_sleep = 0; /* let nofork's xfuncs die */
+ if (ENABLE_HUSH_JOB)
+ die_sleep = 0; /* let nofork's xfuncs die */
setpgrp();
debug_printf_jobs("set pgrp for child %d ok\n", getpid());
set_every_sighandler(SIG_DFL);
static void sigexit(int sig) ATTRIBUTE_NORETURN;
static void sigexit(int sig)
{
- sigset_t block_all;
-
/* Disable all signals: job control, SIGPIPE, etc. */
- sigfillset(&block_all);
- sigprocmask(SIG_SETMASK, &block_all, NULL);
+ sigprocmask_allsigs(SIG_BLOCK);
if (interactive_fd)
tcsetpgrp(interactive_fd, saved_tty_pgrp);
if (sig <= 0)
_exit(- sig);
- /* Enable only this sig and kill ourself with it */
- signal(sig, SIG_DFL);
- sigdelset(&block_all, sig);
- sigprocmask(SIG_SETMASK, &block_all, NULL);
- raise(sig);
- _exit(1); /* Should not reach it */
+ kill_myself_with_sig(sig); /* does not return */
}
/* Restores tty foreground process group, and exits. */
#define set_fatal_sighandler(handler) ((void)0)
#define set_jobctrl_sighandler(handler) ((void)0)
-#define set_misc_sighandler(handler) ((void)0)
#define hush_exit(e) exit(e)
#endif /* JOB */
}
+/* built-in 'true' handler */
+static int builtin_true(char **argv ATTRIBUTE_UNUSED)
+{
+ return 0;
+}
+
/* built-in 'test' handler */
static int builtin_test(char **argv)
{
static int builtin_exec(char **argv)
{
if (argv[1] == NULL)
- return EXIT_SUCCESS; /* Really? */
- pseudo_exec_argv(argv + 1);
- /* never returns */
+ return EXIT_SUCCESS; /* bash does this */
+ {
+#if !BB_MMU
+ char **ptrs2free = alloc_ptrs(argv);
+#endif
+// FIXME: if exec fails, bash does NOT exit! We do...
+ pseudo_exec_argv(ptrs2free, argv + 1);
+ /* never returns */
+ }
}
/* built-in 'exit' handler */
printf("\nBuilt-in commands:\n");
printf("-------------------\n");
- for (x = bltins; x->cmd; x++) {
+ for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
printf("%s\t%s\n", x->cmd, x->descr);
}
printf("\n\n");
char *string;
const char *name = argv[1] ? argv[1] : "REPLY";
- string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
+ string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
return set_local_var(string, 0);
}
// return EXIT_FAILURE;
//}
-static int b_check_space(o_string *o, int len)
+/*
+ * o_string support
+ */
+#define B_CHUNK (32 * sizeof(char*))
+
+static void o_reset(o_string *o)
+{
+ o->length = 0;
+ o->nonnull = 0;
+ if (o->data)
+ o->data[0] = '\0';
+}
+
+static void o_free(o_string *o)
+{
+ free(o->data);
+ memset(o, 0, sizeof(*o));
+}
+
+static void o_grow_by(o_string *o, int len)
{
- /* It would be easy to drop a more restrictive policy
- * in here, such as setting a maximum string length */
if (o->length + len > o->maxlen) {
- /* assert(data == NULL || o->maxlen != 0); */
o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
o->data = xrealloc(o->data, 1 + o->maxlen);
}
- return o->data == NULL;
}
-static int b_addchr(o_string *o, int ch)
+static void o_addchr(o_string *o, int ch)
{
- debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
- if (b_check_space(o, 1))
- return B_NOSPAC;
+ debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
+ o_grow_by(o, 1);
o->data[o->length] = ch;
o->length++;
o->data[o->length] = '\0';
- return 0;
}
-static void b_reset(o_string *o)
+static void o_addstr(o_string *o, const char *str, int len)
{
- o->length = 0;
- o->nonnull = 0;
- if (o->data)
- o->data[0] = '\0';
+ o_grow_by(o, len);
+ memcpy(&o->data[o->length], str, len);
+ o->length += len;
+ o->data[o->length] = '\0';
}
-static void b_free(o_string *o)
+/* My analysis of quoting semantics tells me that state information
+ * is associated with a destination, not a source.
+ */
+static void o_addqchr(o_string *o, int ch)
{
- free(o->data);
- memset(o, 0, sizeof(*o));
+ int sz = 1;
+ if (strchr("*?[\\", ch)) {
+ sz++;
+ o->data[o->length] = '\\';
+ o->length++;
+ }
+ o_grow_by(o, sz);
+ o->data[o->length] = ch;
+ o->length++;
+ o->data[o->length] = '\0';
}
-/* My analysis of quoting semantics tells me that state information
- * is associated with a destination, not a source.
+static void o_addQchr(o_string *o, int ch)
+{
+ int sz = 1;
+ if (o->o_quote && strchr("*?[\\", ch)) {
+ sz++;
+ o->data[o->length] = '\\';
+ o->length++;
+ }
+ o_grow_by(o, sz);
+ o->data[o->length] = ch;
+ o->length++;
+ o->data[o->length] = '\0';
+}
+
+static void o_addQstr(o_string *o, const char *str, int len)
+{
+ if (!o->o_quote) {
+ o_addstr(o, str, len);
+ return;
+ }
+ while (len) {
+ char ch;
+ int sz;
+ int ordinary_cnt = strcspn(str, "*?[\\");
+ if (ordinary_cnt > len) /* paranoia */
+ ordinary_cnt = len;
+ o_addstr(o, str, ordinary_cnt);
+ if (ordinary_cnt == len)
+ return;
+ str += ordinary_cnt;
+ len -= ordinary_cnt - 1; /* we are processing + 1 char below */
+
+ ch = *str++;
+ sz = 1;
+ if (ch) { /* it is necessarily one of "*?[\\" */
+ sz++;
+ o->data[o->length] = '\\';
+ o->length++;
+ }
+ o_grow_by(o, sz);
+ o->data[o->length] = ch;
+ o->length++;
+ o->data[o->length] = '\0';
+ }
+}
+
+/* A special kind of o_string for $VAR and `cmd` expansion.
+ * It contains char* list[] at the beginning, which is grown in 16 element
+ * increments. Actual string data starts at the next multiple of 16.
+ * list[i] contains an INDEX (int!) into this string data.
+ * It means that if list[] needs to grow, data needs to be moved higher up
+ * but list[i]'s need not be modified.
+ * NB: remembering how many list[i]'s you have there is crucial.
+ * o_finalize_list() operation post-processes this structure - calculates
+ * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
*/
-static int b_addqchr(o_string *o, int ch, int quote)
+static int o_save_ptr(o_string *o, int n)
{
- if (quote && strchr("*?[\\", ch)) {
- int rc;
- rc = b_addchr(o, '\\');
- if (rc)
- return rc;
+ char **list = (char**)o->data;
+ int string_start;
+ int string_len;
+
+ if (!o->has_empty_slot) {
+ string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
+ string_len = o->length - string_start;
+ if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
+ //bb_error_msg("list[%d]=%d string_start=%d (growing)", n, string_len, string_start);
+ /* list[n] points to string_start, make space for 16 more pointers */
+ o->maxlen += 0x10 * sizeof(list[0]);
+ o->data = xrealloc(o->data, o->maxlen + 1);
+ list = (char**)o->data;
+ memmove(list + n + 0x10, list + n, string_len);
+ o->length += 0x10 * sizeof(list[0]);
+ }
+ //else bb_error_msg("list[%d]=%d string_start=%d", n, string_len, string_start);
+ } else {
+ /* We have empty slot at list[n], reuse without growth */
+ string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
+ string_len = o->length - string_start;
+ //bb_error_msg("list[%d]=%d string_start=%d (empty slot)", n, string_len, string_start);
+ o->has_empty_slot = 0;
}
- return b_addchr(o, ch);
+ list[n] = (char*)string_len;
+ return n + 1;
}
+static int o_get_last_ptr(o_string *o, int n)
+{
+ char **list = (char**)o->data;
+ int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
+
+ return ((int)list[n-1]) + string_start;
+}
+
+static char **o_finalize_list(o_string *o, int n)
+{
+ char **list = (char**)o->data;
+ int string_start;
+
+ o_save_ptr(o, n); /* force growth for list[n] if necessary */
+ string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]);
+ list[n] = NULL;
+ while (n) {
+ n--;
+ list[n] = o->data + (int)list[n] + string_start;
+ }
+ return list;
+}
+
+#ifdef DEBUG_EXPAND
+static void o_debug_list(const char *prefix, o_string *o, int n)
+{
+ char **list = (char**)o->data;
+ int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
+ int i = 0;
+ 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) {
+ fprintf(stderr, " list[%d]=%d '%s'\n", i, (int)list[i],
+ o->data + (int)list[i] + string_start);
+ i++;
+ }
+ if (n) {
+ const char *p = o->data + (int)list[n] + string_start;
+ fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
+ }
+}
+#else
+#define o_debug_list(prefix, o, n) ((void)0)
+#endif
+
+
+/*
+ * in_str support
+ */
static int static_get(struct in_str *i)
{
int ch = *i->p++;
prompt_str = setup_prompt_string(i->promptmode);
#if ENABLE_FEATURE_EDITING
/* Enable command line editing only while a command line
- * is actually being read; otherwise, we'll end up bequeathing
- * atexit() handlers and other unwanted stuff to our
- * child processes (rob@sysgo.de) */
- r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
+ * is actually being read */
+ do {
+ r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
+ } while (r == 0); /* repeat if Ctrl-C */
i->eof_flag = (r < 0);
if (i->eof_flag) { /* EOF/error detected */
user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
* XXX no exit() here. If you don't exec, use _exit instead.
* The at_exit handlers apparently confuse the calling process,
* in particular stdin handling. Not sure why? -- because of vfork! (vda) */
-static void pseudo_exec_argv(char **argv)
+static void pseudo_exec_argv(char **ptrs2free, char **argv)
{
int i, rcode;
char *p;
for (i = 0; is_assignment(argv[i]); i++) {
debug_printf_exec("pid %d environment modification: %s\n",
getpid(), argv[i]);
-// FIXME: vfork case??
p = expand_string_to_string(argv[i]);
+#if !BB_MMU
+ *ptrs2free++ = p;
+#endif
putenv(p);
}
argv += i;
_exit(EXIT_SUCCESS);
argv = expand_strvec_to_strvec(argv);
+#if !BB_MMU
+ *ptrs2free++ = (char*) argv;
+#endif
/*
* Check if the command matches any of the builtins.
* easier to waste a few CPU cycles than it is to figure out
* if this is one of those cases.
*/
- for (x = bltins; x->cmd; x++) {
+ for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
if (strcmp(argv[0], x->cmd) == 0) {
debug_printf_exec("running builtin '%s'\n", argv[0]);
rcode = x->function(argv);
debug_printf_exec("execing '%s'\n", argv[0]);
execvp(argv[0], argv);
bb_perror_msg("cannot exec '%s'", argv[0]);
- _exit(1);
+ _exit(EXIT_FAILURE);
}
/* Called after [v]fork() in run_pipe()
*/
-static void pseudo_exec(struct child_prog *child)
+static void pseudo_exec(char **ptrs2free, struct child_prog *child)
{
-// FIXME: buggy wrt NOMMU! Must not modify any global data
-// until it does exec/_exit, but currently it does
-// (puts malloc'ed stuff into environment)
if (child->argv)
- pseudo_exec_argv(child->argv);
+ pseudo_exec_argv(ptrs2free, child->argv);
if (child->group) {
#if !BB_MMU
if (pi->cmdtext)
return pi->cmdtext;
argv = pi->progs[0].argv;
- if (!argv || !argv[0])
- return (pi->cmdtext = xzalloc(1));
+ if (!argv || !argv[0]) {
+ pi->cmdtext = xzalloc(1);
+ return pi->cmdtext;
+ }
len = 0;
do len += strlen(*argv) + 1; while (*++argv);
if (dead) {
fg_pipe->progs[i].pid = 0;
fg_pipe->running_progs--;
- if (i == fg_pipe->num_progs - 1)
+ if (i == fg_pipe->num_progs - 1) {
/* last process gives overall exitstatus */
rcode = WEXITSTATUS(status);
+ if (fg_pipe->pi_inverted)
+ rcode = !rcode;
+ }
} else {
fg_pipe->progs[i].is_stopped = 1;
fg_pipe->stopped_progs++;
rcode = run_list(child->group) & 0xff;
restore_redirects(squirrel);
debug_printf_exec("run_pipe return %d\n", rcode);
+ if (pi->pi_inverted)
+ rcode = !rcode;
return rcode;
}
}
for (i = 0; is_assignment(argv[i]); i++) {
p = expand_string_to_string(argv[i]);
- //sp: child->sp--;
putenv(p);
}
- for (x = bltins; x->cmd; x++) {
+ for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
if (strcmp(argv[i], x->cmd) == 0) {
if (x->function == builtin_exec && argv[i+1] == NULL) {
debug_printf("magic exec\n");
* things seem to work with glibc. */
setup_redirects(child, squirrel);
debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
- //sp: if (child->sp) /* btw we can do it unconditionally... */
argv_expanded = expand_strvec_to_strvec(argv + i);
rcode = x->function(argv_expanded) & 0xff;
free(argv_expanded);
restore_redirects(squirrel);
debug_printf_exec("run_pipe return %d\n", rcode);
+ if (pi->pi_inverted)
+ rcode = !rcode;
return rcode;
}
}
setup_redirects(child, squirrel);
save_nofork_data(&nofork_save);
argv_expanded = argv + i;
- //sp: if (child->sp)
argv_expanded = expand_strvec_to_strvec(argv + i);
debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
- rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
+ rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
free(argv_expanded);
restore_redirects(squirrel);
debug_printf_exec("run_pipe return %d\n", rcode);
+ if (pi->pi_inverted)
+ rcode = !rcode;
return rcode;
}
}
nextin = 0;
for (i = 0; i < pi->num_progs; i++) {
+#if !BB_MMU
+ char **ptrs2free = NULL;
+#endif
child = &(pi->progs[i]);
- if (child->argv)
+ if (child->argv) {
debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
- else
+#if !BB_MMU
+ ptrs2free = alloc_ptrs(child->argv);
+#endif
+ } else
debug_printf_exec(": pipe member with no argv\n");
/* pipes are inserted between pairs of commands */
child->pid = BB_MMU ? fork() : vfork();
if (!child->pid) { /* child */
- die_sleep = 0; /* let nofork's xfuncs die */
+ if (ENABLE_HUSH_JOB)
+ die_sleep = 0; /* let nofork's xfuncs die */
#if ENABLE_HUSH_JOB
/* Every child adds itself to new process group
* with pgid == pid_of_first_child_in_pipe */
set_jobctrl_sighandler(SIG_DFL);
set_misc_sighandler(SIG_DFL);
signal(SIGCHLD, SIG_DFL);
- pseudo_exec(child); /* does not return */
+ pseudo_exec(ptrs2free, child); /* does not return */
}
-
+#if !BB_MMU
+ free_strings(ptrs2free);
+#endif
if (child->pid < 0) { /* [v]fork failed */
/* Clearly indicate, was it fork or vfork */
bb_perror_msg(BB_MMU ? "fork" : "vfork");
#if ENABLE_FEATURE_SH_STANDALONE
nofork_save.saved = 0; /* in case we will run a nofork later */
#endif
- signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
+ signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
signal(SIGINT, handler_ctrl_c);
}
#endif /* JOB */
* In the long run that function can be merged with run_list,
* but doing that now would hobble the debugging effort. */
free_pipe_list(pi, /* indent: */ 0);
- debug_printf_exec("run_nad_free_list return %d\n", rcode);
+ debug_printf_exec("run_and_free_list return %d\n", rcode);
return rcode;
}
* followed by strings themself.
* Caller can deallocate entire list by single free(list). */
-/* Helpers first:
- * count_XXX estimates size of the block we need. It's okay
- * to over-estimate sizes a bit, if it makes code simpler */
-static int count_ifs(const char *str)
-{
- int cnt = 0;
- debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
- while (1) {
- str += strcspn(str, ifs);
- if (!*str) break;
- str++; /* str += strspn(str, ifs); */
- cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
- }
- debug_printf_expand(" return %d\n", cnt);
- return cnt;
-}
-
-static void count_var_expansion_space(int *countp, int *lenp, char *arg)
-{
- char first_ch;
- int i;
- int len = *lenp;
- int count = *countp;
- const char *val;
- char *p;
-
- while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
- len += p - arg;
- arg = ++p;
- p = strchr(p, SPECIAL_VAR_SYMBOL);
- first_ch = arg[0];
-
- switch (first_ch & 0x7f) {
- /* high bit in 1st_ch indicates that var is double-quoted */
- case '$': /* pid */
- case '!': /* bg pid */
- case '?': /* exitcode */
- case '#': /* argc */
- len += sizeof(int)*3 + 1; /* enough for int */
- break;
- case '*':
- case '@':
- for (i = 1; global_argv[i]; i++) {
- len += strlen(global_argv[i]) + 1;
- count++;
- if (!(first_ch & 0x80))
- count += count_ifs(global_argv[i]);
- }
- break;
- default:
- *p = '\0';
- arg[0] = first_ch & 0x7f;
- if (isdigit(arg[0])) {
- i = xatoi_u(arg);
- val = NULL;
- if (i < global_argc)
- val = global_argv[i];
- } else
- val = lookup_param(arg);
- arg[0] = first_ch;
- *p = SPECIAL_VAR_SYMBOL;
-
- if (val) {
- len += strlen(val) + 1;
- if (!(first_ch & 0x80))
- count += count_ifs(val);
- }
- }
- arg = ++p;
- }
-
- len += strlen(arg) + 1;
- count++;
- *lenp = len;
- *countp = count;
-}
-
/* Store given string, finalizing the word and starting new one whenever
* we encounter ifs char(s). This is used for expanding variable values.
* End-of-string does NOT finalize word: think about 'echo -$VAR-' */
-static int expand_on_ifs(char **list, int n, char **posp, const char *str)
+static int expand_on_ifs(o_string *output, int n, const char *str)
{
- char *pos = *posp;
while (1) {
int word_len = strcspn(str, ifs);
if (word_len) {
- memcpy(pos, str, word_len); /* store non-ifs chars */
- pos += word_len;
+ o_addQstr(output, str, word_len);
str += word_len;
}
if (!*str) /* EOL - do not finalize word */
break;
- *pos++ = '\0';
- if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
- "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
- strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
- list[n++] = pos;
+ o_addchr(output, '\0');
+ o_debug_list("expand_on_ifs", output, n);
+ n = o_save_ptr(output, n);
str += strspn(str, ifs); /* skip ifs chars */
}
- *posp = pos;
+ o_debug_list("expand_on_ifs[1]", output, n);
return n;
}
* 'echo -$*-'. If you play here, you must run testsuite afterwards! */
/* NB: another bug is that we cannot detect empty strings yet:
* "" or $empty"" expands to zero words, has to expand to empty word */
-static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
+static 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) */
int i;
const char *val;
char *p;
- char *pos = *posp;
ored_ch = 0;
- if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
- "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
- strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
- list[n++] = pos;
+ debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
+ o_debug_list("expand_vars_to_list", output, n);
+ n = o_save_ptr(output, n);
+ o_debug_list("expand_vars_to_list[0]", output, n);
- while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
- memcpy(pos, arg, p - arg);
- pos += (p - arg);
+ while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
+ o_string subst_result = NULL_O_STRING;
+
+ o_addQstr(output, arg, p - arg);
+ o_debug_list("expand_vars_to_list[1]", output, n);
arg = ++p;
p = strchr(p, SPECIAL_VAR_SYMBOL);
break;
if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
while (global_argv[i]) {
- n = expand_on_ifs(list, n, &pos, global_argv[i]);
+ n = expand_on_ifs(output, n, global_argv[i]);
debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
if (global_argv[i++][0] && global_argv[i]) {
/* this argv[] is not empty and not last:
* put terminating NUL, start new word */
- *pos++ = '\0';
- if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
- "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
- strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
- list[n++] = pos;
+ o_addchr(output, '\0');
+ o_debug_list("expand_vars_to_list[2]", output, n);
+ n = o_save_ptr(output, n);
+ o_debug_list("expand_vars_to_list[3]", output, n);
}
}
} else
* and in this case should treat it like '$*' - see 'else...' below */
if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
while (1) {
- strcpy(pos, global_argv[i]);
- pos += strlen(global_argv[i]);
+ o_addQstr(output, global_argv[i], strlen(global_argv[i]));
if (++i >= global_argc)
break;
- *pos++ = '\0';
- if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
- "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
- strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
- list[n++] = pos;
+ o_addchr(output, '\0');
+ o_debug_list("expand_vars_to_list[4]", output, n);
+ n = o_save_ptr(output, n);
}
} else { /* quoted $*: add as one word */
while (1) {
- strcpy(pos, global_argv[i]);
- pos += strlen(global_argv[i]);
+ o_addQstr(output, global_argv[i], strlen(global_argv[i]));
if (!global_argv[++i])
break;
if (ifs[0])
- *pos++ = ifs[0];
+ o_addchr(output, ifs[0]);
}
}
break;
+ case '`': {
+ struct in_str input;
+ *p = '\0';
+ arg++;
+ //bb_error_msg("SUBST '%s' first_ch %x", arg, first_ch);
+ setup_string_in_str(&input, arg);
+ process_command_subs(&subst_result, &input, NULL);
+ //bb_error_msg("RES '%s'", subst_result.data);
+ val = subst_result.data;
+ goto store_val;
+ }
default:
*p = '\0';
arg[0] = first_ch & 0x7f;
} else
val = lookup_param(arg);
arg[0] = first_ch;
+ store_val:
*p = SPECIAL_VAR_SYMBOL;
if (!(first_ch & 0x80)) { /* unquoted $VAR */
if (val) {
- n = expand_on_ifs(list, n, &pos, val);
+ n = expand_on_ifs(output, n, val);
val = NULL;
}
- } /* else: quoted $VAR, val will be appended at pos */
+ } /* else: quoted $VAR, val will be appended below */
}
if (val) {
- strcpy(pos, val);
- pos += strlen(val);
+ o_addQstr(output, val, strlen(val));
}
+
+ o_free(&subst_result);
arg = ++p;
+ } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
+
+ if (arg[0]) {
+ o_debug_list("expand_vars_to_list[a]", output, n);
+ o_addQstr(output, arg, strlen(arg) + 1);
+ o_debug_list("expand_vars_to_list[b]", output, n);
+ } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
+ && !(ored_ch & 0x80) /* and all vars were not quoted. */
+ ) {
+ n--;
+ /* allow to reuse list[n] later without re-growth */
+ output->has_empty_slot = 1;
+ } else {
+ o_addchr(output, '\0');
}
- debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
- strcpy(pos, arg);
- pos += strlen(arg) + 1;
- if (pos == list[n-1] + 1) { /* expansion is empty */
- if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
- debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
- pos--;
- n--;
- }
- }
-
- *posp = pos;
return n;
}
static char **expand_variables(char **argv, char or_mask)
{
int n;
- int count = 1;
- int len = 0;
- char *pos, **v, **list;
+ char **list;
+ char **v;
+ o_string output = NULL_O_STRING;
- v = argv;
- if (!*v) debug_printf_expand("count_var_expansion_space: "
- "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
- count, len, sizeof(char*) * count + len);
- while (*v) {
- count_var_expansion_space(&count, &len, *v);
- debug_printf_expand("count_var_expansion_space: "
- "'%s' count=%d len=%d alloc_space=%d\n",
- *v, count, len, sizeof(char*) * count + len);
- v++;
- }
- len += sizeof(char*) * count; /* total to alloc */
- list = xmalloc(len);
- pos = (char*)(list + count);
- debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
n = 0;
v = argv;
while (*v)
- n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
+ n = expand_vars_to_list(&output, n, *v++, or_mask);
+ o_debug_list("expand_variables", &output, n);
- if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
- "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
- strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
- list[n] = NULL;
+ /* output.data (malloced) gets returned in "list" */
+ list = o_finalize_list(&output, n);
#ifdef DEBUG_EXPAND
{
debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
m++;
}
- debug_printf_expand("used_space=%d\n", pos - (char*)list);
}
#endif
- if (ENABLE_HUSH_DEBUG)
- if (pos - (char*)list > len)
- bb_error_msg_and_die("BUG in varexp");
return list;
}
/* Check for a '2>&1' type redirect */
redir->dup = redirect_dup_num(input);
- if (redir->dup == -2) return 1; /* syntax error */
+ if (redir->dup == -2)
+ return 1; /* syntax error */
if (redir->dup != -1) {
/* Erik had a check here that the file descriptor in question
* is legit; I postpone that to "run time"
{
struct pipe *pi;
pi = xzalloc(sizeof(struct pipe));
- /*pi->num_progs = 0;*/
- /*pi->progs = NULL;*/
- /*pi->next = NULL;*/
- /*pi->followup = 0; invalid */
+ /*pi->followup = 0; - deliberately invalid value */
if (RES_NONE)
pi->res_word = RES_NONE;
return pi;
static void initialize_context(struct p_context *ctx)
{
- ctx->child = NULL;
+ smallint sv = ctx->parse_type;
+ memset(ctx, 0, sizeof(*ctx));
+ ctx->parse_type = sv;
ctx->pipe = ctx->list_head = new_pipe();
- ctx->pending_redirect = NULL;
- ctx->res_w = RES_NONE;
- //only ctx->parse_type is not touched... is this intentional?
- ctx->old_flag = 0;
- ctx->stack = NULL;
- done_command(ctx); /* creates the memory for working child */
+ /* Create the memory for child, roughly:
+ * ctx->pipe->progs = new struct child_prog;
+ * ctx->pipe->progs[0].family = ctx->pipe;
+ * ctx->child = &ctx->pipe->progs[0];
+ */
+ done_command(ctx);
}
-/* normal return is 0
- * if a reserved word is found, and processed, return 1
- * should handle if, then, elif, else, fi, for, while, until, do, done.
+/* If a reserved word is found and processed, parse context is modified
+ * and 1 is returned.
+ * Handles if, then, elif, else, fi, for, while, until, do, done.
* case, function, and select are obnoxious, save those for later.
*/
#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
-static int reserved_word(o_string *dest, struct p_context *ctx)
+static int reserved_word(const o_string *word, struct p_context *ctx)
{
struct reserved_combo {
char literal[7];
- unsigned char code;
+ unsigned char res;
int flag;
};
+ enum {
+ FLAG_END = (1 << RES_NONE ),
+#if ENABLE_HUSH_IF
+ FLAG_IF = (1 << RES_IF ),
+ FLAG_THEN = (1 << RES_THEN ),
+ FLAG_ELIF = (1 << RES_ELIF ),
+ FLAG_ELSE = (1 << RES_ELSE ),
+ FLAG_FI = (1 << RES_FI ),
+#endif
+#if ENABLE_HUSH_LOOPS
+ FLAG_FOR = (1 << RES_FOR ),
+ FLAG_WHILE = (1 << RES_WHILE),
+ FLAG_UNTIL = (1 << RES_UNTIL),
+ FLAG_DO = (1 << RES_DO ),
+ FLAG_DONE = (1 << RES_DONE ),
+ FLAG_IN = (1 << RES_IN ),
+#endif
+ FLAG_START = (1 << RES_XXXX ),
+ };
/* Mostly a list of accepted follow-up reserved words.
* FLAG_END means we are done with the sequence, and are ready
* to turn the compound list into a command.
*/
static const struct reserved_combo reserved_list[] = {
#if ENABLE_HUSH_IF
+ { "!", RES_NONE, 0 },
{ "if", RES_IF, FLAG_THEN | FLAG_START },
{ "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
{ "elif", RES_ELIF, FLAG_THEN },
{ "fi", RES_FI, FLAG_END },
#endif
#if ENABLE_HUSH_LOOPS
- { "for", RES_FOR, FLAG_IN | FLAG_START },
- { "while", RES_WHILE, FLAG_DO | FLAG_START },
- { "until", RES_UNTIL, FLAG_DO | FLAG_START },
+ { "for", RES_FOR, FLAG_IN | FLAG_START },
+ { "while", RES_WHILE, FLAG_DO | FLAG_START },
+ { "until", RES_UNTIL, FLAG_DO | FLAG_START },
{ "in", RES_IN, FLAG_DO },
{ "do", RES_DO, FLAG_DONE },
{ "done", RES_DONE, FLAG_END }
const struct reserved_combo *r;
for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
- if (strcmp(dest->data, r->literal) != 0)
+ if (strcmp(word->data, r->literal) != 0)
continue;
- debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
+ debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
+ if (r->flag == 0) { /* '!' */
+ if (ctx->res_w == RES_IN) {
+ /* 'for a in ! a b c; ...' - ! isn't a keyword here */
+ break;
+ }
+ if (ctx->res_w == RES_FOR /* example: 'for ! a' */
+ || ctx->ctx_inverted /* bash doesn't accept '! ! true' */
+ ) {
+ syntax(NULL);
+ ctx->res_w = RES_SNTX;
+ }
+ ctx->ctx_inverted = 1;
+ return 1;
+ }
if (r->flag & FLAG_START) {
struct p_context *new;
debug_printf("push stack\n");
if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
syntax("malformed for"); /* example: 'for if' */
ctx->res_w = RES_SNTX;
- b_reset(dest);
return 1;
}
#endif
*new = *ctx; /* physical copy */
initialize_context(ctx);
ctx->stack = new;
- } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
+ } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->res))) {
syntax(NULL);
ctx->res_w = RES_SNTX;
- b_reset(dest);
return 1;
}
- ctx->res_w = r->code;
+ ctx->res_w = r->res;
ctx->old_flag = r->flag;
if (ctx->old_flag & FLAG_END) {
struct p_context *old;
*ctx = *old; /* physical copy */
free(old);
}
- b_reset(dest);
return 1;
}
return 0;
}
#else
-#define reserved_word(dest, ctx) ((int)0)
+#define reserved_word(word, ctx) ((int)0)
#endif
-/* Normal return is 0.
+/* Word is complete, look at it and update parsing context.
+ * Normal return is 0.
* Syntax or xglob errors return 1. */
-static int done_word(o_string *dest, struct p_context *ctx)
+static int done_word(o_string *word, struct p_context *ctx)
{
struct child_prog *child = ctx->child;
char ***glob_target;
int gr;
- debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
- if (dest->length == 0 && !dest->nonnull) {
+ debug_printf_parse("done_word entered: '%s' %p\n", word->data, child);
+ if (word->length == 0 && !word->nonnull) {
debug_printf_parse("done_word return 0: true null, ignored\n");
return 0;
}
if (ctx->pending_redirect) {
glob_target = &ctx->pending_redirect->glob_word;
} else {
- if (child->group) {
+ if (child->group) { /* TODO: example how to trigger? */
syntax(NULL);
debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
return 1;
}
if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
- debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
- if (reserved_word(dest, ctx)) {
+ debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
+ if (reserved_word(word, ctx)) {
+ o_reset(word);
debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
return (ctx->res_w == RES_SNTX);
}
}
glob_target = &child->argv;
}
- gr = xglob(dest, glob_target);
+//BUG! globbing should be done after variable expansion!
+//See glob_and_vars testcase
+ gr = xglob(word, glob_target);
if (gr != 0) {
debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
return 1;
}
- b_reset(dest);
+ o_reset(word);
if (ctx->pending_redirect) {
/* NB: don't free_strings(ctx->pending_redirect->glob_word) here */
if (ctx->pending_redirect->glob_word
ctx->pending_redirect = NULL;
}
#if ENABLE_HUSH_LOOPS
- if (ctx->res_w == RES_FOR) {
- done_word(dest, ctx);
+ if (ctx->res_w == RES_FOR) { /* comment? */
+//TESTING
+//looks like (word->length == 0 && !word->nonnull) is true here, always
+//(due to o_reset). done_word would return at once. Why then?
+// done_word(word, ctx);
done_pipe(ctx, PIPE_SEQ);
}
#endif
child = &pi->progs[pi->num_progs];
memset(child, 0, sizeof(*child));
- /*child->redirects = NULL;*/
- /*child->argv = NULL;*/
- /*child->is_stopped = 0;*/
- /*child->group = NULL;*/
child->family = pi;
- //sp: /*child->sp = 0;*/
- //pt: child->parse_type = ctx->parse_type;
ctx->child = child;
/* but ctx->pipe and ctx->list_head remain unchanged */
return pi->num_progs; /* used only for 0/nonzero check */
}
-static int done_pipe(struct p_context *ctx, pipe_style type)
+static void done_pipe(struct p_context *ctx, pipe_style type)
{
struct pipe *new_p;
int not_null;
not_null = done_command(ctx); /* implicit closure of previous command */
ctx->pipe->followup = type;
ctx->pipe->res_word = ctx->res_w;
+ ctx->pipe->pi_inverted = ctx->ctx_inverted;
+ ctx->ctx_inverted = 0;
/* Without this check, even just <enter> on command line generates
* tree of three NOPs (!). Which is harmless but annoying.
* IOW: it is safe to do it unconditionally. */
new_p = new_pipe();
ctx->pipe->next = new_p;
ctx->pipe = new_p;
- ctx->child = NULL;
- done_command(ctx); /* set up new pipe to accept commands */
+ ctx->child = NULL; /* needed! */
+ /* Create the memory for child, roughly:
+ * ctx->pipe->progs = new struct child_prog;
+ * ctx->pipe->progs[0].family = ctx->pipe;
+ * ctx->child = &ctx->pipe->progs[0];
+ */
+ done_command(ctx);
}
- debug_printf_parse("done_pipe return 0\n");
- return 0;
+ debug_printf_parse("done_pipe return\n");
}
/* peek ahead in the in_str to find out if we have a "&n" construct,
static int redirect_dup_num(struct in_str *input)
{
int ch, d = 0, ok = 0;
- ch = b_peek(input);
+ ch = i_peek(input);
if (ch != '&') return -1;
- b_getch(input); /* get the & */
- ch = b_peek(input);
+ i_getch(input); /* get the & */
+ ch = i_peek(input);
if (ch == '-') {
- b_getch(input);
+ i_getch(input);
return -3; /* "-" represents "close me" */
}
while (isdigit(ch)) {
d = d*10 + (ch-'0');
ok = 1;
- b_getch(input);
- ch = b_peek(input);
+ i_getch(input);
+ ch = i_peek(input);
}
if (ok) return d;
}
/* reuse num (and save an int) */
num = atoi(o->data);
- b_reset(o);
+ o_reset(o);
return num;
}
#if ENABLE_HUSH_TICK
-/* NB: currently disabled on NOMMU */
static FILE *generate_stream_from_list(struct pipe *head)
{
FILE *pf;
/* By using vfork here, we suspend parent till child exits or execs.
* If child will not do it before it fills the pipe, it can block forever
* in write(STDOUT_FILENO), and parent (shell) will be also stuck.
+ * Try this script:
+ * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
+ * huge=`cat TESTFILE` # will block here forever
+ * echo OK
*/
pid = BB_MMU ? fork() : vfork();
if (pid < 0)
bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
if (pid == 0) { /* child */
- die_sleep = 0; /* let nofork's xfuncs die */
- close(channel[0]);
+ if (ENABLE_HUSH_JOB)
+ die_sleep = 0; /* let nofork's xfuncs die */
+ close(channel[0]); /* NB: close _first_, then move fd! */
xmove_fd(channel[1], 1);
/* Prevent it from trying to handle ctrl-z etc */
#if ENABLE_HUSH_JOB
}
/* Return code is exit status of the process that is run. */
-static int process_command_subs(o_string *dest, struct p_context *ctx,
- struct in_str *input, const char *subst_end)
+static int process_command_subs(o_string *dest,
+ struct in_str *input,
+ const char *subst_end)
{
int retcode, ch, eol_cnt;
o_string result = NULL_O_STRING;
return retcode; /* syntax error or EOF */
done_word(&result, &inner);
done_pipe(&inner, PIPE_SEQ);
- b_free(&result);
+ o_free(&result);
p = generate_stream_from_list(inner.list_head);
if (p == NULL)
/* now send results of command back into original context */
eol_cnt = 0;
- while ((ch = b_getch(&pipe_str)) != EOF) {
+ while ((ch = i_getch(&pipe_str)) != EOF) {
if (ch == '\n') {
eol_cnt++;
continue;
}
while (eol_cnt) {
- b_addqchr(dest, '\n', dest->o_quote);
+ o_addQchr(dest, '\n');
eol_cnt--;
}
- b_addqchr(dest, ch, dest->o_quote);
+ o_addQchr(dest, ch);
}
debug_printf("done reading from pipe, pclose()ing\n");
return NULL;
}
+#if ENABLE_HUSH_TICK
+/* Subroutines for copying $(...) and `...` things */
+static void add_till_backquote(o_string *dest, struct in_str *input);
+/* '...' */
+static void add_till_single_quote(o_string *dest, struct in_str *input)
+{
+ while (1) {
+ int ch = i_getch(input);
+ if (ch == EOF)
+ break;
+ if (ch == '\'')
+ break;
+ o_addqchr(dest, ch);
+ }
+}
+/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
+static void add_till_double_quote(o_string *dest, struct in_str *input)
+{
+ while (1) {
+ int ch = i_getch(input);
+ if (ch == '"')
+ break;
+ if (ch == '\\') { /* \x. Copy both chars. */
+ o_addqchr(dest, ch);
+ ch = i_getch(input);
+ }
+ if (ch == EOF)
+ break;
+ o_addqchr(dest, ch);
+ if (ch == '`') {
+ add_till_backquote(dest, input);
+ o_addqchr(dest, ch);
+ continue;
+ }
+// if (ch == '$') ...
+ }
+}
+/* Process `cmd` - copy contents until "`" is seen. Complicated by
+ * \` quoting.
+ * "Within the backquoted style of command substitution, backslash
+ * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
+ * The search for the matching backquote shall be satisfied by the first
+ * backquote found without a preceding backslash; during this search,
+ * if a non-escaped backquote is encountered within a shell comment,
+ * a here-document, an embedded command substitution of the $(command)
+ * form, or a quoted string, undefined results occur. A single-quoted
+ * or double-quoted string that begins, but does not end, within the
+ * "`...`" sequence produces undefined results."
+ * Example Output
+ * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
+ */
+static void add_till_backquote(o_string *dest, struct in_str *input)
+{
+ while (1) {
+ int ch = i_getch(input);
+ if (ch == '`')
+ break;
+ if (ch == '\\') { /* \x. Copy both chars unless it is \` */
+ int ch2 = i_getch(input);
+ if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
+ o_addqchr(dest, ch);
+ ch = ch2;
+ }
+ if (ch == EOF)
+ break;
+ o_addqchr(dest, ch);
+ }
+}
+/* Process $(cmd) - copy contents until ")" is seen. Complicated by
+ * quoting and nested ()s.
+ * "With the $(command) style of command substitution, all characters
+ * following the open parenthesis to the matching closing parenthesis
+ * constitute the command. Any valid shell script can be used for command,
+ * except a script consisting solely of redirections which produces
+ * unspecified results."
+ * Example Output
+ * echo $(echo '(TEST)' BEST) (TEST) BEST
+ * echo $(echo 'TEST)' BEST) TEST) BEST
+ * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
+ */
+static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
+{
+ int count = 0;
+ while (1) {
+ int ch = i_getch(input);
+ if (ch == EOF)
+ break;
+ if (ch == '(')
+ count++;
+ if (ch == ')')
+ if (--count < 0)
+ break;
+ o_addqchr(dest, ch);
+ if (ch == '\'') {
+ add_till_single_quote(dest, input);
+ o_addqchr(dest, ch);
+ continue;
+ }
+ if (ch == '"') {
+ add_till_double_quote(dest, input);
+ o_addqchr(dest, ch);
+ continue;
+ }
+ if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
+ ch = i_getch(input);
+ if (ch == EOF)
+ break;
+ o_addqchr(dest, ch);
+ continue;
+ }
+ }
+}
+#endif /* ENABLE_HUSH_TICK */
+
/* return code: 0 for OK, 1 for syntax error */
-static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
+static int handle_dollar(o_string *dest, struct in_str *input)
{
- int ch = b_peek(input); /* first character after the $ */
+ int ch = i_peek(input); /* first character after the $ */
unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
if (isalpha(ch)) {
- b_addchr(dest, SPECIAL_VAR_SYMBOL);
- //sp: ctx->child->sp++;
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
while (1) {
debug_printf_parse(": '%c'\n", ch);
- b_getch(input);
- b_addchr(dest, ch | quote_mask);
+ i_getch(input);
+ o_addchr(dest, ch | quote_mask);
quote_mask = 0;
- ch = b_peek(input);
+ ch = i_peek(input);
if (!isalnum(ch) && ch != '_')
break;
}
- b_addchr(dest, SPECIAL_VAR_SYMBOL);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
} else if (isdigit(ch)) {
make_one_char_var:
- b_addchr(dest, SPECIAL_VAR_SYMBOL);
- //sp: ctx->child->sp++;
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
debug_printf_parse(": '%c'\n", ch);
- b_getch(input);
- b_addchr(dest, ch | quote_mask);
- b_addchr(dest, SPECIAL_VAR_SYMBOL);
+ i_getch(input);
+ o_addchr(dest, ch | quote_mask);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
} else switch (ch) {
case '$': /* pid */
case '!': /* last bg pid */
case '@': /* args */
goto make_one_char_var;
case '{':
- b_addchr(dest, SPECIAL_VAR_SYMBOL);
- //sp: ctx->child->sp++;
- b_getch(input);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
+ i_getch(input);
/* XXX maybe someone will try to escape the '}' */
while (1) {
- ch = b_getch(input);
+ ch = i_getch(input);
if (ch == '}')
break;
if (!isalnum(ch) && ch != '_') {
return 1;
}
debug_printf_parse(": '%c'\n", ch);
- b_addchr(dest, ch | quote_mask);
+ o_addchr(dest, ch | quote_mask);
quote_mask = 0;
}
- b_addchr(dest, SPECIAL_VAR_SYMBOL);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
break;
#if ENABLE_HUSH_TICK
- case '(':
- b_getch(input);
- process_command_subs(dest, ctx, input, ")");
+ case '(': {
+ //int pos = dest->length;
+ i_getch(input);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
+ o_addchr(dest, quote_mask | '`');
+ add_till_closing_curly_brace(dest, input);
+ //bb_error_msg("RES '%s'", dest->data + pos);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
break;
+ }
#endif
case '-':
case '_':
return 1;
break;
default:
- b_addqchr(dest, '$', dest->o_quote);
+ o_addQchr(dest, '$');
}
debug_printf_parse("handle_dollar return 0\n");
return 0;
while (1) {
m = CHAR_IFS;
next = '\0';
- ch = b_getch(input);
+ ch = i_getch(input);
if (ch != EOF) {
m = charmap[ch];
if (ch != '\n')
- next = b_peek(input);
+ next = i_peek(input);
}
debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
ch, ch, m, dest->o_quote);
debug_printf_parse("parse_stream return 1: unterminated \"\n");
return 1;
}
- b_addqchr(dest, ch, dest->o_quote);
+ o_addQchr(dest, ch);
continue;
}
if (m == CHAR_IFS) {
case '#':
if (dest->length == 0 && !dest->o_quote) {
while (1) {
- ch = b_peek(input);
+ ch = i_peek(input);
if (ch == EOF || ch == '\n')
break;
- b_getch(input);
+ i_getch(input);
}
} else {
- b_addqchr(dest, ch, dest->o_quote);
+ o_addQchr(dest, ch);
}
break;
case '\\':
debug_printf_parse("parse_stream return 1: \\<eof>\n");
return 1;
}
- b_addqchr(dest, '\\', dest->o_quote);
- b_addqchr(dest, b_getch(input), dest->o_quote);
+ /* bash:
+ * "The backslash retains its special meaning [in "..."]
+ * only when followed by one of the following characters:
+ * $, `, ", \, or <newline>. A double quote may be quoted
+ * within double quotes by preceding it with a backslash.
+ * If enabled, history expansion will be performed unless
+ * an ! appearing in double quotes is escaped using
+ * a backslash. The backslash preceding the ! is not removed."
+ */
+ if (dest->o_quote) {
+ if (strchr("$`\"\\", next) != NULL) {
+ o_addqchr(dest, i_getch(input));
+ } else {
+ o_addqchr(dest, '\\');
+ }
+ } else {
+ o_addchr(dest, '\\');
+ o_addchr(dest, i_getch(input));
+ }
break;
case '$':
- if (handle_dollar(dest, ctx, input) != 0) {
+ if (handle_dollar(dest, input) != 0) {
debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
return 1;
}
case '\'':
dest->nonnull = 1;
while (1) {
- ch = b_getch(input);
+ ch = i_getch(input);
if (ch == EOF || ch == '\'')
break;
- b_addchr(dest, ch);
+ o_addqchr(dest, ch);
}
if (ch == EOF) {
syntax("unterminated '");
dest->o_quote ^= 1; /* invert */
break;
#if ENABLE_HUSH_TICK
- case '`':
- process_command_subs(dest, ctx, input, "`");
+ case '`': {
+ //int pos = dest->length;
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
+ o_addchr(dest, dest->o_quote ? 0x80 | '`' : '`');
+ add_till_backquote(dest, input);
+ o_addchr(dest, SPECIAL_VAR_SYMBOL);
+ //bb_error_msg("RES '%s'", dest->data + pos);
break;
+ }
#endif
case '>':
redir_fd = redirect_opt_num(dest);
redir_style = REDIRECT_OVERWRITE;
if (next == '>') {
redir_style = REDIRECT_APPEND;
- b_getch(input);
+ i_getch(input);
}
#if 0
else if (next == '(') {
redir_style = REDIRECT_INPUT;
if (next == '<') {
redir_style = REDIRECT_HEREIS;
- b_getch(input);
+ i_getch(input);
} else if (next == '>') {
redir_style = REDIRECT_IO;
- b_getch(input);
+ i_getch(input);
}
#if 0
else if (next == '(') {
case '&':
done_word(dest, ctx);
if (next == '&') {
- b_getch(input);
+ i_getch(input);
done_pipe(ctx, PIPE_AND);
} else {
done_pipe(ctx, PIPE_BG);
case '|':
done_word(dest, ctx);
if (next == '|') {
- b_getch(input);
+ i_getch(input);
done_pipe(ctx, PIPE_OR);
} else {
/* we could pick up a file descriptor choice here
break;
case ')':
case '}':
- syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
+ /* proper use of this character is caught by end_trigger */
+ syntax("unexpected } or )");
debug_printf_parse("parse_stream return 1: unexpected '}'\n");
return 1;
default:
* from builtin_source() and builtin_eval() */
static int parse_and_run_stream(struct in_str *inp, int parse_flag)
{
+//TODO: PARSEFLAG_SEMICOLON bit is always set in parse_flag. fishy
+//TODO: PARSEFLAG_REPARSING bit is never set (grep for it). wow
struct p_context ctx;
o_string temp = NULL_O_STRING;
int rcode;
do {
+// It always has PARSEFLAG_SEMICOLON, can we remove all checks for this bit?
+// After that, the whole parse_type fiels is not needed.
ctx.parse_type = parse_flag;
initialize_context(&ctx);
update_charmap();
} else {
if (ctx.old_flag != 0) {
free(ctx.stack);
- b_reset(&temp);
+ o_reset(&temp);
}
temp.nonnull = 0;
temp.o_quote = 0;
inp->p = NULL;
free_pipe_list(ctx.list_head, /* indent: */ 0);
}
- b_free(&temp);
+ o_free(&temp);
} while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
return 0;
}
static int parse_and_run_string(const char *s, int parse_flag)
{
+//TODO: PARSEFLAG_SEMICOLON bit is always set in parse_flag. fishy
struct in_str input;
setup_string_in_str(&input, s);
return parse_and_run_stream(&input, parse_flag);
char **e;
struct variable *cur_var;
- PTR_TO_GLOBALS = xzalloc(sizeof(G));
+ INIT_G();
/* Deal with HUSH_VERSION */
shell_ver = const_shell_ver; /* copying struct here */
}
debug_printf("interactive_fd=%d\n", interactive_fd);
if (interactive_fd) {
+ fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
/* Looks like they want an interactive shell */
setup_job_control();
/* -1 is special - makes xfuncs longjmp, not exit
/* give up */
interactive_fd = 0;
}
+ if (interactive_fd) {
+ fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
+ set_misc_sighandler(SIG_IGN);
+ }
}
-
#endif
if (argv[optind] == NULL) {
global_argv = argv + optind;
global_argc = argc - optind;
input = xfopen(argv[optind], "r");
+ fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
opt = parse_and_run_file(input);
}