1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * o_addchr() derived from similar w_addchar function in glibc-2.2.
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * POSIX syntax not implemented:
41 * Arithmetic Expansion
42 * <(list) and >(list) Process Substitution
43 * Here Documents ( << word )
46 * Parameter Expansion for substring processing ${var#word} ${var%word}
48 * Bash stuff maybe optional enable:
49 * &> and >& redirection of stdout+stderr
51 * reserved words: [[ ]] function select
52 * substrings ${var:1:5}
55 * job handling woefully incomplete and buggy (improved --vda)
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * change { and } from special chars to reserved words
59 * builtins: return, trap, ulimit
60 * test magic exec with redirection only
61 * follow IFS rules more precisely, including update semantics
62 * figure out what to do with backslash-newline
63 * propagate syntax errors, die on resource errors?
64 * continuation lines, both explicit and implicit - done?
65 * maybe change charmap[] to use 2-bit entries
67 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
70 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
71 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
72 //#include "applet_tables.h" doesn't work
74 /* #include <dmalloc.h> */
79 #define HUSH_VER_STR "0.92"
81 #if defined SINGLE_APPLET_MAIN
82 /* STANDALONE does not make sense, and won't compile */
83 #undef CONFIG_FEATURE_SH_STANDALONE
84 #undef ENABLE_FEATURE_SH_STANDALONE
85 #undef USE_FEATURE_SH_STANDALONE
86 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87 #define ENABLE_FEATURE_SH_STANDALONE 0
88 #define USE_FEATURE_SH_STANDALONE(...)
89 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
92 #if !BB_MMU && ENABLE_HUSH_TICK
93 //#undef ENABLE_HUSH_TICK
94 //#define ENABLE_HUSH_TICK 0
95 #warning On NOMMU, hush command substitution is dangerous.
96 #warning Dont use it for commands which produce lots of output.
97 #warning For more info see shell/hush.c, generate_stream_from_list().
100 #if !ENABLE_HUSH_INTERACTIVE
101 #undef ENABLE_FEATURE_EDITING
102 #define ENABLE_FEATURE_EDITING 0
103 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
107 /* Do we support ANY keywords? */
108 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
109 #define HAS_KEYWORDS 1
110 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
111 #define IF_HAS_NO_KEYWORDS(...)
113 #define HAS_KEYWORDS 0
114 #define IF_HAS_KEYWORDS(...)
115 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
118 /* Keep unconditionally on for now */
121 #define ENABLE_HUSH_FUNCTIONS 0
124 /* If you comment out one of these below, it will be #defined later
125 * to perform debug printfs to stderr: */
126 #define debug_printf(...) do {} while (0)
127 /* Finer-grained debug switches */
128 #define debug_printf_parse(...) do {} while (0)
129 #define debug_print_tree(a, b) do {} while (0)
130 #define debug_printf_exec(...) do {} while (0)
131 #define debug_printf_env(...) do {} while (0)
132 #define debug_printf_jobs(...) do {} while (0)
133 #define debug_printf_expand(...) do {} while (0)
134 #define debug_printf_glob(...) do {} while (0)
135 #define debug_printf_list(...) do {} while (0)
136 #define debug_printf_subst(...) do {} while (0)
137 #define debug_printf_clean(...) do {} while (0)
140 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
143 #ifndef debug_printf_parse
144 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
147 #ifndef debug_printf_exec
148 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
151 #ifndef debug_printf_env
152 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
155 #ifndef debug_printf_jobs
156 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
162 #ifndef debug_printf_expand
163 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
164 #define DEBUG_EXPAND 1
166 #define DEBUG_EXPAND 0
169 #ifndef debug_printf_glob
170 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
176 #ifndef debug_printf_list
177 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
180 #ifndef debug_printf_subst
181 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
184 #ifndef debug_printf_clean
185 /* broken, of course, but OK for testing */
186 static const char *indenter(int i)
188 static const char blanks[] ALIGN1 =
190 return &blanks[sizeof(blanks) - i - 1];
192 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
193 #define DEBUG_CLEAN 1
197 static void debug_print_strings(const char *prefix, char **vv)
199 fprintf(stderr, "%s:\n", prefix);
201 fprintf(stderr, " '%s'\n", *vv++);
204 #define debug_print_strings(prefix, vv) ((void)0)
208 * Leak hunting. Use hush_leaktool.sh for post-processing.
210 #ifdef FOR_HUSH_LEAKTOOL
211 /* suppress "warning: no previous prototype..." */
212 void *xxmalloc(int lineno, size_t size);
213 void *xxrealloc(int lineno, void *ptr, size_t size);
214 char *xxstrdup(int lineno, const char *str);
215 void xxfree(void *ptr);
216 void *xxmalloc(int lineno, size_t size)
218 void *ptr = xmalloc((size + 0xff) & ~0xff);
219 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
222 void *xxrealloc(int lineno, void *ptr, size_t size)
224 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
225 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
228 char *xxstrdup(int lineno, const char *str)
230 char *ptr = xstrdup(str);
231 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
234 void xxfree(void *ptr)
236 fprintf(stderr, "free %p\n", ptr);
239 #define xmalloc(s) xxmalloc(__LINE__, s)
240 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
241 #define xstrdup(s) xxstrdup(__LINE__, s)
242 #define free(p) xxfree(p)
246 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
248 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
250 #define SPECIAL_VAR_SYMBOL 3
251 #define PARSEFLAG_EXIT_FROM_LOOP 1
253 typedef enum redir_type {
255 REDIRECT_OVERWRITE = 2,
261 /* The descrip member of this structure is only used to make
262 * debugging output pretty */
263 static const struct {
265 signed char default_fd;
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_RDONLY, -1, "<<" },
276 typedef enum pipe_style {
283 typedef enum reserved_style {
292 #if ENABLE_HUSH_LOOPS
299 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
304 /* two pseudo-keywords support contrived "case" syntax: */
305 RES_MATCH , /* "word)" */
306 RES_CASEI , /* "this command is inside CASE" */
313 struct redir_struct {
314 struct redir_struct *next;
315 char *rd_filename; /* filename */
316 int fd; /* file descriptor being redirected */
317 int dup; /* -1, or file descriptor being duplicated */
318 smallint /*enum redir_type*/ rd_type;
322 pid_t pid; /* 0 if exited */
323 int assignment_cnt; /* how many argv[i] are assignments? */
324 smallint is_stopped; /* is the command currently running? */
325 smallint grp_type; /* GRP_xxx */
326 struct pipe *group; /* if non-NULL, this "prog" is {} group,
327 * subshell, or a compound statement */
328 char **argv; /* command name and arguments */
329 struct redir_struct *redirects; /* I/O redirections */
331 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
332 * and on execution these are substituted with their values.
333 * Substitution can make _several_ words out of one argv[n]!
334 * Example: argv[0]=='.^C*^C.' here: echo .$*.
335 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
338 #define GRP_SUBSHELL 1
339 #if ENABLE_HUSH_FUNCTIONS
340 #define GRP_FUNCTION 2
345 int num_cmds; /* total number of commands in job */
346 int alive_cmds; /* number of commands running (not exited) */
347 int stopped_cmds; /* number of commands alive, but stopped */
349 int jobid; /* job number */
350 pid_t pgrp; /* process group ID for the job */
351 char *cmdtext; /* name of job */
353 struct command *cmds; /* array of commands in pipe */
354 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
355 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
356 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
359 /* This holds pointers to the various results of parsing */
360 struct parse_context {
361 struct command *command;
362 struct pipe *list_head;
364 struct redir_struct *pending_redirect;
367 smallint ctx_inverted; /* "! cmd | cmd" */
369 smallint ctx_dsemicolon; /* ";;" seen */
371 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
372 struct parse_context *stack;
376 /* On program start, environ points to initial environment.
377 * putenv adds new pointers into it, unsetenv removes them.
378 * Neither of these (de)allocates the strings.
379 * setenv allocates new strings in malloc space and does putenv,
380 * and thus setenv is unusable (leaky) for shell's purposes */
381 #define setenv(...) setenv_is_leaky_dont_use()
383 struct variable *next;
384 char *varstr; /* points to "name=" portion */
385 int max_len; /* if > 0, name is part of initial env; else name is malloced */
386 smallint flg_export; /* putenv should be done on this var */
387 smallint flg_read_only;
390 typedef struct o_string {
392 int length; /* position where data is appended */
394 /* Misnomer! it's not "quoting", it's "protection against globbing"!
395 * (by prepending \ to *, ?, [ and to \ too) */
399 smallint has_empty_slot;
400 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
403 MAYBE_ASSIGNMENT = 0,
404 DEFINITELY_ASSIGNMENT = 1,
406 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
408 /* Used for initialization: o_string foo = NULL_O_STRING; */
409 #define NULL_O_STRING { NULL }
411 /* I can almost use ordinary FILE*. Is open_memstream() universally
412 * available? Where is it documented? */
413 typedef struct in_str {
415 /* eof_flag=1: last char in ->p is really an EOF */
416 char eof_flag; /* meaningless if ->p == NULL */
418 #if ENABLE_HUSH_INTERACTIVE
420 smallint promptmode; /* 0: PS1, 1: PS2 */
423 int (*get) (struct in_str *);
424 int (*peek) (struct in_str *);
426 #define i_getch(input) ((input)->get(input))
427 #define i_peek(input) ((input)->peek(input))
431 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
432 CHAR_IFS = 2, /* treated as ordinary if quoted */
433 CHAR_SPECIAL = 3, /* example: $ */
442 /* "Globals" within this file */
443 /* Sorted roughly by size (smaller offsets == smaller code) */
445 #if ENABLE_HUSH_INTERACTIVE
446 /* 'interactive_fd' is a fd# open to ctty, if we have one
447 * _AND_ if we decided to act interactively */
452 #if ENABLE_FEATURE_EDITING
453 line_input_t *line_input_state;
459 pid_t saved_tty_pgrp;
461 struct pipe *job_list;
462 struct pipe *toplevel_list;
463 smallint ctrl_z_flag;
465 #if ENABLE_HUSH_LOOPS
466 smallint flag_break_continue;
469 /* these three support $?, $#, and $1 */
470 smalluint last_return_code;
471 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
472 smalluint global_args_malloced;
473 /* how many non-NULL argv's we have. NB: $# + 1 */
476 #if ENABLE_HUSH_LOOPS
477 unsigned depth_break_continue;
478 unsigned depth_of_loop;
482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
483 struct variable shell_ver;
484 #if ENABLE_FEATURE_SH_STANDALONE
485 struct nofork_save_area nofork_save;
488 sigjmp_buf toplevel_jb;
490 unsigned char charmap[256];
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
494 #define G (*ptr_to_globals)
495 /* Not #defining name to G.name - this quickly gets unwieldy
496 * (too many defines). Also, I actually prefer to see when a variable
497 * is global, thus "G." prefix is a useful hint */
498 #define INIT_G() do { \
499 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
503 /* Function prototypes for builtins */
504 static int builtin_cd(char **argv);
505 static int builtin_echo(char **argv);
506 static int builtin_eval(char **argv);
507 static int builtin_exec(char **argv);
508 static int builtin_exit(char **argv);
509 static int builtin_export(char **argv);
511 static int builtin_fg_bg(char **argv);
512 static int builtin_jobs(char **argv);
515 static int builtin_help(char **argv);
517 static int builtin_pwd(char **argv);
518 static int builtin_read(char **argv);
519 static int builtin_test(char **argv);
520 static int builtin_true(char **argv);
521 static int builtin_set(char **argv);
522 static int builtin_set_mode(const char, const char);
523 static int builtin_shift(char **argv);
524 static int builtin_source(char **argv);
525 static int builtin_umask(char **argv);
526 static int builtin_unset(char **argv);
527 static int builtin_wait(char **argv);
528 #if ENABLE_HUSH_LOOPS
529 static int builtin_break(char **argv);
530 static int builtin_continue(char **argv);
532 //static int builtin_not_written(char **argv);
534 /* Table of built-in functions. They can be forked or not, depending on
535 * context: within pipes, they fork. As simple commands, they do not.
536 * When used in non-forking context, they can change global variables
537 * in the parent shell process. If forked, of course they cannot.
538 * For example, 'unset foo | whatever' will parse and run, but foo will
539 * still be set at the end. */
540 struct built_in_command {
542 int (*function)(char **argv);
545 #define BLTIN(cmd, func, help) { cmd, func, help }
547 #define BLTIN(cmd, func, help) { cmd, func }
551 /* For now, echo and test are unconditionally enabled.
552 * Maybe make it configurable? */
553 static const struct built_in_command bltins[] = {
554 BLTIN("." , builtin_source, "Run commands in a file"),
555 BLTIN(":" , builtin_true, "No-op"),
556 BLTIN("[" , builtin_test, "Test condition"),
558 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
560 #if ENABLE_HUSH_LOOPS
561 BLTIN("break" , builtin_break, "Exit from a loop"),
563 BLTIN("cd" , builtin_cd, "Change directory"),
564 #if ENABLE_HUSH_LOOPS
565 BLTIN("continue", builtin_continue, "Start new loop iteration"),
567 BLTIN("echo" , builtin_echo, "Write to stdout"),
568 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
569 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
570 BLTIN("exit" , builtin_exit, "Exit"),
571 BLTIN("export", builtin_export, "Set environment variable"),
573 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
574 BLTIN("jobs" , builtin_jobs, "List active jobs"),
576 BLTIN("pwd" , builtin_pwd, "Print current directory"),
577 BLTIN("read" , builtin_read, "Input environment variable"),
578 // BLTIN("return", builtin_not_written, "Return from a function"),
579 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
580 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
581 // BLTIN("trap" , builtin_not_written, "Trap signals"),
582 BLTIN("test" , builtin_test, "Test condition"),
583 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
584 BLTIN("umask" , builtin_umask, "Set file creation mask"),
585 BLTIN("unset" , builtin_unset, "Unset environment variable"),
586 BLTIN("wait" , builtin_wait, "Wait for process"),
588 BLTIN("help" , builtin_help, "List shell built-in commands"),
594 static void maybe_die(const char *notice, const char *msg)
596 /* Was using fancy stuff:
597 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
598 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
599 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
600 #if ENABLE_HUSH_INTERACTIVE
601 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
603 fp(msg ? "%s: %s" : notice, notice, msg);
606 #define syntax(msg) maybe_die("syntax error", msg);
608 /* Debug -- trick gcc to expand __LINE__ and convert to string */
609 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
610 #define _syntax(msg, line) __syntax(msg, line)
611 #define syntax(msg) _syntax(msg, __LINE__)
614 static int glob_needed(const char *s)
619 if (*s == '*' || *s == '[' || *s == '?')
626 static int is_assignment(const char *s)
628 if (!s || !(isalpha(*s) || *s == '_'))
631 while (isalnum(*s) || *s == '_')
636 /* Replace each \x with x in place, return ptr past NUL. */
637 static char *unbackslash(char *src)
643 if ((*dst++ = *src++) == '\0')
649 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
670 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
671 v[count1 + count2] = NULL;
674 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
678 static char **add_string_to_strings(char **strings, char *add)
683 return add_strings_to_strings(strings, v, /*dup:*/ 0);
686 static void putenv_all(char **strings)
691 debug_printf_env("putenv '%s'\n", *strings);
696 static char **putenv_all_and_save_old(char **strings)
706 eq = strchr(*strings, '=');
709 v = getenv(*strings);
712 /* v points to VAL in VAR=VAL, go back to VAR */
713 v -= (eq - *strings) + 1;
714 old = add_string_to_strings(old, v);
723 static void free_strings_and_unsetenv(char **strings, int unset)
733 debug_printf_env("unsetenv '%s'\n", *v);
741 static void free_strings(char **strings)
743 free_strings_and_unsetenv(strings, 0);
747 /* Signals are grouped, we handle them in batches */
748 static void set_misc_sighandler(void (*handler)(int))
759 static void set_fatal_sighandler(void (*handler)(int))
768 /* bash 3.2 seems to handle these just like 'fatal' ones */
774 static void set_jobctrl_sighandler(void (*handler)(int))
782 /* SIGCHLD is special and handled separately */
784 static void set_every_sighandler(void (*handler)(int))
786 set_fatal_sighandler(handler);
787 set_jobctrl_sighandler(handler);
788 set_misc_sighandler(handler);
789 signal(SIGCHLD, handler);
792 static void handler_ctrl_c(int sig UNUSED_PARAM)
794 debug_printf_jobs("got sig %d\n", sig);
795 // as usual we can have all kinds of nasty problems with leaked malloc data here
796 siglongjmp(G.toplevel_jb, 1);
799 static void handler_ctrl_z(int sig UNUSED_PARAM)
803 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
806 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
811 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
814 if (!pid) { /* child */
816 die_sleep = 0; /* let nofork's xfuncs die */
818 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
819 set_every_sighandler(SIG_DFL);
820 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
821 debug_printf_jobs("returning in child\n");
822 /* return to nofork, it will eventually exit now,
823 * not return back to shell */
827 /* finish filling up pipe info */
828 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
829 G.toplevel_list->cmds[0].pid = pid;
830 /* parent needs to longjmp out of running nofork.
831 * we will "return" exitcode 0, with child put in background */
832 // as usual we can have all kinds of nasty problems with leaked malloc data here
833 debug_printf_jobs("siglongjmp in parent\n");
834 siglongjmp(G.toplevel_jb, 1);
837 /* Restores tty foreground process group, and exits.
838 * May be called as signal handler for fatal signal
839 * (will faithfully resend signal to itself, producing correct exit state)
840 * or called directly with -EXITCODE.
841 * We also call it if xfunc is exiting. */
842 static void sigexit(int sig) NORETURN;
843 static void sigexit(int sig)
845 /* Disable all signals: job control, SIGPIPE, etc. */
846 sigprocmask_allsigs(SIG_BLOCK);
848 #if ENABLE_HUSH_INTERACTIVE
849 if (G.interactive_fd)
850 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
853 /* Not a signal, just exit */
857 kill_myself_with_sig(sig); /* does not return */
860 /* Restores tty foreground process group, and exits. */
861 static void hush_exit(int exitcode) NORETURN;
862 static void hush_exit(int exitcode)
864 fflush(NULL); /* flush all streams */
865 sigexit(- (exitcode & 0xff));
870 #define set_fatal_sighandler(handler) ((void)0)
871 #define set_jobctrl_sighandler(handler) ((void)0)
872 #define hush_exit(e) exit(e)
877 static const char *set_cwd(void)
879 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
880 * we must not try to free(bb_msg_unknown) */
881 if (G.cwd == bb_msg_unknown)
883 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
885 G.cwd = bb_msg_unknown;
890 /* Get/check local shell variables */
891 static struct variable *get_local_var(const char *name)
893 struct variable *cur;
899 for (cur = G.top_var; cur; cur = cur->next) {
900 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
906 /* Basically useful version until someone wants to get fancier,
907 * see the bash man page under "Parameter Expansion" */
908 static const char *lookup_param(const char *src)
910 struct variable *var = get_local_var(src);
912 return strchr(var->varstr, '=') + 1;
916 /* str holds "NAME=VAL" and is expected to be malloced.
917 * We take ownership of it.
918 * flg_export is used by:
921 * -1: if NAME is set, leave export status alone
922 * if NAME is not set, do not export
924 static int set_local_var(char *str, int flg_export)
926 struct variable *cur;
930 value = strchr(str, '=');
931 if (!value) { /* not expected to ever happen? */
936 name_len = value - str + 1; /* including '=' */
937 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
939 if (strncmp(cur->varstr, str, name_len) != 0) {
941 /* Bail out. Note that now cur points
942 * to last var in linked list */
948 /* We found an existing var with this name */
950 if (cur->flg_read_only) {
951 bb_error_msg("%s: readonly variable", str);
955 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
956 unsetenv(str); /* just in case */
958 if (strcmp(cur->varstr, str) == 0) {
963 if (cur->max_len >= strlen(str)) {
964 /* This one is from startup env, reuse space */
965 strcpy(cur->varstr, str);
968 /* max_len == 0 signifies "malloced" var, which we can
969 * (and has to) free */
973 goto set_str_and_exp;
976 /* Not found - create next variable struct */
977 cur->next = xzalloc(sizeof(*cur));
985 if (cur->flg_export) {
986 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
987 return putenv(cur->varstr);
992 static void unset_local_var(const char *name)
994 struct variable *cur;
995 struct variable *prev = prev; /* for gcc */
1000 name_len = strlen(name);
1003 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1004 if (cur->flg_read_only) {
1005 bb_error_msg("%s: readonly variable", name);
1008 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1009 * is ro, and we cannot reach this code on the 1st pass */
1010 prev->next = cur->next;
1011 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1012 bb_unsetenv(cur->varstr);
1027 static int static_get(struct in_str *i)
1030 if (ch == '\0') return EOF;
1034 static int static_peek(struct in_str *i)
1039 #if ENABLE_HUSH_INTERACTIVE
1041 static void cmdedit_set_initial_prompt(void)
1043 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1044 G.PS1 = getenv("PS1");
1051 static const char* setup_prompt_string(int promptmode)
1053 const char *prompt_str;
1054 debug_printf("setup_prompt_string %d ", promptmode);
1055 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1056 /* Set up the prompt */
1057 if (promptmode == 0) { /* PS1 */
1059 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1064 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1065 debug_printf("result '%s'\n", prompt_str);
1069 static void get_user_input(struct in_str *i)
1072 const char *prompt_str;
1074 prompt_str = setup_prompt_string(i->promptmode);
1075 #if ENABLE_FEATURE_EDITING
1076 /* Enable command line editing only while a command line
1077 * is actually being read */
1079 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1080 } while (r == 0); /* repeat if Ctrl-C */
1081 i->eof_flag = (r < 0);
1082 if (i->eof_flag) { /* EOF/error detected */
1083 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1084 G.user_input_buf[1] = '\0';
1087 fputs(prompt_str, stdout);
1089 G.user_input_buf[0] = r = fgetc(i->file);
1090 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1091 i->eof_flag = (r == EOF);
1093 i->p = G.user_input_buf;
1096 #endif /* INTERACTIVE */
1098 /* This is the magic location that prints prompts
1099 * and gets data back from the user */
1100 static int file_get(struct in_str *i)
1104 /* If there is data waiting, eat it up */
1105 if (i->p && *i->p) {
1106 #if ENABLE_HUSH_INTERACTIVE
1110 if (i->eof_flag && !*i->p)
1113 /* need to double check i->file because we might be doing something
1114 * more complicated by now, like sourcing or substituting. */
1115 #if ENABLE_HUSH_INTERACTIVE
1116 if (G.interactive_fd && i->promptme && i->file == stdin) {
1119 } while (!*i->p); /* need non-empty line */
1120 i->promptmode = 1; /* PS2 */
1125 ch = fgetc(i->file);
1127 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1128 #if ENABLE_HUSH_INTERACTIVE
1135 /* All the callers guarantee this routine will never be
1136 * used right after a newline, so prompting is not needed.
1138 static int file_peek(struct in_str *i)
1141 if (i->p && *i->p) {
1142 if (i->eof_flag && !i->p[1])
1146 ch = fgetc(i->file);
1147 i->eof_flag = (ch == EOF);
1148 i->peek_buf[0] = ch;
1149 i->peek_buf[1] = '\0';
1151 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1155 static void setup_file_in_str(struct in_str *i, FILE *f)
1157 i->peek = file_peek;
1159 #if ENABLE_HUSH_INTERACTIVE
1161 i->promptmode = 0; /* PS1 */
1167 static void setup_string_in_str(struct in_str *i, const char *s)
1169 i->peek = static_peek;
1170 i->get = static_get;
1171 #if ENABLE_HUSH_INTERACTIVE
1173 i->promptmode = 0; /* PS1 */
1183 #define B_CHUNK (32 * sizeof(char*))
1185 static void o_reset(o_string *o)
1193 static void o_free(o_string *o)
1196 memset(o, 0, sizeof(*o));
1199 static void o_grow_by(o_string *o, int len)
1201 if (o->length + len > o->maxlen) {
1202 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1203 o->data = xrealloc(o->data, 1 + o->maxlen);
1207 static void o_addchr(o_string *o, int ch)
1209 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1211 o->data[o->length] = ch;
1213 o->data[o->length] = '\0';
1216 static void o_addstr(o_string *o, const char *str, int len)
1219 memcpy(&o->data[o->length], str, len);
1221 o->data[o->length] = '\0';
1224 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1229 && (*str != '*' && *str != '?' && *str != '[')
1237 /* My analysis of quoting semantics tells me that state information
1238 * is associated with a destination, not a source.
1240 static void o_addqchr(o_string *o, int ch)
1243 char *found = strchr("*?[\\", ch);
1248 o->data[o->length] = '\\';
1251 o->data[o->length] = ch;
1253 o->data[o->length] = '\0';
1256 static void o_addQchr(o_string *o, int ch)
1259 if (o->o_quote && strchr("*?[\\", ch)) {
1261 o->data[o->length] = '\\';
1265 o->data[o->length] = ch;
1267 o->data[o->length] = '\0';
1270 static void o_addQstr(o_string *o, const char *str, int len)
1273 o_addstr(o, str, len);
1279 int ordinary_cnt = strcspn(str, "*?[\\");
1280 if (ordinary_cnt > len) /* paranoia */
1282 o_addstr(o, str, ordinary_cnt);
1283 if (ordinary_cnt == len)
1285 str += ordinary_cnt;
1286 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1290 if (ch) { /* it is necessarily one of "*?[\\" */
1292 o->data[o->length] = '\\';
1296 o->data[o->length] = ch;
1298 o->data[o->length] = '\0';
1302 /* A special kind of o_string for $VAR and `cmd` expansion.
1303 * It contains char* list[] at the beginning, which is grown in 16 element
1304 * increments. Actual string data starts at the next multiple of 16 * (char*).
1305 * list[i] contains an INDEX (int!) into this string data.
1306 * It means that if list[] needs to grow, data needs to be moved higher up
1307 * but list[i]'s need not be modified.
1308 * NB: remembering how many list[i]'s you have there is crucial.
1309 * o_finalize_list() operation post-processes this structure - calculates
1310 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1312 #if DEBUG_EXPAND || DEBUG_GLOB
1313 static void debug_print_list(const char *prefix, o_string *o, int n)
1315 char **list = (char**)o->data;
1316 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1318 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1319 prefix, list, n, string_start, o->length, o->maxlen);
1321 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1322 o->data + (int)list[i] + string_start,
1323 o->data + (int)list[i] + string_start);
1327 const char *p = o->data + (int)list[n - 1] + string_start;
1328 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
1332 #define debug_print_list(prefix, o, n) ((void)0)
1335 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1336 * in list[n] so that it points past last stored byte so far.
1337 * It returns n+1. */
1338 static int o_save_ptr_helper(o_string *o, int n)
1340 char **list = (char**)o->data;
1344 if (!o->has_empty_slot) {
1345 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1346 string_len = o->length - string_start;
1347 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1348 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1349 /* list[n] points to string_start, make space for 16 more pointers */
1350 o->maxlen += 0x10 * sizeof(list[0]);
1351 o->data = xrealloc(o->data, o->maxlen + 1);
1352 list = (char**)o->data;
1353 memmove(list + n + 0x10, list + n, string_len);
1354 o->length += 0x10 * sizeof(list[0]);
1356 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1358 /* We have empty slot at list[n], reuse without growth */
1359 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1360 string_len = o->length - string_start;
1361 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1362 o->has_empty_slot = 0;
1364 list[n] = (char*)(ptrdiff_t)string_len;
1368 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1369 static int o_get_last_ptr(o_string *o, int n)
1371 char **list = (char**)o->data;
1372 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1374 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1377 /* o_glob performs globbing on last list[], saving each result
1378 * as a new list[]. */
1379 static int o_glob(o_string *o, int n)
1385 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1387 return o_save_ptr_helper(o, n);
1388 pattern = o->data + o_get_last_ptr(o, n);
1389 debug_printf_glob("glob pattern '%s'\n", pattern);
1390 if (!glob_needed(pattern)) {
1392 o->length = unbackslash(pattern) - o->data;
1393 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1394 return o_save_ptr_helper(o, n);
1397 memset(&globdata, 0, sizeof(globdata));
1398 gr = glob(pattern, 0, NULL, &globdata);
1399 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1400 if (gr == GLOB_NOSPACE)
1401 bb_error_msg_and_die("out of memory during glob");
1402 if (gr == GLOB_NOMATCH) {
1403 globfree(&globdata);
1406 if (gr != 0) { /* GLOB_ABORTED ? */
1407 //TODO: testcase for bad glob pattern behavior
1408 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1410 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1411 char **argv = globdata.gl_pathv;
1412 o->length = pattern - o->data; /* "forget" pattern */
1414 o_addstr(o, *argv, strlen(*argv) + 1);
1415 n = o_save_ptr_helper(o, n);
1421 globfree(&globdata);
1423 debug_print_list("o_glob returning", o, n);
1427 /* If o->o_glob == 1, glob the string so far remembered.
1428 * Otherwise, just finish current list[] and start new */
1429 static int o_save_ptr(o_string *o, int n)
1431 if (o->o_glob) { /* if globbing is requested */
1432 /* If o->has_empty_slot, list[n] was already globbed
1433 * (if it was requested back then when it was filled)
1434 * so don't do that again! */
1435 if (!o->has_empty_slot)
1436 return o_glob(o, n); /* o_save_ptr_helper is inside */
1438 return o_save_ptr_helper(o, n);
1441 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1442 static char **o_finalize_list(o_string *o, int n)
1447 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1449 debug_print_list("finalized", o, n);
1450 debug_printf_expand("finalized n:%d\n", n);
1451 list = (char**)o->data;
1452 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1456 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1462 /* expand_strvec_to_strvec() takes a list of strings, expands
1463 * all variable references within and returns a pointer to
1464 * a list of expanded strings, possibly with larger number
1465 * of strings. (Think VAR="a b"; echo $VAR).
1466 * This new list is allocated as a single malloc block.
1467 * NULL-terminated list of char* pointers is at the beginning of it,
1468 * followed by strings themself.
1469 * Caller can deallocate entire list by single free(list). */
1471 /* Store given string, finalizing the word and starting new one whenever
1472 * we encounter IFS char(s). This is used for expanding variable values.
1473 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1474 static int expand_on_ifs(o_string *output, int n, const char *str)
1477 int word_len = strcspn(str, G.ifs);
1479 if (output->o_quote || !output->o_glob)
1480 o_addQstr(output, str, word_len);
1481 else /* protect backslashes against globbing up :) */
1482 o_addstr_duplicate_backslash(output, str, word_len);
1485 if (!*str) /* EOL - do not finalize word */
1487 o_addchr(output, '\0');
1488 debug_print_list("expand_on_ifs", output, n);
1489 n = o_save_ptr(output, n);
1490 str += strspn(str, G.ifs); /* skip ifs chars */
1492 debug_print_list("expand_on_ifs[1]", output, n);
1496 #if ENABLE_HUSH_TICK
1497 static int process_command_subs(o_string *dest,
1498 struct in_str *input, const char *subst_end);
1501 /* Expand all variable references in given string, adding words to list[]
1502 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1503 * to be filled). This routine is extremely tricky: has to deal with
1504 * variables/parameters with whitespace, $* and $@, and constructs like
1505 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1506 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1508 /* or_mask is either 0 (normal case) or 0x80
1509 * (expansion of right-hand side of assignment == 1-element expand.
1510 * It will also do no globbing, and thus we must not backslash-quote!) */
1512 char first_ch, ored_ch;
1519 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1520 debug_print_list("expand_vars_to_list", output, n);
1521 n = o_save_ptr(output, n);
1522 debug_print_list("expand_vars_to_list[0]", output, n);
1524 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1525 #if ENABLE_HUSH_TICK
1526 o_string subst_result = NULL_O_STRING;
1528 o_addstr(output, arg, p - arg);
1529 debug_print_list("expand_vars_to_list[1]", output, n);
1531 p = strchr(p, SPECIAL_VAR_SYMBOL);
1533 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1534 /* "$@" is special. Even if quoted, it can still
1535 * expand to nothing (not even an empty string) */
1536 if ((first_ch & 0x7f) != '@')
1537 ored_ch |= first_ch;
1539 switch (first_ch & 0x7f) {
1540 /* Highest bit in first_ch indicates that var is double-quoted */
1542 val = utoa(G.root_pid);
1544 case '!': /* bg pid */
1545 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1547 case '?': /* exitcode */
1548 val = utoa(G.last_return_code);
1550 case '#': /* argc */
1551 if (arg[1] != SPECIAL_VAR_SYMBOL)
1552 /* actually, it's a ${#var} */
1554 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1559 if (!G.global_argv[i])
1561 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1562 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1563 smallint sv = output->o_quote;
1564 /* unquoted var's contents should be globbed, so don't quote */
1565 output->o_quote = 0;
1566 while (G.global_argv[i]) {
1567 n = expand_on_ifs(output, n, G.global_argv[i]);
1568 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1569 if (G.global_argv[i++][0] && G.global_argv[i]) {
1570 /* this argv[] is not empty and not last:
1571 * put terminating NUL, start new word */
1572 o_addchr(output, '\0');
1573 debug_print_list("expand_vars_to_list[2]", output, n);
1574 n = o_save_ptr(output, n);
1575 debug_print_list("expand_vars_to_list[3]", output, n);
1578 output->o_quote = sv;
1580 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1581 * and in this case should treat it like '$*' - see 'else...' below */
1582 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1584 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1585 if (++i >= G.global_argc)
1587 o_addchr(output, '\0');
1588 debug_print_list("expand_vars_to_list[4]", output, n);
1589 n = o_save_ptr(output, n);
1591 } else { /* quoted $*: add as one word */
1593 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1594 if (!G.global_argv[++i])
1597 o_addchr(output, G.ifs[0]);
1601 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1602 /* "Empty variable", used to make "" etc to not disappear */
1606 #if ENABLE_HUSH_TICK
1607 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1608 struct in_str input;
1611 //TODO: can we just stuff it into "output" directly?
1612 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1613 setup_string_in_str(&input, arg);
1614 process_command_subs(&subst_result, &input, NULL);
1615 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1616 val = subst_result.data;
1620 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1622 bool exp_len = false, exp_null = false;
1623 char *var = arg, exp_save, exp_op, *exp_word;
1626 arg[0] = first_ch & 0x7f;
1628 /* prepare for expansions */
1629 if (var[0] == '#') {
1630 /* handle length expansion ${#var} */
1634 /* maybe handle parameter expansion */
1635 exp_off = strcspn(var, ":-=+?");
1639 exp_save = var[exp_off];
1640 exp_null = exp_save == ':';
1641 exp_word = var + exp_off;
1642 if (exp_null) ++exp_word;
1643 exp_op = *exp_word++;
1644 var[exp_off] = '\0';
1648 /* lookup the variable in question */
1649 if (isdigit(var[0])) {
1650 /* handle_dollar() should have vetted var for us */
1652 if (i < G.global_argc)
1653 val = G.global_argv[i];
1654 /* else val remains NULL: $N with too big N */
1656 val = lookup_param(var);
1658 /* handle any expansions */
1660 debug_printf_expand("expand: length of '%s' = ", val);
1661 val = utoa(val ? strlen(val) : 0);
1662 debug_printf_expand("%s\n", val);
1663 } else if (exp_off) {
1664 /* we need to do an expansion */
1665 int exp_test = (!val || (exp_null && !val[0]));
1667 exp_test = !exp_test;
1668 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1669 exp_null ? "true" : "false", exp_test);
1672 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1676 if (exp_op == '=') {
1677 if (isdigit(var[0]) || var[0] == '#') {
1678 maybe_die(var, "special vars cannot assign in this way");
1681 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1682 sprintf(new_var, "%s=%s", var, val);
1683 set_local_var(new_var, -1);
1687 var[exp_off] = exp_save;
1692 #if ENABLE_HUSH_TICK
1695 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1696 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1698 /* unquoted var's contents should be globbed, so don't quote */
1699 smallint sv = output->o_quote;
1700 output->o_quote = 0;
1701 n = expand_on_ifs(output, n, val);
1703 output->o_quote = sv;
1705 } else { /* quoted $VAR, val will be appended below */
1706 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1711 o_addQstr(output, val, strlen(val));
1713 /* Do the check to avoid writing to a const string */
1714 if (p && *p != SPECIAL_VAR_SYMBOL)
1715 *p = SPECIAL_VAR_SYMBOL;
1717 #if ENABLE_HUSH_TICK
1718 o_free(&subst_result);
1721 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1724 debug_print_list("expand_vars_to_list[a]", output, n);
1725 /* this part is literal, and it was already pre-quoted
1726 * if needed (much earlier), do not use o_addQstr here! */
1727 o_addstr(output, arg, strlen(arg) + 1);
1728 debug_print_list("expand_vars_to_list[b]", output, n);
1729 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1730 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1733 /* allow to reuse list[n] later without re-growth */
1734 output->has_empty_slot = 1;
1736 o_addchr(output, '\0');
1741 static char **expand_variables(char **argv, int or_mask)
1746 o_string output = NULL_O_STRING;
1748 if (or_mask & 0x100) {
1749 output.o_quote = 1; /* protect against globbing for "$var" */
1750 /* (unquoted $var will temporarily switch it off) */
1757 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1760 debug_print_list("expand_variables", &output, n);
1762 /* output.data (malloced in one block) gets returned in "list" */
1763 list = o_finalize_list(&output, n);
1764 debug_print_strings("expand_variables[1]", list);
1768 static char **expand_strvec_to_strvec(char **argv)
1770 return expand_variables(argv, 0x100);
1773 /* Used for expansion of right hand of assignments */
1774 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1776 static char *expand_string_to_string(const char *str)
1778 char *argv[2], **list;
1780 argv[0] = (char*)str;
1782 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1784 if (!list[0] || list[1])
1785 bb_error_msg_and_die("BUG in varexp2");
1786 /* actually, just move string 2*sizeof(char*) bytes back */
1787 overlapping_strcpy((char*)list, list[0]);
1788 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1792 /* Used for "eval" builtin */
1793 static char* expand_strvec_to_string(char **argv)
1797 list = expand_variables(argv, 0x80);
1798 /* Convert all NULs to spaces */
1803 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1804 bb_error_msg_and_die("BUG in varexp3");
1805 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1809 overlapping_strcpy((char*)list, list[0]);
1810 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1814 static char **expand_assignments(char **argv, int count)
1818 /* Expand assignments into one string each */
1819 for (i = 0; i < count; i++) {
1820 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1826 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1827 * and stderr if they are redirected. */
1828 static int setup_redirects(struct command *prog, int squirrel[])
1831 struct redir_struct *redir;
1833 for (redir = prog->redirects; redir; redir = redir->next) {
1834 if (redir->dup == -1 && redir->rd_filename == NULL) {
1835 /* something went wrong in the parse. Pretend it didn't happen */
1838 if (redir->dup == -1) {
1840 mode = redir_table[redir->rd_type].mode;
1841 //TODO: check redir for names like '\\'
1842 p = expand_string_to_string(redir->rd_filename);
1843 openfd = open_or_warn(p, mode);
1846 /* this could get lost if stderr has been redirected, but
1847 bash and ash both lose it as well (though zsh doesn't!) */
1851 openfd = redir->dup;
1854 if (openfd != redir->fd) {
1855 if (squirrel && redir->fd < 3) {
1856 squirrel[redir->fd] = dup(redir->fd);
1859 //close(openfd); // close(-3) ??!
1861 dup2(openfd, redir->fd);
1862 if (redir->dup == -1)
1870 static void restore_redirects(int squirrel[])
1873 for (i = 0; i < 3; i++) {
1876 /* We simply die on error */
1883 #if !defined(DEBUG_CLEAN)
1884 #define free_pipe_list(head, indent) free_pipe_list(head)
1885 #define free_pipe(pi, indent) free_pipe(pi)
1887 static int free_pipe_list(struct pipe *head, int indent);
1889 /* return code is the exit status of the pipe */
1890 static int free_pipe(struct pipe *pi, int indent)
1893 struct command *command;
1894 struct redir_struct *r, *rnext;
1895 int a, i, ret_code = 0;
1897 if (pi->stopped_cmds > 0)
1899 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1900 for (i = 0; i < pi->num_cmds; i++) {
1901 command = &pi->cmds[i];
1902 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1903 if (command->argv) {
1904 for (a = 0, p = command->argv; *p; a++, p++) {
1905 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1907 free_strings(command->argv);
1908 command->argv = NULL;
1909 } else if (command->group) {
1910 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1911 ret_code = free_pipe_list(command->group, indent+3);
1912 debug_printf_clean("%s end group\n", indenter(indent));
1914 debug_printf_clean("%s (nil)\n", indenter(indent));
1916 for (r = command->redirects; r; r = rnext) {
1917 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1919 /* guard against the case >$FOO, where foo is unset or blank */
1920 if (r->rd_filename) {
1921 debug_printf_clean(" %s\n", r->rd_filename);
1922 free(r->rd_filename);
1923 r->rd_filename = NULL;
1926 debug_printf_clean("&%d\n", r->dup);
1931 command->redirects = NULL;
1933 free(pi->cmds); /* children are an array, they get freed all at once */
1942 static int free_pipe_list(struct pipe *head, int indent)
1944 int rcode = 0; /* if list has no members */
1945 struct pipe *pi, *next;
1947 for (pi = head; pi; pi = next) {
1949 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1951 rcode = free_pipe(pi, indent);
1952 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1954 /*pi->next = NULL;*/
1962 typedef struct nommu_save_t {
1968 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1969 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1970 #define pseudo_exec(nommu_save, command, argv_expanded) \
1971 pseudo_exec(command, argv_expanded)
1974 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1976 * XXX no exit() here. If you don't exec, use _exit instead.
1977 * The at_exit handlers apparently confuse the calling process,
1978 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1979 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
1980 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1984 const struct built_in_command *x;
1986 /* If a variable is assigned in a forest, and nobody listens,
1987 * was it ever really set?
1989 if (!argv[assignment_cnt])
1990 _exit(EXIT_SUCCESS);
1992 new_env = expand_assignments(argv, assignment_cnt);
1994 putenv_all(new_env);
1995 free(new_env); /* optional */
1997 nommu_save->new_env = new_env;
1998 nommu_save->old_env = putenv_all_and_save_old(new_env);
2000 if (argv_expanded) {
2001 argv = argv_expanded;
2003 argv = expand_strvec_to_strvec(argv);
2005 nommu_save->argv = argv;
2010 * Check if the command matches any of the builtins.
2011 * Depending on context, this might be redundant. But it's
2012 * easier to waste a few CPU cycles than it is to figure out
2013 * if this is one of those cases.
2015 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2016 if (strcmp(argv[0], x->cmd) == 0) {
2017 debug_printf_exec("running builtin '%s'\n", argv[0]);
2018 rcode = x->function(argv);
2024 /* Check if the command matches any busybox applets */
2025 #if ENABLE_FEATURE_SH_STANDALONE
2026 if (strchr(argv[0], '/') == NULL) {
2027 int a = find_applet_by_name(argv[0]);
2029 if (APPLET_IS_NOEXEC(a)) {
2030 debug_printf_exec("running applet '%s'\n", argv[0]);
2031 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2032 run_applet_no_and_exit(a, argv);
2034 /* re-exec ourselves with the new arguments */
2035 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2036 execvp(bb_busybox_exec_path, argv);
2037 /* If they called chroot or otherwise made the binary no longer
2038 * executable, fall through */
2043 debug_printf_exec("execing '%s'\n", argv[0]);
2044 execvp(argv[0], argv);
2045 bb_perror_msg("can't exec '%s'", argv[0]);
2046 _exit(EXIT_FAILURE);
2049 static int run_list(struct pipe *pi);
2051 /* Called after [v]fork() in run_pipe()
2053 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
2054 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
2057 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
2059 if (command->group) {
2061 bb_error_msg_and_die("nested lists are not supported on NOMMU");
2064 debug_printf_exec("pseudo_exec: run_list\n");
2065 rcode = run_list(command->group);
2066 /* OK to leak memory by not calling free_pipe_list,
2067 * since this process is about to exit */
2072 /* Can happen. See what bash does with ">foo" by itself. */
2073 debug_printf("trying to pseudo_exec null command\n");
2074 _exit(EXIT_SUCCESS);
2078 static const char *get_cmdtext(struct pipe *pi)
2084 /* This is subtle. ->cmdtext is created only on first backgrounding.
2085 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2086 * On subsequent bg argv is trashed, but we won't use it */
2089 argv = pi->cmds[0].argv;
2090 if (!argv || !argv[0]) {
2091 pi->cmdtext = xzalloc(1);
2096 do len += strlen(*argv) + 1; while (*++argv);
2097 pi->cmdtext = p = xmalloc(len);
2098 argv = pi->cmds[0].argv;
2100 len = strlen(*argv);
2101 memcpy(p, *argv, len);
2109 static void insert_bg_job(struct pipe *pi)
2111 struct pipe *thejob;
2114 /* Linear search for the ID of the job to use */
2116 for (thejob = G.job_list; thejob; thejob = thejob->next)
2117 if (thejob->jobid >= pi->jobid)
2118 pi->jobid = thejob->jobid + 1;
2120 /* Add thejob to the list of running jobs */
2122 thejob = G.job_list = xmalloc(sizeof(*thejob));
2124 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2126 thejob->next = xmalloc(sizeof(*thejob));
2127 thejob = thejob->next;
2130 /* Physically copy the struct job */
2131 memcpy(thejob, pi, sizeof(struct pipe));
2132 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2133 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2134 for (i = 0; i < pi->num_cmds; i++) {
2135 // TODO: do we really need to have so many fields which are just dead weight
2136 // at execution stage?
2137 thejob->cmds[i].pid = pi->cmds[i].pid;
2138 /* all other fields are not used and stay zero */
2140 thejob->next = NULL;
2141 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2143 /* We don't wait for background thejobs to return -- append it
2144 to the list of backgrounded thejobs and leave it alone */
2145 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2146 G.last_bg_pid = thejob->cmds[0].pid;
2147 G.last_jobid = thejob->jobid;
2150 static void remove_bg_job(struct pipe *pi)
2152 struct pipe *prev_pipe;
2154 if (pi == G.job_list) {
2155 G.job_list = pi->next;
2157 prev_pipe = G.job_list;
2158 while (prev_pipe->next != pi)
2159 prev_pipe = prev_pipe->next;
2160 prev_pipe->next = pi->next;
2163 G.last_jobid = G.job_list->jobid;
2168 /* Remove a backgrounded job */
2169 static void delete_finished_bg_job(struct pipe *pi)
2172 pi->stopped_cmds = 0;
2178 /* Check to see if any processes have exited -- if they
2179 * have, figure out why and see if a job has completed */
2180 static int checkjobs(struct pipe* fg_pipe)
2190 attributes = WUNTRACED;
2191 if (fg_pipe == NULL)
2192 attributes |= WNOHANG;
2194 /* Do we do this right?
2195 * bash-3.00# sleep 20 | false
2197 * [3]+ Stopped sleep 20 | false
2198 * bash-3.00# echo $?
2199 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2202 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2203 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2204 // + killall -STOP cat
2207 // TODO: safe_waitpid?
2208 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
2210 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
2212 if (WIFSTOPPED(status))
2213 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2214 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2215 if (WIFSIGNALED(status))
2216 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2217 childpid, WTERMSIG(status), WEXITSTATUS(status));
2218 if (WIFEXITED(status))
2219 debug_printf_jobs("pid %d exited, exitcode %d\n",
2220 childpid, WEXITSTATUS(status));
2222 /* Were we asked to wait for fg pipe? */
2224 for (i = 0; i < fg_pipe->num_cmds; i++) {
2225 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2226 if (fg_pipe->cmds[i].pid != childpid)
2228 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2230 fg_pipe->cmds[i].pid = 0;
2231 fg_pipe->alive_cmds--;
2232 if (i == fg_pipe->num_cmds - 1) {
2233 /* last process gives overall exitstatus */
2234 rcode = WEXITSTATUS(status);
2235 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2238 fg_pipe->cmds[i].is_stopped = 1;
2239 fg_pipe->stopped_cmds++;
2241 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2242 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2243 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2244 /* All processes in fg pipe have exited/stopped */
2246 if (fg_pipe->alive_cmds)
2247 insert_bg_job(fg_pipe);
2251 /* There are still running processes in the fg pipe */
2252 goto wait_more; /* do waitpid again */
2254 /* it wasnt fg_pipe, look for process in bg pipes */
2258 /* We asked to wait for bg or orphaned children */
2259 /* No need to remember exitcode in this case */
2260 for (pi = G.job_list; pi; pi = pi->next) {
2261 for (i = 0; i < pi->num_cmds; i++) {
2262 if (pi->cmds[i].pid == childpid)
2263 goto found_pi_and_prognum;
2266 /* Happens when shell is used as init process (init=/bin/sh) */
2267 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2268 continue; /* do waitpid again */
2270 found_pi_and_prognum:
2273 pi->cmds[i].pid = 0;
2275 if (!pi->alive_cmds) {
2276 printf(JOB_STATUS_FORMAT, pi->jobid,
2277 "Done", pi->cmdtext);
2278 delete_finished_bg_job(pi);
2282 pi->cmds[i].is_stopped = 1;
2286 } /* while (waitpid succeeds)... */
2288 /* wait found no children or failed */
2290 if (childpid && errno != ECHILD)
2291 bb_perror_msg("waitpid");
2296 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2299 int rcode = checkjobs(fg_pipe);
2300 /* Job finished, move the shell to the foreground */
2301 p = getpgid(0); /* pgid of our process */
2302 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2303 tcsetpgrp(G.interactive_fd, p);
2308 /* run_pipe() starts all the jobs, but doesn't wait for anything
2309 * to finish. See checkjobs().
2311 * return code is normally -1, when the caller has to wait for children
2312 * to finish to determine the exit status of the pipe. If the pipe
2313 * is a simple builtin command, however, the action is done by the
2314 * time run_pipe returns, and the exit code is provided as the
2317 * The input of the pipe is always stdin, the output is always
2318 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2319 * because it tries to avoid running the command substitution in
2320 * subshell, when that is in fact necessary. The subshell process
2321 * now has its stdout directed to the input of the appropriate pipe,
2322 * so this routine is noticeably simpler.
2324 * Returns -1 only if started some children. IOW: we have to
2325 * mask out retvals of builtins etc with 0xff!
2327 static int run_pipe(struct pipe *pi)
2331 int pipefds[2]; /* pipefds[0] is for reading */
2332 struct command *command;
2333 char **argv_expanded;
2335 const struct built_in_command *x;
2337 /* it is not always needed, but we aim to smaller code */
2338 int squirrel[] = { -1, -1, -1 };
2340 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
2342 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
2348 pi->stopped_cmds = 0;
2350 /* Check if this is a simple builtin (not part of a pipe).
2351 * Builtins within pipes have to fork anyway, and are handled in
2352 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2354 command = &(pi->cmds[0]);
2356 #if ENABLE_HUSH_FUNCTIONS
2357 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2358 /* We "execute" function definition */
2359 bb_error_msg("here we ought to remember function definition, and go on");
2360 return EXIT_SUCCESS;
2364 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
2365 debug_printf("non-subshell grouping\n");
2366 setup_redirects(command, squirrel);
2367 debug_printf_exec(": run_list\n");
2368 rcode = run_list(command->group) & 0xff;
2369 restore_redirects(squirrel);
2370 debug_printf_exec("run_pipe return %d\n", rcode);
2371 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2375 argv = command->argv;
2376 argv_expanded = NULL;
2378 if (single_and_fg && argv != NULL) {
2379 char **new_env = NULL;
2380 char **old_env = NULL;
2382 i = command->assignment_cnt;
2383 if (i != 0 && argv[i] == NULL) {
2384 /* assignments, but no command: set local environment */
2385 for (i = 0; argv[i] != NULL; i++) {
2386 debug_printf("local environment set: %s\n", argv[i]);
2387 p = expand_string_to_string(argv[i]);
2388 set_local_var(p, 0);
2390 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
2393 /* Expand the rest into (possibly) many strings each */
2394 argv_expanded = expand_strvec_to_strvec(argv + i);
2396 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2397 if (strcmp(argv_expanded[0], x->cmd) != 0)
2399 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2400 debug_printf("exec with redirects only\n");
2401 setup_redirects(command, NULL);
2402 rcode = EXIT_SUCCESS;
2403 goto clean_up_and_ret1;
2405 debug_printf("builtin inline %s\n", argv_expanded[0]);
2406 /* XXX setup_redirects acts on file descriptors, not FILEs.
2407 * This is perfect for work that comes after exec().
2408 * Is it really safe for inline use? Experimentally,
2409 * things seem to work with glibc. */
2410 setup_redirects(command, squirrel);
2411 new_env = expand_assignments(argv, command->assignment_cnt);
2412 old_env = putenv_all_and_save_old(new_env);
2413 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2414 rcode = x->function(argv_expanded) & 0xff;
2415 #if ENABLE_FEATURE_SH_STANDALONE
2418 restore_redirects(squirrel);
2419 free_strings_and_unsetenv(new_env, 1);
2420 putenv_all(old_env);
2421 free(old_env); /* not free_strings()! */
2423 free(argv_expanded);
2424 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2425 debug_printf_exec("run_pipe return %d\n", rcode);
2428 #if ENABLE_FEATURE_SH_STANDALONE
2429 i = find_applet_by_name(argv_expanded[0]);
2430 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2431 setup_redirects(command, squirrel);
2432 save_nofork_data(&G.nofork_save);
2433 new_env = expand_assignments(argv, command->assignment_cnt);
2434 old_env = putenv_all_and_save_old(new_env);
2435 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2436 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2437 goto clean_up_and_ret;
2442 /* NB: argv_expanded may already be created, and that
2443 * might include `cmd` runs! Do not rerun it! We *must*
2444 * use argv_expanded if it's non-NULL */
2446 /* Disable job control signals for shell (parent) and
2447 * for initial child code after fork */
2448 set_jobctrl_sighandler(SIG_IGN);
2450 /* Going to fork a child per each pipe member */
2454 for (i = 0; i < pi->num_cmds; i++) {
2456 volatile nommu_save_t nommu_save;
2457 nommu_save.new_env = NULL;
2458 nommu_save.old_env = NULL;
2459 nommu_save.argv = NULL;
2461 command = &(pi->cmds[i]);
2462 if (command->argv) {
2463 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
2465 debug_printf_exec(": pipe member with no argv\n");
2467 /* pipes are inserted between pairs of commands */
2470 if ((i + 1) < pi->num_cmds)
2473 command->pid = BB_MMU ? fork() : vfork();
2474 if (!command->pid) { /* child */
2475 if (ENABLE_HUSH_JOB)
2476 die_sleep = 0; /* let nofork's xfuncs die */
2478 /* Every child adds itself to new process group
2479 * with pgid == pid_of_first_child_in_pipe */
2480 if (G.run_list_level == 1 && G.interactive_fd) {
2482 /* Don't do pgrp restore anymore on fatal signals */
2483 set_fatal_sighandler(SIG_DFL);
2485 if (pgrp < 0) /* true for 1st process only */
2487 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2488 /* We do it in *every* child, not just first,
2490 tcsetpgrp(G.interactive_fd, pgrp);
2494 xmove_fd(nextin, 0);
2495 xmove_fd(pipefds[1], 1); /* write end */
2497 close(pipefds[0]); /* read end */
2498 /* Like bash, explicit redirects override pipes,
2499 * and the pipe fd is available for dup'ing. */
2500 setup_redirects(command, NULL);
2502 /* Restore default handlers just prior to exec */
2503 set_jobctrl_sighandler(SIG_DFL);
2504 set_misc_sighandler(SIG_DFL);
2505 signal(SIGCHLD, SIG_DFL);
2506 /* Stores to nommu_save list of env vars putenv'ed
2507 * (NOMMU, on MMU we don't need that) */
2508 /* cast away volatility... */
2509 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2510 /* pseudo_exec() does not return */
2514 /* Clean up after vforked child */
2515 free(nommu_save.argv);
2516 free_strings_and_unsetenv(nommu_save.new_env, 1);
2517 putenv_all(nommu_save.old_env);
2519 free(argv_expanded);
2520 argv_expanded = NULL;
2521 if (command->pid < 0) { /* [v]fork failed */
2522 /* Clearly indicate, was it fork or vfork */
2523 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2527 /* Second and next children need to know pid of first one */
2529 pi->pgrp = command->pid;
2535 if ((i + 1) < pi->num_cmds)
2536 close(pipefds[1]); /* write end */
2537 /* Pass read (output) pipe end to next iteration */
2538 nextin = pipefds[0];
2541 if (!pi->alive_cmds) {
2542 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2546 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2550 #ifndef debug_print_tree
2551 static void debug_print_tree(struct pipe *pi, int lvl)
2553 static const char *const PIPE[] = {
2559 static const char *RES[] = {
2560 [RES_NONE ] = "NONE" ,
2563 [RES_THEN ] = "THEN" ,
2564 [RES_ELIF ] = "ELIF" ,
2565 [RES_ELSE ] = "ELSE" ,
2568 #if ENABLE_HUSH_LOOPS
2569 [RES_FOR ] = "FOR" ,
2570 [RES_WHILE] = "WHILE",
2571 [RES_UNTIL] = "UNTIL",
2573 [RES_DONE ] = "DONE" ,
2575 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2578 #if ENABLE_HUSH_CASE
2579 [RES_CASE ] = "CASE" ,
2580 [RES_MATCH] = "MATCH",
2581 [RES_CASEI] = "CASEI",
2582 [RES_ESAC ] = "ESAC" ,
2584 [RES_XXXX ] = "XXXX" ,
2585 [RES_SNTX ] = "SNTX" ,
2587 static const char *const GRPTYPE[] = {
2590 #if ENABLE_HUSH_FUNCTIONS
2599 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2600 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2602 while (prn < pi->num_cmds) {
2603 struct command *command = &pi->cmds[prn];
2604 char **argv = command->argv;
2606 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2607 if (command->group) {
2608 fprintf(stderr, " group %s: (argv=%p)\n",
2609 GRPTYPE[command->grp_type],
2611 debug_print_tree(command->group, lvl+1);
2615 if (argv) while (*argv) {
2616 fprintf(stderr, " '%s'", *argv);
2619 fprintf(stderr, "\n");
2628 /* NB: called by pseudo_exec, and therefore must not modify any
2629 * global data until exec/_exit (we can be a child after vfork!) */
2630 static int run_list(struct pipe *pi)
2632 #if ENABLE_HUSH_CASE
2633 char *case_word = NULL;
2635 #if ENABLE_HUSH_LOOPS
2636 struct pipe *loop_top = NULL;
2637 char *for_varname = NULL;
2638 char **for_lcur = NULL;
2639 char **for_list = NULL;
2641 smallint flag_skip = 1;
2642 smalluint rcode = 0; /* probably just for compiler */
2643 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2644 smalluint cond_code = 0;
2646 enum { cond_code = 0, };
2648 /*enum reserved_style*/ smallint rword = RES_NONE;
2649 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2651 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2653 #if ENABLE_HUSH_LOOPS
2654 /* Check syntax for "for" */
2655 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2656 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2658 /* current word is FOR or IN (BOLD in comments below) */
2659 if (cpipe->next == NULL) {
2660 syntax("malformed for");
2661 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2664 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2665 if (cpipe->next->res_word == RES_DO)
2667 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2668 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2669 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2671 syntax("malformed for");
2672 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2678 /* Past this point, all code paths should jump to ret: label
2679 * in order to return, no direct "return" statements please.
2680 * This helps to ensure that no memory is leaked. */
2683 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2684 * We are saving state before entering outermost list ("while...done")
2685 * so that ctrl-Z will correctly background _entire_ outermost list,
2686 * not just a part of it (like "sleep 1 | exit 2") */
2687 if (++G.run_list_level == 1 && G.interactive_fd) {
2688 if (sigsetjmp(G.toplevel_jb, 1)) {
2689 /* ctrl-Z forked and we are parent; or ctrl-C.
2690 * Sighandler has longjmped us here */
2691 signal(SIGINT, SIG_IGN);
2692 signal(SIGTSTP, SIG_IGN);
2693 /* Restore level (we can be coming from deep inside
2695 G.run_list_level = 1;
2696 #if ENABLE_FEATURE_SH_STANDALONE
2697 if (G.nofork_save.saved) { /* if save area is valid */
2698 debug_printf_jobs("exiting nofork early\n");
2699 restore_nofork_data(&G.nofork_save);
2702 if (G.ctrl_z_flag) {
2703 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2704 * Remember this child as background job */
2707 /* ctrl-C. We just stop doing whatever we were doing */
2710 USE_HUSH_LOOPS(loop_top = NULL;)
2711 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2715 /* ctrl-Z handler will store pid etc in pi */
2716 G.toplevel_list = pi;
2718 #if ENABLE_FEATURE_SH_STANDALONE
2719 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2721 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2722 signal(SIGINT, handler_ctrl_c);
2726 /* Go through list of pipes, (maybe) executing them. */
2727 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2728 IF_HAS_KEYWORDS(rword = pi->res_word;)
2729 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2730 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2731 rword, cond_code, skip_more_for_this_rword);
2732 #if ENABLE_HUSH_LOOPS
2733 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2734 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2736 /* start of a loop: remember where loop starts */
2741 if (rword == skip_more_for_this_rword && flag_skip) {
2742 if (pi->followup == PIPE_SEQ)
2744 /* it is "<false> && CMD" or "<true> || CMD"
2745 * and we should not execute CMD */
2749 skip_more_for_this_rword = RES_XXXX;
2752 if (rword == RES_THEN) {
2753 /* "if <false> THEN cmd": skip cmd */
2757 if (rword == RES_ELSE || rword == RES_ELIF) {
2758 /* "if <true> then ... ELSE/ELIF cmd":
2759 * skip cmd and all following ones */
2764 #if ENABLE_HUSH_LOOPS
2765 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2767 /* first loop through for */
2769 static const char encoded_dollar_at[] ALIGN1 = {
2770 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2771 }; /* encoded representation of "$@" */
2772 static const char *const encoded_dollar_at_argv[] = {
2773 encoded_dollar_at, NULL
2774 }; /* argv list with one element: "$@" */
2777 vals = (char**)encoded_dollar_at_argv;
2778 if (pi->next->res_word == RES_IN) {
2779 /* if no variable values after "in" we skip "for" */
2780 if (!pi->next->cmds[0].argv)
2782 vals = pi->next->cmds[0].argv;
2783 } /* else: "for var; do..." -> assume "$@" list */
2784 /* create list of variable values */
2785 debug_print_strings("for_list made from", vals);
2786 for_list = expand_strvec_to_strvec(vals);
2787 for_lcur = for_list;
2788 debug_print_strings("for_list", for_list);
2789 for_varname = pi->cmds[0].argv[0];
2790 pi->cmds[0].argv[0] = NULL;
2792 free(pi->cmds[0].argv[0]);
2794 /* "for" loop is over, clean up */
2798 pi->cmds[0].argv[0] = for_varname;
2801 /* insert next value from for_lcur */
2802 //TODO: does it need escaping?
2803 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2804 pi->cmds[0].assignment_cnt = 1;
2806 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2808 if (rword == RES_DONE) {
2809 continue; /* "done" has no cmds too */
2812 #if ENABLE_HUSH_CASE
2813 if (rword == RES_CASE) {
2814 case_word = expand_strvec_to_string(pi->cmds->argv);
2817 if (rword == RES_MATCH) {
2820 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2822 /* all prev words didn't match, does this one match? */
2823 argv = pi->cmds->argv;
2825 char *pattern = expand_string_to_string(*argv);
2826 /* TODO: which FNM_xxx flags to use? */
2827 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2829 if (cond_code == 0) { /* match! we will execute this branch */
2830 free(case_word); /* make future "word)" stop */
2838 if (rword == RES_CASEI) { /* inside of a case branch */
2840 continue; /* not matched yet, skip this pipe */
2843 if (pi->num_cmds == 0)
2844 goto check_jobs_and_continue;
2846 /* After analyzing all keywords and conditions, we decided
2847 * to execute this pipe. NB: has to do checkjobs(NULL)
2848 * after run_pipe() to collect any background children,
2849 * even if list execution is to be stopped. */
2850 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2853 #if ENABLE_HUSH_LOOPS
2854 G.flag_break_continue = 0;
2856 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2858 /* we only ran a builtin: rcode is already known
2859 * and we don't need to wait for anything. */
2860 #if ENABLE_HUSH_LOOPS
2861 /* was it "break" or "continue"? */
2862 if (G.flag_break_continue) {
2863 smallint fbc = G.flag_break_continue;
2864 /* we might fall into outer *loop*,
2865 * don't want to break it too */
2867 G.depth_break_continue--;
2868 if (G.depth_break_continue == 0)
2869 G.flag_break_continue = 0;
2870 /* else: e.g. "continue 2" should *break* once, *then* continue */
2871 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2872 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2873 goto check_jobs_and_break;
2874 /* "continue": simulate end of loop */
2879 } else if (pi->followup == PIPE_BG) {
2880 /* what does bash do with attempts to background builtins? */
2881 /* even bash 3.2 doesn't do that well with nested bg:
2882 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2883 * I'm NOT treating inner &'s as jobs */
2885 if (G.run_list_level == 1)
2888 rcode = 0; /* EXIT_SUCCESS */
2891 if (G.run_list_level == 1 && G.interactive_fd) {
2892 /* waits for completion, then fg's main shell */
2893 rcode = checkjobs_and_fg_shell(pi);
2894 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2897 { /* this one just waits for completion */
2898 rcode = checkjobs(pi);
2899 debug_printf_exec(": checkjobs returned %d\n", rcode);
2903 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2904 G.last_return_code = rcode;
2906 /* Analyze how result affects subsequent commands */
2908 if (rword == RES_IF || rword == RES_ELIF)
2911 #if ENABLE_HUSH_LOOPS
2912 if (rword == RES_WHILE) {
2914 rcode = 0; /* "while false; do...done" - exitcode 0 */
2915 goto check_jobs_and_break;
2918 if (rword == RES_UNTIL) {
2920 check_jobs_and_break:
2926 if ((rcode == 0 && pi->followup == PIPE_OR)
2927 || (rcode != 0 && pi->followup == PIPE_AND)
2929 skip_more_for_this_rword = rword;
2932 check_jobs_and_continue:
2937 if (G.ctrl_z_flag) {
2938 /* ctrl-Z forked somewhere in the past, we are the child,
2939 * and now we completed running the list. Exit. */
2944 if (!--G.run_list_level && G.interactive_fd) {
2945 signal(SIGTSTP, SIG_IGN);
2946 signal(SIGINT, SIG_IGN);
2949 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2950 #if ENABLE_HUSH_LOOPS
2955 #if ENABLE_HUSH_CASE
2961 /* Select which version we will use */
2962 static int run_and_free_list(struct pipe *pi)
2965 debug_printf_exec("run_and_free_list entered\n");
2967 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2968 rcode = run_list(pi);
2970 /* free_pipe_list has the side effect of clearing memory.
2971 * In the long run that function can be merged with run_list,
2972 * but doing that now would hobble the debugging effort. */
2973 free_pipe_list(pi, /* indent: */ 0);
2974 debug_printf_exec("run_and_free_list return %d\n", rcode);
2979 /* Peek ahead in the in_str to find out if we have a "&n" construct,
2980 * as in "2>&1", that represents duplicating a file descriptor.
2981 * Return either -2 (syntax error), -1 (no &), or the number found.
2983 static int redirect_dup_num(struct in_str *input)
2985 int ch, d = 0, ok = 0;
2987 if (ch != '&') return -1;
2989 i_getch(input); /* get the & */
2993 return -3; /* "-" represents "close me" */
2995 while (isdigit(ch)) {
2996 d = d*10 + (ch-'0');
3003 bb_error_msg("ambiguous redirect");
3007 /* The src parameter allows us to peek forward to a possible &n syntax
3008 * for file descriptor duplication, e.g., "2>&1".
3009 * Return code is 0 normally, 1 if a syntax error is detected in src.
3010 * Resource errors (in xmalloc) cause the process to exit */
3011 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
3012 struct in_str *input)
3014 struct command *command = ctx->command;
3015 struct redir_struct *redir = command->redirects;
3016 struct redir_struct *last_redir = NULL;
3018 /* Create a new redir_struct and drop it onto the end of the linked list */
3021 redir = redir->next;
3023 redir = xzalloc(sizeof(struct redir_struct));
3024 /* redir->next = NULL; */
3025 /* redir->rd_filename = NULL; */
3027 last_redir->next = redir;
3029 command->redirects = redir;
3032 redir->rd_type = style;
3033 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3035 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3037 /* Check for a '2>&1' type redirect */
3038 redir->dup = redirect_dup_num(input);
3039 if (redir->dup == -2)
3040 return 1; /* syntax error */
3041 if (redir->dup != -1) {
3042 /* Erik had a check here that the file descriptor in question
3043 * is legit; I postpone that to "run time"
3044 * A "-" representation of "close me" shows up as a -3 here */
3045 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3047 /* We do _not_ try to open the file that src points to,
3048 * since we need to return and let src be expanded first.
3049 * Set ctx->pending_redirect, so we know what to do at the
3050 * end of the next parsed word. */
3051 ctx->pending_redirect = redir;
3057 static struct pipe *new_pipe(void)
3060 pi = xzalloc(sizeof(struct pipe));
3061 /*pi->followup = 0; - deliberately invalid value */
3062 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3066 /* Command (member of a pipe) is complete. The only possible error here
3067 * is out of memory, in which case xmalloc exits. */
3068 static int done_command(struct parse_context *ctx)
3070 /* The command is really already in the pipe structure, so
3071 * advance the pipe counter and make a new, null command. */
3072 struct pipe *pi = ctx->pipe;
3073 struct command *command = ctx->command;
3076 if (command->group == NULL
3077 && command->argv == NULL
3078 && command->redirects == NULL
3080 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3081 return pi->num_cmds;
3084 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3086 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3089 /* Only real trickiness here is that the uncommitted
3090 * command structure is not counted in pi->num_cmds. */
3091 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3092 command = &pi->cmds[pi->num_cmds];
3093 memset(command, 0, sizeof(*command));
3095 ctx->command = command;
3096 /* but ctx->pipe and ctx->list_head remain unchanged */
3098 return pi->num_cmds; /* used only for 0/nonzero check */
3101 static void done_pipe(struct parse_context *ctx, pipe_style type)
3105 debug_printf_parse("done_pipe entered, followup %d\n", type);
3106 /* Close previous command */
3107 not_null = done_command(ctx);
3108 ctx->pipe->followup = type;
3109 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3110 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3111 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3113 /* Without this check, even just <enter> on command line generates
3114 * tree of three NOPs (!). Which is harmless but annoying.
3115 * IOW: it is safe to do it unconditionally.
3116 * RES_NONE case is for "for a in; do ..." (empty IN set)
3117 * to work, possibly other cases too. */
3118 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3120 debug_printf_parse("done_pipe: adding new pipe: "
3121 "not_null:%d ctx->ctx_res_w:%d\n",
3122 not_null, ctx->ctx_res_w);
3124 ctx->pipe->next = new_p;
3126 ctx->command = NULL; /* needed! */
3127 /* RES_THEN, RES_DO etc are "sticky" -
3128 * they remain set for commands inside if/while.
3129 * This is used to control execution.
3130 * RES_FOR and RES_IN are NOT sticky (needed to support
3131 * cases where variable or value happens to match a keyword):
3133 #if ENABLE_HUSH_LOOPS
3134 if (ctx->ctx_res_w == RES_FOR
3135 || ctx->ctx_res_w == RES_IN)
3136 ctx->ctx_res_w = RES_NONE;
3138 #if ENABLE_HUSH_CASE
3139 if (ctx->ctx_res_w == RES_MATCH)
3140 ctx->ctx_res_w = RES_CASEI;
3142 /* Create the memory for command, roughly:
3143 * ctx->pipe->cmds = new struct command;
3144 * ctx->command = &ctx->pipe->cmds[0];
3148 debug_printf_parse("done_pipe return\n");
3151 static void initialize_context(struct parse_context *ctx)
3153 memset(ctx, 0, sizeof(*ctx));
3154 ctx->pipe = ctx->list_head = new_pipe();
3155 /* Create the memory for command, roughly:
3156 * ctx->pipe->cmds = new struct command;
3157 * ctx->command = &ctx->pipe->cmds[0];
3163 /* If a reserved word is found and processed, parse context is modified
3164 * and 1 is returned.
3165 * Handles if, then, elif, else, fi, for, while, until, do, done.
3166 * case, function, and select are obnoxious, save those for later.
3169 struct reserved_combo {
3172 unsigned char assignment_flag;
3176 FLAG_END = (1 << RES_NONE ),
3178 FLAG_IF = (1 << RES_IF ),
3179 FLAG_THEN = (1 << RES_THEN ),
3180 FLAG_ELIF = (1 << RES_ELIF ),
3181 FLAG_ELSE = (1 << RES_ELSE ),
3182 FLAG_FI = (1 << RES_FI ),
3184 #if ENABLE_HUSH_LOOPS
3185 FLAG_FOR = (1 << RES_FOR ),
3186 FLAG_WHILE = (1 << RES_WHILE),
3187 FLAG_UNTIL = (1 << RES_UNTIL),
3188 FLAG_DO = (1 << RES_DO ),
3189 FLAG_DONE = (1 << RES_DONE ),
3190 FLAG_IN = (1 << RES_IN ),
3192 #if ENABLE_HUSH_CASE
3193 FLAG_MATCH = (1 << RES_MATCH),
3194 FLAG_ESAC = (1 << RES_ESAC ),
3196 FLAG_START = (1 << RES_XXXX ),
3199 static const struct reserved_combo* match_reserved_word(o_string *word)
3201 /* Mostly a list of accepted follow-up reserved words.
3202 * FLAG_END means we are done with the sequence, and are ready
3203 * to turn the compound list into a command.
3204 * FLAG_START means the word must start a new compound list.
3206 static const struct reserved_combo reserved_list[] = {
3208 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3209 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3210 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3211 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3212 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3213 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3215 #if ENABLE_HUSH_LOOPS
3216 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3217 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3218 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3219 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3220 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3221 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3223 #if ENABLE_HUSH_CASE
3224 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3225 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3228 const struct reserved_combo *r;
3230 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3231 if (strcmp(word->data, r->literal) == 0)
3236 static int reserved_word(o_string *word, struct parse_context *ctx)
3238 #if ENABLE_HUSH_CASE
3239 static const struct reserved_combo reserved_match = {
3240 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3243 const struct reserved_combo *r;
3245 r = match_reserved_word(word);
3249 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3250 #if ENABLE_HUSH_CASE
3251 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3252 /* "case word IN ..." - IN part starts first match part */
3253 r = &reserved_match;
3256 if (r->flag == 0) { /* '!' */
3257 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3259 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3261 ctx->ctx_inverted = 1;
3264 if (r->flag & FLAG_START) {
3265 struct parse_context *new;
3266 debug_printf("push stack\n");
3267 new = xmalloc(sizeof(*new));
3268 *new = *ctx; /* physical copy */
3269 initialize_context(ctx);
3271 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3273 ctx->ctx_res_w = RES_SNTX;
3276 ctx->ctx_res_w = r->res;
3277 ctx->old_flag = r->flag;
3278 if (ctx->old_flag & FLAG_END) {
3279 struct parse_context *old;
3280 debug_printf("pop stack\n");
3281 done_pipe(ctx, PIPE_SEQ);
3283 old->command->group = ctx->list_head;
3284 old->command->grp_type = GRP_NORMAL;
3285 *ctx = *old; /* physical copy */
3288 word->o_assignment = r->assignment_flag;
3293 //TODO: many, many callers don't check error from done_word()
3295 /* Word is complete, look at it and update parsing context.
3296 * Normal return is 0. Syntax errors return 1. */
3297 static int done_word(o_string *word, struct parse_context *ctx)
3299 struct command *command = ctx->command;
3301 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3302 if (word->length == 0 && word->nonnull == 0) {
3303 debug_printf_parse("done_word return 0: true null, ignored\n");
3306 /* If this word wasn't an assignment, next ones definitely
3307 * can't be assignments. Even if they look like ones. */
3308 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3309 && word->o_assignment != WORD_IS_KEYWORD
3311 word->o_assignment = NOT_ASSIGNMENT;
3313 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3314 command->assignment_cnt++;
3315 word->o_assignment = MAYBE_ASSIGNMENT;
3318 if (ctx->pending_redirect) {
3319 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3320 * only if run as "bash", not "sh" */
3321 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3322 word->o_assignment = NOT_ASSIGNMENT;
3323 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3325 /* "{ echo foo; } echo bar" - bad */
3326 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3327 if (command->group) {
3329 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3333 #if ENABLE_HUSH_CASE
3334 if (ctx->ctx_dsemicolon
3335 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3337 /* already done when ctx_dsemicolon was set to 1: */
3338 /* ctx->ctx_res_w = RES_MATCH; */
3339 ctx->ctx_dsemicolon = 0;
3343 if (!command->argv /* if it's the first word... */
3344 #if ENABLE_HUSH_LOOPS
3345 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3346 && ctx->ctx_res_w != RES_IN
3349 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3350 if (reserved_word(word, ctx)) {
3352 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3353 return (ctx->ctx_res_w == RES_SNTX);
3357 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3358 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3359 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3360 /* (otherwise it's known to be not empty and is already safe) */
3362 /* exclude "$@" - it can expand to no word despite "" */
3363 char *p = word->data;
3364 while (p[0] == SPECIAL_VAR_SYMBOL
3365 && (p[1] & 0x7f) == '@'
3366 && p[2] == SPECIAL_VAR_SYMBOL
3370 if (p == word->data || p[0] != '\0') {
3371 /* saw no "$@", or not only "$@" but some
3372 * real text is there too */
3373 /* insert "empty variable" reference, this makes
3374 * e.g. "", $empty"" etc to not disappear */
3375 o_addchr(word, SPECIAL_VAR_SYMBOL);
3376 o_addchr(word, SPECIAL_VAR_SYMBOL);
3379 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3380 debug_print_strings("word appended to argv", command->argv);
3384 ctx->pending_redirect = NULL;
3386 #if ENABLE_HUSH_LOOPS
3387 /* Force FOR to have just one word (variable name) */
3388 /* NB: basically, this makes hush see "for v in ..." syntax as if
3389 * as it is "for v; in ...". FOR and IN become two pipe structs
3391 if (ctx->ctx_res_w == RES_FOR) {
3392 //TODO: check that command->argv[0] is a valid variable name!
3393 done_pipe(ctx, PIPE_SEQ);
3396 #if ENABLE_HUSH_CASE
3397 /* Force CASE to have just one word */
3398 if (ctx->ctx_res_w == RES_CASE) {
3399 done_pipe(ctx, PIPE_SEQ);
3402 debug_printf_parse("done_word return 0\n");
3406 /* If a redirect is immediately preceded by a number, that number is
3407 * supposed to tell which file descriptor to redirect. This routine
3408 * looks for such preceding numbers. In an ideal world this routine
3409 * needs to handle all the following classes of redirects...
3410 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3411 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3412 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3413 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3414 * A -1 output from this program means no valid number was found, so the
3415 * caller should use the appropriate default for this redirection.
3417 static int redirect_opt_num(o_string *o)
3423 for (num = 0; num < o->length; num++) {
3424 if (!isdigit(o->data[num])) {
3428 num = atoi(o->data);
3433 static int parse_stream(o_string *dest, struct parse_context *ctx,
3434 struct in_str *input0, const char *end_trigger);
3436 #if ENABLE_HUSH_TICK
3437 static FILE *generate_stream_from_list(struct pipe *head)
3440 int pid, channel[2];
3443 /* *** NOMMU WARNING *** */
3444 /* By using vfork here, we suspend parent till child exits or execs.
3445 * If child will not do it before it fills the pipe, it can block forever
3446 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3448 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3449 * huge=`cat TESTFILE` # will block here forever
3452 pid = BB_MMU ? fork() : vfork();
3454 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3455 if (pid == 0) { /* child */
3456 if (ENABLE_HUSH_JOB)
3457 die_sleep = 0; /* let nofork's xfuncs die */
3458 close(channel[0]); /* NB: close _first_, then move fd! */
3459 xmove_fd(channel[1], 1);
3460 /* Prevent it from trying to handle ctrl-z etc */
3462 G.run_list_level = 1;
3464 /* Process substitution is not considered to be usual
3465 * 'command execution'.
3466 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3467 /* Not needed, we are relying on it being disabled
3468 * everywhere outside actual command execution. */
3469 /*set_jobctrl_sighandler(SIG_IGN);*/
3470 set_misc_sighandler(SIG_DFL);
3471 /* Freeing 'head' here would break NOMMU. */
3472 _exit(run_list(head));
3475 pf = fdopen(channel[0], "r");
3477 /* 'head' is freed by the caller */
3480 /* Return code is exit status of the process that is run. */
3481 static int process_command_subs(o_string *dest,
3482 struct in_str *input,
3483 const char *subst_end)
3485 int retcode, ch, eol_cnt;
3486 o_string result = NULL_O_STRING;
3487 struct parse_context inner;
3489 struct in_str pipe_str;
3491 initialize_context(&inner);
3493 /* Recursion to generate command */
3494 retcode = parse_stream(&result, &inner, input, subst_end);
3496 return retcode; /* syntax error or EOF */
3497 done_word(&result, &inner);
3498 done_pipe(&inner, PIPE_SEQ);
3501 p = generate_stream_from_list(inner.list_head);
3504 close_on_exec_on(fileno(p));
3505 setup_file_in_str(&pipe_str, p);
3507 /* Now send results of command back into original context */
3509 while ((ch = i_getch(&pipe_str)) != EOF) {
3515 o_addchr(dest, '\n');
3518 o_addQchr(dest, ch);
3521 debug_printf("done reading from pipe, pclose()ing\n");
3522 /* This is the step that wait()s for the child. Should be pretty
3523 * safe, since we just read an EOF from its stdout. We could try
3524 * to do better, by using wait(), and keeping track of background jobs
3525 * at the same time. That would be a lot of work, and contrary
3526 * to the KISS philosophy of this program. */
3527 retcode = fclose(p);
3528 free_pipe_list(inner.list_head, /* indent: */ 0);
3529 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3534 static int parse_group(o_string *dest, struct parse_context *ctx,
3535 struct in_str *input, int ch)
3537 /* dest contains characters seen prior to ( or {.
3538 * Typically it's empty, but for functions defs,
3539 * it contains function name (without '()'). */
3541 const char *endch = NULL;
3542 struct parse_context sub;
3543 struct command *command = ctx->command;
3545 debug_printf_parse("parse_group entered\n");
3546 #if ENABLE_HUSH_FUNCTIONS
3547 if (ch == 'F') { /* function definition? */
3548 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3549 //command->fname = dest->data;
3550 command->grp_type = GRP_FUNCTION;
3551 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3552 memset(dest, 0, sizeof(*dest));
3555 if (command->argv /* word [word](... */
3556 || dest->length /* word(... */
3557 || dest->nonnull /* ""(... */
3560 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3563 initialize_context(&sub);
3567 command->grp_type = GRP_SUBSHELL;
3569 rcode = parse_stream(dest, &sub, input, endch);
3571 done_word(dest, &sub); /* finish off the final word in the subcontext */
3572 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3573 command->group = sub.list_head;
3575 debug_printf_parse("parse_group return %d\n", rcode);
3577 /* command remains "open", available for possible redirects */
3580 #if ENABLE_HUSH_TICK
3581 /* Subroutines for copying $(...) and `...` things */
3582 static void add_till_backquote(o_string *dest, struct in_str *input);
3584 static void add_till_single_quote(o_string *dest, struct in_str *input)
3587 int ch = i_getch(input);
3595 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3596 static void add_till_double_quote(o_string *dest, struct in_str *input)
3599 int ch = i_getch(input);
3602 if (ch == '\\') { /* \x. Copy both chars. */
3604 ch = i_getch(input);
3610 add_till_backquote(dest, input);
3614 //if (ch == '$') ...
3617 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3619 * "Within the backquoted style of command substitution, backslash
3620 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3621 * The search for the matching backquote shall be satisfied by the first
3622 * backquote found without a preceding backslash; during this search,
3623 * if a non-escaped backquote is encountered within a shell comment,
3624 * a here-document, an embedded command substitution of the $(command)
3625 * form, or a quoted string, undefined results occur. A single-quoted
3626 * or double-quoted string that begins, but does not end, within the
3627 * "`...`" sequence produces undefined results."
3629 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3631 static void add_till_backquote(o_string *dest, struct in_str *input)
3634 int ch = i_getch(input);
3637 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3638 int ch2 = i_getch(input);
3639 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3648 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3649 * quoting and nested ()s.
3650 * "With the $(command) style of command substitution, all characters
3651 * following the open parenthesis to the matching closing parenthesis
3652 * constitute the command. Any valid shell script can be used for command,
3653 * except a script consisting solely of redirections which produces
3654 * unspecified results."
3656 * echo $(echo '(TEST)' BEST) (TEST) BEST
3657 * echo $(echo 'TEST)' BEST) TEST) BEST
3658 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3660 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3664 int ch = i_getch(input);
3674 add_till_single_quote(dest, input);
3679 add_till_double_quote(dest, input);
3683 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3684 ch = i_getch(input);
3692 #endif /* ENABLE_HUSH_TICK */
3694 /* Return code: 0 for OK, 1 for syntax error */
3695 static int handle_dollar(o_string *dest, struct in_str *input)
3698 int ch = i_peek(input); /* first character after the $ */
3699 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3701 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3707 debug_printf_parse(": '%c'\n", ch);
3708 o_addchr(dest, ch | quote_mask);
3711 if (!isalnum(ch) && ch != '_')
3715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3716 } else if (isdigit(ch)) {
3719 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3720 debug_printf_parse(": '%c'\n", ch);
3721 o_addchr(dest, ch | quote_mask);
3722 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3723 } else switch (ch) {
3725 case '!': /* last bg pid */
3726 case '?': /* last exit code */
3727 case '#': /* number of args */
3728 case '*': /* args */
3729 case '@': /* args */
3730 goto make_one_char_var;
3732 bool first_char, all_digits;
3734 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3736 /* XXX maybe someone will try to escape the '}' */
3741 ch = i_getch(input);
3747 /* ${#var}: length of var contents */
3749 else if (isdigit(ch)) {
3755 if (expansion < 2 &&
3756 ((all_digits && !isdigit(ch)) ||
3757 (!all_digits && !isalnum(ch) && ch != '_')))
3759 /* handle parameter expansions
3760 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3765 case ':': /* null modifier */
3766 if (expansion == 0) {
3767 debug_printf_parse(": null modifier\n");
3773 #if 0 /* not implemented yet :( */
3774 case '#': /* remove prefix */
3775 case '%': /* remove suffix */
3776 if (expansion == 0) {
3777 debug_printf_parse(": remove suffix/prefix\n");
3784 case '-': /* default value */
3785 case '=': /* assign default */
3786 case '+': /* alternative */
3787 case '?': /* error indicate */
3788 debug_printf_parse(": parameter expansion\n");
3794 syntax("unterminated ${name}");
3795 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3801 debug_printf_parse(": '%c'\n", ch);
3802 o_addchr(dest, ch | quote_mask);
3806 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3809 #if ENABLE_HUSH_TICK
3811 //int pos = dest->length;
3813 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3814 o_addchr(dest, quote_mask | '`');
3815 add_till_closing_curly_brace(dest, input);
3816 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3817 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3824 if (isalnum(ch)) { /* it's $_name or $_123 */
3830 /* still unhandled, but should be eventually */
3831 bb_error_msg("unhandled syntax: $%c", ch);
3835 o_addQchr(dest, '$');
3837 debug_printf_parse("handle_dollar return 0\n");
3841 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3842 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3843 * Return code is 0 if end_trigger char is met,
3844 * -1 on EOF (but if end_trigger == NULL then return 0),
3845 * 1 for syntax error */
3846 static int parse_stream(o_string *dest, struct parse_context *ctx,
3847 struct in_str *input, const char *end_trigger)
3851 redir_type redir_style;
3852 int shadow_quote = dest->o_quote;
3855 /* Only double-quote state is handled in the state variable dest->o_quote.
3856 * A single-quote triggers a bypass of the main loop until its mate is
3857 * found. When recursing, quote state is passed in via dest->o_quote. */
3859 debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3864 ch = i_getch(input);
3868 next = i_peek(input);
3871 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3872 ch, ch, m, dest->o_quote);
3873 if (m == CHAR_ORDINARY
3874 || (m != CHAR_SPECIAL && shadow_quote)
3877 syntax("unterminated \"");
3878 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3881 o_addQchr(dest, ch);
3882 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3883 || dest->o_assignment == WORD_IS_KEYWORD)
3885 && is_assignment(dest->data)
3887 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3891 if (m == CHAR_IFS) {
3892 if (done_word(dest, ctx)) {
3893 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3898 /* If we aren't performing a substitution, treat
3899 * a newline as a command separator.
3900 * [why we don't handle it exactly like ';'? --vda] */
3901 if (end_trigger && ch == '\n') {
3902 #if ENABLE_HUSH_CASE
3903 /* "case ... in <newline> word) ..." -
3904 * newlines are ignored (but ';' wouldn't be) */
3905 if (dest->length == 0 // && argv[0] == NULL
3906 && ctx->ctx_res_w == RES_MATCH
3911 done_pipe(ctx, PIPE_SEQ);
3912 dest->o_assignment = MAYBE_ASSIGNMENT;
3916 if (!shadow_quote && strchr(end_trigger, ch)) {
3917 /* Special case: (...word) makes last word terminate,
3918 * as if ';' is seen */
3920 done_word(dest, ctx);
3922 done_pipe(ctx, PIPE_SEQ);
3923 dest->o_assignment = MAYBE_ASSIGNMENT;
3926 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3928 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3936 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3937 /* ch is a special char and thus this word
3938 * cannot be an assignment: */
3939 dest->o_assignment = NOT_ASSIGNMENT;
3944 if (dest->length == 0 && !shadow_quote) {
3947 if (ch == EOF || ch == '\n')
3952 o_addQchr(dest, ch);
3958 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3962 * "The backslash retains its special meaning [in "..."]
3963 * only when followed by one of the following characters:
3964 * $, `, ", \, or <newline>. A double quote may be quoted
3965 * within double quotes by preceding it with a backslash.
3966 * If enabled, history expansion will be performed unless
3967 * an ! appearing in double quotes is escaped using
3968 * a backslash. The backslash preceding the ! is not removed."
3970 if (shadow_quote) { //NOT SURE dest->o_quote) {
3971 if (strchr("$`\"\\", next) != NULL) {
3972 o_addqchr(dest, i_getch(input));
3974 o_addqchr(dest, '\\');
3977 o_addchr(dest, '\\');
3978 o_addchr(dest, i_getch(input));
3982 if (handle_dollar(dest, input) != 0) {
3983 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3990 ch = i_getch(input);
3992 syntax("unterminated '");
3993 debug_printf_parse("parse_stream return 1: unterminated '\n");
3998 if (dest->o_assignment == NOT_ASSIGNMENT)
3999 o_addqchr(dest, ch);
4006 shadow_quote ^= 1; /* invert */
4007 if (dest->o_assignment == NOT_ASSIGNMENT)
4010 #if ENABLE_HUSH_TICK
4012 //int pos = dest->length;
4013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4014 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
4015 add_till_backquote(dest, input);
4016 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4017 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4022 redir_fd = redirect_opt_num(dest);
4023 done_word(dest, ctx);
4024 redir_style = REDIRECT_OVERWRITE;
4026 redir_style = REDIRECT_APPEND;
4030 else if (next == '(') {
4031 syntax(">(process) not supported");
4032 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
4036 setup_redirect(ctx, redir_fd, redir_style, input);
4039 redir_fd = redirect_opt_num(dest);
4040 done_word(dest, ctx);
4041 redir_style = REDIRECT_INPUT;
4043 redir_style = REDIRECT_HEREIS;
4045 } else if (next == '>') {
4046 redir_style = REDIRECT_IO;
4050 else if (next == '(') {
4051 syntax("<(process) not supported");
4052 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
4056 setup_redirect(ctx, redir_fd, redir_style, input);
4059 #if ENABLE_HUSH_CASE
4062 done_word(dest, ctx);
4063 done_pipe(ctx, PIPE_SEQ);
4064 #if ENABLE_HUSH_CASE
4065 /* Eat multiple semicolons, detect
4066 * whether it means something special */
4072 if (ctx->ctx_res_w == RES_CASEI) {
4073 ctx->ctx_dsemicolon = 1;
4074 ctx->ctx_res_w = RES_MATCH;
4080 /* We just finished a cmd. New one may start
4081 * with an assignment */
4082 dest->o_assignment = MAYBE_ASSIGNMENT;
4085 done_word(dest, ctx);
4088 done_pipe(ctx, PIPE_AND);
4090 done_pipe(ctx, PIPE_BG);
4094 done_word(dest, ctx);
4095 #if ENABLE_HUSH_CASE
4096 if (ctx->ctx_res_w == RES_MATCH)
4097 break; /* we are in case's "word | word)" */
4099 if (next == '|') { /* || */
4101 done_pipe(ctx, PIPE_OR);
4103 /* we could pick up a file descriptor choice here
4104 * with redirect_opt_num(), but bash doesn't do it.
4105 * "echo foo 2| cat" yields "foo 2". */
4110 #if ENABLE_HUSH_CASE
4111 /* "case... in [(]word)..." - skip '(' */
4112 if (ctx->ctx_res_w == RES_MATCH
4113 && ctx->command->argv == NULL /* not (word|(... */
4114 && dest->length == 0 /* not word(... */
4115 && dest->nonnull == 0 /* not ""(... */
4120 #if ENABLE_HUSH_FUNCTIONS
4121 if (dest->length != 0 /* not just () but word() */
4122 && dest->nonnull == 0 /* not a"b"c() */
4123 && ctx->command->argv == NULL /* it's the first word */
4124 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4125 && i_peek(input) == ')'
4126 && !match_reserved_word(dest)
4128 bb_error_msg("seems like a function definition");
4131 //TODO: do it properly.
4132 ch = i_getch(input);
4133 } while (ch == ' ' || ch == '\n');
4135 syntax("was expecting {");
4136 debug_printf_parse("parse_stream return 1\n");
4139 ch = 'F'; /* magic value */
4143 if (parse_group(dest, ctx, input, ch) != 0) {
4144 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4149 #if ENABLE_HUSH_CASE
4150 if (ctx->ctx_res_w == RES_MATCH)
4154 /* proper use of this character is caught by end_trigger:
4155 * if we see {, we call parse_group(..., end_trigger='}')
4156 * and it will match } earlier (not here). */
4157 syntax("unexpected } or )");
4158 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4162 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4165 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4171 static void set_in_charmap(const char *set, int code)
4174 G.charmap[(unsigned char)*set++] = code;
4177 static void update_charmap(void)
4179 G.ifs = getenv("IFS");
4182 /* Precompute a list of 'flow through' behavior so it can be treated
4183 * quickly up front. Computation is necessary because of IFS.
4184 * Special case handling of IFS == " \t\n" is not implemented.
4185 * The charmap[] array only really needs two bits each,
4186 * and on most machines that would be faster (reduced L1 cache use).
4188 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4189 #if ENABLE_HUSH_TICK
4190 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4192 set_in_charmap("\\$\"", CHAR_SPECIAL);
4194 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4195 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4198 /* Most recursion does not come through here, the exception is
4199 * from builtin_source() and builtin_eval() */
4200 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4202 struct parse_context ctx;
4203 o_string temp = NULL_O_STRING;
4207 initialize_context(&ctx);
4209 #if ENABLE_HUSH_INTERACTIVE
4210 inp->promptmode = 0; /* PS1 */
4212 /* We will stop & execute after each ';' or '\n'.
4213 * Example: "sleep 9999; echo TEST" + ctrl-C:
4214 * TEST should be printed */
4215 temp.o_assignment = MAYBE_ASSIGNMENT;
4216 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4218 if (rcode != 1 && ctx.old_flag != 0) {
4222 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4223 done_word(&temp, &ctx);
4224 done_pipe(&ctx, PIPE_SEQ);
4225 debug_print_tree(ctx.list_head, 0);
4226 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4227 run_and_free_list(ctx.list_head);
4229 /* We arrive here also if rcode == 1 (error in parse_stream) */
4231 if (ctx.old_flag != 0) {
4236 /*temp.nonnull = 0; - o_free does it below */
4237 /*temp.o_quote = 0; - o_free does it below */
4238 free_pipe_list(ctx.list_head, /* indent: */ 0);
4239 /* Discard all unprocessed line input, force prompt on */
4241 #if ENABLE_HUSH_INTERACTIVE
4246 /* loop on syntax errors, return on EOF: */
4247 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4251 static int parse_and_run_string(const char *s, int parse_flag)
4253 struct in_str input;
4254 setup_string_in_str(&input, s);
4255 return parse_and_run_stream(&input, parse_flag);
4258 static int parse_and_run_file(FILE *f)
4261 struct in_str input;
4262 setup_file_in_str(&input, f);
4263 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4268 /* Make sure we have a controlling tty. If we get started under a job
4269 * aware app (like bash for example), make sure we are now in charge so
4270 * we don't fight over who gets the foreground */
4271 static void setup_job_control(void)
4275 shell_pgrp = getpgrp();
4276 close_on_exec_on(G.interactive_fd);
4278 /* If we were ran as 'hush &',
4279 * sleep until we are in the foreground. */
4280 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4281 /* Send TTIN to ourself (should stop us) */
4282 kill(- shell_pgrp, SIGTTIN);
4283 shell_pgrp = getpgrp();
4286 /* Ignore job-control and misc signals. */
4287 set_jobctrl_sighandler(SIG_IGN);
4288 set_misc_sighandler(SIG_IGN);
4289 //huh? signal(SIGCHLD, SIG_IGN);
4291 /* We _must_ restore tty pgrp on fatal signals */
4292 set_fatal_sighandler(sigexit);
4294 /* Put ourselves in our own process group. */
4295 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4296 /* Grab control of the terminal. */
4297 tcsetpgrp(G.interactive_fd, getpid());
4302 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4303 int hush_main(int argc, char **argv)
4305 static const struct variable const_shell_ver = {
4307 .varstr = (char*)hush_version_str,
4308 .max_len = 1, /* 0 can provoke free(name) */
4316 struct variable *cur_var;
4320 G.root_pid = getpid();
4322 /* Deal with HUSH_VERSION */
4323 G.shell_ver = const_shell_ver; /* copying struct here */
4324 G.top_var = &G.shell_ver;
4325 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4326 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4327 /* Initialize our shell local variables with the values
4328 * currently living in the environment */
4329 cur_var = G.top_var;
4332 char *value = strchr(*e, '=');
4333 if (value) { /* paranoia */
4334 cur_var->next = xzalloc(sizeof(*cur_var));
4335 cur_var = cur_var->next;
4336 cur_var->varstr = *e;
4337 cur_var->max_len = strlen(*e);
4338 cur_var->flg_export = 1;
4342 debug_printf_env("putenv '%s'\n", hush_version_str);
4343 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4345 #if ENABLE_FEATURE_EDITING
4346 G.line_input_state = new_line_input_t(FOR_SHELL);
4348 /* XXX what should these be while sourcing /etc/profile? */
4349 G.global_argc = argc;
4350 G.global_argv = argv;
4351 /* Initialize some more globals to non-zero values */
4353 #if ENABLE_HUSH_INTERACTIVE
4354 if (ENABLE_FEATURE_EDITING)
4355 cmdedit_set_initial_prompt();
4359 if (EXIT_SUCCESS) /* otherwise is already done */
4360 G.last_return_code = EXIT_SUCCESS;
4362 if (argv[0] && argv[0][0] == '-') {
4363 debug_printf("sourcing /etc/profile\n");
4364 input = fopen_for_read("/etc/profile");
4365 if (input != NULL) {
4366 close_on_exec_on(fileno(input));
4367 parse_and_run_file(input);
4373 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4374 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4377 G.global_argv = argv + optind;
4378 if (!argv[optind]) {
4379 /* -c 'script' (no params): prevent empty $0 */
4380 *--G.global_argv = argv[0];
4382 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4383 G.global_argc = argc - optind;
4384 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4387 /* Well, we cannot just declare interactiveness,
4388 * we have to have some stuff (ctty, etc) */
4389 /* G.interactive_fd++; */
4392 /* "-s" means "read from stdin", but this is how we always
4393 * operate, so simply do nothing here. */
4397 if (!builtin_set_mode('-', opt))
4401 fprintf(stderr, "Usage: sh [FILE]...\n"
4402 " or: sh -c command [args]...\n\n");
4410 /* A shell is interactive if the '-i' flag was given, or if all of
4411 * the following conditions are met:
4413 * no arguments remaining or the -s flag given
4414 * standard input is a terminal
4415 * standard output is a terminal
4416 * Refer to Posix.2, the description of the 'sh' utility. */
4417 if (argv[optind] == NULL && input == stdin
4418 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4420 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4421 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4422 if (G.saved_tty_pgrp >= 0) {
4423 /* try to dup to high fd#, >= 255 */
4424 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4425 if (G.interactive_fd < 0) {
4426 /* try to dup to any fd */
4427 G.interactive_fd = dup(STDIN_FILENO);
4428 if (G.interactive_fd < 0)
4430 G.interactive_fd = 0;
4432 // TODO: track & disallow any attempts of user
4433 // to (inadvertently) close/redirect it
4436 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4437 if (G.interactive_fd) {
4438 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4439 /* Looks like they want an interactive shell */
4440 setup_job_control();
4441 /* -1 is special - makes xfuncs longjmp, not exit
4442 * (we reset die_sleep = 0 whereever we [v]fork) */
4444 if (setjmp(die_jmp)) {
4445 /* xfunc has failed! die die die */
4446 hush_exit(xfunc_error_retval);
4449 #elif ENABLE_HUSH_INTERACTIVE
4450 /* no job control compiled, only prompt/line editing */
4451 if (argv[optind] == NULL && input == stdin
4452 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4454 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4455 if (G.interactive_fd < 0) {
4456 /* try to dup to any fd */
4457 G.interactive_fd = dup(STDIN_FILENO);
4458 if (G.interactive_fd < 0)
4460 G.interactive_fd = 0;
4462 if (G.interactive_fd) {
4463 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4464 set_misc_sighandler(SIG_IGN);
4469 #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4470 if (G.interactive_fd) {
4471 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4472 printf("Enter 'help' for a list of built-in commands.\n\n");
4476 if (argv[optind] == NULL) {
4477 opt = parse_and_run_file(stdin);
4479 debug_printf("\nrunning script '%s'\n", argv[optind]);
4480 G.global_argv = argv + optind;
4481 G.global_argc = argc - optind;
4482 input = xfopen_for_read(argv[optind]);
4483 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4484 opt = parse_and_run_file(input);
4489 #if ENABLE_FEATURE_CLEAN_UP
4491 if (G.cwd != bb_msg_unknown)
4493 cur_var = G.top_var->next;
4495 struct variable *tmp = cur_var;
4496 if (!cur_var->max_len)
4497 free(cur_var->varstr);
4498 cur_var = cur_var->next;
4502 hush_exit(opt ? opt : G.last_return_code);
4507 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4508 int lash_main(int argc, char **argv)
4510 //bb_error_msg("lash is deprecated, please use hush instead");
4511 return hush_main(argc, argv);
4519 static int builtin_true(char **argv UNUSED_PARAM)
4524 static int builtin_test(char **argv)
4531 return test_main(argc, argv - argc);
4534 static int builtin_echo(char **argv)
4541 return echo_main(argc, argv - argc);
4544 static int builtin_eval(char **argv)
4546 int rcode = EXIT_SUCCESS;
4549 char *str = expand_strvec_to_string(argv + 1);
4550 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4552 rcode = G.last_return_code;
4557 static int builtin_cd(char **argv)
4560 if (argv[1] == NULL) {
4561 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4562 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4563 newdir = getenv("HOME") ? : "/";
4566 if (chdir(newdir)) {
4567 printf("cd: %s: %s\n", newdir, strerror(errno));
4568 return EXIT_FAILURE;
4571 return EXIT_SUCCESS;
4574 static int builtin_exec(char **argv)
4576 if (argv[1] == NULL)
4577 return EXIT_SUCCESS; /* bash does this */
4582 // FIXME: if exec fails, bash does NOT exit! We do...
4583 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4588 static int builtin_exit(char **argv)
4590 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4591 //puts("exit"); /* bash does it */
4592 // TODO: warn if we have background jobs: "There are stopped jobs"
4593 // On second consecutive 'exit', exit anyway.
4594 if (argv[1] == NULL)
4595 hush_exit(G.last_return_code);
4596 /* mimic bash: exit 123abc == exit 255 + error msg */
4597 xfunc_error_retval = 255;
4598 /* bash: exit -2 == exit 254, no error msg */
4599 hush_exit(xatoi(argv[1]) & 0xff);
4602 static int builtin_export(char **argv)
4605 char *name = argv[1];
4609 // ash emits: export VAR='VAL'
4610 // bash: declare -x VAR="VAL"
4611 // (both also escape as needed (quotes, $, etc))
4616 return EXIT_SUCCESS;
4619 value = strchr(name, '=');
4621 /* They are exporting something without a =VALUE */
4622 struct variable *var;
4624 var = get_local_var(name);
4626 var->flg_export = 1;
4627 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4628 putenv(var->varstr);
4630 /* bash does not return an error when trying to export
4631 * an undefined variable. Do likewise. */
4632 return EXIT_SUCCESS;
4635 set_local_var(xstrdup(name), 1);
4636 return EXIT_SUCCESS;
4640 /* built-in 'fg' and 'bg' handler */
4641 static int builtin_fg_bg(char **argv)
4646 if (!G.interactive_fd)
4647 return EXIT_FAILURE;
4648 /* If they gave us no args, assume they want the last backgrounded task */
4650 for (pi = G.job_list; pi; pi = pi->next) {
4651 if (pi->jobid == G.last_jobid) {
4655 bb_error_msg("%s: no current job", argv[0]);
4656 return EXIT_FAILURE;
4658 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4659 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4660 return EXIT_FAILURE;
4662 for (pi = G.job_list; pi; pi = pi->next) {
4663 if (pi->jobid == jobnum) {
4667 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4668 return EXIT_FAILURE;
4670 // TODO: bash prints a string representation
4671 // of job being foregrounded (like "sleep 1 | cat")
4672 if (*argv[0] == 'f') {
4673 /* Put the job into the foreground. */
4674 tcsetpgrp(G.interactive_fd, pi->pgrp);
4677 /* Restart the processes in the job */
4678 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4679 for (i = 0; i < pi->num_cmds; i++) {
4680 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4681 pi->cmds[i].is_stopped = 0;
4683 pi->stopped_cmds = 0;
4685 i = kill(- pi->pgrp, SIGCONT);
4687 if (errno == ESRCH) {
4688 delete_finished_bg_job(pi);
4689 return EXIT_SUCCESS;
4691 bb_perror_msg("kill (SIGCONT)");
4695 if (*argv[0] == 'f') {
4697 return checkjobs_and_fg_shell(pi);
4699 return EXIT_SUCCESS;
4703 #if ENABLE_HUSH_HELP
4704 static int builtin_help(char **argv UNUSED_PARAM)
4706 const struct built_in_command *x;
4708 printf("\nBuilt-in commands:\n");
4709 printf("-------------------\n");
4710 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4711 printf("%s\t%s\n", x->cmd, x->descr);
4714 return EXIT_SUCCESS;
4719 static int builtin_jobs(char **argv UNUSED_PARAM)
4722 const char *status_string;
4724 for (job = G.job_list; job; job = job->next) {
4725 if (job->alive_cmds == job->stopped_cmds)
4726 status_string = "Stopped";
4728 status_string = "Running";
4730 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4732 return EXIT_SUCCESS;
4736 static int builtin_pwd(char **argv UNUSED_PARAM)
4739 return EXIT_SUCCESS;
4742 static int builtin_read(char **argv)
4745 const char *name = argv[1] ? argv[1] : "REPLY";
4747 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4748 return set_local_var(string, 0);
4751 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4752 * built-in 'set' handler
4754 * set [-abCefhmnuvx] [-o option] [argument...]
4755 * set [+abCefhmnuvx] [+o option] [argument...]
4756 * set -- [argument...]
4759 * Implementations shall support the options in both their hyphen and
4760 * plus-sign forms. These options can also be specified as options to sh.
4762 * Write out all variables and their values: set
4763 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4764 * Turn on the -x and -v options: set -xv
4765 * Unset all positional parameters: set --
4766 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4767 * Set the positional parameters to the expansion of x, even if x expands
4768 * with a leading '-' or '+': set -- $x
4770 * So far, we only support "set -- [argument...]" and some of the short names.
4772 static int builtin_set_mode(const char cstate, const char mode)
4774 int state = (cstate == '-' ? 1 : 0);
4776 case 'n': G.fake_mode = state; break;
4777 case 'x': /*G.debug_mode = state;*/ break;
4778 default: return EXIT_FAILURE;
4780 return EXIT_SUCCESS;
4782 static int builtin_set(char **argv)
4785 char **pp, **g_argv;
4786 char *arg = *++argv;
4790 for (e = G.top_var; e; e = e->next)
4792 return EXIT_SUCCESS;
4796 if (!strcmp(arg, "--")) {
4801 if (arg[0] == '+' || arg[0] == '-') {
4802 for (n = 1; arg[n]; ++n)
4803 if (builtin_set_mode(arg[0], arg[n]))
4809 } while ((arg = *++argv) != NULL);
4810 /* Now argv[0] is 1st argument */
4812 /* Only reset global_argv if we didn't process anything */
4814 return EXIT_SUCCESS;
4817 /* NB: G.global_argv[0] ($0) is never freed/changed */
4818 g_argv = G.global_argv;
4819 if (G.global_args_malloced) {
4825 G.global_args_malloced = 1;
4826 pp = xzalloc(sizeof(pp[0]) * 2);
4827 pp[0] = g_argv[0]; /* retain $0 */
4830 /* This realloc's G.global_argv */
4831 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4838 return EXIT_SUCCESS;
4840 /* Nothing known, so abort */
4842 bb_error_msg("set: %s: invalid option", arg);
4843 return EXIT_FAILURE;
4846 static int builtin_shift(char **argv)
4852 if (n >= 0 && n < G.global_argc) {
4853 if (G.global_args_malloced) {
4856 free(G.global_argv[m++]);
4859 memmove(&G.global_argv[1], &G.global_argv[n+1],
4860 G.global_argc * sizeof(G.global_argv[0]));
4861 return EXIT_SUCCESS;
4863 return EXIT_FAILURE;
4866 static int builtin_source(char **argv)
4871 if (argv[1] == NULL)
4872 return EXIT_FAILURE;
4874 /* XXX search through $PATH is missing */
4875 input = fopen_for_read(argv[1]);
4877 bb_error_msg("can't open '%s'", argv[1]);
4878 return EXIT_FAILURE;
4880 close_on_exec_on(fileno(input));
4882 /* Now run the file */
4883 /* XXX argv and argc are broken; need to save old G.global_argv
4884 * (pointer only is OK!) on this stack frame,
4885 * set G.global_argv=argv+1, recurse, and restore. */
4886 status = parse_and_run_file(input);
4891 static int builtin_umask(char **argv)
4894 const char *arg = argv[1];
4896 new_umask = bb_strtou(arg, NULL, 8);
4898 return EXIT_FAILURE;
4900 new_umask = umask(0);
4901 printf("%.3o\n", (unsigned) new_umask);
4904 return EXIT_SUCCESS;
4907 static int builtin_unset(char **argv)
4909 /* bash always returns true */
4910 unset_local_var(argv[1]);
4911 return EXIT_SUCCESS;
4914 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
4915 static int builtin_wait(char **argv)
4917 int ret = EXIT_SUCCESS;
4920 if (argv[1] == NULL)
4921 /* don't care about exit status */
4925 pid_t pid = bb_strtou(argv[1], NULL, 10);
4927 bb_perror_msg("wait %s", argv[1]);
4928 return EXIT_FAILURE;
4929 } else if (waitpid(pid, &status, 0) == pid) {
4930 if (WIFSIGNALED(status))
4931 ret = 128 + WTERMSIG(status);
4932 else if (WIFEXITED(status))
4933 ret = WEXITSTATUS(status);
4937 bb_perror_msg("wait %s", argv[1]);
4946 #if ENABLE_HUSH_LOOPS
4947 static int builtin_break(char **argv)
4949 if (G.depth_of_loop == 0) {
4950 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4951 return EXIT_SUCCESS; /* bash compat */
4953 G.flag_break_continue++; /* BC_BREAK = 1 */
4954 G.depth_break_continue = 1;
4956 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4957 if (errno || !G.depth_break_continue || argv[2]) {
4958 bb_error_msg("%s: bad arguments", argv[0]);
4959 G.flag_break_continue = BC_BREAK;
4960 G.depth_break_continue = UINT_MAX;
4963 if (G.depth_of_loop < G.depth_break_continue)
4964 G.depth_break_continue = G.depth_of_loop;
4965 return EXIT_SUCCESS;
4968 static int builtin_continue(char **argv)
4970 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4971 return builtin_break(argv);