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>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
45 * Bash stuff (maybe optionally enable?):
46 * &> and >& redirection of stdout+stderr
48 * reserved words: [[ ]] function select
49 * substrings ${var:1:5}
52 * grep for "TODO" and fix (some of them are easy)
54 * follow IFS rules more precisely, including update semantics
56 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
58 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
60 /* #include <dmalloc.h> */
67 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
72 #define LEAK_HUNTING 0
73 #define BUILD_AS_NOMMU 0
74 /* Enable/disable sanity checks. Ok to enable in production,
75 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
76 * Keeping 1 for now even in released versions.
79 /* Slightly bigger (+200 bytes), but faster hush.
80 * So far it only enables a trick with counting SIGCHLDs and forks,
81 * which allows us to do fewer waitpid's.
82 * (we can detect a case where neither forks were done nor SIGCHLDs happened
83 * and therefore waitpid will return the same result as last time)
85 #define ENABLE_HUSH_FAST 0
93 # define USE_FOR_NOMMU(...) __VA_ARGS__
94 # define USE_FOR_MMU(...)
97 #if defined SINGLE_APPLET_MAIN
98 /* STANDALONE does not make sense, and won't compile */
99 # undef CONFIG_FEATURE_SH_STANDALONE
100 # undef ENABLE_FEATURE_SH_STANDALONE
101 # undef IF_FEATURE_SH_STANDALONE
102 # define IF_FEATURE_SH_STANDALONE(...)
103 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
104 # define ENABLE_FEATURE_SH_STANDALONE 0
107 #if !ENABLE_HUSH_INTERACTIVE
108 # undef ENABLE_FEATURE_EDITING
109 # define ENABLE_FEATURE_EDITING 0
110 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
111 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
114 /* Do we support ANY keywords? */
115 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
116 # define HAS_KEYWORDS 1
117 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
118 # define IF_HAS_NO_KEYWORDS(...)
120 # define HAS_KEYWORDS 0
121 # define IF_HAS_KEYWORDS(...)
122 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
125 /* If you comment out one of these below, it will be #defined later
126 * to perform debug printfs to stderr: */
127 #define debug_printf(...) do {} while (0)
128 /* Finer-grained debug switches */
129 #define debug_printf_parse(...) do {} while (0)
130 #define debug_print_tree(a, b) do {} while (0)
131 #define debug_printf_exec(...) do {} while (0)
132 #define debug_printf_env(...) do {} while (0)
133 #define debug_printf_jobs(...) do {} while (0)
134 #define debug_printf_expand(...) do {} while (0)
135 #define debug_printf_glob(...) do {} while (0)
136 #define debug_printf_list(...) do {} while (0)
137 #define debug_printf_subst(...) do {} while (0)
138 #define debug_printf_clean(...) do {} while (0)
140 #define ERR_PTR ((void*)(long)1)
142 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
144 #define SPECIAL_VAR_SYMBOL 3
148 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
150 /* This supports saving pointers malloced in vfork child,
151 * to be freed in the parent.
154 typedef struct nommu_save_t {
156 struct variable *old_vars;
158 char **argv_from_re_execing;
162 /* The descrip member of this structure is only used to make
163 * debugging output pretty */
164 static const struct {
166 signed char default_fd;
170 { O_RDONLY, 0, "<" },
171 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
172 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
173 { O_RDONLY, 0, "<<" },
174 { O_CREAT|O_RDWR, 1, "<>" },
175 /* Should not be needed. Bogus default_fd helps in debugging */
176 /* { O_RDONLY, 77, "<<" }, */
179 typedef enum reserved_style {
188 #if ENABLE_HUSH_LOOPS
195 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
200 /* three pseudo-keywords support contrived "case" syntax: */
201 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
202 RES_MATCH , /* "word)" */
203 RES_CASE_BODY, /* "this command is inside CASE" */
210 typedef struct o_string {
212 int length; /* position where data is appended */
214 /* Protect newly added chars against globbing
215 * (by prepending \ to *, ?, [, \) */
218 /* At least some part of the string was inside '' or "",
219 * possibly empty one: word"", wo''rd etc. */
221 smallint has_empty_slot;
222 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
225 MAYBE_ASSIGNMENT = 0,
226 DEFINITELY_ASSIGNMENT = 1,
228 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
230 /* Used for initialization: o_string foo = NULL_O_STRING; */
231 #define NULL_O_STRING { NULL }
233 /* I can almost use ordinary FILE*. Is open_memstream() universally
234 * available? Where is it documented? */
235 typedef struct in_str {
237 /* eof_flag=1: last char in ->p is really an EOF */
238 char eof_flag; /* meaningless if ->p == NULL */
240 #if ENABLE_HUSH_INTERACTIVE
242 smallint promptmode; /* 0: PS1, 1: PS2 */
245 int (*get) (struct in_str *);
246 int (*peek) (struct in_str *);
248 #define i_getch(input) ((input)->get(input))
249 #define i_peek(input) ((input)->peek(input))
251 struct redir_struct {
252 struct redir_struct *next;
253 char *rd_filename; /* filename */
254 int rd_fd; /* fd to redirect */
255 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
257 smallint rd_type; /* (enum redir_type) */
258 /* note: for heredocs, rd_filename contains heredoc delimiter,
259 * and subsequently heredoc itself; and rd_dup is a bitmask:
260 * 1: do we need to trim leading tabs?
261 * 2: is heredoc quoted (<<'delim' syntax) ?
264 typedef enum redir_type {
265 REDIRECT_INVALID = 0,
267 REDIRECT_OVERWRITE = 2,
269 REDIRECT_HEREDOC = 4,
271 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
274 REDIRFD_SYNTAX_ERR = -2,
275 REDIRFD_TO_FILE = -1,
276 /* otherwise, rd_fd is redirected to rd_dup */
278 HEREDOC_SKIPTABS = 1,
284 pid_t pid; /* 0 if exited */
285 int assignment_cnt; /* how many argv[i] are assignments? */
286 smallint is_stopped; /* is the command currently running? */
287 smallint grp_type; /* GRP_xxx */
289 #define GRP_SUBSHELL 1
290 #if ENABLE_HUSH_FUNCTIONS
291 # define GRP_FUNCTION 2
293 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
296 char *group_as_string;
298 #if ENABLE_HUSH_FUNCTIONS
299 struct function *child_func;
300 /* This field is used to prevent a bug here:
301 * while...do f1() {a;}; f1; f1 {b;}; f1; done
302 * When we execute "f1() {a;}" cmd, we create new function and clear
303 * cmd->group, cmd->group_as_string, cmd->argv[0].
304 * when we execute "f1 {b;}", we notice that f1 exists,
305 * and that it's "parent cmd" struct is still "alive",
306 * we put those fields back into cmd->xxx
307 * (struct function has ->parent_cmd ptr to facilitate that).
308 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
309 * Without this trick, loop would execute a;b;b;b;...
310 * instead of correct sequence a;b;a;b;...
311 * When command is freed, it severs the link
312 * (sets ->child_func->parent_cmd to NULL).
315 char **argv; /* command name and arguments */
316 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
317 * and on execution these are substituted with their values.
318 * Substitution can make _several_ words out of one argv[n]!
319 * Example: argv[0]=='.^C*^C.' here: echo .$*.
320 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
322 struct redir_struct *redirects; /* I/O redirections */
324 /* Is there anything in this command at all? */
325 #define IS_NULL_CMD(cmd) \
326 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
331 int num_cmds; /* total number of commands in pipe */
332 int alive_cmds; /* number of commands running (not exited) */
333 int stopped_cmds; /* number of commands alive, but stopped */
335 int jobid; /* job number */
336 pid_t pgrp; /* process group ID for the job */
337 char *cmdtext; /* name of job */
339 struct command *cmds; /* array of commands in pipe */
340 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
341 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
342 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
344 typedef enum pipe_style {
350 /* Is there anything in this pipe at all? */
351 #define IS_NULL_PIPE(pi) \
352 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
354 /* This holds pointers to the various results of parsing */
355 struct parse_context {
356 /* linked list of pipes */
357 struct pipe *list_head;
358 /* last pipe (being constructed right now) */
360 /* last command in pipe (being constructed right now) */
361 struct command *command;
362 /* last redirect in command->redirects list */
363 struct redir_struct *pending_redirect;
369 smallint ctx_inverted; /* "! cmd | cmd" */
371 smallint ctx_dsemicolon; /* ";;" seen */
373 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
375 /* group we are enclosed in:
376 * example: "if pipe1; pipe2; then pipe3; fi"
377 * when we see "if" or "then", we malloc and copy current context,
378 * and make ->stack point to it. then we parse pipeN.
379 * when closing "then" / fi" / whatever is found,
380 * we move list_head into ->stack->command->group,
381 * copy ->stack into current context, and delete ->stack.
382 * (parsing of { list } and ( list ) doesn't use this method)
384 struct parse_context *stack;
388 /* On program start, environ points to initial environment.
389 * putenv adds new pointers into it, unsetenv removes them.
390 * Neither of these (de)allocates the strings.
391 * setenv allocates new strings in malloc space and does putenv,
392 * and thus setenv is unusable (leaky) for shell's purposes */
393 #define setenv(...) setenv_is_leaky_dont_use()
395 struct variable *next;
396 char *varstr; /* points to "name=" portion */
397 #if ENABLE_HUSH_LOCAL
398 unsigned func_nest_level;
400 int max_len; /* if > 0, name is part of initial env; else name is malloced */
401 smallint flg_export; /* putenv should be done on this var */
402 smallint flg_read_only;
410 #if ENABLE_HUSH_FUNCTIONS
412 struct function *next;
414 struct command *parent_cmd;
417 char *body_as_string;
423 /* "Globals" within this file */
424 /* Sorted roughly by size (smaller offsets == smaller code) */
426 /* interactive_fd != 0 means we are an interactive shell.
427 * If we are, then saved_tty_pgrp can also be != 0, meaning
428 * that controlling tty is available. With saved_tty_pgrp == 0,
429 * job control still works, but terminal signals
430 * (^C, ^Z, ^Y, ^\) won't work at all, and background
431 * process groups can only be created with "cmd &".
432 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
433 * to give tty to the foreground process group,
434 * and will take it back when the group is stopped (^Z)
437 #if ENABLE_HUSH_INTERACTIVE
438 /* 'interactive_fd' is a fd# open to ctty, if we have one
439 * _AND_ if we decided to act interactively */
443 # define G_interactive_fd (G.interactive_fd)
445 # define G_interactive_fd 0
447 #if ENABLE_FEATURE_EDITING
448 line_input_t *line_input_state;
455 pid_t saved_tty_pgrp;
456 struct pipe *job_list;
457 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
459 # define G_saved_tty_pgrp 0
461 smallint flag_SIGINT;
462 #if ENABLE_HUSH_LOOPS
463 smallint flag_break_continue;
465 #if ENABLE_HUSH_FUNCTIONS
466 /* 0: outside of a function (or sourced file)
467 * -1: inside of a function, ok to use return builtin
468 * 1: return is invoked, skip all till end of func
470 smallint flag_return_in_progress;
473 smallint exiting; /* used to prevent EXIT trap recursion */
474 /* These four support $?, $#, and $1 */
475 smalluint last_exitcode;
476 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
477 smalluint global_args_malloced;
478 /* how many non-NULL argv's we have. NB: $# + 1 */
482 char *argv0_for_re_execing;
484 #if ENABLE_HUSH_LOOPS
485 unsigned depth_break_continue;
486 unsigned depth_of_loop;
490 struct variable *top_var; /* = &G.shell_ver (set in main()) */
491 struct variable shell_ver;
492 #if ENABLE_HUSH_FUNCTIONS
493 struct function *top_func;
494 # if ENABLE_HUSH_LOCAL
495 struct variable **shadowed_vars_pp;
496 unsigned func_nest_level;
499 /* Signal and trap handling */
501 unsigned count_SIGCHLD;
502 unsigned handled_SIGCHLD;
503 smallint we_have_children;
505 /* which signals have non-DFL handler (even with no traps set)? */
506 unsigned non_DFL_mask;
507 char **traps; /* char *traps[NSIG] */
508 sigset_t blocked_set;
509 sigset_t inherited_set;
511 unsigned long memleak_value;
514 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
516 #define G (*ptr_to_globals)
517 /* Not #defining name to G.name - this quickly gets unwieldy
518 * (too many defines). Also, I actually prefer to see when a variable
519 * is global, thus "G." prefix is a useful hint */
520 #define INIT_G() do { \
521 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
525 /* Function prototypes for builtins */
526 static int builtin_cd(char **argv);
527 static int builtin_echo(char **argv);
528 static int builtin_eval(char **argv);
529 static int builtin_exec(char **argv);
530 static int builtin_exit(char **argv);
531 static int builtin_export(char **argv);
533 static int builtin_fg_bg(char **argv);
534 static int builtin_jobs(char **argv);
537 static int builtin_help(char **argv);
539 #if ENABLE_HUSH_LOCAL
540 static int builtin_local(char **argv);
543 static int builtin_memleak(char **argv);
545 static int builtin_pwd(char **argv);
546 static int builtin_read(char **argv);
547 static int builtin_set(char **argv);
548 static int builtin_shift(char **argv);
549 static int builtin_source(char **argv);
550 static int builtin_test(char **argv);
551 static int builtin_trap(char **argv);
552 static int builtin_type(char **argv);
553 static int builtin_true(char **argv);
554 static int builtin_umask(char **argv);
555 static int builtin_unset(char **argv);
556 static int builtin_wait(char **argv);
557 #if ENABLE_HUSH_LOOPS
558 static int builtin_break(char **argv);
559 static int builtin_continue(char **argv);
561 #if ENABLE_HUSH_FUNCTIONS
562 static int builtin_return(char **argv);
565 /* Table of built-in functions. They can be forked or not, depending on
566 * context: within pipes, they fork. As simple commands, they do not.
567 * When used in non-forking context, they can change global variables
568 * in the parent shell process. If forked, of course they cannot.
569 * For example, 'unset foo | whatever' will parse and run, but foo will
570 * still be set at the end. */
571 struct built_in_command {
573 int (*function)(char **argv);
576 # define BLTIN(cmd, func, help) { cmd, func, help }
578 # define BLTIN(cmd, func, help) { cmd, func }
582 /* For now, echo and test are unconditionally enabled.
583 * Maybe make it configurable? */
584 static const struct built_in_command bltins[] = {
585 BLTIN("." , builtin_source , "Run commands in a file"),
586 BLTIN(":" , builtin_true , "No-op"),
587 BLTIN("[" , builtin_test , "Test condition"),
589 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
591 #if ENABLE_HUSH_LOOPS
592 BLTIN("break" , builtin_break , "Exit from a loop"),
594 BLTIN("cd" , builtin_cd , "Change directory"),
595 #if ENABLE_HUSH_LOOPS
596 BLTIN("continue", builtin_continue, "Start new loop iteration"),
598 BLTIN("echo" , builtin_echo , "Write to stdout"),
599 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
600 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
601 BLTIN("exit" , builtin_exit , "Exit"),
602 BLTIN("export" , builtin_export , "Set environment variable"),
604 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
607 BLTIN("help" , builtin_help , "List shell built-in commands"),
610 BLTIN("jobs" , builtin_jobs , "List active jobs"),
612 #if ENABLE_HUSH_LOCAL
613 BLTIN("local" , builtin_local , "Set local variable"),
616 BLTIN("memleak" , builtin_memleak , "Debug tool"),
618 BLTIN("pwd" , builtin_pwd , "Print current directory"),
619 BLTIN("read" , builtin_read , "Input environment variable"),
620 #if ENABLE_HUSH_FUNCTIONS
621 BLTIN("return" , builtin_return , "Return from a function"),
623 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
624 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
625 BLTIN("test" , builtin_test , "Test condition"),
626 BLTIN("trap" , builtin_trap , "Trap signals"),
627 BLTIN("type" , builtin_type , "Write a description of command type"),
628 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
629 BLTIN("umask" , builtin_umask , "Set file creation mask"),
630 BLTIN("unset" , builtin_unset , "Unset environment variable"),
631 BLTIN("wait" , builtin_wait , "Wait for process"),
638 /* prevent disasters with G.debug_indent < 0 */
639 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
640 # define debug_enter() (G.debug_indent++)
641 # define debug_leave() (G.debug_indent--)
643 # define indent() ((void)0)
644 # define debug_enter() ((void)0)
645 # define debug_leave() ((void)0)
649 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
652 #ifndef debug_printf_parse
653 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
656 #ifndef debug_printf_exec
657 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
660 #ifndef debug_printf_env
661 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
664 #ifndef debug_printf_jobs
665 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
666 # define DEBUG_JOBS 1
668 # define DEBUG_JOBS 0
671 #ifndef debug_printf_expand
672 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
673 # define DEBUG_EXPAND 1
675 # define DEBUG_EXPAND 0
678 #ifndef debug_printf_glob
679 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
680 # define DEBUG_GLOB 1
682 # define DEBUG_GLOB 0
685 #ifndef debug_printf_list
686 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
689 #ifndef debug_printf_subst
690 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
693 #ifndef debug_printf_clean
694 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
695 # define DEBUG_CLEAN 1
697 # define DEBUG_CLEAN 0
701 static void debug_print_strings(const char *prefix, char **vv)
704 fprintf(stderr, "%s:\n", prefix);
706 fprintf(stderr, " '%s'\n", *vv++);
709 # define debug_print_strings(prefix, vv) ((void)0)
713 /* Leak hunting. Use hush_leaktool.sh for post-processing.
716 static void *xxmalloc(int lineno, size_t size)
718 void *ptr = xmalloc((size + 0xff) & ~0xff);
719 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
722 static void *xxrealloc(int lineno, void *ptr, size_t size)
724 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
725 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
728 static char *xxstrdup(int lineno, const char *str)
730 char *ptr = xstrdup(str);
731 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
734 static void xxfree(void *ptr)
736 fdprintf(2, "free %p\n", ptr);
739 #define xmalloc(s) xxmalloc(__LINE__, s)
740 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
741 #define xstrdup(s) xxstrdup(__LINE__, s)
742 #define free(p) xxfree(p)
746 /* Syntax and runtime errors. They always abort scripts.
747 * In interactive use they usually discard unparsed and/or unexecuted commands
748 * and return to the prompt.
749 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
752 # define die_if_script(lineno, fmt...) die_if_script(fmt)
753 # define syntax_error(lineno, msg) syntax_error(msg)
754 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
755 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
756 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
757 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
760 static void die_if_script(unsigned lineno, const char *fmt, ...)
765 bb_error_msg("hush.c:%u", lineno);
768 bb_verror_msg(fmt, p, NULL);
770 if (!G_interactive_fd)
774 static void syntax_error(unsigned lineno, const char *msg)
777 die_if_script(lineno, "syntax error: %s", msg);
779 die_if_script(lineno, "syntax error", NULL);
782 static void syntax_error_at(unsigned lineno, const char *msg)
784 die_if_script(lineno, "syntax error at '%s'", msg);
787 static void syntax_error_unterm_str(unsigned lineno, const char *s)
789 die_if_script(lineno, "syntax error: unterminated %s", s);
792 /* It so happens that all such cases are totally fatal
793 * even if shell is interactive: EOF while looking for closing
794 * delimiter. There is nowhere to read stuff from after that,
795 * it's EOF! The only choice is to terminate.
797 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
798 static void syntax_error_unterm_ch(unsigned lineno, char ch)
800 char msg[2] = { ch, '\0' };
801 syntax_error_unterm_str(lineno, msg);
805 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
810 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
814 # undef die_if_script
816 # undef syntax_error_at
817 # undef syntax_error_unterm_ch
818 # undef syntax_error_unterm_str
819 # undef syntax_error_unexpected_ch
821 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
822 # define syntax_error(msg) syntax_error(__LINE__, msg)
823 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
824 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
825 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
826 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
830 #if ENABLE_HUSH_INTERACTIVE
831 static void cmdedit_update_prompt(void);
833 # define cmdedit_update_prompt() ((void)0)
839 static int glob_needed(const char *s)
844 if (*s == '*' || *s == '[' || *s == '?')
851 static int is_well_formed_var_name(const char *s, char terminator)
853 if (!s || !(isalpha(*s) || *s == '_'))
856 while (isalnum(*s) || *s == '_')
858 return *s == terminator;
861 /* Replace each \x with x in place, return ptr past NUL. */
862 static char *unbackslash(char *src)
868 if ((*dst++ = *src++) == '\0')
874 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
895 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
896 v[count1 + count2] = NULL;
899 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
903 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
905 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
906 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
909 #define add_strings_to_strings(strings, add, need_to_dup) \
910 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
913 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
914 static char **add_string_to_strings(char **strings, char *add)
919 return add_strings_to_strings(strings, v, /*dup:*/ 0);
922 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
924 char **ptr = add_string_to_strings(strings, add);
925 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
928 #define add_string_to_strings(strings, add) \
929 xx_add_string_to_strings(__LINE__, strings, add)
932 static void free_strings(char **strings)
947 /* Helpers for setting new $n and restoring them back
949 typedef struct save_arg_t {
953 smallint sv_g_malloced;
956 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
960 sv->sv_argv0 = argv[0];
961 sv->sv_g_argv = G.global_argv;
962 sv->sv_g_argc = G.global_argc;
963 sv->sv_g_malloced = G.global_args_malloced;
965 argv[0] = G.global_argv[0]; /* retain $0 */
966 G.global_argv = argv;
967 G.global_args_malloced = 0;
975 static void restore_G_args(save_arg_t *sv, char **argv)
979 if (G.global_args_malloced) {
980 /* someone ran "set -- arg1 arg2 ...", undo */
982 while (*++pp) /* note: does not free $0 */
986 argv[0] = sv->sv_argv0;
987 G.global_argv = sv->sv_g_argv;
988 G.global_argc = sv->sv_g_argc;
989 G.global_args_malloced = sv->sv_g_malloced;
993 /* Basic theory of signal handling in shell
994 * ========================================
995 * This does not describe what hush does, rather, it is current understanding
996 * what it _should_ do. If it doesn't, it's a bug.
997 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
999 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1000 * is finished or backgrounded. It is the same in interactive and
1001 * non-interactive shells, and is the same regardless of whether
1002 * a user trap handler is installed or a shell special one is in effect.
1003 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1004 * backgrounds (i.e. stops) or kills all members of currently running
1007 * Wait builtin in interruptible by signals for which user trap is set
1008 * or by SIGINT in interactive shell.
1010 * Trap handlers will execute even within trap handlers. (right?)
1012 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1014 * If job control is off, backgrounded commands ("cmd &")
1015 * have SIGINT, SIGQUIT set to SIG_IGN.
1017 * Commands which are run in command substitution ("`cmd`")
1018 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1020 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1021 * by the shell from its parent.
1023 * Signals which differ from SIG_DFL action
1024 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1027 * SIGTERM (interactive): ignore
1028 * SIGHUP (interactive):
1029 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1030 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1031 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1032 * that all pipe members are stopped. Try this in bash:
1033 * while :; do :; done - ^Z does not background it
1034 * (while :; do :; done) - ^Z backgrounds it
1035 * SIGINT (interactive): wait for last pipe, ignore the rest
1036 * of the command line, show prompt. NB: ^C does not send SIGINT
1037 * to interactive shell while shell is waiting for a pipe,
1038 * since shell is bg'ed (is not in foreground process group).
1039 * Example 1: this waits 5 sec, but does not execute ls:
1040 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1041 * Example 2: this does not wait and does not execute ls:
1042 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1043 * Example 3: this does not wait 5 sec, but executes ls:
1044 * "sleep 5; ls -l" + press ^C
1046 * (What happens to signals which are IGN on shell start?)
1047 * (What happens with signal mask on shell start?)
1049 * Implementation in hush
1050 * ======================
1051 * We use in-kernel pending signal mask to determine which signals were sent.
1052 * We block all signals which we don't want to take action immediately,
1053 * i.e. we block all signals which need to have special handling as described
1054 * above, and all signals which have traps set.
1055 * After each pipe execution, we extract any pending signals via sigtimedwait()
1058 * unsigned non_DFL_mask: a mask of such "special" signals
1059 * sigset_t blocked_set: current blocked signal set
1062 * clear bit in blocked_set unless it is also in non_DFL_mask
1063 * "trap 'cmd' SIGxxx":
1064 * set bit in blocked_set (even if 'cmd' is '')
1065 * after [v]fork, if we plan to be a shell:
1066 * unblock signals with special interactive handling
1067 * (child shell is not interactive),
1068 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1069 * after [v]fork, if we plan to exec:
1070 * POSIX says pending signal mask is cleared in child - no need to clear it.
1071 * Restore blocked signal set to one inherited by shell just prior to exec.
1073 * Note: as a result, we do not use signal handlers much. The only uses
1074 * are to count SIGCHLDs
1075 * and to restore tty pgrp on signal-induced exit.
1078 SPECIAL_INTERACTIVE_SIGS = 0
1083 SPECIAL_JOB_SIGS = 0
1091 #if ENABLE_HUSH_FAST
1092 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1095 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1101 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1102 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1103 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1104 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1106 /* Restores tty foreground process group, and exits.
1107 * May be called as signal handler for fatal signal
1108 * (will resend signal to itself, producing correct exit state)
1109 * or called directly with -EXITCODE.
1110 * We also call it if xfunc is exiting. */
1111 static void sigexit(int sig) NORETURN;
1112 static void sigexit(int sig)
1114 /* Disable all signals: job control, SIGPIPE, etc. */
1115 sigprocmask_allsigs(SIG_BLOCK);
1117 /* Careful: we can end up here after [v]fork. Do not restore
1118 * tty pgrp then, only top-level shell process does that */
1119 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1120 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1122 /* Not a signal, just exit */
1126 kill_myself_with_sig(sig); /* does not return */
1130 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1131 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1135 /* Restores tty foreground process group, and exits. */
1136 static void hush_exit(int exitcode) NORETURN;
1137 static void hush_exit(int exitcode)
1139 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1140 /* Prevent recursion:
1141 * trap "echo Hi; exit" EXIT; exit
1143 char *argv[] = { NULL, G.traps[0], NULL };
1151 fflush(NULL); /* flush all streams */
1152 sigexit(- (exitcode & 0xff));
1158 static int check_and_run_traps(int sig)
1160 static const struct timespec zero_timespec = { 0, 0 };
1161 smalluint save_rcode;
1167 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1172 if (G.traps && G.traps[sig]) {
1173 if (G.traps[sig][0]) {
1174 /* We have user-defined handler */
1175 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1176 save_rcode = G.last_exitcode;
1179 G.last_exitcode = save_rcode;
1180 } /* else: "" trap, ignoring signal */
1183 /* not a trap: special action */
1185 #if ENABLE_HUSH_FAST
1188 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1192 /* Builtin was ^C'ed, make it look prettier: */
1199 /* bash is observed to signal whole process groups,
1200 * not individual processes */
1201 for (job = G.job_list; job; job = job->next) {
1204 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1205 if (kill(- job->pgrp, SIGHUP) == 0)
1206 kill(- job->pgrp, SIGCONT);
1211 default: /* ignored: */
1212 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1220 static const char *set_cwd(void)
1222 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1223 * we must not try to free(bb_msg_unknown) */
1224 if (G.cwd == bb_msg_unknown)
1226 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1228 G.cwd = bb_msg_unknown;
1234 * Shell and environment variable support
1236 static struct variable **get_ptr_to_local_var(const char *name)
1238 struct variable **pp;
1239 struct variable *cur;
1244 while ((cur = *pp) != NULL) {
1245 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1252 static struct variable *get_local_var(const char *name)
1254 struct variable **pp = get_ptr_to_local_var(name);
1260 static const char *get_local_var_value(const char *name)
1262 struct variable **pp = get_ptr_to_local_var(name);
1264 return strchr((*pp)->varstr, '=') + 1;
1268 /* str holds "NAME=VAL" and is expected to be malloced.
1269 * We take ownership of it.
1271 * 0: do not change export flag
1272 * (if creating new variable, flag will be 0)
1273 * 1: set export flag and putenv the variable
1274 * -1: clear export flag and unsetenv the variable
1275 * flg_read_only is set only when we handle -R var=val
1277 #if !BB_MMU && ENABLE_HUSH_LOCAL
1278 /* all params are used */
1279 #elif BB_MMU && ENABLE_HUSH_LOCAL
1280 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1281 set_local_var(str, flg_export, local_lvl)
1282 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1283 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1284 set_local_var(str, flg_export)
1285 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1286 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1287 set_local_var(str, flg_export, flg_read_only)
1289 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1291 struct variable **var_pp;
1292 struct variable *cur;
1296 eq_sign = strchr(str, '=');
1297 if (!eq_sign) { /* not expected to ever happen? */
1302 name_len = eq_sign - str + 1; /* including '=' */
1303 var_pp = &G.top_var;
1304 while ((cur = *var_pp) != NULL) {
1305 if (strncmp(cur->varstr, str, name_len) != 0) {
1306 var_pp = &cur->next;
1309 /* We found an existing var with this name */
1310 if (cur->flg_read_only) {
1314 bb_error_msg("%s: readonly variable", str);
1318 if (flg_export == -1) { // "&& cur->flg_export" ?
1319 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1324 #if ENABLE_HUSH_LOCAL
1325 if (cur->func_nest_level < local_lvl) {
1326 /* New variable is declared as local,
1327 * and existing one is global, or local
1328 * from enclosing function.
1329 * Remove and save old one: */
1330 *var_pp = cur->next;
1331 cur->next = *G.shadowed_vars_pp;
1332 *G.shadowed_vars_pp = cur;
1333 /* bash 3.2.33(1) and exported vars:
1335 * # f() { local z=a; env | grep ^z; }
1341 if (cur->flg_export)
1346 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1351 if (cur->max_len != 0) {
1352 if (cur->max_len >= strlen(str)) {
1353 /* This one is from startup env, reuse space */
1354 strcpy(cur->varstr, str);
1358 /* max_len == 0 signifies "malloced" var, which we can
1359 * (and has to) free */
1363 goto set_str_and_exp;
1366 /* Not found - create new variable struct */
1367 cur = xzalloc(sizeof(*cur));
1368 #if ENABLE_HUSH_LOCAL
1369 cur->func_nest_level = local_lvl;
1371 cur->next = *var_pp;
1377 cur->flg_read_only = flg_read_only;
1380 if (flg_export == 1)
1381 cur->flg_export = 1;
1382 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1383 cmdedit_update_prompt();
1384 if (cur->flg_export) {
1385 if (flg_export == -1) {
1386 cur->flg_export = 0;
1387 /* unsetenv was already done */
1389 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1390 return putenv(cur->varstr);
1396 static int unset_local_var_len(const char *name, int name_len)
1398 struct variable *cur;
1399 struct variable **var_pp;
1402 return EXIT_SUCCESS;
1403 var_pp = &G.top_var;
1404 while ((cur = *var_pp) != NULL) {
1405 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1406 if (cur->flg_read_only) {
1407 bb_error_msg("%s: readonly variable", name);
1408 return EXIT_FAILURE;
1410 *var_pp = cur->next;
1411 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1412 bb_unsetenv(cur->varstr);
1413 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1414 cmdedit_update_prompt();
1418 return EXIT_SUCCESS;
1420 var_pp = &cur->next;
1422 return EXIT_SUCCESS;
1425 static int unset_local_var(const char *name)
1427 return unset_local_var_len(name, strlen(name));
1430 static void unset_vars(char **strings)
1438 const char *eq = strchrnul(*v, '=');
1439 unset_local_var_len(*v, (int)(eq - *v));
1445 #if ENABLE_SH_MATH_SUPPORT
1446 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1447 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1448 static char *endofname(const char *name)
1456 if (!is_in_name(*p))
1462 static void arith_set_local_var(const char *name, const char *val, int flags)
1464 /* arith code doesnt malloc space, so do it for it */
1465 char *var = xasprintf("%s=%s", name, val);
1466 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1472 * Helpers for "var1=val1 var2=val2 cmd" feature
1474 static void add_vars(struct variable *var)
1476 struct variable *next;
1480 var->next = G.top_var;
1482 if (var->flg_export) {
1483 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1484 putenv(var->varstr);
1486 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1492 static struct variable *set_vars_and_save_old(char **strings)
1495 struct variable *old = NULL;
1501 struct variable *var_p;
1502 struct variable **var_pp;
1505 eq = strchr(*s, '=');
1508 var_pp = get_ptr_to_local_var(*s);
1511 /* Remove variable from global linked list */
1513 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1514 *var_pp = var_p->next;
1515 /* Add it to returned list */
1519 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1530 static int static_get(struct in_str *i)
1539 static int static_peek(struct in_str *i)
1544 #if ENABLE_HUSH_INTERACTIVE
1546 static void cmdedit_update_prompt(void)
1548 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1549 G.PS1 = get_local_var_value("PS1");
1552 G.PS2 = get_local_var_value("PS2");
1560 static const char* setup_prompt_string(int promptmode)
1562 const char *prompt_str;
1563 debug_printf("setup_prompt_string %d ", promptmode);
1564 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1565 /* Set up the prompt */
1566 if (promptmode == 0) { /* PS1 */
1568 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1573 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1574 debug_printf("result '%s'\n", prompt_str);
1578 static void get_user_input(struct in_str *i)
1581 const char *prompt_str;
1583 prompt_str = setup_prompt_string(i->promptmode);
1584 #if ENABLE_FEATURE_EDITING
1585 /* Enable command line editing only while a command line
1586 * is actually being read */
1589 /* buglet: SIGINT will not make new prompt to appear _at once_,
1590 * only after <Enter>. (^C will work) */
1591 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1592 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1593 check_and_run_traps(0);
1594 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1595 i->eof_flag = (r < 0);
1596 if (i->eof_flag) { /* EOF/error detected */
1597 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1598 G.user_input_buf[1] = '\0';
1603 fputs(prompt_str, stdout);
1605 G.user_input_buf[0] = r = fgetc(i->file);
1606 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1607 //do we need check_and_run_traps(0)? (maybe only if stdin)
1608 } while (G.flag_SIGINT);
1609 i->eof_flag = (r == EOF);
1611 i->p = G.user_input_buf;
1614 #endif /* INTERACTIVE */
1616 /* This is the magic location that prints prompts
1617 * and gets data back from the user */
1618 static int file_get(struct in_str *i)
1622 /* If there is data waiting, eat it up */
1623 if (i->p && *i->p) {
1624 #if ENABLE_HUSH_INTERACTIVE
1628 if (i->eof_flag && !*i->p)
1630 /* note: ch is never NUL */
1632 /* need to double check i->file because we might be doing something
1633 * more complicated by now, like sourcing or substituting. */
1634 #if ENABLE_HUSH_INTERACTIVE
1635 if (G_interactive_fd && i->promptme && i->file == stdin) {
1638 } while (!*i->p); /* need non-empty line */
1639 i->promptmode = 1; /* PS2 */
1644 do ch = fgetc(i->file); while (ch == '\0');
1646 debug_printf("file_get: got '%c' %d\n", ch, ch);
1647 #if ENABLE_HUSH_INTERACTIVE
1654 /* All callers guarantee this routine will never
1655 * be used right after a newline, so prompting is not needed.
1657 static int file_peek(struct in_str *i)
1660 if (i->p && *i->p) {
1661 if (i->eof_flag && !i->p[1])
1664 /* note: ch is never NUL */
1666 do ch = fgetc(i->file); while (ch == '\0');
1667 i->eof_flag = (ch == EOF);
1668 i->peek_buf[0] = ch;
1669 i->peek_buf[1] = '\0';
1671 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1675 static void setup_file_in_str(struct in_str *i, FILE *f)
1677 i->peek = file_peek;
1679 #if ENABLE_HUSH_INTERACTIVE
1681 i->promptmode = 0; /* PS1 */
1687 static void setup_string_in_str(struct in_str *i, const char *s)
1689 i->peek = static_peek;
1690 i->get = static_get;
1691 #if ENABLE_HUSH_INTERACTIVE
1693 i->promptmode = 0; /* PS1 */
1703 #define B_CHUNK (32 * sizeof(char*))
1705 static void o_reset_to_empty_unquoted(o_string *o)
1713 static void o_free(o_string *o)
1716 memset(o, 0, sizeof(*o));
1719 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1724 static void o_grow_by(o_string *o, int len)
1726 if (o->length + len > o->maxlen) {
1727 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1728 o->data = xrealloc(o->data, 1 + o->maxlen);
1732 static void o_addchr(o_string *o, int ch)
1734 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1736 o->data[o->length] = ch;
1738 o->data[o->length] = '\0';
1741 static void o_addblock(o_string *o, const char *str, int len)
1744 memcpy(&o->data[o->length], str, len);
1746 o->data[o->length] = '\0';
1750 static void o_addstr(o_string *o, const char *str)
1752 o_addblock(o, str, strlen(str));
1754 static void nommu_addchr(o_string *o, int ch)
1760 # define nommu_addchr(o, str) ((void)0)
1763 static void o_addstr_with_NUL(o_string *o, const char *str)
1765 o_addblock(o, str, strlen(str) + 1);
1768 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1773 && (*str != '*' && *str != '?' && *str != '[')
1781 /* My analysis of quoting semantics tells me that state information
1782 * is associated with a destination, not a source.
1784 static void o_addqchr(o_string *o, int ch)
1787 char *found = strchr("*?[\\", ch);
1792 o->data[o->length] = '\\';
1795 o->data[o->length] = ch;
1797 o->data[o->length] = '\0';
1800 static void o_addQchr(o_string *o, int ch)
1803 if (o->o_escape && strchr("*?[\\", ch)) {
1805 o->data[o->length] = '\\';
1809 o->data[o->length] = ch;
1811 o->data[o->length] = '\0';
1814 static void o_addQstr(o_string *o, const char *str, int len)
1817 o_addblock(o, str, len);
1823 int ordinary_cnt = strcspn(str, "*?[\\");
1824 if (ordinary_cnt > len) /* paranoia */
1826 o_addblock(o, str, ordinary_cnt);
1827 if (ordinary_cnt == len)
1829 str += ordinary_cnt;
1830 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1834 if (ch) { /* it is necessarily one of "*?[\\" */
1836 o->data[o->length] = '\\';
1840 o->data[o->length] = ch;
1842 o->data[o->length] = '\0';
1846 /* A special kind of o_string for $VAR and `cmd` expansion.
1847 * It contains char* list[] at the beginning, which is grown in 16 element
1848 * increments. Actual string data starts at the next multiple of 16 * (char*).
1849 * list[i] contains an INDEX (int!) into this string data.
1850 * It means that if list[] needs to grow, data needs to be moved higher up
1851 * but list[i]'s need not be modified.
1852 * NB: remembering how many list[i]'s you have there is crucial.
1853 * o_finalize_list() operation post-processes this structure - calculates
1854 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1856 #if DEBUG_EXPAND || DEBUG_GLOB
1857 static void debug_print_list(const char *prefix, o_string *o, int n)
1859 char **list = (char**)o->data;
1860 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1864 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1865 prefix, list, n, string_start, o->length, o->maxlen);
1868 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1869 o->data + (int)list[i] + string_start,
1870 o->data + (int)list[i] + string_start);
1874 const char *p = o->data + (int)list[n - 1] + string_start;
1876 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1880 # define debug_print_list(prefix, o, n) ((void)0)
1883 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1884 * in list[n] so that it points past last stored byte so far.
1885 * It returns n+1. */
1886 static int o_save_ptr_helper(o_string *o, int n)
1888 char **list = (char**)o->data;
1892 if (!o->has_empty_slot) {
1893 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1894 string_len = o->length - string_start;
1895 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1896 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1897 /* list[n] points to string_start, make space for 16 more pointers */
1898 o->maxlen += 0x10 * sizeof(list[0]);
1899 o->data = xrealloc(o->data, o->maxlen + 1);
1900 list = (char**)o->data;
1901 memmove(list + n + 0x10, list + n, string_len);
1902 o->length += 0x10 * sizeof(list[0]);
1904 debug_printf_list("list[%d]=%d string_start=%d\n",
1905 n, string_len, string_start);
1908 /* We have empty slot at list[n], reuse without growth */
1909 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1910 string_len = o->length - string_start;
1911 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1912 n, string_len, string_start);
1913 o->has_empty_slot = 0;
1915 list[n] = (char*)(ptrdiff_t)string_len;
1919 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1920 static int o_get_last_ptr(o_string *o, int n)
1922 char **list = (char**)o->data;
1923 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1925 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1928 /* o_glob performs globbing on last list[], saving each result
1929 * as a new list[]. */
1930 static int o_glob(o_string *o, int n)
1936 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1938 return o_save_ptr_helper(o, n);
1939 pattern = o->data + o_get_last_ptr(o, n);
1940 debug_printf_glob("glob pattern '%s'\n", pattern);
1941 if (!glob_needed(pattern)) {
1943 o->length = unbackslash(pattern) - o->data;
1944 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1945 return o_save_ptr_helper(o, n);
1948 memset(&globdata, 0, sizeof(globdata));
1949 gr = glob(pattern, 0, NULL, &globdata);
1950 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1951 if (gr == GLOB_NOSPACE)
1952 bb_error_msg_and_die("out of memory during glob");
1953 if (gr == GLOB_NOMATCH) {
1954 globfree(&globdata);
1957 if (gr != 0) { /* GLOB_ABORTED ? */
1958 /* TODO: testcase for bad glob pattern behavior */
1959 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1961 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1962 char **argv = globdata.gl_pathv;
1963 o->length = pattern - o->data; /* "forget" pattern */
1965 o_addstr_with_NUL(o, *argv);
1966 n = o_save_ptr_helper(o, n);
1972 globfree(&globdata);
1974 debug_print_list("o_glob returning", o, n);
1978 /* If o->o_glob == 1, glob the string so far remembered.
1979 * Otherwise, just finish current list[] and start new */
1980 static int o_save_ptr(o_string *o, int n)
1982 if (o->o_glob) { /* if globbing is requested */
1983 /* If o->has_empty_slot, list[n] was already globbed
1984 * (if it was requested back then when it was filled)
1985 * so don't do that again! */
1986 if (!o->has_empty_slot)
1987 return o_glob(o, n); /* o_save_ptr_helper is inside */
1989 return o_save_ptr_helper(o, n);
1992 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1993 static char **o_finalize_list(o_string *o, int n)
1998 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2000 debug_print_list("finalized", o, n);
2001 debug_printf_expand("finalized n:%d\n", n);
2002 list = (char**)o->data;
2003 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2007 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2013 /* Expansion can recurse */
2014 #if ENABLE_HUSH_TICK
2015 static int process_command_subs(o_string *dest, const char *s);
2017 static char *expand_string_to_string(const char *str);
2019 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2020 parse_stream_dquoted(dest, input, dquote_end)
2022 static int parse_stream_dquoted(o_string *as_string,
2024 struct in_str *input,
2027 /* expand_strvec_to_strvec() takes a list of strings, expands
2028 * all variable references within and returns a pointer to
2029 * a list of expanded strings, possibly with larger number
2030 * of strings. (Think VAR="a b"; echo $VAR).
2031 * This new list is allocated as a single malloc block.
2032 * NULL-terminated list of char* pointers is at the beginning of it,
2033 * followed by strings themself.
2034 * Caller can deallocate entire list by single free(list). */
2036 /* Store given string, finalizing the word and starting new one whenever
2037 * we encounter IFS char(s). This is used for expanding variable values.
2038 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2039 static int expand_on_ifs(o_string *output, int n, const char *str)
2042 int word_len = strcspn(str, G.ifs);
2044 if (output->o_escape || !output->o_glob)
2045 o_addQstr(output, str, word_len);
2046 else /* protect backslashes against globbing up :) */
2047 o_addblock_duplicate_backslash(output, str, word_len);
2050 if (!*str) /* EOL - do not finalize word */
2052 o_addchr(output, '\0');
2053 debug_print_list("expand_on_ifs", output, n);
2054 n = o_save_ptr(output, n);
2055 str += strspn(str, G.ifs); /* skip ifs chars */
2057 debug_print_list("expand_on_ifs[1]", output, n);
2061 /* Helper to expand $((...)) and heredoc body. These act as if
2062 * they are in double quotes, with the exception that they are not :).
2063 * Just the rules are similar: "expand only $var and `cmd`"
2065 * Returns malloced string.
2066 * As an optimization, we return NULL if expansion is not needed.
2068 static char *expand_pseudo_dquoted(const char *str)
2071 struct in_str input;
2072 o_string dest = NULL_O_STRING;
2074 if (strchr(str, '$') == NULL
2075 #if ENABLE_HUSH_TICK
2076 && strchr(str, '`') == NULL
2082 /* We need to expand. Example:
2083 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2085 setup_string_in_str(&input, str);
2086 parse_stream_dquoted(NULL, &dest, &input, EOF);
2087 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2088 exp_str = expand_string_to_string(dest.data);
2089 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2090 o_free_unsafe(&dest);
2094 /* Expand all variable references in given string, adding words to list[]
2095 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2096 * to be filled). This routine is extremely tricky: has to deal with
2097 * variables/parameters with whitespace, $* and $@, and constructs like
2098 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2099 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2101 /* or_mask is either 0 (normal case) or 0x80 -
2102 * expansion of right-hand side of assignment == 1-element expand.
2103 * It will also do no globbing, and thus we must not backslash-quote!
2110 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2111 debug_print_list("expand_vars_to_list", output, n);
2112 n = o_save_ptr(output, n);
2113 debug_print_list("expand_vars_to_list[0]", output, n);
2115 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2118 char *dyn_val = NULL;
2119 const char *val = NULL;
2120 #if ENABLE_HUSH_TICK
2121 o_string subst_result = NULL_O_STRING;
2123 #if ENABLE_SH_MATH_SUPPORT
2124 char arith_buf[sizeof(arith_t)*3 + 2];
2126 o_addblock(output, arg, p - arg);
2127 debug_print_list("expand_vars_to_list[1]", output, n);
2129 p = strchr(p, SPECIAL_VAR_SYMBOL);
2131 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2132 /* "$@" is special. Even if quoted, it can still
2133 * expand to nothing (not even an empty string) */
2134 if ((first_ch & 0x7f) != '@')
2135 ored_ch |= first_ch;
2137 switch (first_ch & 0x7f) {
2138 /* Highest bit in first_ch indicates that var is double-quoted */
2140 val = utoa(G.root_pid);
2142 case '!': /* bg pid */
2143 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2145 case '?': /* exitcode */
2146 val = utoa(G.last_exitcode);
2148 case '#': /* argc */
2149 if (arg[1] != SPECIAL_VAR_SYMBOL)
2150 /* actually, it's a ${#var} */
2152 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2157 if (!G.global_argv[i])
2159 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2160 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2161 smallint sv = output->o_escape;
2162 /* unquoted var's contents should be globbed, so don't escape */
2163 output->o_escape = 0;
2164 while (G.global_argv[i]) {
2165 n = expand_on_ifs(output, n, G.global_argv[i]);
2166 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2167 if (G.global_argv[i++][0] && G.global_argv[i]) {
2168 /* this argv[] is not empty and not last:
2169 * put terminating NUL, start new word */
2170 o_addchr(output, '\0');
2171 debug_print_list("expand_vars_to_list[2]", output, n);
2172 n = o_save_ptr(output, n);
2173 debug_print_list("expand_vars_to_list[3]", output, n);
2176 output->o_escape = sv;
2178 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2179 * and in this case should treat it like '$*' - see 'else...' below */
2180 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2182 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2183 if (++i >= G.global_argc)
2185 o_addchr(output, '\0');
2186 debug_print_list("expand_vars_to_list[4]", output, n);
2187 n = o_save_ptr(output, n);
2189 } else { /* quoted $*: add as one word */
2191 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2192 if (!G.global_argv[++i])
2195 o_addchr(output, G.ifs[0]);
2199 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2200 /* "Empty variable", used to make "" etc to not disappear */
2204 #if ENABLE_HUSH_TICK
2205 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2208 /* Can't just stuff it into output o_string,
2209 * expanded result may need to be globbed
2210 * and $IFS-splitted */
2211 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2212 process_command_subs(&subst_result, arg);
2213 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2214 val = subst_result.data;
2217 #if ENABLE_SH_MATH_SUPPORT
2218 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2219 arith_eval_hooks_t hooks;
2224 arg++; /* skip '+' */
2225 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2226 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2228 exp_str = expand_pseudo_dquoted(arg);
2229 hooks.lookupvar = get_local_var_value;
2230 hooks.setvar = arith_set_local_var;
2231 hooks.endofname = endofname;
2232 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2236 const char *msg = "error in arithmetic";
2239 msg = "exponent less than 0";
2242 msg = "divide by 0";
2245 msg = "expression recursion loop detected";
2250 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2251 sprintf(arith_buf, arith_t_fmt, res);
2256 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2258 bool exp_len = false;
2259 bool exp_null = false;
2261 char exp_save = exp_save; /* for compiler */
2262 char exp_op = exp_op; /* for compiler */
2263 char *exp_word = exp_word; /* for compiler */
2267 arg[0] = first_ch & 0x7f;
2269 /* prepare for expansions */
2270 if (var[0] == '#') {
2271 /* handle length expansion ${#var} */
2275 /* maybe handle parameter expansion */
2276 exp_off = strcspn(var, ":-=+?%#");
2280 exp_save = var[exp_off];
2281 exp_null = exp_save == ':';
2282 exp_word = var + exp_off;
2285 exp_op = *exp_word++;
2286 var[exp_off] = '\0';
2290 /* lookup the variable in question */
2291 if (isdigit(var[0])) {
2292 /* handle_dollar() should have vetted var for us */
2294 if (i < G.global_argc)
2295 val = G.global_argv[i];
2296 /* else val remains NULL: $N with too big N */
2298 val = get_local_var_value(var);
2300 /* handle any expansions */
2302 debug_printf_expand("expand: length of '%s' = ", val);
2303 val = utoa(val ? strlen(val) : 0);
2304 debug_printf_expand("%s\n", val);
2305 } else if (exp_off) {
2306 if (exp_op == '%' || exp_op == '#') {
2308 /* we need to do a pattern match */
2311 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2312 if (exp_op == *exp_word) /* ## or %% */
2314 val = dyn_val = xstrdup(val);
2315 loc = scan(dyn_val, exp_word, match_at_left);
2316 if (match_at_left) /* # or ## */
2318 else if (loc) /* % or %% and match was found */
2322 /* we need to do an expansion */
2323 int exp_test = (!val || (exp_null && !val[0]));
2325 exp_test = !exp_test;
2326 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2327 exp_null ? "true" : "false", exp_test);
2329 if (exp_op == '?') {
2330 //TODO: how interactive bash aborts expansion mid-command?
2331 /* ${var?[error_msg_if_unset]} */
2332 /* ${var:?[error_msg_if_unset_or_null]} */
2333 /* mimic bash message */
2334 die_if_script("%s: %s",
2336 exp_word[0] ? exp_word : "parameter null or not set"
2342 if (exp_op == '=') {
2343 /* ${var=[word]} or ${var:=[word]} */
2344 if (isdigit(var[0]) || var[0] == '#') {
2345 /* mimic bash message */
2346 die_if_script("$%s: cannot assign in this way", var);
2349 char *new_var = xasprintf("%s=%s", var, val);
2350 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2356 var[exp_off] = exp_save;
2360 #if ENABLE_HUSH_TICK
2363 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2364 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2366 /* unquoted var's contents should be globbed, so don't escape */
2367 smallint sv = output->o_escape;
2368 output->o_escape = 0;
2369 n = expand_on_ifs(output, n, val);
2371 output->o_escape = sv;
2373 } else { /* quoted $VAR, val will be appended below */
2374 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2377 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2380 o_addQstr(output, val, strlen(val));
2383 /* Do the check to avoid writing to a const string */
2384 if (*p != SPECIAL_VAR_SYMBOL)
2385 *p = SPECIAL_VAR_SYMBOL;
2387 #if ENABLE_HUSH_TICK
2388 o_free(&subst_result);
2391 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2394 debug_print_list("expand_vars_to_list[a]", output, n);
2395 /* this part is literal, and it was already pre-quoted
2396 * if needed (much earlier), do not use o_addQstr here! */
2397 o_addstr_with_NUL(output, arg);
2398 debug_print_list("expand_vars_to_list[b]", output, n);
2399 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2400 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2403 /* allow to reuse list[n] later without re-growth */
2404 output->has_empty_slot = 1;
2406 o_addchr(output, '\0');
2411 static char **expand_variables(char **argv, int or_mask)
2416 o_string output = NULL_O_STRING;
2418 if (or_mask & 0x100) {
2419 output.o_escape = 1; /* protect against globbing for "$var" */
2420 /* (unquoted $var will temporarily switch it off) */
2427 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2430 debug_print_list("expand_variables", &output, n);
2432 /* output.data (malloced in one block) gets returned in "list" */
2433 list = o_finalize_list(&output, n);
2434 debug_print_strings("expand_variables[1]", list);
2438 static char **expand_strvec_to_strvec(char **argv)
2440 return expand_variables(argv, 0x100);
2443 /* Used for expansion of right hand of assignments */
2444 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2446 static char *expand_string_to_string(const char *str)
2448 char *argv[2], **list;
2450 argv[0] = (char*)str;
2452 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2454 if (!list[0] || list[1])
2455 bb_error_msg_and_die("BUG in varexp2");
2456 /* actually, just move string 2*sizeof(char*) bytes back */
2457 overlapping_strcpy((char*)list, list[0]);
2458 unbackslash((char*)list);
2459 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2463 /* Used for "eval" builtin */
2464 static char* expand_strvec_to_string(char **argv)
2468 list = expand_variables(argv, 0x80);
2469 /* Convert all NULs to spaces */
2474 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2475 bb_error_msg_and_die("BUG in varexp3");
2476 /* bash uses ' ' regardless of $IFS contents */
2481 overlapping_strcpy((char*)list, list[0]);
2482 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2486 static char **expand_assignments(char **argv, int count)
2490 /* Expand assignments into one string each */
2491 for (i = 0; i < count; i++) {
2492 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2500 void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
2502 static void reset_traps_to_defaults(void)
2504 /* This function is always called in a child shell
2505 * after fork (not vfork, NOMMU doesn't use this function).
2506 * Child shells are not interactive.
2507 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2508 * Testcase: (while :; do :; done) + ^Z should background.
2509 * Same goes for SIGTERM, SIGHUP, SIGINT.
2514 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2517 /* Stupid. It can be done with *single* &= op, but we can't use
2518 * the fact that G.blocked_set is implemented as a bitmask... */
2519 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2523 sigdelset(&G.blocked_set, sig);
2530 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2531 mask = G.non_DFL_mask;
2532 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2536 G.traps[sig] = NULL;
2537 /* There is no signal for 0 (EXIT) */
2540 /* There was a trap handler, we are removing it.
2541 * But if sig still has non-DFL handling,
2542 * we should not unblock it. */
2545 sigdelset(&G.blocked_set, sig);
2547 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2552 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2553 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
2555 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2556 char *heredoc_argv[4];
2557 struct variable *cur;
2558 #if ENABLE_HUSH_FUNCTIONS
2559 struct function *funcp;
2564 if (!g_argv0) { /* heredoc */
2565 argv = heredoc_argv;
2566 argv[0] = (char *) G.argv0_for_re_execing;
2567 argv[1] = (char *) "-<";
2568 argv[2] = (char *) s;
2570 pp = &argv[3]; /* used as pointer to empty environment */
2574 sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
2575 , (unsigned) G.root_pid
2576 , (unsigned) G.last_bg_pid
2577 , (unsigned) G.last_exitcode
2578 IF_HUSH_LOOPS(, G.depth_of_loop)
2580 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2581 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2584 for (cur = G.top_var; cur; cur = cur->next) {
2585 if (!cur->flg_export || cur->flg_read_only)
2588 #if ENABLE_HUSH_FUNCTIONS
2589 for (funcp = G.top_func; funcp; funcp = funcp->next)
2595 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2596 *pp++ = (char *) G.argv0_for_re_execing;
2598 for (cur = G.top_var; cur; cur = cur->next) {
2599 if (cur->varstr == hush_version_str)
2601 if (cur->flg_read_only) {
2602 *pp++ = (char *) "-R";
2603 *pp++ = cur->varstr;
2604 } else if (!cur->flg_export) {
2605 *pp++ = (char *) "-V";
2606 *pp++ = cur->varstr;
2609 #if ENABLE_HUSH_FUNCTIONS
2610 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2611 *pp++ = (char *) "-F";
2612 *pp++ = funcp->name;
2613 *pp++ = funcp->body_as_string;
2616 /* We can pass activated traps here. Say, -Tnn:trap_string
2618 * However, POSIX says that subshells reset signals with traps
2620 * I tested bash-3.2 and it not only does that with true subshells
2621 * of the form ( list ), but with any forked children shells.
2622 * I set trap "echo W" WINCH; and then tried:
2624 * { echo 1; sleep 20; echo 2; } &
2625 * while true; do echo 1; sleep 20; echo 2; break; done &
2626 * true | { echo 1; sleep 20; echo 2; } | cat
2628 * In all these cases sending SIGWINCH to the child shell
2629 * did not run the trap. If I add trap "echo V" WINCH;
2630 * _inside_ group (just before echo 1), it works.
2632 * I conclude it means we don't need to pass active traps here.
2633 * exec syscall below resets them to SIG_DFL for us.
2635 *pp++ = (char *) "-c";
2640 /* *pp = NULL; - is already there */
2644 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2645 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2646 execve(bb_busybox_exec_path, argv, pp);
2647 /* Fallback. Useful for init=/bin/hush usage etc */
2648 if (argv[0][0] == '/')
2649 execve(argv[0], argv, pp);
2650 xfunc_error_retval = 127;
2651 bb_error_msg_and_die("can't re-execute the shell");
2653 #endif /* !BB_MMU */
2656 static void setup_heredoc(struct redir_struct *redir)
2658 struct fd_pair pair;
2661 /* the _body_ of heredoc (misleading field name) */
2662 const char *heredoc = redir->rd_filename;
2669 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2670 expanded = expand_pseudo_dquoted(heredoc);
2674 len = strlen(heredoc);
2676 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2678 xmove_fd(pair.rd, redir->rd_fd);
2680 /* Try writing without forking. Newer kernels have
2681 * dynamically growing pipes. Must use non-blocking write! */
2684 written = write(pair.wr, heredoc, len);
2695 ndelay_off(pair.wr);
2697 /* Okay, pipe buffer was not big enough */
2698 /* Note: we must not create a stray child (bastard? :)
2699 * for the unsuspecting parent process. Child creates a grandchild
2700 * and exits before parent execs the process which consumes heredoc
2701 * (that exec happens after we return from this function) */
2707 bb_perror_msg_and_die("vfork");
2710 disable_restore_tty_pgrp_on_exit();
2711 pid = BB_MMU ? fork() : vfork();
2713 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2717 close(redir->rd_fd); /* read side of the pipe */
2719 full_write(pair.wr, heredoc, len); /* may loop or block */
2722 /* Delegate blocking writes to another process */
2723 xmove_fd(pair.wr, STDOUT_FILENO);
2724 re_execute_shell(&to_free, heredoc, NULL, NULL);
2728 #if ENABLE_HUSH_FAST
2730 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2732 enable_restore_tty_pgrp_on_exit();
2738 wait(NULL); /* wait till child has died */
2741 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2742 * and stderr if they are redirected. */
2743 static int setup_redirects(struct command *prog, int squirrel[])
2746 struct redir_struct *redir;
2748 for (redir = prog->redirects; redir; redir = redir->next) {
2749 if (redir->rd_type == REDIRECT_HEREDOC2) {
2750 /* rd_fd<<HERE case */
2751 if (squirrel && redir->rd_fd < 3
2752 && squirrel[redir->rd_fd] < 0
2754 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2756 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2758 debug_printf_parse("set heredoc '%s'\n",
2759 redir->rd_filename);
2760 setup_heredoc(redir);
2764 if (redir->rd_dup == REDIRFD_TO_FILE) {
2765 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2767 if (redir->rd_filename == NULL) {
2768 /* Something went wrong in the parse.
2769 * Pretend it didn't happen */
2770 bb_error_msg("bug in redirect parse");
2773 mode = redir_table[redir->rd_type].mode;
2774 p = expand_string_to_string(redir->rd_filename);
2775 openfd = open_or_warn(p, mode);
2778 /* this could get lost if stderr has been redirected, but
2779 * bash and ash both lose it as well (though zsh doesn't!) */
2780 //what the above comment tries to say?
2784 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2785 openfd = redir->rd_dup;
2788 if (openfd != redir->rd_fd) {
2789 if (squirrel && redir->rd_fd < 3
2790 && squirrel[redir->rd_fd] < 0
2792 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2794 if (openfd == REDIRFD_CLOSE) {
2795 /* "n>-" means "close me" */
2796 close(redir->rd_fd);
2798 xdup2(openfd, redir->rd_fd);
2799 if (redir->rd_dup == REDIRFD_TO_FILE)
2807 static void restore_redirects(int squirrel[])
2810 for (i = 0; i < 3; i++) {
2813 /* We simply die on error */
2820 static void free_pipe_list(struct pipe *head);
2822 /* Return code is the exit status of the pipe */
2823 static void free_pipe(struct pipe *pi)
2826 struct command *command;
2827 struct redir_struct *r, *rnext;
2830 if (pi->stopped_cmds > 0) /* why? */
2832 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2833 for (i = 0; i < pi->num_cmds; i++) {
2834 command = &pi->cmds[i];
2835 debug_printf_clean(" command %d:\n", i);
2836 if (command->argv) {
2837 for (a = 0, p = command->argv; *p; a++, p++) {
2838 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2840 free_strings(command->argv);
2841 command->argv = NULL;
2843 /* not "else if": on syntax error, we may have both! */
2844 if (command->group) {
2845 debug_printf_clean(" begin group (grp_type:%d)\n",
2847 free_pipe_list(command->group);
2848 debug_printf_clean(" end group\n");
2849 command->group = NULL;
2851 /* else is crucial here.
2852 * If group != NULL, child_func is meaningless */
2853 #if ENABLE_HUSH_FUNCTIONS
2854 else if (command->child_func) {
2855 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2856 command->child_func->parent_cmd = NULL;
2860 free(command->group_as_string);
2861 command->group_as_string = NULL;
2863 for (r = command->redirects; r; r = rnext) {
2864 debug_printf_clean(" redirect %d%s",
2865 r->rd_fd, redir_table[r->rd_type].descrip);
2866 /* guard against the case >$FOO, where foo is unset or blank */
2867 if (r->rd_filename) {
2868 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2869 free(r->rd_filename);
2870 r->rd_filename = NULL;
2872 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2876 command->redirects = NULL;
2878 free(pi->cmds); /* children are an array, they get freed all at once */
2886 static void free_pipe_list(struct pipe *head)
2888 struct pipe *pi, *next;
2890 for (pi = head; pi; pi = next) {
2892 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2895 debug_printf_clean("pipe followup code %d\n", pi->followup);
2897 /*pi->next = NULL;*/
2903 static int run_list(struct pipe *pi);
2905 #define parse_stream(pstring, input, end_trigger) \
2906 parse_stream(input, end_trigger)
2908 static struct pipe *parse_stream(char **pstring,
2909 struct in_str *input,
2911 static void parse_and_run_string(const char *s);
2914 static char *find_in_path(const char *arg)
2917 const char *PATH = get_local_var_value("PATH");
2923 const char *end = strchrnul(PATH, ':');
2924 int sz = end - PATH; /* must be int! */
2928 ret = xasprintf("%.*s/%s", sz, PATH, arg);
2930 /* We have xxx::yyyy in $PATH,
2931 * it means "use current dir" */
2934 if (access(ret, F_OK) == 0)
2947 static const struct built_in_command* find_builtin(const char *name)
2949 const struct built_in_command *x;
2950 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2951 if (strcmp(name, x->cmd) != 0)
2953 debug_printf_exec("found builtin '%s'\n", name);
2959 #if ENABLE_HUSH_FUNCTIONS
2960 static const struct function *find_function(const char *name)
2962 const struct function *funcp = G.top_func;
2964 if (strcmp(name, funcp->name) == 0) {
2967 funcp = funcp->next;
2970 debug_printf_exec("found function '%s'\n", name);
2974 /* Note: takes ownership on name ptr */
2975 static struct function *new_function(char *name)
2977 struct function *funcp;
2978 struct function **funcpp = &G.top_func;
2980 while ((funcp = *funcpp) != NULL) {
2981 struct command *cmd;
2983 if (strcmp(funcp->name, name) != 0) {
2984 funcpp = &funcp->next;
2988 cmd = funcp->parent_cmd;
2989 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2991 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2993 /* Note: if !funcp->body, do not free body_as_string!
2994 * This is a special case of "-F name body" function:
2995 * body_as_string was not malloced! */
2997 free_pipe_list(funcp->body);
2999 free(funcp->body_as_string);
3003 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3004 cmd->argv[0] = funcp->name;
3005 cmd->group = funcp->body;
3007 cmd->group_as_string = funcp->body_as_string;
3012 debug_printf_exec("remembering new function '%s'\n", name);
3013 funcp = *funcpp = xzalloc(sizeof(*funcp));
3014 /*funcp->next = NULL;*/
3020 static void unset_func(const char *name)
3022 struct function *funcp;
3023 struct function **funcpp = &G.top_func;
3025 while ((funcp = *funcpp) != NULL) {
3026 if (strcmp(funcp->name, name) == 0) {
3027 *funcpp = funcp->next;
3028 /* funcp is unlinked now, deleting it.
3029 * Note: if !funcp->body, the function was created by
3030 * "-F name body", do not free ->body_as_string
3031 * and ->name as they were not malloced. */
3033 free_pipe_list(funcp->body);
3036 free(funcp->body_as_string);
3042 funcpp = &funcp->next;
3047 #define exec_function(nommu_save, funcp, argv) \
3048 exec_function(funcp, argv)
3050 static void exec_function(nommu_save_t *nommu_save,
3051 const struct function *funcp,
3052 char **argv) NORETURN;
3053 static void exec_function(nommu_save_t *nommu_save,
3054 const struct function *funcp,
3060 argv[0] = G.global_argv[0];
3061 G.global_argv = argv;
3065 /* On MMU, funcp->body is always non-NULL */
3066 n = run_list(funcp->body);
3070 re_execute_shell(&nommu_save->argv_from_re_execing,
3071 funcp->body_as_string,
3077 static int run_function(const struct function *funcp, char **argv)
3083 save_and_replace_G_args(&sv, argv);
3085 /* "we are in function, ok to use return" */
3086 sv_flg = G.flag_return_in_progress;
3087 G.flag_return_in_progress = -1;
3088 #if ENABLE_HUSH_LOCAL
3089 G.func_nest_level++;
3092 /* On MMU, funcp->body is always non-NULL */
3095 /* Function defined by -F */
3096 parse_and_run_string(funcp->body_as_string);
3097 rc = G.last_exitcode;
3101 rc = run_list(funcp->body);
3104 #if ENABLE_HUSH_LOCAL
3106 struct variable *var;
3107 struct variable **var_pp;
3109 var_pp = &G.top_var;
3110 while ((var = *var_pp) != NULL) {
3111 if (var->func_nest_level < G.func_nest_level) {
3112 var_pp = &var->next;
3116 if (var->flg_export)
3117 bb_unsetenv(var->varstr);
3118 /* Remove from global list */
3119 *var_pp = var->next;
3125 G.func_nest_level--;
3128 G.flag_return_in_progress = sv_flg;
3130 restore_G_args(&sv, argv);
3134 #endif /* ENABLE_HUSH_FUNCTIONS */
3138 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3139 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3140 #define pseudo_exec(nommu_save, command, argv_expanded) \
3141 pseudo_exec(command, argv_expanded)
3144 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3146 * Don't exit() here. If you don't exec, use _exit instead.
3147 * The at_exit handlers apparently confuse the calling process,
3148 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3149 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3150 char **argv, int assignment_cnt,
3151 char **argv_expanded) NORETURN;
3152 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3153 char **argv, int assignment_cnt,
3154 char **argv_expanded)
3158 /* Case when we are here: ... | var=val | ... */
3159 if (!argv[assignment_cnt])
3160 _exit(EXIT_SUCCESS);
3162 new_env = expand_assignments(argv, assignment_cnt);
3164 set_vars_and_save_old(new_env);
3165 free(new_env); /* optional */
3166 /* we can also destroy set_vars_and_save_old's return value,
3169 nommu_save->new_env = new_env;
3170 nommu_save->old_vars = set_vars_and_save_old(new_env);
3172 if (argv_expanded) {
3173 argv = argv_expanded;
3175 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3177 nommu_save->argv = argv;
3181 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3182 if (strchr(argv[0], '/') != NULL)
3186 /* On NOMMU, we must never block!
3187 * Example: { sleep 99999 | read line } & echo Ok
3188 * read builtin will block on read syscall, leaving parent blocked
3189 * in vfork. Therefore we can't do this:
3192 /* Check if the command matches any of the builtins.
3193 * Depending on context, this might be redundant. But it's
3194 * easier to waste a few CPU cycles than it is to figure out
3195 * if this is one of those cases.
3199 const struct built_in_command *x = find_builtin(argv[0]);
3201 rcode = x->function(argv);
3207 #if ENABLE_HUSH_FUNCTIONS
3208 /* Check if the command matches any functions */
3210 const struct function *funcp = find_function(argv[0]);
3212 exec_function(nommu_save, funcp, argv);
3217 #if ENABLE_FEATURE_SH_STANDALONE
3218 /* Check if the command matches any busybox applets */
3220 int a = find_applet_by_name(argv[0]);
3222 # if BB_MMU /* see above why on NOMMU it is not allowed */
3223 if (APPLET_IS_NOEXEC(a)) {
3224 debug_printf_exec("running applet '%s'\n", argv[0]);
3225 run_applet_no_and_exit(a, argv);
3228 /* Re-exec ourselves */
3229 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3230 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3231 execv(bb_busybox_exec_path, argv);
3232 /* If they called chroot or otherwise made the binary no longer
3233 * executable, fall through */
3238 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3241 debug_printf_exec("execing '%s'\n", argv[0]);
3242 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3243 execvp(argv[0], argv);
3244 bb_perror_msg("can't execute '%s'", argv[0]);
3245 _exit(EXIT_FAILURE);
3248 /* Called after [v]fork() in run_pipe
3250 static void pseudo_exec(nommu_save_t *nommu_save,
3251 struct command *command,
3252 char **argv_expanded) NORETURN;
3253 static void pseudo_exec(nommu_save_t *nommu_save,
3254 struct command *command,
3255 char **argv_expanded)
3257 if (command->argv) {
3258 pseudo_exec_argv(nommu_save, command->argv,
3259 command->assignment_cnt, argv_expanded);
3262 if (command->group) {
3263 /* Cases when we are here:
3266 * ... | ( list ) | ...
3267 * ... | { list } | ...
3271 debug_printf_exec("pseudo_exec: run_list\n");
3272 reset_traps_to_defaults();
3273 rcode = run_list(command->group);
3274 /* OK to leak memory by not calling free_pipe_list,
3275 * since this process is about to exit */
3278 re_execute_shell(&nommu_save->argv_from_re_execing,
3279 command->group_as_string,
3285 /* Case when we are here: ... | >file */
3286 debug_printf_exec("pseudo_exec'ed null command\n");
3287 _exit(EXIT_SUCCESS);
3291 static const char *get_cmdtext(struct pipe *pi)
3297 /* This is subtle. ->cmdtext is created only on first backgrounding.
3298 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3299 * On subsequent bg argv is trashed, but we won't use it */
3302 argv = pi->cmds[0].argv;
3303 if (!argv || !argv[0]) {
3304 pi->cmdtext = xzalloc(1);
3310 len += strlen(*argv) + 1;
3314 argv = pi->cmds[0].argv;
3316 len = strlen(*argv);
3317 memcpy(p, *argv, len);
3325 static void insert_bg_job(struct pipe *pi)
3327 struct pipe *job, **jobp;
3330 /* Linear search for the ID of the job to use */
3332 for (job = G.job_list; job; job = job->next)
3333 if (job->jobid >= pi->jobid)
3334 pi->jobid = job->jobid + 1;
3336 /* Add job to the list of running jobs */
3338 while ((job = *jobp) != NULL)
3340 job = *jobp = xmalloc(sizeof(*job));
3342 *job = *pi; /* physical copy */
3344 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3345 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3346 for (i = 0; i < pi->num_cmds; i++) {
3347 job->cmds[i].pid = pi->cmds[i].pid;
3348 /* all other fields are not used and stay zero */
3350 job->cmdtext = xstrdup(get_cmdtext(pi));
3352 if (G_interactive_fd)
3353 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3354 /* Last command's pid goes to $! */
3355 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3356 G.last_jobid = job->jobid;
3359 static void remove_bg_job(struct pipe *pi)
3361 struct pipe *prev_pipe;
3363 if (pi == G.job_list) {
3364 G.job_list = pi->next;
3366 prev_pipe = G.job_list;
3367 while (prev_pipe->next != pi)
3368 prev_pipe = prev_pipe->next;
3369 prev_pipe->next = pi->next;
3372 G.last_jobid = G.job_list->jobid;
3377 /* Remove a backgrounded job */
3378 static void delete_finished_bg_job(struct pipe *pi)
3381 pi->stopped_cmds = 0;
3387 /* Check to see if any processes have exited -- if they
3388 * have, figure out why and see if a job has completed */
3389 static int checkjobs(struct pipe* fg_pipe)
3399 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3401 attributes = WUNTRACED;
3402 if (fg_pipe == NULL)
3403 attributes |= WNOHANG;
3406 #if ENABLE_HUSH_FAST
3407 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3408 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3409 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3410 /* There was neither fork nor SIGCHLD since last waitpid */
3411 /* Avoid doing waitpid syscall if possible */
3412 if (!G.we_have_children) {
3416 if (fg_pipe == NULL) { /* is WNOHANG set? */
3417 /* We have children, but they did not exit
3418 * or stop yet (we saw no SIGCHLD) */
3421 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3425 /* Do we do this right?
3426 * bash-3.00# sleep 20 | false
3428 * [3]+ Stopped sleep 20 | false
3429 * bash-3.00# echo $?
3430 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3431 * [hush 1.14.0: yes we do it right]
3438 #if ENABLE_HUSH_FAST
3439 i = G.count_SIGCHLD;
3441 childpid = waitpid(-1, &status, attributes);
3442 if (childpid <= 0) {
3443 if (childpid && errno != ECHILD)
3444 bb_perror_msg("waitpid");
3445 #if ENABLE_HUSH_FAST
3446 else { /* Until next SIGCHLD, waitpid's are useless */
3447 G.we_have_children = (childpid == 0);
3448 G.handled_SIGCHLD = i;
3449 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3454 dead = WIFEXITED(status) || WIFSIGNALED(status);
3457 if (WIFSTOPPED(status))
3458 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3459 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3460 if (WIFSIGNALED(status))
3461 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3462 childpid, WTERMSIG(status), WEXITSTATUS(status));
3463 if (WIFEXITED(status))
3464 debug_printf_jobs("pid %d exited, exitcode %d\n",
3465 childpid, WEXITSTATUS(status));
3467 /* Were we asked to wait for fg pipe? */
3469 for (i = 0; i < fg_pipe->num_cmds; i++) {
3470 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3471 if (fg_pipe->cmds[i].pid != childpid)
3474 fg_pipe->cmds[i].pid = 0;
3475 fg_pipe->alive_cmds--;
3476 if (i == fg_pipe->num_cmds - 1) {
3477 /* last process gives overall exitstatus */
3478 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3479 rcode = WEXITSTATUS(status);
3480 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3481 /* bash prints killing signal's name for *last*
3482 * process in pipe (prints just newline for SIGINT).
3483 * Mimic this. Example: "sleep 5" + ^\
3485 if (WIFSIGNALED(status)) {
3486 int sig = WTERMSIG(status);
3487 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3491 fg_pipe->cmds[i].is_stopped = 1;
3492 fg_pipe->stopped_cmds++;
3494 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3495 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3496 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3497 /* All processes in fg pipe have exited or stopped */
3498 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3499 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3500 * and "killall -STOP cat" */
3501 if (G_interactive_fd) {
3503 if (fg_pipe->alive_cmds)
3504 insert_bg_job(fg_pipe);
3509 /* There are still running processes in the fg pipe */
3510 goto wait_more; /* do waitpid again */
3512 /* it wasnt fg_pipe, look for process in bg pipes */
3516 /* We asked to wait for bg or orphaned children */
3517 /* No need to remember exitcode in this case */
3518 for (pi = G.job_list; pi; pi = pi->next) {
3519 for (i = 0; i < pi->num_cmds; i++) {
3520 if (pi->cmds[i].pid == childpid)
3521 goto found_pi_and_prognum;
3524 /* Happens when shell is used as init process (init=/bin/sh) */
3525 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3526 continue; /* do waitpid again */
3528 found_pi_and_prognum:
3531 pi->cmds[i].pid = 0;
3533 if (!pi->alive_cmds) {
3534 if (G_interactive_fd)
3535 printf(JOB_STATUS_FORMAT, pi->jobid,
3536 "Done", pi->cmdtext);
3537 delete_finished_bg_job(pi);
3541 pi->cmds[i].is_stopped = 1;
3545 } /* while (waitpid succeeds)... */
3551 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3554 int rcode = checkjobs(fg_pipe);
3555 if (G_saved_tty_pgrp) {
3556 /* Job finished, move the shell to the foreground */
3557 p = getpgrp(); /* our process group id */
3558 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3559 tcsetpgrp(G_interactive_fd, p);
3565 /* Start all the jobs, but don't wait for anything to finish.
3568 * Return code is normally -1, when the caller has to wait for children
3569 * to finish to determine the exit status of the pipe. If the pipe
3570 * is a simple builtin command, however, the action is done by the
3571 * time run_pipe returns, and the exit code is provided as the
3574 * Returns -1 only if started some children. IOW: we have to
3575 * mask out retvals of builtins etc with 0xff!
3577 * The only case when we do not need to [v]fork is when the pipe
3578 * is single, non-backgrounded, non-subshell command. Examples:
3579 * cmd ; ... { list } ; ...
3580 * cmd && ... { list } && ...
3581 * cmd || ... { list } || ...
3582 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3583 * or (if SH_STANDALONE) an applet, and we can run the { list }
3584 * with run_list. If it isn't one of these, we fork and exec cmd.
3586 * Cases when we must fork:
3587 * non-single: cmd | cmd
3588 * backgrounded: cmd & { list } &
3589 * subshell: ( list ) [&]
3591 static int run_pipe(struct pipe *pi)
3593 static const char *const null_ptr = NULL;
3596 struct command *command;
3597 char **argv_expanded;
3600 /* it is not always needed, but we aim to smaller code */
3601 int squirrel[] = { -1, -1, -1 };
3604 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3607 IF_HUSH_JOB(pi->pgrp = -1;)
3608 pi->stopped_cmds = 0;
3609 command = &(pi->cmds[0]);
3610 argv_expanded = NULL;
3612 if (pi->num_cmds != 1
3613 || pi->followup == PIPE_BG
3614 || command->grp_type == GRP_SUBSHELL
3621 debug_printf_exec(": group:%p argv:'%s'\n",
3622 command->group, command->argv ? command->argv[0] : "NONE");
3624 if (command->group) {
3625 #if ENABLE_HUSH_FUNCTIONS
3626 if (command->grp_type == GRP_FUNCTION) {
3627 /* "executing" func () { list } */
3628 struct function *funcp;
3630 funcp = new_function(command->argv[0]);
3631 /* funcp->name is already set to argv[0] */
3632 funcp->body = command->group;
3634 funcp->body_as_string = command->group_as_string;
3635 command->group_as_string = NULL;
3637 command->group = NULL;
3638 command->argv[0] = NULL;
3639 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3640 funcp->parent_cmd = command;
3641 command->child_func = funcp;
3643 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3645 return EXIT_SUCCESS;
3649 debug_printf("non-subshell group\n");
3650 rcode = 1; /* exitcode if redir failed */
3651 if (setup_redirects(command, squirrel) == 0) {
3652 debug_printf_exec(": run_list\n");
3653 rcode = run_list(command->group) & 0xff;
3655 restore_redirects(squirrel);
3656 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3658 debug_printf_exec("run_pipe: return %d\n", rcode);
3662 argv = command->argv ? command->argv : (char **) &null_ptr;
3664 const struct built_in_command *x;
3665 #if ENABLE_HUSH_FUNCTIONS
3666 const struct function *funcp;
3670 char **new_env = NULL;
3671 struct variable *old_vars = NULL;
3673 if (argv[command->assignment_cnt] == NULL) {
3674 /* Assignments, but no command */
3675 /* Ensure redirects take effect. Try "a=t >file" */
3676 rcode = setup_redirects(command, squirrel);
3677 restore_redirects(squirrel);
3678 /* Set shell variables */
3680 p = expand_string_to_string(*argv);
3681 debug_printf_exec("set shell var:'%s'->'%s'\n",
3683 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3686 /* Do we need to flag set_local_var() errors?
3687 * "assignment to readonly var" and "putenv error"
3689 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3691 debug_printf_exec("run_pipe: return %d\n", rcode);
3695 /* Expand the rest into (possibly) many strings each */
3696 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3698 x = find_builtin(argv_expanded[0]);
3699 #if ENABLE_HUSH_FUNCTIONS
3702 funcp = find_function(argv_expanded[0]);
3706 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3707 debug_printf("exec with redirects only\n");
3708 rcode = setup_redirects(command, NULL);
3709 goto clean_up_and_ret1;
3712 /* setup_redirects acts on file descriptors, not FILEs.
3713 * This is perfect for work that comes after exec().
3714 * Is it really safe for inline use? Experimentally,
3715 * things seem to work. */
3716 rcode = setup_redirects(command, squirrel);
3718 new_env = expand_assignments(argv, command->assignment_cnt);
3719 old_vars = set_vars_and_save_old(new_env);
3721 debug_printf_exec(": builtin '%s' '%s'...\n",
3722 x->cmd, argv_expanded[1]);
3723 rcode = x->function(argv_expanded) & 0xff;
3726 #if ENABLE_HUSH_FUNCTIONS
3728 # if ENABLE_HUSH_LOCAL
3729 struct variable **sv;
3730 sv = G.shadowed_vars_pp;
3731 G.shadowed_vars_pp = &old_vars;
3733 debug_printf_exec(": function '%s' '%s'...\n",
3734 funcp->name, argv_expanded[1]);
3735 rcode = run_function(funcp, argv_expanded) & 0xff;
3736 # if ENABLE_HUSH_LOCAL
3737 G.shadowed_vars_pp = sv;
3742 #if ENABLE_FEATURE_SH_STANDALONE
3745 restore_redirects(squirrel);
3746 unset_vars(new_env);
3749 free(argv_expanded);
3750 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3752 debug_printf_exec("run_pipe return %d\n", rcode);
3756 #if ENABLE_FEATURE_SH_STANDALONE
3757 i = find_applet_by_name(argv_expanded[0]);
3758 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3759 rcode = setup_redirects(command, squirrel);
3761 new_env = expand_assignments(argv, command->assignment_cnt);
3762 old_vars = set_vars_and_save_old(new_env);
3763 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3764 argv_expanded[0], argv_expanded[1]);
3765 rcode = run_nofork_applet(i, argv_expanded);
3767 goto clean_up_and_ret;
3770 /* It is neither builtin nor applet. We must fork. */
3774 /* NB: argv_expanded may already be created, and that
3775 * might include `cmd` runs! Do not rerun it! We *must*
3776 * use argv_expanded if it's non-NULL */
3778 /* Going to fork a child per each pipe member */
3782 for (i = 0; i < pi->num_cmds; i++) {
3783 struct fd_pair pipefds;
3785 volatile nommu_save_t nommu_save;
3786 nommu_save.new_env = NULL;
3787 nommu_save.old_vars = NULL;
3788 nommu_save.argv = NULL;
3789 nommu_save.argv_from_re_execing = NULL;
3791 command = &(pi->cmds[i]);
3792 if (command->argv) {
3793 debug_printf_exec(": pipe member '%s' '%s'...\n",
3794 command->argv[0], command->argv[1]);
3796 debug_printf_exec(": pipe member with no argv\n");
3799 /* pipes are inserted between pairs of commands */
3802 if ((i + 1) < pi->num_cmds)
3803 xpiped_pair(pipefds);
3805 command->pid = BB_MMU ? fork() : vfork();
3806 if (!command->pid) { /* child */
3808 disable_restore_tty_pgrp_on_exit();
3810 /* Every child adds itself to new process group
3811 * with pgid == pid_of_first_child_in_pipe */
3812 if (G.run_list_level == 1 && G_interactive_fd) {
3815 if (pgrp < 0) /* true for 1st process only */
3817 if (setpgid(0, pgrp) == 0
3818 && pi->followup != PIPE_BG
3819 && G_saved_tty_pgrp /* we have ctty */
3821 /* We do it in *every* child, not just first,
3823 tcsetpgrp(G_interactive_fd, pgrp);
3827 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3828 /* 1st cmd in backgrounded pipe
3829 * should have its stdin /dev/null'ed */
3831 if (open(bb_dev_null, O_RDONLY))
3832 xopen("/", O_RDONLY);
3834 xmove_fd(nextin, 0);
3836 xmove_fd(pipefds.wr, 1);
3839 /* Like bash, explicit redirects override pipes,
3840 * and the pipe fd is available for dup'ing. */
3841 if (setup_redirects(command, NULL))
3844 /* Restore default handlers just prior to exec */
3845 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3847 /* Stores to nommu_save list of env vars putenv'ed
3848 * (NOMMU, on MMU we don't need that) */
3849 /* cast away volatility... */
3850 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3851 /* pseudo_exec() does not return */
3854 /* parent or error */
3855 #if ENABLE_HUSH_FAST
3857 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3859 enable_restore_tty_pgrp_on_exit();
3861 /* Clean up after vforked child */
3862 free(nommu_save.argv);
3863 free(nommu_save.argv_from_re_execing);
3864 unset_vars(nommu_save.new_env);
3865 add_vars(nommu_save.old_vars);
3867 free(argv_expanded);
3868 argv_expanded = NULL;
3869 if (command->pid < 0) { /* [v]fork failed */
3870 /* Clearly indicate, was it fork or vfork */
3871 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3875 /* Second and next children need to know pid of first one */
3877 pi->pgrp = command->pid;
3883 if ((i + 1) < pi->num_cmds)
3885 /* Pass read (output) pipe end to next iteration */
3886 nextin = pipefds.rd;
3889 if (!pi->alive_cmds) {
3891 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3896 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3900 #ifndef debug_print_tree
3901 static void debug_print_tree(struct pipe *pi, int lvl)
3903 static const char *const PIPE[] = {
3909 static const char *RES[] = {
3910 [RES_NONE ] = "NONE" ,
3913 [RES_THEN ] = "THEN" ,
3914 [RES_ELIF ] = "ELIF" ,
3915 [RES_ELSE ] = "ELSE" ,
3918 #if ENABLE_HUSH_LOOPS
3919 [RES_FOR ] = "FOR" ,
3920 [RES_WHILE] = "WHILE",
3921 [RES_UNTIL] = "UNTIL",
3923 [RES_DONE ] = "DONE" ,
3925 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3928 #if ENABLE_HUSH_CASE
3929 [RES_CASE ] = "CASE" ,
3930 [RES_CASE_IN ] = "CASE_IN" ,
3931 [RES_MATCH] = "MATCH",
3932 [RES_CASE_BODY] = "CASE_BODY",
3933 [RES_ESAC ] = "ESAC" ,
3935 [RES_XXXX ] = "XXXX" ,
3936 [RES_SNTX ] = "SNTX" ,
3938 static const char *const GRPTYPE[] = {
3941 #if ENABLE_HUSH_FUNCTIONS
3950 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3951 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3953 while (prn < pi->num_cmds) {
3954 struct command *command = &pi->cmds[prn];
3955 char **argv = command->argv;
3957 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3959 command->assignment_cnt);
3960 if (command->group) {
3961 fprintf(stderr, " group %s: (argv=%p)\n",
3962 GRPTYPE[command->grp_type],
3964 debug_print_tree(command->group, lvl+1);
3968 if (argv) while (*argv) {
3969 fprintf(stderr, " '%s'", *argv);
3972 fprintf(stderr, "\n");
3981 /* NB: called by pseudo_exec, and therefore must not modify any
3982 * global data until exec/_exit (we can be a child after vfork!) */
3983 static int run_list(struct pipe *pi)
3985 #if ENABLE_HUSH_CASE
3986 char *case_word = NULL;
3988 #if ENABLE_HUSH_LOOPS
3989 struct pipe *loop_top = NULL;
3990 char **for_lcur = NULL;
3991 char **for_list = NULL;
3993 smallint last_followup;
3995 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3996 smalluint cond_code = 0;
3998 enum { cond_code = 0 };
4001 smallint rword; /* enum reserved_style */
4002 smallint last_rword; /* ditto */
4005 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4008 #if ENABLE_HUSH_LOOPS
4009 /* Check syntax for "for" */
4010 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4011 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4013 /* current word is FOR or IN (BOLD in comments below) */
4014 if (cpipe->next == NULL) {
4015 syntax_error("malformed for");
4017 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4020 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4021 if (cpipe->next->res_word == RES_DO)
4023 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4024 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4025 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4027 syntax_error("malformed for");
4029 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4035 /* Past this point, all code paths should jump to ret: label
4036 * in order to return, no direct "return" statements please.
4037 * This helps to ensure that no memory is leaked. */
4045 last_rword = RES_XXXX;
4047 last_followup = PIPE_SEQ;
4048 rcode = G.last_exitcode;
4050 /* Go through list of pipes, (maybe) executing them. */
4051 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4055 IF_HAS_KEYWORDS(rword = pi->res_word;)
4056 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4057 rword, cond_code, last_rword);
4058 #if ENABLE_HUSH_LOOPS
4059 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4060 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4062 /* start of a loop: remember where loop starts */
4067 /* Still in the same "if...", "then..." or "do..." branch? */
4068 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4069 if ((rcode == 0 && last_followup == PIPE_OR)
4070 || (rcode != 0 && last_followup == PIPE_AND)
4072 /* It is "<true> || CMD" or "<false> && CMD"
4073 * and we should not execute CMD */
4074 debug_printf_exec("skipped cmd because of || or &&\n");
4075 last_followup = pi->followup;
4079 last_followup = pi->followup;
4080 IF_HAS_KEYWORDS(last_rword = rword;)
4083 if (rword == RES_THEN) {
4084 /* if false; then ... fi has exitcode 0! */
4085 G.last_exitcode = rcode = EXIT_SUCCESS;
4086 /* "if <false> THEN cmd": skip cmd */
4090 if (rword == RES_ELSE || rword == RES_ELIF) {
4091 /* "if <true> then ... ELSE/ELIF cmd":
4092 * skip cmd and all following ones */
4097 #if ENABLE_HUSH_LOOPS
4098 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4100 /* first loop through for */
4102 static const char encoded_dollar_at[] ALIGN1 = {
4103 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4104 }; /* encoded representation of "$@" */
4105 static const char *const encoded_dollar_at_argv[] = {
4106 encoded_dollar_at, NULL
4107 }; /* argv list with one element: "$@" */
4110 vals = (char**)encoded_dollar_at_argv;
4111 if (pi->next->res_word == RES_IN) {
4112 /* if no variable values after "in" we skip "for" */
4113 if (!pi->next->cmds[0].argv) {
4114 G.last_exitcode = rcode = EXIT_SUCCESS;
4115 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4118 vals = pi->next->cmds[0].argv;
4119 } /* else: "for var; do..." -> assume "$@" list */
4120 /* create list of variable values */
4121 debug_print_strings("for_list made from", vals);
4122 for_list = expand_strvec_to_strvec(vals);
4123 for_lcur = for_list;
4124 debug_print_strings("for_list", for_list);
4127 /* "for" loop is over, clean up */
4133 /* Insert next value from for_lcur */
4134 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4135 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4138 if (rword == RES_IN) {
4139 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4141 if (rword == RES_DONE) {
4142 continue; /* "done" has no cmds too */
4145 #if ENABLE_HUSH_CASE
4146 if (rword == RES_CASE) {
4147 case_word = expand_strvec_to_string(pi->cmds->argv);
4150 if (rword == RES_MATCH) {
4153 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4155 /* all prev words didn't match, does this one match? */
4156 argv = pi->cmds->argv;
4158 char *pattern = expand_string_to_string(*argv);
4159 /* TODO: which FNM_xxx flags to use? */
4160 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4162 if (cond_code == 0) { /* match! we will execute this branch */
4163 free(case_word); /* make future "word)" stop */
4171 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4173 continue; /* not matched yet, skip this pipe */
4176 /* Just pressing <enter> in shell should check for jobs.
4177 * OTOH, in non-interactive shell this is useless
4178 * and only leads to extra job checks */
4179 if (pi->num_cmds == 0) {
4180 if (G_interactive_fd)
4181 goto check_jobs_and_continue;
4185 /* After analyzing all keywords and conditions, we decided
4186 * to execute this pipe. NB: have to do checkjobs(NULL)
4187 * after run_pipe to collect any background children,
4188 * even if list execution is to be stopped. */
4189 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4192 #if ENABLE_HUSH_LOOPS
4193 G.flag_break_continue = 0;
4195 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4197 /* We ran a builtin, function, or group.
4198 * rcode is already known
4199 * and we don't need to wait for anything. */
4200 G.last_exitcode = rcode;
4201 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4202 check_and_run_traps(0);
4203 #if ENABLE_HUSH_LOOPS
4204 /* Was it "break" or "continue"? */
4205 if (G.flag_break_continue) {
4206 smallint fbc = G.flag_break_continue;
4207 /* We might fall into outer *loop*,
4208 * don't want to break it too */
4210 G.depth_break_continue--;
4211 if (G.depth_break_continue == 0)
4212 G.flag_break_continue = 0;
4213 /* else: e.g. "continue 2" should *break* once, *then* continue */
4214 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4215 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4216 goto check_jobs_and_break;
4217 /* "continue": simulate end of loop */
4222 #if ENABLE_HUSH_FUNCTIONS
4223 if (G.flag_return_in_progress == 1) {
4224 /* same as "goto check_jobs_and_break" */
4229 } else if (pi->followup == PIPE_BG) {
4230 /* What does bash do with attempts to background builtins? */
4231 /* even bash 3.2 doesn't do that well with nested bg:
4232 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4233 * I'm NOT treating inner &'s as jobs */
4234 check_and_run_traps(0);
4236 if (G.run_list_level == 1)
4239 G.last_exitcode = rcode = EXIT_SUCCESS;
4240 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4243 if (G.run_list_level == 1 && G_interactive_fd) {
4244 /* Waits for completion, then fg's main shell */
4245 rcode = checkjobs_and_fg_shell(pi);
4246 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4247 check_and_run_traps(0);
4250 { /* This one just waits for completion */
4251 rcode = checkjobs(pi);
4252 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4253 check_and_run_traps(0);
4255 G.last_exitcode = rcode;
4259 /* Analyze how result affects subsequent commands */
4261 if (rword == RES_IF || rword == RES_ELIF)
4264 #if ENABLE_HUSH_LOOPS
4265 /* Beware of "while false; true; do ..."! */
4266 if (pi->next && pi->next->res_word == RES_DO) {
4267 if (rword == RES_WHILE) {
4269 /* "while false; do...done" - exitcode 0 */
4270 G.last_exitcode = rcode = EXIT_SUCCESS;
4271 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4272 goto check_jobs_and_break;
4275 if (rword == RES_UNTIL) {
4277 debug_printf_exec(": until expr is true: breaking\n");
4278 check_jobs_and_break:
4286 check_jobs_and_continue:
4293 #if ENABLE_HUSH_LOOPS
4298 #if ENABLE_HUSH_CASE
4302 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4306 /* Select which version we will use */
4307 static int run_and_free_list(struct pipe *pi)
4310 debug_printf_exec("run_and_free_list entered\n");
4312 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4313 rcode = run_list(pi);
4315 /* free_pipe_list has the side effect of clearing memory.
4316 * In the long run that function can be merged with run_list,
4317 * but doing that now would hobble the debugging effort. */
4319 debug_printf_exec("run_and_free_list return %d\n", rcode);
4324 static struct pipe *new_pipe(void)
4327 pi = xzalloc(sizeof(struct pipe));
4328 /*pi->followup = 0; - deliberately invalid value */
4329 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4333 /* Command (member of a pipe) is complete, or we start a new pipe
4334 * if ctx->command is NULL.
4335 * No errors possible here.
4337 static int done_command(struct parse_context *ctx)
4339 /* The command is really already in the pipe structure, so
4340 * advance the pipe counter and make a new, null command. */
4341 struct pipe *pi = ctx->pipe;
4342 struct command *command = ctx->command;
4345 if (IS_NULL_CMD(command)) {
4346 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4350 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4351 //debug_print_tree(ctx->list_head, 20);
4353 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4356 /* Only real trickiness here is that the uncommitted
4357 * command structure is not counted in pi->num_cmds. */
4358 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4359 ctx->command = command = &pi->cmds[pi->num_cmds];
4361 memset(command, 0, sizeof(*command));
4362 return pi->num_cmds; /* used only for 0/nonzero check */
4365 static void done_pipe(struct parse_context *ctx, pipe_style type)
4369 debug_printf_parse("done_pipe entered, followup %d\n", type);
4370 /* Close previous command */
4371 not_null = done_command(ctx);
4372 ctx->pipe->followup = type;
4374 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4375 ctx->ctx_inverted = 0;
4376 ctx->pipe->res_word = ctx->ctx_res_w;
4379 /* Without this check, even just <enter> on command line generates
4380 * tree of three NOPs (!). Which is harmless but annoying.
4381 * IOW: it is safe to do it unconditionally. */
4384 || ctx->ctx_res_w == RES_FI
4386 #if ENABLE_HUSH_LOOPS
4387 || ctx->ctx_res_w == RES_DONE
4388 || ctx->ctx_res_w == RES_FOR
4389 || ctx->ctx_res_w == RES_IN
4391 #if ENABLE_HUSH_CASE
4392 || ctx->ctx_res_w == RES_ESAC
4396 debug_printf_parse("done_pipe: adding new pipe: "
4397 "not_null:%d ctx->ctx_res_w:%d\n",
4398 not_null, ctx->ctx_res_w);
4400 ctx->pipe->next = new_p;
4402 /* RES_THEN, RES_DO etc are "sticky" -
4403 * they remain set for pipes inside if/while.
4404 * This is used to control execution.
4405 * RES_FOR and RES_IN are NOT sticky (needed to support
4406 * cases where variable or value happens to match a keyword):
4408 #if ENABLE_HUSH_LOOPS
4409 if (ctx->ctx_res_w == RES_FOR
4410 || ctx->ctx_res_w == RES_IN)
4411 ctx->ctx_res_w = RES_NONE;
4413 #if ENABLE_HUSH_CASE
4414 if (ctx->ctx_res_w == RES_MATCH)
4415 ctx->ctx_res_w = RES_CASE_BODY;
4416 if (ctx->ctx_res_w == RES_CASE)
4417 ctx->ctx_res_w = RES_CASE_IN;
4419 ctx->command = NULL; /* trick done_command below */
4420 /* Create the memory for command, roughly:
4421 * ctx->pipe->cmds = new struct command;
4422 * ctx->command = &ctx->pipe->cmds[0];
4425 //debug_print_tree(ctx->list_head, 10);
4427 debug_printf_parse("done_pipe return\n");
4430 static void initialize_context(struct parse_context *ctx)
4432 memset(ctx, 0, sizeof(*ctx));
4433 ctx->pipe = ctx->list_head = new_pipe();
4434 /* Create the memory for command, roughly:
4435 * ctx->pipe->cmds = new struct command;
4436 * ctx->command = &ctx->pipe->cmds[0];
4441 /* If a reserved word is found and processed, parse context is modified
4442 * and 1 is returned.
4445 struct reserved_combo {
4448 unsigned char assignment_flag;
4452 FLAG_END = (1 << RES_NONE ),
4454 FLAG_IF = (1 << RES_IF ),
4455 FLAG_THEN = (1 << RES_THEN ),
4456 FLAG_ELIF = (1 << RES_ELIF ),
4457 FLAG_ELSE = (1 << RES_ELSE ),
4458 FLAG_FI = (1 << RES_FI ),
4460 #if ENABLE_HUSH_LOOPS
4461 FLAG_FOR = (1 << RES_FOR ),
4462 FLAG_WHILE = (1 << RES_WHILE),
4463 FLAG_UNTIL = (1 << RES_UNTIL),
4464 FLAG_DO = (1 << RES_DO ),
4465 FLAG_DONE = (1 << RES_DONE ),
4466 FLAG_IN = (1 << RES_IN ),
4468 #if ENABLE_HUSH_CASE
4469 FLAG_MATCH = (1 << RES_MATCH),
4470 FLAG_ESAC = (1 << RES_ESAC ),
4472 FLAG_START = (1 << RES_XXXX ),
4475 static const struct reserved_combo* match_reserved_word(o_string *word)
4477 /* Mostly a list of accepted follow-up reserved words.
4478 * FLAG_END means we are done with the sequence, and are ready
4479 * to turn the compound list into a command.
4480 * FLAG_START means the word must start a new compound list.
4482 static const struct reserved_combo reserved_list[] = {
4484 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4485 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4486 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4487 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4488 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4489 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4491 #if ENABLE_HUSH_LOOPS
4492 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4493 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4494 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4495 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4496 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4497 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4499 #if ENABLE_HUSH_CASE
4500 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4501 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4504 const struct reserved_combo *r;
4506 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4507 if (strcmp(word->data, r->literal) == 0)
4512 /* Return 0: not a keyword, 1: keyword
4514 static int reserved_word(o_string *word, struct parse_context *ctx)
4516 #if ENABLE_HUSH_CASE
4517 static const struct reserved_combo reserved_match = {
4518 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4521 const struct reserved_combo *r;
4525 r = match_reserved_word(word);
4529 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4530 #if ENABLE_HUSH_CASE
4531 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4532 /* "case word IN ..." - IN part starts first MATCH part */
4533 r = &reserved_match;
4536 if (r->flag == 0) { /* '!' */
4537 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4538 syntax_error("! ! command");
4539 ctx->ctx_res_w = RES_SNTX;
4541 ctx->ctx_inverted = 1;
4544 if (r->flag & FLAG_START) {
4545 struct parse_context *old;
4547 old = xmalloc(sizeof(*old));
4548 debug_printf_parse("push stack %p\n", old);
4549 *old = *ctx; /* physical copy */
4550 initialize_context(ctx);
4552 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4553 syntax_error_at(word->data);
4554 ctx->ctx_res_w = RES_SNTX;
4557 /* "{...} fi" is ok. "{...} if" is not
4559 * if { echo foo; } then { echo bar; } fi */
4560 if (ctx->command->group)
4561 done_pipe(ctx, PIPE_SEQ);
4564 ctx->ctx_res_w = r->res;
4565 ctx->old_flag = r->flag;
4566 word->o_assignment = r->assignment_flag;
4568 if (ctx->old_flag & FLAG_END) {
4569 struct parse_context *old;
4571 done_pipe(ctx, PIPE_SEQ);
4572 debug_printf_parse("pop stack %p\n", ctx->stack);
4574 old->command->group = ctx->list_head;
4575 old->command->grp_type = GRP_NORMAL;
4577 o_addstr(&old->as_string, ctx->as_string.data);
4578 o_free_unsafe(&ctx->as_string);
4579 old->command->group_as_string = xstrdup(old->as_string.data);
4580 debug_printf_parse("pop, remembering as:'%s'\n",
4581 old->command->group_as_string);
4583 *ctx = *old; /* physical copy */
4590 /* Word is complete, look at it and update parsing context.
4591 * Normal return is 0. Syntax errors return 1.
4592 * Note: on return, word is reset, but not o_free'd!
4594 static int done_word(o_string *word, struct parse_context *ctx)
4596 struct command *command = ctx->command;
4598 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4599 if (word->length == 0 && word->o_quoted == 0) {
4600 debug_printf_parse("done_word return 0: true null, ignored\n");
4604 if (ctx->pending_redirect) {
4605 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4606 * only if run as "bash", not "sh" */
4607 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4609 * ...the word that follows the redirection operator
4610 * shall be subjected to tilde expansion, parameter expansion,
4611 * command substitution, arithmetic expansion, and quote
4612 * removal. Pathname expansion shall not be performed
4613 * on the word by a non-interactive shell; an interactive
4614 * shell may perform it, but shall do so only when
4615 * the expansion would result in one word."
4617 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4618 /* Cater for >\file case:
4619 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4620 * Same with heredocs:
4621 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4623 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4624 unbackslash(ctx->pending_redirect->rd_filename);
4625 /* Is it <<"HEREDOC"? */
4626 if (word->o_quoted) {
4627 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4630 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4631 ctx->pending_redirect = NULL;
4633 /* If this word wasn't an assignment, next ones definitely
4634 * can't be assignments. Even if they look like ones. */
4635 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4636 && word->o_assignment != WORD_IS_KEYWORD
4638 word->o_assignment = NOT_ASSIGNMENT;
4640 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4641 command->assignment_cnt++;
4642 word->o_assignment = MAYBE_ASSIGNMENT;
4646 # if ENABLE_HUSH_CASE
4647 if (ctx->ctx_dsemicolon
4648 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4650 /* already done when ctx_dsemicolon was set to 1: */
4651 /* ctx->ctx_res_w = RES_MATCH; */
4652 ctx->ctx_dsemicolon = 0;
4655 if (!command->argv /* if it's the first word... */
4656 # if ENABLE_HUSH_LOOPS
4657 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4658 && ctx->ctx_res_w != RES_IN
4660 # if ENABLE_HUSH_CASE
4661 && ctx->ctx_res_w != RES_CASE
4664 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4665 if (reserved_word(word, ctx)) {
4666 o_reset_to_empty_unquoted(word);
4667 debug_printf_parse("done_word return %d\n",
4668 (ctx->ctx_res_w == RES_SNTX));
4669 return (ctx->ctx_res_w == RES_SNTX);
4673 if (command->group) {
4674 /* "{ echo foo; } echo bar" - bad */
4675 syntax_error_at(word->data);
4676 debug_printf_parse("done_word return 1: syntax error, "
4677 "groups and arglists don't mix\n");
4680 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4681 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4682 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4683 /* (otherwise it's known to be not empty and is already safe) */
4685 /* exclude "$@" - it can expand to no word despite "" */
4686 char *p = word->data;
4687 while (p[0] == SPECIAL_VAR_SYMBOL
4688 && (p[1] & 0x7f) == '@'
4689 && p[2] == SPECIAL_VAR_SYMBOL
4693 if (p == word->data || p[0] != '\0') {
4694 /* saw no "$@", or not only "$@" but some
4695 * real text is there too */
4696 /* insert "empty variable" reference, this makes
4697 * e.g. "", $empty"" etc to not disappear */
4698 o_addchr(word, SPECIAL_VAR_SYMBOL);
4699 o_addchr(word, SPECIAL_VAR_SYMBOL);
4702 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4703 debug_print_strings("word appended to argv", command->argv);
4706 #if ENABLE_HUSH_LOOPS
4707 if (ctx->ctx_res_w == RES_FOR) {
4709 || !is_well_formed_var_name(command->argv[0], '\0')
4711 /* bash says just "not a valid identifier" */
4712 syntax_error("not a valid identifier in for");
4715 /* Force FOR to have just one word (variable name) */
4716 /* NB: basically, this makes hush see "for v in ..."
4717 * syntax as if it is "for v; in ...". FOR and IN become
4718 * two pipe structs in parse tree. */
4719 done_pipe(ctx, PIPE_SEQ);
4722 #if ENABLE_HUSH_CASE
4723 /* Force CASE to have just one word */
4724 if (ctx->ctx_res_w == RES_CASE) {
4725 done_pipe(ctx, PIPE_SEQ);
4729 o_reset_to_empty_unquoted(word);
4731 debug_printf_parse("done_word return 0\n");
4736 /* Peek ahead in the input to find out if we have a "&n" construct,
4737 * as in "2>&1", that represents duplicating a file descriptor.
4739 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4740 * REDIRFD_SYNTAX_ERR if syntax error,
4741 * REDIRFD_TO_FILE if no & was seen,
4742 * or the number found.
4745 #define parse_redir_right_fd(as_string, input) \
4746 parse_redir_right_fd(input)
4748 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4754 return REDIRFD_TO_FILE;
4756 ch = i_getch(input); /* get the & */
4757 nommu_addchr(as_string, ch);
4760 ch = i_getch(input);
4761 nommu_addchr(as_string, ch);
4762 return REDIRFD_CLOSE;
4766 while (ch != EOF && isdigit(ch)) {
4767 d = d*10 + (ch-'0');
4769 ch = i_getch(input);
4770 nommu_addchr(as_string, ch);
4775 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4777 bb_error_msg("ambiguous redirect");
4778 return REDIRFD_SYNTAX_ERR;
4781 /* Return code is 0 normal, 1 if a syntax error is detected
4783 static int parse_redirect(struct parse_context *ctx,
4786 struct in_str *input)
4788 struct command *command = ctx->command;
4789 struct redir_struct *redir;
4790 struct redir_struct **redirp;
4793 dup_num = REDIRFD_TO_FILE;
4794 if (style != REDIRECT_HEREDOC) {
4795 /* Check for a '>&1' type redirect */
4796 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4797 if (dup_num == REDIRFD_SYNTAX_ERR)
4800 int ch = i_peek(input);
4801 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4802 if (dup_num) { /* <<-... */
4803 ch = i_getch(input);
4804 nommu_addchr(&ctx->as_string, ch);
4809 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4810 int ch = i_peek(input);
4812 /* >|FILE redirect ("clobbering" >).
4813 * Since we do not support "set -o noclobber" yet,
4814 * >| and > are the same for now. Just eat |.
4816 ch = i_getch(input);
4817 nommu_addchr(&ctx->as_string, ch);
4821 /* Create a new redir_struct and append it to the linked list */
4822 redirp = &command->redirects;
4823 while ((redir = *redirp) != NULL) {
4824 redirp = &(redir->next);
4826 *redirp = redir = xzalloc(sizeof(*redir));
4827 /* redir->next = NULL; */
4828 /* redir->rd_filename = NULL; */
4829 redir->rd_type = style;
4830 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4832 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4833 redir_table[style].descrip);
4835 redir->rd_dup = dup_num;
4836 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4837 /* Erik had a check here that the file descriptor in question
4838 * is legit; I postpone that to "run time"
4839 * A "-" representation of "close me" shows up as a -3 here */
4840 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4841 redir->rd_fd, redir->rd_dup);
4843 /* Set ctx->pending_redirect, so we know what to do at the
4844 * end of the next parsed word. */
4845 ctx->pending_redirect = redir;
4850 /* If a redirect is immediately preceded by a number, that number is
4851 * supposed to tell which file descriptor to redirect. This routine
4852 * looks for such preceding numbers. In an ideal world this routine
4853 * needs to handle all the following classes of redirects...
4854 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4855 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4856 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4857 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4859 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4861 * ... If n is quoted, the number shall not be recognized as part of
4862 * the redirection expression. For example:
4864 * writes the character 2 into file a"
4865 * We are getting it right by setting ->o_quoted on any \<char>
4867 * A -1 return means no valid number was found,
4868 * the caller should use the appropriate default for this redirection.
4870 static int redirect_opt_num(o_string *o)
4874 if (o->data == NULL)
4876 num = bb_strtou(o->data, NULL, 10);
4877 if (errno || num < 0)
4879 o_reset_to_empty_unquoted(o);
4884 #define fetch_till_str(as_string, input, word, skip_tabs) \
4885 fetch_till_str(input, word, skip_tabs)
4887 static char *fetch_till_str(o_string *as_string,
4888 struct in_str *input,
4892 o_string heredoc = NULL_O_STRING;
4898 ch = i_getch(input);
4899 nommu_addchr(as_string, ch);
4901 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4902 heredoc.data[past_EOL] = '\0';
4903 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4904 return heredoc.data;
4907 o_addchr(&heredoc, ch);
4908 past_EOL = heredoc.length;
4911 ch = i_getch(input);
4912 nommu_addchr(as_string, ch);
4913 } while (skip_tabs && ch == '\t');
4914 } while (ch == '\n');
4917 o_free_unsafe(&heredoc);
4920 o_addchr(&heredoc, ch);
4921 nommu_addchr(as_string, ch);
4925 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4926 * and load them all. There should be exactly heredoc_cnt of them.
4928 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4930 struct pipe *pi = ctx->list_head;
4932 while (pi && heredoc_cnt) {
4934 struct command *cmd = pi->cmds;
4936 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4938 cmd->argv ? cmd->argv[0] : "NONE");
4939 for (i = 0; i < pi->num_cmds; i++) {
4940 struct redir_struct *redir = cmd->redirects;
4942 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4943 i, cmd->argv ? cmd->argv[0] : "NONE");
4945 if (redir->rd_type == REDIRECT_HEREDOC) {
4948 redir->rd_type = REDIRECT_HEREDOC2;
4949 /* redir->dup is (ab)used to indicate <<- */
4950 p = fetch_till_str(&ctx->as_string, input,
4951 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4953 syntax_error("unexpected EOF in here document");
4956 free(redir->rd_filename);
4957 redir->rd_filename = p;
4960 redir = redir->next;
4967 /* Should be 0. If it isn't, it's a parse error */
4969 bb_error_msg_and_die("heredoc BUG 2");
4975 #if ENABLE_HUSH_TICK
4976 static FILE *generate_stream_from_string(const char *s)
4979 int pid, channel[2];
4985 pid = BB_MMU ? fork() : vfork();
4987 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4989 if (pid == 0) { /* child */
4990 disable_restore_tty_pgrp_on_exit();
4991 /* Process substitution is not considered to be usual
4992 * 'command execution'.
4993 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5000 close(channel[0]); /* NB: close _first_, then move fd! */
5001 xmove_fd(channel[1], 1);
5002 /* Prevent it from trying to handle ctrl-z etc */
5003 IF_HUSH_JOB(G.run_list_level = 1;)
5005 reset_traps_to_defaults();
5006 parse_and_run_string(s);
5007 _exit(G.last_exitcode);
5009 /* We re-execute after vfork on NOMMU. This makes this script safe:
5010 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5011 * huge=`cat BIG` # was blocking here forever
5014 re_execute_shell(&to_free,
5022 #if ENABLE_HUSH_FAST
5024 //bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5026 enable_restore_tty_pgrp_on_exit();
5031 pf = fdopen(channel[0], "r");
5035 /* Return code is exit status of the process that is run. */
5036 static int process_command_subs(o_string *dest, const char *s)
5039 struct in_str pipe_str;
5042 pf = generate_stream_from_string(s);
5045 close_on_exec_on(fileno(pf));
5047 /* Now send results of command back into original context */
5048 setup_file_in_str(&pipe_str, pf);
5050 while ((ch = i_getch(&pipe_str)) != EOF) {
5056 o_addchr(dest, '\n');
5059 o_addQchr(dest, ch);
5062 debug_printf("done reading from pipe, pclose()ing\n");
5063 /* Note: we got EOF, and we just close the read end of the pipe.
5064 * We do not wait for the `cmd` child to terminate. bash and ash do.
5066 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5067 * `false`; echo $? - bash outputs "1"
5070 debug_printf("closed FILE from child. return 0\n");
5075 static int parse_group(o_string *dest, struct parse_context *ctx,
5076 struct in_str *input, int ch)
5078 /* dest contains characters seen prior to ( or {.
5079 * Typically it's empty, but for function defs,
5080 * it contains function name (without '()'). */
5081 struct pipe *pipe_list;
5083 struct command *command = ctx->command;
5085 debug_printf_parse("parse_group entered\n");
5086 #if ENABLE_HUSH_FUNCTIONS
5087 if (ch == '(' && !dest->o_quoted) {
5089 if (done_word(dest, ctx))
5092 goto skip; /* (... */
5093 if (command->argv[1]) { /* word word ... (... */
5094 syntax_error_unexpected_ch('(');
5097 /* it is "word(..." or "word (..." */
5099 ch = i_getch(input);
5100 while (ch == ' ' || ch == '\t');
5102 syntax_error_unexpected_ch(ch);
5105 nommu_addchr(&ctx->as_string, ch);
5107 ch = i_getch(input);
5108 while (ch == ' ' || ch == '\t' || ch == '\n');
5110 syntax_error_unexpected_ch(ch);
5113 nommu_addchr(&ctx->as_string, ch);
5114 command->grp_type = GRP_FUNCTION;
5118 if (command->argv /* word [word]{... */
5119 || dest->length /* word{... */
5120 || dest->o_quoted /* ""{... */
5123 debug_printf_parse("parse_group return 1: "
5124 "syntax error, groups and arglists don't mix\n");
5128 #if ENABLE_HUSH_FUNCTIONS
5134 command->grp_type = GRP_SUBSHELL;
5136 /* bash does not allow "{echo...", requires whitespace */
5137 ch = i_getch(input);
5138 if (ch != ' ' && ch != '\t' && ch != '\n') {
5139 syntax_error_unexpected_ch(ch);
5142 nommu_addchr(&ctx->as_string, ch);
5147 char *as_string = NULL;
5149 pipe_list = parse_stream(&as_string, input, endch);
5152 o_addstr(&ctx->as_string, as_string);
5154 /* empty ()/{} or parse error? */
5155 if (!pipe_list || pipe_list == ERR_PTR) {
5156 /* parse_stream already emitted error msg */
5160 debug_printf_parse("parse_group return 1: "
5161 "parse_stream returned %p\n", pipe_list);
5164 command->group = pipe_list;
5166 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5167 command->group_as_string = as_string;
5168 debug_printf_parse("end of group, remembering as:'%s'\n",
5169 command->group_as_string);
5172 debug_printf_parse("parse_group return 0\n");
5174 /* command remains "open", available for possible redirects */
5177 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5178 /* Subroutines for copying $(...) and `...` things */
5179 static void add_till_backquote(o_string *dest, struct in_str *input);
5181 static void add_till_single_quote(o_string *dest, struct in_str *input)
5184 int ch = i_getch(input);
5186 syntax_error_unterm_ch('\'');
5187 /*xfunc_die(); - redundant */
5194 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5195 static void add_till_double_quote(o_string *dest, struct in_str *input)
5198 int ch = i_getch(input);
5200 syntax_error_unterm_ch('"');
5201 /*xfunc_die(); - redundant */
5205 if (ch == '\\') { /* \x. Copy both chars. */
5207 ch = i_getch(input);
5211 add_till_backquote(dest, input);
5215 //if (ch == '$') ...
5218 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5220 * "Within the backquoted style of command substitution, backslash
5221 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5222 * The search for the matching backquote shall be satisfied by the first
5223 * backquote found without a preceding backslash; during this search,
5224 * if a non-escaped backquote is encountered within a shell comment,
5225 * a here-document, an embedded command substitution of the $(command)
5226 * form, or a quoted string, undefined results occur. A single-quoted
5227 * or double-quoted string that begins, but does not end, within the
5228 * "`...`" sequence produces undefined results."
5230 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5232 static void add_till_backquote(o_string *dest, struct in_str *input)
5235 int ch = i_getch(input);
5237 syntax_error_unterm_ch('`');
5238 /*xfunc_die(); - redundant */
5243 /* \x. Copy both chars unless it is \` */
5244 int ch2 = i_getch(input);
5246 syntax_error_unterm_ch('`');
5247 /*xfunc_die(); - redundant */
5249 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5256 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5257 * quoting and nested ()s.
5258 * "With the $(command) style of command substitution, all characters
5259 * following the open parenthesis to the matching closing parenthesis
5260 * constitute the command. Any valid shell script can be used for command,
5261 * except a script consisting solely of redirections which produces
5262 * unspecified results."
5264 * echo $(echo '(TEST)' BEST) (TEST) BEST
5265 * echo $(echo 'TEST)' BEST) TEST) BEST
5266 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5268 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5272 int ch = i_getch(input);
5274 syntax_error_unterm_ch(')');
5275 /*xfunc_die(); - redundant */
5283 if (i_peek(input) == ')') {
5291 add_till_single_quote(dest, input);
5296 add_till_double_quote(dest, input);
5301 /* \x. Copy verbatim. Important for \(, \) */
5302 ch = i_getch(input);
5304 syntax_error_unterm_ch(')');
5305 /*xfunc_die(); - redundant */
5312 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5314 /* Return code: 0 for OK, 1 for syntax error */
5316 #define handle_dollar(as_string, dest, input) \
5317 handle_dollar(dest, input)
5319 static int handle_dollar(o_string *as_string,
5321 struct in_str *input)
5323 int ch = i_peek(input); /* first character after the $ */
5324 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5326 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5328 ch = i_getch(input);
5329 nommu_addchr(as_string, ch);
5331 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5333 debug_printf_parse(": '%c'\n", ch);
5334 o_addchr(dest, ch | quote_mask);
5337 if (!isalnum(ch) && ch != '_')
5339 ch = i_getch(input);
5340 nommu_addchr(as_string, ch);
5342 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5343 } else if (isdigit(ch)) {
5345 ch = i_getch(input);
5346 nommu_addchr(as_string, ch);
5347 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5348 debug_printf_parse(": '%c'\n", ch);
5349 o_addchr(dest, ch | quote_mask);
5350 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5351 } else switch (ch) {
5353 case '!': /* last bg pid */
5354 case '?': /* last exit code */
5355 case '#': /* number of args */
5356 case '*': /* args */
5357 case '@': /* args */
5358 goto make_one_char_var;
5360 bool first_char, all_digits;
5363 ch = i_getch(input);
5364 nommu_addchr(as_string, ch);
5365 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5367 /* TODO: maybe someone will try to escape the '}' */
5372 ch = i_getch(input);
5373 nommu_addchr(as_string, ch);
5380 /* ${#var}: length of var contents */
5387 /* They're being verbose and doing ${?} */
5388 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5393 && ( (all_digits && !isdigit(ch))
5394 || (!all_digits && !isalnum(ch) && ch != '_')
5397 /* handle parameter expansions
5398 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5403 case ':': /* null modifier */
5404 if (expansion == 0) {
5405 debug_printf_parse(": null modifier\n");
5410 case '#': /* remove prefix */
5411 case '%': /* remove suffix */
5412 if (expansion == 0) {
5413 debug_printf_parse(": remove suffix/prefix\n");
5418 case '-': /* default value */
5419 case '=': /* assign default */
5420 case '+': /* alternative */
5421 case '?': /* error indicate */
5422 debug_printf_parse(": parameter expansion\n");
5427 syntax_error_unterm_str("${name}");
5428 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5433 debug_printf_parse(": '%c'\n", ch);
5434 o_addchr(dest, ch | quote_mask);
5438 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5441 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5446 ch = i_getch(input);
5447 nommu_addchr(as_string, ch);
5448 # if ENABLE_SH_MATH_SUPPORT
5449 if (i_peek(input) == '(') {
5450 ch = i_getch(input);
5451 nommu_addchr(as_string, ch);
5452 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5453 o_addchr(dest, /*quote_mask |*/ '+');
5457 add_till_closing_paren(dest, input, true);
5460 o_addstr(as_string, dest->data + pos);
5461 o_addchr(as_string, ')');
5462 o_addchr(as_string, ')');
5465 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5469 # if ENABLE_HUSH_TICK
5470 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5471 o_addchr(dest, quote_mask | '`');
5475 add_till_closing_paren(dest, input, false);
5478 o_addstr(as_string, dest->data + pos);
5479 o_addchr(as_string, '`');
5482 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5488 ch = i_getch(input);
5489 nommu_addchr(as_string, ch);
5491 if (isalnum(ch)) { /* it's $_name or $_123 */
5497 /* $_ Shell or shell script name; or last cmd name */
5498 /* $- Option flags set by set builtin or shell options (-i etc) */
5500 o_addQchr(dest, '$');
5502 debug_printf_parse("handle_dollar return 0\n");
5507 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5508 parse_stream_dquoted(dest, input, dquote_end)
5510 static int parse_stream_dquoted(o_string *as_string,
5512 struct in_str *input,
5519 ch = i_getch(input);
5521 nommu_addchr(as_string, ch);
5522 if (ch == dquote_end) { /* may be only '"' or EOF */
5523 if (dest->o_assignment == NOT_ASSIGNMENT)
5524 dest->o_escape ^= 1;
5525 debug_printf_parse("parse_stream_dquoted return 0\n");
5528 /* note: can't move it above ch == dquote_end check! */
5530 syntax_error_unterm_ch('"');
5531 /*xfunc_die(); - redundant */
5535 next = i_peek(input);
5537 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5538 ch, ch, dest->o_escape);
5541 syntax_error("\\<eof>");
5545 * "The backslash retains its special meaning [in "..."]
5546 * only when followed by one of the following characters:
5547 * $, `, ", \, or <newline>. A double quote may be quoted
5548 * within double quotes by preceding it with a backslash."
5550 if (strchr("$`\"\\\n", next) != NULL) {
5551 ch = i_getch(input);
5553 o_addqchr(dest, ch);
5554 nommu_addchr(as_string, ch);
5557 o_addqchr(dest, '\\');
5558 nommu_addchr(as_string, '\\');
5563 if (handle_dollar(as_string, dest, input) != 0) {
5564 debug_printf_parse("parse_stream_dquoted return 1: "
5565 "handle_dollar returned non-0\n");
5570 #if ENABLE_HUSH_TICK
5572 //int pos = dest->length;
5573 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5574 o_addchr(dest, 0x80 | '`');
5575 add_till_backquote(dest, input);
5576 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5577 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5581 o_addQchr(dest, ch);
5583 && (dest->o_assignment == MAYBE_ASSIGNMENT
5584 || dest->o_assignment == WORD_IS_KEYWORD)
5585 && is_well_formed_var_name(dest->data, '=')
5587 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5593 * Scan input until EOF or end_trigger char.
5594 * Return a list of pipes to execute, or NULL on EOF
5595 * or if end_trigger character is met.
5596 * On syntax error, exit is shell is not interactive,
5597 * reset parsing machinery and start parsing anew,
5598 * or return ERR_PTR.
5600 static struct pipe *parse_stream(char **pstring,
5601 struct in_str *input,
5604 struct parse_context ctx;
5605 o_string dest = NULL_O_STRING;
5609 /* Double-quote state is handled in the state variable is_in_dquote.
5610 * A single-quote triggers a bypass of the main loop until its mate is
5611 * found. When recursing, quote state is passed in via dest->o_escape.
5613 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5614 end_trigger ? : 'X');
5617 G.ifs = get_local_var_value("IFS");
5622 #if ENABLE_HUSH_INTERACTIVE
5623 input->promptmode = 0; /* PS1 */
5625 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5626 initialize_context(&ctx);
5631 const char *is_special;
5635 redir_type redir_style;
5638 /* dest.o_quoted = 1; - already is (see below) */
5639 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5642 /* We reached closing '"' */
5645 ch = i_getch(input);
5646 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5647 ch, ch, dest.o_escape);
5652 syntax_error_unterm_str("here document");
5655 /* end_trigger == '}' case errors out earlier,
5656 * checking only ')' */
5657 if (end_trigger == ')') {
5658 syntax_error_unterm_ch('('); /* exits */
5659 /* goto parse_error; */
5662 if (done_word(&dest, &ctx)) {
5666 done_pipe(&ctx, PIPE_SEQ);
5668 /* If we got nothing... */
5669 /* (this makes bare "&" cmd a no-op.
5670 * bash says: "syntax error near unexpected token '&'") */
5671 if (pi->num_cmds == 0
5672 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5678 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5680 *pstring = ctx.as_string.data;
5682 o_free_unsafe(&ctx.as_string);
5685 debug_printf_parse("parse_stream return %p\n", pi);
5688 nommu_addchr(&ctx.as_string, ch);
5689 is_ifs = strchr(G.ifs, ch);
5690 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5691 "\\$\"" IF_HUSH_TICK("`") /* always special */
5694 if (!is_special && !is_ifs) { /* ordinary char */
5696 o_addQchr(&dest, ch);
5697 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5698 || dest.o_assignment == WORD_IS_KEYWORD)
5700 && is_well_formed_var_name(dest.data, '=')
5702 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5708 if (done_word(&dest, &ctx)) {
5712 #if ENABLE_HUSH_CASE
5713 /* "case ... in <newline> word) ..." -
5714 * newlines are ignored (but ';' wouldn't be) */
5715 if (ctx.command->argv == NULL
5716 && ctx.ctx_res_w == RES_MATCH
5721 /* Treat newline as a command separator. */
5722 done_pipe(&ctx, PIPE_SEQ);
5723 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5725 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5730 dest.o_assignment = MAYBE_ASSIGNMENT;
5732 /* note: if (is_ifs) continue;
5733 * will still trigger for us */
5737 /* "cmd}" or "cmd }..." without semicolon or &:
5738 * } is an ordinary char in this case, even inside { cmd; }
5739 * Pathological example: { ""}; } should exec "}" cmd
5742 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5743 || dest.length != 0 /* word} */
5744 || dest.o_quoted /* ""} */
5748 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5749 goto skip_end_trigger;
5750 /* else: } does terminate a group */
5753 if (end_trigger && end_trigger == ch
5754 && (ch != ';' || heredoc_cnt == 0)
5755 #if ENABLE_HUSH_CASE
5757 || ctx.ctx_res_w != RES_MATCH
5758 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5763 /* This is technically valid:
5764 * { cat <<HERE; }; echo Ok
5768 * but we don't support this.
5769 * We require heredoc to be in enclosing {}/(),
5772 syntax_error_unterm_str("here document");
5775 if (done_word(&dest, &ctx)) {
5778 done_pipe(&ctx, PIPE_SEQ);
5779 dest.o_assignment = MAYBE_ASSIGNMENT;
5780 /* Do we sit outside of any if's, loops or case's? */
5782 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5786 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5788 *pstring = ctx.as_string.data;
5790 o_free_unsafe(&ctx.as_string);
5793 debug_printf_parse("parse_stream return %p: "
5794 "end_trigger char found\n",
5796 return ctx.list_head;
5805 next = i_peek(input);
5808 /* Catch <, > before deciding whether this word is
5809 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5812 redir_fd = redirect_opt_num(&dest);
5813 if (done_word(&dest, &ctx)) {
5816 redir_style = REDIRECT_OVERWRITE;
5818 redir_style = REDIRECT_APPEND;
5819 ch = i_getch(input);
5820 nommu_addchr(&ctx.as_string, ch);
5823 else if (next == '(') {
5824 syntax_error(">(process) not supported");
5828 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5830 continue; /* back to top of while (1) */
5832 redir_fd = redirect_opt_num(&dest);
5833 if (done_word(&dest, &ctx)) {
5836 redir_style = REDIRECT_INPUT;
5838 redir_style = REDIRECT_HEREDOC;
5840 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5841 ch = i_getch(input);
5842 nommu_addchr(&ctx.as_string, ch);
5843 } else if (next == '>') {
5844 redir_style = REDIRECT_IO;
5845 ch = i_getch(input);
5846 nommu_addchr(&ctx.as_string, ch);
5849 else if (next == '(') {
5850 syntax_error("<(process) not supported");
5854 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5856 continue; /* back to top of while (1) */
5859 if (dest.o_assignment == MAYBE_ASSIGNMENT
5860 /* check that we are not in word in "a=1 2>word b=1": */
5861 && !ctx.pending_redirect
5863 /* ch is a special char and thus this word
5864 * cannot be an assignment */
5865 dest.o_assignment = NOT_ASSIGNMENT;
5870 if (dest.length == 0) {
5873 if (ch == EOF || ch == '\n')
5876 /* note: we do not add it to &ctx.as_string */
5878 nommu_addchr(&ctx.as_string, '\n');
5880 o_addQchr(&dest, ch);
5885 syntax_error("\\<eof>");
5888 ch = i_getch(input);
5890 o_addchr(&dest, '\\');
5891 nommu_addchr(&ctx.as_string, '\\');
5892 o_addchr(&dest, ch);
5893 nommu_addchr(&ctx.as_string, ch);
5894 /* Example: echo Hello \2>file
5895 * we need to know that word 2 is quoted */
5900 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5901 debug_printf_parse("parse_stream parse error: "
5902 "handle_dollar returned non-0\n");
5909 ch = i_getch(input);
5911 syntax_error_unterm_ch('\'');
5912 /*xfunc_die(); - redundant */
5914 nommu_addchr(&ctx.as_string, ch);
5917 o_addqchr(&dest, ch);
5922 is_in_dquote ^= 1; /* invert */
5923 if (dest.o_assignment == NOT_ASSIGNMENT)
5926 #if ENABLE_HUSH_TICK
5931 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5932 o_addchr(&dest, '`');
5936 add_till_backquote(&dest, input);
5938 o_addstr(&ctx.as_string, dest.data + pos);
5939 o_addchr(&ctx.as_string, '`');
5941 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5942 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5947 #if ENABLE_HUSH_CASE
5950 if (done_word(&dest, &ctx)) {
5953 done_pipe(&ctx, PIPE_SEQ);
5954 #if ENABLE_HUSH_CASE
5955 /* Eat multiple semicolons, detect
5956 * whether it means something special */
5961 ch = i_getch(input);
5962 nommu_addchr(&ctx.as_string, ch);
5963 if (ctx.ctx_res_w == RES_CASE_BODY) {
5964 ctx.ctx_dsemicolon = 1;
5965 ctx.ctx_res_w = RES_MATCH;
5971 /* We just finished a cmd. New one may start
5972 * with an assignment */
5973 dest.o_assignment = MAYBE_ASSIGNMENT;
5976 if (done_word(&dest, &ctx)) {
5980 ch = i_getch(input);
5981 nommu_addchr(&ctx.as_string, ch);
5982 done_pipe(&ctx, PIPE_AND);
5984 done_pipe(&ctx, PIPE_BG);
5988 if (done_word(&dest, &ctx)) {
5991 #if ENABLE_HUSH_CASE
5992 if (ctx.ctx_res_w == RES_MATCH)
5993 break; /* we are in case's "word | word)" */
5995 if (next == '|') { /* || */
5996 ch = i_getch(input);
5997 nommu_addchr(&ctx.as_string, ch);
5998 done_pipe(&ctx, PIPE_OR);
6000 /* we could pick up a file descriptor choice here
6001 * with redirect_opt_num(), but bash doesn't do it.
6002 * "echo foo 2| cat" yields "foo 2". */
6007 #if ENABLE_HUSH_CASE
6008 /* "case... in [(]word)..." - skip '(' */
6009 if (ctx.ctx_res_w == RES_MATCH
6010 && ctx.command->argv == NULL /* not (word|(... */
6011 && dest.length == 0 /* not word(... */
6012 && dest.o_quoted == 0 /* not ""(... */
6018 if (parse_group(&dest, &ctx, input, ch) != 0) {
6023 #if ENABLE_HUSH_CASE
6024 if (ctx.ctx_res_w == RES_MATCH)
6028 /* proper use of this character is caught by end_trigger:
6029 * if we see {, we call parse_group(..., end_trigger='}')
6030 * and it will match } earlier (not here). */
6031 syntax_error_unexpected_ch(ch);
6035 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6041 struct parse_context *pctx;
6042 IF_HAS_KEYWORDS(struct parse_context *p2;)
6044 /* Clean up allocated tree.
6045 * Samples for finding leaks on syntax error recovery path.
6046 * Run them from interactive shell, watch pmap `pidof hush`.
6047 * while if false; then false; fi do break; done
6049 * while if false; then false; fi; do break; fi
6050 * Samples to catch leaks at execution:
6051 * while if (true | {true;}); then echo ok; fi; do break; done
6052 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6056 /* Update pipe/command counts,
6057 * otherwise freeing may miss some */
6058 done_pipe(pctx, PIPE_SEQ);
6059 debug_printf_clean("freeing list %p from ctx %p\n",
6060 pctx->list_head, pctx);
6061 debug_print_tree(pctx->list_head, 0);
6062 free_pipe_list(pctx->list_head);
6063 debug_printf_clean("freed list %p\n", pctx->list_head);
6065 o_free_unsafe(&pctx->as_string);
6067 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6071 IF_HAS_KEYWORDS(pctx = p2;)
6072 } while (HAS_KEYWORDS && pctx);
6073 /* Free text, clear all dest fields */
6075 /* If we are not in top-level parse, we return,
6076 * our caller will propagate error.
6078 if (end_trigger != ';') {
6086 /* Discard cached input, force prompt */
6088 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6093 /* Executing from string: eval, sh -c '...'
6094 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6095 * end_trigger controls how often we stop parsing
6096 * NUL: parse all, execute, return
6097 * ';': parse till ';' or newline, execute, repeat till EOF
6099 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6102 struct pipe *pipe_list;
6104 pipe_list = parse_stream(NULL, inp, end_trigger);
6105 if (!pipe_list) /* EOF */
6107 debug_print_tree(pipe_list, 0);
6108 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6109 run_and_free_list(pipe_list);
6113 static void parse_and_run_string(const char *s)
6115 struct in_str input;
6116 setup_string_in_str(&input, s);
6117 parse_and_run_stream(&input, '\0');
6120 static void parse_and_run_file(FILE *f)
6122 struct in_str input;
6123 setup_file_in_str(&input, f);
6124 parse_and_run_stream(&input, ';');
6127 /* Called a few times only (or even once if "sh -c") */
6128 static void block_signals(int second_time)
6133 mask = (1 << SIGQUIT);
6134 if (G_interactive_fd) {
6135 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6136 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6137 mask |= SPECIAL_JOB_SIGS;
6139 G.non_DFL_mask = mask;
6142 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6146 sigaddset(&G.blocked_set, sig);
6150 sigdelset(&G.blocked_set, SIGCHLD);
6152 sigprocmask(SIG_SETMASK, &G.blocked_set,
6153 second_time ? NULL : &G.inherited_set);
6154 /* POSIX allows shell to re-enable SIGCHLD
6155 * even if it was SIG_IGN on entry */
6156 #if ENABLE_HUSH_FAST
6157 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6159 signal(SIGCHLD, SIGCHLD_handler);
6162 signal(SIGCHLD, SIG_DFL);
6168 static void maybe_set_to_sigexit(int sig)
6170 void (*handler)(int);
6171 /* non_DFL_mask'ed signals are, well, masked,
6172 * no need to set handler for them.
6174 if (!((G.non_DFL_mask >> sig) & 1)) {
6175 handler = signal(sig, sigexit);
6176 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6177 signal(sig, handler);
6180 /* Set handlers to restore tty pgrp and exit */
6181 static void set_fatal_handlers(void)
6183 /* We _must_ restore tty pgrp on fatal signals */
6185 maybe_set_to_sigexit(SIGILL );
6186 maybe_set_to_sigexit(SIGFPE );
6187 maybe_set_to_sigexit(SIGBUS );
6188 maybe_set_to_sigexit(SIGSEGV);
6189 maybe_set_to_sigexit(SIGTRAP);
6190 } /* else: hush is perfect. what SEGV? */
6191 maybe_set_to_sigexit(SIGABRT);
6192 /* bash 3.2 seems to handle these just like 'fatal' ones */
6193 maybe_set_to_sigexit(SIGPIPE);
6194 maybe_set_to_sigexit(SIGALRM);
6195 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6196 * if we aren't interactive... but in this case
6197 * we never want to restore pgrp on exit, and this fn is not called */
6198 /*maybe_set_to_sigexit(SIGHUP );*/
6199 /*maybe_set_to_sigexit(SIGTERM);*/
6200 /*maybe_set_to_sigexit(SIGINT );*/
6204 static int set_mode(const char cstate, const char mode)
6206 int state = (cstate == '-' ? 1 : 0);
6208 case 'n': G.fake_mode = state; break;
6209 case 'x': /*G.debug_mode = state;*/ break;
6210 default: return EXIT_FAILURE;
6212 return EXIT_SUCCESS;
6215 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6216 int hush_main(int argc, char **argv)
6218 static const struct variable const_shell_ver = {
6220 .varstr = (char*)hush_version_str,
6221 .max_len = 1, /* 0 can provoke free(name) */
6225 int signal_mask_is_inited = 0;
6228 struct variable *cur_var;
6231 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6232 G.last_exitcode = EXIT_SUCCESS;
6234 G.argv0_for_re_execing = argv[0];
6236 /* Deal with HUSH_VERSION */
6237 G.shell_ver = const_shell_ver; /* copying struct here */
6238 G.top_var = &G.shell_ver;
6239 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6240 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6241 /* Initialize our shell local variables with the values
6242 * currently living in the environment */
6243 cur_var = G.top_var;
6246 char *value = strchr(*e, '=');
6247 if (value) { /* paranoia */
6248 cur_var->next = xzalloc(sizeof(*cur_var));
6249 cur_var = cur_var->next;
6250 cur_var->varstr = *e;
6251 cur_var->max_len = strlen(*e);
6252 cur_var->flg_export = 1;
6256 debug_printf_env("putenv '%s'\n", hush_version_str);
6257 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6258 #if ENABLE_FEATURE_EDITING
6259 G.line_input_state = new_line_input_t(FOR_SHELL);
6261 G.global_argc = argc;
6262 G.global_argv = argv;
6263 /* Initialize some more globals to non-zero values */
6265 cmdedit_update_prompt();
6267 if (setjmp(die_jmp)) {
6268 /* xfunc has failed! die die die */
6269 /* no EXIT traps, this is an escape hatch! */
6271 hush_exit(xfunc_error_retval);
6274 /* Shell is non-interactive at first. We need to call
6275 * block_signals(0) if we are going to execute "sh <script>",
6276 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6277 * If we later decide that we are interactive, we run block_signals(0)
6278 * (or re-run block_signals(1) if we ran block_signals(0) before)
6279 * in order to intercept (more) signals.
6283 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6285 opt = getopt(argc, argv, "c:xins"
6288 # if ENABLE_HUSH_FUNCTIONS
6298 G.root_pid = getpid();
6299 G.global_argv = argv + optind;
6300 if (!argv[optind]) {
6301 /* -c 'script' (no params): prevent empty $0 */
6302 *--G.global_argv = argv[0];
6304 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
6305 G.global_argc = argc - optind;
6306 block_signals(0); /* 0: called 1st time */
6307 parse_and_run_string(optarg);
6310 /* Well, we cannot just declare interactiveness,
6311 * we have to have some stuff (ctty, etc) */
6312 /* G_interactive_fd++; */
6315 /* "-s" means "read from stdin", but this is how we always
6316 * operate, so simply do nothing here. */
6319 case '<': /* "big heredoc" support */
6320 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6323 G.root_pid = bb_strtou(optarg, &optarg, 16);
6325 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6327 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6328 # if ENABLE_HUSH_LOOPS
6330 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6335 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6337 # if ENABLE_HUSH_FUNCTIONS
6339 struct function *funcp = new_function(optarg);
6340 /* funcp->name is already set to optarg */
6341 /* funcp->body is set to NULL. It's a special case. */
6342 funcp->body_as_string = argv[optind];
6350 if (!set_mode('-', opt))
6354 fprintf(stderr, "Usage: sh [FILE]...\n"
6355 " or: sh -c command [args]...\n\n");
6361 } /* option parsing loop */
6364 G.root_pid = getpid();
6366 /* If we are login shell... */
6367 if (argv[0] && argv[0][0] == '-') {
6369 debug_printf("sourcing /etc/profile\n");
6370 input = fopen_for_read("/etc/profile");
6371 if (input != NULL) {
6372 close_on_exec_on(fileno(input));
6373 block_signals(0); /* 0: called 1st time */
6374 signal_mask_is_inited = 1;
6375 parse_and_run_file(input);
6378 /* bash: after sourcing /etc/profile,
6379 * tries to source (in the given order):
6380 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6381 * stopping on first found. --noprofile turns this off.
6382 * bash also sources ~/.bash_logout on exit.
6383 * If called as sh, skips .bash_XXX files.
6390 * "bash <script>" (which is never interactive (unless -i?))
6391 * sources $BASH_ENV here (without scanning $PATH).
6392 * If called as sh, does the same but with $ENV.
6394 debug_printf("running script '%s'\n", argv[optind]);
6395 G.global_argv = argv + optind;
6396 G.global_argc = argc - optind;
6397 input = xfopen_for_read(argv[optind]);
6398 close_on_exec_on(fileno(input));
6399 if (!signal_mask_is_inited)
6400 block_signals(0); /* 0: called 1st time */
6401 parse_and_run_file(input);
6402 #if ENABLE_FEATURE_CLEAN_UP
6408 /* Up to here, shell was non-interactive. Now it may become one.
6409 * NB: don't forget to (re)run block_signals(0/1) as needed.
6412 /* A shell is interactive if the '-i' flag was given,
6413 * or if all of the following conditions are met:
6415 * no arguments remaining or the -s flag given
6416 * standard input is a terminal
6417 * standard output is a terminal
6418 * Refer to Posix.2, the description of the 'sh' utility.
6421 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6422 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6423 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6424 if (G_saved_tty_pgrp < 0)
6425 G_saved_tty_pgrp = 0;
6427 /* try to dup stdin to high fd#, >= 255 */
6428 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6429 if (G_interactive_fd < 0) {
6430 /* try to dup to any fd */
6431 G_interactive_fd = dup(STDIN_FILENO);
6432 if (G_interactive_fd < 0) {
6434 G_interactive_fd = 0;
6435 G_saved_tty_pgrp = 0;
6438 // TODO: track & disallow any attempts of user
6439 // to (inadvertently) close/redirect G_interactive_fd
6441 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6442 if (G_interactive_fd) {
6443 close_on_exec_on(G_interactive_fd);
6445 if (G_saved_tty_pgrp) {
6446 /* If we were run as 'hush &', sleep until we are
6447 * in the foreground (tty pgrp == our pgrp).
6448 * If we get started under a job aware app (like bash),
6449 * make sure we are now in charge so we don't fight over
6450 * who gets the foreground */
6452 pid_t shell_pgrp = getpgrp();
6453 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6454 if (G_saved_tty_pgrp == shell_pgrp)
6456 /* send TTIN to ourself (should stop us) */
6457 kill(- shell_pgrp, SIGTTIN);
6461 /* Block some signals */
6462 block_signals(signal_mask_is_inited);
6464 if (G_saved_tty_pgrp) {
6465 /* Set other signals to restore saved_tty_pgrp */
6466 set_fatal_handlers();
6467 /* Put ourselves in our own process group
6468 * (bash, too, does this only if ctty is available) */
6469 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6470 /* Grab control of the terminal */
6471 tcsetpgrp(G_interactive_fd, getpid());
6473 /* -1 is special - makes xfuncs longjmp, not exit
6474 * (we reset die_sleep = 0 whereever we [v]fork) */
6475 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6476 } else if (!signal_mask_is_inited) {
6477 block_signals(0); /* 0: called 1st time */
6478 } /* else: block_signals(0) was done before */
6479 #elif ENABLE_HUSH_INTERACTIVE
6480 /* No job control compiled in, only prompt/line editing */
6481 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6482 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6483 if (G_interactive_fd < 0) {
6484 /* try to dup to any fd */
6485 G_interactive_fd = dup(STDIN_FILENO);
6486 if (G_interactive_fd < 0)
6488 G_interactive_fd = 0;
6491 if (G_interactive_fd) {
6492 close_on_exec_on(G_interactive_fd);
6493 block_signals(signal_mask_is_inited);
6494 } else if (!signal_mask_is_inited) {
6498 /* We have interactiveness code disabled */
6499 if (!signal_mask_is_inited) {
6504 * if interactive but not a login shell, sources ~/.bashrc
6505 * (--norc turns this off, --rcfile <file> overrides)
6508 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6509 printf("\n\n%s hush - the humble shell\n", bb_banner);
6510 if (ENABLE_HUSH_HELP)
6511 puts("Enter 'help' for a list of built-in commands.");
6515 parse_and_run_file(stdin);
6518 #if ENABLE_FEATURE_CLEAN_UP
6519 if (G.cwd != bb_msg_unknown)
6521 cur_var = G.top_var->next;
6523 struct variable *tmp = cur_var;
6524 if (!cur_var->max_len)
6525 free(cur_var->varstr);
6526 cur_var = cur_var->next;
6530 hush_exit(G.last_exitcode);
6535 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6536 int lash_main(int argc, char **argv)
6538 //bb_error_msg("lash is deprecated, please use hush instead");
6539 return hush_main(argc, argv);
6547 static int builtin_true(char **argv UNUSED_PARAM)
6552 static int builtin_test(char **argv)
6559 return test_main(argc, argv - argc);
6562 static int builtin_echo(char **argv)
6569 return echo_main(argc, argv - argc);
6572 static int builtin_eval(char **argv)
6574 int rcode = EXIT_SUCCESS;
6577 char *str = expand_strvec_to_string(argv);
6579 * eval "echo Hi; done" ("done" is syntax error):
6580 * "echo Hi" will not execute too.
6582 parse_and_run_string(str);
6584 rcode = G.last_exitcode;
6589 static int builtin_cd(char **argv)
6591 const char *newdir = argv[1];
6592 if (newdir == NULL) {
6593 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6594 * bash says "bash: cd: HOME not set" and does nothing
6597 newdir = get_local_var_value("HOME") ? : "/";
6599 if (chdir(newdir)) {
6600 /* Mimic bash message exactly */
6601 bb_perror_msg("cd: %s", newdir);
6602 return EXIT_FAILURE;
6605 return EXIT_SUCCESS;
6608 static int builtin_exec(char **argv)
6610 if (*++argv == NULL)
6611 return EXIT_SUCCESS; /* bash does this */
6616 /* TODO: if exec fails, bash does NOT exit! We do... */
6617 pseudo_exec_argv(&dummy, argv, 0, NULL);
6622 static int builtin_exit(char **argv)
6624 debug_printf_exec("%s()\n", __func__);
6626 /* interactive bash:
6627 * # trap "echo EEE" EXIT
6630 * There are stopped jobs.
6631 * (if there are _stopped_ jobs, running ones don't count)
6634 # EEE (then bash exits)
6636 * we can use G.exiting = -1 as indicator "last cmd was exit"
6639 /* note: EXIT trap is run by hush_exit */
6640 if (*++argv == NULL)
6641 hush_exit(G.last_exitcode);
6642 /* mimic bash: exit 123abc == exit 255 + error msg */
6643 xfunc_error_retval = 255;
6644 /* bash: exit -2 == exit 254, no error msg */
6645 hush_exit(xatoi(*argv) & 0xff);
6648 static void print_escaped(const char *s)
6654 p = strchrnul(s, '\'');
6655 /* print 'xxxx', possibly just '' */
6656 printf("'%.*s'", (int)(p - s), s);
6661 /* s points to '; print "'''...'''" */
6663 do putchar('\''); while (*++s == '\'');
6668 #if !ENABLE_HUSH_LOCAL
6669 #define helper_export_local(argv, exp, lvl) \
6670 helper_export_local(argv, exp)
6672 static void helper_export_local(char **argv, int exp, int lvl)
6677 /* So far we do not check that name is valid (TODO?) */
6679 if (strchr(name, '=') == NULL) {
6680 struct variable *var;
6682 var = get_local_var(name);
6683 if (exp == -1) { /* unexporting? */
6684 /* export -n NAME (without =VALUE) */
6686 var->flg_export = 0;
6687 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6689 } /* else: export -n NOT_EXISTING_VAR: no-op */
6692 if (exp == 1) { /* exporting? */
6693 /* export NAME (without =VALUE) */
6695 var->flg_export = 1;
6696 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6697 putenv(var->varstr);
6701 /* Exporting non-existing variable.
6702 * bash does not put it in environment,
6703 * but remembers that it is exported,
6704 * and does put it in env when it is set later.
6705 * We just set it to "" and export. */
6706 /* Or, it's "local NAME" (without =VALUE).
6707 * bash sets the value to "". */
6708 name = xasprintf("%s=", name);
6710 /* (Un)exporting/making local NAME=VALUE */
6711 name = xstrdup(name);
6713 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6717 static int builtin_export(char **argv)
6719 unsigned opt_unexport;
6721 if (argv[1] == NULL) {
6728 /* ash emits: export VAR='VAL'
6729 * bash: declare -x VAR="VAL"
6730 * we follow ash example */
6731 const char *s = *e++;
6732 const char *p = strchr(s, '=');
6734 if (!p) /* wtf? take next variable */
6737 printf("export %.*s", (int)(p - s) + 1, s);
6738 print_escaped(p + 1);
6742 /*fflush(stdout); - done after each builtin anyway */
6744 return EXIT_SUCCESS;
6747 #if ENABLE_HUSH_EXPORT_N
6748 /* "!": do not abort on errors */
6749 /* "+": stop at 1st non-option */
6750 opt_unexport = getopt32(argv, "!+n");
6751 if (opt_unexport == (unsigned)-1)
6752 return EXIT_FAILURE;
6759 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
6761 return EXIT_SUCCESS;
6764 #if ENABLE_HUSH_LOCAL
6765 static int builtin_local(char **argv)
6767 if (G.func_nest_level == 0) {
6768 bb_error_msg("%s: not in a function", argv[0]);
6769 return EXIT_FAILURE; /* bash compat */
6771 helper_export_local(argv, 0, G.func_nest_level);
6772 return EXIT_SUCCESS;
6776 static int builtin_trap(char **argv)
6782 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6787 /* No args: print all trapped */
6788 for (i = 0; i < NSIG; ++i) {
6791 print_escaped(G.traps[i]);
6792 printf(" %s\n", get_signame(i));
6795 /*fflush(stdout); - done after each builtin anyway */
6796 return EXIT_SUCCESS;
6800 /* If first arg is a number: reset all specified signals */
6801 sig = bb_strtou(*argv, NULL, 10);
6807 sig = get_signum(*argv++);
6808 if (sig < 0 || sig >= NSIG) {
6810 /* Mimic bash message exactly */
6811 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
6816 G.traps[sig] = xstrdup(new_cmd);
6818 debug_printf("trap: setting SIG%s (%i) to '%s'",
6819 get_signame(sig), sig, G.traps[sig]);
6821 /* There is no signal for 0 (EXIT) */
6826 sigaddset(&G.blocked_set, sig);
6828 /* There was a trap handler, we are removing it
6829 * (if sig has non-DFL handling,
6830 * we don't need to do anything) */
6831 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6833 sigdelset(&G.blocked_set, sig);
6836 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6840 if (!argv[1]) { /* no second arg */
6841 bb_error_msg("trap: invalid arguments");
6842 return EXIT_FAILURE;
6845 /* First arg is "-": reset all specified to default */
6846 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6847 /* Everything else: set arg as signal handler
6848 * (includes "" case, which ignores signal) */
6849 if (argv[0][0] == '-') {
6850 if (argv[0][1] == '\0') { /* "-" */
6851 /* new_cmd remains NULL: "reset these sigs" */
6854 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6857 /* else: "-something", no special meaning */
6862 goto process_sig_list;
6865 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
6866 static int builtin_type(char **argv)
6868 int ret = EXIT_SUCCESS;
6874 if (0) {} /* make conditional compile easier below */
6875 /*else if (find_alias(*argv))
6876 type = "an alias";*/
6877 #if ENABLE_HUSH_FUNCTIONS
6878 else if (find_function(*argv))
6879 type = "a function";
6881 else if (find_builtin(*argv))
6882 type = "a shell builtin";
6883 else if ((path = find_in_path(*argv)) != NULL)
6886 bb_error_msg("type: %s: not found", *argv);
6891 printf("%s is %s\n", *argv, type);
6899 /* built-in 'fg' and 'bg' handler */
6900 static int builtin_fg_bg(char **argv)
6905 if (!G_interactive_fd)
6906 return EXIT_FAILURE;
6908 /* If they gave us no args, assume they want the last backgrounded task */
6910 for (pi = G.job_list; pi; pi = pi->next) {
6911 if (pi->jobid == G.last_jobid) {
6915 bb_error_msg("%s: no current job", argv[0]);
6916 return EXIT_FAILURE;
6918 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6919 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6920 return EXIT_FAILURE;
6922 for (pi = G.job_list; pi; pi = pi->next) {
6923 if (pi->jobid == jobnum) {
6927 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6928 return EXIT_FAILURE;
6930 /* TODO: bash prints a string representation
6931 * of job being foregrounded (like "sleep 1 | cat") */
6932 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
6933 /* Put the job into the foreground. */
6934 tcsetpgrp(G_interactive_fd, pi->pgrp);
6937 /* Restart the processes in the job */
6938 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6939 for (i = 0; i < pi->num_cmds; i++) {
6940 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6941 pi->cmds[i].is_stopped = 0;
6943 pi->stopped_cmds = 0;
6945 i = kill(- pi->pgrp, SIGCONT);
6947 if (errno == ESRCH) {
6948 delete_finished_bg_job(pi);
6949 return EXIT_SUCCESS;
6951 bb_perror_msg("kill (SIGCONT)");
6954 if (argv[0][0] == 'f') {
6956 return checkjobs_and_fg_shell(pi);
6958 return EXIT_SUCCESS;
6962 #if ENABLE_HUSH_HELP
6963 static int builtin_help(char **argv UNUSED_PARAM)
6965 const struct built_in_command *x;
6968 "Built-in commands:\n"
6969 "------------------\n");
6970 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6971 printf("%s\t%s\n", x->cmd, x->descr);
6974 return EXIT_SUCCESS;
6979 static int builtin_jobs(char **argv UNUSED_PARAM)
6982 const char *status_string;
6984 for (job = G.job_list; job; job = job->next) {
6985 if (job->alive_cmds == job->stopped_cmds)
6986 status_string = "Stopped";
6988 status_string = "Running";
6990 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6992 return EXIT_SUCCESS;
6997 static int builtin_memleak(char **argv UNUSED_PARAM)
7002 /* Crude attempt to find where "free memory" starts,
7003 * sans fragmentation. */
7005 l = (unsigned long)p;
7008 if (l < (unsigned long)p) l = (unsigned long)p;
7011 if (!G.memleak_value)
7012 G.memleak_value = l;
7014 l -= G.memleak_value;
7021 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7026 static int builtin_pwd(char **argv UNUSED_PARAM)
7029 return EXIT_SUCCESS;
7032 static int builtin_read(char **argv)
7035 const char *name = "REPLY";
7039 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7040 * and _after_ that_ it will complain */
7041 if (!is_well_formed_var_name(name, '\0')) {
7042 /* Mimic bash message */
7043 bb_error_msg("read: '%s': not a valid identifier", name);
7048 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7050 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7051 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7054 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7055 * built-in 'set' handler
7057 * set [-abCefhmnuvx] [-o option] [argument...]
7058 * set [+abCefhmnuvx] [+o option] [argument...]
7059 * set -- [argument...]
7062 * Implementations shall support the options in both their hyphen and
7063 * plus-sign forms. These options can also be specified as options to sh.
7065 * Write out all variables and their values: set
7066 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7067 * Turn on the -x and -v options: set -xv
7068 * Unset all positional parameters: set --
7069 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7070 * Set the positional parameters to the expansion of x, even if x expands
7071 * with a leading '-' or '+': set -- $x
7073 * So far, we only support "set -- [argument...]" and some of the short names.
7075 static int builtin_set(char **argv)
7078 char **pp, **g_argv;
7079 char *arg = *++argv;
7083 for (e = G.top_var; e; e = e->next)
7085 return EXIT_SUCCESS;
7089 if (!strcmp(arg, "--")) {
7093 if (arg[0] != '+' && arg[0] != '-')
7095 for (n = 1; arg[n]; ++n)
7096 if (set_mode(arg[0], arg[n]))
7098 } while ((arg = *++argv) != NULL);
7099 /* Now argv[0] is 1st argument */
7102 return EXIT_SUCCESS;
7105 /* NB: G.global_argv[0] ($0) is never freed/changed */
7106 g_argv = G.global_argv;
7107 if (G.global_args_malloced) {
7113 G.global_args_malloced = 1;
7114 pp = xzalloc(sizeof(pp[0]) * 2);
7115 pp[0] = g_argv[0]; /* retain $0 */
7118 /* This realloc's G.global_argv */
7119 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7126 return EXIT_SUCCESS;
7128 /* Nothing known, so abort */
7130 bb_error_msg("set: %s: invalid option", arg);
7131 return EXIT_FAILURE;
7134 static int builtin_shift(char **argv)
7140 if (n >= 0 && n < G.global_argc) {
7141 if (G.global_args_malloced) {
7144 free(G.global_argv[m++]);
7147 memmove(&G.global_argv[1], &G.global_argv[n+1],
7148 G.global_argc * sizeof(G.global_argv[0]));
7149 return EXIT_SUCCESS;
7151 return EXIT_FAILURE;
7154 static int builtin_source(char **argv)
7159 #if ENABLE_HUSH_FUNCTIONS
7163 if (*++argv == NULL)
7164 return EXIT_FAILURE;
7166 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7167 input = fopen_for_read(arg_path);
7170 input = fopen_or_warn(*argv, "r");
7172 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7173 return EXIT_FAILURE;
7175 close_on_exec_on(fileno(input));
7177 #if ENABLE_HUSH_FUNCTIONS
7178 sv_flg = G.flag_return_in_progress;
7179 /* "we are inside sourced file, ok to use return" */
7180 G.flag_return_in_progress = -1;
7182 save_and_replace_G_args(&sv, argv);
7184 parse_and_run_file(input);
7187 restore_G_args(&sv, argv);
7188 #if ENABLE_HUSH_FUNCTIONS
7189 G.flag_return_in_progress = sv_flg;
7192 return G.last_exitcode;
7195 static int builtin_umask(char **argv)
7202 mode_t old_mask = mask;
7205 rc = bb_parse_mode(argv[1], &mask);
7210 * bash: umask: 'q': invalid symbolic mode operator
7211 * bash: umask: 999: octal number out of range
7213 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7218 printf("%04o\n", (unsigned) mask);
7219 /* fall through and restore mask which we set to 0 */
7223 return !rc; /* rc != 0 - success */
7226 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7227 static int builtin_unset(char **argv)
7232 /* "!": do not abort on errors */
7233 /* "+": stop at 1st non-option */
7234 opts = getopt32(argv, "!+vf");
7235 if (opts == (unsigned)-1)
7236 return EXIT_FAILURE;
7238 bb_error_msg("unset: -v and -f are exclusive");
7239 return EXIT_FAILURE;
7245 if (!(opts & 2)) { /* not -f */
7246 if (unset_local_var(*argv)) {
7247 /* unset <nonexistent_var> doesn't fail.
7248 * Error is when one tries to unset RO var.
7249 * Message was printed by unset_local_var. */
7253 #if ENABLE_HUSH_FUNCTIONS
7263 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7264 static int builtin_wait(char **argv)
7266 int ret = EXIT_SUCCESS;
7269 if (*++argv == NULL) {
7270 /* Don't care about wait results */
7271 /* Note 1: must wait until there are no more children */
7272 /* Note 2: must be interruptible */
7274 * $ sleep 3 & sleep 6 & wait
7279 * $ sleep 3 & sleep 6 & wait
7283 * ^C <-- after ~4 sec from keyboard
7286 sigaddset(&G.blocked_set, SIGCHLD);
7287 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7290 if (errno == ECHILD)
7292 /* Wait for SIGCHLD or any other signal of interest */
7293 /* sigtimedwait with infinite timeout: */
7294 sig = sigwaitinfo(&G.blocked_set, NULL);
7296 sig = check_and_run_traps(sig);
7297 if (sig && sig != SIGCHLD) { /* see note 2 */
7303 sigdelset(&G.blocked_set, SIGCHLD);
7304 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7308 /* This is probably buggy wrt interruptible-ness */
7310 pid_t pid = bb_strtou(*argv, NULL, 10);
7312 /* mimic bash message */
7313 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7314 return EXIT_FAILURE;
7316 if (waitpid(pid, &status, 0) == pid) {
7317 if (WIFSIGNALED(status))
7318 ret = 128 + WTERMSIG(status);
7319 else if (WIFEXITED(status))
7320 ret = WEXITSTATUS(status);
7324 bb_perror_msg("wait %s", *argv);
7333 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7334 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7337 def = bb_strtou(argv[1], NULL, 10);
7338 if (errno || def < def_min || argv[2]) {
7339 bb_error_msg("%s: bad arguments", argv[0]);
7347 #if ENABLE_HUSH_LOOPS
7348 static int builtin_break(char **argv)
7351 if (G.depth_of_loop == 0) {
7352 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7353 return EXIT_SUCCESS; /* bash compat */
7355 G.flag_break_continue++; /* BC_BREAK = 1 */
7357 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7358 if (depth == UINT_MAX)
7359 G.flag_break_continue = BC_BREAK;
7360 if (G.depth_of_loop < depth)
7361 G.depth_break_continue = G.depth_of_loop;
7363 return EXIT_SUCCESS;
7366 static int builtin_continue(char **argv)
7368 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7369 return builtin_break(argv);
7373 #if ENABLE_HUSH_FUNCTIONS
7374 static int builtin_return(char **argv)
7378 if (G.flag_return_in_progress != -1) {
7379 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7380 return EXIT_FAILURE; /* bash compat */
7383 G.flag_return_in_progress = 1;
7386 * out of range: wraps around at 256, does not error out
7387 * non-numeric param:
7388 * f() { false; return qwe; }; f; echo $?
7389 * bash: return: qwe: numeric argument required <== we do this
7390 * 255 <== we also do this
7392 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);