1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
45 * Bash stuff (maybe optionally enable?):
46 * &> and >& redirection of stdout+stderr
48 * reserved words: [[ ]] function select
49 * substrings ${var:1:5}
52 * grep for "TODO" and fix (some of them are easy)
54 * follow IFS rules more precisely, including update semantics
56 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
58 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
60 /* #include <dmalloc.h> */
67 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
72 #define LEAK_HUNTING 0
73 #define BUILD_AS_NOMMU 0
74 /* Enable/disable sanity checks. Ok to enable in production,
75 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
76 * Keeping 1 for now even in released versions.
79 /* Slightly bigger (+200 bytes), but faster hush.
80 * So far it only enables a trick with counting SIGCHLDs and forks,
81 * which allows us to do fewer waitpid's.
82 * (we can detect a case where neither forks were done nor SIGCHLDs happened
83 * and therefore waitpid will return the same result as last time)
85 #define ENABLE_HUSH_FAST 0
93 # define USE_FOR_NOMMU(...) __VA_ARGS__
94 # define USE_FOR_MMU(...)
97 #if defined SINGLE_APPLET_MAIN
98 /* STANDALONE does not make sense, and won't compile */
99 # undef CONFIG_FEATURE_SH_STANDALONE
100 # undef ENABLE_FEATURE_SH_STANDALONE
101 # undef IF_FEATURE_SH_STANDALONE
102 # define IF_FEATURE_SH_STANDALONE(...)
103 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
104 # define ENABLE_FEATURE_SH_STANDALONE 0
107 #if !ENABLE_HUSH_INTERACTIVE
108 # undef ENABLE_FEATURE_EDITING
109 # define ENABLE_FEATURE_EDITING 0
110 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
111 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
114 /* Do we support ANY keywords? */
115 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
116 # define HAS_KEYWORDS 1
117 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
118 # define IF_HAS_NO_KEYWORDS(...)
120 # define HAS_KEYWORDS 0
121 # define IF_HAS_KEYWORDS(...)
122 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
125 /* If you comment out one of these below, it will be #defined later
126 * to perform debug printfs to stderr: */
127 #define debug_printf(...) do {} while (0)
128 /* Finer-grained debug switches */
129 #define debug_printf_parse(...) do {} while (0)
130 #define debug_print_tree(a, b) do {} while (0)
131 #define debug_printf_exec(...) do {} while (0)
132 #define debug_printf_env(...) do {} while (0)
133 #define debug_printf_jobs(...) do {} while (0)
134 #define debug_printf_expand(...) do {} while (0)
135 #define debug_printf_glob(...) do {} while (0)
136 #define debug_printf_list(...) do {} while (0)
137 #define debug_printf_subst(...) do {} while (0)
138 #define debug_printf_clean(...) do {} while (0)
140 #define ERR_PTR ((void*)(long)1)
142 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
144 #define SPECIAL_VAR_SYMBOL 3
148 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
150 /* This supports saving pointers malloced in vfork child,
151 * to be freed in the parent.
154 typedef struct nommu_save_t {
156 struct variable *old_vars;
158 char **argv_from_re_execing;
162 /* The descrip member of this structure is only used to make
163 * debugging output pretty */
164 static const struct {
166 signed char default_fd;
170 { O_RDONLY, 0, "<" },
171 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
172 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
173 { O_RDONLY, 0, "<<" },
174 { O_CREAT|O_RDWR, 1, "<>" },
175 /* Should not be needed. Bogus default_fd helps in debugging */
176 /* { O_RDONLY, 77, "<<" }, */
179 typedef enum reserved_style {
188 #if ENABLE_HUSH_LOOPS
195 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
200 /* three pseudo-keywords support contrived "case" syntax: */
201 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
202 RES_MATCH , /* "word)" */
203 RES_CASE_BODY, /* "this command is inside CASE" */
210 typedef struct o_string {
212 int length; /* position where data is appended */
214 /* Protect newly added chars against globbing
215 * (by prepending \ to *, ?, [, \) */
218 /* At least some part of the string was inside '' or "",
219 * possibly empty one: word"", wo''rd etc. */
221 smallint has_empty_slot;
222 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
225 MAYBE_ASSIGNMENT = 0,
226 DEFINITELY_ASSIGNMENT = 1,
228 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
230 /* Used for initialization: o_string foo = NULL_O_STRING; */
231 #define NULL_O_STRING { NULL }
233 /* I can almost use ordinary FILE*. Is open_memstream() universally
234 * available? Where is it documented? */
235 typedef struct in_str {
237 /* eof_flag=1: last char in ->p is really an EOF */
238 char eof_flag; /* meaningless if ->p == NULL */
240 #if ENABLE_HUSH_INTERACTIVE
242 smallint promptmode; /* 0: PS1, 1: PS2 */
245 int (*get) (struct in_str *);
246 int (*peek) (struct in_str *);
248 #define i_getch(input) ((input)->get(input))
249 #define i_peek(input) ((input)->peek(input))
251 struct redir_struct {
252 struct redir_struct *next;
253 char *rd_filename; /* filename */
254 int rd_fd; /* fd to redirect */
255 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
257 smallint rd_type; /* (enum redir_type) */
258 /* note: for heredocs, rd_filename contains heredoc delimiter,
259 * and subsequently heredoc itself; and rd_dup is a bitmask:
260 * 1: do we need to trim leading tabs?
261 * 2: is heredoc quoted (<<'delim' syntax) ?
264 typedef enum redir_type {
265 REDIRECT_INVALID = 0,
267 REDIRECT_OVERWRITE = 2,
269 REDIRECT_HEREDOC = 4,
271 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
274 REDIRFD_SYNTAX_ERR = -2,
275 REDIRFD_TO_FILE = -1,
276 /* otherwise, rd_fd is redirected to rd_dup */
278 HEREDOC_SKIPTABS = 1,
284 pid_t pid; /* 0 if exited */
285 int assignment_cnt; /* how many argv[i] are assignments? */
286 smallint is_stopped; /* is the command currently running? */
287 smallint grp_type; /* GRP_xxx */
289 #define GRP_SUBSHELL 1
290 #if ENABLE_HUSH_FUNCTIONS
291 # define GRP_FUNCTION 2
293 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
296 char *group_as_string;
298 #if ENABLE_HUSH_FUNCTIONS
299 struct function *child_func;
300 /* This field is used to prevent a bug here:
301 * while...do f1() {a;}; f1; f1 {b;}; f1; done
302 * When we execute "f1() {a;}" cmd, we create new function and clear
303 * cmd->group, cmd->group_as_string, cmd->argv[0].
304 * when we execute "f1 {b;}", we notice that f1 exists,
305 * and that it's "parent cmd" struct is still "alive",
306 * we put those fields back into cmd->xxx
307 * (struct function has ->parent_cmd ptr to facilitate that).
308 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
309 * Without this trick, loop would execute a;b;b;b;...
310 * instead of correct sequence a;b;a;b;...
311 * When command is freed, it severs the link
312 * (sets ->child_func->parent_cmd to NULL).
315 char **argv; /* command name and arguments */
316 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
317 * and on execution these are substituted with their values.
318 * Substitution can make _several_ words out of one argv[n]!
319 * Example: argv[0]=='.^C*^C.' here: echo .$*.
320 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
322 struct redir_struct *redirects; /* I/O redirections */
324 /* Is there anything in this command at all? */
325 #define IS_NULL_CMD(cmd) \
326 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
331 int num_cmds; /* total number of commands in pipe */
332 int alive_cmds; /* number of commands running (not exited) */
333 int stopped_cmds; /* number of commands alive, but stopped */
335 int jobid; /* job number */
336 pid_t pgrp; /* process group ID for the job */
337 char *cmdtext; /* name of job */
339 struct command *cmds; /* array of commands in pipe */
340 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
341 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
342 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
344 typedef enum pipe_style {
350 /* Is there anything in this pipe at all? */
351 #define IS_NULL_PIPE(pi) \
352 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
354 /* This holds pointers to the various results of parsing */
355 struct parse_context {
356 /* linked list of pipes */
357 struct pipe *list_head;
358 /* last pipe (being constructed right now) */
360 /* last command in pipe (being constructed right now) */
361 struct command *command;
362 /* last redirect in command->redirects list */
363 struct redir_struct *pending_redirect;
369 smallint ctx_inverted; /* "! cmd | cmd" */
371 smallint ctx_dsemicolon; /* ";;" seen */
373 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
375 /* group we are enclosed in:
376 * example: "if pipe1; pipe2; then pipe3; fi"
377 * when we see "if" or "then", we malloc and copy current context,
378 * and make ->stack point to it. then we parse pipeN.
379 * when closing "then" / fi" / whatever is found,
380 * we move list_head into ->stack->command->group,
381 * copy ->stack into current context, and delete ->stack.
382 * (parsing of { list } and ( list ) doesn't use this method)
384 struct parse_context *stack;
388 /* On program start, environ points to initial environment.
389 * putenv adds new pointers into it, unsetenv removes them.
390 * Neither of these (de)allocates the strings.
391 * setenv allocates new strings in malloc space and does putenv,
392 * and thus setenv is unusable (leaky) for shell's purposes */
393 #define setenv(...) setenv_is_leaky_dont_use()
395 struct variable *next;
396 char *varstr; /* points to "name=" portion */
397 int max_len; /* if > 0, name is part of initial env; else name is malloced */
398 smallint flg_export; /* putenv should be done on this var */
399 smallint flg_read_only;
407 #if ENABLE_HUSH_FUNCTIONS
409 struct function *next;
411 struct command *parent_cmd;
414 char *body_as_string;
420 /* "Globals" within this file */
421 /* Sorted roughly by size (smaller offsets == smaller code) */
423 /* interactive_fd != 0 means we are an interactive shell.
424 * If we are, then saved_tty_pgrp can also be != 0, meaning
425 * that controlling tty is available. With saved_tty_pgrp == 0,
426 * job control still works, but terminal signals
427 * (^C, ^Z, ^Y, ^\) won't work at all, and background
428 * process groups can only be created with "cmd &".
429 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
430 * to give tty to the foreground process group,
431 * and will take it back when the group is stopped (^Z)
434 #if ENABLE_HUSH_INTERACTIVE
435 /* 'interactive_fd' is a fd# open to ctty, if we have one
436 * _AND_ if we decided to act interactively */
440 # define G_interactive_fd (G.interactive_fd)
442 # define G_interactive_fd 0
444 #if ENABLE_FEATURE_EDITING
445 line_input_t *line_input_state;
452 pid_t saved_tty_pgrp;
453 struct pipe *job_list;
454 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
456 # define G_saved_tty_pgrp 0
458 smallint flag_SIGINT;
459 #if ENABLE_HUSH_LOOPS
460 smallint flag_break_continue;
462 #if ENABLE_HUSH_FUNCTIONS
463 /* 0: outside of a function (or sourced file)
464 * -1: inside of a function, ok to use return builtin
465 * 1: return is invoked, skip all till end of func
467 smallint flag_return_in_progress;
470 smallint exiting; /* used to prevent EXIT trap recursion */
471 /* These four support $?, $#, and $1 */
472 smalluint last_exitcode;
473 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
474 smalluint global_args_malloced;
475 /* how many non-NULL argv's we have. NB: $# + 1 */
479 char *argv0_for_re_execing;
481 #if ENABLE_HUSH_LOOPS
482 unsigned depth_break_continue;
483 unsigned depth_of_loop;
487 struct variable *top_var; /* = &G.shell_ver (set in main()) */
488 struct variable shell_ver;
489 #if ENABLE_HUSH_FUNCTIONS
490 struct function *top_func;
492 /* Signal and trap handling */
494 unsigned count_SIGCHLD;
495 unsigned handled_SIGCHLD;
496 smallint we_have_children;
498 /* which signals have non-DFL handler (even with no traps set)? */
499 unsigned non_DFL_mask;
500 char **traps; /* char *traps[NSIG] */
501 sigset_t blocked_set;
502 sigset_t inherited_set;
504 unsigned long memleak_value;
507 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
509 #define G (*ptr_to_globals)
510 /* Not #defining name to G.name - this quickly gets unwieldy
511 * (too many defines). Also, I actually prefer to see when a variable
512 * is global, thus "G." prefix is a useful hint */
513 #define INIT_G() do { \
514 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
518 /* Function prototypes for builtins */
519 static int builtin_cd(char **argv);
520 static int builtin_echo(char **argv);
521 static int builtin_eval(char **argv);
522 static int builtin_exec(char **argv);
523 static int builtin_exit(char **argv);
524 static int builtin_export(char **argv);
526 static int builtin_fg_bg(char **argv);
527 static int builtin_jobs(char **argv);
530 static int builtin_help(char **argv);
533 static int builtin_memleak(char **argv);
535 static int builtin_pwd(char **argv);
536 static int builtin_read(char **argv);
537 static int builtin_set(char **argv);
538 static int builtin_shift(char **argv);
539 static int builtin_source(char **argv);
540 static int builtin_test(char **argv);
541 static int builtin_trap(char **argv);
542 static int builtin_type(char **argv);
543 static int builtin_true(char **argv);
544 static int builtin_umask(char **argv);
545 static int builtin_unset(char **argv);
546 static int builtin_wait(char **argv);
547 #if ENABLE_HUSH_LOOPS
548 static int builtin_break(char **argv);
549 static int builtin_continue(char **argv);
551 #if ENABLE_HUSH_FUNCTIONS
552 static int builtin_return(char **argv);
555 /* Table of built-in functions. They can be forked or not, depending on
556 * context: within pipes, they fork. As simple commands, they do not.
557 * When used in non-forking context, they can change global variables
558 * in the parent shell process. If forked, of course they cannot.
559 * For example, 'unset foo | whatever' will parse and run, but foo will
560 * still be set at the end. */
561 struct built_in_command {
563 int (*function)(char **argv);
566 #define BLTIN(cmd, func, help) { cmd, func, help }
568 #define BLTIN(cmd, func, help) { cmd, func }
572 /* For now, echo and test are unconditionally enabled.
573 * Maybe make it configurable? */
574 static const struct built_in_command bltins[] = {
575 BLTIN("." , builtin_source , "Run commands in a file"),
576 BLTIN(":" , builtin_true , "No-op"),
577 BLTIN("[" , builtin_test , "Test condition"),
579 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
581 #if ENABLE_HUSH_LOOPS
582 BLTIN("break" , builtin_break , "Exit from a loop"),
584 BLTIN("cd" , builtin_cd , "Change directory"),
585 #if ENABLE_HUSH_LOOPS
586 BLTIN("continue", builtin_continue, "Start new loop iteration"),
588 BLTIN("echo" , builtin_echo , "Write to stdout"),
589 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
590 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
591 BLTIN("exit" , builtin_exit , "Exit"),
592 BLTIN("export" , builtin_export , "Set environment variable"),
594 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
597 BLTIN("help" , builtin_help , "List shell built-in commands"),
600 BLTIN("jobs" , builtin_jobs , "List active jobs"),
603 BLTIN("memleak" , builtin_memleak , "Debug tool"),
605 BLTIN("pwd" , builtin_pwd , "Print current directory"),
606 BLTIN("read" , builtin_read , "Input environment variable"),
607 #if ENABLE_HUSH_FUNCTIONS
608 BLTIN("return" , builtin_return , "Return from a function"),
610 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
611 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
612 BLTIN("test" , builtin_test , "Test condition"),
613 BLTIN("trap" , builtin_trap , "Trap signals"),
614 BLTIN("type" , builtin_type , "Write a description of command type"),
615 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
616 BLTIN("umask" , builtin_umask , "Set file creation mask"),
617 BLTIN("unset" , builtin_unset , "Unset environment variable"),
618 BLTIN("wait" , builtin_wait , "Wait for process"),
625 /* prevent disasters with G.debug_indent < 0 */
626 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
627 # define debug_enter() (G.debug_indent++)
628 # define debug_leave() (G.debug_indent--)
630 # define indent() ((void)0)
631 # define debug_enter() ((void)0)
632 # define debug_leave() ((void)0)
636 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
639 #ifndef debug_printf_parse
640 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
643 #ifndef debug_printf_exec
644 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
647 #ifndef debug_printf_env
648 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
651 #ifndef debug_printf_jobs
652 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
653 # define DEBUG_JOBS 1
655 # define DEBUG_JOBS 0
658 #ifndef debug_printf_expand
659 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
660 # define DEBUG_EXPAND 1
662 # define DEBUG_EXPAND 0
665 #ifndef debug_printf_glob
666 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
667 # define DEBUG_GLOB 1
669 # define DEBUG_GLOB 0
672 #ifndef debug_printf_list
673 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
676 #ifndef debug_printf_subst
677 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
680 #ifndef debug_printf_clean
681 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
682 # define DEBUG_CLEAN 1
684 # define DEBUG_CLEAN 0
688 static void debug_print_strings(const char *prefix, char **vv)
691 fprintf(stderr, "%s:\n", prefix);
693 fprintf(stderr, " '%s'\n", *vv++);
696 #define debug_print_strings(prefix, vv) ((void)0)
700 /* Leak hunting. Use hush_leaktool.sh for post-processing.
703 static void *xxmalloc(int lineno, size_t size)
705 void *ptr = xmalloc((size + 0xff) & ~0xff);
706 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
709 static void *xxrealloc(int lineno, void *ptr, size_t size)
711 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
712 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
715 static char *xxstrdup(int lineno, const char *str)
717 char *ptr = xstrdup(str);
718 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
721 static void xxfree(void *ptr)
723 fdprintf(2, "free %p\n", ptr);
726 #define xmalloc(s) xxmalloc(__LINE__, s)
727 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
728 #define xstrdup(s) xxstrdup(__LINE__, s)
729 #define free(p) xxfree(p)
733 /* Syntax and runtime errors. They always abort scripts.
734 * In interactive use they usually discard unparsed and/or unexecuted commands
735 * and return to the prompt.
736 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
739 # define die_if_script(lineno, fmt...) die_if_script(fmt)
740 # define syntax_error(lineno, msg) syntax_error(msg)
741 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
742 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
743 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
744 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
747 static void die_if_script(unsigned lineno, const char *fmt, ...)
752 bb_error_msg("hush.c:%u", lineno);
755 bb_verror_msg(fmt, p, NULL);
757 if (!G_interactive_fd)
761 static void syntax_error(unsigned lineno, const char *msg)
764 die_if_script(lineno, "syntax error: %s", msg);
766 die_if_script(lineno, "syntax error", NULL);
769 static void syntax_error_at(unsigned lineno, const char *msg)
771 die_if_script(lineno, "syntax error at '%s'", msg);
774 /* It so happens that all such cases are totally fatal
775 * even if shell is interactive: EOF while looking for closing
776 * delimiter. There is nowhere to read stuff from after that,
777 * it's EOF! The only choice is to terminate.
779 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
780 static void syntax_error_unterm_ch(unsigned lineno, char ch)
785 die_if_script(lineno, "syntax error: unterminated %s", msg);
789 static void syntax_error_unterm_str(unsigned lineno, const char *s)
791 die_if_script(lineno, "syntax error: unterminated %s", s);
794 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
799 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
803 # undef die_if_script
805 # undef syntax_error_at
806 # undef syntax_error_unterm_ch
807 # undef syntax_error_unterm_str
808 # undef syntax_error_unexpected_ch
810 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
811 # define syntax_error(msg) syntax_error(__LINE__, msg)
812 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
813 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
814 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
815 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
819 #if ENABLE_HUSH_INTERACTIVE
820 static void cmdedit_update_prompt(void);
822 # define cmdedit_update_prompt()
828 static int glob_needed(const char *s)
833 if (*s == '*' || *s == '[' || *s == '?')
840 static int is_well_formed_var_name(const char *s, char terminator)
842 if (!s || !(isalpha(*s) || *s == '_'))
845 while (isalnum(*s) || *s == '_')
847 return *s == terminator;
850 /* Replace each \x with x in place, return ptr past NUL. */
851 static char *unbackslash(char *src)
857 if ((*dst++ = *src++) == '\0')
863 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
884 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
885 v[count1 + count2] = NULL;
888 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
892 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
894 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
895 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
898 #define add_strings_to_strings(strings, add, need_to_dup) \
899 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
902 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
903 static char **add_string_to_strings(char **strings, char *add)
908 return add_strings_to_strings(strings, v, /*dup:*/ 0);
911 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
913 char **ptr = add_string_to_strings(strings, add);
914 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
917 #define add_string_to_strings(strings, add) \
918 xx_add_string_to_strings(__LINE__, strings, add)
921 static void free_strings(char **strings)
936 /* Helpers for setting new $n and restoring them back
938 typedef struct save_arg_t {
942 smallint sv_g_malloced;
945 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
949 sv->sv_argv0 = argv[0];
950 sv->sv_g_argv = G.global_argv;
951 sv->sv_g_argc = G.global_argc;
952 sv->sv_g_malloced = G.global_args_malloced;
954 argv[0] = G.global_argv[0]; /* retain $0 */
955 G.global_argv = argv;
956 G.global_args_malloced = 0;
964 static void restore_G_args(save_arg_t *sv, char **argv)
968 if (G.global_args_malloced) {
969 /* someone ran "set -- arg1 arg2 ...", undo */
971 while (*++pp) /* note: does not free $0 */
975 argv[0] = sv->sv_argv0;
976 G.global_argv = sv->sv_g_argv;
977 G.global_argc = sv->sv_g_argc;
978 G.global_args_malloced = sv->sv_g_malloced;
982 /* Basic theory of signal handling in shell
983 * ========================================
984 * This does not describe what hush does, rather, it is current understanding
985 * what it _should_ do. If it doesn't, it's a bug.
986 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
988 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
989 * is finished or backgrounded. It is the same in interactive and
990 * non-interactive shells, and is the same regardless of whether
991 * a user trap handler is installed or a shell special one is in effect.
992 * ^C or ^Z from keyboard seem to execute "at once" because it usually
993 * backgrounds (i.e. stops) or kills all members of currently running
996 * Wait builtin in interruptible by signals for which user trap is set
997 * or by SIGINT in interactive shell.
999 * Trap handlers will execute even within trap handlers. (right?)
1001 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1003 * If job control is off, backgrounded commands ("cmd &")
1004 * have SIGINT, SIGQUIT set to SIG_IGN.
1006 * Commands run in command substitution ("`cmd`")
1007 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1009 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
1010 * by the shell from its parent.
1012 * Siganls which differ from SIG_DFL action
1013 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1016 * SIGTERM (interactive): ignore
1017 * SIGHUP (interactive):
1018 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1019 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1020 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1021 * that all pipe members are stopped. Try this in bash:
1022 * while :; do :; done - ^Z does not background it
1023 * (while :; do :; done) - ^Z backgrounds it
1024 * SIGINT (interactive): wait for last pipe, ignore the rest
1025 * of the command line, show prompt. NB: ^C does not send SIGINT
1026 * to interactive shell while shell is waiting for a pipe,
1027 * since shell is bg'ed (is not in foreground process group).
1028 * Example 1: this waits 5 sec, but does not execute ls:
1029 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1030 * Example 2: this does not wait and does not execute ls:
1031 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1032 * Example 3: this does not wait 5 sec, but executes ls:
1033 * "sleep 5; ls -l" + press ^C
1035 * (What happens to signals which are IGN on shell start?)
1036 * (What happens with signal mask on shell start?)
1038 * Implementation in hush
1039 * ======================
1040 * We use in-kernel pending signal mask to determine which signals were sent.
1041 * We block all signals which we don't want to take action immediately,
1042 * i.e. we block all signals which need to have special handling as described
1043 * above, and all signals which have traps set.
1044 * After each pipe execution, we extract any pending signals via sigtimedwait()
1047 * unsigned non_DFL_mask: a mask of such "special" signals
1048 * sigset_t blocked_set: current blocked signal set
1051 * clear bit in blocked_set unless it is also in non_DFL_mask
1052 * "trap 'cmd' SIGxxx":
1053 * set bit in blocked_set (even if 'cmd' is '')
1054 * after [v]fork, if we plan to be a shell:
1055 * unblock signals with special interactive handling
1056 * (child shell is not interactive),
1057 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1058 * after [v]fork, if we plan to exec:
1059 * POSIX says pending signal mask is cleared in child - no need to clear it.
1060 * Restore blocked signal set to one inherited by shell just prior to exec.
1062 * Note: as a result, we do not use signal handlers much. The only uses
1063 * are to count SIGCHLDs
1064 * and to restore tty pgrp on signal-induced exit.
1067 SPECIAL_INTERACTIVE_SIGS = 0
1072 SPECIAL_JOB_SIGS = 0
1080 #if ENABLE_HUSH_FAST
1081 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1084 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1090 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1091 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1092 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1093 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1095 /* Restores tty foreground process group, and exits.
1096 * May be called as signal handler for fatal signal
1097 * (will resend signal to itself, producing correct exit state)
1098 * or called directly with -EXITCODE.
1099 * We also call it if xfunc is exiting. */
1100 static void sigexit(int sig) NORETURN;
1101 static void sigexit(int sig)
1103 /* Disable all signals: job control, SIGPIPE, etc. */
1104 sigprocmask_allsigs(SIG_BLOCK);
1106 /* Careful: we can end up here after [v]fork. Do not restore
1107 * tty pgrp then, only top-level shell process does that */
1108 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1109 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1111 /* Not a signal, just exit */
1115 kill_myself_with_sig(sig); /* does not return */
1119 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1120 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1124 /* Restores tty foreground process group, and exits. */
1125 static void hush_exit(int exitcode) NORETURN;
1126 static void hush_exit(int exitcode)
1128 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1129 /* Prevent recursion:
1130 * trap "echo Hi; exit" EXIT; exit
1132 char *argv[] = { NULL, G.traps[0], NULL };
1140 fflush(NULL); /* flush all streams */
1141 sigexit(- (exitcode & 0xff));
1147 static int check_and_run_traps(int sig)
1149 static const struct timespec zero_timespec = { 0, 0 };
1150 smalluint save_rcode;
1156 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1161 if (G.traps && G.traps[sig]) {
1162 if (G.traps[sig][0]) {
1163 /* We have user-defined handler */
1164 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1165 save_rcode = G.last_exitcode;
1168 G.last_exitcode = save_rcode;
1169 } /* else: "" trap, ignoring signal */
1172 /* not a trap: special action */
1174 #if ENABLE_HUSH_FAST
1177 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1181 /* Builtin was ^C'ed, make it look prettier: */
1188 /* bash is observed to signal whole process groups,
1189 * not individual processes */
1190 for (job = G.job_list; job; job = job->next) {
1193 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1194 if (kill(- job->pgrp, SIGHUP) == 0)
1195 kill(- job->pgrp, SIGCONT);
1200 default: /* ignored: */
1201 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1209 static const char *set_cwd(void)
1211 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1212 * we must not try to free(bb_msg_unknown) */
1213 if (G.cwd == bb_msg_unknown)
1215 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1217 G.cwd = bb_msg_unknown;
1223 * Shell and environment variable support
1225 static struct variable **get_ptr_to_local_var(const char *name)
1227 struct variable **pp;
1228 struct variable *cur;
1233 while ((cur = *pp) != NULL) {
1234 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1241 static struct variable *get_local_var(const char *name)
1243 struct variable **pp = get_ptr_to_local_var(name);
1249 static const char *get_local_var_value(const char *name)
1251 struct variable **pp = get_ptr_to_local_var(name);
1253 return strchr((*pp)->varstr, '=') + 1;
1257 /* str holds "NAME=VAL" and is expected to be malloced.
1258 * We take ownership of it.
1260 * 0: do not change export flag
1261 * (if creating new variable, flag will be 0)
1262 * 1: set export flag and putenv the variable
1263 * -1: clear export flag and unsetenv the variable
1264 * flg_read_only is set only when we handle -R var=val
1267 #define set_local_var(str, flg_export, flg_read_only) \
1268 set_local_var(str, flg_export)
1270 static int set_local_var(char *str, int flg_export, int flg_read_only)
1272 struct variable *cur;
1276 eq_sign = strchr(str, '=');
1277 if (!eq_sign) { /* not expected to ever happen? */
1282 name_len = eq_sign - str + 1; /* including '=' */
1283 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1285 if (strncmp(cur->varstr, str, name_len) != 0) {
1287 /* Bail out. Note that now cur points
1288 * to last var in linked list */
1294 /* We found an existing var with this name */
1295 if (cur->flg_read_only) {
1299 bb_error_msg("%s: readonly variable", str);
1303 if (flg_export == -1) {
1304 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1309 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1314 if (cur->max_len >= strlen(str)) {
1315 /* This one is from startup env, reuse space */
1316 strcpy(cur->varstr, str);
1319 /* max_len == 0 signifies "malloced" var, which we can
1320 * (and has to) free */
1324 goto set_str_and_exp;
1327 /* Not found - create next variable struct */
1328 cur->next = xzalloc(sizeof(*cur));
1334 cur->flg_read_only = flg_read_only;
1337 if (flg_export == 1)
1338 cur->flg_export = 1;
1339 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1340 cmdedit_update_prompt();
1341 if (cur->flg_export) {
1342 if (flg_export == -1) {
1343 cur->flg_export = 0;
1344 /* unsetenv was already done */
1346 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1347 return putenv(cur->varstr);
1353 static int unset_local_var_len(const char *name, int name_len)
1355 struct variable *cur;
1356 struct variable **var_pp;
1359 return EXIT_SUCCESS;
1360 var_pp = &G.top_var;
1361 while ((cur = *var_pp) != NULL) {
1362 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1363 if (cur->flg_read_only) {
1364 bb_error_msg("%s: readonly variable", name);
1365 return EXIT_FAILURE;
1367 *var_pp = cur->next;
1368 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1369 bb_unsetenv(cur->varstr);
1370 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1371 cmdedit_update_prompt();
1375 return EXIT_SUCCESS;
1377 var_pp = &cur->next;
1379 return EXIT_SUCCESS;
1382 static int unset_local_var(const char *name)
1384 return unset_local_var_len(name, strlen(name));
1387 static void unset_vars(char **strings)
1395 const char *eq = strchrnul(*v, '=');
1396 unset_local_var_len(*v, (int)(eq - *v));
1402 #if ENABLE_SH_MATH_SUPPORT
1403 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1404 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1405 static char *endofname(const char *name)
1413 if (!is_in_name(*p))
1419 static void arith_set_local_var(const char *name, const char *val, int flags)
1421 /* arith code doesnt malloc space, so do it for it */
1422 char *var = xasprintf("%s=%s", name, val);
1423 set_local_var(var, flags, 0);
1429 * Helpers for "var1=val1 var2=val2 cmd" feature
1431 static void add_vars(struct variable *var)
1433 struct variable *next;
1437 var->next = G.top_var;
1439 if (var->flg_export) {
1440 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1441 putenv(var->varstr);
1443 debug_printf_env("%s: restoring local '%s'\n", __func__, var->varstr);
1449 static struct variable *set_vars_and_save_old(char **strings)
1452 struct variable *old = NULL;
1458 struct variable *var_p;
1459 struct variable **var_pp;
1462 eq = strchr(*s, '=');
1465 var_pp = get_ptr_to_local_var(*s);
1468 /* Remove variable from global linked list */
1470 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1471 *var_pp = var_p->next;
1472 /* Add it to returned list */
1476 set_local_var(*s, 1, 0);
1487 static int static_get(struct in_str *i)
1496 static int static_peek(struct in_str *i)
1501 #if ENABLE_HUSH_INTERACTIVE
1503 static void cmdedit_update_prompt(void)
1505 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1506 G.PS1 = get_local_var_value("PS1");
1509 G.PS2 = get_local_var_value("PS2");
1517 static const char* setup_prompt_string(int promptmode)
1519 const char *prompt_str;
1520 debug_printf("setup_prompt_string %d ", promptmode);
1521 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1522 /* Set up the prompt */
1523 if (promptmode == 0) { /* PS1 */
1525 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1530 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1531 debug_printf("result '%s'\n", prompt_str);
1535 static void get_user_input(struct in_str *i)
1538 const char *prompt_str;
1540 prompt_str = setup_prompt_string(i->promptmode);
1541 #if ENABLE_FEATURE_EDITING
1542 /* Enable command line editing only while a command line
1543 * is actually being read */
1546 /* buglet: SIGINT will not make new prompt to appear _at once_,
1547 * only after <Enter>. (^C will work) */
1548 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1549 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1550 check_and_run_traps(0);
1551 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1552 i->eof_flag = (r < 0);
1553 if (i->eof_flag) { /* EOF/error detected */
1554 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1555 G.user_input_buf[1] = '\0';
1560 fputs(prompt_str, stdout);
1562 G.user_input_buf[0] = r = fgetc(i->file);
1563 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1564 //do we need check_and_run_traps(0)? (maybe only if stdin)
1565 } while (G.flag_SIGINT);
1566 i->eof_flag = (r == EOF);
1568 i->p = G.user_input_buf;
1571 #endif /* INTERACTIVE */
1573 /* This is the magic location that prints prompts
1574 * and gets data back from the user */
1575 static int file_get(struct in_str *i)
1579 /* If there is data waiting, eat it up */
1580 if (i->p && *i->p) {
1581 #if ENABLE_HUSH_INTERACTIVE
1585 if (i->eof_flag && !*i->p)
1587 /* note: ch is never NUL */
1589 /* need to double check i->file because we might be doing something
1590 * more complicated by now, like sourcing or substituting. */
1591 #if ENABLE_HUSH_INTERACTIVE
1592 if (G_interactive_fd && i->promptme && i->file == stdin) {
1595 } while (!*i->p); /* need non-empty line */
1596 i->promptmode = 1; /* PS2 */
1601 do ch = fgetc(i->file); while (ch == '\0');
1603 debug_printf("file_get: got '%c' %d\n", ch, ch);
1604 #if ENABLE_HUSH_INTERACTIVE
1611 /* All callers guarantee this routine will never
1612 * be used right after a newline, so prompting is not needed.
1614 static int file_peek(struct in_str *i)
1617 if (i->p && *i->p) {
1618 if (i->eof_flag && !i->p[1])
1621 /* note: ch is never NUL */
1623 do ch = fgetc(i->file); while (ch == '\0');
1624 i->eof_flag = (ch == EOF);
1625 i->peek_buf[0] = ch;
1626 i->peek_buf[1] = '\0';
1628 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1632 static void setup_file_in_str(struct in_str *i, FILE *f)
1634 i->peek = file_peek;
1636 #if ENABLE_HUSH_INTERACTIVE
1638 i->promptmode = 0; /* PS1 */
1644 static void setup_string_in_str(struct in_str *i, const char *s)
1646 i->peek = static_peek;
1647 i->get = static_get;
1648 #if ENABLE_HUSH_INTERACTIVE
1650 i->promptmode = 0; /* PS1 */
1660 #define B_CHUNK (32 * sizeof(char*))
1662 static void o_reset_to_empty_unquoted(o_string *o)
1670 static void o_free(o_string *o)
1673 memset(o, 0, sizeof(*o));
1676 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1681 static void o_grow_by(o_string *o, int len)
1683 if (o->length + len > o->maxlen) {
1684 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1685 o->data = xrealloc(o->data, 1 + o->maxlen);
1689 static void o_addchr(o_string *o, int ch)
1691 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1693 o->data[o->length] = ch;
1695 o->data[o->length] = '\0';
1698 static void o_addblock(o_string *o, const char *str, int len)
1701 memcpy(&o->data[o->length], str, len);
1703 o->data[o->length] = '\0';
1707 static void o_addstr(o_string *o, const char *str)
1709 o_addblock(o, str, strlen(str));
1711 static void nommu_addchr(o_string *o, int ch)
1717 #define nommu_addchr(o, str) ((void)0)
1720 static void o_addstr_with_NUL(o_string *o, const char *str)
1722 o_addblock(o, str, strlen(str) + 1);
1725 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1730 && (*str != '*' && *str != '?' && *str != '[')
1738 /* My analysis of quoting semantics tells me that state information
1739 * is associated with a destination, not a source.
1741 static void o_addqchr(o_string *o, int ch)
1744 char *found = strchr("*?[\\", ch);
1749 o->data[o->length] = '\\';
1752 o->data[o->length] = ch;
1754 o->data[o->length] = '\0';
1757 static void o_addQchr(o_string *o, int ch)
1760 if (o->o_escape && strchr("*?[\\", ch)) {
1762 o->data[o->length] = '\\';
1766 o->data[o->length] = ch;
1768 o->data[o->length] = '\0';
1771 static void o_addQstr(o_string *o, const char *str, int len)
1774 o_addblock(o, str, len);
1780 int ordinary_cnt = strcspn(str, "*?[\\");
1781 if (ordinary_cnt > len) /* paranoia */
1783 o_addblock(o, str, ordinary_cnt);
1784 if (ordinary_cnt == len)
1786 str += ordinary_cnt;
1787 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1791 if (ch) { /* it is necessarily one of "*?[\\" */
1793 o->data[o->length] = '\\';
1797 o->data[o->length] = ch;
1799 o->data[o->length] = '\0';
1803 /* A special kind of o_string for $VAR and `cmd` expansion.
1804 * It contains char* list[] at the beginning, which is grown in 16 element
1805 * increments. Actual string data starts at the next multiple of 16 * (char*).
1806 * list[i] contains an INDEX (int!) into this string data.
1807 * It means that if list[] needs to grow, data needs to be moved higher up
1808 * but list[i]'s need not be modified.
1809 * NB: remembering how many list[i]'s you have there is crucial.
1810 * o_finalize_list() operation post-processes this structure - calculates
1811 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1813 #if DEBUG_EXPAND || DEBUG_GLOB
1814 static void debug_print_list(const char *prefix, o_string *o, int n)
1816 char **list = (char**)o->data;
1817 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1821 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1822 prefix, list, n, string_start, o->length, o->maxlen);
1825 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1826 o->data + (int)list[i] + string_start,
1827 o->data + (int)list[i] + string_start);
1831 const char *p = o->data + (int)list[n - 1] + string_start;
1833 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1837 #define debug_print_list(prefix, o, n) ((void)0)
1840 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1841 * in list[n] so that it points past last stored byte so far.
1842 * It returns n+1. */
1843 static int o_save_ptr_helper(o_string *o, int n)
1845 char **list = (char**)o->data;
1849 if (!o->has_empty_slot) {
1850 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1851 string_len = o->length - string_start;
1852 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1853 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1854 /* list[n] points to string_start, make space for 16 more pointers */
1855 o->maxlen += 0x10 * sizeof(list[0]);
1856 o->data = xrealloc(o->data, o->maxlen + 1);
1857 list = (char**)o->data;
1858 memmove(list + n + 0x10, list + n, string_len);
1859 o->length += 0x10 * sizeof(list[0]);
1861 debug_printf_list("list[%d]=%d string_start=%d\n",
1862 n, string_len, string_start);
1865 /* We have empty slot at list[n], reuse without growth */
1866 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1867 string_len = o->length - string_start;
1868 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1869 n, string_len, string_start);
1870 o->has_empty_slot = 0;
1872 list[n] = (char*)(ptrdiff_t)string_len;
1876 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1877 static int o_get_last_ptr(o_string *o, int n)
1879 char **list = (char**)o->data;
1880 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1882 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1885 /* o_glob performs globbing on last list[], saving each result
1886 * as a new list[]. */
1887 static int o_glob(o_string *o, int n)
1893 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1895 return o_save_ptr_helper(o, n);
1896 pattern = o->data + o_get_last_ptr(o, n);
1897 debug_printf_glob("glob pattern '%s'\n", pattern);
1898 if (!glob_needed(pattern)) {
1900 o->length = unbackslash(pattern) - o->data;
1901 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1902 return o_save_ptr_helper(o, n);
1905 memset(&globdata, 0, sizeof(globdata));
1906 gr = glob(pattern, 0, NULL, &globdata);
1907 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1908 if (gr == GLOB_NOSPACE)
1909 bb_error_msg_and_die("out of memory during glob");
1910 if (gr == GLOB_NOMATCH) {
1911 globfree(&globdata);
1914 if (gr != 0) { /* GLOB_ABORTED ? */
1915 /* TODO: testcase for bad glob pattern behavior */
1916 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1918 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1919 char **argv = globdata.gl_pathv;
1920 o->length = pattern - o->data; /* "forget" pattern */
1922 o_addstr_with_NUL(o, *argv);
1923 n = o_save_ptr_helper(o, n);
1929 globfree(&globdata);
1931 debug_print_list("o_glob returning", o, n);
1935 /* If o->o_glob == 1, glob the string so far remembered.
1936 * Otherwise, just finish current list[] and start new */
1937 static int o_save_ptr(o_string *o, int n)
1939 if (o->o_glob) { /* if globbing is requested */
1940 /* If o->has_empty_slot, list[n] was already globbed
1941 * (if it was requested back then when it was filled)
1942 * so don't do that again! */
1943 if (!o->has_empty_slot)
1944 return o_glob(o, n); /* o_save_ptr_helper is inside */
1946 return o_save_ptr_helper(o, n);
1949 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1950 static char **o_finalize_list(o_string *o, int n)
1955 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1957 debug_print_list("finalized", o, n);
1958 debug_printf_expand("finalized n:%d\n", n);
1959 list = (char**)o->data;
1960 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1964 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1970 /* Expansion can recurse */
1971 #if ENABLE_HUSH_TICK
1972 static int process_command_subs(o_string *dest, const char *s);
1974 static char *expand_string_to_string(const char *str);
1976 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1977 parse_stream_dquoted(dest, input, dquote_end)
1979 static int parse_stream_dquoted(o_string *as_string,
1981 struct in_str *input,
1984 /* expand_strvec_to_strvec() takes a list of strings, expands
1985 * all variable references within and returns a pointer to
1986 * a list of expanded strings, possibly with larger number
1987 * of strings. (Think VAR="a b"; echo $VAR).
1988 * This new list is allocated as a single malloc block.
1989 * NULL-terminated list of char* pointers is at the beginning of it,
1990 * followed by strings themself.
1991 * Caller can deallocate entire list by single free(list). */
1993 /* Store given string, finalizing the word and starting new one whenever
1994 * we encounter IFS char(s). This is used for expanding variable values.
1995 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1996 static int expand_on_ifs(o_string *output, int n, const char *str)
1999 int word_len = strcspn(str, G.ifs);
2001 if (output->o_escape || !output->o_glob)
2002 o_addQstr(output, str, word_len);
2003 else /* protect backslashes against globbing up :) */
2004 o_addblock_duplicate_backslash(output, str, word_len);
2007 if (!*str) /* EOL - do not finalize word */
2009 o_addchr(output, '\0');
2010 debug_print_list("expand_on_ifs", output, n);
2011 n = o_save_ptr(output, n);
2012 str += strspn(str, G.ifs); /* skip ifs chars */
2014 debug_print_list("expand_on_ifs[1]", output, n);
2018 /* Helper to expand $((...)) and heredoc body. These act as if
2019 * they are in double quotes, with the exception that they are not :).
2020 * Just the rules are similar: "expand only $var and `cmd`"
2022 * Returns malloced string.
2023 * As an optimization, we return NULL if expansion is not needed.
2025 static char *expand_pseudo_dquoted(const char *str)
2028 struct in_str input;
2029 o_string dest = NULL_O_STRING;
2031 if (strchr(str, '$') == NULL
2032 #if ENABLE_HUSH_TICK
2033 && strchr(str, '`') == NULL
2039 /* We need to expand. Example:
2040 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2042 setup_string_in_str(&input, str);
2043 parse_stream_dquoted(NULL, &dest, &input, EOF);
2044 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2045 exp_str = expand_string_to_string(dest.data);
2046 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2047 o_free_unsafe(&dest);
2051 /* Expand all variable references in given string, adding words to list[]
2052 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2053 * to be filled). This routine is extremely tricky: has to deal with
2054 * variables/parameters with whitespace, $* and $@, and constructs like
2055 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2056 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2058 /* or_mask is either 0 (normal case) or 0x80
2059 * (expansion of right-hand side of assignment == 1-element expand.
2060 * It will also do no globbing, and thus we must not backslash-quote!) */
2067 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2068 debug_print_list("expand_vars_to_list", output, n);
2069 n = o_save_ptr(output, n);
2070 debug_print_list("expand_vars_to_list[0]", output, n);
2072 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2075 char *dyn_val = NULL;
2076 const char *val = NULL;
2077 #if ENABLE_HUSH_TICK
2078 o_string subst_result = NULL_O_STRING;
2080 #if ENABLE_SH_MATH_SUPPORT
2081 char arith_buf[sizeof(arith_t)*3 + 2];
2083 o_addblock(output, arg, p - arg);
2084 debug_print_list("expand_vars_to_list[1]", output, n);
2086 p = strchr(p, SPECIAL_VAR_SYMBOL);
2088 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2089 /* "$@" is special. Even if quoted, it can still
2090 * expand to nothing (not even an empty string) */
2091 if ((first_ch & 0x7f) != '@')
2092 ored_ch |= first_ch;
2094 switch (first_ch & 0x7f) {
2095 /* Highest bit in first_ch indicates that var is double-quoted */
2097 val = utoa(G.root_pid);
2099 case '!': /* bg pid */
2100 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2102 case '?': /* exitcode */
2103 val = utoa(G.last_exitcode);
2105 case '#': /* argc */
2106 if (arg[1] != SPECIAL_VAR_SYMBOL)
2107 /* actually, it's a ${#var} */
2109 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2114 if (!G.global_argv[i])
2116 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2117 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2118 smallint sv = output->o_escape;
2119 /* unquoted var's contents should be globbed, so don't escape */
2120 output->o_escape = 0;
2121 while (G.global_argv[i]) {
2122 n = expand_on_ifs(output, n, G.global_argv[i]);
2123 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2124 if (G.global_argv[i++][0] && G.global_argv[i]) {
2125 /* this argv[] is not empty and not last:
2126 * put terminating NUL, start new word */
2127 o_addchr(output, '\0');
2128 debug_print_list("expand_vars_to_list[2]", output, n);
2129 n = o_save_ptr(output, n);
2130 debug_print_list("expand_vars_to_list[3]", output, n);
2133 output->o_escape = sv;
2135 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2136 * and in this case should treat it like '$*' - see 'else...' below */
2137 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2139 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2140 if (++i >= G.global_argc)
2142 o_addchr(output, '\0');
2143 debug_print_list("expand_vars_to_list[4]", output, n);
2144 n = o_save_ptr(output, n);
2146 } else { /* quoted $*: add as one word */
2148 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2149 if (!G.global_argv[++i])
2152 o_addchr(output, G.ifs[0]);
2156 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2157 /* "Empty variable", used to make "" etc to not disappear */
2161 #if ENABLE_HUSH_TICK
2162 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2165 /* Can't just stuff it into output o_string,
2166 * expanded result may need to be globbed
2167 * and $IFS-splitted */
2168 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2169 process_command_subs(&subst_result, arg);
2170 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2171 val = subst_result.data;
2174 #if ENABLE_SH_MATH_SUPPORT
2175 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2176 arith_eval_hooks_t hooks;
2181 arg++; /* skip '+' */
2182 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2183 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2185 exp_str = expand_pseudo_dquoted(arg);
2186 hooks.lookupvar = get_local_var_value;
2187 hooks.setvar = arith_set_local_var;
2188 hooks.endofname = endofname;
2189 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2193 const char *msg = "error in arithmetic";
2196 msg = "exponent less than 0";
2199 msg = "divide by 0";
2202 msg = "expression recursion loop detected";
2207 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2208 sprintf(arith_buf, arith_t_fmt, res);
2213 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2215 bool exp_len = false;
2216 bool exp_null = false;
2218 char exp_save = exp_save; /* for compiler */
2219 char exp_op = exp_op; /* for compiler */
2220 char *exp_word = exp_word; /* for compiler */
2224 arg[0] = first_ch & 0x7f;
2226 /* prepare for expansions */
2227 if (var[0] == '#') {
2228 /* handle length expansion ${#var} */
2232 /* maybe handle parameter expansion */
2233 exp_off = strcspn(var, ":-=+?%#");
2237 exp_save = var[exp_off];
2238 exp_null = exp_save == ':';
2239 exp_word = var + exp_off;
2242 exp_op = *exp_word++;
2243 var[exp_off] = '\0';
2247 /* lookup the variable in question */
2248 if (isdigit(var[0])) {
2249 /* handle_dollar() should have vetted var for us */
2251 if (i < G.global_argc)
2252 val = G.global_argv[i];
2253 /* else val remains NULL: $N with too big N */
2255 val = get_local_var_value(var);
2257 /* handle any expansions */
2259 debug_printf_expand("expand: length of '%s' = ", val);
2260 val = utoa(val ? strlen(val) : 0);
2261 debug_printf_expand("%s\n", val);
2262 } else if (exp_off) {
2263 if (exp_op == '%' || exp_op == '#') {
2265 /* we need to do a pattern match */
2268 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2269 if (exp_op == *exp_word) /* ## or %% */
2271 val = dyn_val = xstrdup(val);
2272 loc = scan(dyn_val, exp_word, match_at_left);
2273 if (match_at_left) /* # or ## */
2275 else if (loc) /* % or %% and match was found */
2279 /* we need to do an expansion */
2280 int exp_test = (!val || (exp_null && !val[0]));
2282 exp_test = !exp_test;
2283 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2284 exp_null ? "true" : "false", exp_test);
2286 if (exp_op == '?') {
2287 //TODO: how interactive bash aborts expansion mid-command?
2288 /* ${var?[error_msg_if_unset]} */
2289 /* ${var:?[error_msg_if_unset_or_null]} */
2290 /* mimic bash message */
2291 die_if_script("%s: %s",
2293 exp_word[0] ? exp_word : "parameter null or not set"
2299 if (exp_op == '=') {
2300 /* ${var=[word]} or ${var:=[word]} */
2301 if (isdigit(var[0]) || var[0] == '#') {
2302 /* mimic bash message */
2303 die_if_script("$%s: cannot assign in this way", var);
2306 char *new_var = xasprintf("%s=%s", var, val);
2307 set_local_var(new_var, 0, 0);
2313 var[exp_off] = exp_save;
2317 #if ENABLE_HUSH_TICK
2320 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2321 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2323 /* unquoted var's contents should be globbed, so don't escape */
2324 smallint sv = output->o_escape;
2325 output->o_escape = 0;
2326 n = expand_on_ifs(output, n, val);
2328 output->o_escape = sv;
2330 } else { /* quoted $VAR, val will be appended below */
2331 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2334 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2337 o_addQstr(output, val, strlen(val));
2340 /* Do the check to avoid writing to a const string */
2341 if (*p != SPECIAL_VAR_SYMBOL)
2342 *p = SPECIAL_VAR_SYMBOL;
2344 #if ENABLE_HUSH_TICK
2345 o_free(&subst_result);
2348 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2351 debug_print_list("expand_vars_to_list[a]", output, n);
2352 /* this part is literal, and it was already pre-quoted
2353 * if needed (much earlier), do not use o_addQstr here! */
2354 o_addstr_with_NUL(output, arg);
2355 debug_print_list("expand_vars_to_list[b]", output, n);
2356 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2357 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2360 /* allow to reuse list[n] later without re-growth */
2361 output->has_empty_slot = 1;
2363 o_addchr(output, '\0');
2368 static char **expand_variables(char **argv, int or_mask)
2373 o_string output = NULL_O_STRING;
2375 if (or_mask & 0x100) {
2376 output.o_escape = 1; /* protect against globbing for "$var" */
2377 /* (unquoted $var will temporarily switch it off) */
2384 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2387 debug_print_list("expand_variables", &output, n);
2389 /* output.data (malloced in one block) gets returned in "list" */
2390 list = o_finalize_list(&output, n);
2391 debug_print_strings("expand_variables[1]", list);
2395 static char **expand_strvec_to_strvec(char **argv)
2397 return expand_variables(argv, 0x100);
2400 /* Used for expansion of right hand of assignments */
2401 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2403 static char *expand_string_to_string(const char *str)
2405 char *argv[2], **list;
2407 argv[0] = (char*)str;
2409 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2411 if (!list[0] || list[1])
2412 bb_error_msg_and_die("BUG in varexp2");
2413 /* actually, just move string 2*sizeof(char*) bytes back */
2414 overlapping_strcpy((char*)list, list[0]);
2415 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2419 /* Used for "eval" builtin */
2420 static char* expand_strvec_to_string(char **argv)
2424 list = expand_variables(argv, 0x80);
2425 /* Convert all NULs to spaces */
2430 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2431 bb_error_msg_and_die("BUG in varexp3");
2432 /* bash uses ' ' regardless of $IFS contents */
2437 overlapping_strcpy((char*)list, list[0]);
2438 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2442 static char **expand_assignments(char **argv, int count)
2446 /* Expand assignments into one string each */
2447 for (i = 0; i < count; i++) {
2448 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2456 void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
2458 static void reset_traps_to_defaults(void)
2460 /* This function is always called in a child shell
2461 * after fork (not vfork, NOMMU doesn't use this function).
2462 * Child shells are not interactive.
2463 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2464 * Testcase: (while :; do :; done) + ^Z should background.
2465 * Same goes for SIGTERM, SIGHUP, SIGINT.
2470 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2473 /* Stupid. It can be done with *single* &= op, but we can't use
2474 * the fact that G.blocked_set is implemented as a bitmask... */
2475 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2479 sigdelset(&G.blocked_set, sig);
2486 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2487 mask = G.non_DFL_mask;
2488 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2492 G.traps[sig] = NULL;
2493 /* There is no signal for 0 (EXIT) */
2496 /* There was a trap handler, we are removing it.
2497 * But if sig still has non-DFL handling,
2498 * we should not unblock it. */
2501 sigdelset(&G.blocked_set, sig);
2503 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2508 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2509 static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
2511 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2512 char *heredoc_argv[4];
2513 struct variable *cur;
2514 #if ENABLE_HUSH_FUNCTIONS
2515 struct function *funcp;
2520 if (!g_argv0) { /* heredoc */
2521 argv = heredoc_argv;
2522 argv[0] = (char *) G.argv0_for_re_execing;
2523 argv[1] = (char *) "-<";
2524 argv[2] = (char *) s;
2526 pp = &argv[3]; /* used as pointer to empty environment */
2530 sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
2531 , (unsigned) G.root_pid
2532 , (unsigned) G.last_bg_pid
2533 , (unsigned) G.last_exitcode
2534 IF_HUSH_LOOPS(, G.depth_of_loop)
2536 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2537 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2540 for (cur = G.top_var; cur; cur = cur->next) {
2541 if (!cur->flg_export || cur->flg_read_only)
2544 #if ENABLE_HUSH_FUNCTIONS
2545 for (funcp = G.top_func; funcp; funcp = funcp->next)
2551 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2552 *pp++ = (char *) G.argv0_for_re_execing;
2554 for (cur = G.top_var; cur; cur = cur->next) {
2555 if (cur->varstr == hush_version_str)
2557 if (cur->flg_read_only) {
2558 *pp++ = (char *) "-R";
2559 *pp++ = cur->varstr;
2560 } else if (!cur->flg_export) {
2561 *pp++ = (char *) "-V";
2562 *pp++ = cur->varstr;
2565 #if ENABLE_HUSH_FUNCTIONS
2566 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2567 *pp++ = (char *) "-F";
2568 *pp++ = funcp->name;
2569 *pp++ = funcp->body_as_string;
2572 /* We can pass activated traps here. Say, -Tnn:trap_string
2574 * However, POSIX says that subshells reset signals with traps
2576 * I tested bash-3.2 and it not only does that with true subshells
2577 * of the form ( list ), but with any forked children shells.
2578 * I set trap "echo W" WINCH; and then tried:
2580 * { echo 1; sleep 20; echo 2; } &
2581 * while true; do echo 1; sleep 20; echo 2; break; done &
2582 * true | { echo 1; sleep 20; echo 2; } | cat
2584 * In all these cases sending SIGWINCH to the child shell
2585 * did not run the trap. If I add trap "echo V" WINCH;
2586 * _inside_ group (just before echo 1), it works.
2588 * I conclude it means we don't need to pass active traps here.
2589 * exec syscall below resets them to SIG_DFL for us.
2591 *pp++ = (char *) "-c";
2596 /* *pp = NULL; - is already there */
2600 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2601 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2602 execve(bb_busybox_exec_path, argv, pp);
2603 /* Fallback. Useful for init=/bin/hush usage etc */
2604 if (argv[0][0] == '/')
2605 execve(argv[0], argv, pp);
2606 xfunc_error_retval = 127;
2607 bb_error_msg_and_die("can't re-execute the shell");
2609 #endif /* !BB_MMU */
2612 static void setup_heredoc(struct redir_struct *redir)
2614 struct fd_pair pair;
2617 /* the _body_ of heredoc (misleading field name) */
2618 const char *heredoc = redir->rd_filename;
2625 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2626 expanded = expand_pseudo_dquoted(heredoc);
2630 len = strlen(heredoc);
2632 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2634 xmove_fd(pair.rd, redir->rd_fd);
2636 /* Try writing without forking. Newer kernels have
2637 * dynamically growing pipes. Must use non-blocking write! */
2640 written = write(pair.wr, heredoc, len);
2651 ndelay_off(pair.wr);
2653 /* Okay, pipe buffer was not big enough */
2654 /* Note: we must not create a stray child (bastard? :)
2655 * for the unsuspecting parent process. Child creates a grandchild
2656 * and exits before parent execs the process which consumes heredoc
2657 * (that exec happens after we return from this function) */
2663 bb_perror_msg_and_die("vfork");
2666 disable_restore_tty_pgrp_on_exit();
2667 pid = BB_MMU ? fork() : vfork();
2669 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2673 close(redir->rd_fd); /* read side of the pipe */
2675 full_write(pair.wr, heredoc, len); /* may loop or block */
2678 /* Delegate blocking writes to another process */
2679 xmove_fd(pair.wr, STDOUT_FILENO);
2680 re_execute_shell(&to_free, heredoc, NULL, NULL);
2684 #if ENABLE_HUSH_FAST
2686 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2688 enable_restore_tty_pgrp_on_exit();
2694 wait(NULL); /* wait till child has died */
2697 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2698 * and stderr if they are redirected. */
2699 static int setup_redirects(struct command *prog, int squirrel[])
2702 struct redir_struct *redir;
2704 for (redir = prog->redirects; redir; redir = redir->next) {
2705 if (redir->rd_type == REDIRECT_HEREDOC2) {
2706 /* rd_fd<<HERE case */
2707 if (squirrel && redir->rd_fd < 3
2708 && squirrel[redir->rd_fd] < 0
2710 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2712 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2714 debug_printf_parse("set heredoc '%s'\n",
2715 redir->rd_filename);
2716 setup_heredoc(redir);
2720 if (redir->rd_dup == REDIRFD_TO_FILE) {
2721 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2723 if (redir->rd_filename == NULL) {
2724 /* Something went wrong in the parse.
2725 * Pretend it didn't happen */
2726 bb_error_msg("bug in redirect parse");
2729 mode = redir_table[redir->rd_type].mode;
2730 p = expand_string_to_string(redir->rd_filename);
2731 openfd = open_or_warn(p, mode);
2734 /* this could get lost if stderr has been redirected, but
2735 * bash and ash both lose it as well (though zsh doesn't!) */
2736 //what the above comment tries to say?
2740 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2741 openfd = redir->rd_dup;
2744 if (openfd != redir->rd_fd) {
2745 if (squirrel && redir->rd_fd < 3
2746 && squirrel[redir->rd_fd] < 0
2748 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2750 if (openfd == REDIRFD_CLOSE) {
2751 /* "n>-" means "close me" */
2752 close(redir->rd_fd);
2754 xdup2(openfd, redir->rd_fd);
2755 if (redir->rd_dup == REDIRFD_TO_FILE)
2763 static void restore_redirects(int squirrel[])
2766 for (i = 0; i < 3; i++) {
2769 /* We simply die on error */
2776 static void free_pipe_list(struct pipe *head);
2778 /* Return code is the exit status of the pipe */
2779 static void free_pipe(struct pipe *pi)
2782 struct command *command;
2783 struct redir_struct *r, *rnext;
2786 if (pi->stopped_cmds > 0) /* why? */
2788 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2789 for (i = 0; i < pi->num_cmds; i++) {
2790 command = &pi->cmds[i];
2791 debug_printf_clean(" command %d:\n", i);
2792 if (command->argv) {
2793 for (a = 0, p = command->argv; *p; a++, p++) {
2794 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2796 free_strings(command->argv);
2797 command->argv = NULL;
2799 /* not "else if": on syntax error, we may have both! */
2800 if (command->group) {
2801 debug_printf_clean(" begin group (grp_type:%d)\n",
2803 free_pipe_list(command->group);
2804 debug_printf_clean(" end group\n");
2805 command->group = NULL;
2807 /* else is crucial here.
2808 * If group != NULL, child_func is meaningless */
2809 #if ENABLE_HUSH_FUNCTIONS
2810 else if (command->child_func) {
2811 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2812 command->child_func->parent_cmd = NULL;
2816 free(command->group_as_string);
2817 command->group_as_string = NULL;
2819 for (r = command->redirects; r; r = rnext) {
2820 debug_printf_clean(" redirect %d%s",
2821 r->rd_fd, redir_table[r->rd_type].descrip);
2822 /* guard against the case >$FOO, where foo is unset or blank */
2823 if (r->rd_filename) {
2824 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2825 free(r->rd_filename);
2826 r->rd_filename = NULL;
2828 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2832 command->redirects = NULL;
2834 free(pi->cmds); /* children are an array, they get freed all at once */
2842 static void free_pipe_list(struct pipe *head)
2844 struct pipe *pi, *next;
2846 for (pi = head; pi; pi = next) {
2848 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2851 debug_printf_clean("pipe followup code %d\n", pi->followup);
2853 /*pi->next = NULL;*/
2859 static int run_list(struct pipe *pi);
2861 #define parse_stream(pstring, input, end_trigger) \
2862 parse_stream(input, end_trigger)
2864 static struct pipe *parse_stream(char **pstring,
2865 struct in_str *input,
2867 static void parse_and_run_string(const char *s);
2870 static char *find_in_path(const char *arg)
2873 const char *PATH = get_local_var_value("PATH");
2879 const char *end = strchrnul(PATH, ':');
2880 int sz = end - PATH; /* must be int! */
2884 ret = xasprintf("%.*s/%s", sz, PATH, arg);
2886 /* We have xxx::yyyy in $PATH,
2887 * it means "use current dir" */
2890 if (access(ret, F_OK) == 0)
2903 static const struct built_in_command* find_builtin(const char *name)
2905 const struct built_in_command *x;
2906 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2907 if (strcmp(name, x->cmd) != 0)
2909 debug_printf_exec("found builtin '%s'\n", name);
2915 #if ENABLE_HUSH_FUNCTIONS
2916 static const struct function *find_function(const char *name)
2918 const struct function *funcp = G.top_func;
2920 if (strcmp(name, funcp->name) == 0) {
2923 funcp = funcp->next;
2926 debug_printf_exec("found function '%s'\n", name);
2930 /* Note: takes ownership on name ptr */
2931 static struct function *new_function(char *name)
2933 struct function *funcp;
2934 struct function **funcpp = &G.top_func;
2936 while ((funcp = *funcpp) != NULL) {
2937 struct command *cmd;
2939 if (strcmp(funcp->name, name) != 0) {
2940 funcpp = &funcp->next;
2944 cmd = funcp->parent_cmd;
2945 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2947 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2949 /* Note: if !funcp->body, do not free body_as_string!
2950 * This is a special case of "-F name body" function:
2951 * body_as_string was not malloced! */
2953 free_pipe_list(funcp->body);
2955 free(funcp->body_as_string);
2959 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2960 cmd->argv[0] = funcp->name;
2961 cmd->group = funcp->body;
2963 cmd->group_as_string = funcp->body_as_string;
2968 debug_printf_exec("remembering new function '%s'\n", name);
2969 funcp = *funcpp = xzalloc(sizeof(*funcp));
2970 /*funcp->next = NULL;*/
2976 static void unset_func(const char *name)
2978 struct function *funcp;
2979 struct function **funcpp = &G.top_func;
2981 while ((funcp = *funcpp) != NULL) {
2982 if (strcmp(funcp->name, name) == 0) {
2983 *funcpp = funcp->next;
2984 /* funcp is unlinked now, deleting it.
2985 * Note: if !funcp->body, the function was created by
2986 * "-F name body", do not free ->body_as_string
2987 * and ->name as they were not malloced. */
2989 free_pipe_list(funcp->body);
2992 free(funcp->body_as_string);
2998 funcpp = &funcp->next;
3003 #define exec_function(nommu_save, funcp, argv) \
3004 exec_function(funcp, argv)
3006 static void exec_function(nommu_save_t *nommu_save,
3007 const struct function *funcp,
3008 char **argv) NORETURN;
3009 static void exec_function(nommu_save_t *nommu_save,
3010 const struct function *funcp,
3016 argv[0] = G.global_argv[0];
3017 G.global_argv = argv;
3021 /* On MMU, funcp->body is always non-NULL */
3022 n = run_list(funcp->body);
3026 re_execute_shell(&nommu_save->argv_from_re_execing,
3027 funcp->body_as_string,
3033 static int run_function(const struct function *funcp, char **argv)
3039 save_and_replace_G_args(&sv, argv);
3040 /* "we are in function, ok to use return" */
3041 sv_flg = G.flag_return_in_progress;
3042 G.flag_return_in_progress = -1;
3044 /* On MMU, funcp->body is always non-NULL */
3047 /* Function defined by -F */
3048 parse_and_run_string(funcp->body_as_string);
3049 rc = G.last_exitcode;
3053 rc = run_list(funcp->body);
3056 G.flag_return_in_progress = sv_flg;
3057 restore_G_args(&sv, argv);
3061 #endif /* ENABLE_HUSH_FUNCTIONS */
3065 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3066 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3067 #define pseudo_exec(nommu_save, command, argv_expanded) \
3068 pseudo_exec(command, argv_expanded)
3071 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3073 * Don't exit() here. If you don't exec, use _exit instead.
3074 * The at_exit handlers apparently confuse the calling process,
3075 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3076 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3077 char **argv, int assignment_cnt,
3078 char **argv_expanded) NORETURN;
3079 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3080 char **argv, int assignment_cnt,
3081 char **argv_expanded)
3085 /* Case when we are here: ... | var=val | ... */
3086 if (!argv[assignment_cnt])
3087 _exit(EXIT_SUCCESS);
3089 new_env = expand_assignments(argv, assignment_cnt);
3091 set_vars_and_save_old(new_env);
3092 free(new_env); /* optional */
3093 /* we can also destroy set_vars_and_save_old's return value,
3096 nommu_save->new_env = new_env;
3097 nommu_save->old_vars = set_vars_and_save_old(new_env);
3099 if (argv_expanded) {
3100 argv = argv_expanded;
3102 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3104 nommu_save->argv = argv;
3108 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3109 if (strchr(argv[0], '/') != NULL)
3113 /* On NOMMU, we must never block!
3114 * Example: { sleep 99999 | read line } & echo Ok
3115 * read builtin will block on read syscall, leaving parent blocked
3116 * in vfork. Therefore we can't do this:
3119 /* Check if the command matches any of the builtins.
3120 * Depending on context, this might be redundant. But it's
3121 * easier to waste a few CPU cycles than it is to figure out
3122 * if this is one of those cases.
3126 const struct built_in_command *x = find_builtin(argv[0]);
3128 rcode = x->function(argv);
3134 #if ENABLE_HUSH_FUNCTIONS
3135 /* Check if the command matches any functions */
3137 const struct function *funcp = find_function(argv[0]);
3139 exec_function(nommu_save, funcp, argv);
3144 #if ENABLE_FEATURE_SH_STANDALONE
3145 /* Check if the command matches any busybox applets */
3147 int a = find_applet_by_name(argv[0]);
3149 # if BB_MMU /* see above why on NOMMU it is not allowed */
3150 if (APPLET_IS_NOEXEC(a)) {
3151 debug_printf_exec("running applet '%s'\n", argv[0]);
3152 run_applet_no_and_exit(a, argv);
3155 /* Re-exec ourselves */
3156 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3157 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3158 execv(bb_busybox_exec_path, argv);
3159 /* If they called chroot or otherwise made the binary no longer
3160 * executable, fall through */
3165 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3168 debug_printf_exec("execing '%s'\n", argv[0]);
3169 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3170 execvp(argv[0], argv);
3171 bb_perror_msg("can't execute '%s'", argv[0]);
3172 _exit(EXIT_FAILURE);
3175 /* Called after [v]fork() in run_pipe
3177 static void pseudo_exec(nommu_save_t *nommu_save,
3178 struct command *command,
3179 char **argv_expanded) NORETURN;
3180 static void pseudo_exec(nommu_save_t *nommu_save,
3181 struct command *command,
3182 char **argv_expanded)
3184 if (command->argv) {
3185 pseudo_exec_argv(nommu_save, command->argv,
3186 command->assignment_cnt, argv_expanded);
3189 if (command->group) {
3190 /* Cases when we are here:
3193 * ... | ( list ) | ...
3194 * ... | { list } | ...
3198 debug_printf_exec("pseudo_exec: run_list\n");
3199 reset_traps_to_defaults();
3200 rcode = run_list(command->group);
3201 /* OK to leak memory by not calling free_pipe_list,
3202 * since this process is about to exit */
3205 re_execute_shell(&nommu_save->argv_from_re_execing,
3206 command->group_as_string,
3212 /* Case when we are here: ... | >file */
3213 debug_printf_exec("pseudo_exec'ed null command\n");
3214 _exit(EXIT_SUCCESS);
3218 static const char *get_cmdtext(struct pipe *pi)
3224 /* This is subtle. ->cmdtext is created only on first backgrounding.
3225 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3226 * On subsequent bg argv is trashed, but we won't use it */
3229 argv = pi->cmds[0].argv;
3230 if (!argv || !argv[0]) {
3231 pi->cmdtext = xzalloc(1);
3237 len += strlen(*argv) + 1;
3241 argv = pi->cmds[0].argv;
3243 len = strlen(*argv);
3244 memcpy(p, *argv, len);
3252 static void insert_bg_job(struct pipe *pi)
3254 struct pipe *job, **jobp;
3257 /* Linear search for the ID of the job to use */
3259 for (job = G.job_list; job; job = job->next)
3260 if (job->jobid >= pi->jobid)
3261 pi->jobid = job->jobid + 1;
3263 /* Add job to the list of running jobs */
3265 while ((job = *jobp) != NULL)
3267 job = *jobp = xmalloc(sizeof(*job));
3269 *job = *pi; /* physical copy */
3271 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3272 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3273 for (i = 0; i < pi->num_cmds; i++) {
3274 job->cmds[i].pid = pi->cmds[i].pid;
3275 /* all other fields are not used and stay zero */
3277 job->cmdtext = xstrdup(get_cmdtext(pi));
3279 if (G_interactive_fd)
3280 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3281 /* Last command's pid goes to $! */
3282 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3283 G.last_jobid = job->jobid;
3286 static void remove_bg_job(struct pipe *pi)
3288 struct pipe *prev_pipe;
3290 if (pi == G.job_list) {
3291 G.job_list = pi->next;
3293 prev_pipe = G.job_list;
3294 while (prev_pipe->next != pi)
3295 prev_pipe = prev_pipe->next;
3296 prev_pipe->next = pi->next;
3299 G.last_jobid = G.job_list->jobid;
3304 /* Remove a backgrounded job */
3305 static void delete_finished_bg_job(struct pipe *pi)
3308 pi->stopped_cmds = 0;
3314 /* Check to see if any processes have exited -- if they
3315 * have, figure out why and see if a job has completed */
3316 static int checkjobs(struct pipe* fg_pipe)
3326 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3328 attributes = WUNTRACED;
3329 if (fg_pipe == NULL)
3330 attributes |= WNOHANG;
3333 #if ENABLE_HUSH_FAST
3334 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3335 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3336 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3337 /* There was neither fork nor SIGCHLD since last waitpid */
3338 /* Avoid doing waitpid syscall if possible */
3339 if (!G.we_have_children) {
3343 if (fg_pipe == NULL) { /* is WNOHANG set? */
3344 /* We have children, but they did not exit
3345 * or stop yet (we saw no SIGCHLD) */
3348 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3352 /* Do we do this right?
3353 * bash-3.00# sleep 20 | false
3355 * [3]+ Stopped sleep 20 | false
3356 * bash-3.00# echo $?
3357 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3358 * [hush 1.14.0: yes we do it right]
3365 #if ENABLE_HUSH_FAST
3366 i = G.count_SIGCHLD;
3368 childpid = waitpid(-1, &status, attributes);
3369 if (childpid <= 0) {
3370 if (childpid && errno != ECHILD)
3371 bb_perror_msg("waitpid");
3372 #if ENABLE_HUSH_FAST
3373 else { /* Until next SIGCHLD, waitpid's are useless */
3374 G.we_have_children = (childpid == 0);
3375 G.handled_SIGCHLD = i;
3376 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3381 dead = WIFEXITED(status) || WIFSIGNALED(status);
3384 if (WIFSTOPPED(status))
3385 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3386 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3387 if (WIFSIGNALED(status))
3388 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3389 childpid, WTERMSIG(status), WEXITSTATUS(status));
3390 if (WIFEXITED(status))
3391 debug_printf_jobs("pid %d exited, exitcode %d\n",
3392 childpid, WEXITSTATUS(status));
3394 /* Were we asked to wait for fg pipe? */
3396 for (i = 0; i < fg_pipe->num_cmds; i++) {
3397 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3398 if (fg_pipe->cmds[i].pid != childpid)
3401 fg_pipe->cmds[i].pid = 0;
3402 fg_pipe->alive_cmds--;
3403 if (i == fg_pipe->num_cmds - 1) {
3404 /* last process gives overall exitstatus */
3405 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3406 rcode = WEXITSTATUS(status);
3407 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3408 /* bash prints killing signal's name for *last*
3409 * process in pipe (prints just newline for SIGINT).
3410 * Mimic this. Example: "sleep 5" + ^\
3412 if (WIFSIGNALED(status)) {
3413 int sig = WTERMSIG(status);
3414 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3418 fg_pipe->cmds[i].is_stopped = 1;
3419 fg_pipe->stopped_cmds++;
3421 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3422 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3423 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3424 /* All processes in fg pipe have exited or stopped */
3425 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3426 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3427 * and "killall -STOP cat" */
3428 if (G_interactive_fd) {
3430 if (fg_pipe->alive_cmds)
3431 insert_bg_job(fg_pipe);
3436 /* There are still running processes in the fg pipe */
3437 goto wait_more; /* do waitpid again */
3439 /* it wasnt fg_pipe, look for process in bg pipes */
3443 /* We asked to wait for bg or orphaned children */
3444 /* No need to remember exitcode in this case */
3445 for (pi = G.job_list; pi; pi = pi->next) {
3446 for (i = 0; i < pi->num_cmds; i++) {
3447 if (pi->cmds[i].pid == childpid)
3448 goto found_pi_and_prognum;
3451 /* Happens when shell is used as init process (init=/bin/sh) */
3452 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3453 continue; /* do waitpid again */
3455 found_pi_and_prognum:
3458 pi->cmds[i].pid = 0;
3460 if (!pi->alive_cmds) {
3461 if (G_interactive_fd)
3462 printf(JOB_STATUS_FORMAT, pi->jobid,
3463 "Done", pi->cmdtext);
3464 delete_finished_bg_job(pi);
3468 pi->cmds[i].is_stopped = 1;
3472 } /* while (waitpid succeeds)... */
3478 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3481 int rcode = checkjobs(fg_pipe);
3482 if (G_saved_tty_pgrp) {
3483 /* Job finished, move the shell to the foreground */
3484 p = getpgrp(); /* our process group id */
3485 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3486 tcsetpgrp(G_interactive_fd, p);
3492 /* Start all the jobs, but don't wait for anything to finish.
3495 * Return code is normally -1, when the caller has to wait for children
3496 * to finish to determine the exit status of the pipe. If the pipe
3497 * is a simple builtin command, however, the action is done by the
3498 * time run_pipe returns, and the exit code is provided as the
3501 * Returns -1 only if started some children. IOW: we have to
3502 * mask out retvals of builtins etc with 0xff!
3504 * The only case when we do not need to [v]fork is when the pipe
3505 * is single, non-backgrounded, non-subshell command. Examples:
3506 * cmd ; ... { list } ; ...
3507 * cmd && ... { list } && ...
3508 * cmd || ... { list } || ...
3509 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3510 * or (if SH_STANDALONE) an applet, and we can run the { list }
3511 * with run_list. If it isn't one of these, we fork and exec cmd.
3513 * Cases when we must fork:
3514 * non-single: cmd | cmd
3515 * backgrounded: cmd & { list } &
3516 * subshell: ( list ) [&]
3518 static int run_pipe(struct pipe *pi)
3520 static const char *const null_ptr = NULL;
3523 struct command *command;
3524 char **argv_expanded;
3527 /* it is not always needed, but we aim to smaller code */
3528 int squirrel[] = { -1, -1, -1 };
3531 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3534 IF_HUSH_JOB(pi->pgrp = -1;)
3535 pi->stopped_cmds = 0;
3536 command = &(pi->cmds[0]);
3537 argv_expanded = NULL;
3539 if (pi->num_cmds != 1
3540 || pi->followup == PIPE_BG
3541 || command->grp_type == GRP_SUBSHELL
3548 debug_printf_exec(": group:%p argv:'%s'\n",
3549 command->group, command->argv ? command->argv[0] : "NONE");
3551 if (command->group) {
3552 #if ENABLE_HUSH_FUNCTIONS
3553 if (command->grp_type == GRP_FUNCTION) {
3554 /* "executing" func () { list } */
3555 struct function *funcp;
3557 funcp = new_function(command->argv[0]);
3558 /* funcp->name is already set to argv[0] */
3559 funcp->body = command->group;
3561 funcp->body_as_string = command->group_as_string;
3562 command->group_as_string = NULL;
3564 command->group = NULL;
3565 command->argv[0] = NULL;
3566 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3567 funcp->parent_cmd = command;
3568 command->child_func = funcp;
3570 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3572 return EXIT_SUCCESS;
3576 debug_printf("non-subshell group\n");
3577 rcode = 1; /* exitcode if redir failed */
3578 if (setup_redirects(command, squirrel) == 0) {
3579 debug_printf_exec(": run_list\n");
3580 rcode = run_list(command->group) & 0xff;
3582 restore_redirects(squirrel);
3583 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3585 debug_printf_exec("run_pipe: return %d\n", rcode);
3589 argv = command->argv ? command->argv : (char **) &null_ptr;
3591 const struct built_in_command *x;
3592 #if ENABLE_HUSH_FUNCTIONS
3593 const struct function *funcp;
3597 char **new_env = NULL;
3598 struct variable *old_vars = NULL;
3600 if (argv[command->assignment_cnt] == NULL) {
3601 /* Assignments, but no command */
3602 /* Ensure redirects take effect. Try "a=t >file" */
3603 rcode = setup_redirects(command, squirrel);
3604 restore_redirects(squirrel);
3605 /* Set shell variables */
3607 p = expand_string_to_string(*argv);
3608 debug_printf_exec("set shell var:'%s'->'%s'\n",
3610 set_local_var(p, 0, 0);
3613 /* Do we need to flag set_local_var() errors?
3614 * "assignment to readonly var" and "putenv error"
3616 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3618 debug_printf_exec("run_pipe: return %d\n", rcode);
3622 /* Expand the rest into (possibly) many strings each */
3623 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3625 x = find_builtin(argv_expanded[0]);
3626 #if ENABLE_HUSH_FUNCTIONS
3629 funcp = find_function(argv_expanded[0]);
3633 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3634 debug_printf("exec with redirects only\n");
3635 rcode = setup_redirects(command, NULL);
3636 goto clean_up_and_ret1;
3639 /* setup_redirects acts on file descriptors, not FILEs.
3640 * This is perfect for work that comes after exec().
3641 * Is it really safe for inline use? Experimentally,
3642 * things seem to work. */
3643 rcode = setup_redirects(command, squirrel);
3645 new_env = expand_assignments(argv, command->assignment_cnt);
3646 old_vars = set_vars_and_save_old(new_env);
3648 debug_printf_exec(": builtin '%s' '%s'...\n",
3649 x->cmd, argv_expanded[1]);
3650 rcode = x->function(argv_expanded) & 0xff;
3653 #if ENABLE_HUSH_FUNCTIONS
3655 debug_printf_exec(": function '%s' '%s'...\n",
3656 funcp->name, argv_expanded[1]);
3657 rcode = run_function(funcp, argv_expanded) & 0xff;
3661 #if ENABLE_FEATURE_SH_STANDALONE
3664 restore_redirects(squirrel);
3665 unset_vars(new_env);
3668 free(argv_expanded);
3669 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3671 debug_printf_exec("run_pipe return %d\n", rcode);
3675 #if ENABLE_FEATURE_SH_STANDALONE
3676 i = find_applet_by_name(argv_expanded[0]);
3677 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3678 rcode = setup_redirects(command, squirrel);
3680 new_env = expand_assignments(argv, command->assignment_cnt);
3681 old_vars = set_vars_and_save_old(new_env);
3682 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3683 argv_expanded[0], argv_expanded[1]);
3684 rcode = run_nofork_applet(i, argv_expanded);
3686 goto clean_up_and_ret;
3689 /* It is neither builtin nor applet. We must fork. */
3693 /* NB: argv_expanded may already be created, and that
3694 * might include `cmd` runs! Do not rerun it! We *must*
3695 * use argv_expanded if it's non-NULL */
3697 /* Going to fork a child per each pipe member */
3701 for (i = 0; i < pi->num_cmds; i++) {
3702 struct fd_pair pipefds;
3704 volatile nommu_save_t nommu_save;
3705 nommu_save.new_env = NULL;
3706 nommu_save.old_vars = NULL;
3707 nommu_save.argv = NULL;
3708 nommu_save.argv_from_re_execing = NULL;
3710 command = &(pi->cmds[i]);
3711 if (command->argv) {
3712 debug_printf_exec(": pipe member '%s' '%s'...\n",
3713 command->argv[0], command->argv[1]);
3715 debug_printf_exec(": pipe member with no argv\n");
3718 /* pipes are inserted between pairs of commands */
3721 if ((i + 1) < pi->num_cmds)
3722 xpiped_pair(pipefds);
3724 command->pid = BB_MMU ? fork() : vfork();
3725 if (!command->pid) { /* child */
3727 disable_restore_tty_pgrp_on_exit();
3729 /* Every child adds itself to new process group
3730 * with pgid == pid_of_first_child_in_pipe */
3731 if (G.run_list_level == 1 && G_interactive_fd) {
3734 if (pgrp < 0) /* true for 1st process only */
3736 if (setpgid(0, pgrp) == 0
3737 && pi->followup != PIPE_BG
3738 && G_saved_tty_pgrp /* we have ctty */
3740 /* We do it in *every* child, not just first,
3742 tcsetpgrp(G_interactive_fd, pgrp);
3746 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3747 /* 1st cmd in backgrounded pipe
3748 * should have its stdin /dev/null'ed */
3750 if (open(bb_dev_null, O_RDONLY))
3751 xopen("/", O_RDONLY);
3753 xmove_fd(nextin, 0);
3755 xmove_fd(pipefds.wr, 1);
3758 /* Like bash, explicit redirects override pipes,
3759 * and the pipe fd is available for dup'ing. */
3760 if (setup_redirects(command, NULL))
3763 /* Restore default handlers just prior to exec */
3764 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3766 /* Stores to nommu_save list of env vars putenv'ed
3767 * (NOMMU, on MMU we don't need that) */
3768 /* cast away volatility... */
3769 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3770 /* pseudo_exec() does not return */
3773 /* parent or error */
3774 #if ENABLE_HUSH_FAST
3776 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3778 enable_restore_tty_pgrp_on_exit();
3780 /* Clean up after vforked child */
3781 free(nommu_save.argv);
3782 free(nommu_save.argv_from_re_execing);
3783 unset_vars(nommu_save.new_env);
3784 add_vars(nommu_save.old_vars);
3786 free(argv_expanded);
3787 argv_expanded = NULL;
3788 if (command->pid < 0) { /* [v]fork failed */
3789 /* Clearly indicate, was it fork or vfork */
3790 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3794 /* Second and next children need to know pid of first one */
3796 pi->pgrp = command->pid;
3802 if ((i + 1) < pi->num_cmds)
3804 /* Pass read (output) pipe end to next iteration */
3805 nextin = pipefds.rd;
3808 if (!pi->alive_cmds) {
3810 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3815 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3819 #ifndef debug_print_tree
3820 static void debug_print_tree(struct pipe *pi, int lvl)
3822 static const char *const PIPE[] = {
3828 static const char *RES[] = {
3829 [RES_NONE ] = "NONE" ,
3832 [RES_THEN ] = "THEN" ,
3833 [RES_ELIF ] = "ELIF" ,
3834 [RES_ELSE ] = "ELSE" ,
3837 #if ENABLE_HUSH_LOOPS
3838 [RES_FOR ] = "FOR" ,
3839 [RES_WHILE] = "WHILE",
3840 [RES_UNTIL] = "UNTIL",
3842 [RES_DONE ] = "DONE" ,
3844 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3847 #if ENABLE_HUSH_CASE
3848 [RES_CASE ] = "CASE" ,
3849 [RES_CASE_IN ] = "CASE_IN" ,
3850 [RES_MATCH] = "MATCH",
3851 [RES_CASE_BODY] = "CASE_BODY",
3852 [RES_ESAC ] = "ESAC" ,
3854 [RES_XXXX ] = "XXXX" ,
3855 [RES_SNTX ] = "SNTX" ,
3857 static const char *const GRPTYPE[] = {
3860 #if ENABLE_HUSH_FUNCTIONS
3869 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3870 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3872 while (prn < pi->num_cmds) {
3873 struct command *command = &pi->cmds[prn];
3874 char **argv = command->argv;
3876 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3878 command->assignment_cnt);
3879 if (command->group) {
3880 fprintf(stderr, " group %s: (argv=%p)\n",
3881 GRPTYPE[command->grp_type],
3883 debug_print_tree(command->group, lvl+1);
3887 if (argv) while (*argv) {
3888 fprintf(stderr, " '%s'", *argv);
3891 fprintf(stderr, "\n");
3900 /* NB: called by pseudo_exec, and therefore must not modify any
3901 * global data until exec/_exit (we can be a child after vfork!) */
3902 static int run_list(struct pipe *pi)
3904 #if ENABLE_HUSH_CASE
3905 char *case_word = NULL;
3907 #if ENABLE_HUSH_LOOPS
3908 struct pipe *loop_top = NULL;
3909 char *for_varname = NULL;
3910 char **for_lcur = NULL;
3911 char **for_list = NULL;
3913 smallint last_followup;
3915 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3916 smalluint cond_code = 0;
3918 enum { cond_code = 0 };
3921 smallint rword; /* enum reserved_style */
3922 smallint last_rword; /* ditto */
3925 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
3928 #if ENABLE_HUSH_LOOPS
3929 /* Check syntax for "for" */
3930 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3931 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3933 /* current word is FOR or IN (BOLD in comments below) */
3934 if (cpipe->next == NULL) {
3935 syntax_error("malformed for");
3937 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3940 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3941 if (cpipe->next->res_word == RES_DO)
3943 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3944 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3945 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3947 syntax_error("malformed for");
3949 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3955 /* Past this point, all code paths should jump to ret: label
3956 * in order to return, no direct "return" statements please.
3957 * This helps to ensure that no memory is leaked. */
3965 last_rword = RES_XXXX;
3967 last_followup = PIPE_SEQ;
3968 rcode = G.last_exitcode;
3970 /* Go through list of pipes, (maybe) executing them. */
3971 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3975 IF_HAS_KEYWORDS(rword = pi->res_word;)
3976 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3977 rword, cond_code, last_rword);
3978 #if ENABLE_HUSH_LOOPS
3979 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3980 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3982 /* start of a loop: remember where loop starts */
3987 /* Still in the same "if...", "then..." or "do..." branch? */
3988 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3989 if ((rcode == 0 && last_followup == PIPE_OR)
3990 || (rcode != 0 && last_followup == PIPE_AND)
3992 /* It is "<true> || CMD" or "<false> && CMD"
3993 * and we should not execute CMD */
3994 debug_printf_exec("skipped cmd because of || or &&\n");
3995 last_followup = pi->followup;
3999 last_followup = pi->followup;
4000 IF_HAS_KEYWORDS(last_rword = rword;)
4003 if (rword == RES_THEN) {
4004 /* if false; then ... fi has exitcode 0! */
4005 G.last_exitcode = rcode = EXIT_SUCCESS;
4006 /* "if <false> THEN cmd": skip cmd */
4010 if (rword == RES_ELSE || rword == RES_ELIF) {
4011 /* "if <true> then ... ELSE/ELIF cmd":
4012 * skip cmd and all following ones */
4017 #if ENABLE_HUSH_LOOPS
4018 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4020 /* first loop through for */
4022 static const char encoded_dollar_at[] ALIGN1 = {
4023 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4024 }; /* encoded representation of "$@" */
4025 static const char *const encoded_dollar_at_argv[] = {
4026 encoded_dollar_at, NULL
4027 }; /* argv list with one element: "$@" */
4030 vals = (char**)encoded_dollar_at_argv;
4031 if (pi->next->res_word == RES_IN) {
4032 /* if no variable values after "in" we skip "for" */
4033 if (!pi->next->cmds[0].argv) {
4034 G.last_exitcode = rcode = EXIT_SUCCESS;
4035 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4038 vals = pi->next->cmds[0].argv;
4039 } /* else: "for var; do..." -> assume "$@" list */
4040 /* create list of variable values */
4041 debug_print_strings("for_list made from", vals);
4042 for_list = expand_strvec_to_strvec(vals);
4043 for_lcur = for_list;
4044 debug_print_strings("for_list", for_list);
4045 for_varname = pi->cmds[0].argv[0];
4046 pi->cmds[0].argv[0] = NULL;
4048 free(pi->cmds[0].argv[0]);
4050 /* "for" loop is over, clean up */
4054 pi->cmds[0].argv[0] = for_varname;
4057 /* Insert next value from for_lcur */
4058 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4059 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
4060 pi->cmds[0].assignment_cnt = 1;
4062 if (rword == RES_IN) {
4063 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4065 if (rword == RES_DONE) {
4066 continue; /* "done" has no cmds too */
4069 #if ENABLE_HUSH_CASE
4070 if (rword == RES_CASE) {
4071 case_word = expand_strvec_to_string(pi->cmds->argv);
4074 if (rword == RES_MATCH) {
4077 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4079 /* all prev words didn't match, does this one match? */
4080 argv = pi->cmds->argv;
4082 char *pattern = expand_string_to_string(*argv);
4083 /* TODO: which FNM_xxx flags to use? */
4084 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4086 if (cond_code == 0) { /* match! we will execute this branch */
4087 free(case_word); /* make future "word)" stop */
4095 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4097 continue; /* not matched yet, skip this pipe */
4100 /* Just pressing <enter> in shell should check for jobs.
4101 * OTOH, in non-interactive shell this is useless
4102 * and only leads to extra job checks */
4103 if (pi->num_cmds == 0) {
4104 if (G_interactive_fd)
4105 goto check_jobs_and_continue;
4109 /* After analyzing all keywords and conditions, we decided
4110 * to execute this pipe. NB: have to do checkjobs(NULL)
4111 * after run_pipe to collect any background children,
4112 * even if list execution is to be stopped. */
4113 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4116 #if ENABLE_HUSH_LOOPS
4117 G.flag_break_continue = 0;
4119 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4121 /* We ran a builtin, function, or group.
4122 * rcode is already known
4123 * and we don't need to wait for anything. */
4124 G.last_exitcode = rcode;
4125 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4126 check_and_run_traps(0);
4127 #if ENABLE_HUSH_LOOPS
4128 /* Was it "break" or "continue"? */
4129 if (G.flag_break_continue) {
4130 smallint fbc = G.flag_break_continue;
4131 /* We might fall into outer *loop*,
4132 * don't want to break it too */
4134 G.depth_break_continue--;
4135 if (G.depth_break_continue == 0)
4136 G.flag_break_continue = 0;
4137 /* else: e.g. "continue 2" should *break* once, *then* continue */
4138 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4139 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4140 goto check_jobs_and_break;
4141 /* "continue": simulate end of loop */
4146 #if ENABLE_HUSH_FUNCTIONS
4147 if (G.flag_return_in_progress == 1) {
4148 /* same as "goto check_jobs_and_break" */
4153 } else if (pi->followup == PIPE_BG) {
4154 /* What does bash do with attempts to background builtins? */
4155 /* even bash 3.2 doesn't do that well with nested bg:
4156 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4157 * I'm NOT treating inner &'s as jobs */
4158 check_and_run_traps(0);
4160 if (G.run_list_level == 1)
4163 G.last_exitcode = rcode = EXIT_SUCCESS;
4164 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4167 if (G.run_list_level == 1 && G_interactive_fd) {
4168 /* Waits for completion, then fg's main shell */
4169 rcode = checkjobs_and_fg_shell(pi);
4170 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4171 check_and_run_traps(0);
4174 { /* This one just waits for completion */
4175 rcode = checkjobs(pi);
4176 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4177 check_and_run_traps(0);
4179 G.last_exitcode = rcode;
4183 /* Analyze how result affects subsequent commands */
4185 if (rword == RES_IF || rword == RES_ELIF)
4188 #if ENABLE_HUSH_LOOPS
4189 /* Beware of "while false; true; do ..."! */
4190 if (pi->next && pi->next->res_word == RES_DO) {
4191 if (rword == RES_WHILE) {
4193 /* "while false; do...done" - exitcode 0 */
4194 G.last_exitcode = rcode = EXIT_SUCCESS;
4195 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4196 goto check_jobs_and_break;
4199 if (rword == RES_UNTIL) {
4201 debug_printf_exec(": until expr is true: breaking\n");
4202 check_jobs_and_break:
4210 check_jobs_and_continue:
4217 #if ENABLE_HUSH_LOOPS
4222 #if ENABLE_HUSH_CASE
4226 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4230 /* Select which version we will use */
4231 static int run_and_free_list(struct pipe *pi)
4234 debug_printf_exec("run_and_free_list entered\n");
4236 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4237 rcode = run_list(pi);
4239 /* free_pipe_list has the side effect of clearing memory.
4240 * In the long run that function can be merged with run_list,
4241 * but doing that now would hobble the debugging effort. */
4243 debug_printf_exec("run_and_free_list return %d\n", rcode);
4248 static struct pipe *new_pipe(void)
4251 pi = xzalloc(sizeof(struct pipe));
4252 /*pi->followup = 0; - deliberately invalid value */
4253 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4257 /* Command (member of a pipe) is complete, or we start a new pipe
4258 * if ctx->command is NULL.
4259 * No errors possible here.
4261 static int done_command(struct parse_context *ctx)
4263 /* The command is really already in the pipe structure, so
4264 * advance the pipe counter and make a new, null command. */
4265 struct pipe *pi = ctx->pipe;
4266 struct command *command = ctx->command;
4269 if (IS_NULL_CMD(command)) {
4270 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4274 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4275 //debug_print_tree(ctx->list_head, 20);
4277 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4280 /* Only real trickiness here is that the uncommitted
4281 * command structure is not counted in pi->num_cmds. */
4282 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4283 ctx->command = command = &pi->cmds[pi->num_cmds];
4285 memset(command, 0, sizeof(*command));
4286 return pi->num_cmds; /* used only for 0/nonzero check */
4289 static void done_pipe(struct parse_context *ctx, pipe_style type)
4293 debug_printf_parse("done_pipe entered, followup %d\n", type);
4294 /* Close previous command */
4295 not_null = done_command(ctx);
4296 ctx->pipe->followup = type;
4298 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4299 ctx->ctx_inverted = 0;
4300 ctx->pipe->res_word = ctx->ctx_res_w;
4303 /* Without this check, even just <enter> on command line generates
4304 * tree of three NOPs (!). Which is harmless but annoying.
4305 * IOW: it is safe to do it unconditionally. */
4308 || ctx->ctx_res_w == RES_FI
4310 #if ENABLE_HUSH_LOOPS
4311 || ctx->ctx_res_w == RES_DONE
4312 || ctx->ctx_res_w == RES_FOR
4313 || ctx->ctx_res_w == RES_IN
4315 #if ENABLE_HUSH_CASE
4316 || ctx->ctx_res_w == RES_ESAC
4320 debug_printf_parse("done_pipe: adding new pipe: "
4321 "not_null:%d ctx->ctx_res_w:%d\n",
4322 not_null, ctx->ctx_res_w);
4324 ctx->pipe->next = new_p;
4326 /* RES_THEN, RES_DO etc are "sticky" -
4327 * they remain set for pipes inside if/while.
4328 * This is used to control execution.
4329 * RES_FOR and RES_IN are NOT sticky (needed to support
4330 * cases where variable or value happens to match a keyword):
4332 #if ENABLE_HUSH_LOOPS
4333 if (ctx->ctx_res_w == RES_FOR
4334 || ctx->ctx_res_w == RES_IN)
4335 ctx->ctx_res_w = RES_NONE;
4337 #if ENABLE_HUSH_CASE
4338 if (ctx->ctx_res_w == RES_MATCH)
4339 ctx->ctx_res_w = RES_CASE_BODY;
4340 if (ctx->ctx_res_w == RES_CASE)
4341 ctx->ctx_res_w = RES_CASE_IN;
4343 ctx->command = NULL; /* trick done_command below */
4344 /* Create the memory for command, roughly:
4345 * ctx->pipe->cmds = new struct command;
4346 * ctx->command = &ctx->pipe->cmds[0];
4349 //debug_print_tree(ctx->list_head, 10);
4351 debug_printf_parse("done_pipe return\n");
4354 static void initialize_context(struct parse_context *ctx)
4356 memset(ctx, 0, sizeof(*ctx));
4357 ctx->pipe = ctx->list_head = new_pipe();
4358 /* Create the memory for command, roughly:
4359 * ctx->pipe->cmds = new struct command;
4360 * ctx->command = &ctx->pipe->cmds[0];
4365 /* If a reserved word is found and processed, parse context is modified
4366 * and 1 is returned.
4369 struct reserved_combo {
4372 unsigned char assignment_flag;
4376 FLAG_END = (1 << RES_NONE ),
4378 FLAG_IF = (1 << RES_IF ),
4379 FLAG_THEN = (1 << RES_THEN ),
4380 FLAG_ELIF = (1 << RES_ELIF ),
4381 FLAG_ELSE = (1 << RES_ELSE ),
4382 FLAG_FI = (1 << RES_FI ),
4384 #if ENABLE_HUSH_LOOPS
4385 FLAG_FOR = (1 << RES_FOR ),
4386 FLAG_WHILE = (1 << RES_WHILE),
4387 FLAG_UNTIL = (1 << RES_UNTIL),
4388 FLAG_DO = (1 << RES_DO ),
4389 FLAG_DONE = (1 << RES_DONE ),
4390 FLAG_IN = (1 << RES_IN ),
4392 #if ENABLE_HUSH_CASE
4393 FLAG_MATCH = (1 << RES_MATCH),
4394 FLAG_ESAC = (1 << RES_ESAC ),
4396 FLAG_START = (1 << RES_XXXX ),
4399 static const struct reserved_combo* match_reserved_word(o_string *word)
4401 /* Mostly a list of accepted follow-up reserved words.
4402 * FLAG_END means we are done with the sequence, and are ready
4403 * to turn the compound list into a command.
4404 * FLAG_START means the word must start a new compound list.
4406 static const struct reserved_combo reserved_list[] = {
4408 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4409 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4410 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4411 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4412 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4413 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4415 #if ENABLE_HUSH_LOOPS
4416 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4417 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4418 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4419 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4420 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4421 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4423 #if ENABLE_HUSH_CASE
4424 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4425 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4428 const struct reserved_combo *r;
4430 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4431 if (strcmp(word->data, r->literal) == 0)
4436 /* Return 0: not a keyword, 1: keyword
4438 static int reserved_word(o_string *word, struct parse_context *ctx)
4440 #if ENABLE_HUSH_CASE
4441 static const struct reserved_combo reserved_match = {
4442 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4445 const struct reserved_combo *r;
4449 r = match_reserved_word(word);
4453 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4454 #if ENABLE_HUSH_CASE
4455 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4456 /* "case word IN ..." - IN part starts first MATCH part */
4457 r = &reserved_match;
4460 if (r->flag == 0) { /* '!' */
4461 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4462 syntax_error("! ! command");
4463 ctx->ctx_res_w = RES_SNTX;
4465 ctx->ctx_inverted = 1;
4468 if (r->flag & FLAG_START) {
4469 struct parse_context *old;
4471 old = xmalloc(sizeof(*old));
4472 debug_printf_parse("push stack %p\n", old);
4473 *old = *ctx; /* physical copy */
4474 initialize_context(ctx);
4476 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4477 syntax_error_at(word->data);
4478 ctx->ctx_res_w = RES_SNTX;
4481 /* "{...} fi" is ok. "{...} if" is not
4483 * if { echo foo; } then { echo bar; } fi */
4484 if (ctx->command->group)
4485 done_pipe(ctx, PIPE_SEQ);
4488 ctx->ctx_res_w = r->res;
4489 ctx->old_flag = r->flag;
4490 word->o_assignment = r->assignment_flag;
4492 if (ctx->old_flag & FLAG_END) {
4493 struct parse_context *old;
4495 done_pipe(ctx, PIPE_SEQ);
4496 debug_printf_parse("pop stack %p\n", ctx->stack);
4498 old->command->group = ctx->list_head;
4499 old->command->grp_type = GRP_NORMAL;
4501 o_addstr(&old->as_string, ctx->as_string.data);
4502 o_free_unsafe(&ctx->as_string);
4503 old->command->group_as_string = xstrdup(old->as_string.data);
4504 debug_printf_parse("pop, remembering as:'%s'\n",
4505 old->command->group_as_string);
4507 *ctx = *old; /* physical copy */
4514 /* Word is complete, look at it and update parsing context.
4515 * Normal return is 0. Syntax errors return 1.
4516 * Note: on return, word is reset, but not o_free'd!
4518 static int done_word(o_string *word, struct parse_context *ctx)
4520 struct command *command = ctx->command;
4522 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4523 if (word->length == 0 && word->o_quoted == 0) {
4524 debug_printf_parse("done_word return 0: true null, ignored\n");
4528 if (ctx->pending_redirect) {
4529 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4530 * only if run as "bash", not "sh" */
4531 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4533 * ...the word that follows the redirection operator
4534 * shall be subjected to tilde expansion, parameter expansion,
4535 * command substitution, arithmetic expansion, and quote
4536 * removal. Pathname expansion shall not be performed
4537 * on the word by a non-interactive shell; an interactive
4538 * shell may perform it, but shall do so only when
4539 * the expansion would result in one word."
4541 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4542 /* Cater for >\file case:
4543 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4544 * Same with heredocs:
4545 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4547 unbackslash(ctx->pending_redirect->rd_filename);
4548 /* Is it <<"HEREDOC"? */
4549 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4552 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4554 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4555 ctx->pending_redirect = NULL;
4557 /* If this word wasn't an assignment, next ones definitely
4558 * can't be assignments. Even if they look like ones. */
4559 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4560 && word->o_assignment != WORD_IS_KEYWORD
4562 word->o_assignment = NOT_ASSIGNMENT;
4564 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4565 command->assignment_cnt++;
4566 word->o_assignment = MAYBE_ASSIGNMENT;
4570 # if ENABLE_HUSH_CASE
4571 if (ctx->ctx_dsemicolon
4572 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4574 /* already done when ctx_dsemicolon was set to 1: */
4575 /* ctx->ctx_res_w = RES_MATCH; */
4576 ctx->ctx_dsemicolon = 0;
4579 if (!command->argv /* if it's the first word... */
4580 # if ENABLE_HUSH_LOOPS
4581 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4582 && ctx->ctx_res_w != RES_IN
4584 # if ENABLE_HUSH_CASE
4585 && ctx->ctx_res_w != RES_CASE
4588 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4589 if (reserved_word(word, ctx)) {
4590 o_reset_to_empty_unquoted(word);
4591 debug_printf_parse("done_word return %d\n",
4592 (ctx->ctx_res_w == RES_SNTX));
4593 return (ctx->ctx_res_w == RES_SNTX);
4597 if (command->group) {
4598 /* "{ echo foo; } echo bar" - bad */
4599 syntax_error_at(word->data);
4600 debug_printf_parse("done_word return 1: syntax error, "
4601 "groups and arglists don't mix\n");
4604 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4605 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4606 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4607 /* (otherwise it's known to be not empty and is already safe) */
4609 /* exclude "$@" - it can expand to no word despite "" */
4610 char *p = word->data;
4611 while (p[0] == SPECIAL_VAR_SYMBOL
4612 && (p[1] & 0x7f) == '@'
4613 && p[2] == SPECIAL_VAR_SYMBOL
4617 if (p == word->data || p[0] != '\0') {
4618 /* saw no "$@", or not only "$@" but some
4619 * real text is there too */
4620 /* insert "empty variable" reference, this makes
4621 * e.g. "", $empty"" etc to not disappear */
4622 o_addchr(word, SPECIAL_VAR_SYMBOL);
4623 o_addchr(word, SPECIAL_VAR_SYMBOL);
4626 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4627 debug_print_strings("word appended to argv", command->argv);
4630 #if ENABLE_HUSH_LOOPS
4631 if (ctx->ctx_res_w == RES_FOR) {
4633 || !is_well_formed_var_name(command->argv[0], '\0')
4635 /* bash says just "not a valid identifier" */
4636 syntax_error("not a valid identifier in for");
4639 /* Force FOR to have just one word (variable name) */
4640 /* NB: basically, this makes hush see "for v in ..."
4641 * syntax as if it is "for v; in ...". FOR and IN become
4642 * two pipe structs in parse tree. */
4643 done_pipe(ctx, PIPE_SEQ);
4646 #if ENABLE_HUSH_CASE
4647 /* Force CASE to have just one word */
4648 if (ctx->ctx_res_w == RES_CASE) {
4649 done_pipe(ctx, PIPE_SEQ);
4653 o_reset_to_empty_unquoted(word);
4655 debug_printf_parse("done_word return 0\n");
4660 /* Peek ahead in the input to find out if we have a "&n" construct,
4661 * as in "2>&1", that represents duplicating a file descriptor.
4663 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4664 * REDIRFD_SYNTAX_ERR if syntax error,
4665 * REDIRFD_TO_FILE if no & was seen,
4666 * or the number found.
4669 #define parse_redir_right_fd(as_string, input) \
4670 parse_redir_right_fd(input)
4672 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4678 return REDIRFD_TO_FILE;
4680 ch = i_getch(input); /* get the & */
4681 nommu_addchr(as_string, ch);
4684 ch = i_getch(input);
4685 nommu_addchr(as_string, ch);
4686 return REDIRFD_CLOSE;
4690 while (ch != EOF && isdigit(ch)) {
4691 d = d*10 + (ch-'0');
4693 ch = i_getch(input);
4694 nommu_addchr(as_string, ch);
4699 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4701 bb_error_msg("ambiguous redirect");
4702 return REDIRFD_SYNTAX_ERR;
4705 /* Return code is 0 normal, 1 if a syntax error is detected
4707 static int parse_redirect(struct parse_context *ctx,
4710 struct in_str *input)
4712 struct command *command = ctx->command;
4713 struct redir_struct *redir;
4714 struct redir_struct **redirp;
4717 dup_num = REDIRFD_TO_FILE;
4718 if (style != REDIRECT_HEREDOC) {
4719 /* Check for a '>&1' type redirect */
4720 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4721 if (dup_num == REDIRFD_SYNTAX_ERR)
4724 int ch = i_peek(input);
4725 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4726 if (dup_num) { /* <<-... */
4727 ch = i_getch(input);
4728 nommu_addchr(&ctx->as_string, ch);
4733 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4734 int ch = i_peek(input);
4736 /* >|FILE redirect ("clobbering" >).
4737 * Since we do not support "set -o noclobber" yet,
4738 * >| and > are the same for now. Just eat |.
4740 ch = i_getch(input);
4741 nommu_addchr(&ctx->as_string, ch);
4745 /* Create a new redir_struct and append it to the linked list */
4746 redirp = &command->redirects;
4747 while ((redir = *redirp) != NULL) {
4748 redirp = &(redir->next);
4750 *redirp = redir = xzalloc(sizeof(*redir));
4751 /* redir->next = NULL; */
4752 /* redir->rd_filename = NULL; */
4753 redir->rd_type = style;
4754 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4756 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4757 redir_table[style].descrip);
4759 redir->rd_dup = dup_num;
4760 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4761 /* Erik had a check here that the file descriptor in question
4762 * is legit; I postpone that to "run time"
4763 * A "-" representation of "close me" shows up as a -3 here */
4764 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4765 redir->rd_fd, redir->rd_dup);
4767 /* Set ctx->pending_redirect, so we know what to do at the
4768 * end of the next parsed word. */
4769 ctx->pending_redirect = redir;
4774 /* If a redirect is immediately preceded by a number, that number is
4775 * supposed to tell which file descriptor to redirect. This routine
4776 * looks for such preceding numbers. In an ideal world this routine
4777 * needs to handle all the following classes of redirects...
4778 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4779 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4780 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4781 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4783 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4785 * ... If n is quoted, the number shall not be recognized as part of
4786 * the redirection expression. For example:
4788 * writes the character 2 into file a"
4789 * We are getting it right by setting ->o_quoted on any \<char>
4791 * A -1 return means no valid number was found,
4792 * the caller should use the appropriate default for this redirection.
4794 static int redirect_opt_num(o_string *o)
4798 if (o->data == NULL)
4800 num = bb_strtou(o->data, NULL, 10);
4801 if (errno || num < 0)
4803 o_reset_to_empty_unquoted(o);
4808 #define fetch_till_str(as_string, input, word, skip_tabs) \
4809 fetch_till_str(input, word, skip_tabs)
4811 static char *fetch_till_str(o_string *as_string,
4812 struct in_str *input,
4816 o_string heredoc = NULL_O_STRING;
4822 ch = i_getch(input);
4823 nommu_addchr(as_string, ch);
4825 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4826 heredoc.data[past_EOL] = '\0';
4827 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4828 return heredoc.data;
4831 o_addchr(&heredoc, ch);
4832 past_EOL = heredoc.length;
4835 ch = i_getch(input);
4836 nommu_addchr(as_string, ch);
4837 } while (skip_tabs && ch == '\t');
4838 } while (ch == '\n');
4841 o_free_unsafe(&heredoc);
4844 o_addchr(&heredoc, ch);
4845 nommu_addchr(as_string, ch);
4849 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4850 * and load them all. There should be exactly heredoc_cnt of them.
4852 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4854 struct pipe *pi = ctx->list_head;
4856 while (pi && heredoc_cnt) {
4858 struct command *cmd = pi->cmds;
4860 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4862 cmd->argv ? cmd->argv[0] : "NONE");
4863 for (i = 0; i < pi->num_cmds; i++) {
4864 struct redir_struct *redir = cmd->redirects;
4866 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4867 i, cmd->argv ? cmd->argv[0] : "NONE");
4869 if (redir->rd_type == REDIRECT_HEREDOC) {
4872 redir->rd_type = REDIRECT_HEREDOC2;
4873 /* redir->dup is (ab)used to indicate <<- */
4874 p = fetch_till_str(&ctx->as_string, input,
4875 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4877 syntax_error("unexpected EOF in here document");
4880 free(redir->rd_filename);
4881 redir->rd_filename = p;
4884 redir = redir->next;
4891 /* Should be 0. If it isn't, it's a parse error */
4893 bb_error_msg_and_die("heredoc BUG 2");
4899 #if ENABLE_HUSH_TICK
4900 static FILE *generate_stream_from_string(const char *s)
4903 int pid, channel[2];
4909 pid = BB_MMU ? fork() : vfork();
4911 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4913 if (pid == 0) { /* child */
4914 disable_restore_tty_pgrp_on_exit();
4915 /* Process substitution is not considered to be usual
4916 * 'command execution'.
4917 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4924 close(channel[0]); /* NB: close _first_, then move fd! */
4925 xmove_fd(channel[1], 1);
4926 /* Prevent it from trying to handle ctrl-z etc */
4927 IF_HUSH_JOB(G.run_list_level = 1;)
4929 reset_traps_to_defaults();
4930 parse_and_run_string(s);
4931 _exit(G.last_exitcode);
4933 /* We re-execute after vfork on NOMMU. This makes this script safe:
4934 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4935 * huge=`cat BIG` # was blocking here forever
4938 re_execute_shell(&to_free,
4946 #if ENABLE_HUSH_FAST
4948 //bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4950 enable_restore_tty_pgrp_on_exit();
4955 pf = fdopen(channel[0], "r");
4959 /* Return code is exit status of the process that is run. */
4960 static int process_command_subs(o_string *dest, const char *s)
4963 struct in_str pipe_str;
4966 pf = generate_stream_from_string(s);
4969 close_on_exec_on(fileno(pf));
4971 /* Now send results of command back into original context */
4972 setup_file_in_str(&pipe_str, pf);
4974 while ((ch = i_getch(&pipe_str)) != EOF) {
4980 o_addchr(dest, '\n');
4983 o_addQchr(dest, ch);
4986 debug_printf("done reading from pipe, pclose()ing\n");
4987 /* Note: we got EOF, and we just close the read end of the pipe.
4988 * We do not wait for the `cmd` child to terminate. bash and ash do.
4990 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4991 * `false`; echo $? - bash outputs "1"
4994 debug_printf("closed FILE from child. return 0\n");
4999 static int parse_group(o_string *dest, struct parse_context *ctx,
5000 struct in_str *input, int ch)
5002 /* dest contains characters seen prior to ( or {.
5003 * Typically it's empty, but for function defs,
5004 * it contains function name (without '()'). */
5005 struct pipe *pipe_list;
5007 struct command *command = ctx->command;
5009 debug_printf_parse("parse_group entered\n");
5010 #if ENABLE_HUSH_FUNCTIONS
5011 if (ch == '(' && !dest->o_quoted) {
5013 if (done_word(dest, ctx))
5016 goto skip; /* (... */
5017 if (command->argv[1]) { /* word word ... (... */
5018 syntax_error_unexpected_ch('(');
5021 /* it is "word(..." or "word (..." */
5023 ch = i_getch(input);
5024 while (ch == ' ' || ch == '\t');
5026 syntax_error_unexpected_ch(ch);
5029 nommu_addchr(&ctx->as_string, ch);
5031 ch = i_getch(input);
5032 while (ch == ' ' || ch == '\t' || ch == '\n');
5034 syntax_error_unexpected_ch(ch);
5037 nommu_addchr(&ctx->as_string, ch);
5038 command->grp_type = GRP_FUNCTION;
5042 if (command->argv /* word [word]{... */
5043 || dest->length /* word{... */
5044 || dest->o_quoted /* ""{... */
5047 debug_printf_parse("parse_group return 1: "
5048 "syntax error, groups and arglists don't mix\n");
5052 #if ENABLE_HUSH_FUNCTIONS
5058 command->grp_type = GRP_SUBSHELL;
5060 /* bash does not allow "{echo...", requires whitespace */
5061 ch = i_getch(input);
5062 if (ch != ' ' && ch != '\t' && ch != '\n') {
5063 syntax_error_unexpected_ch(ch);
5066 nommu_addchr(&ctx->as_string, ch);
5071 char *as_string = NULL;
5073 pipe_list = parse_stream(&as_string, input, endch);
5076 o_addstr(&ctx->as_string, as_string);
5078 /* empty ()/{} or parse error? */
5079 if (!pipe_list || pipe_list == ERR_PTR) {
5080 /* parse_stream already emitted error msg */
5084 debug_printf_parse("parse_group return 1: "
5085 "parse_stream returned %p\n", pipe_list);
5088 command->group = pipe_list;
5090 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5091 command->group_as_string = as_string;
5092 debug_printf_parse("end of group, remembering as:'%s'\n",
5093 command->group_as_string);
5096 debug_printf_parse("parse_group return 0\n");
5098 /* command remains "open", available for possible redirects */
5101 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5102 /* Subroutines for copying $(...) and `...` things */
5103 static void add_till_backquote(o_string *dest, struct in_str *input);
5105 static void add_till_single_quote(o_string *dest, struct in_str *input)
5108 int ch = i_getch(input);
5110 syntax_error_unterm_ch('\'');
5111 /*xfunc_die(); - redundant */
5118 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5119 static void add_till_double_quote(o_string *dest, struct in_str *input)
5122 int ch = i_getch(input);
5124 syntax_error_unterm_ch('"');
5125 /*xfunc_die(); - redundant */
5129 if (ch == '\\') { /* \x. Copy both chars. */
5131 ch = i_getch(input);
5135 add_till_backquote(dest, input);
5139 //if (ch == '$') ...
5142 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5144 * "Within the backquoted style of command substitution, backslash
5145 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5146 * The search for the matching backquote shall be satisfied by the first
5147 * backquote found without a preceding backslash; during this search,
5148 * if a non-escaped backquote is encountered within a shell comment,
5149 * a here-document, an embedded command substitution of the $(command)
5150 * form, or a quoted string, undefined results occur. A single-quoted
5151 * or double-quoted string that begins, but does not end, within the
5152 * "`...`" sequence produces undefined results."
5154 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5156 static void add_till_backquote(o_string *dest, struct in_str *input)
5159 int ch = i_getch(input);
5161 syntax_error_unterm_ch('`');
5162 /*xfunc_die(); - redundant */
5167 /* \x. Copy both chars unless it is \` */
5168 int ch2 = i_getch(input);
5170 syntax_error_unterm_ch('`');
5171 /*xfunc_die(); - redundant */
5173 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5180 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5181 * quoting and nested ()s.
5182 * "With the $(command) style of command substitution, all characters
5183 * following the open parenthesis to the matching closing parenthesis
5184 * constitute the command. Any valid shell script can be used for command,
5185 * except a script consisting solely of redirections which produces
5186 * unspecified results."
5188 * echo $(echo '(TEST)' BEST) (TEST) BEST
5189 * echo $(echo 'TEST)' BEST) TEST) BEST
5190 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5192 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5196 int ch = i_getch(input);
5198 syntax_error_unterm_ch(')');
5199 /*xfunc_die(); - redundant */
5207 if (i_peek(input) == ')') {
5215 add_till_single_quote(dest, input);
5220 add_till_double_quote(dest, input);
5225 /* \x. Copy verbatim. Important for \(, \) */
5226 ch = i_getch(input);
5228 syntax_error_unterm_ch(')');
5229 /*xfunc_die(); - redundant */
5236 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5238 /* Return code: 0 for OK, 1 for syntax error */
5240 #define handle_dollar(as_string, dest, input) \
5241 handle_dollar(dest, input)
5243 static int handle_dollar(o_string *as_string,
5245 struct in_str *input)
5248 int ch = i_peek(input); /* first character after the $ */
5249 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5251 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5253 ch = i_getch(input);
5254 nommu_addchr(as_string, ch);
5256 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5258 debug_printf_parse(": '%c'\n", ch);
5259 o_addchr(dest, ch | quote_mask);
5262 if (!isalnum(ch) && ch != '_')
5264 ch = i_getch(input);
5265 nommu_addchr(as_string, ch);
5267 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5268 } else if (isdigit(ch)) {
5270 ch = i_getch(input);
5271 nommu_addchr(as_string, ch);
5272 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5273 debug_printf_parse(": '%c'\n", ch);
5274 o_addchr(dest, ch | quote_mask);
5275 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5276 } else switch (ch) {
5278 case '!': /* last bg pid */
5279 case '?': /* last exit code */
5280 case '#': /* number of args */
5281 case '*': /* args */
5282 case '@': /* args */
5283 goto make_one_char_var;
5285 bool first_char, all_digits;
5287 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5288 ch = i_getch(input);
5289 nommu_addchr(as_string, ch);
5290 /* TODO: maybe someone will try to escape the '}' */
5295 ch = i_getch(input);
5296 nommu_addchr(as_string, ch);
5303 /* ${#var}: length of var contents */
5313 && ( (all_digits && !isdigit(ch))
5314 || (!all_digits && !isalnum(ch) && ch != '_')
5317 /* handle parameter expansions
5318 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5323 case ':': /* null modifier */
5324 if (expansion == 0) {
5325 debug_printf_parse(": null modifier\n");
5330 case '#': /* remove prefix */
5331 case '%': /* remove suffix */
5332 if (expansion == 0) {
5333 debug_printf_parse(": remove suffix/prefix\n");
5338 case '-': /* default value */
5339 case '=': /* assign default */
5340 case '+': /* alternative */
5341 case '?': /* error indicate */
5342 debug_printf_parse(": parameter expansion\n");
5347 syntax_error_unterm_str("${name}");
5348 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5353 debug_printf_parse(": '%c'\n", ch);
5354 o_addchr(dest, ch | quote_mask);
5358 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5361 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5366 ch = i_getch(input);
5367 nommu_addchr(as_string, ch);
5368 # if ENABLE_SH_MATH_SUPPORT
5369 if (i_peek(input) == '(') {
5370 ch = i_getch(input);
5371 nommu_addchr(as_string, ch);
5372 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5373 o_addchr(dest, /*quote_mask |*/ '+');
5377 add_till_closing_paren(dest, input, true);
5380 o_addstr(as_string, dest->data + pos);
5381 o_addchr(as_string, ')');
5382 o_addchr(as_string, ')');
5385 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5389 # if ENABLE_HUSH_TICK
5390 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5391 o_addchr(dest, quote_mask | '`');
5395 add_till_closing_paren(dest, input, false);
5398 o_addstr(as_string, dest->data + pos);
5399 o_addchr(as_string, '`');
5402 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5408 ch = i_getch(input);
5409 nommu_addchr(as_string, ch);
5411 if (isalnum(ch)) { /* it's $_name or $_123 */
5417 /* $_ Shell or shell script name; or last cmd name */
5418 /* $- Option flags set by set builtin or shell options (-i etc) */
5420 o_addQchr(dest, '$');
5422 debug_printf_parse("handle_dollar return 0\n");
5427 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5428 parse_stream_dquoted(dest, input, dquote_end)
5430 static int parse_stream_dquoted(o_string *as_string,
5432 struct in_str *input,
5439 ch = i_getch(input);
5441 nommu_addchr(as_string, ch);
5442 if (ch == dquote_end) { /* may be only '"' or EOF */
5443 if (dest->o_assignment == NOT_ASSIGNMENT)
5444 dest->o_escape ^= 1;
5445 debug_printf_parse("parse_stream_dquoted return 0\n");
5448 /* note: can't move it above ch == dquote_end check! */
5450 syntax_error_unterm_ch('"');
5451 /*xfunc_die(); - redundant */
5455 next = i_peek(input);
5457 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5458 ch, ch, dest->o_escape);
5461 syntax_error("\\<eof>");
5465 * "The backslash retains its special meaning [in "..."]
5466 * only when followed by one of the following characters:
5467 * $, `, ", \, or <newline>. A double quote may be quoted
5468 * within double quotes by preceding it with a backslash.
5470 if (strchr("$`\"\\\n", next) != NULL) {
5471 ch = i_getch(input);
5473 o_addqchr(dest, ch);
5474 nommu_addchr(as_string, ch);
5477 o_addqchr(dest, '\\');
5478 nommu_addchr(as_string, '\\');
5483 if (handle_dollar(as_string, dest, input) != 0) {
5484 debug_printf_parse("parse_stream_dquoted return 1: "
5485 "handle_dollar returned non-0\n");
5490 #if ENABLE_HUSH_TICK
5492 //int pos = dest->length;
5493 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5494 o_addchr(dest, 0x80 | '`');
5495 add_till_backquote(dest, input);
5496 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5497 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5501 o_addQchr(dest, ch);
5503 && (dest->o_assignment == MAYBE_ASSIGNMENT
5504 || dest->o_assignment == WORD_IS_KEYWORD)
5505 && is_well_formed_var_name(dest->data, '=')
5507 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5513 * Scan input until EOF or end_trigger char.
5514 * Return a list of pipes to execute, or NULL on EOF
5515 * or if end_trigger character is met.
5516 * On syntax error, exit is shell is not interactive,
5517 * reset parsing machinery and start parsing anew,
5518 * or return ERR_PTR.
5520 static struct pipe *parse_stream(char **pstring,
5521 struct in_str *input,
5524 struct parse_context ctx;
5525 o_string dest = NULL_O_STRING;
5529 /* Double-quote state is handled in the state variable is_in_dquote.
5530 * A single-quote triggers a bypass of the main loop until its mate is
5531 * found. When recursing, quote state is passed in via dest->o_escape.
5533 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5534 end_trigger ? : 'X');
5537 G.ifs = get_local_var_value("IFS");
5542 #if ENABLE_HUSH_INTERACTIVE
5543 input->promptmode = 0; /* PS1 */
5545 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5546 initialize_context(&ctx);
5551 const char *is_special;
5555 redir_type redir_style;
5558 /* dest.o_quoted = 1; - already is (see below) */
5559 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5562 /* We reached closing '"' */
5565 ch = i_getch(input);
5566 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5567 ch, ch, dest.o_escape);
5572 syntax_error_unterm_str("here document");
5575 /* end_trigger == '}' case errors out earlier,
5576 * checking only ')' */
5577 if (end_trigger == ')') {
5578 syntax_error_unterm_ch('('); /* exits */
5579 /* goto parse_error; */
5582 if (done_word(&dest, &ctx)) {
5586 done_pipe(&ctx, PIPE_SEQ);
5588 /* If we got nothing... */
5589 /* (this makes bare "&" cmd a no-op.
5590 * bash says: "syntax error near unexpected token '&'") */
5591 if (pi->num_cmds == 0
5592 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5598 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5600 *pstring = ctx.as_string.data;
5602 o_free_unsafe(&ctx.as_string);
5605 debug_printf_parse("parse_stream return %p\n", pi);
5608 nommu_addchr(&ctx.as_string, ch);
5609 is_ifs = strchr(G.ifs, ch);
5610 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5611 "\\$\"" IF_HUSH_TICK("`") /* always special */
5614 if (!is_special && !is_ifs) { /* ordinary char */
5616 o_addQchr(&dest, ch);
5617 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5618 || dest.o_assignment == WORD_IS_KEYWORD)
5620 && is_well_formed_var_name(dest.data, '=')
5622 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5628 if (done_word(&dest, &ctx)) {
5632 #if ENABLE_HUSH_CASE
5633 /* "case ... in <newline> word) ..." -
5634 * newlines are ignored (but ';' wouldn't be) */
5635 if (ctx.command->argv == NULL
5636 && ctx.ctx_res_w == RES_MATCH
5641 /* Treat newline as a command separator. */
5642 done_pipe(&ctx, PIPE_SEQ);
5643 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5645 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5650 dest.o_assignment = MAYBE_ASSIGNMENT;
5652 /* note: if (is_ifs) continue;
5653 * will still trigger for us */
5657 /* "cmd}" or "cmd }..." without semicolon or &:
5658 * } is an ordinary char in this case, even inside { cmd; }
5659 * Pathological example: { ""}; } should exec "}" cmd
5662 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5663 || dest.length != 0 /* word} */
5664 || dest.o_quoted /* ""} */
5668 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5669 goto skip_end_trigger;
5670 /* else: } does terminate a group */
5673 if (end_trigger && end_trigger == ch
5674 && (ch != ';' || heredoc_cnt == 0)
5675 #if ENABLE_HUSH_CASE
5677 || ctx.ctx_res_w != RES_MATCH
5678 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5683 /* This is technically valid:
5684 * { cat <<HERE; }; echo Ok
5688 * but we don't support this.
5689 * We require heredoc to be in enclosing {}/(),
5692 syntax_error_unterm_str("here document");
5695 if (done_word(&dest, &ctx)) {
5698 done_pipe(&ctx, PIPE_SEQ);
5699 dest.o_assignment = MAYBE_ASSIGNMENT;
5700 /* Do we sit outside of any if's, loops or case's? */
5702 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5706 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5708 *pstring = ctx.as_string.data;
5710 o_free_unsafe(&ctx.as_string);
5713 debug_printf_parse("parse_stream return %p: "
5714 "end_trigger char found\n",
5716 return ctx.list_head;
5725 next = i_peek(input);
5728 /* Catch <, > before deciding whether this word is
5729 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5732 redir_fd = redirect_opt_num(&dest);
5733 if (done_word(&dest, &ctx)) {
5736 redir_style = REDIRECT_OVERWRITE;
5738 redir_style = REDIRECT_APPEND;
5739 ch = i_getch(input);
5740 nommu_addchr(&ctx.as_string, ch);
5743 else if (next == '(') {
5744 syntax_error(">(process) not supported");
5748 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5750 continue; /* back to top of while (1) */
5752 redir_fd = redirect_opt_num(&dest);
5753 if (done_word(&dest, &ctx)) {
5756 redir_style = REDIRECT_INPUT;
5758 redir_style = REDIRECT_HEREDOC;
5760 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5761 ch = i_getch(input);
5762 nommu_addchr(&ctx.as_string, ch);
5763 } else if (next == '>') {
5764 redir_style = REDIRECT_IO;
5765 ch = i_getch(input);
5766 nommu_addchr(&ctx.as_string, ch);
5769 else if (next == '(') {
5770 syntax_error("<(process) not supported");
5774 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5776 continue; /* back to top of while (1) */
5779 if (dest.o_assignment == MAYBE_ASSIGNMENT
5780 /* check that we are not in word in "a=1 2>word b=1": */
5781 && !ctx.pending_redirect
5783 /* ch is a special char and thus this word
5784 * cannot be an assignment */
5785 dest.o_assignment = NOT_ASSIGNMENT;
5790 if (dest.length == 0) {
5793 if (ch == EOF || ch == '\n')
5796 /* note: we do not add it to &ctx.as_string */
5798 nommu_addchr(&ctx.as_string, '\n');
5800 o_addQchr(&dest, ch);
5805 syntax_error("\\<eof>");
5808 ch = i_getch(input);
5810 o_addchr(&dest, '\\');
5811 nommu_addchr(&ctx.as_string, '\\');
5812 o_addchr(&dest, ch);
5813 nommu_addchr(&ctx.as_string, ch);
5814 /* Example: echo Hello \2>file
5815 * we need to know that word 2 is quoted */
5820 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5821 debug_printf_parse("parse_stream parse error: "
5822 "handle_dollar returned non-0\n");
5829 ch = i_getch(input);
5831 syntax_error_unterm_ch('\'');
5832 /*xfunc_die(); - redundant */
5834 nommu_addchr(&ctx.as_string, ch);
5837 if (dest.o_assignment == NOT_ASSIGNMENT)
5838 o_addqchr(&dest, ch);
5840 o_addchr(&dest, ch);
5845 is_in_dquote ^= 1; /* invert */
5846 if (dest.o_assignment == NOT_ASSIGNMENT)
5849 #if ENABLE_HUSH_TICK
5854 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5855 o_addchr(&dest, '`');
5859 add_till_backquote(&dest, input);
5861 o_addstr(&ctx.as_string, dest.data + pos);
5862 o_addchr(&ctx.as_string, '`');
5864 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5865 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5870 #if ENABLE_HUSH_CASE
5873 if (done_word(&dest, &ctx)) {
5876 done_pipe(&ctx, PIPE_SEQ);
5877 #if ENABLE_HUSH_CASE
5878 /* Eat multiple semicolons, detect
5879 * whether it means something special */
5884 ch = i_getch(input);
5885 nommu_addchr(&ctx.as_string, ch);
5886 if (ctx.ctx_res_w == RES_CASE_BODY) {
5887 ctx.ctx_dsemicolon = 1;
5888 ctx.ctx_res_w = RES_MATCH;
5894 /* We just finished a cmd. New one may start
5895 * with an assignment */
5896 dest.o_assignment = MAYBE_ASSIGNMENT;
5899 if (done_word(&dest, &ctx)) {
5903 ch = i_getch(input);
5904 nommu_addchr(&ctx.as_string, ch);
5905 done_pipe(&ctx, PIPE_AND);
5907 done_pipe(&ctx, PIPE_BG);
5911 if (done_word(&dest, &ctx)) {
5914 #if ENABLE_HUSH_CASE
5915 if (ctx.ctx_res_w == RES_MATCH)
5916 break; /* we are in case's "word | word)" */
5918 if (next == '|') { /* || */
5919 ch = i_getch(input);
5920 nommu_addchr(&ctx.as_string, ch);
5921 done_pipe(&ctx, PIPE_OR);
5923 /* we could pick up a file descriptor choice here
5924 * with redirect_opt_num(), but bash doesn't do it.
5925 * "echo foo 2| cat" yields "foo 2". */
5930 #if ENABLE_HUSH_CASE
5931 /* "case... in [(]word)..." - skip '(' */
5932 if (ctx.ctx_res_w == RES_MATCH
5933 && ctx.command->argv == NULL /* not (word|(... */
5934 && dest.length == 0 /* not word(... */
5935 && dest.o_quoted == 0 /* not ""(... */
5941 if (parse_group(&dest, &ctx, input, ch) != 0) {
5946 #if ENABLE_HUSH_CASE
5947 if (ctx.ctx_res_w == RES_MATCH)
5951 /* proper use of this character is caught by end_trigger:
5952 * if we see {, we call parse_group(..., end_trigger='}')
5953 * and it will match } earlier (not here). */
5954 syntax_error_unexpected_ch(ch);
5958 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5964 struct parse_context *pctx;
5965 IF_HAS_KEYWORDS(struct parse_context *p2;)
5967 /* Clean up allocated tree.
5968 * Samples for finding leaks on syntax error recovery path.
5969 * Run them from interactive shell, watch pmap `pidof hush`.
5970 * while if false; then false; fi do break; done
5972 * while if false; then false; fi; do break; fi
5973 * Samples to catch leaks at execution:
5974 * while if (true | {true;}); then echo ok; fi; do break; done
5975 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5979 /* Update pipe/command counts,
5980 * otherwise freeing may miss some */
5981 done_pipe(pctx, PIPE_SEQ);
5982 debug_printf_clean("freeing list %p from ctx %p\n",
5983 pctx->list_head, pctx);
5984 debug_print_tree(pctx->list_head, 0);
5985 free_pipe_list(pctx->list_head);
5986 debug_printf_clean("freed list %p\n", pctx->list_head);
5988 o_free_unsafe(&pctx->as_string);
5990 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5994 IF_HAS_KEYWORDS(pctx = p2;)
5995 } while (HAS_KEYWORDS && pctx);
5996 /* Free text, clear all dest fields */
5998 /* If we are not in top-level parse, we return,
5999 * our caller will propagate error.
6001 if (end_trigger != ';') {
6009 /* Discard cached input, force prompt */
6011 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6016 /* Executing from string: eval, sh -c '...'
6017 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6018 * end_trigger controls how often we stop parsing
6019 * NUL: parse all, execute, return
6020 * ';': parse till ';' or newline, execute, repeat till EOF
6022 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6025 struct pipe *pipe_list;
6027 pipe_list = parse_stream(NULL, inp, end_trigger);
6028 if (!pipe_list) /* EOF */
6030 debug_print_tree(pipe_list, 0);
6031 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6032 run_and_free_list(pipe_list);
6036 static void parse_and_run_string(const char *s)
6038 struct in_str input;
6039 setup_string_in_str(&input, s);
6040 parse_and_run_stream(&input, '\0');
6043 static void parse_and_run_file(FILE *f)
6045 struct in_str input;
6046 setup_file_in_str(&input, f);
6047 parse_and_run_stream(&input, ';');
6050 /* Called a few times only (or even once if "sh -c") */
6051 static void block_signals(int second_time)
6056 mask = (1 << SIGQUIT);
6057 if (G_interactive_fd) {
6058 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6059 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6060 mask |= SPECIAL_JOB_SIGS;
6062 G.non_DFL_mask = mask;
6065 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6069 sigaddset(&G.blocked_set, sig);
6073 sigdelset(&G.blocked_set, SIGCHLD);
6075 sigprocmask(SIG_SETMASK, &G.blocked_set,
6076 second_time ? NULL : &G.inherited_set);
6077 /* POSIX allows shell to re-enable SIGCHLD
6078 * even if it was SIG_IGN on entry */
6079 #if ENABLE_HUSH_FAST
6080 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6082 signal(SIGCHLD, SIGCHLD_handler);
6085 signal(SIGCHLD, SIG_DFL);
6091 static void maybe_set_to_sigexit(int sig)
6093 void (*handler)(int);
6094 /* non_DFL_mask'ed signals are, well, masked,
6095 * no need to set handler for them.
6097 if (!((G.non_DFL_mask >> sig) & 1)) {
6098 handler = signal(sig, sigexit);
6099 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6100 signal(sig, handler);
6103 /* Set handlers to restore tty pgrp and exit */
6104 static void set_fatal_handlers(void)
6106 /* We _must_ restore tty pgrp on fatal signals */
6108 maybe_set_to_sigexit(SIGILL );
6109 maybe_set_to_sigexit(SIGFPE );
6110 maybe_set_to_sigexit(SIGBUS );
6111 maybe_set_to_sigexit(SIGSEGV);
6112 maybe_set_to_sigexit(SIGTRAP);
6113 } /* else: hush is perfect. what SEGV? */
6114 maybe_set_to_sigexit(SIGABRT);
6115 /* bash 3.2 seems to handle these just like 'fatal' ones */
6116 maybe_set_to_sigexit(SIGPIPE);
6117 maybe_set_to_sigexit(SIGALRM);
6118 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6119 * if we aren't interactive... but in this case
6120 * we never want to restore pgrp on exit, and this fn is not called */
6121 /*maybe_set_to_sigexit(SIGHUP );*/
6122 /*maybe_set_to_sigexit(SIGTERM);*/
6123 /*maybe_set_to_sigexit(SIGINT );*/
6127 static int set_mode(const char cstate, const char mode)
6129 int state = (cstate == '-' ? 1 : 0);
6131 case 'n': G.fake_mode = state; break;
6132 case 'x': /*G.debug_mode = state;*/ break;
6133 default: return EXIT_FAILURE;
6135 return EXIT_SUCCESS;
6138 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6139 int hush_main(int argc, char **argv)
6141 static const struct variable const_shell_ver = {
6143 .varstr = (char*)hush_version_str,
6144 .max_len = 1, /* 0 can provoke free(name) */
6148 int signal_mask_is_inited = 0;
6151 struct variable *cur_var;
6154 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6155 G.last_exitcode = EXIT_SUCCESS;
6157 G.argv0_for_re_execing = argv[0];
6159 /* Deal with HUSH_VERSION */
6160 G.shell_ver = const_shell_ver; /* copying struct here */
6161 G.top_var = &G.shell_ver;
6162 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6163 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6164 /* Initialize our shell local variables with the values
6165 * currently living in the environment */
6166 cur_var = G.top_var;
6169 char *value = strchr(*e, '=');
6170 if (value) { /* paranoia */
6171 cur_var->next = xzalloc(sizeof(*cur_var));
6172 cur_var = cur_var->next;
6173 cur_var->varstr = *e;
6174 cur_var->max_len = strlen(*e);
6175 cur_var->flg_export = 1;
6179 debug_printf_env("putenv '%s'\n", hush_version_str);
6180 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6181 #if ENABLE_FEATURE_EDITING
6182 G.line_input_state = new_line_input_t(FOR_SHELL);
6184 G.global_argc = argc;
6185 G.global_argv = argv;
6186 /* Initialize some more globals to non-zero values */
6188 cmdedit_update_prompt();
6190 if (setjmp(die_jmp)) {
6191 /* xfunc has failed! die die die */
6192 /* no EXIT traps, this is an escape hatch! */
6194 hush_exit(xfunc_error_retval);
6197 /* Shell is non-interactive at first. We need to call
6198 * block_signals(0) if we are going to execute "sh <script>",
6199 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6200 * If we later decide that we are interactive, we run block_signals(0)
6201 * (or re-run block_signals(1) if we ran block_signals(0) before)
6202 * in order to intercept (more) signals.
6206 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6208 opt = getopt(argc, argv, "c:xins"
6211 # if ENABLE_HUSH_FUNCTIONS
6221 G.root_pid = getpid();
6222 G.global_argv = argv + optind;
6223 if (!argv[optind]) {
6224 /* -c 'script' (no params): prevent empty $0 */
6225 *--G.global_argv = argv[0];
6227 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
6228 G.global_argc = argc - optind;
6229 block_signals(0); /* 0: called 1st time */
6230 parse_and_run_string(optarg);
6233 /* Well, we cannot just declare interactiveness,
6234 * we have to have some stuff (ctty, etc) */
6235 /* G_interactive_fd++; */
6238 /* "-s" means "read from stdin", but this is how we always
6239 * operate, so simply do nothing here. */
6242 case '<': /* "big heredoc" support */
6243 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6246 G.root_pid = bb_strtou(optarg, &optarg, 16);
6248 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6250 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6251 # if ENABLE_HUSH_LOOPS
6253 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6258 set_local_var(xstrdup(optarg), 0, opt == 'R');
6260 # if ENABLE_HUSH_FUNCTIONS
6262 struct function *funcp = new_function(optarg);
6263 /* funcp->name is already set to optarg */
6264 /* funcp->body is set to NULL. It's a special case. */
6265 funcp->body_as_string = argv[optind];
6273 if (!set_mode('-', opt))
6277 fprintf(stderr, "Usage: sh [FILE]...\n"
6278 " or: sh -c command [args]...\n\n");
6284 } /* option parsing loop */
6287 G.root_pid = getpid();
6289 /* If we are login shell... */
6290 if (argv[0] && argv[0][0] == '-') {
6292 debug_printf("sourcing /etc/profile\n");
6293 input = fopen_for_read("/etc/profile");
6294 if (input != NULL) {
6295 close_on_exec_on(fileno(input));
6296 block_signals(0); /* 0: called 1st time */
6297 signal_mask_is_inited = 1;
6298 parse_and_run_file(input);
6301 /* bash: after sourcing /etc/profile,
6302 * tries to source (in the given order):
6303 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6304 * stopping of first found. --noprofile turns this off.
6305 * bash also sources ~/.bash_logout on exit.
6306 * If called as sh, skips .bash_XXX files.
6313 * "bash <script>" (which is never interactive (unless -i?))
6314 * sources $BASH_ENV here (without scanning $PATH).
6315 * If called as sh, does the same but with $ENV.
6317 debug_printf("running script '%s'\n", argv[optind]);
6318 G.global_argv = argv + optind;
6319 G.global_argc = argc - optind;
6320 input = xfopen_for_read(argv[optind]);
6321 close_on_exec_on(fileno(input));
6322 if (!signal_mask_is_inited)
6323 block_signals(0); /* 0: called 1st time */
6324 parse_and_run_file(input);
6325 #if ENABLE_FEATURE_CLEAN_UP
6331 /* Up to here, shell was non-interactive. Now it may become one.
6332 * NB: don't forget to (re)run block_signals(0/1) as needed.
6335 /* A shell is interactive if the '-i' flag was given, or if all of
6336 * the following conditions are met:
6338 * no arguments remaining or the -s flag given
6339 * standard input is a terminal
6340 * standard output is a terminal
6341 * Refer to Posix.2, the description of the 'sh' utility.
6344 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6345 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6346 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6347 if (G_saved_tty_pgrp < 0)
6348 G_saved_tty_pgrp = 0;
6350 /* try to dup stdin to high fd#, >= 255 */
6351 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6352 if (G_interactive_fd < 0) {
6353 /* try to dup to any fd */
6354 G_interactive_fd = dup(STDIN_FILENO);
6355 if (G_interactive_fd < 0) {
6357 G_interactive_fd = 0;
6358 G_saved_tty_pgrp = 0;
6361 // TODO: track & disallow any attempts of user
6362 // to (inadvertently) close/redirect G_interactive_fd
6364 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6365 if (G_interactive_fd) {
6366 close_on_exec_on(G_interactive_fd);
6368 if (G_saved_tty_pgrp) {
6369 /* If we were run as 'hush &', sleep until we are
6370 * in the foreground (tty pgrp == our pgrp).
6371 * If we get started under a job aware app (like bash),
6372 * make sure we are now in charge so we don't fight over
6373 * who gets the foreground */
6375 pid_t shell_pgrp = getpgrp();
6376 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6377 if (G_saved_tty_pgrp == shell_pgrp)
6379 /* send TTIN to ourself (should stop us) */
6380 kill(- shell_pgrp, SIGTTIN);
6384 /* Block some signals */
6385 block_signals(signal_mask_is_inited);
6387 if (G_saved_tty_pgrp) {
6388 /* Set other signals to restore saved_tty_pgrp */
6389 set_fatal_handlers();
6390 /* Put ourselves in our own process group
6391 * (bash, too, does this only if ctty is available) */
6392 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6393 /* Grab control of the terminal */
6394 tcsetpgrp(G_interactive_fd, getpid());
6396 /* -1 is special - makes xfuncs longjmp, not exit
6397 * (we reset die_sleep = 0 whereever we [v]fork) */
6398 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6399 } else if (!signal_mask_is_inited) {
6400 block_signals(0); /* 0: called 1st time */
6401 } /* else: block_signals(0) was done before */
6402 #elif ENABLE_HUSH_INTERACTIVE
6403 /* No job control compiled in, only prompt/line editing */
6404 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6405 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6406 if (G_interactive_fd < 0) {
6407 /* try to dup to any fd */
6408 G_interactive_fd = dup(STDIN_FILENO);
6409 if (G_interactive_fd < 0)
6411 G_interactive_fd = 0;
6414 if (G_interactive_fd) {
6415 close_on_exec_on(G_interactive_fd);
6416 block_signals(signal_mask_is_inited);
6417 } else if (!signal_mask_is_inited) {
6421 /* We have interactiveness code disabled */
6422 if (!signal_mask_is_inited) {
6427 * if interactive but not a login shell, sources ~/.bashrc
6428 * (--norc turns this off, --rcfile <file> overrides)
6431 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6432 printf("\n\n%s hush - the humble shell\n", bb_banner);
6433 if (ENABLE_HUSH_HELP)
6434 puts("Enter 'help' for a list of built-in commands.");
6438 parse_and_run_file(stdin);
6441 #if ENABLE_FEATURE_CLEAN_UP
6442 if (G.cwd != bb_msg_unknown)
6444 cur_var = G.top_var->next;
6446 struct variable *tmp = cur_var;
6447 if (!cur_var->max_len)
6448 free(cur_var->varstr);
6449 cur_var = cur_var->next;
6453 hush_exit(G.last_exitcode);
6458 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6459 int lash_main(int argc, char **argv)
6461 //bb_error_msg("lash is deprecated, please use hush instead");
6462 return hush_main(argc, argv);
6470 static int builtin_true(char **argv UNUSED_PARAM)
6475 static int builtin_test(char **argv)
6482 return test_main(argc, argv - argc);
6485 static int builtin_echo(char **argv)
6492 return echo_main(argc, argv - argc);
6495 static int builtin_eval(char **argv)
6497 int rcode = EXIT_SUCCESS;
6500 char *str = expand_strvec_to_string(argv);
6502 * eval "echo Hi; done" ("done" is syntax error):
6503 * "echo Hi" will not execute too.
6505 parse_and_run_string(str);
6507 rcode = G.last_exitcode;
6512 static int builtin_cd(char **argv)
6514 const char *newdir = argv[1];
6515 if (newdir == NULL) {
6516 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6517 * bash says "bash: cd: HOME not set" and does nothing
6520 newdir = get_local_var_value("HOME") ? : "/";
6522 if (chdir(newdir)) {
6523 /* Mimic bash message exactly */
6524 bb_perror_msg("cd: %s", newdir);
6525 return EXIT_FAILURE;
6528 return EXIT_SUCCESS;
6531 static int builtin_exec(char **argv)
6533 if (*++argv == NULL)
6534 return EXIT_SUCCESS; /* bash does this */
6539 /* TODO: if exec fails, bash does NOT exit! We do... */
6540 pseudo_exec_argv(&dummy, argv, 0, NULL);
6545 static int builtin_exit(char **argv)
6547 debug_printf_exec("%s()\n", __func__);
6549 /* interactive bash:
6550 * # trap "echo EEE" EXIT
6553 * There are stopped jobs.
6554 * (if there are _stopped_ jobs, running ones don't count)
6557 # EEE (then bash exits)
6559 * we can use G.exiting = -1 as indicator "last cmd was exit"
6562 /* note: EXIT trap is run by hush_exit */
6563 if (*++argv == NULL)
6564 hush_exit(G.last_exitcode);
6565 /* mimic bash: exit 123abc == exit 255 + error msg */
6566 xfunc_error_retval = 255;
6567 /* bash: exit -2 == exit 254, no error msg */
6568 hush_exit(xatoi(*argv) & 0xff);
6571 static void print_escaped(const char *s)
6577 p = strchrnul(s, '\'');
6578 /* print 'xxxx', possibly just '' */
6579 printf("'%.*s'", (int)(p - s), s);
6584 /* s points to '; print "'''...'''" */
6586 do putchar('\''); while (*++s == '\'');
6591 static int builtin_export(char **argv)
6593 unsigned opt_unexport;
6595 if (argv[1] == NULL) {
6602 /* ash emits: export VAR='VAL'
6603 * bash: declare -x VAR="VAL"
6604 * we follow ash example */
6605 const char *s = *e++;
6606 const char *p = strchr(s, '=');
6608 if (!p) /* wtf? take next variable */
6611 printf("export %.*s", (int)(p - s) + 1, s);
6612 print_escaped(p + 1);
6616 /*fflush(stdout); - done after each builtin anyway */
6618 return EXIT_SUCCESS;
6621 #if ENABLE_HUSH_EXPORT_N
6622 /* "!": do not abort on errors */
6623 /* "+": stop at 1st non-option */
6624 opt_unexport = getopt32(argv, "!+n");
6625 if (opt_unexport == (unsigned)-1)
6626 return EXIT_FAILURE;
6636 /* So far we do not check that name is valid (TODO?) */
6638 if (strchr(name, '=') == NULL) {
6639 struct variable *var;
6641 var = get_local_var(name);
6643 /* export -n NAME (without =VALUE) */
6645 var->flg_export = 0;
6646 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6648 } /* else: export -n NOT_EXISTING_VAR: no-op */
6651 /* export NAME (without =VALUE) */
6653 var->flg_export = 1;
6654 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6655 putenv(var->varstr);
6658 /* Exporting non-existing variable.
6659 * bash does not put it in environment,
6660 * but remembers that it is exported,
6661 * and does put it in env when it is set later.
6662 * We just set it to "" and export. */
6663 name = xasprintf("%s=", name);
6665 /* (Un)exporting NAME=VALUE */
6666 name = xstrdup(name);
6669 /*export:*/ (opt_unexport ? -1 : 1),
6674 return EXIT_SUCCESS;
6677 static int builtin_trap(char **argv)
6683 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6688 /* No args: print all trapped */
6689 for (i = 0; i < NSIG; ++i) {
6692 print_escaped(G.traps[i]);
6693 printf(" %s\n", get_signame(i));
6696 /*fflush(stdout); - done after each builtin anyway */
6697 return EXIT_SUCCESS;
6701 /* If first arg is a number: reset all specified signals */
6702 sig = bb_strtou(*argv, NULL, 10);
6708 sig = get_signum(*argv++);
6709 if (sig < 0 || sig >= NSIG) {
6711 /* Mimic bash message exactly */
6712 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
6717 G.traps[sig] = xstrdup(new_cmd);
6719 debug_printf("trap: setting SIG%s (%i) to '%s'",
6720 get_signame(sig), sig, G.traps[sig]);
6722 /* There is no signal for 0 (EXIT) */
6727 sigaddset(&G.blocked_set, sig);
6729 /* There was a trap handler, we are removing it
6730 * (if sig has non-DFL handling,
6731 * we don't need to do anything) */
6732 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6734 sigdelset(&G.blocked_set, sig);
6737 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6741 if (!argv[1]) { /* no second arg */
6742 bb_error_msg("trap: invalid arguments");
6743 return EXIT_FAILURE;
6746 /* First arg is "-": reset all specified to default */
6747 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6748 /* Everything else: set arg as signal handler
6749 * (includes "" case, which ignores signal) */
6750 if (argv[0][0] == '-') {
6751 if (argv[0][1] == '\0') { /* "-" */
6752 /* new_cmd remains NULL: "reset these sigs" */
6755 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6758 /* else: "-something", no special meaning */
6763 goto process_sig_list;
6766 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
6767 static int builtin_type(char **argv)
6769 int ret = EXIT_SUCCESS;
6777 if (0) {} /* make conditional compile easier below */
6778 /*else if (find_alias(*argv))
6779 type = "an alias";*/
6780 #if ENABLE_HUSH_FUNCTIONS
6781 else if (find_function(*argv))
6782 type = "a function";
6784 else if (find_builtin(*argv))
6785 type = "a shell builtin";
6786 else if ((path = find_in_path(*argv)) != NULL)
6790 bb_error_msg("type: %s: not found", *argv);
6793 printf("%s is %s\n", *argv, type);
6803 /* built-in 'fg' and 'bg' handler */
6804 static int builtin_fg_bg(char **argv)
6809 if (!G_interactive_fd)
6810 return EXIT_FAILURE;
6812 /* If they gave us no args, assume they want the last backgrounded task */
6814 for (pi = G.job_list; pi; pi = pi->next) {
6815 if (pi->jobid == G.last_jobid) {
6819 bb_error_msg("%s: no current job", argv[0]);
6820 return EXIT_FAILURE;
6822 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6823 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6824 return EXIT_FAILURE;
6826 for (pi = G.job_list; pi; pi = pi->next) {
6827 if (pi->jobid == jobnum) {
6831 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6832 return EXIT_FAILURE;
6834 /* TODO: bash prints a string representation
6835 * of job being foregrounded (like "sleep 1 | cat") */
6836 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
6837 /* Put the job into the foreground. */
6838 tcsetpgrp(G_interactive_fd, pi->pgrp);
6841 /* Restart the processes in the job */
6842 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6843 for (i = 0; i < pi->num_cmds; i++) {
6844 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6845 pi->cmds[i].is_stopped = 0;
6847 pi->stopped_cmds = 0;
6849 i = kill(- pi->pgrp, SIGCONT);
6851 if (errno == ESRCH) {
6852 delete_finished_bg_job(pi);
6853 return EXIT_SUCCESS;
6855 bb_perror_msg("kill (SIGCONT)");
6858 if (argv[0][0] == 'f') {
6860 return checkjobs_and_fg_shell(pi);
6862 return EXIT_SUCCESS;
6866 #if ENABLE_HUSH_HELP
6867 static int builtin_help(char **argv UNUSED_PARAM)
6869 const struct built_in_command *x;
6872 "Built-in commands:\n"
6873 "------------------\n");
6874 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6875 printf("%s\t%s\n", x->cmd, x->descr);
6878 return EXIT_SUCCESS;
6883 static int builtin_jobs(char **argv UNUSED_PARAM)
6886 const char *status_string;
6888 for (job = G.job_list; job; job = job->next) {
6889 if (job->alive_cmds == job->stopped_cmds)
6890 status_string = "Stopped";
6892 status_string = "Running";
6894 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6896 return EXIT_SUCCESS;
6901 static int builtin_memleak(char **argv UNUSED_PARAM)
6906 /* Crude attempt to find where "free memory" starts,
6907 * sans fragmentation. */
6909 l = (unsigned long)p;
6912 if (l < (unsigned long)p) l = (unsigned long)p;
6915 if (!G.memleak_value)
6916 G.memleak_value = l;
6918 l -= G.memleak_value;
6925 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6930 static int builtin_pwd(char **argv UNUSED_PARAM)
6933 return EXIT_SUCCESS;
6936 static int builtin_read(char **argv)
6939 const char *name = "REPLY";
6943 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6944 * and _after_ that_ it will complain */
6945 if (!is_well_formed_var_name(name, '\0')) {
6946 /* Mimic bash message */
6947 bb_error_msg("read: '%s': not a valid identifier", name);
6952 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
6954 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
6955 return set_local_var(string, 0, 0);
6958 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6959 * built-in 'set' handler
6961 * set [-abCefhmnuvx] [-o option] [argument...]
6962 * set [+abCefhmnuvx] [+o option] [argument...]
6963 * set -- [argument...]
6966 * Implementations shall support the options in both their hyphen and
6967 * plus-sign forms. These options can also be specified as options to sh.
6969 * Write out all variables and their values: set
6970 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6971 * Turn on the -x and -v options: set -xv
6972 * Unset all positional parameters: set --
6973 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6974 * Set the positional parameters to the expansion of x, even if x expands
6975 * with a leading '-' or '+': set -- $x
6977 * So far, we only support "set -- [argument...]" and some of the short names.
6979 static int builtin_set(char **argv)
6982 char **pp, **g_argv;
6983 char *arg = *++argv;
6987 for (e = G.top_var; e; e = e->next)
6989 return EXIT_SUCCESS;
6993 if (!strcmp(arg, "--")) {
6997 if (arg[0] != '+' && arg[0] != '-')
6999 for (n = 1; arg[n]; ++n)
7000 if (set_mode(arg[0], arg[n]))
7002 } while ((arg = *++argv) != NULL);
7003 /* Now argv[0] is 1st argument */
7006 return EXIT_SUCCESS;
7009 /* NB: G.global_argv[0] ($0) is never freed/changed */
7010 g_argv = G.global_argv;
7011 if (G.global_args_malloced) {
7017 G.global_args_malloced = 1;
7018 pp = xzalloc(sizeof(pp[0]) * 2);
7019 pp[0] = g_argv[0]; /* retain $0 */
7022 /* This realloc's G.global_argv */
7023 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7030 return EXIT_SUCCESS;
7032 /* Nothing known, so abort */
7034 bb_error_msg("set: %s: invalid option", arg);
7035 return EXIT_FAILURE;
7038 static int builtin_shift(char **argv)
7044 if (n >= 0 && n < G.global_argc) {
7045 if (G.global_args_malloced) {
7048 free(G.global_argv[m++]);
7051 memmove(&G.global_argv[1], &G.global_argv[n+1],
7052 G.global_argc * sizeof(G.global_argv[0]));
7053 return EXIT_SUCCESS;
7055 return EXIT_FAILURE;
7058 static int builtin_source(char **argv)
7063 #if ENABLE_HUSH_FUNCTIONS
7067 if (*++argv == NULL)
7068 return EXIT_FAILURE;
7070 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7071 input = fopen_for_read(arg_path);
7074 input = fopen_or_warn(*argv, "r");
7076 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7077 return EXIT_FAILURE;
7079 close_on_exec_on(fileno(input));
7081 #if ENABLE_HUSH_FUNCTIONS
7082 sv_flg = G.flag_return_in_progress;
7083 /* "we are inside sourced file, ok to use return" */
7084 G.flag_return_in_progress = -1;
7086 save_and_replace_G_args(&sv, argv);
7088 parse_and_run_file(input);
7091 restore_G_args(&sv, argv);
7092 #if ENABLE_HUSH_FUNCTIONS
7093 G.flag_return_in_progress = sv_flg;
7096 return G.last_exitcode;
7099 static int builtin_umask(char **argv)
7106 mode_t old_mask = mask;
7109 rc = bb_parse_mode(argv[1], &mask);
7114 * bash: umask: 'q': invalid symbolic mode operator
7115 * bash: umask: 999: octal number out of range
7117 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7122 printf("%04o\n", (unsigned) mask);
7123 /* fall through and restore mask which we set to 0 */
7127 return !rc; /* rc != 0 - success */
7130 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7131 static int builtin_unset(char **argv)
7136 /* "!": do not abort on errors */
7137 /* "+": stop at 1st non-option */
7138 opts = getopt32(argv, "!+vf");
7139 if (opts == (unsigned)-1)
7140 return EXIT_FAILURE;
7142 bb_error_msg("unset: -v and -f are exclusive");
7143 return EXIT_FAILURE;
7149 if (!(opts & 2)) { /* not -f */
7150 if (unset_local_var(*argv)) {
7151 /* unset <nonexistent_var> doesn't fail.
7152 * Error is when one tries to unset RO var.
7153 * Message was printed by unset_local_var. */
7157 #if ENABLE_HUSH_FUNCTIONS
7167 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7168 static int builtin_wait(char **argv)
7170 int ret = EXIT_SUCCESS;
7173 if (*++argv == NULL) {
7174 /* Don't care about wait results */
7175 /* Note 1: must wait until there are no more children */
7176 /* Note 2: must be interruptible */
7178 * $ sleep 3 & sleep 6 & wait
7183 * $ sleep 3 & sleep 6 & wait
7187 * ^C <-- after ~4 sec from keyboard
7190 sigaddset(&G.blocked_set, SIGCHLD);
7191 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7194 if (errno == ECHILD)
7196 /* Wait for SIGCHLD or any other signal of interest */
7197 /* sigtimedwait with infinite timeout: */
7198 sig = sigwaitinfo(&G.blocked_set, NULL);
7200 sig = check_and_run_traps(sig);
7201 if (sig && sig != SIGCHLD) { /* see note 2 */
7207 sigdelset(&G.blocked_set, SIGCHLD);
7208 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7212 /* This is probably buggy wrt interruptible-ness */
7214 pid_t pid = bb_strtou(*argv, NULL, 10);
7216 /* mimic bash message */
7217 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7218 return EXIT_FAILURE;
7220 if (waitpid(pid, &status, 0) == pid) {
7221 if (WIFSIGNALED(status))
7222 ret = 128 + WTERMSIG(status);
7223 else if (WIFEXITED(status))
7224 ret = WEXITSTATUS(status);
7228 bb_perror_msg("wait %s", *argv);
7237 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7238 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7241 def = bb_strtou(argv[1], NULL, 10);
7242 if (errno || def < def_min || argv[2]) {
7243 bb_error_msg("%s: bad arguments", argv[0]);
7251 #if ENABLE_HUSH_LOOPS
7252 static int builtin_break(char **argv)
7255 if (G.depth_of_loop == 0) {
7256 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7257 return EXIT_SUCCESS; /* bash compat */
7259 G.flag_break_continue++; /* BC_BREAK = 1 */
7261 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7262 if (depth == UINT_MAX)
7263 G.flag_break_continue = BC_BREAK;
7264 if (G.depth_of_loop < depth)
7265 G.depth_break_continue = G.depth_of_loop;
7267 return EXIT_SUCCESS;
7270 static int builtin_continue(char **argv)
7272 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7273 return builtin_break(argv);
7277 #if ENABLE_HUSH_FUNCTIONS
7278 static int builtin_return(char **argv)
7282 if (G.flag_return_in_progress != -1) {
7283 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7284 return EXIT_FAILURE; /* bash compat */
7287 G.flag_return_in_progress = 1;
7290 * out of range: wraps around at 256, does not error out
7291 * non-numeric param:
7292 * f() { false; return qwe; }; f; echo $?
7293 * bash: return: qwe: numeric argument required <== we do this
7294 * 255 <== we also do this
7296 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);