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 /* three pseudo-keywords support contrived "case" syntax: */
196 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
197 RES_MATCH , /* "word)" */
198 RES_CASE_BODY, /* "this command is inside CASE" */
205 typedef struct o_string {
207 int length; /* position where data is appended */
209 /* Protect newly added chars against globbing
210 * (by prepending \ to *, ?, [, \) */
213 /* At least some part of the string was inside '' or "",
214 * possibly empty one: word"", wo''rd etc. */
216 smallint has_empty_slot;
217 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
220 MAYBE_ASSIGNMENT = 0,
221 DEFINITELY_ASSIGNMENT = 1,
223 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
225 /* Used for initialization: o_string foo = NULL_O_STRING; */
226 #define NULL_O_STRING { NULL }
228 /* I can almost use ordinary FILE*. Is open_memstream() universally
229 * available? Where is it documented? */
230 typedef struct in_str {
232 /* eof_flag=1: last char in ->p is really an EOF */
233 char eof_flag; /* meaningless if ->p == NULL */
235 #if ENABLE_HUSH_INTERACTIVE
237 smallint promptmode; /* 0: PS1, 1: PS2 */
240 int (*get) (struct in_str *);
241 int (*peek) (struct in_str *);
243 #define i_getch(input) ((input)->get(input))
244 #define i_peek(input) ((input)->peek(input))
246 struct redir_struct {
247 struct redir_struct *next;
248 char *rd_filename; /* filename */
249 int rd_fd; /* fd to redirect */
250 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
252 smallint rd_type; /* (enum redir_type) */
253 /* note: for heredocs, rd_filename contains heredoc delimiter,
254 * and subsequently heredoc itself; and rd_dup is a bitmask:
255 * 1: do we need to trim leading tabs?
256 * 2: is heredoc quoted (<<'delim' syntax) ?
259 typedef enum redir_type {
260 REDIRECT_INVALID = 0,
262 REDIRECT_OVERWRITE = 2,
264 REDIRECT_HEREDOC = 4,
266 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
269 REDIRFD_SYNTAX_ERR = -2,
270 REDIRFD_TO_FILE = -1,
271 /* otherwise, rd_fd is redirected to rd_dup */
273 HEREDOC_SKIPTABS = 1,
279 pid_t pid; /* 0 if exited */
280 int assignment_cnt; /* how many argv[i] are assignments? */
281 smallint is_stopped; /* is the command currently running? */
282 smallint grp_type; /* GRP_xxx */
284 #define GRP_SUBSHELL 1
285 #if ENABLE_HUSH_FUNCTIONS
286 # define GRP_FUNCTION 2
288 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
291 char *group_as_string;
293 #if ENABLE_HUSH_FUNCTIONS
294 struct function *child_func;
295 /* This field is used to prevent a bug here:
296 * while...do f1() {a;}; f1; f1 {b;}; f1; done
297 * When we execute "f1() {a;}" cmd, we create new function and clear
298 * cmd->group, cmd->group_as_string, cmd->argv[0].
299 * when we execute "f1 {b;}", we notice that f1 exists,
300 * and that it's "parent cmd" struct is still "alive",
301 * we put those fields back into cmd->xxx
302 * (struct function has ->parent_cmd ptr to facilitate that).
303 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
304 * Without this trick, loop would execute a;b;b;b;...
305 * instead of correct sequence a;b;a;b;...
306 * When command is freed, it severs the link
307 * (sets ->child_func->parent_cmd to NULL).
310 char **argv; /* command name and arguments */
311 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
312 * and on execution these are substituted with their values.
313 * Substitution can make _several_ words out of one argv[n]!
314 * Example: argv[0]=='.^C*^C.' here: echo .$*.
315 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
317 struct redir_struct *redirects; /* I/O redirections */
319 /* Is there anything in this command at all? */
320 #define IS_NULL_CMD(cmd) \
321 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
326 int num_cmds; /* total number of commands in pipe */
327 int alive_cmds; /* number of commands running (not exited) */
328 int stopped_cmds; /* number of commands alive, but stopped */
330 int jobid; /* job number */
331 pid_t pgrp; /* process group ID for the job */
332 char *cmdtext; /* name of job */
334 struct command *cmds; /* array of commands in pipe */
335 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
336 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
337 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
339 typedef enum pipe_style {
345 /* Is there anything in this pipe at all? */
346 #define IS_NULL_PIPE(pi) \
347 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
349 /* This holds pointers to the various results of parsing */
350 struct parse_context {
351 /* linked list of pipes */
352 struct pipe *list_head;
353 /* last pipe (being constructed right now) */
355 /* last command in pipe (being constructed right now) */
356 struct command *command;
357 /* last redirect in command->redirects list */
358 struct redir_struct *pending_redirect;
364 smallint ctx_inverted; /* "! cmd | cmd" */
366 smallint ctx_dsemicolon; /* ";;" seen */
368 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
370 /* group we are enclosed in:
371 * example: "if pipe1; pipe2; then pipe3; fi"
372 * when we see "if" or "then", we malloc and copy current context,
373 * and make ->stack point to it. then we parse pipeN.
374 * when closing "then" / fi" / whatever is found,
375 * we move list_head into ->stack->command->group,
376 * copy ->stack into current context, and delete ->stack.
377 * (parsing of { list } and ( list ) doesn't use this method)
379 struct parse_context *stack;
383 /* On program start, environ points to initial environment.
384 * putenv adds new pointers into it, unsetenv removes them.
385 * Neither of these (de)allocates the strings.
386 * setenv allocates new strings in malloc space and does putenv,
387 * and thus setenv is unusable (leaky) for shell's purposes */
388 #define setenv(...) setenv_is_leaky_dont_use()
390 struct variable *next;
391 char *varstr; /* points to "name=" portion */
392 int max_len; /* if > 0, name is part of initial env; else name is malloced */
393 smallint flg_export; /* putenv should be done on this var */
394 smallint flg_read_only;
402 #if ENABLE_HUSH_FUNCTIONS
404 struct function *next;
406 struct command *parent_cmd;
409 char *body_as_string;
415 /* "Globals" within this file */
416 /* Sorted roughly by size (smaller offsets == smaller code) */
418 /* interactive_fd != 0 means we are an interactive shell.
419 * If we are, then saved_tty_pgrp can also be != 0, meaning
420 * that controlling tty is available. With saved_tty_pgrp == 0,
421 * job control still works, but terminal signals
422 * (^C, ^Z, ^Y, ^\) won't work at all, and background
423 * process groups can only be created with "cmd &".
424 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
425 * to give tty to the foreground process group,
426 * and will take it back when the group is stopped (^Z)
429 #if ENABLE_HUSH_INTERACTIVE
430 /* 'interactive_fd' is a fd# open to ctty, if we have one
431 * _AND_ if we decided to act interactively */
435 # define G_interactive_fd (G.interactive_fd)
437 # define G_interactive_fd 0
439 #if ENABLE_FEATURE_EDITING
440 line_input_t *line_input_state;
447 pid_t saved_tty_pgrp;
448 struct pipe *job_list;
449 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
451 # define G_saved_tty_pgrp 0
453 smallint flag_SIGINT;
454 #if ENABLE_HUSH_LOOPS
455 smallint flag_break_continue;
457 #if ENABLE_HUSH_FUNCTIONS
458 /* 0: outside of a function (or sourced file)
459 * -1: inside of a function, ok to use return builtin
460 * 1: return is invoked, skip all till end of func
462 smallint flag_return_in_progress;
465 smallint exiting; /* used to prevent EXIT trap recursion */
466 /* These four support $?, $#, and $1 */
467 smalluint last_exitcode;
468 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
469 smalluint global_args_malloced;
470 /* how many non-NULL argv's we have. NB: $# + 1 */
474 char *argv0_for_re_execing;
476 #if ENABLE_HUSH_LOOPS
477 unsigned depth_break_continue;
478 unsigned depth_of_loop;
482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
483 struct variable shell_ver;
484 #if ENABLE_HUSH_FUNCTIONS
485 struct function *top_func;
487 /* Signal and trap handling */
488 // unsigned count_SIGCHLD;
489 // unsigned handled_SIGCHLD;
490 /* which signals have non-DFL handler (even with no traps set)? */
491 unsigned non_DFL_mask;
492 char **traps; /* char *traps[NSIG] */
493 sigset_t blocked_set;
494 sigset_t inherited_set;
496 unsigned long memleak_value;
499 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
501 #define G (*ptr_to_globals)
502 /* Not #defining name to G.name - this quickly gets unwieldy
503 * (too many defines). Also, I actually prefer to see when a variable
504 * is global, thus "G." prefix is a useful hint */
505 #define INIT_G() do { \
506 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
510 /* Function prototypes for builtins */
511 static int builtin_cd(char **argv);
512 static int builtin_echo(char **argv);
513 static int builtin_eval(char **argv);
514 static int builtin_exec(char **argv);
515 static int builtin_exit(char **argv);
516 static int builtin_export(char **argv);
518 static int builtin_fg_bg(char **argv);
519 static int builtin_jobs(char **argv);
522 static int builtin_help(char **argv);
525 static int builtin_memleak(char **argv);
527 static int builtin_pwd(char **argv);
528 static int builtin_read(char **argv);
529 static int builtin_set(char **argv);
530 static int builtin_shift(char **argv);
531 static int builtin_source(char **argv);
532 static int builtin_test(char **argv);
533 static int builtin_trap(char **argv);
534 static int builtin_true(char **argv);
535 static int builtin_umask(char **argv);
536 static int builtin_unset(char **argv);
537 static int builtin_wait(char **argv);
538 #if ENABLE_HUSH_LOOPS
539 static int builtin_break(char **argv);
540 static int builtin_continue(char **argv);
542 #if ENABLE_HUSH_FUNCTIONS
543 static int builtin_return(char **argv);
546 /* Table of built-in functions. They can be forked or not, depending on
547 * context: within pipes, they fork. As simple commands, they do not.
548 * When used in non-forking context, they can change global variables
549 * in the parent shell process. If forked, of course they cannot.
550 * For example, 'unset foo | whatever' will parse and run, but foo will
551 * still be set at the end. */
552 struct built_in_command {
554 int (*function)(char **argv);
557 #define BLTIN(cmd, func, help) { cmd, func, help }
559 #define BLTIN(cmd, func, help) { cmd, func }
563 /* For now, echo and test are unconditionally enabled.
564 * Maybe make it configurable? */
565 static const struct built_in_command bltins[] = {
566 BLTIN("." , builtin_source , "Run commands in a file"),
567 BLTIN(":" , builtin_true , "No-op"),
568 BLTIN("[" , builtin_test , "Test condition"),
570 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
572 #if ENABLE_HUSH_LOOPS
573 BLTIN("break" , builtin_break , "Exit from a loop"),
575 BLTIN("cd" , builtin_cd , "Change directory"),
576 #if ENABLE_HUSH_LOOPS
577 BLTIN("continue", builtin_continue, "Start new loop iteration"),
579 BLTIN("echo" , builtin_echo , "Write to stdout"),
580 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
581 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
582 BLTIN("exit" , builtin_exit , "Exit"),
583 BLTIN("export" , builtin_export , "Set environment variable"),
585 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
588 BLTIN("help" , builtin_help , "List shell built-in commands"),
591 BLTIN("jobs" , builtin_jobs , "List active jobs"),
594 BLTIN("memleak" , builtin_memleak , "Debug tool"),
596 BLTIN("pwd" , builtin_pwd , "Print current directory"),
597 BLTIN("read" , builtin_read , "Input environment variable"),
598 #if ENABLE_HUSH_FUNCTIONS
599 BLTIN("return" , builtin_return , "Return from a function"),
601 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
602 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
603 BLTIN("test" , builtin_test , "Test condition"),
604 BLTIN("trap" , builtin_trap , "Trap signals"),
605 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
606 BLTIN("umask" , builtin_umask , "Set file creation mask"),
607 BLTIN("unset" , builtin_unset , "Unset environment variable"),
608 BLTIN("wait" , builtin_wait , "Wait for process"),
615 /* prevent disasters with G.debug_indent < 0 */
616 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
617 # define debug_enter() (G.debug_indent++)
618 # define debug_leave() (G.debug_indent--)
620 # define indent() ((void)0)
621 # define debug_enter() ((void)0)
622 # define debug_leave() ((void)0)
626 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
629 #ifndef debug_printf_parse
630 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
633 #ifndef debug_printf_exec
634 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
637 #ifndef debug_printf_env
638 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
641 #ifndef debug_printf_jobs
642 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
643 # define DEBUG_JOBS 1
645 # define DEBUG_JOBS 0
648 #ifndef debug_printf_expand
649 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
650 # define DEBUG_EXPAND 1
652 # define DEBUG_EXPAND 0
655 #ifndef debug_printf_glob
656 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
657 # define DEBUG_GLOB 1
659 # define DEBUG_GLOB 0
662 #ifndef debug_printf_list
663 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
666 #ifndef debug_printf_subst
667 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
670 #ifndef debug_printf_clean
671 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
672 # define DEBUG_CLEAN 1
674 # define DEBUG_CLEAN 0
678 static void debug_print_strings(const char *prefix, char **vv)
681 fprintf(stderr, "%s:\n", prefix);
683 fprintf(stderr, " '%s'\n", *vv++);
686 #define debug_print_strings(prefix, vv) ((void)0)
690 /* Leak hunting. Use hush_leaktool.sh for post-processing.
693 static void *xxmalloc(int lineno, size_t size)
695 void *ptr = xmalloc((size + 0xff) & ~0xff);
696 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
699 static void *xxrealloc(int lineno, void *ptr, size_t size)
701 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
702 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
705 static char *xxstrdup(int lineno, const char *str)
707 char *ptr = xstrdup(str);
708 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
711 static void xxfree(void *ptr)
713 fdprintf(2, "free %p\n", ptr);
716 #define xmalloc(s) xxmalloc(__LINE__, s)
717 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
718 #define xstrdup(s) xxstrdup(__LINE__, s)
719 #define free(p) xxfree(p)
723 /* Syntax and runtime errors. They always abort scripts.
724 * In interactive use they usually discard unparsed and/or unexecuted commands
725 * and return to the prompt.
726 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
729 # define die_if_script(lineno, fmt...) die_if_script(fmt)
730 # define syntax_error(lineno, msg) syntax_error(msg)
731 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
732 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
733 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
734 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
737 static void die_if_script(unsigned lineno, const char *fmt, ...)
742 bb_error_msg("hush.c:%u", lineno);
745 bb_verror_msg(fmt, p, NULL);
747 if (!G_interactive_fd)
751 static void syntax_error(unsigned lineno, const char *msg)
754 die_if_script(lineno, "syntax error: %s", msg);
756 die_if_script(lineno, "syntax error", NULL);
759 static void syntax_error_at(unsigned lineno, const char *msg)
761 die_if_script(lineno, "syntax error at '%s'", msg);
764 /* It so happens that all such cases are totally fatal
765 * even if shell is interactive: EOF while looking for closing
766 * delimiter. There is nowhere to read stuff from after that,
767 * it's EOF! The only choice is to terminate.
769 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
770 static void syntax_error_unterm_ch(unsigned lineno, char ch)
775 die_if_script(lineno, "syntax error: unterminated %s", msg);
779 static void syntax_error_unterm_str(unsigned lineno, const char *s)
781 die_if_script(lineno, "syntax error: unterminated %s", s);
784 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
789 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
793 # undef die_if_script
795 # undef syntax_error_at
796 # undef syntax_error_unterm_ch
797 # undef syntax_error_unterm_str
798 # undef syntax_error_unexpected_ch
800 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
801 # define syntax_error(msg) syntax_error(__LINE__, msg)
802 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
803 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
804 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
805 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
809 #if ENABLE_HUSH_INTERACTIVE
810 static void cmdedit_update_prompt(void);
812 # define cmdedit_update_prompt()
818 static int glob_needed(const char *s)
823 if (*s == '*' || *s == '[' || *s == '?')
830 static int is_well_formed_var_name(const char *s, char terminator)
832 if (!s || !(isalpha(*s) || *s == '_'))
835 while (isalnum(*s) || *s == '_')
837 return *s == terminator;
840 /* Replace each \x with x in place, return ptr past NUL. */
841 static char *unbackslash(char *src)
847 if ((*dst++ = *src++) == '\0')
853 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
874 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
875 v[count1 + count2] = NULL;
878 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
882 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
884 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
885 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
888 #define add_strings_to_strings(strings, add, need_to_dup) \
889 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
892 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
893 static char **add_string_to_strings(char **strings, char *add)
898 return add_strings_to_strings(strings, v, /*dup:*/ 0);
901 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
903 char **ptr = add_string_to_strings(strings, add);
904 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
907 #define add_string_to_strings(strings, add) \
908 xx_add_string_to_strings(__LINE__, strings, add)
911 static void free_strings(char **strings)
926 /* Helpers for setting new $n and restoring them back
928 typedef struct save_arg_t {
932 smallint sv_g_malloced;
935 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
939 sv->sv_argv0 = argv[0];
940 sv->sv_g_argv = G.global_argv;
941 sv->sv_g_argc = G.global_argc;
942 sv->sv_g_malloced = G.global_args_malloced;
944 argv[0] = G.global_argv[0]; /* retain $0 */
945 G.global_argv = argv;
946 G.global_args_malloced = 0;
954 static void restore_G_args(save_arg_t *sv, char **argv)
958 if (G.global_args_malloced) {
959 /* someone ran "set -- arg1 arg2 ...", undo */
961 while (*++pp) /* note: does not free $0 */
965 argv[0] = sv->sv_argv0;
966 G.global_argv = sv->sv_g_argv;
967 G.global_argc = sv->sv_g_argc;
968 G.global_args_malloced = sv->sv_g_malloced;
972 /* Basic theory of signal handling in shell
973 * ========================================
974 * This does not describe what hush does, rather, it is current understanding
975 * what it _should_ do. If it doesn't, it's a bug.
976 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
978 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
979 * is finished or backgrounded. It is the same in interactive and
980 * non-interactive shells, and is the same regardless of whether
981 * a user trap handler is installed or a shell special one is in effect.
982 * ^C or ^Z from keyboard seem to execute "at once" because it usually
983 * backgrounds (i.e. stops) or kills all members of currently running
986 * Wait builtin in interruptible by signals for which user trap is set
987 * or by SIGINT in interactive shell.
989 * Trap handlers will execute even within trap handlers. (right?)
991 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
993 * If job control is off, backgrounded commands ("cmd &")
994 * have SIGINT, SIGQUIT set to SIG_IGN.
996 * Commands run in command substitution ("`cmd`")
997 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
999 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
1000 * by the shell from its parent.
1002 * Siganls which differ from SIG_DFL action
1003 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1006 * SIGTERM (interactive): ignore
1007 * SIGHUP (interactive):
1008 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1009 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1010 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1011 * that all pipe members are stopped. Try this in bash:
1012 * while :; do :; done - ^Z does not background it
1013 * (while :; do :; done) - ^Z backgrounds it
1014 * SIGINT (interactive): wait for last pipe, ignore the rest
1015 * of the command line, show prompt. NB: ^C does not send SIGINT
1016 * to interactive shell while shell is waiting for a pipe,
1017 * since shell is bg'ed (is not in foreground process group).
1018 * Example 1: this waits 5 sec, but does not execute ls:
1019 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1020 * Example 2: this does not wait and does not execute ls:
1021 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1022 * Example 3: this does not wait 5 sec, but executes ls:
1023 * "sleep 5; ls -l" + press ^C
1025 * (What happens to signals which are IGN on shell start?)
1026 * (What happens with signal mask on shell start?)
1028 * Implementation in hush
1029 * ======================
1030 * We use in-kernel pending signal mask to determine which signals were sent.
1031 * We block all signals which we don't want to take action immediately,
1032 * i.e. we block all signals which need to have special handling as described
1033 * above, and all signals which have traps set.
1034 * After each pipe execution, we extract any pending signals via sigtimedwait()
1037 * unsigned non_DFL_mask: a mask of such "special" signals
1038 * sigset_t blocked_set: current blocked signal set
1041 * clear bit in blocked_set unless it is also in non_DFL_mask
1042 * "trap 'cmd' SIGxxx":
1043 * set bit in blocked_set (even if 'cmd' is '')
1044 * after [v]fork, if we plan to be a shell:
1045 * unblock signals with special interactive handling
1046 * (child shell is not interactive),
1047 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1048 * after [v]fork, if we plan to exec:
1049 * POSIX says pending signal mask is cleared in child - no need to clear it.
1050 * Restore blocked signal set to one inherited by shell just prior to exec.
1052 * Note: as a result, we do not use signal handlers much. The only uses
1053 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
1054 * and to restore tty pgrp on signal-induced exit.
1057 SPECIAL_INTERACTIVE_SIGS = 0
1062 SPECIAL_JOB_SIGS = 0
1070 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
1072 // G.count_SIGCHLD++;
1077 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1078 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1079 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1080 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1082 /* Restores tty foreground process group, and exits.
1083 * May be called as signal handler for fatal signal
1084 * (will resend signal to itself, producing correct exit state)
1085 * or called directly with -EXITCODE.
1086 * We also call it if xfunc is exiting. */
1087 static void sigexit(int sig) NORETURN;
1088 static void sigexit(int sig)
1090 /* Disable all signals: job control, SIGPIPE, etc. */
1091 sigprocmask_allsigs(SIG_BLOCK);
1093 /* Careful: we can end up here after [v]fork. Do not restore
1094 * tty pgrp then, only top-level shell process does that */
1095 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1096 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1098 /* Not a signal, just exit */
1102 kill_myself_with_sig(sig); /* does not return */
1106 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1107 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1111 /* Restores tty foreground process group, and exits. */
1112 static void hush_exit(int exitcode) NORETURN;
1113 static void hush_exit(int exitcode)
1115 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1116 /* Prevent recursion:
1117 * trap "echo Hi; exit" EXIT; exit
1119 char *argv[] = { NULL, G.traps[0], NULL };
1127 fflush(NULL); /* flush all streams */
1128 sigexit(- (exitcode & 0xff));
1134 static int check_and_run_traps(int sig)
1136 static const struct timespec zero_timespec = { 0, 0 };
1137 smalluint save_rcode;
1143 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1148 if (G.traps && G.traps[sig]) {
1149 if (G.traps[sig][0]) {
1150 /* We have user-defined handler */
1151 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1152 save_rcode = G.last_exitcode;
1155 G.last_exitcode = save_rcode;
1156 } /* else: "" trap, ignoring signal */
1159 /* not a trap: special action */
1162 // G.count_SIGCHLD++;
1165 /* Builtin was ^C'ed, make it look prettier: */
1172 /* bash is observed to signal whole process groups,
1173 * not individual processes */
1174 for (job = G.job_list; job; job = job->next) {
1177 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1178 if (kill(- job->pgrp, SIGHUP) == 0)
1179 kill(- job->pgrp, SIGCONT);
1184 default: /* ignored: */
1185 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1193 static const char *set_cwd(void)
1195 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1196 * we must not try to free(bb_msg_unknown) */
1197 if (G.cwd == bb_msg_unknown)
1199 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1201 G.cwd = bb_msg_unknown;
1207 * Shell and environment variable support
1209 static struct variable **get_ptr_to_local_var(const char *name)
1211 struct variable **pp;
1212 struct variable *cur;
1217 while ((cur = *pp) != NULL) {
1218 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1225 static struct variable *get_local_var(const char *name)
1227 struct variable **pp = get_ptr_to_local_var(name);
1233 static const char *get_local_var_value(const char *name)
1235 struct variable **pp = get_ptr_to_local_var(name);
1237 return strchr((*pp)->varstr, '=') + 1;
1241 /* str holds "NAME=VAL" and is expected to be malloced.
1242 * We take ownership of it.
1244 * 0: do not change export flag
1245 * (if creating new variable, flag will be 0)
1246 * 1: set export flag and putenv the variable
1247 * -1: clear export flag and unsetenv the variable
1248 * flg_read_only is set only when we handle -R var=val
1251 #define set_local_var(str, flg_export, flg_read_only) \
1252 set_local_var(str, flg_export)
1254 static int set_local_var(char *str, int flg_export, int flg_read_only)
1256 struct variable *cur;
1260 eq_sign = strchr(str, '=');
1261 if (!eq_sign) { /* not expected to ever happen? */
1266 name_len = eq_sign - str + 1; /* including '=' */
1267 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1269 if (strncmp(cur->varstr, str, name_len) != 0) {
1271 /* Bail out. Note that now cur points
1272 * to last var in linked list */
1278 /* We found an existing var with this name */
1279 if (cur->flg_read_only) {
1283 bb_error_msg("%s: readonly variable", str);
1287 if (flg_export == -1) {
1288 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1293 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1298 if (cur->max_len >= strlen(str)) {
1299 /* This one is from startup env, reuse space */
1300 strcpy(cur->varstr, str);
1303 /* max_len == 0 signifies "malloced" var, which we can
1304 * (and has to) free */
1308 goto set_str_and_exp;
1311 /* Not found - create next variable struct */
1312 cur->next = xzalloc(sizeof(*cur));
1318 cur->flg_read_only = flg_read_only;
1321 if (flg_export == 1)
1322 cur->flg_export = 1;
1323 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1324 cmdedit_update_prompt();
1325 if (cur->flg_export) {
1326 if (flg_export == -1) {
1327 cur->flg_export = 0;
1328 /* unsetenv was already done */
1330 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1331 return putenv(cur->varstr);
1337 static int unset_local_var_len(const char *name, int name_len)
1339 struct variable *cur;
1340 struct variable **var_pp;
1343 return EXIT_SUCCESS;
1344 var_pp = &G.top_var;
1345 while ((cur = *var_pp) != NULL) {
1346 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1347 if (cur->flg_read_only) {
1348 bb_error_msg("%s: readonly variable", name);
1349 return EXIT_FAILURE;
1351 *var_pp = cur->next;
1352 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1353 bb_unsetenv(cur->varstr);
1354 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1355 cmdedit_update_prompt();
1359 return EXIT_SUCCESS;
1361 var_pp = &cur->next;
1363 return EXIT_SUCCESS;
1366 static int unset_local_var(const char *name)
1368 return unset_local_var_len(name, strlen(name));
1371 static void unset_vars(char **strings)
1379 const char *eq = strchrnul(*v, '=');
1380 unset_local_var_len(*v, (int)(eq - *v));
1386 #if ENABLE_SH_MATH_SUPPORT
1387 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1388 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1389 static char *endofname(const char *name)
1397 if (!is_in_name(*p))
1403 static void arith_set_local_var(const char *name, const char *val, int flags)
1405 /* arith code doesnt malloc space, so do it for it */
1406 char *var = xasprintf("%s=%s", name, val);
1407 set_local_var(var, flags, 0);
1413 * Helpers for "var1=val1 var2=val2 cmd" feature
1415 static void add_vars(struct variable *var)
1417 struct variable *next;
1421 var->next = G.top_var;
1423 if (var->flg_export) {
1424 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1425 putenv(var->varstr);
1427 debug_printf_env("%s: restoring local '%s'\n", __func__, var->varstr);
1433 static struct variable *set_vars_and_save_old(char **strings)
1436 struct variable *old = NULL;
1442 struct variable *var_p;
1443 struct variable **var_pp;
1446 eq = strchr(*s, '=');
1449 var_pp = get_ptr_to_local_var(*s);
1452 /* Remove variable from global linked list */
1454 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1455 *var_pp = var_p->next;
1456 /* Add it to returned list */
1460 set_local_var(*s, 1, 0);
1471 static int static_get(struct in_str *i)
1480 static int static_peek(struct in_str *i)
1485 #if ENABLE_HUSH_INTERACTIVE
1487 static void cmdedit_update_prompt(void)
1489 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1490 G.PS1 = get_local_var_value("PS1");
1493 G.PS2 = get_local_var_value("PS2");
1501 static const char* setup_prompt_string(int promptmode)
1503 const char *prompt_str;
1504 debug_printf("setup_prompt_string %d ", promptmode);
1505 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1506 /* Set up the prompt */
1507 if (promptmode == 0) { /* PS1 */
1509 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1514 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1515 debug_printf("result '%s'\n", prompt_str);
1519 static void get_user_input(struct in_str *i)
1522 const char *prompt_str;
1524 prompt_str = setup_prompt_string(i->promptmode);
1525 #if ENABLE_FEATURE_EDITING
1526 /* Enable command line editing only while a command line
1527 * is actually being read */
1530 /* buglet: SIGINT will not make new prompt to appear _at once_,
1531 * only after <Enter>. (^C will work) */
1532 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1533 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1534 check_and_run_traps(0);
1535 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1536 i->eof_flag = (r < 0);
1537 if (i->eof_flag) { /* EOF/error detected */
1538 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1539 G.user_input_buf[1] = '\0';
1544 fputs(prompt_str, stdout);
1546 G.user_input_buf[0] = r = fgetc(i->file);
1547 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1548 //do we need check_and_run_traps(0)? (maybe only if stdin)
1549 } while (G.flag_SIGINT);
1550 i->eof_flag = (r == EOF);
1552 i->p = G.user_input_buf;
1555 #endif /* INTERACTIVE */
1557 /* This is the magic location that prints prompts
1558 * and gets data back from the user */
1559 static int file_get(struct in_str *i)
1563 /* If there is data waiting, eat it up */
1564 if (i->p && *i->p) {
1565 #if ENABLE_HUSH_INTERACTIVE
1569 if (i->eof_flag && !*i->p)
1571 /* note: ch is never NUL */
1573 /* need to double check i->file because we might be doing something
1574 * more complicated by now, like sourcing or substituting. */
1575 #if ENABLE_HUSH_INTERACTIVE
1576 if (G_interactive_fd && i->promptme && i->file == stdin) {
1579 } while (!*i->p); /* need non-empty line */
1580 i->promptmode = 1; /* PS2 */
1585 do ch = fgetc(i->file); while (ch == '\0');
1587 debug_printf("file_get: got '%c' %d\n", ch, ch);
1588 #if ENABLE_HUSH_INTERACTIVE
1595 /* All callers guarantee this routine will never
1596 * be used right after a newline, so prompting is not needed.
1598 static int file_peek(struct in_str *i)
1601 if (i->p && *i->p) {
1602 if (i->eof_flag && !i->p[1])
1605 /* note: ch is never NUL */
1607 do ch = fgetc(i->file); while (ch == '\0');
1608 i->eof_flag = (ch == EOF);
1609 i->peek_buf[0] = ch;
1610 i->peek_buf[1] = '\0';
1612 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1616 static void setup_file_in_str(struct in_str *i, FILE *f)
1618 i->peek = file_peek;
1620 #if ENABLE_HUSH_INTERACTIVE
1622 i->promptmode = 0; /* PS1 */
1628 static void setup_string_in_str(struct in_str *i, const char *s)
1630 i->peek = static_peek;
1631 i->get = static_get;
1632 #if ENABLE_HUSH_INTERACTIVE
1634 i->promptmode = 0; /* PS1 */
1644 #define B_CHUNK (32 * sizeof(char*))
1646 static void o_reset_to_empty_unquoted(o_string *o)
1654 static void o_free(o_string *o)
1657 memset(o, 0, sizeof(*o));
1660 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1665 static void o_grow_by(o_string *o, int len)
1667 if (o->length + len > o->maxlen) {
1668 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1669 o->data = xrealloc(o->data, 1 + o->maxlen);
1673 static void o_addchr(o_string *o, int ch)
1675 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1677 o->data[o->length] = ch;
1679 o->data[o->length] = '\0';
1682 static void o_addblock(o_string *o, const char *str, int len)
1685 memcpy(&o->data[o->length], str, len);
1687 o->data[o->length] = '\0';
1691 static void o_addstr(o_string *o, const char *str)
1693 o_addblock(o, str, strlen(str));
1695 static void nommu_addchr(o_string *o, int ch)
1701 #define nommu_addchr(o, str) ((void)0)
1704 static void o_addstr_with_NUL(o_string *o, const char *str)
1706 o_addblock(o, str, strlen(str) + 1);
1709 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1714 && (*str != '*' && *str != '?' && *str != '[')
1722 /* My analysis of quoting semantics tells me that state information
1723 * is associated with a destination, not a source.
1725 static void o_addqchr(o_string *o, int ch)
1728 char *found = strchr("*?[\\", ch);
1733 o->data[o->length] = '\\';
1736 o->data[o->length] = ch;
1738 o->data[o->length] = '\0';
1741 static void o_addQchr(o_string *o, int ch)
1744 if (o->o_escape && strchr("*?[\\", ch)) {
1746 o->data[o->length] = '\\';
1750 o->data[o->length] = ch;
1752 o->data[o->length] = '\0';
1755 static void o_addQstr(o_string *o, const char *str, int len)
1758 o_addblock(o, str, len);
1764 int ordinary_cnt = strcspn(str, "*?[\\");
1765 if (ordinary_cnt > len) /* paranoia */
1767 o_addblock(o, str, ordinary_cnt);
1768 if (ordinary_cnt == len)
1770 str += ordinary_cnt;
1771 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1775 if (ch) { /* it is necessarily one of "*?[\\" */
1777 o->data[o->length] = '\\';
1781 o->data[o->length] = ch;
1783 o->data[o->length] = '\0';
1787 /* A special kind of o_string for $VAR and `cmd` expansion.
1788 * It contains char* list[] at the beginning, which is grown in 16 element
1789 * increments. Actual string data starts at the next multiple of 16 * (char*).
1790 * list[i] contains an INDEX (int!) into this string data.
1791 * It means that if list[] needs to grow, data needs to be moved higher up
1792 * but list[i]'s need not be modified.
1793 * NB: remembering how many list[i]'s you have there is crucial.
1794 * o_finalize_list() operation post-processes this structure - calculates
1795 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1797 #if DEBUG_EXPAND || DEBUG_GLOB
1798 static void debug_print_list(const char *prefix, o_string *o, int n)
1800 char **list = (char**)o->data;
1801 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1805 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1806 prefix, list, n, string_start, o->length, o->maxlen);
1809 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1810 o->data + (int)list[i] + string_start,
1811 o->data + (int)list[i] + string_start);
1815 const char *p = o->data + (int)list[n - 1] + string_start;
1817 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1821 #define debug_print_list(prefix, o, n) ((void)0)
1824 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1825 * in list[n] so that it points past last stored byte so far.
1826 * It returns n+1. */
1827 static int o_save_ptr_helper(o_string *o, int n)
1829 char **list = (char**)o->data;
1833 if (!o->has_empty_slot) {
1834 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1835 string_len = o->length - string_start;
1836 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1837 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1838 /* list[n] points to string_start, make space for 16 more pointers */
1839 o->maxlen += 0x10 * sizeof(list[0]);
1840 o->data = xrealloc(o->data, o->maxlen + 1);
1841 list = (char**)o->data;
1842 memmove(list + n + 0x10, list + n, string_len);
1843 o->length += 0x10 * sizeof(list[0]);
1845 debug_printf_list("list[%d]=%d string_start=%d\n",
1846 n, string_len, string_start);
1849 /* We have empty slot at list[n], reuse without growth */
1850 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1851 string_len = o->length - string_start;
1852 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1853 n, string_len, string_start);
1854 o->has_empty_slot = 0;
1856 list[n] = (char*)(ptrdiff_t)string_len;
1860 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1861 static int o_get_last_ptr(o_string *o, int n)
1863 char **list = (char**)o->data;
1864 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1866 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1869 /* o_glob performs globbing on last list[], saving each result
1870 * as a new list[]. */
1871 static int o_glob(o_string *o, int n)
1877 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1879 return o_save_ptr_helper(o, n);
1880 pattern = o->data + o_get_last_ptr(o, n);
1881 debug_printf_glob("glob pattern '%s'\n", pattern);
1882 if (!glob_needed(pattern)) {
1884 o->length = unbackslash(pattern) - o->data;
1885 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1886 return o_save_ptr_helper(o, n);
1889 memset(&globdata, 0, sizeof(globdata));
1890 gr = glob(pattern, 0, NULL, &globdata);
1891 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1892 if (gr == GLOB_NOSPACE)
1893 bb_error_msg_and_die("out of memory during glob");
1894 if (gr == GLOB_NOMATCH) {
1895 globfree(&globdata);
1898 if (gr != 0) { /* GLOB_ABORTED ? */
1899 /* TODO: testcase for bad glob pattern behavior */
1900 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1902 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1903 char **argv = globdata.gl_pathv;
1904 o->length = pattern - o->data; /* "forget" pattern */
1906 o_addstr_with_NUL(o, *argv);
1907 n = o_save_ptr_helper(o, n);
1913 globfree(&globdata);
1915 debug_print_list("o_glob returning", o, n);
1919 /* If o->o_glob == 1, glob the string so far remembered.
1920 * Otherwise, just finish current list[] and start new */
1921 static int o_save_ptr(o_string *o, int n)
1923 if (o->o_glob) { /* if globbing is requested */
1924 /* If o->has_empty_slot, list[n] was already globbed
1925 * (if it was requested back then when it was filled)
1926 * so don't do that again! */
1927 if (!o->has_empty_slot)
1928 return o_glob(o, n); /* o_save_ptr_helper is inside */
1930 return o_save_ptr_helper(o, n);
1933 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1934 static char **o_finalize_list(o_string *o, int n)
1939 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1941 debug_print_list("finalized", o, n);
1942 debug_printf_expand("finalized n:%d\n", n);
1943 list = (char**)o->data;
1944 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1948 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1954 /* Expansion can recurse */
1955 #if ENABLE_HUSH_TICK
1956 static int process_command_subs(o_string *dest, const char *s);
1958 static char *expand_string_to_string(const char *str);
1960 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1961 parse_stream_dquoted(dest, input, dquote_end)
1963 static int parse_stream_dquoted(o_string *as_string,
1965 struct in_str *input,
1968 /* expand_strvec_to_strvec() takes a list of strings, expands
1969 * all variable references within and returns a pointer to
1970 * a list of expanded strings, possibly with larger number
1971 * of strings. (Think VAR="a b"; echo $VAR).
1972 * This new list is allocated as a single malloc block.
1973 * NULL-terminated list of char* pointers is at the beginning of it,
1974 * followed by strings themself.
1975 * Caller can deallocate entire list by single free(list). */
1977 /* Store given string, finalizing the word and starting new one whenever
1978 * we encounter IFS char(s). This is used for expanding variable values.
1979 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1980 static int expand_on_ifs(o_string *output, int n, const char *str)
1983 int word_len = strcspn(str, G.ifs);
1985 if (output->o_escape || !output->o_glob)
1986 o_addQstr(output, str, word_len);
1987 else /* protect backslashes against globbing up :) */
1988 o_addblock_duplicate_backslash(output, str, word_len);
1991 if (!*str) /* EOL - do not finalize word */
1993 o_addchr(output, '\0');
1994 debug_print_list("expand_on_ifs", output, n);
1995 n = o_save_ptr(output, n);
1996 str += strspn(str, G.ifs); /* skip ifs chars */
1998 debug_print_list("expand_on_ifs[1]", output, n);
2002 /* Helper to expand $((...)) and heredoc body. These act as if
2003 * they are in double quotes, with the exception that they are not :).
2004 * Just the rules are similar: "expand only $var and `cmd`"
2006 * Returns malloced string.
2007 * As an optimization, we return NULL if expansion is not needed.
2009 static char *expand_pseudo_dquoted(const char *str)
2012 struct in_str input;
2013 o_string dest = NULL_O_STRING;
2015 if (strchr(str, '$') == NULL
2016 #if ENABLE_HUSH_TICK
2017 && strchr(str, '`') == NULL
2023 /* We need to expand. Example:
2024 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2026 setup_string_in_str(&input, str);
2027 parse_stream_dquoted(NULL, &dest, &input, EOF);
2028 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2029 exp_str = expand_string_to_string(dest.data);
2030 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2031 o_free_unsafe(&dest);
2035 /* Expand all variable references in given string, adding words to list[]
2036 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2037 * to be filled). This routine is extremely tricky: has to deal with
2038 * variables/parameters with whitespace, $* and $@, and constructs like
2039 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2040 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2042 /* or_mask is either 0 (normal case) or 0x80
2043 * (expansion of right-hand side of assignment == 1-element expand.
2044 * It will also do no globbing, and thus we must not backslash-quote!) */
2051 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2052 debug_print_list("expand_vars_to_list", output, n);
2053 n = o_save_ptr(output, n);
2054 debug_print_list("expand_vars_to_list[0]", output, n);
2056 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2059 char *dyn_val = NULL;
2060 const char *val = NULL;
2061 #if ENABLE_HUSH_TICK
2062 o_string subst_result = NULL_O_STRING;
2064 #if ENABLE_SH_MATH_SUPPORT
2065 char arith_buf[sizeof(arith_t)*3 + 2];
2067 o_addblock(output, arg, p - arg);
2068 debug_print_list("expand_vars_to_list[1]", output, n);
2070 p = strchr(p, SPECIAL_VAR_SYMBOL);
2072 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2073 /* "$@" is special. Even if quoted, it can still
2074 * expand to nothing (not even an empty string) */
2075 if ((first_ch & 0x7f) != '@')
2076 ored_ch |= first_ch;
2078 switch (first_ch & 0x7f) {
2079 /* Highest bit in first_ch indicates that var is double-quoted */
2081 val = utoa(G.root_pid);
2083 case '!': /* bg pid */
2084 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2086 case '?': /* exitcode */
2087 val = utoa(G.last_exitcode);
2089 case '#': /* argc */
2090 if (arg[1] != SPECIAL_VAR_SYMBOL)
2091 /* actually, it's a ${#var} */
2093 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2098 if (!G.global_argv[i])
2100 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2101 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2102 smallint sv = output->o_escape;
2103 /* unquoted var's contents should be globbed, so don't escape */
2104 output->o_escape = 0;
2105 while (G.global_argv[i]) {
2106 n = expand_on_ifs(output, n, G.global_argv[i]);
2107 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2108 if (G.global_argv[i++][0] && G.global_argv[i]) {
2109 /* this argv[] is not empty and not last:
2110 * put terminating NUL, start new word */
2111 o_addchr(output, '\0');
2112 debug_print_list("expand_vars_to_list[2]", output, n);
2113 n = o_save_ptr(output, n);
2114 debug_print_list("expand_vars_to_list[3]", output, n);
2117 output->o_escape = sv;
2119 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2120 * and in this case should treat it like '$*' - see 'else...' below */
2121 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2123 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2124 if (++i >= G.global_argc)
2126 o_addchr(output, '\0');
2127 debug_print_list("expand_vars_to_list[4]", output, n);
2128 n = o_save_ptr(output, n);
2130 } else { /* quoted $*: add as one word */
2132 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2133 if (!G.global_argv[++i])
2136 o_addchr(output, G.ifs[0]);
2140 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2141 /* "Empty variable", used to make "" etc to not disappear */
2145 #if ENABLE_HUSH_TICK
2146 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2149 /* Can't just stuff it into output o_string,
2150 * expanded result may need to be globbed
2151 * and $IFS-splitted */
2152 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2153 process_command_subs(&subst_result, arg);
2154 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2155 val = subst_result.data;
2158 #if ENABLE_SH_MATH_SUPPORT
2159 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2160 arith_eval_hooks_t hooks;
2165 arg++; /* skip '+' */
2166 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2167 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2169 exp_str = expand_pseudo_dquoted(arg);
2170 hooks.lookupvar = get_local_var_value;
2171 hooks.setvar = arith_set_local_var;
2172 hooks.endofname = endofname;
2173 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2177 const char *msg = "error in arithmetic";
2180 msg = "exponent less than 0";
2183 msg = "divide by 0";
2186 msg = "expression recursion loop detected";
2191 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2192 sprintf(arith_buf, arith_t_fmt, res);
2197 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2199 bool exp_len = false;
2200 bool exp_null = false;
2202 char exp_save = exp_save; /* for compiler */
2203 char exp_op = exp_op; /* for compiler */
2204 char *exp_word = exp_word; /* for compiler */
2208 arg[0] = first_ch & 0x7f;
2210 /* prepare for expansions */
2211 if (var[0] == '#') {
2212 /* handle length expansion ${#var} */
2216 /* maybe handle parameter expansion */
2217 exp_off = strcspn(var, ":-=+?%#");
2221 exp_save = var[exp_off];
2222 exp_null = exp_save == ':';
2223 exp_word = var + exp_off;
2226 exp_op = *exp_word++;
2227 var[exp_off] = '\0';
2231 /* lookup the variable in question */
2232 if (isdigit(var[0])) {
2233 /* handle_dollar() should have vetted var for us */
2235 if (i < G.global_argc)
2236 val = G.global_argv[i];
2237 /* else val remains NULL: $N with too big N */
2239 val = get_local_var_value(var);
2241 /* handle any expansions */
2243 debug_printf_expand("expand: length of '%s' = ", val);
2244 val = utoa(val ? strlen(val) : 0);
2245 debug_printf_expand("%s\n", val);
2246 } else if (exp_off) {
2247 if (exp_op == '%' || exp_op == '#') {
2249 /* we need to do a pattern match */
2252 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2253 if (exp_op == *exp_word) /* ## or %% */
2255 val = dyn_val = xstrdup(val);
2256 loc = scan(dyn_val, exp_word, match_at_left);
2257 if (match_at_left) /* # or ## */
2259 else if (loc) /* % or %% and match was found */
2263 /* we need to do an expansion */
2264 int exp_test = (!val || (exp_null && !val[0]));
2266 exp_test = !exp_test;
2267 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2268 exp_null ? "true" : "false", exp_test);
2270 if (exp_op == '?') {
2271 //TODO: how interactive bash aborts expansion mid-command?
2272 /* ${var?[error_msg_if_unset]} */
2273 /* ${var:?[error_msg_if_unset_or_null]} */
2274 /* mimic bash message */
2275 die_if_script("%s: %s",
2277 exp_word[0] ? exp_word : "parameter null or not set"
2283 if (exp_op == '=') {
2284 /* ${var=[word]} or ${var:=[word]} */
2285 if (isdigit(var[0]) || var[0] == '#') {
2286 /* mimic bash message */
2287 die_if_script("$%s: cannot assign in this way", var);
2290 char *new_var = xasprintf("%s=%s", var, val);
2291 set_local_var(new_var, 0, 0);
2297 var[exp_off] = exp_save;
2301 #if ENABLE_HUSH_TICK
2304 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2305 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2307 /* unquoted var's contents should be globbed, so don't escape */
2308 smallint sv = output->o_escape;
2309 output->o_escape = 0;
2310 n = expand_on_ifs(output, n, val);
2312 output->o_escape = sv;
2314 } else { /* quoted $VAR, val will be appended below */
2315 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2318 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2321 o_addQstr(output, val, strlen(val));
2324 /* Do the check to avoid writing to a const string */
2325 if (*p != SPECIAL_VAR_SYMBOL)
2326 *p = SPECIAL_VAR_SYMBOL;
2328 #if ENABLE_HUSH_TICK
2329 o_free(&subst_result);
2332 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2335 debug_print_list("expand_vars_to_list[a]", output, n);
2336 /* this part is literal, and it was already pre-quoted
2337 * if needed (much earlier), do not use o_addQstr here! */
2338 o_addstr_with_NUL(output, arg);
2339 debug_print_list("expand_vars_to_list[b]", output, n);
2340 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2341 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2344 /* allow to reuse list[n] later without re-growth */
2345 output->has_empty_slot = 1;
2347 o_addchr(output, '\0');
2352 static char **expand_variables(char **argv, int or_mask)
2357 o_string output = NULL_O_STRING;
2359 if (or_mask & 0x100) {
2360 output.o_escape = 1; /* protect against globbing for "$var" */
2361 /* (unquoted $var will temporarily switch it off) */
2368 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2371 debug_print_list("expand_variables", &output, n);
2373 /* output.data (malloced in one block) gets returned in "list" */
2374 list = o_finalize_list(&output, n);
2375 debug_print_strings("expand_variables[1]", list);
2379 static char **expand_strvec_to_strvec(char **argv)
2381 return expand_variables(argv, 0x100);
2384 /* Used for expansion of right hand of assignments */
2385 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2387 static char *expand_string_to_string(const char *str)
2389 char *argv[2], **list;
2391 argv[0] = (char*)str;
2393 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2395 if (!list[0] || list[1])
2396 bb_error_msg_and_die("BUG in varexp2");
2397 /* actually, just move string 2*sizeof(char*) bytes back */
2398 overlapping_strcpy((char*)list, list[0]);
2399 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2403 /* Used for "eval" builtin */
2404 static char* expand_strvec_to_string(char **argv)
2408 list = expand_variables(argv, 0x80);
2409 /* Convert all NULs to spaces */
2414 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2415 bb_error_msg_and_die("BUG in varexp3");
2416 /* bash uses ' ' regardless of $IFS contents */
2421 overlapping_strcpy((char*)list, list[0]);
2422 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2426 static char **expand_assignments(char **argv, int count)
2430 /* Expand assignments into one string each */
2431 for (i = 0; i < count; i++) {
2432 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2440 void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
2442 static void reset_traps_to_defaults(void)
2444 /* This function is always called in a child shell
2445 * after fork (not vfork, NOMMU doesn't use this function).
2446 * Child shells are not interactive.
2447 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2448 * Testcase: (while :; do :; done) + ^Z should background.
2449 * Same goes for SIGTERM, SIGHUP, SIGINT.
2454 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2457 /* Stupid. It can be done with *single* &= op, but we can't use
2458 * the fact that G.blocked_set is implemented as a bitmask... */
2459 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2463 sigdelset(&G.blocked_set, sig);
2470 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2471 mask = G.non_DFL_mask;
2472 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2476 G.traps[sig] = NULL;
2477 /* There is no signal for 0 (EXIT) */
2480 /* There was a trap handler, we are removing it.
2481 * But if sig still has non-DFL handling,
2482 * we should not unblock it. */
2485 sigdelset(&G.blocked_set, sig);
2487 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2492 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2493 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
2495 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2496 char *heredoc_argv[4];
2497 struct variable *cur;
2498 #if ENABLE_HUSH_FUNCTIONS
2499 struct function *funcp;
2504 if (!g_argv0) { /* heredoc */
2505 argv = heredoc_argv;
2506 argv[0] = (char *) G.argv0_for_re_execing;
2507 argv[1] = (char *) "-<";
2508 argv[2] = (char *) s;
2510 pp = &argv[3]; /* used as pointer to empty environment */
2514 sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
2515 , (unsigned) G.root_pid
2516 , (unsigned) G.last_bg_pid
2517 , (unsigned) G.last_exitcode
2518 IF_HUSH_LOOPS(, G.depth_of_loop)
2520 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2521 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2524 for (cur = G.top_var; cur; cur = cur->next) {
2525 if (!cur->flg_export || cur->flg_read_only)
2528 #if ENABLE_HUSH_FUNCTIONS
2529 for (funcp = G.top_func; funcp; funcp = funcp->next)
2535 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2536 *pp++ = (char *) G.argv0_for_re_execing;
2538 for (cur = G.top_var; cur; cur = cur->next) {
2539 if (cur->varstr == hush_version_str)
2541 if (cur->flg_read_only) {
2542 *pp++ = (char *) "-R";
2543 *pp++ = cur->varstr;
2544 } else if (!cur->flg_export) {
2545 *pp++ = (char *) "-V";
2546 *pp++ = cur->varstr;
2549 #if ENABLE_HUSH_FUNCTIONS
2550 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2551 *pp++ = (char *) "-F";
2552 *pp++ = funcp->name;
2553 *pp++ = funcp->body_as_string;
2556 /* We can pass activated traps here. Say, -Tnn:trap_string
2558 * However, POSIX says that subshells reset signals with traps
2560 * I tested bash-3.2 and it not only does that with true subshells
2561 * of the form ( list ), but with any forked children shells.
2562 * I set trap "echo W" WINCH; and then tried:
2564 * { echo 1; sleep 20; echo 2; } &
2565 * while true; do echo 1; sleep 20; echo 2; break; done &
2566 * true | { echo 1; sleep 20; echo 2; } | cat
2568 * In all these cases sending SIGWINCH to the child shell
2569 * did not run the trap. If I add trap "echo V" WINCH;
2570 * _inside_ group (just before echo 1), it works.
2572 * I conclude it means we don't need to pass active traps here.
2573 * exec syscall below resets them to SIG_DFL for us.
2575 *pp++ = (char *) "-c";
2580 /* *pp = NULL; - is already there */
2584 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2585 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2586 execve(bb_busybox_exec_path, argv, pp);
2587 /* Fallback. Useful for init=/bin/hush usage etc */
2588 if (argv[0][0] == '/')
2589 execve(argv[0], argv, pp);
2590 xfunc_error_retval = 127;
2591 bb_error_msg_and_die("can't re-execute the shell");
2593 #endif /* !BB_MMU */
2596 static void setup_heredoc(struct redir_struct *redir)
2598 struct fd_pair pair;
2601 /* the _body_ of heredoc (misleading field name) */
2602 const char *heredoc = redir->rd_filename;
2609 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2610 expanded = expand_pseudo_dquoted(heredoc);
2614 len = strlen(heredoc);
2616 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2618 xmove_fd(pair.rd, redir->rd_fd);
2620 /* Try writing without forking. Newer kernels have
2621 * dynamically growing pipes. Must use non-blocking write! */
2624 written = write(pair.wr, heredoc, len);
2635 ndelay_off(pair.wr);
2637 /* Okay, pipe buffer was not big enough */
2638 /* Note: we must not create a stray child (bastard? :)
2639 * for the unsuspecting parent process. Child creates a grandchild
2640 * and exits before parent execs the process which consumes heredoc
2641 * (that exec happens after we return from this function) */
2647 bb_perror_msg_and_die("vfork");
2650 disable_restore_tty_pgrp_on_exit();
2651 pid = BB_MMU ? fork() : vfork();
2653 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2657 close(redir->rd_fd); /* read side of the pipe */
2659 full_write(pair.wr, heredoc, len); /* may loop or block */
2662 /* Delegate blocking writes to another process */
2663 xmove_fd(pair.wr, STDOUT_FILENO);
2664 re_execute_shell(&to_free, heredoc, NULL, NULL);
2668 enable_restore_tty_pgrp_on_exit();
2674 wait(NULL); /* wait till child has died */
2677 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2678 * and stderr if they are redirected. */
2679 static int setup_redirects(struct command *prog, int squirrel[])
2682 struct redir_struct *redir;
2684 for (redir = prog->redirects; redir; redir = redir->next) {
2685 if (redir->rd_type == REDIRECT_HEREDOC2) {
2686 /* rd_fd<<HERE case */
2687 if (squirrel && redir->rd_fd < 3
2688 && squirrel[redir->rd_fd] < 0
2690 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2692 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2694 debug_printf_parse("set heredoc '%s'\n",
2695 redir->rd_filename);
2696 setup_heredoc(redir);
2700 if (redir->rd_dup == REDIRFD_TO_FILE) {
2701 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2703 if (redir->rd_filename == NULL) {
2704 /* Something went wrong in the parse.
2705 * Pretend it didn't happen */
2706 bb_error_msg("bug in redirect parse");
2709 mode = redir_table[redir->rd_type].mode;
2710 p = expand_string_to_string(redir->rd_filename);
2711 openfd = open_or_warn(p, mode);
2714 /* this could get lost if stderr has been redirected, but
2715 * bash and ash both lose it as well (though zsh doesn't!) */
2716 //what the above comment tries to say?
2720 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2721 openfd = redir->rd_dup;
2724 if (openfd != redir->rd_fd) {
2725 if (squirrel && redir->rd_fd < 3
2726 && squirrel[redir->rd_fd] < 0
2728 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2730 if (openfd == REDIRFD_CLOSE) {
2731 /* "n>-" means "close me" */
2732 close(redir->rd_fd);
2734 xdup2(openfd, redir->rd_fd);
2735 if (redir->rd_dup == REDIRFD_TO_FILE)
2743 static void restore_redirects(int squirrel[])
2746 for (i = 0; i < 3; i++) {
2749 /* We simply die on error */
2756 static void free_pipe_list(struct pipe *head);
2758 /* Return code is the exit status of the pipe */
2759 static void free_pipe(struct pipe *pi)
2762 struct command *command;
2763 struct redir_struct *r, *rnext;
2766 if (pi->stopped_cmds > 0) /* why? */
2768 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2769 for (i = 0; i < pi->num_cmds; i++) {
2770 command = &pi->cmds[i];
2771 debug_printf_clean(" command %d:\n", i);
2772 if (command->argv) {
2773 for (a = 0, p = command->argv; *p; a++, p++) {
2774 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2776 free_strings(command->argv);
2777 command->argv = NULL;
2779 /* not "else if": on syntax error, we may have both! */
2780 if (command->group) {
2781 debug_printf_clean(" begin group (grp_type:%d)\n",
2783 free_pipe_list(command->group);
2784 debug_printf_clean(" end group\n");
2785 command->group = NULL;
2787 /* else is crucial here.
2788 * If group != NULL, child_func is meaningless */
2789 #if ENABLE_HUSH_FUNCTIONS
2790 else if (command->child_func) {
2791 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2792 command->child_func->parent_cmd = NULL;
2796 free(command->group_as_string);
2797 command->group_as_string = NULL;
2799 for (r = command->redirects; r; r = rnext) {
2800 debug_printf_clean(" redirect %d%s",
2801 r->rd_fd, redir_table[r->rd_type].descrip);
2802 /* guard against the case >$FOO, where foo is unset or blank */
2803 if (r->rd_filename) {
2804 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2805 free(r->rd_filename);
2806 r->rd_filename = NULL;
2808 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2812 command->redirects = NULL;
2814 free(pi->cmds); /* children are an array, they get freed all at once */
2822 static void free_pipe_list(struct pipe *head)
2824 struct pipe *pi, *next;
2826 for (pi = head; pi; pi = next) {
2828 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2831 debug_printf_clean("pipe followup code %d\n", pi->followup);
2833 /*pi->next = NULL;*/
2839 static int run_list(struct pipe *pi);
2841 #define parse_stream(pstring, input, end_trigger) \
2842 parse_stream(input, end_trigger)
2844 static struct pipe *parse_stream(char **pstring,
2845 struct in_str *input,
2847 static void parse_and_run_string(const char *s);
2850 static const struct built_in_command* find_builtin(const char *name)
2852 const struct built_in_command *x;
2853 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2854 if (strcmp(name, x->cmd) != 0)
2856 debug_printf_exec("found builtin '%s'\n", name);
2862 #if ENABLE_HUSH_FUNCTIONS
2863 static const struct function *find_function(const char *name)
2865 const struct function *funcp = G.top_func;
2867 if (strcmp(name, funcp->name) == 0) {
2870 funcp = funcp->next;
2873 debug_printf_exec("found function '%s'\n", name);
2877 /* Note: takes ownership on name ptr */
2878 static struct function *new_function(char *name)
2880 struct function *funcp;
2881 struct function **funcpp = &G.top_func;
2883 while ((funcp = *funcpp) != NULL) {
2884 struct command *cmd;
2886 if (strcmp(funcp->name, name) != 0) {
2887 funcpp = &funcp->next;
2891 cmd = funcp->parent_cmd;
2892 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2894 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2896 /* Note: if !funcp->body, do not free body_as_string!
2897 * This is a special case of "-F name body" function:
2898 * body_as_string was not malloced! */
2900 free_pipe_list(funcp->body);
2902 free(funcp->body_as_string);
2906 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2907 cmd->argv[0] = funcp->name;
2908 cmd->group = funcp->body;
2910 cmd->group_as_string = funcp->body_as_string;
2915 debug_printf_exec("remembering new function '%s'\n", name);
2916 funcp = *funcpp = xzalloc(sizeof(*funcp));
2917 /*funcp->next = NULL;*/
2923 static void unset_func(const char *name)
2925 struct function *funcp;
2926 struct function **funcpp = &G.top_func;
2928 while ((funcp = *funcpp) != NULL) {
2929 if (strcmp(funcp->name, name) == 0) {
2930 *funcpp = funcp->next;
2931 /* funcp is unlinked now, deleting it.
2932 * Note: if !funcp->body, the function was created by
2933 * "-F name body", do not free ->body_as_string
2934 * and ->name as they were not malloced. */
2936 free_pipe_list(funcp->body);
2939 free(funcp->body_as_string);
2945 funcpp = &funcp->next;
2950 #define exec_function(nommu_save, funcp, argv) \
2951 exec_function(funcp, argv)
2953 static void exec_function(nommu_save_t *nommu_save,
2954 const struct function *funcp,
2955 char **argv) NORETURN;
2956 static void exec_function(nommu_save_t *nommu_save,
2957 const struct function *funcp,
2963 argv[0] = G.global_argv[0];
2964 G.global_argv = argv;
2968 /* On MMU, funcp->body is always non-NULL */
2969 n = run_list(funcp->body);
2973 re_execute_shell(&nommu_save->argv_from_re_execing,
2974 funcp->body_as_string,
2980 static int run_function(const struct function *funcp, char **argv)
2986 save_and_replace_G_args(&sv, argv);
2987 /* "we are in function, ok to use return" */
2988 sv_flg = G.flag_return_in_progress;
2989 G.flag_return_in_progress = -1;
2991 /* On MMU, funcp->body is always non-NULL */
2994 /* Function defined by -F */
2995 parse_and_run_string(funcp->body_as_string);
2996 rc = G.last_exitcode;
3000 rc = run_list(funcp->body);
3003 G.flag_return_in_progress = sv_flg;
3004 restore_G_args(&sv, argv);
3008 #endif /* ENABLE_HUSH_FUNCTIONS */
3012 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3013 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3014 #define pseudo_exec(nommu_save, command, argv_expanded) \
3015 pseudo_exec(command, argv_expanded)
3018 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3020 * Don't exit() here. If you don't exec, use _exit instead.
3021 * The at_exit handlers apparently confuse the calling process,
3022 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3023 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3024 char **argv, int assignment_cnt,
3025 char **argv_expanded) NORETURN;
3026 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3027 char **argv, int assignment_cnt,
3028 char **argv_expanded)
3032 /* Case when we are here: ... | var=val | ... */
3033 if (!argv[assignment_cnt])
3034 _exit(EXIT_SUCCESS);
3036 new_env = expand_assignments(argv, assignment_cnt);
3038 set_vars_and_save_old(new_env);
3039 free(new_env); /* optional */
3040 /* we can also destroy set_vars_and_save_old's return value,
3043 nommu_save->new_env = new_env;
3044 nommu_save->old_vars = set_vars_and_save_old(new_env);
3046 if (argv_expanded) {
3047 argv = argv_expanded;
3049 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3051 nommu_save->argv = argv;
3055 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3056 if (strchr(argv[0], '/') != NULL)
3060 /* On NOMMU, we must never block!
3061 * Example: { sleep 99999 | read line } & echo Ok
3062 * read builtin will block on read syscall, leaving parent blocked
3063 * in vfork. Therefore we can't do this:
3066 /* Check if the command matches any of the builtins.
3067 * Depending on context, this might be redundant. But it's
3068 * easier to waste a few CPU cycles than it is to figure out
3069 * if this is one of those cases.
3073 const struct built_in_command *x = find_builtin(argv[0]);
3075 rcode = x->function(argv);
3081 #if ENABLE_HUSH_FUNCTIONS
3082 /* Check if the command matches any functions */
3084 const struct function *funcp = find_function(argv[0]);
3086 exec_function(nommu_save, funcp, argv);
3091 #if ENABLE_FEATURE_SH_STANDALONE
3092 /* Check if the command matches any busybox applets */
3094 int a = find_applet_by_name(argv[0]);
3096 # if BB_MMU /* see above why on NOMMU it is not allowed */
3097 if (APPLET_IS_NOEXEC(a)) {
3098 debug_printf_exec("running applet '%s'\n", argv[0]);
3099 run_applet_no_and_exit(a, argv);
3102 /* Re-exec ourselves */
3103 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3104 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3105 execv(bb_busybox_exec_path, argv);
3106 /* If they called chroot or otherwise made the binary no longer
3107 * executable, fall through */
3112 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3115 debug_printf_exec("execing '%s'\n", argv[0]);
3116 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3117 execvp(argv[0], argv);
3118 bb_perror_msg("can't execute '%s'", argv[0]);
3119 _exit(EXIT_FAILURE);
3122 /* Called after [v]fork() in run_pipe
3124 static void pseudo_exec(nommu_save_t *nommu_save,
3125 struct command *command,
3126 char **argv_expanded) NORETURN;
3127 static void pseudo_exec(nommu_save_t *nommu_save,
3128 struct command *command,
3129 char **argv_expanded)
3131 if (command->argv) {
3132 pseudo_exec_argv(nommu_save, command->argv,
3133 command->assignment_cnt, argv_expanded);
3136 if (command->group) {
3137 /* Cases when we are here:
3140 * ... | ( list ) | ...
3141 * ... | { list } | ...
3145 debug_printf_exec("pseudo_exec: run_list\n");
3146 reset_traps_to_defaults();
3147 rcode = run_list(command->group);
3148 /* OK to leak memory by not calling free_pipe_list,
3149 * since this process is about to exit */
3152 re_execute_shell(&nommu_save->argv_from_re_execing,
3153 command->group_as_string,
3159 /* Case when we are here: ... | >file */
3160 debug_printf_exec("pseudo_exec'ed null command\n");
3161 _exit(EXIT_SUCCESS);
3165 static const char *get_cmdtext(struct pipe *pi)
3171 /* This is subtle. ->cmdtext is created only on first backgrounding.
3172 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3173 * On subsequent bg argv is trashed, but we won't use it */
3176 argv = pi->cmds[0].argv;
3177 if (!argv || !argv[0]) {
3178 pi->cmdtext = xzalloc(1);
3184 len += strlen(*argv) + 1;
3188 argv = pi->cmds[0].argv;
3190 len = strlen(*argv);
3191 memcpy(p, *argv, len);
3199 static void insert_bg_job(struct pipe *pi)
3201 struct pipe *job, **jobp;
3204 /* Linear search for the ID of the job to use */
3206 for (job = G.job_list; job; job = job->next)
3207 if (job->jobid >= pi->jobid)
3208 pi->jobid = job->jobid + 1;
3210 /* Add job to the list of running jobs */
3212 while ((job = *jobp) != NULL)
3214 job = *jobp = xmalloc(sizeof(*job));
3216 *job = *pi; /* physical copy */
3218 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3219 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3220 for (i = 0; i < pi->num_cmds; i++) {
3221 job->cmds[i].pid = pi->cmds[i].pid;
3222 /* all other fields are not used and stay zero */
3224 job->cmdtext = xstrdup(get_cmdtext(pi));
3226 if (G_interactive_fd)
3227 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3228 /* Last command's pid goes to $! */
3229 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3230 G.last_jobid = job->jobid;
3233 static void remove_bg_job(struct pipe *pi)
3235 struct pipe *prev_pipe;
3237 if (pi == G.job_list) {
3238 G.job_list = pi->next;
3240 prev_pipe = G.job_list;
3241 while (prev_pipe->next != pi)
3242 prev_pipe = prev_pipe->next;
3243 prev_pipe->next = pi->next;
3246 G.last_jobid = G.job_list->jobid;
3251 /* Remove a backgrounded job */
3252 static void delete_finished_bg_job(struct pipe *pi)
3255 pi->stopped_cmds = 0;
3261 /* Check to see if any processes have exited -- if they
3262 * have, figure out why and see if a job has completed */
3263 static int checkjobs(struct pipe* fg_pipe)
3273 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3276 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
3277 // /* avoid doing syscall, nothing there anyway */
3280 attributes = WUNTRACED;
3281 if (fg_pipe == NULL)
3282 attributes |= WNOHANG;
3284 /* Do we do this right?
3285 * bash-3.00# sleep 20 | false
3287 * [3]+ Stopped sleep 20 | false
3288 * bash-3.00# echo $?
3289 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3290 * [hush 1.14.0: yes we do it right]
3297 // i = G.count_SIGCHLD;
3298 childpid = waitpid(-1, &status, attributes);
3299 if (childpid <= 0) {
3300 if (childpid && errno != ECHILD)
3301 bb_perror_msg("waitpid");
3302 // else /* Until next SIGCHLD, waitpid's are useless */
3303 // G.handled_SIGCHLD = i;
3306 dead = WIFEXITED(status) || WIFSIGNALED(status);
3309 if (WIFSTOPPED(status))
3310 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3311 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3312 if (WIFSIGNALED(status))
3313 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3314 childpid, WTERMSIG(status), WEXITSTATUS(status));
3315 if (WIFEXITED(status))
3316 debug_printf_jobs("pid %d exited, exitcode %d\n",
3317 childpid, WEXITSTATUS(status));
3319 /* Were we asked to wait for fg pipe? */
3321 for (i = 0; i < fg_pipe->num_cmds; i++) {
3322 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3323 if (fg_pipe->cmds[i].pid != childpid)
3326 fg_pipe->cmds[i].pid = 0;
3327 fg_pipe->alive_cmds--;
3328 if (i == fg_pipe->num_cmds - 1) {
3329 /* last process gives overall exitstatus */
3330 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3331 rcode = WEXITSTATUS(status);
3332 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3333 /* bash prints killing signal's name for *last*
3334 * process in pipe (prints just newline for SIGINT).
3335 * Mimic this. Example: "sleep 5" + ^\
3337 if (WIFSIGNALED(status)) {
3338 int sig = WTERMSIG(status);
3339 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3343 fg_pipe->cmds[i].is_stopped = 1;
3344 fg_pipe->stopped_cmds++;
3346 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3347 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3348 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3349 /* All processes in fg pipe have exited or stopped */
3350 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3351 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3352 * and "killall -STOP cat" */
3353 if (G_interactive_fd) {
3355 if (fg_pipe->alive_cmds)
3356 insert_bg_job(fg_pipe);
3361 /* There are still running processes in the fg pipe */
3362 goto wait_more; /* do waitpid again */
3364 /* it wasnt fg_pipe, look for process in bg pipes */
3368 /* We asked to wait for bg or orphaned children */
3369 /* No need to remember exitcode in this case */
3370 for (pi = G.job_list; pi; pi = pi->next) {
3371 for (i = 0; i < pi->num_cmds; i++) {
3372 if (pi->cmds[i].pid == childpid)
3373 goto found_pi_and_prognum;
3376 /* Happens when shell is used as init process (init=/bin/sh) */
3377 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3378 continue; /* do waitpid again */
3380 found_pi_and_prognum:
3383 pi->cmds[i].pid = 0;
3385 if (!pi->alive_cmds) {
3386 if (G_interactive_fd)
3387 printf(JOB_STATUS_FORMAT, pi->jobid,
3388 "Done", pi->cmdtext);
3389 delete_finished_bg_job(pi);
3393 pi->cmds[i].is_stopped = 1;
3397 } /* while (waitpid succeeds)... */
3403 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3406 int rcode = checkjobs(fg_pipe);
3407 if (G_saved_tty_pgrp) {
3408 /* Job finished, move the shell to the foreground */
3409 p = getpgrp(); /* our process group id */
3410 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3411 tcsetpgrp(G_interactive_fd, p);
3417 /* Start all the jobs, but don't wait for anything to finish.
3420 * Return code is normally -1, when the caller has to wait for children
3421 * to finish to determine the exit status of the pipe. If the pipe
3422 * is a simple builtin command, however, the action is done by the
3423 * time run_pipe returns, and the exit code is provided as the
3426 * Returns -1 only if started some children. IOW: we have to
3427 * mask out retvals of builtins etc with 0xff!
3429 * The only case when we do not need to [v]fork is when the pipe
3430 * is single, non-backgrounded, non-subshell command. Examples:
3431 * cmd ; ... { list } ; ...
3432 * cmd && ... { list } && ...
3433 * cmd || ... { list } || ...
3434 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3435 * or (if SH_STANDALONE) an applet, and we can run the { list }
3436 * with run_list. If it isn't one of these, we fork and exec cmd.
3438 * Cases when we must fork:
3439 * non-single: cmd | cmd
3440 * backgrounded: cmd & { list } &
3441 * subshell: ( list ) [&]
3443 static int run_pipe(struct pipe *pi)
3445 static const char *const null_ptr = NULL;
3448 struct command *command;
3449 char **argv_expanded;
3452 /* it is not always needed, but we aim to smaller code */
3453 int squirrel[] = { -1, -1, -1 };
3456 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3459 IF_HUSH_JOB(pi->pgrp = -1;)
3460 pi->stopped_cmds = 0;
3461 command = &(pi->cmds[0]);
3462 argv_expanded = NULL;
3464 if (pi->num_cmds != 1
3465 || pi->followup == PIPE_BG
3466 || command->grp_type == GRP_SUBSHELL
3473 debug_printf_exec(": group:%p argv:'%s'\n",
3474 command->group, command->argv ? command->argv[0] : "NONE");
3476 if (command->group) {
3477 #if ENABLE_HUSH_FUNCTIONS
3478 if (command->grp_type == GRP_FUNCTION) {
3479 /* "executing" func () { list } */
3480 struct function *funcp;
3482 funcp = new_function(command->argv[0]);
3483 /* funcp->name is already set to argv[0] */
3484 funcp->body = command->group;
3486 funcp->body_as_string = command->group_as_string;
3487 command->group_as_string = NULL;
3489 command->group = NULL;
3490 command->argv[0] = NULL;
3491 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3492 funcp->parent_cmd = command;
3493 command->child_func = funcp;
3495 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3497 return EXIT_SUCCESS;
3501 debug_printf("non-subshell group\n");
3502 rcode = 1; /* exitcode if redir failed */
3503 if (setup_redirects(command, squirrel) == 0) {
3504 debug_printf_exec(": run_list\n");
3505 rcode = run_list(command->group) & 0xff;
3507 restore_redirects(squirrel);
3508 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3510 debug_printf_exec("run_pipe: return %d\n", rcode);
3514 argv = command->argv ? command->argv : (char **) &null_ptr;
3516 const struct built_in_command *x;
3517 #if ENABLE_HUSH_FUNCTIONS
3518 const struct function *funcp;
3522 char **new_env = NULL;
3523 struct variable *old_vars = NULL;
3525 if (argv[command->assignment_cnt] == NULL) {
3526 /* Assignments, but no command */
3527 /* Ensure redirects take effect. Try "a=t >file" */
3528 rcode = setup_redirects(command, squirrel);
3529 restore_redirects(squirrel);
3530 /* Set shell variables */
3532 p = expand_string_to_string(*argv);
3533 debug_printf_exec("set shell var:'%s'->'%s'\n",
3535 set_local_var(p, 0, 0);
3538 /* Do we need to flag set_local_var() errors?
3539 * "assignment to readonly var" and "putenv error"
3541 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3543 debug_printf_exec("run_pipe: return %d\n", rcode);
3547 /* Expand the rest into (possibly) many strings each */
3548 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3550 x = find_builtin(argv_expanded[0]);
3551 #if ENABLE_HUSH_FUNCTIONS
3554 funcp = find_function(argv_expanded[0]);
3558 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3559 debug_printf("exec with redirects only\n");
3560 rcode = setup_redirects(command, NULL);
3561 goto clean_up_and_ret1;
3564 /* setup_redirects acts on file descriptors, not FILEs.
3565 * This is perfect for work that comes after exec().
3566 * Is it really safe for inline use? Experimentally,
3567 * things seem to work. */
3568 rcode = setup_redirects(command, squirrel);
3570 new_env = expand_assignments(argv, command->assignment_cnt);
3571 old_vars = set_vars_and_save_old(new_env);
3573 debug_printf_exec(": builtin '%s' '%s'...\n",
3574 x->cmd, argv_expanded[1]);
3575 rcode = x->function(argv_expanded) & 0xff;
3578 #if ENABLE_HUSH_FUNCTIONS
3580 debug_printf_exec(": function '%s' '%s'...\n",
3581 funcp->name, argv_expanded[1]);
3582 rcode = run_function(funcp, argv_expanded) & 0xff;
3586 #if ENABLE_FEATURE_SH_STANDALONE
3589 restore_redirects(squirrel);
3590 unset_vars(new_env);
3593 free(argv_expanded);
3594 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3596 debug_printf_exec("run_pipe return %d\n", rcode);
3600 #if ENABLE_FEATURE_SH_STANDALONE
3601 i = find_applet_by_name(argv_expanded[0]);
3602 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3603 rcode = setup_redirects(command, squirrel);
3605 new_env = expand_assignments(argv, command->assignment_cnt);
3606 old_vars = set_vars_and_save_old(new_env);
3607 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3608 argv_expanded[0], argv_expanded[1]);
3609 rcode = run_nofork_applet(i, argv_expanded);
3611 goto clean_up_and_ret;
3614 /* It is neither builtin nor applet. We must fork. */
3618 /* NB: argv_expanded may already be created, and that
3619 * might include `cmd` runs! Do not rerun it! We *must*
3620 * use argv_expanded if it's non-NULL */
3622 /* Going to fork a child per each pipe member */
3626 for (i = 0; i < pi->num_cmds; i++) {
3627 struct fd_pair pipefds;
3629 volatile nommu_save_t nommu_save;
3630 nommu_save.new_env = NULL;
3631 nommu_save.old_vars = NULL;
3632 nommu_save.argv = NULL;
3633 nommu_save.argv_from_re_execing = NULL;
3635 command = &(pi->cmds[i]);
3636 if (command->argv) {
3637 debug_printf_exec(": pipe member '%s' '%s'...\n",
3638 command->argv[0], command->argv[1]);
3640 debug_printf_exec(": pipe member with no argv\n");
3643 /* pipes are inserted between pairs of commands */
3646 if ((i + 1) < pi->num_cmds)
3647 xpiped_pair(pipefds);
3649 command->pid = BB_MMU ? fork() : vfork();
3650 if (!command->pid) { /* child */
3652 disable_restore_tty_pgrp_on_exit();
3654 /* Every child adds itself to new process group
3655 * with pgid == pid_of_first_child_in_pipe */
3656 if (G.run_list_level == 1 && G_interactive_fd) {
3659 if (pgrp < 0) /* true for 1st process only */
3661 if (setpgid(0, pgrp) == 0
3662 && pi->followup != PIPE_BG
3663 && G_saved_tty_pgrp /* we have ctty */
3665 /* We do it in *every* child, not just first,
3667 tcsetpgrp(G_interactive_fd, pgrp);
3671 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3672 /* 1st cmd in backgrounded pipe
3673 * should have its stdin /dev/null'ed */
3675 if (open(bb_dev_null, O_RDONLY))
3676 xopen("/", O_RDONLY);
3678 xmove_fd(nextin, 0);
3680 xmove_fd(pipefds.wr, 1);
3683 /* Like bash, explicit redirects override pipes,
3684 * and the pipe fd is available for dup'ing. */
3685 if (setup_redirects(command, NULL))
3688 /* Restore default handlers just prior to exec */
3689 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3691 /* Stores to nommu_save list of env vars putenv'ed
3692 * (NOMMU, on MMU we don't need that) */
3693 /* cast away volatility... */
3694 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3695 /* pseudo_exec() does not return */
3698 /* parent or error */
3699 enable_restore_tty_pgrp_on_exit();
3701 /* Clean up after vforked child */
3702 free(nommu_save.argv);
3703 free(nommu_save.argv_from_re_execing);
3704 unset_vars(nommu_save.new_env);
3705 add_vars(nommu_save.old_vars);
3707 free(argv_expanded);
3708 argv_expanded = NULL;
3709 if (command->pid < 0) { /* [v]fork failed */
3710 /* Clearly indicate, was it fork or vfork */
3711 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3715 /* Second and next children need to know pid of first one */
3717 pi->pgrp = command->pid;
3723 if ((i + 1) < pi->num_cmds)
3725 /* Pass read (output) pipe end to next iteration */
3726 nextin = pipefds.rd;
3729 if (!pi->alive_cmds) {
3731 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3736 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3740 #ifndef debug_print_tree
3741 static void debug_print_tree(struct pipe *pi, int lvl)
3743 static const char *const PIPE[] = {
3749 static const char *RES[] = {
3750 [RES_NONE ] = "NONE" ,
3753 [RES_THEN ] = "THEN" ,
3754 [RES_ELIF ] = "ELIF" ,
3755 [RES_ELSE ] = "ELSE" ,
3758 #if ENABLE_HUSH_LOOPS
3759 [RES_FOR ] = "FOR" ,
3760 [RES_WHILE] = "WHILE",
3761 [RES_UNTIL] = "UNTIL",
3763 [RES_DONE ] = "DONE" ,
3765 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3768 #if ENABLE_HUSH_CASE
3769 [RES_CASE ] = "CASE" ,
3770 [RES_CASE_IN ] = "CASE_IN" ,
3771 [RES_MATCH] = "MATCH",
3772 [RES_CASE_BODY] = "CASE_BODY",
3773 [RES_ESAC ] = "ESAC" ,
3775 [RES_XXXX ] = "XXXX" ,
3776 [RES_SNTX ] = "SNTX" ,
3778 static const char *const GRPTYPE[] = {
3781 #if ENABLE_HUSH_FUNCTIONS
3790 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3791 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3793 while (prn < pi->num_cmds) {
3794 struct command *command = &pi->cmds[prn];
3795 char **argv = command->argv;
3797 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3799 command->assignment_cnt);
3800 if (command->group) {
3801 fprintf(stderr, " group %s: (argv=%p)\n",
3802 GRPTYPE[command->grp_type],
3804 debug_print_tree(command->group, lvl+1);
3808 if (argv) while (*argv) {
3809 fprintf(stderr, " '%s'", *argv);
3812 fprintf(stderr, "\n");
3821 /* NB: called by pseudo_exec, and therefore must not modify any
3822 * global data until exec/_exit (we can be a child after vfork!) */
3823 static int run_list(struct pipe *pi)
3825 #if ENABLE_HUSH_CASE
3826 char *case_word = NULL;
3828 #if ENABLE_HUSH_LOOPS
3829 struct pipe *loop_top = NULL;
3830 char *for_varname = NULL;
3831 char **for_lcur = NULL;
3832 char **for_list = NULL;
3834 smallint last_followup;
3836 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3837 smalluint cond_code = 0;
3839 enum { cond_code = 0 };
3842 smallint rword; /* enum reserved_style */
3843 smallint last_rword; /* ditto */
3846 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
3849 #if ENABLE_HUSH_LOOPS
3850 /* Check syntax for "for" */
3851 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3852 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3854 /* current word is FOR or IN (BOLD in comments below) */
3855 if (cpipe->next == NULL) {
3856 syntax_error("malformed for");
3858 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3861 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3862 if (cpipe->next->res_word == RES_DO)
3864 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3865 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3866 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3868 syntax_error("malformed for");
3870 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3876 /* Past this point, all code paths should jump to ret: label
3877 * in order to return, no direct "return" statements please.
3878 * This helps to ensure that no memory is leaked. */
3886 last_rword = RES_XXXX;
3888 last_followup = PIPE_SEQ;
3889 rcode = G.last_exitcode;
3891 /* Go through list of pipes, (maybe) executing them. */
3892 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3896 IF_HAS_KEYWORDS(rword = pi->res_word;)
3897 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3898 rword, cond_code, last_rword);
3899 #if ENABLE_HUSH_LOOPS
3900 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3901 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3903 /* start of a loop: remember where loop starts */
3908 /* Still in the same "if...", "then..." or "do..." branch? */
3909 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3910 if ((rcode == 0 && last_followup == PIPE_OR)
3911 || (rcode != 0 && last_followup == PIPE_AND)
3913 /* It is "<true> || CMD" or "<false> && CMD"
3914 * and we should not execute CMD */
3915 debug_printf_exec("skipped cmd because of || or &&\n");
3916 last_followup = pi->followup;
3920 last_followup = pi->followup;
3921 IF_HAS_KEYWORDS(last_rword = rword;)
3924 if (rword == RES_THEN) {
3925 /* if false; then ... fi has exitcode 0! */
3926 G.last_exitcode = rcode = EXIT_SUCCESS;
3927 /* "if <false> THEN cmd": skip cmd */
3931 if (rword == RES_ELSE || rword == RES_ELIF) {
3932 /* "if <true> then ... ELSE/ELIF cmd":
3933 * skip cmd and all following ones */
3938 #if ENABLE_HUSH_LOOPS
3939 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3941 /* first loop through for */
3943 static const char encoded_dollar_at[] ALIGN1 = {
3944 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3945 }; /* encoded representation of "$@" */
3946 static const char *const encoded_dollar_at_argv[] = {
3947 encoded_dollar_at, NULL
3948 }; /* argv list with one element: "$@" */
3951 vals = (char**)encoded_dollar_at_argv;
3952 if (pi->next->res_word == RES_IN) {
3953 /* if no variable values after "in" we skip "for" */
3954 if (!pi->next->cmds[0].argv) {
3955 G.last_exitcode = rcode = EXIT_SUCCESS;
3956 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3959 vals = pi->next->cmds[0].argv;
3960 } /* else: "for var; do..." -> assume "$@" list */
3961 /* create list of variable values */
3962 debug_print_strings("for_list made from", vals);
3963 for_list = expand_strvec_to_strvec(vals);
3964 for_lcur = for_list;
3965 debug_print_strings("for_list", for_list);
3966 for_varname = pi->cmds[0].argv[0];
3967 pi->cmds[0].argv[0] = NULL;
3969 free(pi->cmds[0].argv[0]);
3971 /* "for" loop is over, clean up */
3975 pi->cmds[0].argv[0] = for_varname;
3978 /* Insert next value from for_lcur */
3979 /* note: *for_lcur already has quotes removed, $var expanded, etc */
3980 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3981 pi->cmds[0].assignment_cnt = 1;
3983 if (rword == RES_IN) {
3984 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3986 if (rword == RES_DONE) {
3987 continue; /* "done" has no cmds too */
3990 #if ENABLE_HUSH_CASE
3991 if (rword == RES_CASE) {
3992 case_word = expand_strvec_to_string(pi->cmds->argv);
3995 if (rword == RES_MATCH) {
3998 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4000 /* all prev words didn't match, does this one match? */
4001 argv = pi->cmds->argv;
4003 char *pattern = expand_string_to_string(*argv);
4004 /* TODO: which FNM_xxx flags to use? */
4005 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4007 if (cond_code == 0) { /* match! we will execute this branch */
4008 free(case_word); /* make future "word)" stop */
4016 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4018 continue; /* not matched yet, skip this pipe */
4021 /* Just pressing <enter> in shell should check for jobs.
4022 * OTOH, in non-interactive shell this is useless
4023 * and only leads to extra job checks */
4024 if (pi->num_cmds == 0) {
4025 if (G_interactive_fd)
4026 goto check_jobs_and_continue;
4030 /* After analyzing all keywords and conditions, we decided
4031 * to execute this pipe. NB: have to do checkjobs(NULL)
4032 * after run_pipe to collect any background children,
4033 * even if list execution is to be stopped. */
4034 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4037 #if ENABLE_HUSH_LOOPS
4038 G.flag_break_continue = 0;
4040 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4042 /* We ran a builtin, function, or group.
4043 * rcode is already known
4044 * and we don't need to wait for anything. */
4045 G.last_exitcode = rcode;
4046 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4047 check_and_run_traps(0);
4048 #if ENABLE_HUSH_LOOPS
4049 /* Was it "break" or "continue"? */
4050 if (G.flag_break_continue) {
4051 smallint fbc = G.flag_break_continue;
4052 /* We might fall into outer *loop*,
4053 * don't want to break it too */
4055 G.depth_break_continue--;
4056 if (G.depth_break_continue == 0)
4057 G.flag_break_continue = 0;
4058 /* else: e.g. "continue 2" should *break* once, *then* continue */
4059 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4060 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4061 goto check_jobs_and_break;
4062 /* "continue": simulate end of loop */
4067 #if ENABLE_HUSH_FUNCTIONS
4068 if (G.flag_return_in_progress == 1)
4069 goto check_jobs_and_break;
4071 } else if (pi->followup == PIPE_BG) {
4072 /* What does bash do with attempts to background builtins? */
4073 /* even bash 3.2 doesn't do that well with nested bg:
4074 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4075 * I'm NOT treating inner &'s as jobs */
4076 check_and_run_traps(0);
4078 if (G.run_list_level == 1)
4081 G.last_exitcode = rcode = EXIT_SUCCESS;
4082 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4085 if (G.run_list_level == 1 && G_interactive_fd) {
4086 /* Waits for completion, then fg's main shell */
4087 rcode = checkjobs_and_fg_shell(pi);
4088 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4089 check_and_run_traps(0);
4092 { /* This one just waits for completion */
4093 rcode = checkjobs(pi);
4094 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4095 check_and_run_traps(0);
4097 G.last_exitcode = rcode;
4101 /* Analyze how result affects subsequent commands */
4103 if (rword == RES_IF || rword == RES_ELIF)
4106 #if ENABLE_HUSH_LOOPS
4107 /* Beware of "while false; true; do ..."! */
4108 if (pi->next && pi->next->res_word == RES_DO) {
4109 if (rword == RES_WHILE) {
4111 /* "while false; do...done" - exitcode 0 */
4112 G.last_exitcode = rcode = EXIT_SUCCESS;
4113 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4114 goto check_jobs_and_break;
4117 if (rword == RES_UNTIL) {
4119 debug_printf_exec(": until expr is true: breaking\n");
4120 check_jobs_and_break:
4128 check_jobs_and_continue:
4135 #if ENABLE_HUSH_LOOPS
4140 #if ENABLE_HUSH_CASE
4144 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4148 /* Select which version we will use */
4149 static int run_and_free_list(struct pipe *pi)
4152 debug_printf_exec("run_and_free_list entered\n");
4154 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4155 rcode = run_list(pi);
4157 /* free_pipe_list has the side effect of clearing memory.
4158 * In the long run that function can be merged with run_list,
4159 * but doing that now would hobble the debugging effort. */
4161 debug_printf_exec("run_and_free_list return %d\n", rcode);
4166 static struct pipe *new_pipe(void)
4169 pi = xzalloc(sizeof(struct pipe));
4170 /*pi->followup = 0; - deliberately invalid value */
4171 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4175 /* Command (member of a pipe) is complete, or we start a new pipe
4176 * if ctx->command is NULL.
4177 * No errors possible here.
4179 static int done_command(struct parse_context *ctx)
4181 /* The command is really already in the pipe structure, so
4182 * advance the pipe counter and make a new, null command. */
4183 struct pipe *pi = ctx->pipe;
4184 struct command *command = ctx->command;
4187 if (IS_NULL_CMD(command)) {
4188 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4192 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4193 //debug_print_tree(ctx->list_head, 20);
4195 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4198 /* Only real trickiness here is that the uncommitted
4199 * command structure is not counted in pi->num_cmds. */
4200 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4201 ctx->command = command = &pi->cmds[pi->num_cmds];
4203 memset(command, 0, sizeof(*command));
4204 return pi->num_cmds; /* used only for 0/nonzero check */
4207 static void done_pipe(struct parse_context *ctx, pipe_style type)
4211 debug_printf_parse("done_pipe entered, followup %d\n", type);
4212 /* Close previous command */
4213 not_null = done_command(ctx);
4214 ctx->pipe->followup = type;
4216 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4217 ctx->ctx_inverted = 0;
4218 ctx->pipe->res_word = ctx->ctx_res_w;
4221 /* Without this check, even just <enter> on command line generates
4222 * tree of three NOPs (!). Which is harmless but annoying.
4223 * IOW: it is safe to do it unconditionally. */
4226 || ctx->ctx_res_w == RES_FI
4228 #if ENABLE_HUSH_LOOPS
4229 || ctx->ctx_res_w == RES_DONE
4230 || ctx->ctx_res_w == RES_FOR
4231 || ctx->ctx_res_w == RES_IN
4233 #if ENABLE_HUSH_CASE
4234 || ctx->ctx_res_w == RES_ESAC
4238 debug_printf_parse("done_pipe: adding new pipe: "
4239 "not_null:%d ctx->ctx_res_w:%d\n",
4240 not_null, ctx->ctx_res_w);
4242 ctx->pipe->next = new_p;
4244 /* RES_THEN, RES_DO etc are "sticky" -
4245 * they remain set for pipes inside if/while.
4246 * This is used to control execution.
4247 * RES_FOR and RES_IN are NOT sticky (needed to support
4248 * cases where variable or value happens to match a keyword):
4250 #if ENABLE_HUSH_LOOPS
4251 if (ctx->ctx_res_w == RES_FOR
4252 || ctx->ctx_res_w == RES_IN)
4253 ctx->ctx_res_w = RES_NONE;
4255 #if ENABLE_HUSH_CASE
4256 if (ctx->ctx_res_w == RES_MATCH)
4257 ctx->ctx_res_w = RES_CASE_BODY;
4258 if (ctx->ctx_res_w == RES_CASE)
4259 ctx->ctx_res_w = RES_CASE_IN;
4261 ctx->command = NULL; /* trick done_command below */
4262 /* Create the memory for command, roughly:
4263 * ctx->pipe->cmds = new struct command;
4264 * ctx->command = &ctx->pipe->cmds[0];
4267 //debug_print_tree(ctx->list_head, 10);
4269 debug_printf_parse("done_pipe return\n");
4272 static void initialize_context(struct parse_context *ctx)
4274 memset(ctx, 0, sizeof(*ctx));
4275 ctx->pipe = ctx->list_head = new_pipe();
4276 /* Create the memory for command, roughly:
4277 * ctx->pipe->cmds = new struct command;
4278 * ctx->command = &ctx->pipe->cmds[0];
4283 /* If a reserved word is found and processed, parse context is modified
4284 * and 1 is returned.
4287 struct reserved_combo {
4290 unsigned char assignment_flag;
4294 FLAG_END = (1 << RES_NONE ),
4296 FLAG_IF = (1 << RES_IF ),
4297 FLAG_THEN = (1 << RES_THEN ),
4298 FLAG_ELIF = (1 << RES_ELIF ),
4299 FLAG_ELSE = (1 << RES_ELSE ),
4300 FLAG_FI = (1 << RES_FI ),
4302 #if ENABLE_HUSH_LOOPS
4303 FLAG_FOR = (1 << RES_FOR ),
4304 FLAG_WHILE = (1 << RES_WHILE),
4305 FLAG_UNTIL = (1 << RES_UNTIL),
4306 FLAG_DO = (1 << RES_DO ),
4307 FLAG_DONE = (1 << RES_DONE ),
4308 FLAG_IN = (1 << RES_IN ),
4310 #if ENABLE_HUSH_CASE
4311 FLAG_MATCH = (1 << RES_MATCH),
4312 FLAG_ESAC = (1 << RES_ESAC ),
4314 FLAG_START = (1 << RES_XXXX ),
4317 static const struct reserved_combo* match_reserved_word(o_string *word)
4319 /* Mostly a list of accepted follow-up reserved words.
4320 * FLAG_END means we are done with the sequence, and are ready
4321 * to turn the compound list into a command.
4322 * FLAG_START means the word must start a new compound list.
4324 static const struct reserved_combo reserved_list[] = {
4326 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4327 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4328 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4329 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4330 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4331 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4333 #if ENABLE_HUSH_LOOPS
4334 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4335 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4336 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4337 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4338 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4339 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4341 #if ENABLE_HUSH_CASE
4342 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4343 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4346 const struct reserved_combo *r;
4348 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4349 if (strcmp(word->data, r->literal) == 0)
4354 /* Return 0: not a keyword, 1: keyword
4356 static int reserved_word(o_string *word, struct parse_context *ctx)
4358 #if ENABLE_HUSH_CASE
4359 static const struct reserved_combo reserved_match = {
4360 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4363 const struct reserved_combo *r;
4367 r = match_reserved_word(word);
4371 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4372 #if ENABLE_HUSH_CASE
4373 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4374 /* "case word IN ..." - IN part starts first MATCH part */
4375 r = &reserved_match;
4378 if (r->flag == 0) { /* '!' */
4379 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4380 syntax_error("! ! command");
4381 ctx->ctx_res_w = RES_SNTX;
4383 ctx->ctx_inverted = 1;
4386 if (r->flag & FLAG_START) {
4387 struct parse_context *old;
4389 old = xmalloc(sizeof(*old));
4390 debug_printf_parse("push stack %p\n", old);
4391 *old = *ctx; /* physical copy */
4392 initialize_context(ctx);
4394 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4395 syntax_error_at(word->data);
4396 ctx->ctx_res_w = RES_SNTX;
4399 /* "{...} fi" is ok. "{...} if" is not
4401 * if { echo foo; } then { echo bar; } fi */
4402 if (ctx->command->group)
4403 done_pipe(ctx, PIPE_SEQ);
4406 ctx->ctx_res_w = r->res;
4407 ctx->old_flag = r->flag;
4408 word->o_assignment = r->assignment_flag;
4410 if (ctx->old_flag & FLAG_END) {
4411 struct parse_context *old;
4413 done_pipe(ctx, PIPE_SEQ);
4414 debug_printf_parse("pop stack %p\n", ctx->stack);
4416 old->command->group = ctx->list_head;
4417 old->command->grp_type = GRP_NORMAL;
4419 o_addstr(&old->as_string, ctx->as_string.data);
4420 o_free_unsafe(&ctx->as_string);
4421 old->command->group_as_string = xstrdup(old->as_string.data);
4422 debug_printf_parse("pop, remembering as:'%s'\n",
4423 old->command->group_as_string);
4425 *ctx = *old; /* physical copy */
4432 /* Word is complete, look at it and update parsing context.
4433 * Normal return is 0. Syntax errors return 1.
4434 * Note: on return, word is reset, but not o_free'd!
4436 static int done_word(o_string *word, struct parse_context *ctx)
4438 struct command *command = ctx->command;
4440 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4441 if (word->length == 0 && word->o_quoted == 0) {
4442 debug_printf_parse("done_word return 0: true null, ignored\n");
4446 if (ctx->pending_redirect) {
4447 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4448 * only if run as "bash", not "sh" */
4449 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4451 * ...the word that follows the redirection operator
4452 * shall be subjected to tilde expansion, parameter expansion,
4453 * command substitution, arithmetic expansion, and quote
4454 * removal. Pathname expansion shall not be performed
4455 * on the word by a non-interactive shell; an interactive
4456 * shell may perform it, but shall do so only when
4457 * the expansion would result in one word."
4459 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4460 /* Cater for >\file case:
4461 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4462 * Same with heredocs:
4463 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4465 unbackslash(ctx->pending_redirect->rd_filename);
4466 /* Is it <<"HEREDOC"? */
4467 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4470 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4472 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4473 ctx->pending_redirect = NULL;
4475 /* If this word wasn't an assignment, next ones definitely
4476 * can't be assignments. Even if they look like ones. */
4477 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4478 && word->o_assignment != WORD_IS_KEYWORD
4480 word->o_assignment = NOT_ASSIGNMENT;
4482 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4483 command->assignment_cnt++;
4484 word->o_assignment = MAYBE_ASSIGNMENT;
4488 # if ENABLE_HUSH_CASE
4489 if (ctx->ctx_dsemicolon
4490 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4492 /* already done when ctx_dsemicolon was set to 1: */
4493 /* ctx->ctx_res_w = RES_MATCH; */
4494 ctx->ctx_dsemicolon = 0;
4497 if (!command->argv /* if it's the first word... */
4498 # if ENABLE_HUSH_LOOPS
4499 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4500 && ctx->ctx_res_w != RES_IN
4502 # if ENABLE_HUSH_CASE
4503 && ctx->ctx_res_w != RES_CASE
4506 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4507 if (reserved_word(word, ctx)) {
4508 o_reset_to_empty_unquoted(word);
4509 debug_printf_parse("done_word return %d\n",
4510 (ctx->ctx_res_w == RES_SNTX));
4511 return (ctx->ctx_res_w == RES_SNTX);
4515 if (command->group) {
4516 /* "{ echo foo; } echo bar" - bad */
4517 syntax_error_at(word->data);
4518 debug_printf_parse("done_word return 1: syntax error, "
4519 "groups and arglists don't mix\n");
4522 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4523 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4524 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4525 /* (otherwise it's known to be not empty and is already safe) */
4527 /* exclude "$@" - it can expand to no word despite "" */
4528 char *p = word->data;
4529 while (p[0] == SPECIAL_VAR_SYMBOL
4530 && (p[1] & 0x7f) == '@'
4531 && p[2] == SPECIAL_VAR_SYMBOL
4535 if (p == word->data || p[0] != '\0') {
4536 /* saw no "$@", or not only "$@" but some
4537 * real text is there too */
4538 /* insert "empty variable" reference, this makes
4539 * e.g. "", $empty"" etc to not disappear */
4540 o_addchr(word, SPECIAL_VAR_SYMBOL);
4541 o_addchr(word, SPECIAL_VAR_SYMBOL);
4544 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4545 debug_print_strings("word appended to argv", command->argv);
4548 #if ENABLE_HUSH_LOOPS
4549 if (ctx->ctx_res_w == RES_FOR) {
4551 || !is_well_formed_var_name(command->argv[0], '\0')
4553 /* bash says just "not a valid identifier" */
4554 syntax_error("not a valid identifier in for");
4557 /* Force FOR to have just one word (variable name) */
4558 /* NB: basically, this makes hush see "for v in ..."
4559 * syntax as if it is "for v; in ...". FOR and IN become
4560 * two pipe structs in parse tree. */
4561 done_pipe(ctx, PIPE_SEQ);
4564 #if ENABLE_HUSH_CASE
4565 /* Force CASE to have just one word */
4566 if (ctx->ctx_res_w == RES_CASE) {
4567 done_pipe(ctx, PIPE_SEQ);
4571 o_reset_to_empty_unquoted(word);
4573 debug_printf_parse("done_word return 0\n");
4578 /* Peek ahead in the input to find out if we have a "&n" construct,
4579 * as in "2>&1", that represents duplicating a file descriptor.
4581 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4582 * REDIRFD_SYNTAX_ERR if syntax error,
4583 * REDIRFD_TO_FILE if no & was seen,
4584 * or the number found.
4587 #define parse_redir_right_fd(as_string, input) \
4588 parse_redir_right_fd(input)
4590 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4596 return REDIRFD_TO_FILE;
4598 ch = i_getch(input); /* get the & */
4599 nommu_addchr(as_string, ch);
4602 ch = i_getch(input);
4603 nommu_addchr(as_string, ch);
4604 return REDIRFD_CLOSE;
4608 while (ch != EOF && isdigit(ch)) {
4609 d = d*10 + (ch-'0');
4611 ch = i_getch(input);
4612 nommu_addchr(as_string, ch);
4617 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4619 bb_error_msg("ambiguous redirect");
4620 return REDIRFD_SYNTAX_ERR;
4623 /* Return code is 0 normal, 1 if a syntax error is detected
4625 static int parse_redirect(struct parse_context *ctx,
4628 struct in_str *input)
4630 struct command *command = ctx->command;
4631 struct redir_struct *redir;
4632 struct redir_struct **redirp;
4635 dup_num = REDIRFD_TO_FILE;
4636 if (style != REDIRECT_HEREDOC) {
4637 /* Check for a '>&1' type redirect */
4638 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4639 if (dup_num == REDIRFD_SYNTAX_ERR)
4642 int ch = i_peek(input);
4643 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4644 if (dup_num) { /* <<-... */
4645 ch = i_getch(input);
4646 nommu_addchr(&ctx->as_string, ch);
4651 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4652 int ch = i_peek(input);
4654 /* >|FILE redirect ("clobbering" >).
4655 * Since we do not support "set -o noclobber" yet,
4656 * >| and > are the same for now. Just eat |.
4658 ch = i_getch(input);
4659 nommu_addchr(&ctx->as_string, ch);
4663 /* Create a new redir_struct and append it to the linked list */
4664 redirp = &command->redirects;
4665 while ((redir = *redirp) != NULL) {
4666 redirp = &(redir->next);
4668 *redirp = redir = xzalloc(sizeof(*redir));
4669 /* redir->next = NULL; */
4670 /* redir->rd_filename = NULL; */
4671 redir->rd_type = style;
4672 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4674 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4675 redir_table[style].descrip);
4677 redir->rd_dup = dup_num;
4678 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4679 /* Erik had a check here that the file descriptor in question
4680 * is legit; I postpone that to "run time"
4681 * A "-" representation of "close me" shows up as a -3 here */
4682 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4683 redir->rd_fd, redir->rd_dup);
4685 /* Set ctx->pending_redirect, so we know what to do at the
4686 * end of the next parsed word. */
4687 ctx->pending_redirect = redir;
4692 /* If a redirect is immediately preceded by a number, that number is
4693 * supposed to tell which file descriptor to redirect. This routine
4694 * looks for such preceding numbers. In an ideal world this routine
4695 * needs to handle all the following classes of redirects...
4696 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4697 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4698 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4699 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4701 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4703 * ... If n is quoted, the number shall not be recognized as part of
4704 * the redirection expression. For example:
4706 * writes the character 2 into file a"
4707 * We are getting it right by setting ->o_quoted on any \<char>
4709 * A -1 return means no valid number was found,
4710 * the caller should use the appropriate default for this redirection.
4712 static int redirect_opt_num(o_string *o)
4716 if (o->data == NULL)
4718 num = bb_strtou(o->data, NULL, 10);
4719 if (errno || num < 0)
4721 o_reset_to_empty_unquoted(o);
4726 #define fetch_till_str(as_string, input, word, skip_tabs) \
4727 fetch_till_str(input, word, skip_tabs)
4729 static char *fetch_till_str(o_string *as_string,
4730 struct in_str *input,
4734 o_string heredoc = NULL_O_STRING;
4740 ch = i_getch(input);
4741 nommu_addchr(as_string, ch);
4743 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4744 heredoc.data[past_EOL] = '\0';
4745 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4746 return heredoc.data;
4749 o_addchr(&heredoc, ch);
4750 past_EOL = heredoc.length;
4753 ch = i_getch(input);
4754 nommu_addchr(as_string, ch);
4755 } while (skip_tabs && ch == '\t');
4756 } while (ch == '\n');
4759 o_free_unsafe(&heredoc);
4762 o_addchr(&heredoc, ch);
4763 nommu_addchr(as_string, ch);
4767 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4768 * and load them all. There should be exactly heredoc_cnt of them.
4770 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4772 struct pipe *pi = ctx->list_head;
4774 while (pi && heredoc_cnt) {
4776 struct command *cmd = pi->cmds;
4778 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4780 cmd->argv ? cmd->argv[0] : "NONE");
4781 for (i = 0; i < pi->num_cmds; i++) {
4782 struct redir_struct *redir = cmd->redirects;
4784 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4785 i, cmd->argv ? cmd->argv[0] : "NONE");
4787 if (redir->rd_type == REDIRECT_HEREDOC) {
4790 redir->rd_type = REDIRECT_HEREDOC2;
4791 /* redir->dup is (ab)used to indicate <<- */
4792 p = fetch_till_str(&ctx->as_string, input,
4793 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4795 syntax_error("unexpected EOF in here document");
4798 free(redir->rd_filename);
4799 redir->rd_filename = p;
4802 redir = redir->next;
4809 /* Should be 0. If it isn't, it's a parse error */
4811 bb_error_msg_and_die("heredoc BUG 2");
4817 #if ENABLE_HUSH_TICK
4818 static FILE *generate_stream_from_string(const char *s)
4821 int pid, channel[2];
4827 pid = BB_MMU ? fork() : vfork();
4829 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4831 if (pid == 0) { /* child */
4832 disable_restore_tty_pgrp_on_exit();
4833 /* Process substitution is not considered to be usual
4834 * 'command execution'.
4835 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4842 close(channel[0]); /* NB: close _first_, then move fd! */
4843 xmove_fd(channel[1], 1);
4844 /* Prevent it from trying to handle ctrl-z etc */
4845 IF_HUSH_JOB(G.run_list_level = 1;)
4847 reset_traps_to_defaults();
4848 parse_and_run_string(s);
4849 _exit(G.last_exitcode);
4851 /* We re-execute after vfork on NOMMU. This makes this script safe:
4852 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4853 * huge=`cat BIG` # was blocking here forever
4856 re_execute_shell(&to_free,
4864 enable_restore_tty_pgrp_on_exit();
4869 pf = fdopen(channel[0], "r");
4873 /* Return code is exit status of the process that is run. */
4874 static int process_command_subs(o_string *dest, const char *s)
4877 struct in_str pipe_str;
4880 pf = generate_stream_from_string(s);
4883 close_on_exec_on(fileno(pf));
4885 /* Now send results of command back into original context */
4886 setup_file_in_str(&pipe_str, pf);
4888 while ((ch = i_getch(&pipe_str)) != EOF) {
4894 o_addchr(dest, '\n');
4897 o_addQchr(dest, ch);
4900 debug_printf("done reading from pipe, pclose()ing\n");
4901 /* Note: we got EOF, and we just close the read end of the pipe.
4902 * We do not wait for the `cmd` child to terminate. bash and ash do.
4904 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4905 * `false`; echo $? - bash outputs "1"
4908 debug_printf("closed FILE from child. return 0\n");
4913 static int parse_group(o_string *dest, struct parse_context *ctx,
4914 struct in_str *input, int ch)
4916 /* dest contains characters seen prior to ( or {.
4917 * Typically it's empty, but for function defs,
4918 * it contains function name (without '()'). */
4919 struct pipe *pipe_list;
4921 struct command *command = ctx->command;
4923 debug_printf_parse("parse_group entered\n");
4924 #if ENABLE_HUSH_FUNCTIONS
4925 if (ch == '(' && !dest->o_quoted) {
4927 if (done_word(dest, ctx))
4930 goto skip; /* (... */
4931 if (command->argv[1]) { /* word word ... (... */
4932 syntax_error_unexpected_ch('(');
4935 /* it is "word(..." or "word (..." */
4937 ch = i_getch(input);
4938 while (ch == ' ' || ch == '\t');
4940 syntax_error_unexpected_ch(ch);
4943 nommu_addchr(&ctx->as_string, ch);
4945 ch = i_getch(input);
4946 while (ch == ' ' || ch == '\t' || ch == '\n');
4948 syntax_error_unexpected_ch(ch);
4951 nommu_addchr(&ctx->as_string, ch);
4952 command->grp_type = GRP_FUNCTION;
4956 if (command->argv /* word [word]{... */
4957 || dest->length /* word{... */
4958 || dest->o_quoted /* ""{... */
4961 debug_printf_parse("parse_group return 1: "
4962 "syntax error, groups and arglists don't mix\n");
4966 #if ENABLE_HUSH_FUNCTIONS
4972 command->grp_type = GRP_SUBSHELL;
4974 /* bash does not allow "{echo...", requires whitespace */
4975 ch = i_getch(input);
4976 if (ch != ' ' && ch != '\t' && ch != '\n') {
4977 syntax_error_unexpected_ch(ch);
4980 nommu_addchr(&ctx->as_string, ch);
4985 char *as_string = NULL;
4987 pipe_list = parse_stream(&as_string, input, endch);
4990 o_addstr(&ctx->as_string, as_string);
4992 /* empty ()/{} or parse error? */
4993 if (!pipe_list || pipe_list == ERR_PTR) {
4994 /* parse_stream already emitted error msg */
4998 debug_printf_parse("parse_group return 1: "
4999 "parse_stream returned %p\n", pipe_list);
5002 command->group = pipe_list;
5004 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5005 command->group_as_string = as_string;
5006 debug_printf_parse("end of group, remembering as:'%s'\n",
5007 command->group_as_string);
5010 debug_printf_parse("parse_group return 0\n");
5012 /* command remains "open", available for possible redirects */
5015 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5016 /* Subroutines for copying $(...) and `...` things */
5017 static void add_till_backquote(o_string *dest, struct in_str *input);
5019 static void add_till_single_quote(o_string *dest, struct in_str *input)
5022 int ch = i_getch(input);
5024 syntax_error_unterm_ch('\'');
5025 /*xfunc_die(); - redundant */
5032 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5033 static void add_till_double_quote(o_string *dest, struct in_str *input)
5036 int ch = i_getch(input);
5038 syntax_error_unterm_ch('"');
5039 /*xfunc_die(); - redundant */
5043 if (ch == '\\') { /* \x. Copy both chars. */
5045 ch = i_getch(input);
5049 add_till_backquote(dest, input);
5053 //if (ch == '$') ...
5056 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5058 * "Within the backquoted style of command substitution, backslash
5059 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5060 * The search for the matching backquote shall be satisfied by the first
5061 * backquote found without a preceding backslash; during this search,
5062 * if a non-escaped backquote is encountered within a shell comment,
5063 * a here-document, an embedded command substitution of the $(command)
5064 * form, or a quoted string, undefined results occur. A single-quoted
5065 * or double-quoted string that begins, but does not end, within the
5066 * "`...`" sequence produces undefined results."
5068 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5070 static void add_till_backquote(o_string *dest, struct in_str *input)
5073 int ch = i_getch(input);
5075 syntax_error_unterm_ch('`');
5076 /*xfunc_die(); - redundant */
5081 /* \x. Copy both chars unless it is \` */
5082 int ch2 = i_getch(input);
5084 syntax_error_unterm_ch('`');
5085 /*xfunc_die(); - redundant */
5087 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5094 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5095 * quoting and nested ()s.
5096 * "With the $(command) style of command substitution, all characters
5097 * following the open parenthesis to the matching closing parenthesis
5098 * constitute the command. Any valid shell script can be used for command,
5099 * except a script consisting solely of redirections which produces
5100 * unspecified results."
5102 * echo $(echo '(TEST)' BEST) (TEST) BEST
5103 * echo $(echo 'TEST)' BEST) TEST) BEST
5104 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5106 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5110 int ch = i_getch(input);
5112 syntax_error_unterm_ch(')');
5113 /*xfunc_die(); - redundant */
5121 if (i_peek(input) == ')') {
5129 add_till_single_quote(dest, input);
5134 add_till_double_quote(dest, input);
5139 /* \x. Copy verbatim. Important for \(, \) */
5140 ch = i_getch(input);
5142 syntax_error_unterm_ch(')');
5143 /*xfunc_die(); - redundant */
5150 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5152 /* Return code: 0 for OK, 1 for syntax error */
5154 #define handle_dollar(as_string, dest, input) \
5155 handle_dollar(dest, input)
5157 static int handle_dollar(o_string *as_string,
5159 struct in_str *input)
5162 int ch = i_peek(input); /* first character after the $ */
5163 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5165 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5167 ch = i_getch(input);
5168 nommu_addchr(as_string, ch);
5170 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5172 debug_printf_parse(": '%c'\n", ch);
5173 o_addchr(dest, ch | quote_mask);
5176 if (!isalnum(ch) && ch != '_')
5178 ch = i_getch(input);
5179 nommu_addchr(as_string, ch);
5181 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5182 } else if (isdigit(ch)) {
5184 ch = i_getch(input);
5185 nommu_addchr(as_string, ch);
5186 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5187 debug_printf_parse(": '%c'\n", ch);
5188 o_addchr(dest, ch | quote_mask);
5189 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5190 } else switch (ch) {
5192 case '!': /* last bg pid */
5193 case '?': /* last exit code */
5194 case '#': /* number of args */
5195 case '*': /* args */
5196 case '@': /* args */
5197 goto make_one_char_var;
5199 bool first_char, all_digits;
5201 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5202 ch = i_getch(input);
5203 nommu_addchr(as_string, ch);
5204 /* TODO: maybe someone will try to escape the '}' */
5209 ch = i_getch(input);
5210 nommu_addchr(as_string, ch);
5217 /* ${#var}: length of var contents */
5227 && ( (all_digits && !isdigit(ch))
5228 || (!all_digits && !isalnum(ch) && ch != '_')
5231 /* handle parameter expansions
5232 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5237 case ':': /* null modifier */
5238 if (expansion == 0) {
5239 debug_printf_parse(": null modifier\n");
5244 case '#': /* remove prefix */
5245 case '%': /* remove suffix */
5246 if (expansion == 0) {
5247 debug_printf_parse(": remove suffix/prefix\n");
5252 case '-': /* default value */
5253 case '=': /* assign default */
5254 case '+': /* alternative */
5255 case '?': /* error indicate */
5256 debug_printf_parse(": parameter expansion\n");
5261 syntax_error_unterm_str("${name}");
5262 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5267 debug_printf_parse(": '%c'\n", ch);
5268 o_addchr(dest, ch | quote_mask);
5272 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5275 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5280 ch = i_getch(input);
5281 nommu_addchr(as_string, ch);
5282 # if ENABLE_SH_MATH_SUPPORT
5283 if (i_peek(input) == '(') {
5284 ch = i_getch(input);
5285 nommu_addchr(as_string, ch);
5286 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5287 o_addchr(dest, /*quote_mask |*/ '+');
5291 add_till_closing_paren(dest, input, true);
5294 o_addstr(as_string, dest->data + pos);
5295 o_addchr(as_string, ')');
5296 o_addchr(as_string, ')');
5299 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5303 # if ENABLE_HUSH_TICK
5304 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5305 o_addchr(dest, quote_mask | '`');
5309 add_till_closing_paren(dest, input, false);
5312 o_addstr(as_string, dest->data + pos);
5313 o_addchr(as_string, '`');
5316 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5322 ch = i_getch(input);
5323 nommu_addchr(as_string, ch);
5325 if (isalnum(ch)) { /* it's $_name or $_123 */
5331 /* $_ Shell or shell script name; or last cmd name */
5332 /* $- Option flags set by set builtin or shell options (-i etc) */
5334 o_addQchr(dest, '$');
5336 debug_printf_parse("handle_dollar return 0\n");
5341 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5342 parse_stream_dquoted(dest, input, dquote_end)
5344 static int parse_stream_dquoted(o_string *as_string,
5346 struct in_str *input,
5353 ch = i_getch(input);
5355 nommu_addchr(as_string, ch);
5356 if (ch == dquote_end) { /* may be only '"' or EOF */
5357 if (dest->o_assignment == NOT_ASSIGNMENT)
5358 dest->o_escape ^= 1;
5359 debug_printf_parse("parse_stream_dquoted return 0\n");
5362 /* note: can't move it above ch == dquote_end check! */
5364 syntax_error_unterm_ch('"');
5365 /*xfunc_die(); - redundant */
5369 next = i_peek(input);
5371 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5372 ch, ch, dest->o_escape);
5375 syntax_error("\\<eof>");
5379 * "The backslash retains its special meaning [in "..."]
5380 * only when followed by one of the following characters:
5381 * $, `, ", \, or <newline>. A double quote may be quoted
5382 * within double quotes by preceding it with a backslash.
5384 if (strchr("$`\"\\\n", next) != NULL) {
5385 ch = i_getch(input);
5387 o_addqchr(dest, ch);
5388 nommu_addchr(as_string, ch);
5391 o_addqchr(dest, '\\');
5392 nommu_addchr(as_string, '\\');
5397 if (handle_dollar(as_string, dest, input) != 0) {
5398 debug_printf_parse("parse_stream_dquoted return 1: "
5399 "handle_dollar returned non-0\n");
5404 #if ENABLE_HUSH_TICK
5406 //int pos = dest->length;
5407 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5408 o_addchr(dest, 0x80 | '`');
5409 add_till_backquote(dest, input);
5410 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5411 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5415 o_addQchr(dest, ch);
5417 && (dest->o_assignment == MAYBE_ASSIGNMENT
5418 || dest->o_assignment == WORD_IS_KEYWORD)
5419 && is_well_formed_var_name(dest->data, '=')
5421 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5427 * Scan input until EOF or end_trigger char.
5428 * Return a list of pipes to execute, or NULL on EOF
5429 * or if end_trigger character is met.
5430 * On syntax error, exit is shell is not interactive,
5431 * reset parsing machinery and start parsing anew,
5432 * or return ERR_PTR.
5434 static struct pipe *parse_stream(char **pstring,
5435 struct in_str *input,
5438 struct parse_context ctx;
5439 o_string dest = NULL_O_STRING;
5443 /* Double-quote state is handled in the state variable is_in_dquote.
5444 * A single-quote triggers a bypass of the main loop until its mate is
5445 * found. When recursing, quote state is passed in via dest->o_escape.
5447 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5448 end_trigger ? : 'X');
5451 G.ifs = get_local_var_value("IFS");
5456 #if ENABLE_HUSH_INTERACTIVE
5457 input->promptmode = 0; /* PS1 */
5459 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5460 initialize_context(&ctx);
5465 const char *is_special;
5469 redir_type redir_style;
5472 /* dest.o_quoted = 1; - already is (see below) */
5473 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5476 /* We reached closing '"' */
5479 ch = i_getch(input);
5480 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5481 ch, ch, dest.o_escape);
5486 syntax_error_unterm_str("here document");
5489 /* end_trigger == '}' case errors out earlier,
5490 * checking only ')' */
5491 if (end_trigger == ')') {
5492 syntax_error_unterm_ch('('); /* exits */
5493 /* goto parse_error; */
5496 if (done_word(&dest, &ctx)) {
5500 done_pipe(&ctx, PIPE_SEQ);
5502 /* If we got nothing... */
5503 /* (this makes bare "&" cmd a no-op.
5504 * bash says: "syntax error near unexpected token '&'") */
5505 if (pi->num_cmds == 0
5506 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5512 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5514 *pstring = ctx.as_string.data;
5516 o_free_unsafe(&ctx.as_string);
5519 debug_printf_parse("parse_stream return %p\n", pi);
5522 nommu_addchr(&ctx.as_string, ch);
5523 is_ifs = strchr(G.ifs, ch);
5524 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5525 "\\$\"" IF_HUSH_TICK("`") /* always special */
5528 if (!is_special && !is_ifs) { /* ordinary char */
5530 o_addQchr(&dest, ch);
5531 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5532 || dest.o_assignment == WORD_IS_KEYWORD)
5534 && is_well_formed_var_name(dest.data, '=')
5536 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5542 if (done_word(&dest, &ctx)) {
5546 #if ENABLE_HUSH_CASE
5547 /* "case ... in <newline> word) ..." -
5548 * newlines are ignored (but ';' wouldn't be) */
5549 if (ctx.command->argv == NULL
5550 && ctx.ctx_res_w == RES_MATCH
5555 /* Treat newline as a command separator. */
5556 done_pipe(&ctx, PIPE_SEQ);
5557 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5559 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5564 dest.o_assignment = MAYBE_ASSIGNMENT;
5566 /* note: if (is_ifs) continue;
5567 * will still trigger for us */
5571 /* "cmd}" or "cmd }..." without semicolon or &:
5572 * } is an ordinary char in this case, even inside { cmd; }
5573 * Pathological example: { ""}; } should exec "}" cmd
5576 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5577 || dest.length != 0 /* word} */
5578 || dest.o_quoted /* ""} */
5582 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5583 goto skip_end_trigger;
5584 /* else: } does terminate a group */
5587 if (end_trigger && end_trigger == ch
5588 && (ch != ';' || heredoc_cnt == 0)
5589 #if ENABLE_HUSH_CASE
5591 || ctx.ctx_res_w != RES_MATCH
5592 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5597 /* This is technically valid:
5598 * { cat <<HERE; }; echo Ok
5602 * but we don't support this.
5603 * We require heredoc to be in enclosing {}/(),
5606 syntax_error_unterm_str("here document");
5609 if (done_word(&dest, &ctx)) {
5612 done_pipe(&ctx, PIPE_SEQ);
5613 dest.o_assignment = MAYBE_ASSIGNMENT;
5614 /* Do we sit outside of any if's, loops or case's? */
5616 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5620 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5622 *pstring = ctx.as_string.data;
5624 o_free_unsafe(&ctx.as_string);
5627 debug_printf_parse("parse_stream return %p: "
5628 "end_trigger char found\n",
5630 return ctx.list_head;
5639 next = i_peek(input);
5642 /* Catch <, > before deciding whether this word is
5643 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5646 redir_fd = redirect_opt_num(&dest);
5647 if (done_word(&dest, &ctx)) {
5650 redir_style = REDIRECT_OVERWRITE;
5652 redir_style = REDIRECT_APPEND;
5653 ch = i_getch(input);
5654 nommu_addchr(&ctx.as_string, ch);
5657 else if (next == '(') {
5658 syntax_error(">(process) not supported");
5662 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5664 continue; /* back to top of while (1) */
5666 redir_fd = redirect_opt_num(&dest);
5667 if (done_word(&dest, &ctx)) {
5670 redir_style = REDIRECT_INPUT;
5672 redir_style = REDIRECT_HEREDOC;
5674 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5675 ch = i_getch(input);
5676 nommu_addchr(&ctx.as_string, ch);
5677 } else if (next == '>') {
5678 redir_style = REDIRECT_IO;
5679 ch = i_getch(input);
5680 nommu_addchr(&ctx.as_string, ch);
5683 else if (next == '(') {
5684 syntax_error("<(process) not supported");
5688 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5690 continue; /* back to top of while (1) */
5693 if (dest.o_assignment == MAYBE_ASSIGNMENT
5694 /* check that we are not in word in "a=1 2>word b=1": */
5695 && !ctx.pending_redirect
5697 /* ch is a special char and thus this word
5698 * cannot be an assignment */
5699 dest.o_assignment = NOT_ASSIGNMENT;
5704 if (dest.length == 0) {
5707 if (ch == EOF || ch == '\n')
5710 /* note: we do not add it to &ctx.as_string */
5712 nommu_addchr(&ctx.as_string, '\n');
5714 o_addQchr(&dest, ch);
5719 syntax_error("\\<eof>");
5722 ch = i_getch(input);
5724 o_addchr(&dest, '\\');
5725 nommu_addchr(&ctx.as_string, '\\');
5726 o_addchr(&dest, ch);
5727 nommu_addchr(&ctx.as_string, ch);
5728 /* Example: echo Hello \2>file
5729 * we need to know that word 2 is quoted */
5734 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5735 debug_printf_parse("parse_stream parse error: "
5736 "handle_dollar returned non-0\n");
5743 ch = i_getch(input);
5745 syntax_error_unterm_ch('\'');
5746 /*xfunc_die(); - redundant */
5748 nommu_addchr(&ctx.as_string, ch);
5751 if (dest.o_assignment == NOT_ASSIGNMENT)
5752 o_addqchr(&dest, ch);
5754 o_addchr(&dest, ch);
5759 is_in_dquote ^= 1; /* invert */
5760 if (dest.o_assignment == NOT_ASSIGNMENT)
5763 #if ENABLE_HUSH_TICK
5768 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5769 o_addchr(&dest, '`');
5773 add_till_backquote(&dest, input);
5775 o_addstr(&ctx.as_string, dest.data + pos);
5776 o_addchr(&ctx.as_string, '`');
5778 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5779 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5784 #if ENABLE_HUSH_CASE
5787 if (done_word(&dest, &ctx)) {
5790 done_pipe(&ctx, PIPE_SEQ);
5791 #if ENABLE_HUSH_CASE
5792 /* Eat multiple semicolons, detect
5793 * whether it means something special */
5798 ch = i_getch(input);
5799 nommu_addchr(&ctx.as_string, ch);
5800 if (ctx.ctx_res_w == RES_CASE_BODY) {
5801 ctx.ctx_dsemicolon = 1;
5802 ctx.ctx_res_w = RES_MATCH;
5808 /* We just finished a cmd. New one may start
5809 * with an assignment */
5810 dest.o_assignment = MAYBE_ASSIGNMENT;
5813 if (done_word(&dest, &ctx)) {
5817 ch = i_getch(input);
5818 nommu_addchr(&ctx.as_string, ch);
5819 done_pipe(&ctx, PIPE_AND);
5821 done_pipe(&ctx, PIPE_BG);
5825 if (done_word(&dest, &ctx)) {
5828 #if ENABLE_HUSH_CASE
5829 if (ctx.ctx_res_w == RES_MATCH)
5830 break; /* we are in case's "word | word)" */
5832 if (next == '|') { /* || */
5833 ch = i_getch(input);
5834 nommu_addchr(&ctx.as_string, ch);
5835 done_pipe(&ctx, PIPE_OR);
5837 /* we could pick up a file descriptor choice here
5838 * with redirect_opt_num(), but bash doesn't do it.
5839 * "echo foo 2| cat" yields "foo 2". */
5844 #if ENABLE_HUSH_CASE
5845 /* "case... in [(]word)..." - skip '(' */
5846 if (ctx.ctx_res_w == RES_MATCH
5847 && ctx.command->argv == NULL /* not (word|(... */
5848 && dest.length == 0 /* not word(... */
5849 && dest.o_quoted == 0 /* not ""(... */
5855 if (parse_group(&dest, &ctx, input, ch) != 0) {
5860 #if ENABLE_HUSH_CASE
5861 if (ctx.ctx_res_w == RES_MATCH)
5865 /* proper use of this character is caught by end_trigger:
5866 * if we see {, we call parse_group(..., end_trigger='}')
5867 * and it will match } earlier (not here). */
5868 syntax_error_unexpected_ch(ch);
5872 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5878 struct parse_context *pctx;
5879 IF_HAS_KEYWORDS(struct parse_context *p2;)
5881 /* Clean up allocated tree.
5882 * Samples for finding leaks on syntax error recovery path.
5883 * Run them from interactive shell, watch pmap `pidof hush`.
5884 * while if false; then false; fi do break; done
5886 * while if false; then false; fi; do break; fi
5887 * Samples to catch leaks at execution:
5888 * while if (true | {true;}); then echo ok; fi; do break; done
5889 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5893 /* Update pipe/command counts,
5894 * otherwise freeing may miss some */
5895 done_pipe(pctx, PIPE_SEQ);
5896 debug_printf_clean("freeing list %p from ctx %p\n",
5897 pctx->list_head, pctx);
5898 debug_print_tree(pctx->list_head, 0);
5899 free_pipe_list(pctx->list_head);
5900 debug_printf_clean("freed list %p\n", pctx->list_head);
5902 o_free_unsafe(&pctx->as_string);
5904 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5908 IF_HAS_KEYWORDS(pctx = p2;)
5909 } while (HAS_KEYWORDS && pctx);
5910 /* Free text, clear all dest fields */
5912 /* If we are not in top-level parse, we return,
5913 * our caller will propagate error.
5915 if (end_trigger != ';') {
5923 /* Discard cached input, force prompt */
5925 IF_HUSH_INTERACTIVE(input->promptme = 1;)
5930 /* Executing from string: eval, sh -c '...'
5931 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5932 * end_trigger controls how often we stop parsing
5933 * NUL: parse all, execute, return
5934 * ';': parse till ';' or newline, execute, repeat till EOF
5936 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5939 struct pipe *pipe_list;
5941 pipe_list = parse_stream(NULL, inp, end_trigger);
5942 if (!pipe_list) /* EOF */
5944 debug_print_tree(pipe_list, 0);
5945 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5946 run_and_free_list(pipe_list);
5950 static void parse_and_run_string(const char *s)
5952 struct in_str input;
5953 setup_string_in_str(&input, s);
5954 parse_and_run_stream(&input, '\0');
5957 static void parse_and_run_file(FILE *f)
5959 struct in_str input;
5960 setup_file_in_str(&input, f);
5961 parse_and_run_stream(&input, ';');
5964 /* Called a few times only (or even once if "sh -c") */
5965 static void block_signals(int second_time)
5970 mask = (1 << SIGQUIT);
5971 if (G_interactive_fd) {
5972 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
5973 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
5974 mask |= SPECIAL_JOB_SIGS;
5976 G.non_DFL_mask = mask;
5979 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5983 sigaddset(&G.blocked_set, sig);
5987 sigdelset(&G.blocked_set, SIGCHLD);
5989 sigprocmask(SIG_SETMASK, &G.blocked_set,
5990 second_time ? NULL : &G.inherited_set);
5991 /* POSIX allows shell to re-enable SIGCHLD
5992 * even if it was SIG_IGN on entry */
5993 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5995 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
6000 static void maybe_set_to_sigexit(int sig)
6002 void (*handler)(int);
6003 /* non_DFL_mask'ed signals are, well, masked,
6004 * no need to set handler for them.
6006 if (!((G.non_DFL_mask >> sig) & 1)) {
6007 handler = signal(sig, sigexit);
6008 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6009 signal(sig, handler);
6012 /* Set handlers to restore tty pgrp and exit */
6013 static void set_fatal_handlers(void)
6015 /* We _must_ restore tty pgrp on fatal signals */
6017 maybe_set_to_sigexit(SIGILL );
6018 maybe_set_to_sigexit(SIGFPE );
6019 maybe_set_to_sigexit(SIGBUS );
6020 maybe_set_to_sigexit(SIGSEGV);
6021 maybe_set_to_sigexit(SIGTRAP);
6022 } /* else: hush is perfect. what SEGV? */
6023 maybe_set_to_sigexit(SIGABRT);
6024 /* bash 3.2 seems to handle these just like 'fatal' ones */
6025 maybe_set_to_sigexit(SIGPIPE);
6026 maybe_set_to_sigexit(SIGALRM);
6027 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6028 * if we aren't interactive... but in this case
6029 * we never want to restore pgrp on exit, and this fn is not called */
6030 /*maybe_set_to_sigexit(SIGHUP );*/
6031 /*maybe_set_to_sigexit(SIGTERM);*/
6032 /*maybe_set_to_sigexit(SIGINT );*/
6036 static int set_mode(const char cstate, const char mode)
6038 int state = (cstate == '-' ? 1 : 0);
6040 case 'n': G.fake_mode = state; break;
6041 case 'x': /*G.debug_mode = state;*/ break;
6042 default: return EXIT_FAILURE;
6044 return EXIT_SUCCESS;
6047 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6048 int hush_main(int argc, char **argv)
6050 static const struct variable const_shell_ver = {
6052 .varstr = (char*)hush_version_str,
6053 .max_len = 1, /* 0 can provoke free(name) */
6057 int signal_mask_is_inited = 0;
6060 struct variable *cur_var;
6063 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6064 G.last_exitcode = EXIT_SUCCESS;
6066 G.argv0_for_re_execing = argv[0];
6068 /* Deal with HUSH_VERSION */
6069 G.shell_ver = const_shell_ver; /* copying struct here */
6070 G.top_var = &G.shell_ver;
6071 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6072 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6073 /* Initialize our shell local variables with the values
6074 * currently living in the environment */
6075 cur_var = G.top_var;
6078 char *value = strchr(*e, '=');
6079 if (value) { /* paranoia */
6080 cur_var->next = xzalloc(sizeof(*cur_var));
6081 cur_var = cur_var->next;
6082 cur_var->varstr = *e;
6083 cur_var->max_len = strlen(*e);
6084 cur_var->flg_export = 1;
6088 debug_printf_env("putenv '%s'\n", hush_version_str);
6089 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6090 #if ENABLE_FEATURE_EDITING
6091 G.line_input_state = new_line_input_t(FOR_SHELL);
6093 G.global_argc = argc;
6094 G.global_argv = argv;
6095 /* Initialize some more globals to non-zero values */
6097 cmdedit_update_prompt();
6099 if (setjmp(die_jmp)) {
6100 /* xfunc has failed! die die die */
6101 /* no EXIT traps, this is an escape hatch! */
6103 hush_exit(xfunc_error_retval);
6106 /* Shell is non-interactive at first. We need to call
6107 * block_signals(0) if we are going to execute "sh <script>",
6108 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6109 * If we later decide that we are interactive, we run block_signals(0)
6110 * (or re-run block_signals(1) if we ran block_signals(0) before)
6111 * in order to intercept (more) signals.
6115 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6117 opt = getopt(argc, argv, "c:xins"
6120 # if ENABLE_HUSH_FUNCTIONS
6130 G.root_pid = getpid();
6131 G.global_argv = argv + optind;
6132 if (!argv[optind]) {
6133 /* -c 'script' (no params): prevent empty $0 */
6134 *--G.global_argv = argv[0];
6136 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
6137 G.global_argc = argc - optind;
6138 block_signals(0); /* 0: called 1st time */
6139 parse_and_run_string(optarg);
6142 /* Well, we cannot just declare interactiveness,
6143 * we have to have some stuff (ctty, etc) */
6144 /* G_interactive_fd++; */
6147 /* "-s" means "read from stdin", but this is how we always
6148 * operate, so simply do nothing here. */
6151 case '<': /* "big heredoc" support */
6152 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6155 G.root_pid = bb_strtou(optarg, &optarg, 16);
6157 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6159 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6160 # if ENABLE_HUSH_LOOPS
6162 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6167 set_local_var(xstrdup(optarg), 0, opt == 'R');
6169 # if ENABLE_HUSH_FUNCTIONS
6171 struct function *funcp = new_function(optarg);
6172 /* funcp->name is already set to optarg */
6173 /* funcp->body is set to NULL. It's a special case. */
6174 funcp->body_as_string = argv[optind];
6182 if (!set_mode('-', opt))
6186 fprintf(stderr, "Usage: sh [FILE]...\n"
6187 " or: sh -c command [args]...\n\n");
6193 } /* option parsing loop */
6196 G.root_pid = getpid();
6198 /* If we are login shell... */
6199 if (argv[0] && argv[0][0] == '-') {
6201 debug_printf("sourcing /etc/profile\n");
6202 input = fopen_for_read("/etc/profile");
6203 if (input != NULL) {
6204 close_on_exec_on(fileno(input));
6205 block_signals(0); /* 0: called 1st time */
6206 signal_mask_is_inited = 1;
6207 parse_and_run_file(input);
6210 /* bash: after sourcing /etc/profile,
6211 * tries to source (in the given order):
6212 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6213 * stopping of first found. --noprofile turns this off.
6214 * bash also sources ~/.bash_logout on exit.
6215 * If called as sh, skips .bash_XXX files.
6222 * "bash <script>" (which is never interactive (unless -i?))
6223 * sources $BASH_ENV here (without scanning $PATH).
6224 * If called as sh, does the same but with $ENV.
6226 debug_printf("running script '%s'\n", argv[optind]);
6227 G.global_argv = argv + optind;
6228 G.global_argc = argc - optind;
6229 input = xfopen_for_read(argv[optind]);
6230 close_on_exec_on(fileno(input));
6231 if (!signal_mask_is_inited)
6232 block_signals(0); /* 0: called 1st time */
6233 parse_and_run_file(input);
6234 #if ENABLE_FEATURE_CLEAN_UP
6240 /* Up to here, shell was non-interactive. Now it may become one.
6241 * NB: don't forget to (re)run block_signals(0/1) as needed.
6244 /* A shell is interactive if the '-i' flag was given, or if all of
6245 * the following conditions are met:
6247 * no arguments remaining or the -s flag given
6248 * standard input is a terminal
6249 * standard output is a terminal
6250 * Refer to Posix.2, the description of the 'sh' utility.
6253 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6254 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6255 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6256 if (G_saved_tty_pgrp < 0)
6257 G_saved_tty_pgrp = 0;
6259 /* try to dup stdin to high fd#, >= 255 */
6260 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6261 if (G_interactive_fd < 0) {
6262 /* try to dup to any fd */
6263 G_interactive_fd = dup(STDIN_FILENO);
6264 if (G_interactive_fd < 0) {
6266 G_interactive_fd = 0;
6267 G_saved_tty_pgrp = 0;
6270 // TODO: track & disallow any attempts of user
6271 // to (inadvertently) close/redirect G_interactive_fd
6273 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6274 if (G_interactive_fd) {
6275 close_on_exec_on(G_interactive_fd);
6277 if (G_saved_tty_pgrp) {
6278 /* If we were run as 'hush &', sleep until we are
6279 * in the foreground (tty pgrp == our pgrp).
6280 * If we get started under a job aware app (like bash),
6281 * make sure we are now in charge so we don't fight over
6282 * who gets the foreground */
6284 pid_t shell_pgrp = getpgrp();
6285 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6286 if (G_saved_tty_pgrp == shell_pgrp)
6288 /* send TTIN to ourself (should stop us) */
6289 kill(- shell_pgrp, SIGTTIN);
6293 /* Block some signals */
6294 block_signals(signal_mask_is_inited);
6296 if (G_saved_tty_pgrp) {
6297 /* Set other signals to restore saved_tty_pgrp */
6298 set_fatal_handlers();
6299 /* Put ourselves in our own process group
6300 * (bash, too, does this only if ctty is available) */
6301 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6302 /* Grab control of the terminal */
6303 tcsetpgrp(G_interactive_fd, getpid());
6305 /* -1 is special - makes xfuncs longjmp, not exit
6306 * (we reset die_sleep = 0 whereever we [v]fork) */
6307 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6308 } else if (!signal_mask_is_inited) {
6309 block_signals(0); /* 0: called 1st time */
6310 } /* else: block_signals(0) was done before */
6311 #elif ENABLE_HUSH_INTERACTIVE
6312 /* No job control compiled in, only prompt/line editing */
6313 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6314 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6315 if (G_interactive_fd < 0) {
6316 /* try to dup to any fd */
6317 G_interactive_fd = dup(STDIN_FILENO);
6318 if (G_interactive_fd < 0)
6320 G_interactive_fd = 0;
6323 if (G_interactive_fd) {
6324 close_on_exec_on(G_interactive_fd);
6325 block_signals(signal_mask_is_inited);
6326 } else if (!signal_mask_is_inited) {
6330 /* We have interactiveness code disabled */
6331 if (!signal_mask_is_inited) {
6336 * if interactive but not a login shell, sources ~/.bashrc
6337 * (--norc turns this off, --rcfile <file> overrides)
6340 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6341 printf("\n\n%s hush - the humble shell\n", bb_banner);
6342 if (ENABLE_HUSH_HELP)
6343 puts("Enter 'help' for a list of built-in commands.");
6347 parse_and_run_file(stdin);
6350 #if ENABLE_FEATURE_CLEAN_UP
6351 if (G.cwd != bb_msg_unknown)
6353 cur_var = G.top_var->next;
6355 struct variable *tmp = cur_var;
6356 if (!cur_var->max_len)
6357 free(cur_var->varstr);
6358 cur_var = cur_var->next;
6362 hush_exit(G.last_exitcode);
6367 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6368 int lash_main(int argc, char **argv)
6370 //bb_error_msg("lash is deprecated, please use hush instead");
6371 return hush_main(argc, argv);
6379 static int builtin_true(char **argv UNUSED_PARAM)
6384 static int builtin_test(char **argv)
6391 return test_main(argc, argv - argc);
6394 static int builtin_echo(char **argv)
6401 return echo_main(argc, argv - argc);
6404 static int builtin_eval(char **argv)
6406 int rcode = EXIT_SUCCESS;
6409 char *str = expand_strvec_to_string(argv);
6411 * eval "echo Hi; done" ("done" is syntax error):
6412 * "echo Hi" will not execute too.
6414 parse_and_run_string(str);
6416 rcode = G.last_exitcode;
6421 static int builtin_cd(char **argv)
6423 const char *newdir = argv[1];
6424 if (newdir == NULL) {
6425 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6426 * bash says "bash: cd: HOME not set" and does nothing
6429 newdir = get_local_var_value("HOME") ? : "/";
6431 if (chdir(newdir)) {
6432 /* Mimic bash message exactly */
6433 bb_perror_msg("cd: %s", newdir);
6434 return EXIT_FAILURE;
6437 return EXIT_SUCCESS;
6440 static int builtin_exec(char **argv)
6442 if (*++argv == NULL)
6443 return EXIT_SUCCESS; /* bash does this */
6448 /* TODO: if exec fails, bash does NOT exit! We do... */
6449 pseudo_exec_argv(&dummy, argv, 0, NULL);
6454 static int builtin_exit(char **argv)
6456 debug_printf_exec("%s()\n", __func__);
6458 /* interactive bash:
6459 * # trap "echo EEE" EXIT
6462 * There are stopped jobs.
6463 * (if there are _stopped_ jobs, running ones don't count)
6466 # EEE (then bash exits)
6468 * we can use G.exiting = -1 as indicator "last cmd was exit"
6471 /* note: EXIT trap is run by hush_exit */
6472 if (*++argv == NULL)
6473 hush_exit(G.last_exitcode);
6474 /* mimic bash: exit 123abc == exit 255 + error msg */
6475 xfunc_error_retval = 255;
6476 /* bash: exit -2 == exit 254, no error msg */
6477 hush_exit(xatoi(*argv) & 0xff);
6480 static void print_escaped(const char *s)
6486 p = strchrnul(s, '\'');
6487 /* print 'xxxx', possibly just '' */
6488 printf("'%.*s'", (int)(p - s), s);
6493 /* s points to '; print "'''...'''" */
6495 do putchar('\''); while (*++s == '\'');
6500 static int builtin_export(char **argv)
6502 unsigned opt_unexport;
6504 if (argv[1] == NULL) {
6511 /* ash emits: export VAR='VAL'
6512 * bash: declare -x VAR="VAL"
6513 * we follow ash example */
6514 const char *s = *e++;
6515 const char *p = strchr(s, '=');
6517 if (!p) /* wtf? take next variable */
6520 printf("export %.*s", (int)(p - s) + 1, s);
6521 print_escaped(p + 1);
6525 /*fflush(stdout); - done after each builtin anyway */
6527 return EXIT_SUCCESS;
6530 #if ENABLE_HUSH_EXPORT_N
6531 /* "!": do not abort on errors */
6532 /* "+": stop at 1st non-option */
6533 opt_unexport = getopt32(argv, "!+n");
6534 if (opt_unexport == (unsigned)-1)
6535 return EXIT_FAILURE;
6545 /* So far we do not check that name is valid (TODO?) */
6547 if (strchr(name, '=') == NULL) {
6548 struct variable *var;
6550 var = get_local_var(name);
6552 /* export -n NAME (without =VALUE) */
6554 var->flg_export = 0;
6555 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6557 } /* else: export -n NOT_EXISTING_VAR: no-op */
6560 /* export NAME (without =VALUE) */
6562 var->flg_export = 1;
6563 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6564 putenv(var->varstr);
6567 /* Exporting non-existing variable.
6568 * bash does not put it in environment,
6569 * but remembers that it is exported,
6570 * and does put it in env when it is set later.
6571 * We just set it to "" and export. */
6572 name = xasprintf("%s=", name);
6574 /* (Un)exporting NAME=VALUE */
6575 name = xstrdup(name);
6578 /*export:*/ (opt_unexport ? -1 : 1),
6583 return EXIT_SUCCESS;
6586 static int builtin_trap(char **argv)
6592 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6597 /* No args: print all trapped */
6598 for (i = 0; i < NSIG; ++i) {
6601 print_escaped(G.traps[i]);
6602 printf(" %s\n", get_signame(i));
6605 /*fflush(stdout); - done after each builtin anyway */
6606 return EXIT_SUCCESS;
6610 /* If first arg is a number: reset all specified signals */
6611 sig = bb_strtou(*argv, NULL, 10);
6617 sig = get_signum(*argv++);
6618 if (sig < 0 || sig >= NSIG) {
6620 /* Mimic bash message exactly */
6621 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
6626 G.traps[sig] = xstrdup(new_cmd);
6628 debug_printf("trap: setting SIG%s (%i) to '%s'",
6629 get_signame(sig), sig, G.traps[sig]);
6631 /* There is no signal for 0 (EXIT) */
6636 sigaddset(&G.blocked_set, sig);
6638 /* There was a trap handler, we are removing it
6639 * (if sig has non-DFL handling,
6640 * we don't need to do anything) */
6641 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6643 sigdelset(&G.blocked_set, sig);
6646 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6650 if (!argv[1]) { /* no second arg */
6651 bb_error_msg("trap: invalid arguments");
6652 return EXIT_FAILURE;
6655 /* First arg is "-": reset all specified to default */
6656 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6657 /* Everything else: set arg as signal handler
6658 * (includes "" case, which ignores signal) */
6659 if (argv[0][0] == '-') {
6660 if (argv[0][1] == '\0') { /* "-" */
6661 /* new_cmd remains NULL: "reset these sigs" */
6664 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6667 /* else: "-something", no special meaning */
6672 goto process_sig_list;
6676 /* built-in 'fg' and 'bg' handler */
6677 static int builtin_fg_bg(char **argv)
6682 if (!G_interactive_fd)
6683 return EXIT_FAILURE;
6685 /* If they gave us no args, assume they want the last backgrounded task */
6687 for (pi = G.job_list; pi; pi = pi->next) {
6688 if (pi->jobid == G.last_jobid) {
6692 bb_error_msg("%s: no current job", argv[0]);
6693 return EXIT_FAILURE;
6695 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6696 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6697 return EXIT_FAILURE;
6699 for (pi = G.job_list; pi; pi = pi->next) {
6700 if (pi->jobid == jobnum) {
6704 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6705 return EXIT_FAILURE;
6707 /* TODO: bash prints a string representation
6708 * of job being foregrounded (like "sleep 1 | cat") */
6709 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
6710 /* Put the job into the foreground. */
6711 tcsetpgrp(G_interactive_fd, pi->pgrp);
6714 /* Restart the processes in the job */
6715 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6716 for (i = 0; i < pi->num_cmds; i++) {
6717 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6718 pi->cmds[i].is_stopped = 0;
6720 pi->stopped_cmds = 0;
6722 i = kill(- pi->pgrp, SIGCONT);
6724 if (errno == ESRCH) {
6725 delete_finished_bg_job(pi);
6726 return EXIT_SUCCESS;
6728 bb_perror_msg("kill (SIGCONT)");
6731 if (argv[0][0] == 'f') {
6733 return checkjobs_and_fg_shell(pi);
6735 return EXIT_SUCCESS;
6739 #if ENABLE_HUSH_HELP
6740 static int builtin_help(char **argv UNUSED_PARAM)
6742 const struct built_in_command *x;
6745 "Built-in commands:\n"
6746 "------------------\n");
6747 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6748 printf("%s\t%s\n", x->cmd, x->descr);
6751 return EXIT_SUCCESS;
6756 static int builtin_jobs(char **argv UNUSED_PARAM)
6759 const char *status_string;
6761 for (job = G.job_list; job; job = job->next) {
6762 if (job->alive_cmds == job->stopped_cmds)
6763 status_string = "Stopped";
6765 status_string = "Running";
6767 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6769 return EXIT_SUCCESS;
6774 static int builtin_memleak(char **argv UNUSED_PARAM)
6779 /* Crude attempt to find where "free memory" starts,
6780 * sans fragmentation. */
6782 l = (unsigned long)p;
6785 if (l < (unsigned long)p) l = (unsigned long)p;
6788 if (!G.memleak_value)
6789 G.memleak_value = l;
6791 l -= G.memleak_value;
6798 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6803 static int builtin_pwd(char **argv UNUSED_PARAM)
6806 return EXIT_SUCCESS;
6809 static int builtin_read(char **argv)
6812 const char *name = "REPLY";
6816 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6817 * and _after_ that_ it will complain */
6818 if (!is_well_formed_var_name(name, '\0')) {
6819 /* Mimic bash message */
6820 bb_error_msg("read: '%s': not a valid identifier", name);
6825 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
6827 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
6828 return set_local_var(string, 0, 0);
6831 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6832 * built-in 'set' handler
6834 * set [-abCefhmnuvx] [-o option] [argument...]
6835 * set [+abCefhmnuvx] [+o option] [argument...]
6836 * set -- [argument...]
6839 * Implementations shall support the options in both their hyphen and
6840 * plus-sign forms. These options can also be specified as options to sh.
6842 * Write out all variables and their values: set
6843 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6844 * Turn on the -x and -v options: set -xv
6845 * Unset all positional parameters: set --
6846 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6847 * Set the positional parameters to the expansion of x, even if x expands
6848 * with a leading '-' or '+': set -- $x
6850 * So far, we only support "set -- [argument...]" and some of the short names.
6852 static int builtin_set(char **argv)
6855 char **pp, **g_argv;
6856 char *arg = *++argv;
6860 for (e = G.top_var; e; e = e->next)
6862 return EXIT_SUCCESS;
6866 if (!strcmp(arg, "--")) {
6870 if (arg[0] != '+' && arg[0] != '-')
6872 for (n = 1; arg[n]; ++n)
6873 if (set_mode(arg[0], arg[n]))
6875 } while ((arg = *++argv) != NULL);
6876 /* Now argv[0] is 1st argument */
6879 return EXIT_SUCCESS;
6882 /* NB: G.global_argv[0] ($0) is never freed/changed */
6883 g_argv = G.global_argv;
6884 if (G.global_args_malloced) {
6890 G.global_args_malloced = 1;
6891 pp = xzalloc(sizeof(pp[0]) * 2);
6892 pp[0] = g_argv[0]; /* retain $0 */
6895 /* This realloc's G.global_argv */
6896 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6903 return EXIT_SUCCESS;
6905 /* Nothing known, so abort */
6907 bb_error_msg("set: %s: invalid option", arg);
6908 return EXIT_FAILURE;
6911 static int builtin_shift(char **argv)
6917 if (n >= 0 && n < G.global_argc) {
6918 if (G.global_args_malloced) {
6921 free(G.global_argv[m++]);
6924 memmove(&G.global_argv[1], &G.global_argv[n+1],
6925 G.global_argc * sizeof(G.global_argv[0]));
6926 return EXIT_SUCCESS;
6928 return EXIT_FAILURE;
6931 static int builtin_source(char **argv)
6936 #if ENABLE_HUSH_FUNCTIONS
6940 if (*++argv == NULL)
6941 return EXIT_FAILURE;
6943 if (strchr(*argv, '/') == NULL
6944 && (PATH = get_local_var_value("PATH")) != NULL
6946 /* Search through $PATH */
6948 const char *end = strchrnul(PATH, ':');
6949 int sz = end - PATH; /* must be int! */
6952 char *tmp = xasprintf("%.*s/%s", sz, PATH, *argv);
6953 input = fopen_for_read(tmp);
6956 /* We have xxx::yyyy in $PATH,
6957 * it means "use current dir" */
6958 input = fopen_for_read(*argv);
6967 input = fopen_or_warn(*argv, "r");
6969 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
6970 return EXIT_FAILURE;
6973 close_on_exec_on(fileno(input));
6975 #if ENABLE_HUSH_FUNCTIONS
6976 sv_flg = G.flag_return_in_progress;
6977 /* "we are inside sourced file, ok to use return" */
6978 G.flag_return_in_progress = -1;
6980 save_and_replace_G_args(&sv, argv);
6982 parse_and_run_file(input);
6985 restore_G_args(&sv, argv);
6986 #if ENABLE_HUSH_FUNCTIONS
6987 G.flag_return_in_progress = sv_flg;
6990 return G.last_exitcode;
6993 static int builtin_umask(char **argv)
7000 mode_t old_mask = mask;
7003 rc = bb_parse_mode(argv[1], &mask);
7008 * bash: umask: 'q': invalid symbolic mode operator
7009 * bash: umask: 999: octal number out of range
7011 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7016 printf("%04o\n", (unsigned) mask);
7017 /* fall through and restore mask which we set to 0 */
7021 return !rc; /* rc != 0 - success */
7024 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7025 static int builtin_unset(char **argv)
7030 /* "!": do not abort on errors */
7031 /* "+": stop at 1st non-option */
7032 opts = getopt32(argv, "!+vf");
7033 if (opts == (unsigned)-1)
7034 return EXIT_FAILURE;
7036 bb_error_msg("unset: -v and -f are exclusive");
7037 return EXIT_FAILURE;
7043 if (!(opts & 2)) { /* not -f */
7044 if (unset_local_var(*argv)) {
7045 /* unset <nonexistent_var> doesn't fail.
7046 * Error is when one tries to unset RO var.
7047 * Message was printed by unset_local_var. */
7051 #if ENABLE_HUSH_FUNCTIONS
7061 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7062 static int builtin_wait(char **argv)
7064 int ret = EXIT_SUCCESS;
7067 if (*++argv == NULL) {
7068 /* Don't care about wait results */
7069 /* Note 1: must wait until there are no more children */
7070 /* Note 2: must be interruptible */
7072 * $ sleep 3 & sleep 6 & wait
7077 * $ sleep 3 & sleep 6 & wait
7081 * ^C <-- after ~4 sec from keyboard
7084 sigaddset(&G.blocked_set, SIGCHLD);
7085 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7088 if (errno == ECHILD)
7090 /* Wait for SIGCHLD or any other signal of interest */
7091 /* sigtimedwait with infinite timeout: */
7092 sig = sigwaitinfo(&G.blocked_set, NULL);
7094 sig = check_and_run_traps(sig);
7095 if (sig && sig != SIGCHLD) { /* see note 2 */
7101 sigdelset(&G.blocked_set, SIGCHLD);
7102 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7106 /* This is probably buggy wrt interruptible-ness */
7108 pid_t pid = bb_strtou(*argv, NULL, 10);
7110 /* mimic bash message */
7111 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7112 return EXIT_FAILURE;
7114 if (waitpid(pid, &status, 0) == pid) {
7115 if (WIFSIGNALED(status))
7116 ret = 128 + WTERMSIG(status);
7117 else if (WIFEXITED(status))
7118 ret = WEXITSTATUS(status);
7122 bb_perror_msg("wait %s", *argv);
7131 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7132 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7135 def = bb_strtou(argv[1], NULL, 10);
7136 if (errno || def < def_min || argv[2]) {
7137 bb_error_msg("%s: bad arguments", argv[0]);
7145 #if ENABLE_HUSH_LOOPS
7146 static int builtin_break(char **argv)
7149 if (G.depth_of_loop == 0) {
7150 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7151 return EXIT_SUCCESS; /* bash compat */
7153 G.flag_break_continue++; /* BC_BREAK = 1 */
7155 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7156 if (depth == UINT_MAX)
7157 G.flag_break_continue = BC_BREAK;
7158 if (G.depth_of_loop < depth)
7159 G.depth_break_continue = G.depth_of_loop;
7161 return EXIT_SUCCESS;
7164 static int builtin_continue(char **argv)
7166 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7167 return builtin_break(argv);
7171 #if ENABLE_HUSH_FUNCTIONS
7172 static int builtin_return(char **argv)
7176 if (G.flag_return_in_progress != -1) {
7177 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7178 return EXIT_FAILURE; /* bash compat */
7181 G.flag_return_in_progress = 1;
7184 * out of range: wraps around at 256, does not error out
7185 * non-numeric param:
7186 * f() { false; return qwe; }; f; echo $?
7187 * bash: return: qwe: numeric argument required <== we do this
7188 * 255 <== we also do this
7190 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);