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)
53 * $var refs in function do not pick up values set by "var=val func"
55 * follow IFS rules more precisely, including update semantics
57 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
59 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
61 /* #include <dmalloc.h> */
68 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
72 /* Debug build knobs */
73 #define LEAK_HUNTING 0
74 #define BUILD_AS_NOMMU 0
75 /* Enable/disable sanity checks. Ok to enable in production,
76 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
77 * Keeping 1 for now even in released versions.
87 # define USE_FOR_NOMMU(...) __VA_ARGS__
88 # define USE_FOR_MMU(...)
91 #if defined SINGLE_APPLET_MAIN
92 /* STANDALONE does not make sense, and won't compile */
93 # undef CONFIG_FEATURE_SH_STANDALONE
94 # undef ENABLE_FEATURE_SH_STANDALONE
95 # undef IF_FEATURE_SH_STANDALONE
96 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
97 # define ENABLE_FEATURE_SH_STANDALONE 0
98 # define IF_FEATURE_SH_STANDALONE(...)
99 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
102 #if !ENABLE_HUSH_INTERACTIVE
103 # undef ENABLE_FEATURE_EDITING
104 # define ENABLE_FEATURE_EDITING 0
105 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
106 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
109 /* Do we support ANY keywords? */
110 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
111 # define HAS_KEYWORDS 1
112 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
113 # define IF_HAS_NO_KEYWORDS(...)
115 # define HAS_KEYWORDS 0
116 # define IF_HAS_KEYWORDS(...)
117 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
120 /* If you comment out one of these below, it will be #defined later
121 * to perform debug printfs to stderr: */
122 #define debug_printf(...) do {} while (0)
123 /* Finer-grained debug switches */
124 #define debug_printf_parse(...) do {} while (0)
125 #define debug_print_tree(a, b) do {} while (0)
126 #define debug_printf_exec(...) do {} while (0)
127 #define debug_printf_env(...) do {} while (0)
128 #define debug_printf_jobs(...) do {} while (0)
129 #define debug_printf_expand(...) do {} while (0)
130 #define debug_printf_glob(...) do {} while (0)
131 #define debug_printf_list(...) do {} while (0)
132 #define debug_printf_subst(...) do {} while (0)
133 #define debug_printf_clean(...) do {} while (0)
135 #define ERR_PTR ((void*)(long)1)
137 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
139 #define SPECIAL_VAR_SYMBOL 3
143 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
145 /* This supports saving pointers malloced in vfork child,
146 * to be freed in the parent.
149 typedef struct nommu_save_t {
151 struct variable *old_vars;
153 char **argv_from_re_execing;
157 /* The descrip member of this structure is only used to make
158 * debugging output pretty */
159 static const struct {
161 signed char default_fd;
165 { O_RDONLY, 0, "<" },
166 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
167 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
168 { O_RDONLY, 0, "<<" },
169 { O_CREAT|O_RDWR, 1, "<>" },
170 /* Should not be needed. Bogus default_fd helps in debugging */
171 /* { O_RDONLY, 77, "<<" }, */
174 typedef enum reserved_style {
183 #if ENABLE_HUSH_LOOPS
190 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
195 /* two pseudo-keywords support contrived "case" syntax: */
196 RES_MATCH , /* "word)" */
197 RES_CASEI , /* "this command is inside CASE" */
204 typedef struct o_string {
206 int length; /* position where data is appended */
208 /* Protect newly added chars against globbing
209 * (by prepending \ to *, ?, [, \) */
212 /* At least some part of the string was inside '' or "",
213 * possibly empty one: word"", wo''rd etc. */
215 smallint has_empty_slot;
216 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
219 MAYBE_ASSIGNMENT = 0,
220 DEFINITELY_ASSIGNMENT = 1,
222 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
224 /* Used for initialization: o_string foo = NULL_O_STRING; */
225 #define NULL_O_STRING { NULL }
227 /* I can almost use ordinary FILE*. Is open_memstream() universally
228 * available? Where is it documented? */
229 typedef struct in_str {
231 /* eof_flag=1: last char in ->p is really an EOF */
232 char eof_flag; /* meaningless if ->p == NULL */
234 #if ENABLE_HUSH_INTERACTIVE
236 smallint promptmode; /* 0: PS1, 1: PS2 */
239 int (*get) (struct in_str *);
240 int (*peek) (struct in_str *);
242 #define i_getch(input) ((input)->get(input))
243 #define i_peek(input) ((input)->peek(input))
245 struct redir_struct {
246 struct redir_struct *next;
247 char *rd_filename; /* filename */
248 int rd_fd; /* fd to redirect */
249 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
251 smallint rd_type; /* (enum redir_type) */
252 /* note: for heredocs, rd_filename contains heredoc delimiter,
253 * and subsequently heredoc itself; and rd_dup is a bitmask:
254 * 1: do we need to trim leading tabs?
255 * 2: is heredoc quoted (<<'delim' syntax) ?
258 typedef enum redir_type {
259 REDIRECT_INVALID = 0,
261 REDIRECT_OVERWRITE = 2,
263 REDIRECT_HEREDOC = 4,
265 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
268 REDIRFD_SYNTAX_ERR = -2,
269 REDIRFD_TO_FILE = -1,
270 /* otherwise, rd_fd is redirected to rd_dup */
272 HEREDOC_SKIPTABS = 1,
278 pid_t pid; /* 0 if exited */
279 int assignment_cnt; /* how many argv[i] are assignments? */
280 smallint is_stopped; /* is the command currently running? */
281 smallint grp_type; /* GRP_xxx */
283 #define GRP_SUBSHELL 1
284 #if ENABLE_HUSH_FUNCTIONS
285 # define GRP_FUNCTION 2
287 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
290 char *group_as_string;
292 #if ENABLE_HUSH_FUNCTIONS
293 struct function *child_func;
294 /* This field is used to prevent a bug here:
295 * while...do f1() {a;}; f1; f1 {b;}; f1; done
296 * When we execute "f1() {a;}" cmd, we create new function and clear
297 * cmd->group, cmd->group_as_string, cmd->argv[0].
298 * when we execute "f1 {b;}", we notice that f1 exists,
299 * and that it's "parent cmd" struct is still "alive",
300 * we put those fields back into cmd->xxx
301 * (struct function has ->parent_cmd ptr to facilitate that).
302 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
303 * Without this trick, loop would execute a;b;b;b;...
304 * instead of correct sequence a;b;a;b;...
305 * When command is freed, it severs the link
306 * (sets ->child_func->parent_cmd to NULL).
309 char **argv; /* command name and arguments */
310 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
311 * and on execution these are substituted with their values.
312 * Substitution can make _several_ words out of one argv[n]!
313 * Example: argv[0]=='.^C*^C.' here: echo .$*.
314 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
316 struct redir_struct *redirects; /* I/O redirections */
318 /* Is there anything in this command at all? */
319 #define IS_NULL_CMD(cmd) \
320 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
325 int num_cmds; /* total number of commands in pipe */
326 int alive_cmds; /* number of commands running (not exited) */
327 int stopped_cmds; /* number of commands alive, but stopped */
329 int jobid; /* job number */
330 pid_t pgrp; /* process group ID for the job */
331 char *cmdtext; /* name of job */
333 struct command *cmds; /* array of commands in pipe */
334 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
335 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
336 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
338 typedef enum pipe_style {
344 /* Is there anything in this pipe at all? */
345 #define IS_NULL_PIPE(pi) \
346 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
348 /* This holds pointers to the various results of parsing */
349 struct parse_context {
350 /* linked list of pipes */
351 struct pipe *list_head;
352 /* last pipe (being constructed right now) */
354 /* last command in pipe (being constructed right now) */
355 struct command *command;
356 /* last redirect in command->redirects list */
357 struct redir_struct *pending_redirect;
363 smallint ctx_inverted; /* "! cmd | cmd" */
365 smallint ctx_dsemicolon; /* ";;" seen */
367 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
369 /* group we are enclosed in:
370 * example: "if pipe1; pipe2; then pipe3; fi"
371 * when we see "if" or "then", we malloc and copy current context,
372 * and make ->stack point to it. then we parse pipeN.
373 * when closing "then" / fi" / whatever is found,
374 * we move list_head into ->stack->command->group,
375 * copy ->stack into current context, and delete ->stack.
376 * (parsing of { list } and ( list ) doesn't use this method)
378 struct parse_context *stack;
382 /* On program start, environ points to initial environment.
383 * putenv adds new pointers into it, unsetenv removes them.
384 * Neither of these (de)allocates the strings.
385 * setenv allocates new strings in malloc space and does putenv,
386 * and thus setenv is unusable (leaky) for shell's purposes */
387 #define setenv(...) setenv_is_leaky_dont_use()
389 struct variable *next;
390 char *varstr; /* points to "name=" portion */
391 int max_len; /* if > 0, name is part of initial env; else name is malloced */
392 smallint flg_export; /* putenv should be done on this var */
393 smallint flg_read_only;
401 #if ENABLE_HUSH_FUNCTIONS
403 struct function *next;
405 struct command *parent_cmd;
408 char *body_as_string;
414 /* "Globals" within this file */
415 /* Sorted roughly by size (smaller offsets == smaller code) */
417 /* interactive_fd != 0 means we are an interactive shell.
418 * If we are, then saved_tty_pgrp can also be != 0, meaning
419 * that controlling tty is available. With saved_tty_pgrp == 0,
420 * job control still works, but terminal signals
421 * (^C, ^Z, ^Y, ^\) won't work at all, and background
422 * process groups can only be created with "cmd &".
423 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
424 * to give tty to the foreground process group,
425 * and will take it back when the group is stopped (^Z)
428 #if ENABLE_HUSH_INTERACTIVE
429 /* 'interactive_fd' is a fd# open to ctty, if we have one
430 * _AND_ if we decided to act interactively */
434 # define G_interactive_fd (G.interactive_fd)
436 # define G_interactive_fd 0
438 #if ENABLE_FEATURE_EDITING
439 line_input_t *line_input_state;
446 pid_t saved_tty_pgrp;
447 struct pipe *job_list;
448 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
450 # define G_saved_tty_pgrp 0
452 smallint flag_SIGINT;
453 #if ENABLE_HUSH_LOOPS
454 smallint flag_break_continue;
456 #if ENABLE_HUSH_FUNCTIONS
457 /* 0: outside of a function (or sourced file)
458 * -1: inside of a function, ok to use return builtin
459 * 1: return is invoked, skip all till end of func
461 smallint flag_return_in_progress;
464 smallint exiting; /* used to prevent EXIT trap recursion */
465 /* These four support $?, $#, and $1 */
466 smalluint last_exitcode;
467 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
468 smalluint global_args_malloced;
469 /* how many non-NULL argv's we have. NB: $# + 1 */
473 char *argv0_for_re_execing;
475 #if ENABLE_HUSH_LOOPS
476 unsigned depth_break_continue;
477 unsigned depth_of_loop;
481 struct variable *top_var; /* = &G.shell_ver (set in main()) */
482 struct variable shell_ver;
483 #if ENABLE_HUSH_FUNCTIONS
484 struct function *top_func;
486 /* Signal and trap handling */
487 // unsigned count_SIGCHLD;
488 // unsigned handled_SIGCHLD;
489 /* which signals have non-DFL handler (even with no traps set)? */
490 unsigned non_DFL_mask;
491 char **traps; /* char *traps[NSIG] */
492 sigset_t blocked_set;
493 sigset_t inherited_set;
495 unsigned long memleak_value;
498 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
500 #define G (*ptr_to_globals)
501 /* Not #defining name to G.name - this quickly gets unwieldy
502 * (too many defines). Also, I actually prefer to see when a variable
503 * is global, thus "G." prefix is a useful hint */
504 #define INIT_G() do { \
505 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
509 /* Function prototypes for builtins */
510 static int builtin_cd(char **argv);
511 static int builtin_echo(char **argv);
512 static int builtin_eval(char **argv);
513 static int builtin_exec(char **argv);
514 static int builtin_exit(char **argv);
515 static int builtin_export(char **argv);
517 static int builtin_fg_bg(char **argv);
518 static int builtin_jobs(char **argv);
521 static int builtin_help(char **argv);
524 static int builtin_memleak(char **argv);
526 static int builtin_pwd(char **argv);
527 static int builtin_read(char **argv);
528 static int builtin_set(char **argv);
529 static int builtin_shift(char **argv);
530 static int builtin_source(char **argv);
531 static int builtin_test(char **argv);
532 static int builtin_trap(char **argv);
533 static int builtin_true(char **argv);
534 static int builtin_umask(char **argv);
535 static int builtin_unset(char **argv);
536 static int builtin_wait(char **argv);
537 #if ENABLE_HUSH_LOOPS
538 static int builtin_break(char **argv);
539 static int builtin_continue(char **argv);
541 #if ENABLE_HUSH_FUNCTIONS
542 static int builtin_return(char **argv);
545 /* Table of built-in functions. They can be forked or not, depending on
546 * context: within pipes, they fork. As simple commands, they do not.
547 * When used in non-forking context, they can change global variables
548 * in the parent shell process. If forked, of course they cannot.
549 * For example, 'unset foo | whatever' will parse and run, but foo will
550 * still be set at the end. */
551 struct built_in_command {
553 int (*function)(char **argv);
556 #define BLTIN(cmd, func, help) { cmd, func, help }
558 #define BLTIN(cmd, func, help) { cmd, func }
562 /* For now, echo and test are unconditionally enabled.
563 * Maybe make it configurable? */
564 static const struct built_in_command bltins[] = {
565 BLTIN("." , builtin_source , "Run commands in a file"),
566 BLTIN(":" , builtin_true , "No-op"),
567 BLTIN("[" , builtin_test , "Test condition"),
569 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
571 #if ENABLE_HUSH_LOOPS
572 BLTIN("break" , builtin_break , "Exit from a loop"),
574 BLTIN("cd" , builtin_cd , "Change directory"),
575 #if ENABLE_HUSH_LOOPS
576 BLTIN("continue", builtin_continue, "Start new loop iteration"),
578 BLTIN("echo" , builtin_echo , "Write to stdout"),
579 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
580 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
581 BLTIN("exit" , builtin_exit , "Exit"),
582 BLTIN("export" , builtin_export , "Set environment variable"),
584 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
587 BLTIN("help" , builtin_help , "List shell built-in commands"),
590 BLTIN("jobs" , builtin_jobs , "List active jobs"),
593 BLTIN("memleak" , builtin_memleak , "Debug tool"),
595 BLTIN("pwd" , builtin_pwd , "Print current directory"),
596 BLTIN("read" , builtin_read , "Input environment variable"),
597 #if ENABLE_HUSH_FUNCTIONS
598 BLTIN("return" , builtin_return , "Return from a function"),
600 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
601 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
602 BLTIN("test" , builtin_test , "Test condition"),
603 BLTIN("trap" , builtin_trap , "Trap signals"),
604 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
605 BLTIN("umask" , builtin_umask , "Set file creation mask"),
606 BLTIN("unset" , builtin_unset , "Unset environment variable"),
607 BLTIN("wait" , builtin_wait , "Wait for process"),
614 /* prevent disasters with G.debug_indent < 0 */
615 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
616 # define debug_enter() (G.debug_indent++)
617 # define debug_leave() (G.debug_indent--)
619 # define indent() ((void)0)
620 # define debug_enter() ((void)0)
621 # define debug_leave() ((void)0)
625 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
628 #ifndef debug_printf_parse
629 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
632 #ifndef debug_printf_exec
633 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
636 #ifndef debug_printf_env
637 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
640 #ifndef debug_printf_jobs
641 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
642 # define DEBUG_JOBS 1
644 # define DEBUG_JOBS 0
647 #ifndef debug_printf_expand
648 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
649 # define DEBUG_EXPAND 1
651 # define DEBUG_EXPAND 0
654 #ifndef debug_printf_glob
655 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
656 # define DEBUG_GLOB 1
658 # define DEBUG_GLOB 0
661 #ifndef debug_printf_list
662 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
665 #ifndef debug_printf_subst
666 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
669 #ifndef debug_printf_clean
670 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
671 # define DEBUG_CLEAN 1
673 # define DEBUG_CLEAN 0
677 static void debug_print_strings(const char *prefix, char **vv)
680 fprintf(stderr, "%s:\n", prefix);
682 fprintf(stderr, " '%s'\n", *vv++);
685 #define debug_print_strings(prefix, vv) ((void)0)
689 /* Leak hunting. Use hush_leaktool.sh for post-processing.
692 static void *xxmalloc(int lineno, size_t size)
694 void *ptr = xmalloc((size + 0xff) & ~0xff);
695 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
698 static void *xxrealloc(int lineno, void *ptr, size_t size)
700 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
701 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
704 static char *xxstrdup(int lineno, const char *str)
706 char *ptr = xstrdup(str);
707 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
710 static void xxfree(void *ptr)
712 fdprintf(2, "free %p\n", ptr);
715 #define xmalloc(s) xxmalloc(__LINE__, s)
716 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
717 #define xstrdup(s) xxstrdup(__LINE__, s)
718 #define free(p) xxfree(p)
722 /* Syntax and runtime errors. They always abort scripts.
723 * In interactive use they usually discard unparsed and/or unexecuted commands
724 * and return to the prompt.
725 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
728 # define die_if_script(lineno, fmt...) die_if_script(fmt)
729 # define syntax_error(lineno, msg) syntax_error(msg)
730 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
731 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
732 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
733 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
736 static void die_if_script(unsigned lineno, const char *fmt, ...)
741 bb_error_msg("hush.c:%u", lineno);
744 bb_verror_msg(fmt, p, NULL);
746 if (!G_interactive_fd)
750 static void syntax_error(unsigned lineno, const char *msg)
753 die_if_script(lineno, "syntax error: %s", msg);
755 die_if_script(lineno, "syntax error", NULL);
758 static void syntax_error_at(unsigned lineno, const char *msg)
760 die_if_script(lineno, "syntax error at '%s'", msg);
763 /* It so happens that all such cases are totally fatal
764 * even if shell is interactive: EOF while looking for closing
765 * delimiter. There is nowhere to read stuff from after that,
766 * it's EOF! The only choice is to terminate.
768 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
769 static void syntax_error_unterm_ch(unsigned lineno, char ch)
774 die_if_script(lineno, "syntax error: unterminated %s", msg);
778 static void syntax_error_unterm_str(unsigned lineno, const char *s)
780 die_if_script(lineno, "syntax error: unterminated %s", s);
783 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
788 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
792 # undef die_if_script
794 # undef syntax_error_at
795 # undef syntax_error_unterm_ch
796 # undef syntax_error_unterm_str
797 # undef syntax_error_unexpected_ch
799 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
800 # define syntax_error(msg) syntax_error(__LINE__, msg)
801 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
802 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
803 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
804 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
808 #if ENABLE_HUSH_INTERACTIVE
809 static void cmdedit_update_prompt(void);
811 # define cmdedit_update_prompt()
817 static int glob_needed(const char *s)
822 if (*s == '*' || *s == '[' || *s == '?')
829 static int is_well_formed_var_name(const char *s, char terminator)
831 if (!s || !(isalpha(*s) || *s == '_'))
834 while (isalnum(*s) || *s == '_')
836 return *s == terminator;
839 /* Replace each \x with x in place, return ptr past NUL. */
840 static char *unbackslash(char *src)
846 if ((*dst++ = *src++) == '\0')
852 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
873 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
874 v[count1 + count2] = NULL;
877 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
881 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
883 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
884 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
887 #define add_strings_to_strings(strings, add, need_to_dup) \
888 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
891 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
892 static char **add_string_to_strings(char **strings, char *add)
897 return add_strings_to_strings(strings, v, /*dup:*/ 0);
900 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
902 char **ptr = add_string_to_strings(strings, add);
903 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
906 #define add_string_to_strings(strings, add) \
907 xx_add_string_to_strings(__LINE__, strings, add)
910 static void free_strings(char **strings)
925 /* Helpers for setting new $n and restoring them back
927 typedef struct save_arg_t {
931 smallint sv_g_malloced;
934 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
938 sv->sv_argv0 = argv[0];
939 sv->sv_g_argv = G.global_argv;
940 sv->sv_g_argc = G.global_argc;
941 sv->sv_g_malloced = G.global_args_malloced;
943 argv[0] = G.global_argv[0]; /* retain $0 */
944 G.global_argv = argv;
945 G.global_args_malloced = 0;
953 static void restore_G_args(save_arg_t *sv, char **argv)
957 if (G.global_args_malloced) {
958 /* someone ran "set -- arg1 arg2 ...", undo */
960 while (*++pp) /* note: does not free $0 */
964 argv[0] = sv->sv_argv0;
965 G.global_argv = sv->sv_g_argv;
966 G.global_argc = sv->sv_g_argc;
967 G.global_args_malloced = sv->sv_g_malloced;
971 /* Basic theory of signal handling in shell
972 * ========================================
973 * This does not describe what hush does, rather, it is current understanding
974 * what it _should_ do. If it doesn't, it's a bug.
975 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
977 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
978 * is finished or backgrounded. It is the same in interactive and
979 * non-interactive shells, and is the same regardless of whether
980 * a user trap handler is installed or a shell special one is in effect.
981 * ^C or ^Z from keyboard seem to execute "at once" because it usually
982 * backgrounds (i.e. stops) or kills all members of currently running
985 * Wait builtin in interruptible by signals for which user trap is set
986 * or by SIGINT in interactive shell.
988 * Trap handlers will execute even within trap handlers. (right?)
990 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
992 * If job control is off, backgrounded commands ("cmd &")
993 * have SIGINT, SIGQUIT set to SIG_IGN.
995 * Commands run in command substitution ("`cmd`")
996 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
998 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
999 * by the shell from its parent.
1001 * Siganls which differ from SIG_DFL action
1002 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1005 * SIGTERM (interactive): ignore
1006 * SIGHUP (interactive):
1007 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1008 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1009 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1010 * that all pipe members are stopped. Try this in bash:
1011 * while :; do :; done - ^Z does not background it
1012 * (while :; do :; done) - ^Z backgrounds it
1013 * SIGINT (interactive): wait for last pipe, ignore the rest
1014 * of the command line, show prompt. NB: ^C does not send SIGINT
1015 * to interactive shell while shell is waiting for a pipe,
1016 * since shell is bg'ed (is not in foreground process group).
1017 * Example 1: this waits 5 sec, but does not execute ls:
1018 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1019 * Example 2: this does not wait and does not execute ls:
1020 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1021 * Example 3: this does not wait 5 sec, but executes ls:
1022 * "sleep 5; ls -l" + press ^C
1024 * (What happens to signals which are IGN on shell start?)
1025 * (What happens with signal mask on shell start?)
1027 * Implementation in hush
1028 * ======================
1029 * We use in-kernel pending signal mask to determine which signals were sent.
1030 * We block all signals which we don't want to take action immediately,
1031 * i.e. we block all signals which need to have special handling as described
1032 * above, and all signals which have traps set.
1033 * After each pipe execution, we extract any pending signals via sigtimedwait()
1036 * unsigned non_DFL_mask: a mask of such "special" signals
1037 * sigset_t blocked_set: current blocked signal set
1040 * clear bit in blocked_set unless it is also in non_DFL_mask
1041 * "trap 'cmd' SIGxxx":
1042 * set bit in blocked_set (even if 'cmd' is '')
1043 * after [v]fork, if we plan to be a shell:
1044 * unblock signals with special interactive handling
1045 * (child shell is not interactive),
1046 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1047 * after [v]fork, if we plan to exec:
1048 * POSIX says pending signal mask is cleared in child - no need to clear it.
1049 * Restore blocked signal set to one inherited by shell just prior to exec.
1051 * Note: as a result, we do not use signal handlers much. The only uses
1052 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
1053 * and to restore tty pgrp on signal-induced exit.
1056 SPECIAL_INTERACTIVE_SIGS = 0
1061 SPECIAL_JOB_SIGS = 0
1069 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
1071 // G.count_SIGCHLD++;
1076 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1077 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1078 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1079 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1081 /* Restores tty foreground process group, and exits.
1082 * May be called as signal handler for fatal signal
1083 * (will resend signal to itself, producing correct exit state)
1084 * or called directly with -EXITCODE.
1085 * We also call it if xfunc is exiting. */
1086 static void sigexit(int sig) NORETURN;
1087 static void sigexit(int sig)
1089 /* Disable all signals: job control, SIGPIPE, etc. */
1090 sigprocmask_allsigs(SIG_BLOCK);
1092 /* Careful: we can end up here after [v]fork. Do not restore
1093 * tty pgrp then, only top-level shell process does that */
1094 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1095 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1097 /* Not a signal, just exit */
1101 kill_myself_with_sig(sig); /* does not return */
1105 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1106 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1110 /* Restores tty foreground process group, and exits. */
1111 static void hush_exit(int exitcode) NORETURN;
1112 static void hush_exit(int exitcode)
1114 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1115 /* Prevent recursion:
1116 * trap "echo Hi; exit" EXIT; exit
1118 char *argv[] = { NULL, G.traps[0], NULL };
1126 fflush(NULL); /* flush all streams */
1127 sigexit(- (exitcode & 0xff));
1133 static int check_and_run_traps(int sig)
1135 static const struct timespec zero_timespec = { 0, 0 };
1136 smalluint save_rcode;
1142 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1147 if (G.traps && G.traps[sig]) {
1148 if (G.traps[sig][0]) {
1149 /* We have user-defined handler */
1150 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1151 save_rcode = G.last_exitcode;
1154 G.last_exitcode = save_rcode;
1155 } /* else: "" trap, ignoring signal */
1158 /* not a trap: special action */
1161 // G.count_SIGCHLD++;
1164 /* Builtin was ^C'ed, make it look prettier: */
1171 /* bash is observed to signal whole process groups,
1172 * not individual processes */
1173 for (job = G.job_list; job; job = job->next) {
1176 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1177 if (kill(- job->pgrp, SIGHUP) == 0)
1178 kill(- job->pgrp, SIGCONT);
1183 default: /* ignored: */
1184 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1192 static const char *set_cwd(void)
1194 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1195 * we must not try to free(bb_msg_unknown) */
1196 if (G.cwd == bb_msg_unknown)
1198 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1200 G.cwd = bb_msg_unknown;
1206 * Shell and environment variable support
1208 static struct variable **get_ptr_to_local_var(const char *name)
1210 struct variable **pp;
1211 struct variable *cur;
1216 while ((cur = *pp) != NULL) {
1217 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1224 static struct variable *get_local_var(const char *name)
1226 struct variable **pp = get_ptr_to_local_var(name);
1232 static const char *get_local_var_value(const char *name)
1234 struct variable **pp = get_ptr_to_local_var(name);
1236 return strchr((*pp)->varstr, '=') + 1;
1240 /* str holds "NAME=VAL" and is expected to be malloced.
1241 * We take ownership of it.
1243 * 0: do not change export flag
1244 * (if creating new variable, flag will be 0)
1245 * 1: set export flag and putenv the variable
1246 * -1: clear export flag and unsetenv the variable
1247 * flg_read_only is set only when we handle -R var=val
1250 #define set_local_var(str, flg_export, flg_read_only) \
1251 set_local_var(str, flg_export)
1253 static int set_local_var(char *str, int flg_export, int flg_read_only)
1255 struct variable *cur;
1259 eq_sign = strchr(str, '=');
1260 if (!eq_sign) { /* not expected to ever happen? */
1265 name_len = eq_sign - str + 1; /* including '=' */
1266 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1268 if (strncmp(cur->varstr, str, name_len) != 0) {
1270 /* Bail out. Note that now cur points
1271 * to last var in linked list */
1277 /* We found an existing var with this name */
1278 if (cur->flg_read_only) {
1282 bb_error_msg("%s: readonly variable", str);
1286 if (flg_export == -1) {
1287 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1292 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1297 if (cur->max_len >= strlen(str)) {
1298 /* This one is from startup env, reuse space */
1299 strcpy(cur->varstr, str);
1302 /* max_len == 0 signifies "malloced" var, which we can
1303 * (and has to) free */
1307 goto set_str_and_exp;
1310 /* Not found - create next variable struct */
1311 cur->next = xzalloc(sizeof(*cur));
1317 cur->flg_read_only = flg_read_only;
1320 if (flg_export == 1)
1321 cur->flg_export = 1;
1322 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1323 cmdedit_update_prompt();
1324 if (cur->flg_export) {
1325 if (flg_export == -1) {
1326 cur->flg_export = 0;
1327 /* unsetenv was already done */
1329 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1330 return putenv(cur->varstr);
1336 static int unset_local_var_len(const char *name, int name_len)
1338 struct variable *cur;
1339 struct variable **var_pp;
1342 return EXIT_SUCCESS;
1343 var_pp = &G.top_var;
1344 while ((cur = *var_pp) != NULL) {
1345 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1346 if (cur->flg_read_only) {
1347 bb_error_msg("%s: readonly variable", name);
1348 return EXIT_FAILURE;
1350 *var_pp = cur->next;
1351 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1352 bb_unsetenv(cur->varstr);
1353 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1354 cmdedit_update_prompt();
1358 return EXIT_SUCCESS;
1360 var_pp = &cur->next;
1362 return EXIT_SUCCESS;
1365 static int unset_local_var(const char *name)
1367 return unset_local_var_len(name, strlen(name));
1370 static void unset_vars(char **strings)
1378 const char *eq = strchrnul(*v, '=');
1379 unset_local_var_len(*v, (int)(eq - *v));
1385 #if ENABLE_SH_MATH_SUPPORT
1386 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1387 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1388 static char *endofname(const char *name)
1396 if (!is_in_name(*p))
1402 static void arith_set_local_var(const char *name, const char *val, int flags)
1404 /* arith code doesnt malloc space, so do it for it */
1405 char *var = xasprintf("%s=%s", name, val);
1406 set_local_var(var, flags, 0);
1412 * Helpers for "var1=val1 var2=val2 cmd" feature
1414 static void add_vars(struct variable *var)
1416 struct variable *next;
1420 var->next = G.top_var;
1422 if (var->flg_export) {
1423 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1424 putenv(var->varstr);
1426 debug_printf_env("%s: restoring local '%s'\n", __func__, var->varstr);
1432 static struct variable *set_vars_and_save_old(char **strings)
1435 struct variable *old = NULL;
1441 struct variable *var_p;
1442 struct variable **var_pp;
1445 eq = strchr(*s, '=');
1448 var_pp = get_ptr_to_local_var(*s);
1451 /* Remove variable from global linked list */
1453 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1454 *var_pp = var_p->next;
1455 /* Add it to returned list */
1459 set_local_var(*s, 1, 0);
1470 static int static_get(struct in_str *i)
1479 static int static_peek(struct in_str *i)
1484 #if ENABLE_HUSH_INTERACTIVE
1486 static void cmdedit_update_prompt(void)
1488 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1489 G.PS1 = get_local_var_value("PS1");
1492 G.PS2 = get_local_var_value("PS2");
1500 static const char* setup_prompt_string(int promptmode)
1502 const char *prompt_str;
1503 debug_printf("setup_prompt_string %d ", promptmode);
1504 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1505 /* Set up the prompt */
1506 if (promptmode == 0) { /* PS1 */
1508 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1513 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1514 debug_printf("result '%s'\n", prompt_str);
1518 static void get_user_input(struct in_str *i)
1521 const char *prompt_str;
1523 prompt_str = setup_prompt_string(i->promptmode);
1524 #if ENABLE_FEATURE_EDITING
1525 /* Enable command line editing only while a command line
1526 * is actually being read */
1529 /* buglet: SIGINT will not make new prompt to appear _at once_,
1530 * only after <Enter>. (^C will work) */
1531 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1532 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1533 check_and_run_traps(0);
1534 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1535 i->eof_flag = (r < 0);
1536 if (i->eof_flag) { /* EOF/error detected */
1537 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1538 G.user_input_buf[1] = '\0';
1543 fputs(prompt_str, stdout);
1545 G.user_input_buf[0] = r = fgetc(i->file);
1546 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1547 //do we need check_and_run_traps(0)? (maybe only if stdin)
1548 } while (G.flag_SIGINT);
1549 i->eof_flag = (r == EOF);
1551 i->p = G.user_input_buf;
1554 #endif /* INTERACTIVE */
1556 /* This is the magic location that prints prompts
1557 * and gets data back from the user */
1558 static int file_get(struct in_str *i)
1562 /* If there is data waiting, eat it up */
1563 if (i->p && *i->p) {
1564 #if ENABLE_HUSH_INTERACTIVE
1568 if (i->eof_flag && !*i->p)
1570 /* note: ch is never NUL */
1572 /* need to double check i->file because we might be doing something
1573 * more complicated by now, like sourcing or substituting. */
1574 #if ENABLE_HUSH_INTERACTIVE
1575 if (G_interactive_fd && i->promptme && i->file == stdin) {
1578 } while (!*i->p); /* need non-empty line */
1579 i->promptmode = 1; /* PS2 */
1584 do ch = fgetc(i->file); while (ch == '\0');
1586 debug_printf("file_get: got '%c' %d\n", ch, ch);
1587 #if ENABLE_HUSH_INTERACTIVE
1594 /* All callers guarantee this routine will never
1595 * be used right after a newline, so prompting is not needed.
1597 static int file_peek(struct in_str *i)
1600 if (i->p && *i->p) {
1601 if (i->eof_flag && !i->p[1])
1604 /* note: ch is never NUL */
1606 do ch = fgetc(i->file); while (ch == '\0');
1607 i->eof_flag = (ch == EOF);
1608 i->peek_buf[0] = ch;
1609 i->peek_buf[1] = '\0';
1611 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1615 static void setup_file_in_str(struct in_str *i, FILE *f)
1617 i->peek = file_peek;
1619 #if ENABLE_HUSH_INTERACTIVE
1621 i->promptmode = 0; /* PS1 */
1627 static void setup_string_in_str(struct in_str *i, const char *s)
1629 i->peek = static_peek;
1630 i->get = static_get;
1631 #if ENABLE_HUSH_INTERACTIVE
1633 i->promptmode = 0; /* PS1 */
1643 #define B_CHUNK (32 * sizeof(char*))
1645 static void o_reset_to_empty_unquoted(o_string *o)
1653 static void o_free(o_string *o)
1656 memset(o, 0, sizeof(*o));
1659 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1664 static void o_grow_by(o_string *o, int len)
1666 if (o->length + len > o->maxlen) {
1667 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1668 o->data = xrealloc(o->data, 1 + o->maxlen);
1672 static void o_addchr(o_string *o, int ch)
1674 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1676 o->data[o->length] = ch;
1678 o->data[o->length] = '\0';
1681 static void o_addblock(o_string *o, const char *str, int len)
1684 memcpy(&o->data[o->length], str, len);
1686 o->data[o->length] = '\0';
1690 static void o_addstr(o_string *o, const char *str)
1692 o_addblock(o, str, strlen(str));
1694 static void nommu_addchr(o_string *o, int ch)
1700 #define nommu_addchr(o, str) ((void)0)
1703 static void o_addstr_with_NUL(o_string *o, const char *str)
1705 o_addblock(o, str, strlen(str) + 1);
1708 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1713 && (*str != '*' && *str != '?' && *str != '[')
1721 /* My analysis of quoting semantics tells me that state information
1722 * is associated with a destination, not a source.
1724 static void o_addqchr(o_string *o, int ch)
1727 char *found = strchr("*?[\\", ch);
1732 o->data[o->length] = '\\';
1735 o->data[o->length] = ch;
1737 o->data[o->length] = '\0';
1740 static void o_addQchr(o_string *o, int ch)
1743 if (o->o_escape && strchr("*?[\\", ch)) {
1745 o->data[o->length] = '\\';
1749 o->data[o->length] = ch;
1751 o->data[o->length] = '\0';
1754 static void o_addQstr(o_string *o, const char *str, int len)
1757 o_addblock(o, str, len);
1763 int ordinary_cnt = strcspn(str, "*?[\\");
1764 if (ordinary_cnt > len) /* paranoia */
1766 o_addblock(o, str, ordinary_cnt);
1767 if (ordinary_cnt == len)
1769 str += ordinary_cnt;
1770 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1774 if (ch) { /* it is necessarily one of "*?[\\" */
1776 o->data[o->length] = '\\';
1780 o->data[o->length] = ch;
1782 o->data[o->length] = '\0';
1786 /* A special kind of o_string for $VAR and `cmd` expansion.
1787 * It contains char* list[] at the beginning, which is grown in 16 element
1788 * increments. Actual string data starts at the next multiple of 16 * (char*).
1789 * list[i] contains an INDEX (int!) into this string data.
1790 * It means that if list[] needs to grow, data needs to be moved higher up
1791 * but list[i]'s need not be modified.
1792 * NB: remembering how many list[i]'s you have there is crucial.
1793 * o_finalize_list() operation post-processes this structure - calculates
1794 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1796 #if DEBUG_EXPAND || DEBUG_GLOB
1797 static void debug_print_list(const char *prefix, o_string *o, int n)
1799 char **list = (char**)o->data;
1800 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1804 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1805 prefix, list, n, string_start, o->length, o->maxlen);
1808 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1809 o->data + (int)list[i] + string_start,
1810 o->data + (int)list[i] + string_start);
1814 const char *p = o->data + (int)list[n - 1] + string_start;
1816 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1820 #define debug_print_list(prefix, o, n) ((void)0)
1823 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1824 * in list[n] so that it points past last stored byte so far.
1825 * It returns n+1. */
1826 static int o_save_ptr_helper(o_string *o, int n)
1828 char **list = (char**)o->data;
1832 if (!o->has_empty_slot) {
1833 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1834 string_len = o->length - string_start;
1835 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1836 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1837 /* list[n] points to string_start, make space for 16 more pointers */
1838 o->maxlen += 0x10 * sizeof(list[0]);
1839 o->data = xrealloc(o->data, o->maxlen + 1);
1840 list = (char**)o->data;
1841 memmove(list + n + 0x10, list + n, string_len);
1842 o->length += 0x10 * sizeof(list[0]);
1844 debug_printf_list("list[%d]=%d string_start=%d\n",
1845 n, string_len, string_start);
1848 /* We have empty slot at list[n], reuse without growth */
1849 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1850 string_len = o->length - string_start;
1851 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1852 n, string_len, string_start);
1853 o->has_empty_slot = 0;
1855 list[n] = (char*)(ptrdiff_t)string_len;
1859 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1860 static int o_get_last_ptr(o_string *o, int n)
1862 char **list = (char**)o->data;
1863 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1865 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1868 /* o_glob performs globbing on last list[], saving each result
1869 * as a new list[]. */
1870 static int o_glob(o_string *o, int n)
1876 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1878 return o_save_ptr_helper(o, n);
1879 pattern = o->data + o_get_last_ptr(o, n);
1880 debug_printf_glob("glob pattern '%s'\n", pattern);
1881 if (!glob_needed(pattern)) {
1883 o->length = unbackslash(pattern) - o->data;
1884 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1885 return o_save_ptr_helper(o, n);
1888 memset(&globdata, 0, sizeof(globdata));
1889 gr = glob(pattern, 0, NULL, &globdata);
1890 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1891 if (gr == GLOB_NOSPACE)
1892 bb_error_msg_and_die("out of memory during glob");
1893 if (gr == GLOB_NOMATCH) {
1894 globfree(&globdata);
1897 if (gr != 0) { /* GLOB_ABORTED ? */
1898 /* TODO: testcase for bad glob pattern behavior */
1899 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1901 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1902 char **argv = globdata.gl_pathv;
1903 o->length = pattern - o->data; /* "forget" pattern */
1905 o_addstr_with_NUL(o, *argv);
1906 n = o_save_ptr_helper(o, n);
1912 globfree(&globdata);
1914 debug_print_list("o_glob returning", o, n);
1918 /* If o->o_glob == 1, glob the string so far remembered.
1919 * Otherwise, just finish current list[] and start new */
1920 static int o_save_ptr(o_string *o, int n)
1922 if (o->o_glob) { /* if globbing is requested */
1923 /* If o->has_empty_slot, list[n] was already globbed
1924 * (if it was requested back then when it was filled)
1925 * so don't do that again! */
1926 if (!o->has_empty_slot)
1927 return o_glob(o, n); /* o_save_ptr_helper is inside */
1929 return o_save_ptr_helper(o, n);
1932 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1933 static char **o_finalize_list(o_string *o, int n)
1938 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1940 debug_print_list("finalized", o, n);
1941 debug_printf_expand("finalized n:%d\n", n);
1942 list = (char**)o->data;
1943 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1947 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1953 /* Expansion can recurse */
1954 #if ENABLE_HUSH_TICK
1955 static int process_command_subs(o_string *dest, const char *s);
1957 static char *expand_string_to_string(const char *str);
1959 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1960 parse_stream_dquoted(dest, input, dquote_end)
1962 static int parse_stream_dquoted(o_string *as_string,
1964 struct in_str *input,
1967 /* expand_strvec_to_strvec() takes a list of strings, expands
1968 * all variable references within and returns a pointer to
1969 * a list of expanded strings, possibly with larger number
1970 * of strings. (Think VAR="a b"; echo $VAR).
1971 * This new list is allocated as a single malloc block.
1972 * NULL-terminated list of char* pointers is at the beginning of it,
1973 * followed by strings themself.
1974 * Caller can deallocate entire list by single free(list). */
1976 /* Store given string, finalizing the word and starting new one whenever
1977 * we encounter IFS char(s). This is used for expanding variable values.
1978 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1979 static int expand_on_ifs(o_string *output, int n, const char *str)
1982 int word_len = strcspn(str, G.ifs);
1984 if (output->o_escape || !output->o_glob)
1985 o_addQstr(output, str, word_len);
1986 else /* protect backslashes against globbing up :) */
1987 o_addblock_duplicate_backslash(output, str, word_len);
1990 if (!*str) /* EOL - do not finalize word */
1992 o_addchr(output, '\0');
1993 debug_print_list("expand_on_ifs", output, n);
1994 n = o_save_ptr(output, n);
1995 str += strspn(str, G.ifs); /* skip ifs chars */
1997 debug_print_list("expand_on_ifs[1]", output, n);
2001 /* Helper to expand $((...)) and heredoc body. These act as if
2002 * they are in double quotes, with the exception that they are not :).
2003 * Just the rules are similar: "expand only $var and `cmd`"
2005 * Returns malloced string.
2006 * As an optimization, we return NULL if expansion is not needed.
2008 static char *expand_pseudo_dquoted(const char *str)
2011 struct in_str input;
2012 o_string dest = NULL_O_STRING;
2014 if (strchr(str, '$') == NULL
2015 #if ENABLE_HUSH_TICK
2016 && strchr(str, '`') == NULL
2022 /* We need to expand. Example:
2023 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2025 setup_string_in_str(&input, str);
2026 parse_stream_dquoted(NULL, &dest, &input, EOF);
2027 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2028 exp_str = expand_string_to_string(dest.data);
2029 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2030 o_free_unsafe(&dest);
2034 /* Expand all variable references in given string, adding words to list[]
2035 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2036 * to be filled). This routine is extremely tricky: has to deal with
2037 * variables/parameters with whitespace, $* and $@, and constructs like
2038 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2039 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2041 /* or_mask is either 0 (normal case) or 0x80
2042 * (expansion of right-hand side of assignment == 1-element expand.
2043 * It will also do no globbing, and thus we must not backslash-quote!) */
2050 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2051 debug_print_list("expand_vars_to_list", output, n);
2052 n = o_save_ptr(output, n);
2053 debug_print_list("expand_vars_to_list[0]", output, n);
2055 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2058 char *dyn_val = NULL;
2059 const char *val = NULL;
2060 #if ENABLE_HUSH_TICK
2061 o_string subst_result = NULL_O_STRING;
2063 #if ENABLE_SH_MATH_SUPPORT
2064 char arith_buf[sizeof(arith_t)*3 + 2];
2066 o_addblock(output, arg, p - arg);
2067 debug_print_list("expand_vars_to_list[1]", output, n);
2069 p = strchr(p, SPECIAL_VAR_SYMBOL);
2071 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2072 /* "$@" is special. Even if quoted, it can still
2073 * expand to nothing (not even an empty string) */
2074 if ((first_ch & 0x7f) != '@')
2075 ored_ch |= first_ch;
2077 switch (first_ch & 0x7f) {
2078 /* Highest bit in first_ch indicates that var is double-quoted */
2080 val = utoa(G.root_pid);
2082 case '!': /* bg pid */
2083 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2085 case '?': /* exitcode */
2086 val = utoa(G.last_exitcode);
2088 case '#': /* argc */
2089 if (arg[1] != SPECIAL_VAR_SYMBOL)
2090 /* actually, it's a ${#var} */
2092 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2097 if (!G.global_argv[i])
2099 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2100 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2101 smallint sv = output->o_escape;
2102 /* unquoted var's contents should be globbed, so don't escape */
2103 output->o_escape = 0;
2104 while (G.global_argv[i]) {
2105 n = expand_on_ifs(output, n, G.global_argv[i]);
2106 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2107 if (G.global_argv[i++][0] && G.global_argv[i]) {
2108 /* this argv[] is not empty and not last:
2109 * put terminating NUL, start new word */
2110 o_addchr(output, '\0');
2111 debug_print_list("expand_vars_to_list[2]", output, n);
2112 n = o_save_ptr(output, n);
2113 debug_print_list("expand_vars_to_list[3]", output, n);
2116 output->o_escape = sv;
2118 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2119 * and in this case should treat it like '$*' - see 'else...' below */
2120 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2122 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2123 if (++i >= G.global_argc)
2125 o_addchr(output, '\0');
2126 debug_print_list("expand_vars_to_list[4]", output, n);
2127 n = o_save_ptr(output, n);
2129 } else { /* quoted $*: add as one word */
2131 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2132 if (!G.global_argv[++i])
2135 o_addchr(output, G.ifs[0]);
2139 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2140 /* "Empty variable", used to make "" etc to not disappear */
2144 #if ENABLE_HUSH_TICK
2145 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2148 /* Can't just stuff it into output o_string,
2149 * expanded result may need to be globbed
2150 * and $IFS-splitted */
2151 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2152 process_command_subs(&subst_result, arg);
2153 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2154 val = subst_result.data;
2157 #if ENABLE_SH_MATH_SUPPORT
2158 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2159 arith_eval_hooks_t hooks;
2164 arg++; /* skip '+' */
2165 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2166 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2168 exp_str = expand_pseudo_dquoted(arg);
2169 hooks.lookupvar = get_local_var_value;
2170 hooks.setvar = arith_set_local_var;
2171 hooks.endofname = endofname;
2172 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2176 const char *msg = "error in arithmetic";
2179 msg = "exponent less than 0";
2182 msg = "divide by 0";
2185 msg = "expression recursion loop detected";
2190 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2191 sprintf(arith_buf, arith_t_fmt, res);
2196 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2198 bool exp_len = false;
2199 bool exp_null = false;
2201 char exp_save = exp_save; /* for compiler */
2202 char exp_op = exp_op; /* for compiler */
2203 char *exp_word = exp_word; /* for compiler */
2207 arg[0] = first_ch & 0x7f;
2209 /* prepare for expansions */
2210 if (var[0] == '#') {
2211 /* handle length expansion ${#var} */
2215 /* maybe handle parameter expansion */
2216 exp_off = strcspn(var, ":-=+?%#");
2220 exp_save = var[exp_off];
2221 exp_null = exp_save == ':';
2222 exp_word = var + exp_off;
2225 exp_op = *exp_word++;
2226 var[exp_off] = '\0';
2230 /* lookup the variable in question */
2231 if (isdigit(var[0])) {
2232 /* handle_dollar() should have vetted var for us */
2234 if (i < G.global_argc)
2235 val = G.global_argv[i];
2236 /* else val remains NULL: $N with too big N */
2238 val = get_local_var_value(var);
2240 /* handle any expansions */
2242 debug_printf_expand("expand: length of '%s' = ", val);
2243 val = utoa(val ? strlen(val) : 0);
2244 debug_printf_expand("%s\n", val);
2245 } else if (exp_off) {
2246 if (exp_op == '%' || exp_op == '#') {
2248 /* we need to do a pattern match */
2251 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2252 if (exp_op == *exp_word) /* ## or %% */
2254 val = dyn_val = xstrdup(val);
2255 loc = scan(dyn_val, exp_word, match_at_left);
2256 if (match_at_left) /* # or ## */
2258 else if (loc) /* % or %% and match was found */
2262 /* we need to do an expansion */
2263 int exp_test = (!val || (exp_null && !val[0]));
2265 exp_test = !exp_test;
2266 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2267 exp_null ? "true" : "false", exp_test);
2269 if (exp_op == '?') {
2270 //TODO: how interactive bash aborts expansion mid-command?
2271 /* ${var?[error_msg_if_unset]} */
2272 /* ${var:?[error_msg_if_unset_or_null]} */
2273 /* mimic bash message */
2274 die_if_script("%s: %s",
2276 exp_word[0] ? exp_word : "parameter null or not set"
2282 if (exp_op == '=') {
2283 /* ${var=[word]} or ${var:=[word]} */
2284 if (isdigit(var[0]) || var[0] == '#') {
2285 /* mimic bash message */
2286 die_if_script("$%s: cannot assign in this way", var);
2289 char *new_var = xasprintf("%s=%s", var, val);
2290 set_local_var(new_var, 0, 0);
2296 var[exp_off] = exp_save;
2300 #if ENABLE_HUSH_TICK
2303 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2304 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2306 /* unquoted var's contents should be globbed, so don't escape */
2307 smallint sv = output->o_escape;
2308 output->o_escape = 0;
2309 n = expand_on_ifs(output, n, val);
2311 output->o_escape = sv;
2313 } else { /* quoted $VAR, val will be appended below */
2314 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2317 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2320 o_addQstr(output, val, strlen(val));
2323 /* Do the check to avoid writing to a const string */
2324 if (*p != SPECIAL_VAR_SYMBOL)
2325 *p = SPECIAL_VAR_SYMBOL;
2327 #if ENABLE_HUSH_TICK
2328 o_free(&subst_result);
2331 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2334 debug_print_list("expand_vars_to_list[a]", output, n);
2335 /* this part is literal, and it was already pre-quoted
2336 * if needed (much earlier), do not use o_addQstr here! */
2337 o_addstr_with_NUL(output, arg);
2338 debug_print_list("expand_vars_to_list[b]", output, n);
2339 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2340 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2343 /* allow to reuse list[n] later without re-growth */
2344 output->has_empty_slot = 1;
2346 o_addchr(output, '\0');
2351 static char **expand_variables(char **argv, int or_mask)
2356 o_string output = NULL_O_STRING;
2358 if (or_mask & 0x100) {
2359 output.o_escape = 1; /* protect against globbing for "$var" */
2360 /* (unquoted $var will temporarily switch it off) */
2367 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2370 debug_print_list("expand_variables", &output, n);
2372 /* output.data (malloced in one block) gets returned in "list" */
2373 list = o_finalize_list(&output, n);
2374 debug_print_strings("expand_variables[1]", list);
2378 static char **expand_strvec_to_strvec(char **argv)
2380 return expand_variables(argv, 0x100);
2383 /* Used for expansion of right hand of assignments */
2384 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2386 static char *expand_string_to_string(const char *str)
2388 char *argv[2], **list;
2390 argv[0] = (char*)str;
2392 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2394 if (!list[0] || list[1])
2395 bb_error_msg_and_die("BUG in varexp2");
2396 /* actually, just move string 2*sizeof(char*) bytes back */
2397 overlapping_strcpy((char*)list, list[0]);
2398 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2402 /* Used for "eval" builtin */
2403 static char* expand_strvec_to_string(char **argv)
2407 list = expand_variables(argv, 0x80);
2408 /* Convert all NULs to spaces */
2413 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2414 bb_error_msg_and_die("BUG in varexp3");
2415 /* bash uses ' ' regardless of $IFS contents */
2420 overlapping_strcpy((char*)list, list[0]);
2421 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2425 static char **expand_assignments(char **argv, int count)
2429 /* Expand assignments into one string each */
2430 for (i = 0; i < count; i++) {
2431 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2439 void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
2441 static void reset_traps_to_defaults(void)
2443 /* This function is always called in a child shell
2444 * after fork (not vfork, NOMMU doesn't use this function).
2445 * Child shells are not interactive.
2446 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2447 * Testcase: (while :; do :; done) + ^Z should background.
2448 * Same goes for SIGTERM, SIGHUP, SIGINT.
2453 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2456 /* Stupid. It can be done with *single* &= op, but we can't use
2457 * the fact that G.blocked_set is implemented as a bitmask... */
2458 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2462 sigdelset(&G.blocked_set, sig);
2469 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2470 mask = G.non_DFL_mask;
2471 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2475 G.traps[sig] = NULL;
2476 /* There is no signal for 0 (EXIT) */
2479 /* There was a trap handler, we are removing it.
2480 * But if sig still has non-DFL handling,
2481 * we should not unblock it. */
2484 sigdelset(&G.blocked_set, sig);
2486 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2491 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2492 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
2494 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2495 char *heredoc_argv[4];
2496 struct variable *cur;
2497 #if ENABLE_HUSH_FUNCTIONS
2498 struct function *funcp;
2503 if (!g_argv0) { /* heredoc */
2504 argv = heredoc_argv;
2505 argv[0] = (char *) G.argv0_for_re_execing;
2506 argv[1] = (char *) "-<";
2507 argv[2] = (char *) s;
2509 pp = &argv[3]; /* used as pointer to empty environment */
2513 sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
2514 , (unsigned) G.root_pid
2515 , (unsigned) G.last_bg_pid
2516 , (unsigned) G.last_exitcode
2517 IF_HUSH_LOOPS(, G.depth_of_loop)
2519 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2520 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2523 for (cur = G.top_var; cur; cur = cur->next) {
2524 if (!cur->flg_export || cur->flg_read_only)
2527 #if ENABLE_HUSH_FUNCTIONS
2528 for (funcp = G.top_func; funcp; funcp = funcp->next)
2534 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2535 *pp++ = (char *) G.argv0_for_re_execing;
2537 for (cur = G.top_var; cur; cur = cur->next) {
2538 if (cur->varstr == hush_version_str)
2540 if (cur->flg_read_only) {
2541 *pp++ = (char *) "-R";
2542 *pp++ = cur->varstr;
2543 } else if (!cur->flg_export) {
2544 *pp++ = (char *) "-V";
2545 *pp++ = cur->varstr;
2548 #if ENABLE_HUSH_FUNCTIONS
2549 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2550 *pp++ = (char *) "-F";
2551 *pp++ = funcp->name;
2552 *pp++ = funcp->body_as_string;
2555 /* We can pass activated traps here. Say, -Tnn:trap_string
2557 * However, POSIX says that subshells reset signals with traps
2559 * I tested bash-3.2 and it not only does that with true subshells
2560 * of the form ( list ), but with any forked children shells.
2561 * I set trap "echo W" WINCH; and then tried:
2563 * { echo 1; sleep 20; echo 2; } &
2564 * while true; do echo 1; sleep 20; echo 2; break; done &
2565 * true | { echo 1; sleep 20; echo 2; } | cat
2567 * In all these cases sending SIGWINCH to the child shell
2568 * did not run the trap. If I add trap "echo V" WINCH;
2569 * _inside_ group (just before echo 1), it works.
2571 * I conclude it means we don't need to pass active traps here.
2572 * exec syscall below resets them to SIG_DFL for us.
2574 *pp++ = (char *) "-c";
2579 /* *pp = NULL; - is already there */
2583 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2584 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2585 execve(bb_busybox_exec_path, argv, pp);
2586 /* Fallback. Useful for init=/bin/hush usage etc */
2587 if (argv[0][0] == '/')
2588 execve(argv[0], argv, pp);
2589 xfunc_error_retval = 127;
2590 bb_error_msg_and_die("can't re-execute the shell");
2592 #endif /* !BB_MMU */
2595 static void setup_heredoc(struct redir_struct *redir)
2597 struct fd_pair pair;
2600 /* the _body_ of heredoc (misleading field name) */
2601 const char *heredoc = redir->rd_filename;
2608 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2609 expanded = expand_pseudo_dquoted(heredoc);
2613 len = strlen(heredoc);
2615 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2617 xmove_fd(pair.rd, redir->rd_fd);
2619 /* Try writing without forking. Newer kernels have
2620 * dynamically growing pipes. Must use non-blocking write! */
2623 written = write(pair.wr, heredoc, len);
2634 ndelay_off(pair.wr);
2636 /* Okay, pipe buffer was not big enough */
2637 /* Note: we must not create a stray child (bastard? :)
2638 * for the unsuspecting parent process. Child creates a grandchild
2639 * and exits before parent execs the process which consumes heredoc
2640 * (that exec happens after we return from this function) */
2646 bb_perror_msg_and_die("vfork");
2649 disable_restore_tty_pgrp_on_exit();
2650 pid = BB_MMU ? fork() : vfork();
2652 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2656 close(redir->rd_fd); /* read side of the pipe */
2658 full_write(pair.wr, heredoc, len); /* may loop or block */
2661 /* Delegate blocking writes to another process */
2662 xmove_fd(pair.wr, STDOUT_FILENO);
2663 re_execute_shell(&to_free, heredoc, NULL, NULL);
2667 enable_restore_tty_pgrp_on_exit();
2673 wait(NULL); /* wait till child has died */
2676 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2677 * and stderr if they are redirected. */
2678 static int setup_redirects(struct command *prog, int squirrel[])
2681 struct redir_struct *redir;
2683 for (redir = prog->redirects; redir; redir = redir->next) {
2684 if (redir->rd_type == REDIRECT_HEREDOC2) {
2685 /* rd_fd<<HERE case */
2686 if (squirrel && redir->rd_fd < 3
2687 && squirrel[redir->rd_fd] < 0
2689 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2691 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2693 debug_printf_parse("set heredoc '%s'\n",
2694 redir->rd_filename);
2695 setup_heredoc(redir);
2699 if (redir->rd_dup == REDIRFD_TO_FILE) {
2700 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2702 if (redir->rd_filename == NULL) {
2703 /* Something went wrong in the parse.
2704 * Pretend it didn't happen */
2705 bb_error_msg("bug in redirect parse");
2708 mode = redir_table[redir->rd_type].mode;
2709 p = expand_string_to_string(redir->rd_filename);
2710 openfd = open_or_warn(p, mode);
2713 /* this could get lost if stderr has been redirected, but
2714 * bash and ash both lose it as well (though zsh doesn't!) */
2715 //what the above comment tries to say?
2719 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2720 openfd = redir->rd_dup;
2723 if (openfd != redir->rd_fd) {
2724 if (squirrel && redir->rd_fd < 3
2725 && squirrel[redir->rd_fd] < 0
2727 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2729 if (openfd == REDIRFD_CLOSE) {
2730 /* "n>-" means "close me" */
2731 close(redir->rd_fd);
2733 xdup2(openfd, redir->rd_fd);
2734 if (redir->rd_dup == REDIRFD_TO_FILE)
2742 static void restore_redirects(int squirrel[])
2745 for (i = 0; i < 3; i++) {
2748 /* We simply die on error */
2755 static void free_pipe_list(struct pipe *head);
2757 /* Return code is the exit status of the pipe */
2758 static void free_pipe(struct pipe *pi)
2761 struct command *command;
2762 struct redir_struct *r, *rnext;
2765 if (pi->stopped_cmds > 0) /* why? */
2767 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2768 for (i = 0; i < pi->num_cmds; i++) {
2769 command = &pi->cmds[i];
2770 debug_printf_clean(" command %d:\n", i);
2771 if (command->argv) {
2772 for (a = 0, p = command->argv; *p; a++, p++) {
2773 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2775 free_strings(command->argv);
2776 command->argv = NULL;
2778 /* not "else if": on syntax error, we may have both! */
2779 if (command->group) {
2780 debug_printf_clean(" begin group (grp_type:%d)\n",
2782 free_pipe_list(command->group);
2783 debug_printf_clean(" end group\n");
2784 command->group = NULL;
2786 /* else is crucial here.
2787 * If group != NULL, child_func is meaningless */
2788 #if ENABLE_HUSH_FUNCTIONS
2789 else if (command->child_func) {
2790 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2791 command->child_func->parent_cmd = NULL;
2795 free(command->group_as_string);
2796 command->group_as_string = NULL;
2798 for (r = command->redirects; r; r = rnext) {
2799 debug_printf_clean(" redirect %d%s",
2800 r->rd_fd, redir_table[r->rd_type].descrip);
2801 /* guard against the case >$FOO, where foo is unset or blank */
2802 if (r->rd_filename) {
2803 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2804 free(r->rd_filename);
2805 r->rd_filename = NULL;
2807 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2811 command->redirects = NULL;
2813 free(pi->cmds); /* children are an array, they get freed all at once */
2821 static void free_pipe_list(struct pipe *head)
2823 struct pipe *pi, *next;
2825 for (pi = head; pi; pi = next) {
2827 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2830 debug_printf_clean("pipe followup code %d\n", pi->followup);
2832 /*pi->next = NULL;*/
2838 static int run_list(struct pipe *pi);
2840 #define parse_stream(pstring, input, end_trigger) \
2841 parse_stream(input, end_trigger)
2843 static struct pipe *parse_stream(char **pstring,
2844 struct in_str *input,
2846 static void parse_and_run_string(const char *s);
2849 static const struct built_in_command* find_builtin(const char *name)
2851 const struct built_in_command *x;
2852 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2853 if (strcmp(name, x->cmd) != 0)
2855 debug_printf_exec("found builtin '%s'\n", name);
2861 #if ENABLE_HUSH_FUNCTIONS
2862 static const struct function *find_function(const char *name)
2864 const struct function *funcp = G.top_func;
2866 if (strcmp(name, funcp->name) == 0) {
2869 funcp = funcp->next;
2872 debug_printf_exec("found function '%s'\n", name);
2876 /* Note: takes ownership on name ptr */
2877 static struct function *new_function(char *name)
2879 struct function *funcp;
2880 struct function **funcpp = &G.top_func;
2882 while ((funcp = *funcpp) != NULL) {
2883 struct command *cmd;
2885 if (strcmp(funcp->name, name) != 0) {
2886 funcpp = &funcp->next;
2890 cmd = funcp->parent_cmd;
2891 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2893 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2895 /* Note: if !funcp->body, do not free body_as_string!
2896 * This is a special case of "-F name body" function:
2897 * body_as_string was not malloced! */
2899 free_pipe_list(funcp->body);
2901 free(funcp->body_as_string);
2905 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2906 cmd->argv[0] = funcp->name;
2907 cmd->group = funcp->body;
2909 cmd->group_as_string = funcp->body_as_string;
2914 debug_printf_exec("remembering new function '%s'\n", name);
2915 funcp = *funcpp = xzalloc(sizeof(*funcp));
2916 /*funcp->next = NULL;*/
2922 static void unset_func(const char *name)
2924 struct function *funcp;
2925 struct function **funcpp = &G.top_func;
2927 while ((funcp = *funcpp) != NULL) {
2928 if (strcmp(funcp->name, name) == 0) {
2929 *funcpp = funcp->next;
2930 /* funcp is unlinked now, deleting it.
2931 * Note: if !funcp->body, the function was created by
2932 * "-F name body", do not free ->body_as_string
2933 * and ->name as they were not malloced. */
2935 free_pipe_list(funcp->body);
2938 free(funcp->body_as_string);
2944 funcpp = &funcp->next;
2949 #define exec_function(nommu_save, funcp, argv) \
2950 exec_function(funcp, argv)
2952 static void exec_function(nommu_save_t *nommu_save,
2953 const struct function *funcp,
2954 char **argv) NORETURN;
2955 static void exec_function(nommu_save_t *nommu_save,
2956 const struct function *funcp,
2962 argv[0] = G.global_argv[0];
2963 G.global_argv = argv;
2967 /* On MMU, funcp->body is always non-NULL */
2968 n = run_list(funcp->body);
2972 re_execute_shell(&nommu_save->argv_from_re_execing,
2973 funcp->body_as_string,
2979 static int run_function(const struct function *funcp, char **argv)
2985 save_and_replace_G_args(&sv, argv);
2986 /* "we are in function, ok to use return" */
2987 sv_flg = G.flag_return_in_progress;
2988 G.flag_return_in_progress = -1;
2990 /* On MMU, funcp->body is always non-NULL */
2993 /* Function defined by -F */
2994 parse_and_run_string(funcp->body_as_string);
2995 rc = G.last_exitcode;
2999 rc = run_list(funcp->body);
3002 G.flag_return_in_progress = sv_flg;
3003 restore_G_args(&sv, argv);
3007 #endif /* ENABLE_HUSH_FUNCTIONS */
3011 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3012 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3013 #define pseudo_exec(nommu_save, command, argv_expanded) \
3014 pseudo_exec(command, argv_expanded)
3017 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3019 * Don't exit() here. If you don't exec, use _exit instead.
3020 * The at_exit handlers apparently confuse the calling process,
3021 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3022 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3023 char **argv, int assignment_cnt,
3024 char **argv_expanded) NORETURN;
3025 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3026 char **argv, int assignment_cnt,
3027 char **argv_expanded)
3031 /* Case when we are here: ... | var=val | ... */
3032 if (!argv[assignment_cnt])
3033 _exit(EXIT_SUCCESS);
3035 new_env = expand_assignments(argv, assignment_cnt);
3037 set_vars_and_save_old(new_env);
3038 free(new_env); /* optional */
3039 /* we can also destroy set_vars_and_save_old's return value,
3042 nommu_save->new_env = new_env;
3043 nommu_save->old_vars = set_vars_and_save_old(new_env);
3045 if (argv_expanded) {
3046 argv = argv_expanded;
3048 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3050 nommu_save->argv = argv;
3054 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3055 if (strchr(argv[0], '/') != NULL)
3059 /* On NOMMU, we must never block!
3060 * Example: { sleep 99999 | read line } & echo Ok
3061 * read builtin will block on read syscall, leaving parent blocked
3062 * in vfork. Therefore we can't do this:
3065 /* Check if the command matches any of the builtins.
3066 * Depending on context, this might be redundant. But it's
3067 * easier to waste a few CPU cycles than it is to figure out
3068 * if this is one of those cases.
3072 const struct built_in_command *x = find_builtin(argv[0]);
3074 rcode = x->function(argv);
3080 #if ENABLE_HUSH_FUNCTIONS
3081 /* Check if the command matches any functions */
3083 const struct function *funcp = find_function(argv[0]);
3085 exec_function(nommu_save, funcp, argv);
3090 #if ENABLE_FEATURE_SH_STANDALONE
3091 /* Check if the command matches any busybox applets */
3093 int a = find_applet_by_name(argv[0]);
3095 # if BB_MMU /* see above why on NOMMU it is not allowed */
3096 if (APPLET_IS_NOEXEC(a)) {
3097 debug_printf_exec("running applet '%s'\n", argv[0]);
3098 run_applet_no_and_exit(a, argv);
3101 /* Re-exec ourselves */
3102 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3103 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3104 execv(bb_busybox_exec_path, argv);
3105 /* If they called chroot or otherwise made the binary no longer
3106 * executable, fall through */
3111 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3114 debug_printf_exec("execing '%s'\n", argv[0]);
3115 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3116 execvp(argv[0], argv);
3117 bb_perror_msg("can't execute '%s'", argv[0]);
3118 _exit(EXIT_FAILURE);
3121 /* Called after [v]fork() in run_pipe
3123 static void pseudo_exec(nommu_save_t *nommu_save,
3124 struct command *command,
3125 char **argv_expanded) NORETURN;
3126 static void pseudo_exec(nommu_save_t *nommu_save,
3127 struct command *command,
3128 char **argv_expanded)
3130 if (command->argv) {
3131 pseudo_exec_argv(nommu_save, command->argv,
3132 command->assignment_cnt, argv_expanded);
3135 if (command->group) {
3136 /* Cases when we are here:
3139 * ... | ( list ) | ...
3140 * ... | { list } | ...
3144 debug_printf_exec("pseudo_exec: run_list\n");
3145 reset_traps_to_defaults();
3146 rcode = run_list(command->group);
3147 /* OK to leak memory by not calling free_pipe_list,
3148 * since this process is about to exit */
3151 re_execute_shell(&nommu_save->argv_from_re_execing,
3152 command->group_as_string,
3158 /* Case when we are here: ... | >file */
3159 debug_printf_exec("pseudo_exec'ed null command\n");
3160 _exit(EXIT_SUCCESS);
3164 static const char *get_cmdtext(struct pipe *pi)
3170 /* This is subtle. ->cmdtext is created only on first backgrounding.
3171 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3172 * On subsequent bg argv is trashed, but we won't use it */
3175 argv = pi->cmds[0].argv;
3176 if (!argv || !argv[0]) {
3177 pi->cmdtext = xzalloc(1);
3183 len += strlen(*argv) + 1;
3187 argv = pi->cmds[0].argv;
3189 len = strlen(*argv);
3190 memcpy(p, *argv, len);
3198 static void insert_bg_job(struct pipe *pi)
3200 struct pipe *job, **jobp;
3203 /* Linear search for the ID of the job to use */
3205 for (job = G.job_list; job; job = job->next)
3206 if (job->jobid >= pi->jobid)
3207 pi->jobid = job->jobid + 1;
3209 /* Add job to the list of running jobs */
3211 while ((job = *jobp) != NULL)
3213 job = *jobp = xmalloc(sizeof(*job));
3215 *job = *pi; /* physical copy */
3217 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3218 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3219 for (i = 0; i < pi->num_cmds; i++) {
3220 job->cmds[i].pid = pi->cmds[i].pid;
3221 /* all other fields are not used and stay zero */
3223 job->cmdtext = xstrdup(get_cmdtext(pi));
3225 if (G_interactive_fd)
3226 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3227 /* Last command's pid goes to $! */
3228 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3229 G.last_jobid = job->jobid;
3232 static void remove_bg_job(struct pipe *pi)
3234 struct pipe *prev_pipe;
3236 if (pi == G.job_list) {
3237 G.job_list = pi->next;
3239 prev_pipe = G.job_list;
3240 while (prev_pipe->next != pi)
3241 prev_pipe = prev_pipe->next;
3242 prev_pipe->next = pi->next;
3245 G.last_jobid = G.job_list->jobid;
3250 /* Remove a backgrounded job */
3251 static void delete_finished_bg_job(struct pipe *pi)
3254 pi->stopped_cmds = 0;
3260 /* Check to see if any processes have exited -- if they
3261 * have, figure out why and see if a job has completed */
3262 static int checkjobs(struct pipe* fg_pipe)
3272 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3275 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
3276 // /* avoid doing syscall, nothing there anyway */
3279 attributes = WUNTRACED;
3280 if (fg_pipe == NULL)
3281 attributes |= WNOHANG;
3283 /* Do we do this right?
3284 * bash-3.00# sleep 20 | false
3286 * [3]+ Stopped sleep 20 | false
3287 * bash-3.00# echo $?
3288 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3289 * [hush 1.14.0: yes we do it right]
3296 // i = G.count_SIGCHLD;
3297 childpid = waitpid(-1, &status, attributes);
3298 if (childpid <= 0) {
3299 if (childpid && errno != ECHILD)
3300 bb_perror_msg("waitpid");
3301 // else /* Until next SIGCHLD, waitpid's are useless */
3302 // G.handled_SIGCHLD = i;
3305 dead = WIFEXITED(status) || WIFSIGNALED(status);
3308 if (WIFSTOPPED(status))
3309 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3310 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3311 if (WIFSIGNALED(status))
3312 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3313 childpid, WTERMSIG(status), WEXITSTATUS(status));
3314 if (WIFEXITED(status))
3315 debug_printf_jobs("pid %d exited, exitcode %d\n",
3316 childpid, WEXITSTATUS(status));
3318 /* Were we asked to wait for fg pipe? */
3320 for (i = 0; i < fg_pipe->num_cmds; i++) {
3321 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3322 if (fg_pipe->cmds[i].pid != childpid)
3325 fg_pipe->cmds[i].pid = 0;
3326 fg_pipe->alive_cmds--;
3327 if (i == fg_pipe->num_cmds - 1) {
3328 /* last process gives overall exitstatus */
3329 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3330 rcode = WEXITSTATUS(status);
3331 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3332 /* bash prints killing signal's name for *last*
3333 * process in pipe (prints just newline for SIGINT).
3334 * Mimic this. Example: "sleep 5" + ^\
3336 if (WIFSIGNALED(status)) {
3337 int sig = WTERMSIG(status);
3338 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3342 fg_pipe->cmds[i].is_stopped = 1;
3343 fg_pipe->stopped_cmds++;
3345 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3346 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3347 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3348 /* All processes in fg pipe have exited or stopped */
3349 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3350 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3351 * and "killall -STOP cat" */
3352 if (G_interactive_fd) {
3354 if (fg_pipe->alive_cmds)
3355 insert_bg_job(fg_pipe);
3360 /* There are still running processes in the fg pipe */
3361 goto wait_more; /* do waitpid again */
3363 /* it wasnt fg_pipe, look for process in bg pipes */
3367 /* We asked to wait for bg or orphaned children */
3368 /* No need to remember exitcode in this case */
3369 for (pi = G.job_list; pi; pi = pi->next) {
3370 for (i = 0; i < pi->num_cmds; i++) {
3371 if (pi->cmds[i].pid == childpid)
3372 goto found_pi_and_prognum;
3375 /* Happens when shell is used as init process (init=/bin/sh) */
3376 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3377 continue; /* do waitpid again */
3379 found_pi_and_prognum:
3382 pi->cmds[i].pid = 0;
3384 if (!pi->alive_cmds) {
3385 if (G_interactive_fd)
3386 printf(JOB_STATUS_FORMAT, pi->jobid,
3387 "Done", pi->cmdtext);
3388 delete_finished_bg_job(pi);
3392 pi->cmds[i].is_stopped = 1;
3396 } /* while (waitpid succeeds)... */
3402 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3405 int rcode = checkjobs(fg_pipe);
3406 if (G_saved_tty_pgrp) {
3407 /* Job finished, move the shell to the foreground */
3408 p = getpgrp(); /* our process group id */
3409 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3410 tcsetpgrp(G_interactive_fd, p);
3416 /* Start all the jobs, but don't wait for anything to finish.
3419 * Return code is normally -1, when the caller has to wait for children
3420 * to finish to determine the exit status of the pipe. If the pipe
3421 * is a simple builtin command, however, the action is done by the
3422 * time run_pipe returns, and the exit code is provided as the
3425 * Returns -1 only if started some children. IOW: we have to
3426 * mask out retvals of builtins etc with 0xff!
3428 * The only case when we do not need to [v]fork is when the pipe
3429 * is single, non-backgrounded, non-subshell command. Examples:
3430 * cmd ; ... { list } ; ...
3431 * cmd && ... { list } && ...
3432 * cmd || ... { list } || ...
3433 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3434 * or (if SH_STANDALONE) an applet, and we can run the { list }
3435 * with run_list. If it isn't one of these, we fork and exec cmd.
3437 * Cases when we must fork:
3438 * non-single: cmd | cmd
3439 * backgrounded: cmd & { list } &
3440 * subshell: ( list ) [&]
3442 static int run_pipe(struct pipe *pi)
3444 static const char *const null_ptr = NULL;
3447 struct command *command;
3448 char **argv_expanded;
3451 /* it is not always needed, but we aim to smaller code */
3452 int squirrel[] = { -1, -1, -1 };
3455 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3458 IF_HUSH_JOB(pi->pgrp = -1;)
3459 pi->stopped_cmds = 0;
3460 command = &(pi->cmds[0]);
3461 argv_expanded = NULL;
3463 if (pi->num_cmds != 1
3464 || pi->followup == PIPE_BG
3465 || command->grp_type == GRP_SUBSHELL
3472 debug_printf_exec(": group:%p argv:'%s'\n",
3473 command->group, command->argv ? command->argv[0] : "NONE");
3475 if (command->group) {
3476 #if ENABLE_HUSH_FUNCTIONS
3477 if (command->grp_type == GRP_FUNCTION) {
3478 /* "executing" func () { list } */
3479 struct function *funcp;
3481 funcp = new_function(command->argv[0]);
3482 /* funcp->name is already set to argv[0] */
3483 funcp->body = command->group;
3485 funcp->body_as_string = command->group_as_string;
3486 command->group_as_string = NULL;
3488 command->group = NULL;
3489 command->argv[0] = NULL;
3490 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3491 funcp->parent_cmd = command;
3492 command->child_func = funcp;
3494 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3496 return EXIT_SUCCESS;
3500 debug_printf("non-subshell group\n");
3501 rcode = 1; /* exitcode if redir failed */
3502 if (setup_redirects(command, squirrel) == 0) {
3503 debug_printf_exec(": run_list\n");
3504 rcode = run_list(command->group) & 0xff;
3506 restore_redirects(squirrel);
3507 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3509 debug_printf_exec("run_pipe: return %d\n", rcode);
3513 argv = command->argv ? command->argv : (char **) &null_ptr;
3515 const struct built_in_command *x;
3516 #if ENABLE_HUSH_FUNCTIONS
3517 const struct function *funcp;
3521 char **new_env = NULL;
3522 struct variable *old_vars = NULL;
3524 if (argv[command->assignment_cnt] == NULL) {
3525 /* Assignments, but no command */
3526 /* Ensure redirects take effect. Try "a=t >file" */
3527 rcode = setup_redirects(command, squirrel);
3528 restore_redirects(squirrel);
3529 /* Set shell variables */
3531 p = expand_string_to_string(*argv);
3532 debug_printf_exec("set shell var:'%s'->'%s'\n",
3534 set_local_var(p, 0, 0);
3537 /* Do we need to flag set_local_var() errors?
3538 * "assignment to readonly var" and "putenv error"
3540 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3542 debug_printf_exec("run_pipe: return %d\n", rcode);
3546 /* Expand the rest into (possibly) many strings each */
3547 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3549 x = find_builtin(argv_expanded[0]);
3550 #if ENABLE_HUSH_FUNCTIONS
3553 funcp = find_function(argv_expanded[0]);
3557 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3558 debug_printf("exec with redirects only\n");
3559 rcode = setup_redirects(command, NULL);
3560 goto clean_up_and_ret1;
3563 /* setup_redirects acts on file descriptors, not FILEs.
3564 * This is perfect for work that comes after exec().
3565 * Is it really safe for inline use? Experimentally,
3566 * things seem to work. */
3567 rcode = setup_redirects(command, squirrel);
3569 new_env = expand_assignments(argv, command->assignment_cnt);
3570 old_vars = set_vars_and_save_old(new_env);
3572 debug_printf_exec(": builtin '%s' '%s'...\n",
3573 x->cmd, argv_expanded[1]);
3574 rcode = x->function(argv_expanded) & 0xff;
3577 #if ENABLE_HUSH_FUNCTIONS
3579 debug_printf_exec(": function '%s' '%s'...\n",
3580 funcp->name, argv_expanded[1]);
3581 rcode = run_function(funcp, argv_expanded) & 0xff;
3585 #if ENABLE_FEATURE_SH_STANDALONE
3588 restore_redirects(squirrel);
3589 unset_vars(new_env);
3592 free(argv_expanded);
3593 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3595 debug_printf_exec("run_pipe return %d\n", rcode);
3599 #if ENABLE_FEATURE_SH_STANDALONE
3600 i = find_applet_by_name(argv_expanded[0]);
3601 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3602 rcode = setup_redirects(command, squirrel);
3604 new_env = expand_assignments(argv, command->assignment_cnt);
3605 old_vars = set_vars_and_save_old(new_env);
3606 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3607 argv_expanded[0], argv_expanded[1]);
3608 rcode = run_nofork_applet(i, argv_expanded);
3610 goto clean_up_and_ret;
3613 /* It is neither builtin nor applet. We must fork. */
3617 /* NB: argv_expanded may already be created, and that
3618 * might include `cmd` runs! Do not rerun it! We *must*
3619 * use argv_expanded if it's non-NULL */
3621 /* Going to fork a child per each pipe member */
3625 for (i = 0; i < pi->num_cmds; i++) {
3626 struct fd_pair pipefds;
3628 volatile nommu_save_t nommu_save;
3629 nommu_save.new_env = NULL;
3630 nommu_save.old_vars = NULL;
3631 nommu_save.argv = NULL;
3632 nommu_save.argv_from_re_execing = NULL;
3634 command = &(pi->cmds[i]);
3635 if (command->argv) {
3636 debug_printf_exec(": pipe member '%s' '%s'...\n",
3637 command->argv[0], command->argv[1]);
3639 debug_printf_exec(": pipe member with no argv\n");
3642 /* pipes are inserted between pairs of commands */
3645 if ((i + 1) < pi->num_cmds)
3646 xpiped_pair(pipefds);
3648 command->pid = BB_MMU ? fork() : vfork();
3649 if (!command->pid) { /* child */
3651 disable_restore_tty_pgrp_on_exit();
3653 /* Every child adds itself to new process group
3654 * with pgid == pid_of_first_child_in_pipe */
3655 if (G.run_list_level == 1 && G_interactive_fd) {
3658 if (pgrp < 0) /* true for 1st process only */
3660 if (setpgid(0, pgrp) == 0
3661 && pi->followup != PIPE_BG
3662 && G_saved_tty_pgrp /* we have ctty */
3664 /* We do it in *every* child, not just first,
3666 tcsetpgrp(G_interactive_fd, pgrp);
3670 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3671 /* 1st cmd in backgrounded pipe
3672 * should have its stdin /dev/null'ed */
3674 if (open(bb_dev_null, O_RDONLY))
3675 xopen("/", O_RDONLY);
3677 xmove_fd(nextin, 0);
3679 xmove_fd(pipefds.wr, 1);
3682 /* Like bash, explicit redirects override pipes,
3683 * and the pipe fd is available for dup'ing. */
3684 if (setup_redirects(command, NULL))
3687 /* Restore default handlers just prior to exec */
3688 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3690 /* Stores to nommu_save list of env vars putenv'ed
3691 * (NOMMU, on MMU we don't need that) */
3692 /* cast away volatility... */
3693 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3694 /* pseudo_exec() does not return */
3697 /* parent or error */
3698 enable_restore_tty_pgrp_on_exit();
3700 /* Clean up after vforked child */
3701 free(nommu_save.argv);
3702 free(nommu_save.argv_from_re_execing);
3703 unset_vars(nommu_save.new_env);
3704 add_vars(nommu_save.old_vars);
3706 free(argv_expanded);
3707 argv_expanded = NULL;
3708 if (command->pid < 0) { /* [v]fork failed */
3709 /* Clearly indicate, was it fork or vfork */
3710 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3714 /* Second and next children need to know pid of first one */
3716 pi->pgrp = command->pid;
3722 if ((i + 1) < pi->num_cmds)
3724 /* Pass read (output) pipe end to next iteration */
3725 nextin = pipefds.rd;
3728 if (!pi->alive_cmds) {
3730 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3735 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3739 #ifndef debug_print_tree
3740 static void debug_print_tree(struct pipe *pi, int lvl)
3742 static const char *const PIPE[] = {
3748 static const char *RES[] = {
3749 [RES_NONE ] = "NONE" ,
3752 [RES_THEN ] = "THEN" ,
3753 [RES_ELIF ] = "ELIF" ,
3754 [RES_ELSE ] = "ELSE" ,
3757 #if ENABLE_HUSH_LOOPS
3758 [RES_FOR ] = "FOR" ,
3759 [RES_WHILE] = "WHILE",
3760 [RES_UNTIL] = "UNTIL",
3762 [RES_DONE ] = "DONE" ,
3764 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3767 #if ENABLE_HUSH_CASE
3768 [RES_CASE ] = "CASE" ,
3769 [RES_MATCH] = "MATCH",
3770 [RES_CASEI] = "CASEI",
3771 [RES_ESAC ] = "ESAC" ,
3773 [RES_XXXX ] = "XXXX" ,
3774 [RES_SNTX ] = "SNTX" ,
3776 static const char *const GRPTYPE[] = {
3779 #if ENABLE_HUSH_FUNCTIONS
3788 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3789 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3791 while (prn < pi->num_cmds) {
3792 struct command *command = &pi->cmds[prn];
3793 char **argv = command->argv;
3795 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3797 command->assignment_cnt);
3798 if (command->group) {
3799 fprintf(stderr, " group %s: (argv=%p)\n",
3800 GRPTYPE[command->grp_type],
3802 debug_print_tree(command->group, lvl+1);
3806 if (argv) while (*argv) {
3807 fprintf(stderr, " '%s'", *argv);
3810 fprintf(stderr, "\n");
3819 /* NB: called by pseudo_exec, and therefore must not modify any
3820 * global data until exec/_exit (we can be a child after vfork!) */
3821 static int run_list(struct pipe *pi)
3823 #if ENABLE_HUSH_CASE
3824 char *case_word = NULL;
3826 #if ENABLE_HUSH_LOOPS
3827 struct pipe *loop_top = NULL;
3828 char *for_varname = NULL;
3829 char **for_lcur = NULL;
3830 char **for_list = NULL;
3832 smallint last_followup;
3834 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3835 smalluint cond_code = 0;
3837 enum { cond_code = 0 };
3840 smallint rword; /* enum reserved_style */
3841 smallint last_rword; /* ditto */
3844 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
3847 #if ENABLE_HUSH_LOOPS
3848 /* Check syntax for "for" */
3849 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3850 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3852 /* current word is FOR or IN (BOLD in comments below) */
3853 if (cpipe->next == NULL) {
3854 syntax_error("malformed for");
3856 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3859 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3860 if (cpipe->next->res_word == RES_DO)
3862 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3863 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3864 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3866 syntax_error("malformed for");
3868 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3874 /* Past this point, all code paths should jump to ret: label
3875 * in order to return, no direct "return" statements please.
3876 * This helps to ensure that no memory is leaked. */
3884 last_rword = RES_XXXX;
3886 last_followup = PIPE_SEQ;
3887 rcode = G.last_exitcode;
3889 /* Go through list of pipes, (maybe) executing them. */
3890 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3894 IF_HAS_KEYWORDS(rword = pi->res_word;)
3895 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3896 rword, cond_code, last_rword);
3897 #if ENABLE_HUSH_LOOPS
3898 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3899 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3901 /* start of a loop: remember where loop starts */
3906 /* Still in the same "if...", "then..." or "do..." branch? */
3907 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3908 if ((rcode == 0 && last_followup == PIPE_OR)
3909 || (rcode != 0 && last_followup == PIPE_AND)
3911 /* It is "<true> || CMD" or "<false> && CMD"
3912 * and we should not execute CMD */
3913 debug_printf_exec("skipped cmd because of || or &&\n");
3914 last_followup = pi->followup;
3918 last_followup = pi->followup;
3919 IF_HAS_KEYWORDS(last_rword = rword;)
3922 if (rword == RES_THEN) {
3923 /* if false; then ... fi has exitcode 0! */
3924 G.last_exitcode = rcode = EXIT_SUCCESS;
3925 /* "if <false> THEN cmd": skip cmd */
3929 if (rword == RES_ELSE || rword == RES_ELIF) {
3930 /* "if <true> then ... ELSE/ELIF cmd":
3931 * skip cmd and all following ones */
3936 #if ENABLE_HUSH_LOOPS
3937 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3939 /* first loop through for */
3941 static const char encoded_dollar_at[] ALIGN1 = {
3942 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3943 }; /* encoded representation of "$@" */
3944 static const char *const encoded_dollar_at_argv[] = {
3945 encoded_dollar_at, NULL
3946 }; /* argv list with one element: "$@" */
3949 vals = (char**)encoded_dollar_at_argv;
3950 if (pi->next->res_word == RES_IN) {
3951 /* if no variable values after "in" we skip "for" */
3952 if (!pi->next->cmds[0].argv) {
3953 G.last_exitcode = rcode = EXIT_SUCCESS;
3954 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3957 vals = pi->next->cmds[0].argv;
3958 } /* else: "for var; do..." -> assume "$@" list */
3959 /* create list of variable values */
3960 debug_print_strings("for_list made from", vals);
3961 for_list = expand_strvec_to_strvec(vals);
3962 for_lcur = for_list;
3963 debug_print_strings("for_list", for_list);
3964 for_varname = pi->cmds[0].argv[0];
3965 pi->cmds[0].argv[0] = NULL;
3967 free(pi->cmds[0].argv[0]);
3969 /* "for" loop is over, clean up */
3973 pi->cmds[0].argv[0] = for_varname;
3976 /* Insert next value from for_lcur */
3977 /* note: *for_lcur already has quotes removed, $var expanded, etc */
3978 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3979 pi->cmds[0].assignment_cnt = 1;
3981 if (rword == RES_IN) {
3982 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3984 if (rword == RES_DONE) {
3985 continue; /* "done" has no cmds too */
3988 #if ENABLE_HUSH_CASE
3989 if (rword == RES_CASE) {
3990 case_word = expand_strvec_to_string(pi->cmds->argv);
3993 if (rword == RES_MATCH) {
3996 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3998 /* all prev words didn't match, does this one match? */
3999 argv = pi->cmds->argv;
4001 char *pattern = expand_string_to_string(*argv);
4002 /* TODO: which FNM_xxx flags to use? */
4003 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4005 if (cond_code == 0) { /* match! we will execute this branch */
4006 free(case_word); /* make future "word)" stop */
4014 if (rword == RES_CASEI) { /* inside of a case branch */
4016 continue; /* not matched yet, skip this pipe */
4019 /* Just pressing <enter> in shell should check for jobs.
4020 * OTOH, in non-interactive shell this is useless
4021 * and only leads to extra job checks */
4022 if (pi->num_cmds == 0) {
4023 if (G_interactive_fd)
4024 goto check_jobs_and_continue;
4028 /* After analyzing all keywords and conditions, we decided
4029 * to execute this pipe. NB: have to do checkjobs(NULL)
4030 * after run_pipe to collect any background children,
4031 * even if list execution is to be stopped. */
4032 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4035 #if ENABLE_HUSH_LOOPS
4036 G.flag_break_continue = 0;
4038 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4040 /* We ran a builtin, function, or group.
4041 * rcode is already known
4042 * and we don't need to wait for anything. */
4043 G.last_exitcode = rcode;
4044 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4045 check_and_run_traps(0);
4046 #if ENABLE_HUSH_LOOPS
4047 /* Was it "break" or "continue"? */
4048 if (G.flag_break_continue) {
4049 smallint fbc = G.flag_break_continue;
4050 /* We might fall into outer *loop*,
4051 * don't want to break it too */
4053 G.depth_break_continue--;
4054 if (G.depth_break_continue == 0)
4055 G.flag_break_continue = 0;
4056 /* else: e.g. "continue 2" should *break* once, *then* continue */
4057 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4058 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4059 goto check_jobs_and_break;
4060 /* "continue": simulate end of loop */
4065 #if ENABLE_HUSH_FUNCTIONS
4066 if (G.flag_return_in_progress == 1)
4067 goto check_jobs_and_break;
4069 } else if (pi->followup == PIPE_BG) {
4070 /* What does bash do with attempts to background builtins? */
4071 /* even bash 3.2 doesn't do that well with nested bg:
4072 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4073 * I'm NOT treating inner &'s as jobs */
4074 check_and_run_traps(0);
4076 if (G.run_list_level == 1)
4079 G.last_exitcode = rcode = EXIT_SUCCESS;
4080 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4083 if (G.run_list_level == 1 && G_interactive_fd) {
4084 /* Waits for completion, then fg's main shell */
4085 rcode = checkjobs_and_fg_shell(pi);
4086 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4087 check_and_run_traps(0);
4090 { /* This one just waits for completion */
4091 rcode = checkjobs(pi);
4092 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4093 check_and_run_traps(0);
4095 G.last_exitcode = rcode;
4099 /* Analyze how result affects subsequent commands */
4101 if (rword == RES_IF || rword == RES_ELIF)
4104 #if ENABLE_HUSH_LOOPS
4105 /* Beware of "while false; true; do ..."! */
4106 if (pi->next && pi->next->res_word == RES_DO) {
4107 if (rword == RES_WHILE) {
4109 /* "while false; do...done" - exitcode 0 */
4110 G.last_exitcode = rcode = EXIT_SUCCESS;
4111 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4112 goto check_jobs_and_break;
4115 if (rword == RES_UNTIL) {
4117 debug_printf_exec(": until expr is true: breaking\n");
4118 check_jobs_and_break:
4126 check_jobs_and_continue:
4133 #if ENABLE_HUSH_LOOPS
4138 #if ENABLE_HUSH_CASE
4142 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4146 /* Select which version we will use */
4147 static int run_and_free_list(struct pipe *pi)
4150 debug_printf_exec("run_and_free_list entered\n");
4152 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4153 rcode = run_list(pi);
4155 /* free_pipe_list has the side effect of clearing memory.
4156 * In the long run that function can be merged with run_list,
4157 * but doing that now would hobble the debugging effort. */
4159 debug_printf_exec("run_and_free_list return %d\n", rcode);
4164 static struct pipe *new_pipe(void)
4167 pi = xzalloc(sizeof(struct pipe));
4168 /*pi->followup = 0; - deliberately invalid value */
4169 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4173 /* Command (member of a pipe) is complete, or we start a new pipe
4174 * if ctx->command is NULL.
4175 * No errors possible here.
4177 static int done_command(struct parse_context *ctx)
4179 /* The command is really already in the pipe structure, so
4180 * advance the pipe counter and make a new, null command. */
4181 struct pipe *pi = ctx->pipe;
4182 struct command *command = ctx->command;
4185 if (IS_NULL_CMD(command)) {
4186 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4190 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4191 //debug_print_tree(ctx->list_head, 20);
4193 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4196 /* Only real trickiness here is that the uncommitted
4197 * command structure is not counted in pi->num_cmds. */
4198 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4199 ctx->command = command = &pi->cmds[pi->num_cmds];
4201 memset(command, 0, sizeof(*command));
4202 return pi->num_cmds; /* used only for 0/nonzero check */
4205 static void done_pipe(struct parse_context *ctx, pipe_style type)
4209 debug_printf_parse("done_pipe entered, followup %d\n", type);
4210 /* Close previous command */
4211 not_null = done_command(ctx);
4212 ctx->pipe->followup = type;
4214 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4215 ctx->ctx_inverted = 0;
4216 ctx->pipe->res_word = ctx->ctx_res_w;
4219 /* Without this check, even just <enter> on command line generates
4220 * tree of three NOPs (!). Which is harmless but annoying.
4221 * IOW: it is safe to do it unconditionally. */
4224 || ctx->ctx_res_w == RES_FI
4226 #if ENABLE_HUSH_LOOPS
4227 || ctx->ctx_res_w == RES_DONE
4228 || ctx->ctx_res_w == RES_FOR
4229 || ctx->ctx_res_w == RES_IN
4231 #if ENABLE_HUSH_CASE
4232 || ctx->ctx_res_w == RES_ESAC
4236 debug_printf_parse("done_pipe: adding new pipe: "
4237 "not_null:%d ctx->ctx_res_w:%d\n",
4238 not_null, ctx->ctx_res_w);
4240 ctx->pipe->next = new_p;
4242 /* RES_THEN, RES_DO etc are "sticky" -
4243 * they remain set for pipes inside if/while.
4244 * This is used to control execution.
4245 * RES_FOR and RES_IN are NOT sticky (needed to support
4246 * cases where variable or value happens to match a keyword):
4248 #if ENABLE_HUSH_LOOPS
4249 if (ctx->ctx_res_w == RES_FOR
4250 || ctx->ctx_res_w == RES_IN)
4251 ctx->ctx_res_w = RES_NONE;
4253 #if ENABLE_HUSH_CASE
4254 if (ctx->ctx_res_w == RES_MATCH)
4255 ctx->ctx_res_w = RES_CASEI;
4257 ctx->command = NULL; /* trick done_command below */
4258 /* Create the memory for command, roughly:
4259 * ctx->pipe->cmds = new struct command;
4260 * ctx->command = &ctx->pipe->cmds[0];
4263 //debug_print_tree(ctx->list_head, 10);
4265 debug_printf_parse("done_pipe return\n");
4268 static void initialize_context(struct parse_context *ctx)
4270 memset(ctx, 0, sizeof(*ctx));
4271 ctx->pipe = ctx->list_head = new_pipe();
4272 /* Create the memory for command, roughly:
4273 * ctx->pipe->cmds = new struct command;
4274 * ctx->command = &ctx->pipe->cmds[0];
4279 /* If a reserved word is found and processed, parse context is modified
4280 * and 1 is returned.
4283 struct reserved_combo {
4286 unsigned char assignment_flag;
4290 FLAG_END = (1 << RES_NONE ),
4292 FLAG_IF = (1 << RES_IF ),
4293 FLAG_THEN = (1 << RES_THEN ),
4294 FLAG_ELIF = (1 << RES_ELIF ),
4295 FLAG_ELSE = (1 << RES_ELSE ),
4296 FLAG_FI = (1 << RES_FI ),
4298 #if ENABLE_HUSH_LOOPS
4299 FLAG_FOR = (1 << RES_FOR ),
4300 FLAG_WHILE = (1 << RES_WHILE),
4301 FLAG_UNTIL = (1 << RES_UNTIL),
4302 FLAG_DO = (1 << RES_DO ),
4303 FLAG_DONE = (1 << RES_DONE ),
4304 FLAG_IN = (1 << RES_IN ),
4306 #if ENABLE_HUSH_CASE
4307 FLAG_MATCH = (1 << RES_MATCH),
4308 FLAG_ESAC = (1 << RES_ESAC ),
4310 FLAG_START = (1 << RES_XXXX ),
4313 static const struct reserved_combo* match_reserved_word(o_string *word)
4315 /* Mostly a list of accepted follow-up reserved words.
4316 * FLAG_END means we are done with the sequence, and are ready
4317 * to turn the compound list into a command.
4318 * FLAG_START means the word must start a new compound list.
4320 static const struct reserved_combo reserved_list[] = {
4322 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4323 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4324 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4325 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4326 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4327 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4329 #if ENABLE_HUSH_LOOPS
4330 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4331 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4332 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4333 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4334 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4335 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4337 #if ENABLE_HUSH_CASE
4338 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4339 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4342 const struct reserved_combo *r;
4344 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4345 if (strcmp(word->data, r->literal) == 0)
4350 /* Return 0: not a keyword, 1: keyword
4352 static int reserved_word(o_string *word, struct parse_context *ctx)
4354 #if ENABLE_HUSH_CASE
4355 static const struct reserved_combo reserved_match = {
4356 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4359 const struct reserved_combo *r;
4363 r = match_reserved_word(word);
4367 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4368 #if ENABLE_HUSH_CASE
4369 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
4370 /* "case word IN ..." - IN part starts first match part */
4371 r = &reserved_match;
4374 if (r->flag == 0) { /* '!' */
4375 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4376 syntax_error("! ! command");
4377 ctx->ctx_res_w = RES_SNTX;
4379 ctx->ctx_inverted = 1;
4382 if (r->flag & FLAG_START) {
4383 struct parse_context *old;
4385 old = xmalloc(sizeof(*old));
4386 debug_printf_parse("push stack %p\n", old);
4387 *old = *ctx; /* physical copy */
4388 initialize_context(ctx);
4390 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4391 syntax_error_at(word->data);
4392 ctx->ctx_res_w = RES_SNTX;
4395 /* "{...} fi" is ok. "{...} if" is not
4397 * if { echo foo; } then { echo bar; } fi */
4398 if (ctx->command->group)
4399 done_pipe(ctx, PIPE_SEQ);
4402 ctx->ctx_res_w = r->res;
4403 ctx->old_flag = r->flag;
4404 word->o_assignment = r->assignment_flag;
4406 if (ctx->old_flag & FLAG_END) {
4407 struct parse_context *old;
4409 done_pipe(ctx, PIPE_SEQ);
4410 debug_printf_parse("pop stack %p\n", ctx->stack);
4412 old->command->group = ctx->list_head;
4413 old->command->grp_type = GRP_NORMAL;
4415 o_addstr(&old->as_string, ctx->as_string.data);
4416 o_free_unsafe(&ctx->as_string);
4417 old->command->group_as_string = xstrdup(old->as_string.data);
4418 debug_printf_parse("pop, remembering as:'%s'\n",
4419 old->command->group_as_string);
4421 *ctx = *old; /* physical copy */
4428 /* Word is complete, look at it and update parsing context.
4429 * Normal return is 0. Syntax errors return 1.
4430 * Note: on return, word is reset, but not o_free'd!
4432 static int done_word(o_string *word, struct parse_context *ctx)
4434 struct command *command = ctx->command;
4436 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4437 if (word->length == 0 && word->o_quoted == 0) {
4438 debug_printf_parse("done_word return 0: true null, ignored\n");
4442 if (ctx->pending_redirect) {
4443 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4444 * only if run as "bash", not "sh" */
4445 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4447 * ...the word that follows the redirection operator
4448 * shall be subjected to tilde expansion, parameter expansion,
4449 * command substitution, arithmetic expansion, and quote
4450 * removal. Pathname expansion shall not be performed
4451 * on the word by a non-interactive shell; an interactive
4452 * shell may perform it, but shall do so only when
4453 * the expansion would result in one word."
4455 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4456 /* Cater for >\file case:
4457 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4458 * Same with heredocs:
4459 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4461 unbackslash(ctx->pending_redirect->rd_filename);
4462 /* Is it <<"HEREDOC"? */
4463 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4466 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4468 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4469 ctx->pending_redirect = NULL;
4471 /* If this word wasn't an assignment, next ones definitely
4472 * can't be assignments. Even if they look like ones. */
4473 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4474 && word->o_assignment != WORD_IS_KEYWORD
4476 word->o_assignment = NOT_ASSIGNMENT;
4478 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4479 command->assignment_cnt++;
4480 word->o_assignment = MAYBE_ASSIGNMENT;
4484 # if ENABLE_HUSH_CASE
4485 if (ctx->ctx_dsemicolon
4486 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4488 /* already done when ctx_dsemicolon was set to 1: */
4489 /* ctx->ctx_res_w = RES_MATCH; */
4490 ctx->ctx_dsemicolon = 0;
4493 if (!command->argv /* if it's the first word... */
4494 # if ENABLE_HUSH_LOOPS
4495 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4496 && ctx->ctx_res_w != RES_IN
4499 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4500 if (reserved_word(word, ctx)) {
4501 o_reset_to_empty_unquoted(word);
4502 debug_printf_parse("done_word return %d\n",
4503 (ctx->ctx_res_w == RES_SNTX));
4504 return (ctx->ctx_res_w == RES_SNTX);
4508 if (command->group) {
4509 /* "{ echo foo; } echo bar" - bad */
4510 syntax_error_at(word->data);
4511 debug_printf_parse("done_word return 1: syntax error, "
4512 "groups and arglists don't mix\n");
4515 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4516 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4517 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4518 /* (otherwise it's known to be not empty and is already safe) */
4520 /* exclude "$@" - it can expand to no word despite "" */
4521 char *p = word->data;
4522 while (p[0] == SPECIAL_VAR_SYMBOL
4523 && (p[1] & 0x7f) == '@'
4524 && p[2] == SPECIAL_VAR_SYMBOL
4528 if (p == word->data || p[0] != '\0') {
4529 /* saw no "$@", or not only "$@" but some
4530 * real text is there too */
4531 /* insert "empty variable" reference, this makes
4532 * e.g. "", $empty"" etc to not disappear */
4533 o_addchr(word, SPECIAL_VAR_SYMBOL);
4534 o_addchr(word, SPECIAL_VAR_SYMBOL);
4537 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4538 debug_print_strings("word appended to argv", command->argv);
4541 #if ENABLE_HUSH_LOOPS
4542 if (ctx->ctx_res_w == RES_FOR) {
4544 || !is_well_formed_var_name(command->argv[0], '\0')
4546 /* bash says just "not a valid identifier" */
4547 syntax_error("not a valid identifier in for");
4550 /* Force FOR to have just one word (variable name) */
4551 /* NB: basically, this makes hush see "for v in ..."
4552 * syntax as if it is "for v; in ...". FOR and IN become
4553 * two pipe structs in parse tree. */
4554 done_pipe(ctx, PIPE_SEQ);
4557 #if ENABLE_HUSH_CASE
4558 /* Force CASE to have just one word */
4559 if (ctx->ctx_res_w == RES_CASE) {
4560 done_pipe(ctx, PIPE_SEQ);
4564 o_reset_to_empty_unquoted(word);
4566 debug_printf_parse("done_word return 0\n");
4571 /* Peek ahead in the input to find out if we have a "&n" construct,
4572 * as in "2>&1", that represents duplicating a file descriptor.
4574 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4575 * REDIRFD_SYNTAX_ERR if syntax error,
4576 * REDIRFD_TO_FILE if no & was seen,
4577 * or the number found.
4580 #define parse_redir_right_fd(as_string, input) \
4581 parse_redir_right_fd(input)
4583 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4589 return REDIRFD_TO_FILE;
4591 ch = i_getch(input); /* get the & */
4592 nommu_addchr(as_string, ch);
4595 ch = i_getch(input);
4596 nommu_addchr(as_string, ch);
4597 return REDIRFD_CLOSE;
4601 while (ch != EOF && isdigit(ch)) {
4602 d = d*10 + (ch-'0');
4604 ch = i_getch(input);
4605 nommu_addchr(as_string, ch);
4610 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4612 bb_error_msg("ambiguous redirect");
4613 return REDIRFD_SYNTAX_ERR;
4616 /* Return code is 0 normal, 1 if a syntax error is detected
4618 static int parse_redirect(struct parse_context *ctx,
4621 struct in_str *input)
4623 struct command *command = ctx->command;
4624 struct redir_struct *redir;
4625 struct redir_struct **redirp;
4628 dup_num = REDIRFD_TO_FILE;
4629 if (style != REDIRECT_HEREDOC) {
4630 /* Check for a '>&1' type redirect */
4631 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4632 if (dup_num == REDIRFD_SYNTAX_ERR)
4635 int ch = i_peek(input);
4636 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4637 if (dup_num) { /* <<-... */
4638 ch = i_getch(input);
4639 nommu_addchr(&ctx->as_string, ch);
4644 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4645 int ch = i_peek(input);
4647 /* >|FILE redirect ("clobbering" >).
4648 * Since we do not support "set -o noclobber" yet,
4649 * >| and > are the same for now. Just eat |.
4651 ch = i_getch(input);
4652 nommu_addchr(&ctx->as_string, ch);
4656 /* Create a new redir_struct and append it to the linked list */
4657 redirp = &command->redirects;
4658 while ((redir = *redirp) != NULL) {
4659 redirp = &(redir->next);
4661 *redirp = redir = xzalloc(sizeof(*redir));
4662 /* redir->next = NULL; */
4663 /* redir->rd_filename = NULL; */
4664 redir->rd_type = style;
4665 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4667 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4668 redir_table[style].descrip);
4670 redir->rd_dup = dup_num;
4671 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4672 /* Erik had a check here that the file descriptor in question
4673 * is legit; I postpone that to "run time"
4674 * A "-" representation of "close me" shows up as a -3 here */
4675 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4676 redir->rd_fd, redir->rd_dup);
4678 /* Set ctx->pending_redirect, so we know what to do at the
4679 * end of the next parsed word. */
4680 ctx->pending_redirect = redir;
4685 /* If a redirect is immediately preceded by a number, that number is
4686 * supposed to tell which file descriptor to redirect. This routine
4687 * looks for such preceding numbers. In an ideal world this routine
4688 * needs to handle all the following classes of redirects...
4689 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4690 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4691 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4692 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4694 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4696 * ... If n is quoted, the number shall not be recognized as part of
4697 * the redirection expression. For example:
4699 * writes the character 2 into file a"
4700 * We are getting it right by setting ->o_quoted on any \<char>
4702 * A -1 return means no valid number was found,
4703 * the caller should use the appropriate default for this redirection.
4705 static int redirect_opt_num(o_string *o)
4709 if (o->data == NULL)
4711 num = bb_strtou(o->data, NULL, 10);
4712 if (errno || num < 0)
4714 o_reset_to_empty_unquoted(o);
4719 #define fetch_till_str(as_string, input, word, skip_tabs) \
4720 fetch_till_str(input, word, skip_tabs)
4722 static char *fetch_till_str(o_string *as_string,
4723 struct in_str *input,
4727 o_string heredoc = NULL_O_STRING;
4733 ch = i_getch(input);
4734 nommu_addchr(as_string, ch);
4736 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4737 heredoc.data[past_EOL] = '\0';
4738 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4739 return heredoc.data;
4742 o_addchr(&heredoc, ch);
4743 past_EOL = heredoc.length;
4746 ch = i_getch(input);
4747 nommu_addchr(as_string, ch);
4748 } while (skip_tabs && ch == '\t');
4749 } while (ch == '\n');
4752 o_free_unsafe(&heredoc);
4755 o_addchr(&heredoc, ch);
4756 nommu_addchr(as_string, ch);
4760 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4761 * and load them all. There should be exactly heredoc_cnt of them.
4763 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4765 struct pipe *pi = ctx->list_head;
4767 while (pi && heredoc_cnt) {
4769 struct command *cmd = pi->cmds;
4771 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4773 cmd->argv ? cmd->argv[0] : "NONE");
4774 for (i = 0; i < pi->num_cmds; i++) {
4775 struct redir_struct *redir = cmd->redirects;
4777 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4778 i, cmd->argv ? cmd->argv[0] : "NONE");
4780 if (redir->rd_type == REDIRECT_HEREDOC) {
4783 redir->rd_type = REDIRECT_HEREDOC2;
4784 /* redir->dup is (ab)used to indicate <<- */
4785 p = fetch_till_str(&ctx->as_string, input,
4786 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4788 syntax_error("unexpected EOF in here document");
4791 free(redir->rd_filename);
4792 redir->rd_filename = p;
4795 redir = redir->next;
4802 /* Should be 0. If it isn't, it's a parse error */
4804 bb_error_msg_and_die("heredoc BUG 2");
4810 #if ENABLE_HUSH_TICK
4811 static FILE *generate_stream_from_string(const char *s)
4814 int pid, channel[2];
4820 pid = BB_MMU ? fork() : vfork();
4822 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4824 if (pid == 0) { /* child */
4825 disable_restore_tty_pgrp_on_exit();
4826 /* Process substitution is not considered to be usual
4827 * 'command execution'.
4828 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4835 close(channel[0]); /* NB: close _first_, then move fd! */
4836 xmove_fd(channel[1], 1);
4837 /* Prevent it from trying to handle ctrl-z etc */
4838 IF_HUSH_JOB(G.run_list_level = 1;)
4840 reset_traps_to_defaults();
4841 parse_and_run_string(s);
4842 _exit(G.last_exitcode);
4844 /* We re-execute after vfork on NOMMU. This makes this script safe:
4845 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4846 * huge=`cat BIG` # was blocking here forever
4849 re_execute_shell(&to_free,
4857 enable_restore_tty_pgrp_on_exit();
4862 pf = fdopen(channel[0], "r");
4866 /* Return code is exit status of the process that is run. */
4867 static int process_command_subs(o_string *dest, const char *s)
4870 struct in_str pipe_str;
4873 pf = generate_stream_from_string(s);
4876 close_on_exec_on(fileno(pf));
4878 /* Now send results of command back into original context */
4879 setup_file_in_str(&pipe_str, pf);
4881 while ((ch = i_getch(&pipe_str)) != EOF) {
4887 o_addchr(dest, '\n');
4890 o_addQchr(dest, ch);
4893 debug_printf("done reading from pipe, pclose()ing\n");
4894 /* Note: we got EOF, and we just close the read end of the pipe.
4895 * We do not wait for the `cmd` child to terminate. bash and ash do.
4897 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4898 * `false`; echo $? - bash outputs "1"
4901 debug_printf("closed FILE from child. return 0\n");
4906 static int parse_group(o_string *dest, struct parse_context *ctx,
4907 struct in_str *input, int ch)
4909 /* dest contains characters seen prior to ( or {.
4910 * Typically it's empty, but for function defs,
4911 * it contains function name (without '()'). */
4912 struct pipe *pipe_list;
4914 struct command *command = ctx->command;
4916 debug_printf_parse("parse_group entered\n");
4917 #if ENABLE_HUSH_FUNCTIONS
4918 if (ch == '(' && !dest->o_quoted) {
4920 if (done_word(dest, ctx))
4923 goto skip; /* (... */
4924 if (command->argv[1]) { /* word word ... (... */
4925 syntax_error_unexpected_ch('(');
4928 /* it is "word(..." or "word (..." */
4930 ch = i_getch(input);
4931 while (ch == ' ' || ch == '\t');
4933 syntax_error_unexpected_ch(ch);
4936 nommu_addchr(&ctx->as_string, ch);
4938 ch = i_getch(input);
4939 while (ch == ' ' || ch == '\t' || ch == '\n');
4941 syntax_error_unexpected_ch(ch);
4944 nommu_addchr(&ctx->as_string, ch);
4945 command->grp_type = GRP_FUNCTION;
4949 if (command->argv /* word [word]{... */
4950 || dest->length /* word{... */
4951 || dest->o_quoted /* ""{... */
4954 debug_printf_parse("parse_group return 1: "
4955 "syntax error, groups and arglists don't mix\n");
4959 #if ENABLE_HUSH_FUNCTIONS
4965 command->grp_type = GRP_SUBSHELL;
4967 /* bash does not allow "{echo...", requires whitespace */
4968 ch = i_getch(input);
4969 if (ch != ' ' && ch != '\t' && ch != '\n') {
4970 syntax_error_unexpected_ch(ch);
4973 nommu_addchr(&ctx->as_string, ch);
4978 char *as_string = NULL;
4980 pipe_list = parse_stream(&as_string, input, endch);
4983 o_addstr(&ctx->as_string, as_string);
4985 /* empty ()/{} or parse error? */
4986 if (!pipe_list || pipe_list == ERR_PTR) {
4987 /* parse_stream already emitted error msg */
4991 debug_printf_parse("parse_group return 1: "
4992 "parse_stream returned %p\n", pipe_list);
4995 command->group = pipe_list;
4997 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4998 command->group_as_string = as_string;
4999 debug_printf_parse("end of group, remembering as:'%s'\n",
5000 command->group_as_string);
5003 debug_printf_parse("parse_group return 0\n");
5005 /* command remains "open", available for possible redirects */
5008 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5009 /* Subroutines for copying $(...) and `...` things */
5010 static void add_till_backquote(o_string *dest, struct in_str *input);
5012 static void add_till_single_quote(o_string *dest, struct in_str *input)
5015 int ch = i_getch(input);
5017 syntax_error_unterm_ch('\'');
5018 /*xfunc_die(); - redundant */
5025 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5026 static void add_till_double_quote(o_string *dest, struct in_str *input)
5029 int ch = i_getch(input);
5031 syntax_error_unterm_ch('"');
5032 /*xfunc_die(); - redundant */
5036 if (ch == '\\') { /* \x. Copy both chars. */
5038 ch = i_getch(input);
5042 add_till_backquote(dest, input);
5046 //if (ch == '$') ...
5049 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5051 * "Within the backquoted style of command substitution, backslash
5052 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5053 * The search for the matching backquote shall be satisfied by the first
5054 * backquote found without a preceding backslash; during this search,
5055 * if a non-escaped backquote is encountered within a shell comment,
5056 * a here-document, an embedded command substitution of the $(command)
5057 * form, or a quoted string, undefined results occur. A single-quoted
5058 * or double-quoted string that begins, but does not end, within the
5059 * "`...`" sequence produces undefined results."
5061 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5063 static void add_till_backquote(o_string *dest, struct in_str *input)
5066 int ch = i_getch(input);
5068 syntax_error_unterm_ch('`');
5069 /*xfunc_die(); - redundant */
5074 /* \x. Copy both chars unless it is \` */
5075 int ch2 = i_getch(input);
5077 syntax_error_unterm_ch('`');
5078 /*xfunc_die(); - redundant */
5080 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5087 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5088 * quoting and nested ()s.
5089 * "With the $(command) style of command substitution, all characters
5090 * following the open parenthesis to the matching closing parenthesis
5091 * constitute the command. Any valid shell script can be used for command,
5092 * except a script consisting solely of redirections which produces
5093 * unspecified results."
5095 * echo $(echo '(TEST)' BEST) (TEST) BEST
5096 * echo $(echo 'TEST)' BEST) TEST) BEST
5097 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5099 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5103 int ch = i_getch(input);
5105 syntax_error_unterm_ch(')');
5106 /*xfunc_die(); - redundant */
5114 if (i_peek(input) == ')') {
5122 add_till_single_quote(dest, input);
5127 add_till_double_quote(dest, input);
5132 /* \x. Copy verbatim. Important for \(, \) */
5133 ch = i_getch(input);
5135 syntax_error_unterm_ch(')');
5136 /*xfunc_die(); - redundant */
5143 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5145 /* Return code: 0 for OK, 1 for syntax error */
5147 #define handle_dollar(as_string, dest, input) \
5148 handle_dollar(dest, input)
5150 static int handle_dollar(o_string *as_string,
5152 struct in_str *input)
5155 int ch = i_peek(input); /* first character after the $ */
5156 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5158 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5160 ch = i_getch(input);
5161 nommu_addchr(as_string, ch);
5163 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5165 debug_printf_parse(": '%c'\n", ch);
5166 o_addchr(dest, ch | quote_mask);
5169 if (!isalnum(ch) && ch != '_')
5171 ch = i_getch(input);
5172 nommu_addchr(as_string, ch);
5174 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5175 } else if (isdigit(ch)) {
5177 ch = i_getch(input);
5178 nommu_addchr(as_string, ch);
5179 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5180 debug_printf_parse(": '%c'\n", ch);
5181 o_addchr(dest, ch | quote_mask);
5182 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5183 } else switch (ch) {
5185 case '!': /* last bg pid */
5186 case '?': /* last exit code */
5187 case '#': /* number of args */
5188 case '*': /* args */
5189 case '@': /* args */
5190 goto make_one_char_var;
5192 bool first_char, all_digits;
5194 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5195 ch = i_getch(input);
5196 nommu_addchr(as_string, ch);
5197 /* TODO: maybe someone will try to escape the '}' */
5202 ch = i_getch(input);
5203 nommu_addchr(as_string, ch);
5210 /* ${#var}: length of var contents */
5220 && ( (all_digits && !isdigit(ch))
5221 || (!all_digits && !isalnum(ch) && ch != '_')
5224 /* handle parameter expansions
5225 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5230 case ':': /* null modifier */
5231 if (expansion == 0) {
5232 debug_printf_parse(": null modifier\n");
5237 case '#': /* remove prefix */
5238 case '%': /* remove suffix */
5239 if (expansion == 0) {
5240 debug_printf_parse(": remove suffix/prefix\n");
5245 case '-': /* default value */
5246 case '=': /* assign default */
5247 case '+': /* alternative */
5248 case '?': /* error indicate */
5249 debug_printf_parse(": parameter expansion\n");
5254 syntax_error_unterm_str("${name}");
5255 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5260 debug_printf_parse(": '%c'\n", ch);
5261 o_addchr(dest, ch | quote_mask);
5265 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5268 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5273 ch = i_getch(input);
5274 nommu_addchr(as_string, ch);
5275 # if ENABLE_SH_MATH_SUPPORT
5276 if (i_peek(input) == '(') {
5277 ch = i_getch(input);
5278 nommu_addchr(as_string, ch);
5279 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5280 o_addchr(dest, /*quote_mask |*/ '+');
5284 add_till_closing_paren(dest, input, true);
5287 o_addstr(as_string, dest->data + pos);
5288 o_addchr(as_string, ')');
5289 o_addchr(as_string, ')');
5292 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5296 # if ENABLE_HUSH_TICK
5297 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5298 o_addchr(dest, quote_mask | '`');
5302 add_till_closing_paren(dest, input, false);
5305 o_addstr(as_string, dest->data + pos);
5306 o_addchr(as_string, '`');
5309 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5315 ch = i_getch(input);
5316 nommu_addchr(as_string, ch);
5318 if (isalnum(ch)) { /* it's $_name or $_123 */
5324 /* $_ Shell or shell script name; or last cmd name */
5325 /* $- Option flags set by set builtin or shell options (-i etc) */
5327 o_addQchr(dest, '$');
5329 debug_printf_parse("handle_dollar return 0\n");
5334 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5335 parse_stream_dquoted(dest, input, dquote_end)
5337 static int parse_stream_dquoted(o_string *as_string,
5339 struct in_str *input,
5346 ch = i_getch(input);
5348 nommu_addchr(as_string, ch);
5349 if (ch == dquote_end) { /* may be only '"' or EOF */
5350 if (dest->o_assignment == NOT_ASSIGNMENT)
5351 dest->o_escape ^= 1;
5352 debug_printf_parse("parse_stream_dquoted return 0\n");
5355 /* note: can't move it above ch == dquote_end check! */
5357 syntax_error_unterm_ch('"');
5358 /*xfunc_die(); - redundant */
5362 next = i_peek(input);
5364 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5365 ch, ch, dest->o_escape);
5368 syntax_error("\\<eof>");
5372 * "The backslash retains its special meaning [in "..."]
5373 * only when followed by one of the following characters:
5374 * $, `, ", \, or <newline>. A double quote may be quoted
5375 * within double quotes by preceding it with a backslash.
5377 if (strchr("$`\"\\\n", next) != NULL) {
5378 ch = i_getch(input);
5380 o_addqchr(dest, ch);
5381 nommu_addchr(as_string, ch);
5384 o_addqchr(dest, '\\');
5385 nommu_addchr(as_string, '\\');
5390 if (handle_dollar(as_string, dest, input) != 0) {
5391 debug_printf_parse("parse_stream_dquoted return 1: "
5392 "handle_dollar returned non-0\n");
5397 #if ENABLE_HUSH_TICK
5399 //int pos = dest->length;
5400 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5401 o_addchr(dest, 0x80 | '`');
5402 add_till_backquote(dest, input);
5403 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5404 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5408 o_addQchr(dest, ch);
5410 && (dest->o_assignment == MAYBE_ASSIGNMENT
5411 || dest->o_assignment == WORD_IS_KEYWORD)
5412 && is_well_formed_var_name(dest->data, '=')
5414 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5420 * Scan input until EOF or end_trigger char.
5421 * Return a list of pipes to execute, or NULL on EOF
5422 * or if end_trigger character is met.
5423 * On syntax error, exit is shell is not interactive,
5424 * reset parsing machinery and start parsing anew,
5425 * or return ERR_PTR.
5427 static struct pipe *parse_stream(char **pstring,
5428 struct in_str *input,
5431 struct parse_context ctx;
5432 o_string dest = NULL_O_STRING;
5436 /* Double-quote state is handled in the state variable is_in_dquote.
5437 * A single-quote triggers a bypass of the main loop until its mate is
5438 * found. When recursing, quote state is passed in via dest->o_escape.
5440 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5441 end_trigger ? : 'X');
5444 G.ifs = get_local_var_value("IFS");
5449 #if ENABLE_HUSH_INTERACTIVE
5450 input->promptmode = 0; /* PS1 */
5452 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5453 initialize_context(&ctx);
5458 const char *is_special;
5462 redir_type redir_style;
5465 /* dest.o_quoted = 1; - already is (see below) */
5466 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5469 /* We reached closing '"' */
5472 ch = i_getch(input);
5473 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5474 ch, ch, dest.o_escape);
5479 syntax_error_unterm_str("here document");
5482 /* end_trigger == '}' case errors out earlier,
5483 * checking only ')' */
5484 if (end_trigger == ')') {
5485 syntax_error_unterm_ch('('); /* exits */
5486 /* goto parse_error; */
5489 if (done_word(&dest, &ctx)) {
5493 done_pipe(&ctx, PIPE_SEQ);
5495 /* If we got nothing... */
5496 /* (this makes bare "&" cmd a no-op.
5497 * bash says: "syntax error near unexpected token '&'") */
5498 if (pi->num_cmds == 0
5499 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5505 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5507 *pstring = ctx.as_string.data;
5509 o_free_unsafe(&ctx.as_string);
5512 debug_printf_parse("parse_stream return %p\n", pi);
5515 nommu_addchr(&ctx.as_string, ch);
5516 is_ifs = strchr(G.ifs, ch);
5517 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5518 "\\$\"" IF_HUSH_TICK("`") /* always special */
5521 if (!is_special && !is_ifs) { /* ordinary char */
5523 o_addQchr(&dest, ch);
5524 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5525 || dest.o_assignment == WORD_IS_KEYWORD)
5527 && is_well_formed_var_name(dest.data, '=')
5529 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5535 if (done_word(&dest, &ctx)) {
5539 #if ENABLE_HUSH_CASE
5540 /* "case ... in <newline> word) ..." -
5541 * newlines are ignored (but ';' wouldn't be) */
5542 if (ctx.command->argv == NULL
5543 && ctx.ctx_res_w == RES_MATCH
5548 /* Treat newline as a command separator. */
5549 done_pipe(&ctx, PIPE_SEQ);
5550 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5552 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5557 dest.o_assignment = MAYBE_ASSIGNMENT;
5559 /* note: if (is_ifs) continue;
5560 * will still trigger for us */
5564 /* "cmd}" or "cmd }..." without semicolon or &:
5565 * } is an ordinary char in this case, even inside { cmd; }
5566 * Pathological example: { ""}; } should exec "}" cmd
5569 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5570 || dest.length != 0 /* word} */
5571 || dest.o_quoted /* ""} */
5575 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5576 goto skip_end_trigger;
5577 /* else: } does terminate a group */
5580 if (end_trigger && end_trigger == ch
5581 && (heredoc_cnt == 0 || end_trigger != ';')
5584 /* This is technically valid:
5585 * { cat <<HERE; }; echo Ok
5589 * but we don't support this.
5590 * We require heredoc to be in enclosing {}/(),
5593 syntax_error_unterm_str("here document");
5596 if (done_word(&dest, &ctx)) {
5599 done_pipe(&ctx, PIPE_SEQ);
5600 dest.o_assignment = MAYBE_ASSIGNMENT;
5601 /* Do we sit outside of any if's, loops or case's? */
5603 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5607 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5609 *pstring = ctx.as_string.data;
5611 o_free_unsafe(&ctx.as_string);
5614 debug_printf_parse("parse_stream return %p: "
5615 "end_trigger char found\n",
5617 return ctx.list_head;
5626 next = i_peek(input);
5629 /* Catch <, > before deciding whether this word is
5630 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5633 redir_fd = redirect_opt_num(&dest);
5634 if (done_word(&dest, &ctx)) {
5637 redir_style = REDIRECT_OVERWRITE;
5639 redir_style = REDIRECT_APPEND;
5640 ch = i_getch(input);
5641 nommu_addchr(&ctx.as_string, ch);
5644 else if (next == '(') {
5645 syntax_error(">(process) not supported");
5649 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5651 continue; /* back to top of while (1) */
5653 redir_fd = redirect_opt_num(&dest);
5654 if (done_word(&dest, &ctx)) {
5657 redir_style = REDIRECT_INPUT;
5659 redir_style = REDIRECT_HEREDOC;
5661 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5662 ch = i_getch(input);
5663 nommu_addchr(&ctx.as_string, ch);
5664 } else if (next == '>') {
5665 redir_style = REDIRECT_IO;
5666 ch = i_getch(input);
5667 nommu_addchr(&ctx.as_string, ch);
5670 else if (next == '(') {
5671 syntax_error("<(process) not supported");
5675 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5677 continue; /* back to top of while (1) */
5680 if (dest.o_assignment == MAYBE_ASSIGNMENT
5681 /* check that we are not in word in "a=1 2>word b=1": */
5682 && !ctx.pending_redirect
5684 /* ch is a special char and thus this word
5685 * cannot be an assignment */
5686 dest.o_assignment = NOT_ASSIGNMENT;
5691 if (dest.length == 0) {
5694 if (ch == EOF || ch == '\n')
5697 /* note: we do not add it to &ctx.as_string */
5699 nommu_addchr(&ctx.as_string, '\n');
5701 o_addQchr(&dest, ch);
5706 syntax_error("\\<eof>");
5709 ch = i_getch(input);
5711 o_addchr(&dest, '\\');
5712 nommu_addchr(&ctx.as_string, '\\');
5713 o_addchr(&dest, ch);
5714 nommu_addchr(&ctx.as_string, ch);
5715 /* Example: echo Hello \2>file
5716 * we need to know that word 2 is quoted */
5721 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5722 debug_printf_parse("parse_stream parse error: "
5723 "handle_dollar returned non-0\n");
5730 ch = i_getch(input);
5732 syntax_error_unterm_ch('\'');
5733 /*xfunc_die(); - redundant */
5735 nommu_addchr(&ctx.as_string, ch);
5738 if (dest.o_assignment == NOT_ASSIGNMENT)
5739 o_addqchr(&dest, ch);
5741 o_addchr(&dest, ch);
5746 is_in_dquote ^= 1; /* invert */
5747 if (dest.o_assignment == NOT_ASSIGNMENT)
5750 #if ENABLE_HUSH_TICK
5755 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5756 o_addchr(&dest, '`');
5760 add_till_backquote(&dest, input);
5762 o_addstr(&ctx.as_string, dest.data + pos);
5763 o_addchr(&ctx.as_string, '`');
5765 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5766 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5771 #if ENABLE_HUSH_CASE
5774 if (done_word(&dest, &ctx)) {
5777 done_pipe(&ctx, PIPE_SEQ);
5778 #if ENABLE_HUSH_CASE
5779 /* Eat multiple semicolons, detect
5780 * whether it means something special */
5785 ch = i_getch(input);
5786 nommu_addchr(&ctx.as_string, ch);
5787 if (ctx.ctx_res_w == RES_CASEI) {
5788 ctx.ctx_dsemicolon = 1;
5789 ctx.ctx_res_w = RES_MATCH;
5795 /* We just finished a cmd. New one may start
5796 * with an assignment */
5797 dest.o_assignment = MAYBE_ASSIGNMENT;
5800 if (done_word(&dest, &ctx)) {
5804 ch = i_getch(input);
5805 nommu_addchr(&ctx.as_string, ch);
5806 done_pipe(&ctx, PIPE_AND);
5808 done_pipe(&ctx, PIPE_BG);
5812 if (done_word(&dest, &ctx)) {
5815 #if ENABLE_HUSH_CASE
5816 if (ctx.ctx_res_w == RES_MATCH)
5817 break; /* we are in case's "word | word)" */
5819 if (next == '|') { /* || */
5820 ch = i_getch(input);
5821 nommu_addchr(&ctx.as_string, ch);
5822 done_pipe(&ctx, PIPE_OR);
5824 /* we could pick up a file descriptor choice here
5825 * with redirect_opt_num(), but bash doesn't do it.
5826 * "echo foo 2| cat" yields "foo 2". */
5831 #if ENABLE_HUSH_CASE
5832 /* "case... in [(]word)..." - skip '(' */
5833 if (ctx.ctx_res_w == RES_MATCH
5834 && ctx.command->argv == NULL /* not (word|(... */
5835 && dest.length == 0 /* not word(... */
5836 && dest.o_quoted == 0 /* not ""(... */
5842 if (parse_group(&dest, &ctx, input, ch) != 0) {
5847 #if ENABLE_HUSH_CASE
5848 if (ctx.ctx_res_w == RES_MATCH)
5852 /* proper use of this character is caught by end_trigger:
5853 * if we see {, we call parse_group(..., end_trigger='}')
5854 * and it will match } earlier (not here). */
5855 syntax_error_unexpected_ch(ch);
5859 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5865 struct parse_context *pctx;
5866 IF_HAS_KEYWORDS(struct parse_context *p2;)
5868 /* Clean up allocated tree.
5869 * Samples for finding leaks on syntax error recovery path.
5870 * Run them from interactive shell, watch pmap `pidof hush`.
5871 * while if false; then false; fi do break; done
5873 * while if false; then false; fi; do break; fi
5874 * Samples to catch leaks at execution:
5875 * while if (true | {true;}); then echo ok; fi; do break; done
5876 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5880 /* Update pipe/command counts,
5881 * otherwise freeing may miss some */
5882 done_pipe(pctx, PIPE_SEQ);
5883 debug_printf_clean("freeing list %p from ctx %p\n",
5884 pctx->list_head, pctx);
5885 debug_print_tree(pctx->list_head, 0);
5886 free_pipe_list(pctx->list_head);
5887 debug_printf_clean("freed list %p\n", pctx->list_head);
5889 o_free_unsafe(&pctx->as_string);
5891 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5895 IF_HAS_KEYWORDS(pctx = p2;)
5896 } while (HAS_KEYWORDS && pctx);
5897 /* Free text, clear all dest fields */
5899 /* If we are not in top-level parse, we return,
5900 * our caller will propagate error.
5902 if (end_trigger != ';') {
5910 /* Discard cached input, force prompt */
5912 IF_HUSH_INTERACTIVE(input->promptme = 1;)
5917 /* Executing from string: eval, sh -c '...'
5918 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5919 * end_trigger controls how often we stop parsing
5920 * NUL: parse all, execute, return
5921 * ';': parse till ';' or newline, execute, repeat till EOF
5923 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5926 struct pipe *pipe_list;
5928 pipe_list = parse_stream(NULL, inp, end_trigger);
5929 if (!pipe_list) /* EOF */
5931 debug_print_tree(pipe_list, 0);
5932 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5933 run_and_free_list(pipe_list);
5937 static void parse_and_run_string(const char *s)
5939 struct in_str input;
5940 setup_string_in_str(&input, s);
5941 parse_and_run_stream(&input, '\0');
5944 static void parse_and_run_file(FILE *f)
5946 struct in_str input;
5947 setup_file_in_str(&input, f);
5948 parse_and_run_stream(&input, ';');
5951 /* Called a few times only (or even once if "sh -c") */
5952 static void block_signals(int second_time)
5957 mask = (1 << SIGQUIT);
5958 if (G_interactive_fd) {
5959 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
5960 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
5961 mask |= SPECIAL_JOB_SIGS;
5963 G.non_DFL_mask = mask;
5966 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5970 sigaddset(&G.blocked_set, sig);
5974 sigdelset(&G.blocked_set, SIGCHLD);
5976 sigprocmask(SIG_SETMASK, &G.blocked_set,
5977 second_time ? NULL : &G.inherited_set);
5978 /* POSIX allows shell to re-enable SIGCHLD
5979 * even if it was SIG_IGN on entry */
5980 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5982 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5987 static void maybe_set_to_sigexit(int sig)
5989 void (*handler)(int);
5990 /* non_DFL_mask'ed signals are, well, masked,
5991 * no need to set handler for them.
5993 if (!((G.non_DFL_mask >> sig) & 1)) {
5994 handler = signal(sig, sigexit);
5995 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5996 signal(sig, handler);
5999 /* Set handlers to restore tty pgrp and exit */
6000 static void set_fatal_handlers(void)
6002 /* We _must_ restore tty pgrp on fatal signals */
6004 maybe_set_to_sigexit(SIGILL );
6005 maybe_set_to_sigexit(SIGFPE );
6006 maybe_set_to_sigexit(SIGBUS );
6007 maybe_set_to_sigexit(SIGSEGV);
6008 maybe_set_to_sigexit(SIGTRAP);
6009 } /* else: hush is perfect. what SEGV? */
6010 maybe_set_to_sigexit(SIGABRT);
6011 /* bash 3.2 seems to handle these just like 'fatal' ones */
6012 maybe_set_to_sigexit(SIGPIPE);
6013 maybe_set_to_sigexit(SIGALRM);
6014 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6015 * if we aren't interactive... but in this case
6016 * we never want to restore pgrp on exit, and this fn is not called */
6017 /*maybe_set_to_sigexit(SIGHUP );*/
6018 /*maybe_set_to_sigexit(SIGTERM);*/
6019 /*maybe_set_to_sigexit(SIGINT );*/
6023 static int set_mode(const char cstate, const char mode)
6025 int state = (cstate == '-' ? 1 : 0);
6027 case 'n': G.fake_mode = state; break;
6028 case 'x': /*G.debug_mode = state;*/ break;
6029 default: return EXIT_FAILURE;
6031 return EXIT_SUCCESS;
6034 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6035 int hush_main(int argc, char **argv)
6037 static const struct variable const_shell_ver = {
6039 .varstr = (char*)hush_version_str,
6040 .max_len = 1, /* 0 can provoke free(name) */
6044 int signal_mask_is_inited = 0;
6047 struct variable *cur_var;
6050 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6051 G.last_exitcode = EXIT_SUCCESS;
6053 G.argv0_for_re_execing = argv[0];
6055 /* Deal with HUSH_VERSION */
6056 G.shell_ver = const_shell_ver; /* copying struct here */
6057 G.top_var = &G.shell_ver;
6058 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6059 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6060 /* Initialize our shell local variables with the values
6061 * currently living in the environment */
6062 cur_var = G.top_var;
6065 char *value = strchr(*e, '=');
6066 if (value) { /* paranoia */
6067 cur_var->next = xzalloc(sizeof(*cur_var));
6068 cur_var = cur_var->next;
6069 cur_var->varstr = *e;
6070 cur_var->max_len = strlen(*e);
6071 cur_var->flg_export = 1;
6075 debug_printf_env("putenv '%s'\n", hush_version_str);
6076 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6077 #if ENABLE_FEATURE_EDITING
6078 G.line_input_state = new_line_input_t(FOR_SHELL);
6080 G.global_argc = argc;
6081 G.global_argv = argv;
6082 /* Initialize some more globals to non-zero values */
6084 cmdedit_update_prompt();
6086 if (setjmp(die_jmp)) {
6087 /* xfunc has failed! die die die */
6088 /* no EXIT traps, this is an escape hatch! */
6090 hush_exit(xfunc_error_retval);
6093 /* Shell is non-interactive at first. We need to call
6094 * block_signals(0) if we are going to execute "sh <script>",
6095 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6096 * If we later decide that we are interactive, we run block_signals(0)
6097 * (or re-run block_signals(1) if we ran block_signals(0) before)
6098 * in order to intercept (more) signals.
6102 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6104 opt = getopt(argc, argv, "c:xins"
6107 # if ENABLE_HUSH_FUNCTIONS
6117 G.root_pid = getpid();
6118 G.global_argv = argv + optind;
6119 if (!argv[optind]) {
6120 /* -c 'script' (no params): prevent empty $0 */
6121 *--G.global_argv = argv[0];
6123 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
6124 G.global_argc = argc - optind;
6125 block_signals(0); /* 0: called 1st time */
6126 parse_and_run_string(optarg);
6129 /* Well, we cannot just declare interactiveness,
6130 * we have to have some stuff (ctty, etc) */
6131 /* G_interactive_fd++; */
6134 /* "-s" means "read from stdin", but this is how we always
6135 * operate, so simply do nothing here. */
6138 case '<': /* "big heredoc" support */
6139 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6142 G.root_pid = bb_strtou(optarg, &optarg, 16);
6144 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6146 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6147 # if ENABLE_HUSH_LOOPS
6149 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6154 set_local_var(xstrdup(optarg), 0, opt == 'R');
6156 # if ENABLE_HUSH_FUNCTIONS
6158 struct function *funcp = new_function(optarg);
6159 /* funcp->name is already set to optarg */
6160 /* funcp->body is set to NULL. It's a special case. */
6161 funcp->body_as_string = argv[optind];
6169 if (!set_mode('-', opt))
6173 fprintf(stderr, "Usage: sh [FILE]...\n"
6174 " or: sh -c command [args]...\n\n");
6180 } /* option parsing loop */
6183 G.root_pid = getpid();
6185 /* If we are login shell... */
6186 if (argv[0] && argv[0][0] == '-') {
6188 debug_printf("sourcing /etc/profile\n");
6189 input = fopen_for_read("/etc/profile");
6190 if (input != NULL) {
6191 close_on_exec_on(fileno(input));
6192 block_signals(0); /* 0: called 1st time */
6193 signal_mask_is_inited = 1;
6194 parse_and_run_file(input);
6197 /* bash: after sourcing /etc/profile,
6198 * tries to source (in the given order):
6199 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6200 * stopping of first found. --noprofile turns this off.
6201 * bash also sources ~/.bash_logout on exit.
6202 * If called as sh, skips .bash_XXX files.
6209 * "bash <script>" (which is never interactive (unless -i?))
6210 * sources $BASH_ENV here (without scanning $PATH).
6211 * If called as sh, does the same but with $ENV.
6213 debug_printf("running script '%s'\n", argv[optind]);
6214 G.global_argv = argv + optind;
6215 G.global_argc = argc - optind;
6216 input = xfopen_for_read(argv[optind]);
6217 close_on_exec_on(fileno(input));
6218 if (!signal_mask_is_inited)
6219 block_signals(0); /* 0: called 1st time */
6220 parse_and_run_file(input);
6221 #if ENABLE_FEATURE_CLEAN_UP
6227 /* Up to here, shell was non-interactive. Now it may become one.
6228 * NB: don't forget to (re)run block_signals(0/1) as needed.
6231 /* A shell is interactive if the '-i' flag was given, or if all of
6232 * the following conditions are met:
6234 * no arguments remaining or the -s flag given
6235 * standard input is a terminal
6236 * standard output is a terminal
6237 * Refer to Posix.2, the description of the 'sh' utility.
6240 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6241 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6242 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6243 if (G_saved_tty_pgrp < 0)
6244 G_saved_tty_pgrp = 0;
6246 /* try to dup stdin to high fd#, >= 255 */
6247 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6248 if (G_interactive_fd < 0) {
6249 /* try to dup to any fd */
6250 G_interactive_fd = dup(STDIN_FILENO);
6251 if (G_interactive_fd < 0) {
6253 G_interactive_fd = 0;
6254 G_saved_tty_pgrp = 0;
6257 // TODO: track & disallow any attempts of user
6258 // to (inadvertently) close/redirect G_interactive_fd
6260 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6261 if (G_interactive_fd) {
6262 close_on_exec_on(G_interactive_fd);
6264 if (G_saved_tty_pgrp) {
6265 /* If we were run as 'hush &', sleep until we are
6266 * in the foreground (tty pgrp == our pgrp).
6267 * If we get started under a job aware app (like bash),
6268 * make sure we are now in charge so we don't fight over
6269 * who gets the foreground */
6271 pid_t shell_pgrp = getpgrp();
6272 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6273 if (G_saved_tty_pgrp == shell_pgrp)
6275 /* send TTIN to ourself (should stop us) */
6276 kill(- shell_pgrp, SIGTTIN);
6280 /* Block some signals */
6281 block_signals(signal_mask_is_inited);
6283 if (G_saved_tty_pgrp) {
6284 /* Set other signals to restore saved_tty_pgrp */
6285 set_fatal_handlers();
6286 /* Put ourselves in our own process group
6287 * (bash, too, does this only if ctty is available) */
6288 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6289 /* Grab control of the terminal */
6290 tcsetpgrp(G_interactive_fd, getpid());
6292 /* -1 is special - makes xfuncs longjmp, not exit
6293 * (we reset die_sleep = 0 whereever we [v]fork) */
6294 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6295 } else if (!signal_mask_is_inited) {
6296 block_signals(0); /* 0: called 1st time */
6297 } /* else: block_signals(0) was done before */
6298 #elif ENABLE_HUSH_INTERACTIVE
6299 /* No job control compiled in, only prompt/line editing */
6300 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6301 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6302 if (G_interactive_fd < 0) {
6303 /* try to dup to any fd */
6304 G_interactive_fd = dup(STDIN_FILENO);
6305 if (G_interactive_fd < 0)
6307 G_interactive_fd = 0;
6310 if (G_interactive_fd) {
6311 close_on_exec_on(G_interactive_fd);
6312 block_signals(signal_mask_is_inited);
6313 } else if (!signal_mask_is_inited) {
6317 /* We have interactiveness code disabled */
6318 if (!signal_mask_is_inited) {
6323 * if interactive but not a login shell, sources ~/.bashrc
6324 * (--norc turns this off, --rcfile <file> overrides)
6327 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6328 printf("\n\n%s hush - the humble shell\n", bb_banner);
6329 if (ENABLE_HUSH_HELP)
6330 puts("Enter 'help' for a list of built-in commands.");
6334 parse_and_run_file(stdin);
6337 #if ENABLE_FEATURE_CLEAN_UP
6338 if (G.cwd != bb_msg_unknown)
6340 cur_var = G.top_var->next;
6342 struct variable *tmp = cur_var;
6343 if (!cur_var->max_len)
6344 free(cur_var->varstr);
6345 cur_var = cur_var->next;
6349 hush_exit(G.last_exitcode);
6354 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6355 int lash_main(int argc, char **argv)
6357 //bb_error_msg("lash is deprecated, please use hush instead");
6358 return hush_main(argc, argv);
6366 static int builtin_true(char **argv UNUSED_PARAM)
6371 static int builtin_test(char **argv)
6378 return test_main(argc, argv - argc);
6381 static int builtin_echo(char **argv)
6388 return echo_main(argc, argv - argc);
6391 static int builtin_eval(char **argv)
6393 int rcode = EXIT_SUCCESS;
6396 char *str = expand_strvec_to_string(argv);
6398 * eval "echo Hi; done" ("done" is syntax error):
6399 * "echo Hi" will not execute too.
6401 parse_and_run_string(str);
6403 rcode = G.last_exitcode;
6408 static int builtin_cd(char **argv)
6410 const char *newdir = argv[1];
6411 if (newdir == NULL) {
6412 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6413 * bash says "bash: cd: HOME not set" and does nothing
6416 newdir = get_local_var_value("HOME") ? : "/";
6418 if (chdir(newdir)) {
6419 /* Mimic bash message exactly */
6420 bb_perror_msg("cd: %s", newdir);
6421 return EXIT_FAILURE;
6424 return EXIT_SUCCESS;
6427 static int builtin_exec(char **argv)
6429 if (*++argv == NULL)
6430 return EXIT_SUCCESS; /* bash does this */
6435 /* TODO: if exec fails, bash does NOT exit! We do... */
6436 pseudo_exec_argv(&dummy, argv, 0, NULL);
6441 static int builtin_exit(char **argv)
6443 debug_printf_exec("%s()\n", __func__);
6445 /* interactive bash:
6446 * # trap "echo EEE" EXIT
6449 * There are stopped jobs.
6450 * (if there are _stopped_ jobs, running ones don't count)
6453 # EEE (then bash exits)
6455 * we can use G.exiting = -1 as indicator "last cmd was exit"
6458 /* note: EXIT trap is run by hush_exit */
6459 if (*++argv == NULL)
6460 hush_exit(G.last_exitcode);
6461 /* mimic bash: exit 123abc == exit 255 + error msg */
6462 xfunc_error_retval = 255;
6463 /* bash: exit -2 == exit 254, no error msg */
6464 hush_exit(xatoi(*argv) & 0xff);
6467 static void print_escaped(const char *s)
6473 p = strchrnul(s, '\'');
6474 /* print 'xxxx', possibly just '' */
6475 printf("'%.*s'", (int)(p - s), s);
6480 /* s points to '; print "'''...'''" */
6482 do putchar('\''); while (*++s == '\'');
6487 static int builtin_export(char **argv)
6489 unsigned opt_unexport;
6491 if (argv[1] == NULL) {
6498 /* ash emits: export VAR='VAL'
6499 * bash: declare -x VAR="VAL"
6500 * we follow ash example */
6501 const char *s = *e++;
6502 const char *p = strchr(s, '=');
6504 if (!p) /* wtf? take next variable */
6507 printf("export %.*s", (int)(p - s) + 1, s);
6508 print_escaped(p + 1);
6512 /*fflush(stdout); - done after each builtin anyway */
6514 return EXIT_SUCCESS;
6517 #if ENABLE_HUSH_EXPORT_N
6518 /* "!": do not abort on errors */
6519 /* "+": stop at 1st non-option */
6520 opt_unexport = getopt32(argv, "!+n");
6521 if (opt_unexport == (unsigned)-1)
6522 return EXIT_FAILURE;
6532 /* So far we do not check that name is valid (TODO?) */
6534 if (strchr(name, '=') == NULL) {
6535 struct variable *var;
6537 var = get_local_var(name);
6539 /* export -n NAME (without =VALUE) */
6541 var->flg_export = 0;
6542 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6544 } /* else: export -n NOT_EXISTING_VAR: no-op */
6547 /* export NAME (without =VALUE) */
6549 var->flg_export = 1;
6550 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6551 putenv(var->varstr);
6554 /* Exporting non-existing variable.
6555 * bash does not put it in environment,
6556 * but remembers that it is exported,
6557 * and does put it in env when it is set later.
6558 * We just set it to "" and export. */
6559 name = xasprintf("%s=", name);
6561 /* (Un)exporting NAME=VALUE */
6562 name = xstrdup(name);
6565 /*export:*/ (opt_unexport ? -1 : 1),
6570 return EXIT_SUCCESS;
6573 static int builtin_trap(char **argv)
6579 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6584 /* No args: print all trapped */
6585 for (i = 0; i < NSIG; ++i) {
6588 print_escaped(G.traps[i]);
6589 printf(" %s\n", get_signame(i));
6592 /*fflush(stdout); - done after each builtin anyway */
6593 return EXIT_SUCCESS;
6597 /* If first arg is a number: reset all specified signals */
6598 sig = bb_strtou(*argv, NULL, 10);
6604 sig = get_signum(*argv++);
6605 if (sig < 0 || sig >= NSIG) {
6607 /* Mimic bash message exactly */
6608 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
6613 G.traps[sig] = xstrdup(new_cmd);
6615 debug_printf("trap: setting SIG%s (%i) to '%s'",
6616 get_signame(sig), sig, G.traps[sig]);
6618 /* There is no signal for 0 (EXIT) */
6623 sigaddset(&G.blocked_set, sig);
6625 /* There was a trap handler, we are removing it
6626 * (if sig has non-DFL handling,
6627 * we don't need to do anything) */
6628 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6630 sigdelset(&G.blocked_set, sig);
6633 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6637 if (!argv[1]) { /* no second arg */
6638 bb_error_msg("trap: invalid arguments");
6639 return EXIT_FAILURE;
6642 /* First arg is "-": reset all specified to default */
6643 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6644 /* Everything else: set arg as signal handler
6645 * (includes "" case, which ignores signal) */
6646 if (argv[0][0] == '-') {
6647 if (argv[0][1] == '\0') { /* "-" */
6648 /* new_cmd remains NULL: "reset these sigs" */
6651 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6654 /* else: "-something", no special meaning */
6659 goto process_sig_list;
6663 /* built-in 'fg' and 'bg' handler */
6664 static int builtin_fg_bg(char **argv)
6669 if (!G_interactive_fd)
6670 return EXIT_FAILURE;
6672 /* If they gave us no args, assume they want the last backgrounded task */
6674 for (pi = G.job_list; pi; pi = pi->next) {
6675 if (pi->jobid == G.last_jobid) {
6679 bb_error_msg("%s: no current job", argv[0]);
6680 return EXIT_FAILURE;
6682 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6683 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6684 return EXIT_FAILURE;
6686 for (pi = G.job_list; pi; pi = pi->next) {
6687 if (pi->jobid == jobnum) {
6691 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6692 return EXIT_FAILURE;
6694 /* TODO: bash prints a string representation
6695 * of job being foregrounded (like "sleep 1 | cat") */
6696 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
6697 /* Put the job into the foreground. */
6698 tcsetpgrp(G_interactive_fd, pi->pgrp);
6701 /* Restart the processes in the job */
6702 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6703 for (i = 0; i < pi->num_cmds; i++) {
6704 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6705 pi->cmds[i].is_stopped = 0;
6707 pi->stopped_cmds = 0;
6709 i = kill(- pi->pgrp, SIGCONT);
6711 if (errno == ESRCH) {
6712 delete_finished_bg_job(pi);
6713 return EXIT_SUCCESS;
6715 bb_perror_msg("kill (SIGCONT)");
6718 if (argv[0][0] == 'f') {
6720 return checkjobs_and_fg_shell(pi);
6722 return EXIT_SUCCESS;
6726 #if ENABLE_HUSH_HELP
6727 static int builtin_help(char **argv UNUSED_PARAM)
6729 const struct built_in_command *x;
6732 "Built-in commands:\n"
6733 "------------------\n");
6734 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6735 printf("%s\t%s\n", x->cmd, x->descr);
6738 return EXIT_SUCCESS;
6743 static int builtin_jobs(char **argv UNUSED_PARAM)
6746 const char *status_string;
6748 for (job = G.job_list; job; job = job->next) {
6749 if (job->alive_cmds == job->stopped_cmds)
6750 status_string = "Stopped";
6752 status_string = "Running";
6754 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6756 return EXIT_SUCCESS;
6761 static int builtin_memleak(char **argv UNUSED_PARAM)
6766 /* Crude attempt to find where "free memory" starts,
6767 * sans fragmentation. */
6769 l = (unsigned long)p;
6772 if (l < (unsigned long)p) l = (unsigned long)p;
6775 if (!G.memleak_value)
6776 G.memleak_value = l;
6778 l -= G.memleak_value;
6785 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6790 static int builtin_pwd(char **argv UNUSED_PARAM)
6793 return EXIT_SUCCESS;
6796 static int builtin_read(char **argv)
6799 const char *name = "REPLY";
6803 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6804 * and _after_ that_ it will complain */
6805 if (!is_well_formed_var_name(name, '\0')) {
6806 /* Mimic bash message */
6807 bb_error_msg("read: '%s': not a valid identifier", name);
6812 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
6814 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
6815 return set_local_var(string, 0, 0);
6818 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6819 * built-in 'set' handler
6821 * set [-abCefhmnuvx] [-o option] [argument...]
6822 * set [+abCefhmnuvx] [+o option] [argument...]
6823 * set -- [argument...]
6826 * Implementations shall support the options in both their hyphen and
6827 * plus-sign forms. These options can also be specified as options to sh.
6829 * Write out all variables and their values: set
6830 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6831 * Turn on the -x and -v options: set -xv
6832 * Unset all positional parameters: set --
6833 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6834 * Set the positional parameters to the expansion of x, even if x expands
6835 * with a leading '-' or '+': set -- $x
6837 * So far, we only support "set -- [argument...]" and some of the short names.
6839 static int builtin_set(char **argv)
6842 char **pp, **g_argv;
6843 char *arg = *++argv;
6847 for (e = G.top_var; e; e = e->next)
6849 return EXIT_SUCCESS;
6853 if (!strcmp(arg, "--")) {
6857 if (arg[0] != '+' && arg[0] != '-')
6859 for (n = 1; arg[n]; ++n)
6860 if (set_mode(arg[0], arg[n]))
6862 } while ((arg = *++argv) != NULL);
6863 /* Now argv[0] is 1st argument */
6866 return EXIT_SUCCESS;
6869 /* NB: G.global_argv[0] ($0) is never freed/changed */
6870 g_argv = G.global_argv;
6871 if (G.global_args_malloced) {
6877 G.global_args_malloced = 1;
6878 pp = xzalloc(sizeof(pp[0]) * 2);
6879 pp[0] = g_argv[0]; /* retain $0 */
6882 /* This realloc's G.global_argv */
6883 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6890 return EXIT_SUCCESS;
6892 /* Nothing known, so abort */
6894 bb_error_msg("set: %s: invalid option", arg);
6895 return EXIT_FAILURE;
6898 static int builtin_shift(char **argv)
6904 if (n >= 0 && n < G.global_argc) {
6905 if (G.global_args_malloced) {
6908 free(G.global_argv[m++]);
6911 memmove(&G.global_argv[1], &G.global_argv[n+1],
6912 G.global_argc * sizeof(G.global_argv[0]));
6913 return EXIT_SUCCESS;
6915 return EXIT_FAILURE;
6918 static int builtin_source(char **argv)
6923 #if ENABLE_HUSH_FUNCTIONS
6927 if (*++argv == NULL)
6928 return EXIT_FAILURE;
6930 if (strchr(*argv, '/') == NULL
6931 && (PATH = get_local_var_value("PATH")) != NULL
6933 /* Search through $PATH */
6935 const char *end = strchrnul(PATH, ':');
6936 int sz = end - PATH; /* must be int! */
6939 char *tmp = xasprintf("%.*s/%s", sz, PATH, *argv);
6940 input = fopen_for_read(tmp);
6943 /* We have xxx::yyyy in $PATH,
6944 * it means "use current dir" */
6945 input = fopen_for_read(*argv);
6954 input = fopen_or_warn(*argv, "r");
6956 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
6957 return EXIT_FAILURE;
6960 close_on_exec_on(fileno(input));
6962 #if ENABLE_HUSH_FUNCTIONS
6963 sv_flg = G.flag_return_in_progress;
6964 /* "we are inside sourced file, ok to use return" */
6965 G.flag_return_in_progress = -1;
6967 save_and_replace_G_args(&sv, argv);
6969 parse_and_run_file(input);
6972 restore_G_args(&sv, argv);
6973 #if ENABLE_HUSH_FUNCTIONS
6974 G.flag_return_in_progress = sv_flg;
6977 return G.last_exitcode;
6980 static int builtin_umask(char **argv)
6987 mode_t old_mask = mask;
6990 rc = bb_parse_mode(argv[1], &mask);
6995 * bash: umask: 'q': invalid symbolic mode operator
6996 * bash: umask: 999: octal number out of range
6998 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7003 printf("%04o\n", (unsigned) mask);
7004 /* fall through and restore mask which we set to 0 */
7008 return !rc; /* rc != 0 - success */
7011 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7012 static int builtin_unset(char **argv)
7017 /* "!": do not abort on errors */
7018 /* "+": stop at 1st non-option */
7019 opts = getopt32(argv, "!+vf");
7020 if (opts == (unsigned)-1)
7021 return EXIT_FAILURE;
7023 bb_error_msg("unset: -v and -f are exclusive");
7024 return EXIT_FAILURE;
7030 if (!(opts & 2)) { /* not -f */
7031 if (unset_local_var(*argv)) {
7032 /* unset <nonexistent_var> doesn't fail.
7033 * Error is when one tries to unset RO var.
7034 * Message was printed by unset_local_var. */
7038 #if ENABLE_HUSH_FUNCTIONS
7048 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7049 static int builtin_wait(char **argv)
7051 int ret = EXIT_SUCCESS;
7054 if (*++argv == NULL) {
7055 /* Don't care about wait results */
7056 /* Note 1: must wait until there are no more children */
7057 /* Note 2: must be interruptible */
7059 * $ sleep 3 & sleep 6 & wait
7064 * $ sleep 3 & sleep 6 & wait
7068 * ^C <-- after ~4 sec from keyboard
7071 sigaddset(&G.blocked_set, SIGCHLD);
7072 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7075 if (errno == ECHILD)
7077 /* Wait for SIGCHLD or any other signal of interest */
7078 /* sigtimedwait with infinite timeout: */
7079 sig = sigwaitinfo(&G.blocked_set, NULL);
7081 sig = check_and_run_traps(sig);
7082 if (sig && sig != SIGCHLD) { /* see note 2 */
7088 sigdelset(&G.blocked_set, SIGCHLD);
7089 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7093 /* This is probably buggy wrt interruptible-ness */
7095 pid_t pid = bb_strtou(*argv, NULL, 10);
7097 /* mimic bash message */
7098 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7099 return EXIT_FAILURE;
7101 if (waitpid(pid, &status, 0) == pid) {
7102 if (WIFSIGNALED(status))
7103 ret = 128 + WTERMSIG(status);
7104 else if (WIFEXITED(status))
7105 ret = WEXITSTATUS(status);
7109 bb_perror_msg("wait %s", *argv);
7118 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7119 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7122 def = bb_strtou(argv[1], NULL, 10);
7123 if (errno || def < def_min || argv[2]) {
7124 bb_error_msg("%s: bad arguments", argv[0]);
7132 #if ENABLE_HUSH_LOOPS
7133 static int builtin_break(char **argv)
7136 if (G.depth_of_loop == 0) {
7137 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7138 return EXIT_SUCCESS; /* bash compat */
7140 G.flag_break_continue++; /* BC_BREAK = 1 */
7142 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7143 if (depth == UINT_MAX)
7144 G.flag_break_continue = BC_BREAK;
7145 if (G.depth_of_loop < depth)
7146 G.depth_break_continue = G.depth_of_loop;
7148 return EXIT_SUCCESS;
7151 static int builtin_continue(char **argv)
7153 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7154 return builtin_break(argv);
7158 #if ENABLE_HUSH_FUNCTIONS
7159 static int builtin_return(char **argv)
7163 if (G.flag_return_in_progress != -1) {
7164 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7165 return EXIT_FAILURE; /* bash compat */
7168 G.flag_return_in_progress = 1;
7171 * out of range: wraps around at 256, does not error out
7172 * non-numeric param:
7173 * f() { false; return qwe; }; f; echo $?
7174 * bash: return: qwe: numeric argument required <== we do this
7175 * 255 <== we also do this
7177 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);