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 (optionally enabled):
46 * &> and >& redirection of stdout+stderr
48 * reserved words: [[ ]] function select
49 * substrings ${var:1:5}
51 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
52 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
53 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
55 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
56 * This is exactly equivalent to let "expression".
59 * grep for "TODO" and fix (some of them are easy)
61 * special variables (done: PWD)
62 * follow IFS rules more precisely, including update semantics
63 * export builtin should be special, its arguments are assignments
64 * and therefore expansion of them should be "one-word" expansion:
65 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
67 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
68 * ls: cannot access i=a: No such file or directory
69 * ls: cannot access b: No such file or directory
70 * Note1: same applies to local builtin.
71 * Note2: bash 3.2.33(1) does this only if export word itself
73 * $ export i=`echo 'aaa bbb'`; echo "$i"
75 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
78 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
80 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
81 #include <malloc.h> /* for malloc_trim */
83 /* #include <dmalloc.h> */
90 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
95 #define LEAK_HUNTING 0
96 #define BUILD_AS_NOMMU 0
97 /* Enable/disable sanity checks. Ok to enable in production,
98 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
99 * Keeping 1 for now even in released versions.
102 /* Slightly bigger (+200 bytes), but faster hush.
103 * So far it only enables a trick with counting SIGCHLDs and forks,
104 * which allows us to do fewer waitpid's.
105 * (we can detect a case where neither forks were done nor SIGCHLDs happened
106 * and therefore waitpid will return the same result as last time)
108 #define ENABLE_HUSH_FAST 0
113 # undef USE_FOR_NOMMU
116 # define USE_FOR_NOMMU(...) __VA_ARGS__
117 # define USE_FOR_MMU(...)
120 #if defined SINGLE_APPLET_MAIN
121 /* STANDALONE does not make sense, and won't compile */
122 # undef CONFIG_FEATURE_SH_STANDALONE
123 # undef ENABLE_FEATURE_SH_STANDALONE
124 # undef IF_FEATURE_SH_STANDALONE
125 # define IF_FEATURE_SH_STANDALONE(...)
126 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
127 # define ENABLE_FEATURE_SH_STANDALONE 0
130 #if !ENABLE_HUSH_INTERACTIVE
131 # undef ENABLE_FEATURE_EDITING
132 # define ENABLE_FEATURE_EDITING 0
133 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
134 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
137 /* Do we support ANY keywords? */
138 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
139 # define HAS_KEYWORDS 1
140 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
141 # define IF_HAS_NO_KEYWORDS(...)
143 # define HAS_KEYWORDS 0
144 # define IF_HAS_KEYWORDS(...)
145 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
148 /* If you comment out one of these below, it will be #defined later
149 * to perform debug printfs to stderr: */
150 #define debug_printf(...) do {} while (0)
151 /* Finer-grained debug switches */
152 #define debug_printf_parse(...) do {} while (0)
153 #define debug_print_tree(a, b) do {} while (0)
154 #define debug_printf_exec(...) do {} while (0)
155 #define debug_printf_env(...) do {} while (0)
156 #define debug_printf_jobs(...) do {} while (0)
157 #define debug_printf_expand(...) do {} while (0)
158 #define debug_printf_glob(...) do {} while (0)
159 #define debug_printf_list(...) do {} while (0)
160 #define debug_printf_subst(...) do {} while (0)
161 #define debug_printf_clean(...) do {} while (0)
163 #define ERR_PTR ((void*)(long)1)
165 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
167 #define SPECIAL_VAR_SYMBOL 3
171 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
173 /* This supports saving pointers malloced in vfork child,
174 * to be freed in the parent.
177 typedef struct nommu_save_t {
179 struct variable *old_vars;
181 char **argv_from_re_execing;
185 typedef enum reserved_style {
194 #if ENABLE_HUSH_LOOPS
201 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
206 /* three pseudo-keywords support contrived "case" syntax: */
207 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
208 RES_MATCH , /* "word)" */
209 RES_CASE_BODY, /* "this command is inside CASE" */
216 typedef struct o_string {
218 int length; /* position where data is appended */
220 /* Protect newly added chars against globbing
221 * (by prepending \ to *, ?, [, \) */
224 /* At least some part of the string was inside '' or "",
225 * possibly empty one: word"", wo''rd etc. */
227 smallint has_empty_slot;
228 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
231 MAYBE_ASSIGNMENT = 0,
232 DEFINITELY_ASSIGNMENT = 1,
234 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
236 /* Used for initialization: o_string foo = NULL_O_STRING; */
237 #define NULL_O_STRING { NULL }
239 /* I can almost use ordinary FILE*. Is open_memstream() universally
240 * available? Where is it documented? */
241 typedef struct in_str {
243 /* eof_flag=1: last char in ->p is really an EOF */
244 char eof_flag; /* meaningless if ->p == NULL */
246 #if ENABLE_HUSH_INTERACTIVE
248 smallint promptmode; /* 0: PS1, 1: PS2 */
251 int (*get) (struct in_str *) FAST_FUNC;
252 int (*peek) (struct in_str *) FAST_FUNC;
254 #define i_getch(input) ((input)->get(input))
255 #define i_peek(input) ((input)->peek(input))
257 /* The descrip member of this structure is only used to make
258 * debugging output pretty */
259 static const struct {
261 signed char default_fd;
264 { O_RDONLY, 0, "<" },
265 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
266 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
267 { O_CREAT|O_RDWR, 1, "<>" },
268 { O_RDONLY, 0, "<<" },
269 /* Should not be needed. Bogus default_fd helps in debugging */
270 /* { O_RDONLY, 77, "<<" }, */
273 struct redir_struct {
274 struct redir_struct *next;
275 char *rd_filename; /* filename */
276 int rd_fd; /* fd to redirect */
277 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
279 smallint rd_type; /* (enum redir_type) */
280 /* note: for heredocs, rd_filename contains heredoc delimiter,
281 * and subsequently heredoc itself; and rd_dup is a bitmask:
282 * bit 0: do we need to trim leading tabs?
283 * bit 1: is heredoc quoted (<<'delim' syntax) ?
286 typedef enum redir_type {
288 REDIRECT_OVERWRITE = 1,
291 REDIRECT_HEREDOC = 4,
292 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
295 REDIRFD_SYNTAX_ERR = -2,
296 REDIRFD_TO_FILE = -1,
297 /* otherwise, rd_fd is redirected to rd_dup */
299 HEREDOC_SKIPTABS = 1,
305 pid_t pid; /* 0 if exited */
306 int assignment_cnt; /* how many argv[i] are assignments? */
307 smallint is_stopped; /* is the command currently running? */
308 smallint cmd_type; /* CMD_xxx */
310 #define CMD_SUBSHELL 1
312 /* used for "[[ EXPR ]]" */
313 #if ENABLE_HUSH_BASH_COMPAT
314 # define CMD_SINGLEWORD_NOGLOB 2
317 /* used for "export noglob=* glob* a=`echo a b`" */
318 //#define CMD_SINGLEWORD_NOGLOB_COND 3
319 // It is hard to implement correctly, it adds significant amounts of tricky code,
320 // and all this is only useful for really obscure export statements
321 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
322 // guards the code which implements it, but I have doubts it works
323 // in all cases (especially with mixed globbed/non-globbed arguments)
325 #if ENABLE_HUSH_FUNCTIONS
326 # define CMD_FUNCDEF 3
329 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
332 char *group_as_string;
334 #if ENABLE_HUSH_FUNCTIONS
335 struct function *child_func;
336 /* This field is used to prevent a bug here:
337 * while...do f1() {a;}; f1; f1() {b;}; f1; done
338 * When we execute "f1() {a;}" cmd, we create new function and clear
339 * cmd->group, cmd->group_as_string, cmd->argv[0].
340 * When we execute "f1() {b;}", we notice that f1 exists,
341 * and that its "parent cmd" struct is still "alive",
342 * we put those fields back into cmd->xxx
343 * (struct function has ->parent_cmd ptr to facilitate that).
344 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
345 * Without this trick, loop would execute a;b;b;b;...
346 * instead of correct sequence a;b;a;b;...
347 * When command is freed, it severs the link
348 * (sets ->child_func->parent_cmd to NULL).
351 char **argv; /* command name and arguments */
352 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
353 * and on execution these are substituted with their values.
354 * Substitution can make _several_ words out of one argv[n]!
355 * Example: argv[0]=='.^C*^C.' here: echo .$*.
356 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
358 struct redir_struct *redirects; /* I/O redirections */
360 /* Is there anything in this command at all? */
361 #define IS_NULL_CMD(cmd) \
362 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
367 int num_cmds; /* total number of commands in pipe */
368 int alive_cmds; /* number of commands running (not exited) */
369 int stopped_cmds; /* number of commands alive, but stopped */
371 int jobid; /* job number */
372 pid_t pgrp; /* process group ID for the job */
373 char *cmdtext; /* name of job */
375 struct command *cmds; /* array of commands in pipe */
376 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
377 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
378 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
380 typedef enum pipe_style {
386 /* Is there anything in this pipe at all? */
387 #define IS_NULL_PIPE(pi) \
388 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
390 /* This holds pointers to the various results of parsing */
391 struct parse_context {
392 /* linked list of pipes */
393 struct pipe *list_head;
394 /* last pipe (being constructed right now) */
396 /* last command in pipe (being constructed right now) */
397 struct command *command;
398 /* last redirect in command->redirects list */
399 struct redir_struct *pending_redirect;
405 smallint ctx_inverted; /* "! cmd | cmd" */
407 smallint ctx_dsemicolon; /* ";;" seen */
409 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
411 /* group we are enclosed in:
412 * example: "if pipe1; pipe2; then pipe3; fi"
413 * when we see "if" or "then", we malloc and copy current context,
414 * and make ->stack point to it. then we parse pipeN.
415 * when closing "then" / fi" / whatever is found,
416 * we move list_head into ->stack->command->group,
417 * copy ->stack into current context, and delete ->stack.
418 * (parsing of { list } and ( list ) doesn't use this method)
420 struct parse_context *stack;
424 /* On program start, environ points to initial environment.
425 * putenv adds new pointers into it, unsetenv removes them.
426 * Neither of these (de)allocates the strings.
427 * setenv allocates new strings in malloc space and does putenv,
428 * and thus setenv is unusable (leaky) for shell's purposes */
429 #define setenv(...) setenv_is_leaky_dont_use()
431 struct variable *next;
432 char *varstr; /* points to "name=" portion */
433 #if ENABLE_HUSH_LOCAL
434 unsigned func_nest_level;
436 int max_len; /* if > 0, name is part of initial env; else name is malloced */
437 smallint flg_export; /* putenv should be done on this var */
438 smallint flg_read_only;
446 #if ENABLE_HUSH_FUNCTIONS
448 struct function *next;
450 struct command *parent_cmd;
453 char *body_as_string;
459 /* "Globals" within this file */
460 /* Sorted roughly by size (smaller offsets == smaller code) */
462 /* interactive_fd != 0 means we are an interactive shell.
463 * If we are, then saved_tty_pgrp can also be != 0, meaning
464 * that controlling tty is available. With saved_tty_pgrp == 0,
465 * job control still works, but terminal signals
466 * (^C, ^Z, ^Y, ^\) won't work at all, and background
467 * process groups can only be created with "cmd &".
468 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
469 * to give tty to the foreground process group,
470 * and will take it back when the group is stopped (^Z)
473 #if ENABLE_HUSH_INTERACTIVE
474 /* 'interactive_fd' is a fd# open to ctty, if we have one
475 * _AND_ if we decided to act interactively */
479 # define G_interactive_fd (G.interactive_fd)
481 # define G_interactive_fd 0
483 #if ENABLE_FEATURE_EDITING
484 line_input_t *line_input_state;
492 pid_t saved_tty_pgrp;
493 struct pipe *job_list;
494 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
496 # define G_saved_tty_pgrp 0
498 smallint flag_SIGINT;
499 #if ENABLE_HUSH_LOOPS
500 smallint flag_break_continue;
502 #if ENABLE_HUSH_FUNCTIONS
503 /* 0: outside of a function (or sourced file)
504 * -1: inside of a function, ok to use return builtin
505 * 1: return is invoked, skip all till end of func
507 smallint flag_return_in_progress;
510 smallint exiting; /* used to prevent EXIT trap recursion */
511 /* These four support $?, $#, and $1 */
512 smalluint last_exitcode;
513 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
514 smalluint global_args_malloced;
515 /* how many non-NULL argv's we have. NB: $# + 1 */
519 char *argv0_for_re_execing;
521 #if ENABLE_HUSH_LOOPS
522 unsigned depth_break_continue;
523 unsigned depth_of_loop;
527 struct variable *top_var; /* = &G.shell_ver (set in main()) */
528 struct variable shell_ver;
529 #if ENABLE_HUSH_FUNCTIONS
530 struct function *top_func;
531 # if ENABLE_HUSH_LOCAL
532 struct variable **shadowed_vars_pp;
533 unsigned func_nest_level;
536 /* Signal and trap handling */
538 unsigned count_SIGCHLD;
539 unsigned handled_SIGCHLD;
540 smallint we_have_children;
542 /* which signals have non-DFL handler (even with no traps set)? */
543 unsigned non_DFL_mask;
544 char **traps; /* char *traps[NSIG] */
545 sigset_t blocked_set;
546 sigset_t inherited_set;
548 unsigned long memleak_value;
551 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
553 #define G (*ptr_to_globals)
554 /* Not #defining name to G.name - this quickly gets unwieldy
555 * (too many defines). Also, I actually prefer to see when a variable
556 * is global, thus "G." prefix is a useful hint */
557 #define INIT_G() do { \
558 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
562 /* Function prototypes for builtins */
563 static int builtin_cd(char **argv) FAST_FUNC;
564 static int builtin_echo(char **argv) FAST_FUNC;
565 static int builtin_eval(char **argv) FAST_FUNC;
566 static int builtin_exec(char **argv) FAST_FUNC;
567 static int builtin_exit(char **argv) FAST_FUNC;
568 static int builtin_export(char **argv) FAST_FUNC;
570 static int builtin_fg_bg(char **argv) FAST_FUNC;
571 static int builtin_jobs(char **argv) FAST_FUNC;
574 static int builtin_help(char **argv) FAST_FUNC;
576 #if ENABLE_HUSH_LOCAL
577 static int builtin_local(char **argv) FAST_FUNC;
580 static int builtin_memleak(char **argv) FAST_FUNC;
582 static int builtin_pwd(char **argv) FAST_FUNC;
583 static int builtin_read(char **argv) FAST_FUNC;
584 static int builtin_set(char **argv) FAST_FUNC;
585 static int builtin_shift(char **argv) FAST_FUNC;
586 static int builtin_source(char **argv) FAST_FUNC;
587 static int builtin_test(char **argv) FAST_FUNC;
588 static int builtin_trap(char **argv) FAST_FUNC;
589 static int builtin_type(char **argv) FAST_FUNC;
590 static int builtin_true(char **argv) FAST_FUNC;
591 static int builtin_umask(char **argv) FAST_FUNC;
592 static int builtin_unset(char **argv) FAST_FUNC;
593 static int builtin_wait(char **argv) FAST_FUNC;
594 #if ENABLE_HUSH_LOOPS
595 static int builtin_break(char **argv) FAST_FUNC;
596 static int builtin_continue(char **argv) FAST_FUNC;
598 #if ENABLE_HUSH_FUNCTIONS
599 static int builtin_return(char **argv) FAST_FUNC;
602 /* Table of built-in functions. They can be forked or not, depending on
603 * context: within pipes, they fork. As simple commands, they do not.
604 * When used in non-forking context, they can change global variables
605 * in the parent shell process. If forked, of course they cannot.
606 * For example, 'unset foo | whatever' will parse and run, but foo will
607 * still be set at the end. */
608 struct built_in_command {
610 int (*function)(char **argv) FAST_FUNC;
613 # define BLTIN(cmd, func, help) { cmd, func, help }
615 # define BLTIN(cmd, func, help) { cmd, func }
619 static const struct built_in_command bltins1[] = {
620 BLTIN("." , builtin_source , "Run commands in a file"),
621 BLTIN(":" , builtin_true , NULL),
623 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
625 #if ENABLE_HUSH_LOOPS
626 BLTIN("break" , builtin_break , "Exit from a loop"),
628 BLTIN("cd" , builtin_cd , "Change directory"),
629 #if ENABLE_HUSH_LOOPS
630 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
632 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
633 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
634 BLTIN("exit" , builtin_exit , "Exit"),
635 BLTIN("export" , builtin_export , "Set environment variables"),
637 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
640 BLTIN("help" , builtin_help , NULL),
643 BLTIN("jobs" , builtin_jobs , "List jobs"),
645 #if ENABLE_HUSH_LOCAL
646 BLTIN("local" , builtin_local , "Set local variables"),
649 BLTIN("memleak" , builtin_memleak , NULL),
651 BLTIN("read" , builtin_read , "Input into variable"),
652 #if ENABLE_HUSH_FUNCTIONS
653 BLTIN("return" , builtin_return , "Return from a function"),
655 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
656 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
657 BLTIN("trap" , builtin_trap , "Trap signals"),
658 BLTIN("type" , builtin_type , "Write a description of command type"),
659 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
660 BLTIN("umask" , builtin_umask , "Set file creation mask"),
661 BLTIN("unset" , builtin_unset , "Unset variables"),
662 BLTIN("wait" , builtin_wait , "Wait for process"),
664 /* For now, echo and test are unconditionally enabled.
665 * Maybe make it configurable? */
666 static const struct built_in_command bltins2[] = {
667 BLTIN("[" , builtin_test , NULL),
668 BLTIN("echo" , builtin_echo , NULL),
669 BLTIN("pwd" , builtin_pwd , NULL),
670 BLTIN("test" , builtin_test , NULL),
677 /* prevent disasters with G.debug_indent < 0 */
678 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
679 # define debug_enter() (G.debug_indent++)
680 # define debug_leave() (G.debug_indent--)
682 # define indent() ((void)0)
683 # define debug_enter() ((void)0)
684 # define debug_leave() ((void)0)
688 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
691 #ifndef debug_printf_parse
692 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
695 #ifndef debug_printf_exec
696 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
699 #ifndef debug_printf_env
700 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
703 #ifndef debug_printf_jobs
704 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
705 # define DEBUG_JOBS 1
707 # define DEBUG_JOBS 0
710 #ifndef debug_printf_expand
711 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
712 # define DEBUG_EXPAND 1
714 # define DEBUG_EXPAND 0
717 #ifndef debug_printf_glob
718 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
719 # define DEBUG_GLOB 1
721 # define DEBUG_GLOB 0
724 #ifndef debug_printf_list
725 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
728 #ifndef debug_printf_subst
729 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
732 #ifndef debug_printf_clean
733 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
734 # define DEBUG_CLEAN 1
736 # define DEBUG_CLEAN 0
740 static void debug_print_strings(const char *prefix, char **vv)
743 fprintf(stderr, "%s:\n", prefix);
745 fprintf(stderr, " '%s'\n", *vv++);
748 # define debug_print_strings(prefix, vv) ((void)0)
752 /* Leak hunting. Use hush_leaktool.sh for post-processing.
755 static void *xxmalloc(int lineno, size_t size)
757 void *ptr = xmalloc((size + 0xff) & ~0xff);
758 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
761 static void *xxrealloc(int lineno, void *ptr, size_t size)
763 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
764 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
767 static char *xxstrdup(int lineno, const char *str)
769 char *ptr = xstrdup(str);
770 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
773 static void xxfree(void *ptr)
775 fdprintf(2, "free %p\n", ptr);
778 #define xmalloc(s) xxmalloc(__LINE__, s)
779 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
780 #define xstrdup(s) xxstrdup(__LINE__, s)
781 #define free(p) xxfree(p)
785 /* Syntax and runtime errors. They always abort scripts.
786 * In interactive use they usually discard unparsed and/or unexecuted commands
787 * and return to the prompt.
788 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
791 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
792 # define syntax_error(lineno, msg) syntax_error(msg)
793 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
794 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
795 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
796 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
799 static void die_if_script(unsigned lineno, const char *fmt, ...)
804 bb_error_msg("hush.c:%u", lineno);
807 bb_verror_msg(fmt, p, NULL);
809 if (!G_interactive_fd)
813 static void syntax_error(unsigned lineno, const char *msg)
816 die_if_script(lineno, "syntax error: %s", msg);
818 die_if_script(lineno, "syntax error", NULL);
821 static void syntax_error_at(unsigned lineno, const char *msg)
823 die_if_script(lineno, "syntax error at '%s'", msg);
826 static void syntax_error_unterm_str(unsigned lineno, const char *s)
828 die_if_script(lineno, "syntax error: unterminated %s", s);
831 /* It so happens that all such cases are totally fatal
832 * even if shell is interactive: EOF while looking for closing
833 * delimiter. There is nowhere to read stuff from after that,
834 * it's EOF! The only choice is to terminate.
836 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
837 static void syntax_error_unterm_ch(unsigned lineno, char ch)
839 char msg[2] = { ch, '\0' };
840 syntax_error_unterm_str(lineno, msg);
844 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
849 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
853 # undef die_if_script
855 # undef syntax_error_at
856 # undef syntax_error_unterm_ch
857 # undef syntax_error_unterm_str
858 # undef syntax_error_unexpected_ch
860 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
861 # define syntax_error(msg) syntax_error(__LINE__, msg)
862 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
863 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
864 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
865 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
869 #if ENABLE_HUSH_INTERACTIVE
870 static void cmdedit_update_prompt(void);
872 # define cmdedit_update_prompt() ((void)0)
878 static int glob_needed(const char *s)
883 if (*s == '*' || *s == '[' || *s == '?')
890 static int is_well_formed_var_name(const char *s, char terminator)
892 if (!s || !(isalpha(*s) || *s == '_'))
895 while (isalnum(*s) || *s == '_')
897 return *s == terminator;
900 /* Replace each \x with x in place, return ptr past NUL. */
901 static char *unbackslash(char *src)
903 char *dst = src = strchrnul(src, '\\');
907 if ((*dst++ = *src++) == '\0')
913 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
934 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
935 v[count1 + count2] = NULL;
938 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
942 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
944 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
945 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
948 #define add_strings_to_strings(strings, add, need_to_dup) \
949 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
952 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
953 static char **add_string_to_strings(char **strings, char *add)
958 return add_strings_to_strings(strings, v, /*dup:*/ 0);
961 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
963 char **ptr = add_string_to_strings(strings, add);
964 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
967 #define add_string_to_strings(strings, add) \
968 xx_add_string_to_strings(__LINE__, strings, add)
971 static void free_strings(char **strings)
986 /* Helpers for setting new $n and restoring them back
988 typedef struct save_arg_t {
992 smallint sv_g_malloced;
995 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
999 sv->sv_argv0 = argv[0];
1000 sv->sv_g_argv = G.global_argv;
1001 sv->sv_g_argc = G.global_argc;
1002 sv->sv_g_malloced = G.global_args_malloced;
1004 argv[0] = G.global_argv[0]; /* retain $0 */
1005 G.global_argv = argv;
1006 G.global_args_malloced = 0;
1014 static void restore_G_args(save_arg_t *sv, char **argv)
1018 if (G.global_args_malloced) {
1019 /* someone ran "set -- arg1 arg2 ...", undo */
1021 while (*++pp) /* note: does not free $0 */
1023 free(G.global_argv);
1025 argv[0] = sv->sv_argv0;
1026 G.global_argv = sv->sv_g_argv;
1027 G.global_argc = sv->sv_g_argc;
1028 G.global_args_malloced = sv->sv_g_malloced;
1032 /* Basic theory of signal handling in shell
1033 * ========================================
1034 * This does not describe what hush does, rather, it is current understanding
1035 * what it _should_ do. If it doesn't, it's a bug.
1036 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1038 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1039 * is finished or backgrounded. It is the same in interactive and
1040 * non-interactive shells, and is the same regardless of whether
1041 * a user trap handler is installed or a shell special one is in effect.
1042 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1043 * backgrounds (i.e. stops) or kills all members of currently running
1046 * Wait builtin in interruptible by signals for which user trap is set
1047 * or by SIGINT in interactive shell.
1049 * Trap handlers will execute even within trap handlers. (right?)
1051 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1053 * If job control is off, backgrounded commands ("cmd &")
1054 * have SIGINT, SIGQUIT set to SIG_IGN.
1056 * Commands which are run in command substitution ("`cmd`")
1057 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1059 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1060 * by the shell from its parent.
1062 * Signals which differ from SIG_DFL action
1063 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1066 * SIGTERM (interactive): ignore
1067 * SIGHUP (interactive):
1068 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1069 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1070 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1071 * that all pipe members are stopped. Try this in bash:
1072 * while :; do :; done - ^Z does not background it
1073 * (while :; do :; done) - ^Z backgrounds it
1074 * SIGINT (interactive): wait for last pipe, ignore the rest
1075 * of the command line, show prompt. NB: ^C does not send SIGINT
1076 * to interactive shell while shell is waiting for a pipe,
1077 * since shell is bg'ed (is not in foreground process group).
1078 * Example 1: this waits 5 sec, but does not execute ls:
1079 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1080 * Example 2: this does not wait and does not execute ls:
1081 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1082 * Example 3: this does not wait 5 sec, but executes ls:
1083 * "sleep 5; ls -l" + press ^C
1085 * (What happens to signals which are IGN on shell start?)
1086 * (What happens with signal mask on shell start?)
1088 * Implementation in hush
1089 * ======================
1090 * We use in-kernel pending signal mask to determine which signals were sent.
1091 * We block all signals which we don't want to take action immediately,
1092 * i.e. we block all signals which need to have special handling as described
1093 * above, and all signals which have traps set.
1094 * After each pipe execution, we extract any pending signals via sigtimedwait()
1097 * unsigned non_DFL_mask: a mask of such "special" signals
1098 * sigset_t blocked_set: current blocked signal set
1101 * clear bit in blocked_set unless it is also in non_DFL_mask
1102 * "trap 'cmd' SIGxxx":
1103 * set bit in blocked_set (even if 'cmd' is '')
1104 * after [v]fork, if we plan to be a shell:
1105 * unblock signals with special interactive handling
1106 * (child shell is not interactive),
1107 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1108 * after [v]fork, if we plan to exec:
1109 * POSIX says fork clears pending signal mask in child - no need to clear it.
1110 * Restore blocked signal set to one inherited by shell just prior to exec.
1112 * Note: as a result, we do not use signal handlers much. The only uses
1113 * are to count SIGCHLDs
1114 * and to restore tty pgrp on signal-induced exit.
1117 * Standard says "When a subshell is entered, traps that are not being ignored
1118 * are set to the default actions". bash interprets it so that traps which
1119 * are set to "" (ignore) are NOT reset to defaults. We do the same.
1122 SPECIAL_INTERACTIVE_SIGS = 0
1127 SPECIAL_JOB_SIGS = 0
1135 #if ENABLE_HUSH_FAST
1136 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1139 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1145 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1146 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1147 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1148 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1150 /* Restores tty foreground process group, and exits.
1151 * May be called as signal handler for fatal signal
1152 * (will resend signal to itself, producing correct exit state)
1153 * or called directly with -EXITCODE.
1154 * We also call it if xfunc is exiting. */
1155 static void sigexit(int sig) NORETURN;
1156 static void sigexit(int sig)
1158 /* Disable all signals: job control, SIGPIPE, etc. */
1159 sigprocmask_allsigs(SIG_BLOCK);
1161 /* Careful: we can end up here after [v]fork. Do not restore
1162 * tty pgrp then, only top-level shell process does that */
1163 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1164 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1166 /* Not a signal, just exit */
1170 kill_myself_with_sig(sig); /* does not return */
1174 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1175 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1179 /* Restores tty foreground process group, and exits. */
1180 static void hush_exit(int exitcode) NORETURN;
1181 static void hush_exit(int exitcode)
1183 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1184 /* Prevent recursion:
1185 * trap "echo Hi; exit" EXIT; exit
1187 char *argv[] = { NULL, G.traps[0], NULL };
1195 fflush(NULL); /* flush all streams */
1196 sigexit(- (exitcode & 0xff));
1202 static int check_and_run_traps(int sig)
1204 static const struct timespec zero_timespec = { 0, 0 };
1205 smalluint save_rcode;
1211 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1216 if (G.traps && G.traps[sig]) {
1217 if (G.traps[sig][0]) {
1218 /* We have user-defined handler */
1219 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1220 save_rcode = G.last_exitcode;
1223 G.last_exitcode = save_rcode;
1224 } /* else: "" trap, ignoring signal */
1227 /* not a trap: special action */
1229 #if ENABLE_HUSH_FAST
1232 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1236 /* Builtin was ^C'ed, make it look prettier: */
1243 /* bash is observed to signal whole process groups,
1244 * not individual processes */
1245 for (job = G.job_list; job; job = job->next) {
1248 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1249 if (kill(- job->pgrp, SIGHUP) == 0)
1250 kill(- job->pgrp, SIGCONT);
1255 default: /* ignored: */
1256 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1264 static const char *get_cwd(int force)
1266 if (force || G.cwd == NULL) {
1267 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1268 * we must not try to free(bb_msg_unknown) */
1269 if (G.cwd == bb_msg_unknown)
1271 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1273 G.cwd = bb_msg_unknown;
1280 * Shell and environment variable support
1282 static struct variable **get_ptr_to_local_var(const char *name)
1284 struct variable **pp;
1285 struct variable *cur;
1290 while ((cur = *pp) != NULL) {
1291 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1298 static struct variable *get_local_var(const char *name)
1300 struct variable **pp = get_ptr_to_local_var(name);
1306 static const char *get_local_var_value(const char *name)
1308 struct variable **pp = get_ptr_to_local_var(name);
1310 return strchr((*pp)->varstr, '=') + 1;
1311 if (strcmp(name, "PPID") == 0)
1312 return utoa(G.root_ppid);
1313 // bash compat: UID? EUID?
1317 /* str holds "NAME=VAL" and is expected to be malloced.
1318 * We take ownership of it.
1320 * 0: do not change export flag
1321 * (if creating new variable, flag will be 0)
1322 * 1: set export flag and putenv the variable
1323 * -1: clear export flag and unsetenv the variable
1324 * flg_read_only is set only when we handle -R var=val
1326 #if !BB_MMU && ENABLE_HUSH_LOCAL
1327 /* all params are used */
1328 #elif BB_MMU && ENABLE_HUSH_LOCAL
1329 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1330 set_local_var(str, flg_export, local_lvl)
1331 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1332 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1333 set_local_var(str, flg_export)
1334 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1335 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1336 set_local_var(str, flg_export, flg_read_only)
1338 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1340 struct variable **var_pp;
1341 struct variable *cur;
1345 eq_sign = strchr(str, '=');
1346 if (!eq_sign) { /* not expected to ever happen? */
1351 name_len = eq_sign - str + 1; /* including '=' */
1352 var_pp = &G.top_var;
1353 while ((cur = *var_pp) != NULL) {
1354 if (strncmp(cur->varstr, str, name_len) != 0) {
1355 var_pp = &cur->next;
1358 /* We found an existing var with this name */
1359 if (cur->flg_read_only) {
1363 bb_error_msg("%s: readonly variable", str);
1367 if (flg_export == -1) { // "&& cur->flg_export" ?
1368 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1373 #if ENABLE_HUSH_LOCAL
1374 if (cur->func_nest_level < local_lvl) {
1375 /* New variable is declared as local,
1376 * and existing one is global, or local
1377 * from enclosing function.
1378 * Remove and save old one: */
1379 *var_pp = cur->next;
1380 cur->next = *G.shadowed_vars_pp;
1381 *G.shadowed_vars_pp = cur;
1382 /* bash 3.2.33(1) and exported vars:
1384 * # f() { local z=a; env | grep ^z; }
1390 if (cur->flg_export)
1395 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1400 if (cur->max_len != 0) {
1401 if (cur->max_len >= strlen(str)) {
1402 /* This one is from startup env, reuse space */
1403 strcpy(cur->varstr, str);
1407 /* max_len == 0 signifies "malloced" var, which we can
1408 * (and has to) free */
1412 goto set_str_and_exp;
1415 /* Not found - create new variable struct */
1416 cur = xzalloc(sizeof(*cur));
1417 #if ENABLE_HUSH_LOCAL
1418 cur->func_nest_level = local_lvl;
1420 cur->next = *var_pp;
1426 cur->flg_read_only = flg_read_only;
1429 if (flg_export == 1)
1430 cur->flg_export = 1;
1431 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1432 cmdedit_update_prompt();
1433 if (cur->flg_export) {
1434 if (flg_export == -1) {
1435 cur->flg_export = 0;
1436 /* unsetenv was already done */
1438 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1439 return putenv(cur->varstr);
1445 /* Used at startup and after each cd */
1446 static void set_pwd_var(int exp)
1448 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1449 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1452 static int unset_local_var_len(const char *name, int name_len)
1454 struct variable *cur;
1455 struct variable **var_pp;
1458 return EXIT_SUCCESS;
1459 var_pp = &G.top_var;
1460 while ((cur = *var_pp) != NULL) {
1461 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1462 if (cur->flg_read_only) {
1463 bb_error_msg("%s: readonly variable", name);
1464 return EXIT_FAILURE;
1466 *var_pp = cur->next;
1467 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1468 bb_unsetenv(cur->varstr);
1469 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1470 cmdedit_update_prompt();
1474 return EXIT_SUCCESS;
1476 var_pp = &cur->next;
1478 return EXIT_SUCCESS;
1481 static int unset_local_var(const char *name)
1483 return unset_local_var_len(name, strlen(name));
1486 static void unset_vars(char **strings)
1494 const char *eq = strchrnul(*v, '=');
1495 unset_local_var_len(*v, (int)(eq - *v));
1501 #if ENABLE_SH_MATH_SUPPORT
1502 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1503 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1504 static char *endofname(const char *name)
1512 if (!is_in_name(*p))
1518 static void arith_set_local_var(const char *name, const char *val, int flags)
1520 /* arith code doesnt malloc space, so do it for it */
1521 char *var = xasprintf("%s=%s", name, val);
1522 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1528 * Helpers for "var1=val1 var2=val2 cmd" feature
1530 static void add_vars(struct variable *var)
1532 struct variable *next;
1536 var->next = G.top_var;
1538 if (var->flg_export) {
1539 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1540 putenv(var->varstr);
1542 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1548 static struct variable *set_vars_and_save_old(char **strings)
1551 struct variable *old = NULL;
1557 struct variable *var_p;
1558 struct variable **var_pp;
1561 eq = strchr(*s, '=');
1564 var_pp = get_ptr_to_local_var(*s);
1567 /* Remove variable from global linked list */
1569 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1570 *var_pp = var_p->next;
1571 /* Add it to returned list */
1575 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1586 static int FAST_FUNC static_get(struct in_str *i)
1595 static int FAST_FUNC static_peek(struct in_str *i)
1600 #if ENABLE_HUSH_INTERACTIVE
1602 static void cmdedit_update_prompt(void)
1604 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1605 G.PS1 = get_local_var_value("PS1");
1608 G.PS2 = get_local_var_value("PS2");
1616 static const char* setup_prompt_string(int promptmode)
1618 const char *prompt_str;
1619 debug_printf("setup_prompt_string %d ", promptmode);
1620 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1621 /* Set up the prompt */
1622 if (promptmode == 0) { /* PS1 */
1624 /* bash uses $PWD value, even if it is set by user.
1625 * It uses current dir only if PWD is unset.
1626 * We always use current dir. */
1627 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1632 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1633 debug_printf("result '%s'\n", prompt_str);
1637 static void get_user_input(struct in_str *i)
1640 const char *prompt_str;
1642 prompt_str = setup_prompt_string(i->promptmode);
1643 #if ENABLE_FEATURE_EDITING
1644 /* Enable command line editing only while a command line
1645 * is actually being read */
1648 /* buglet: SIGINT will not make new prompt to appear _at once_,
1649 * only after <Enter>. (^C will work) */
1650 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1651 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1652 check_and_run_traps(0);
1653 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1654 i->eof_flag = (r < 0);
1655 if (i->eof_flag) { /* EOF/error detected */
1656 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1657 G.user_input_buf[1] = '\0';
1662 fputs(prompt_str, stdout);
1664 G.user_input_buf[0] = r = fgetc(i->file);
1665 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1666 //do we need check_and_run_traps(0)? (maybe only if stdin)
1667 } while (G.flag_SIGINT);
1668 i->eof_flag = (r == EOF);
1670 i->p = G.user_input_buf;
1673 #endif /* INTERACTIVE */
1675 /* This is the magic location that prints prompts
1676 * and gets data back from the user */
1677 static int FAST_FUNC file_get(struct in_str *i)
1681 /* If there is data waiting, eat it up */
1682 if (i->p && *i->p) {
1683 #if ENABLE_HUSH_INTERACTIVE
1687 if (i->eof_flag && !*i->p)
1689 /* note: ch is never NUL */
1691 /* need to double check i->file because we might be doing something
1692 * more complicated by now, like sourcing or substituting. */
1693 #if ENABLE_HUSH_INTERACTIVE
1694 if (G_interactive_fd && i->promptme && i->file == stdin) {
1697 } while (!*i->p); /* need non-empty line */
1698 i->promptmode = 1; /* PS2 */
1703 do ch = fgetc(i->file); while (ch == '\0');
1705 debug_printf("file_get: got '%c' %d\n", ch, ch);
1706 #if ENABLE_HUSH_INTERACTIVE
1713 /* All callers guarantee this routine will never
1714 * be used right after a newline, so prompting is not needed.
1716 static int FAST_FUNC file_peek(struct in_str *i)
1719 if (i->p && *i->p) {
1720 if (i->eof_flag && !i->p[1])
1723 /* note: ch is never NUL */
1725 do ch = fgetc(i->file); while (ch == '\0');
1726 i->eof_flag = (ch == EOF);
1727 i->peek_buf[0] = ch;
1728 i->peek_buf[1] = '\0';
1730 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1734 static void setup_file_in_str(struct in_str *i, FILE *f)
1736 i->peek = file_peek;
1738 #if ENABLE_HUSH_INTERACTIVE
1740 i->promptmode = 0; /* PS1 */
1746 static void setup_string_in_str(struct in_str *i, const char *s)
1748 i->peek = static_peek;
1749 i->get = static_get;
1750 #if ENABLE_HUSH_INTERACTIVE
1752 i->promptmode = 0; /* PS1 */
1762 #define B_CHUNK (32 * sizeof(char*))
1764 static void o_reset_to_empty_unquoted(o_string *o)
1772 static void o_free(o_string *o)
1775 memset(o, 0, sizeof(*o));
1778 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1783 static void o_grow_by(o_string *o, int len)
1785 if (o->length + len > o->maxlen) {
1786 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1787 o->data = xrealloc(o->data, 1 + o->maxlen);
1791 static void o_addchr(o_string *o, int ch)
1793 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1795 o->data[o->length] = ch;
1797 o->data[o->length] = '\0';
1800 static void o_addblock(o_string *o, const char *str, int len)
1803 memcpy(&o->data[o->length], str, len);
1805 o->data[o->length] = '\0';
1809 static void o_addstr(o_string *o, const char *str)
1811 o_addblock(o, str, strlen(str));
1813 static void nommu_addchr(o_string *o, int ch)
1819 # define nommu_addchr(o, str) ((void)0)
1822 static void o_addstr_with_NUL(o_string *o, const char *str)
1824 o_addblock(o, str, strlen(str) + 1);
1827 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1832 && (*str != '*' && *str != '?' && *str != '[')
1840 /* My analysis of quoting semantics tells me that state information
1841 * is associated with a destination, not a source.
1843 static void o_addqchr(o_string *o, int ch)
1846 char *found = strchr("*?[\\", ch);
1851 o->data[o->length] = '\\';
1854 o->data[o->length] = ch;
1856 o->data[o->length] = '\0';
1859 static void o_addQchr(o_string *o, int ch)
1862 if (o->o_escape && strchr("*?[\\", ch)) {
1864 o->data[o->length] = '\\';
1868 o->data[o->length] = ch;
1870 o->data[o->length] = '\0';
1873 static void o_addQstr(o_string *o, const char *str, int len)
1876 o_addblock(o, str, len);
1882 int ordinary_cnt = strcspn(str, "*?[\\");
1883 if (ordinary_cnt > len) /* paranoia */
1885 o_addblock(o, str, ordinary_cnt);
1886 if (ordinary_cnt == len)
1888 str += ordinary_cnt;
1889 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1893 if (ch) { /* it is necessarily one of "*?[\\" */
1895 o->data[o->length] = '\\';
1899 o->data[o->length] = ch;
1901 o->data[o->length] = '\0';
1905 /* A special kind of o_string for $VAR and `cmd` expansion.
1906 * It contains char* list[] at the beginning, which is grown in 16 element
1907 * increments. Actual string data starts at the next multiple of 16 * (char*).
1908 * list[i] contains an INDEX (int!) into this string data.
1909 * It means that if list[] needs to grow, data needs to be moved higher up
1910 * but list[i]'s need not be modified.
1911 * NB: remembering how many list[i]'s you have there is crucial.
1912 * o_finalize_list() operation post-processes this structure - calculates
1913 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1915 #if DEBUG_EXPAND || DEBUG_GLOB
1916 static void debug_print_list(const char *prefix, o_string *o, int n)
1918 char **list = (char**)o->data;
1919 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1923 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1924 prefix, list, n, string_start, o->length, o->maxlen);
1927 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1928 o->data + (int)list[i] + string_start,
1929 o->data + (int)list[i] + string_start);
1933 const char *p = o->data + (int)list[n - 1] + string_start;
1935 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1939 # define debug_print_list(prefix, o, n) ((void)0)
1942 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1943 * in list[n] so that it points past last stored byte so far.
1944 * It returns n+1. */
1945 static int o_save_ptr_helper(o_string *o, int n)
1947 char **list = (char**)o->data;
1951 if (!o->has_empty_slot) {
1952 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1953 string_len = o->length - string_start;
1954 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1955 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1956 /* list[n] points to string_start, make space for 16 more pointers */
1957 o->maxlen += 0x10 * sizeof(list[0]);
1958 o->data = xrealloc(o->data, o->maxlen + 1);
1959 list = (char**)o->data;
1960 memmove(list + n + 0x10, list + n, string_len);
1961 o->length += 0x10 * sizeof(list[0]);
1963 debug_printf_list("list[%d]=%d string_start=%d\n",
1964 n, string_len, string_start);
1967 /* We have empty slot at list[n], reuse without growth */
1968 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1969 string_len = o->length - string_start;
1970 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1971 n, string_len, string_start);
1972 o->has_empty_slot = 0;
1974 list[n] = (char*)(ptrdiff_t)string_len;
1978 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1979 static int o_get_last_ptr(o_string *o, int n)
1981 char **list = (char**)o->data;
1982 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1984 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1987 /* o_glob performs globbing on last list[], saving each result
1988 * as a new list[]. */
1989 static int o_glob(o_string *o, int n)
1995 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1997 return o_save_ptr_helper(o, n);
1998 pattern = o->data + o_get_last_ptr(o, n);
1999 debug_printf_glob("glob pattern '%s'\n", pattern);
2000 if (!glob_needed(pattern)) {
2002 o->length = unbackslash(pattern) - o->data;
2003 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2004 return o_save_ptr_helper(o, n);
2007 memset(&globdata, 0, sizeof(globdata));
2008 gr = glob(pattern, 0, NULL, &globdata);
2009 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2010 if (gr == GLOB_NOSPACE)
2011 bb_error_msg_and_die("out of memory during glob");
2012 if (gr == GLOB_NOMATCH) {
2013 globfree(&globdata);
2016 if (gr != 0) { /* GLOB_ABORTED ? */
2017 /* TODO: testcase for bad glob pattern behavior */
2018 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2020 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2021 char **argv = globdata.gl_pathv;
2022 o->length = pattern - o->data; /* "forget" pattern */
2024 o_addstr_with_NUL(o, *argv);
2025 n = o_save_ptr_helper(o, n);
2031 globfree(&globdata);
2033 debug_print_list("o_glob returning", o, n);
2037 /* If o->o_glob == 1, glob the string so far remembered.
2038 * Otherwise, just finish current list[] and start new */
2039 static int o_save_ptr(o_string *o, int n)
2041 if (o->o_glob) { /* if globbing is requested */
2042 /* If o->has_empty_slot, list[n] was already globbed
2043 * (if it was requested back then when it was filled)
2044 * so don't do that again! */
2045 if (!o->has_empty_slot)
2046 return o_glob(o, n); /* o_save_ptr_helper is inside */
2048 return o_save_ptr_helper(o, n);
2051 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2052 static char **o_finalize_list(o_string *o, int n)
2057 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2059 debug_print_list("finalized", o, n);
2060 debug_printf_expand("finalized n:%d\n", n);
2061 list = (char**)o->data;
2062 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2066 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2072 /* Expansion can recurse */
2073 #if ENABLE_HUSH_TICK
2074 static int process_command_subs(o_string *dest, const char *s);
2076 static char *expand_string_to_string(const char *str);
2078 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2079 parse_stream_dquoted(dest, input, dquote_end)
2081 static int parse_stream_dquoted(o_string *as_string,
2083 struct in_str *input,
2086 /* expand_strvec_to_strvec() takes a list of strings, expands
2087 * all variable references within and returns a pointer to
2088 * a list of expanded strings, possibly with larger number
2089 * of strings. (Think VAR="a b"; echo $VAR).
2090 * This new list is allocated as a single malloc block.
2091 * NULL-terminated list of char* pointers is at the beginning of it,
2092 * followed by strings themself.
2093 * Caller can deallocate entire list by single free(list). */
2095 /* Store given string, finalizing the word and starting new one whenever
2096 * we encounter IFS char(s). This is used for expanding variable values.
2097 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2098 static int expand_on_ifs(o_string *output, int n, const char *str)
2101 int word_len = strcspn(str, G.ifs);
2103 if (output->o_escape || !output->o_glob)
2104 o_addQstr(output, str, word_len);
2105 else /* protect backslashes against globbing up :) */
2106 o_addblock_duplicate_backslash(output, str, word_len);
2109 if (!*str) /* EOL - do not finalize word */
2111 o_addchr(output, '\0');
2112 debug_print_list("expand_on_ifs", output, n);
2113 n = o_save_ptr(output, n);
2114 str += strspn(str, G.ifs); /* skip ifs chars */
2116 debug_print_list("expand_on_ifs[1]", output, n);
2120 /* Helper to expand $((...)) and heredoc body. These act as if
2121 * they are in double quotes, with the exception that they are not :).
2122 * Just the rules are similar: "expand only $var and `cmd`"
2124 * Returns malloced string.
2125 * As an optimization, we return NULL if expansion is not needed.
2127 static char *expand_pseudo_dquoted(const char *str)
2130 struct in_str input;
2131 o_string dest = NULL_O_STRING;
2133 if (strchr(str, '$') == NULL
2134 #if ENABLE_HUSH_TICK
2135 && strchr(str, '`') == NULL
2141 /* We need to expand. Example:
2142 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2144 setup_string_in_str(&input, str);
2145 parse_stream_dquoted(NULL, &dest, &input, EOF);
2146 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2147 exp_str = expand_string_to_string(dest.data);
2148 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2149 o_free_unsafe(&dest);
2153 /* Expand all variable references in given string, adding words to list[]
2154 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2155 * to be filled). This routine is extremely tricky: has to deal with
2156 * variables/parameters with whitespace, $* and $@, and constructs like
2157 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2158 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2160 /* or_mask is either 0 (normal case) or 0x80 -
2161 * expansion of right-hand side of assignment == 1-element expand.
2162 * It will also do no globbing, and thus we must not backslash-quote!
2169 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2170 debug_print_list("expand_vars_to_list", output, n);
2171 n = o_save_ptr(output, n);
2172 debug_print_list("expand_vars_to_list[0]", output, n);
2174 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2177 char *dyn_val = NULL;
2178 const char *val = NULL;
2179 #if ENABLE_HUSH_TICK
2180 o_string subst_result = NULL_O_STRING;
2182 #if ENABLE_SH_MATH_SUPPORT
2183 char arith_buf[sizeof(arith_t)*3 + 2];
2185 o_addblock(output, arg, p - arg);
2186 debug_print_list("expand_vars_to_list[1]", output, n);
2188 p = strchr(p, SPECIAL_VAR_SYMBOL);
2190 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2191 /* "$@" is special. Even if quoted, it can still
2192 * expand to nothing (not even an empty string) */
2193 if ((first_ch & 0x7f) != '@')
2194 ored_ch |= first_ch;
2196 switch (first_ch & 0x7f) {
2197 /* Highest bit in first_ch indicates that var is double-quoted */
2199 val = utoa(G.root_pid);
2201 case '!': /* bg pid */
2202 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2204 case '?': /* exitcode */
2205 val = utoa(G.last_exitcode);
2207 case '#': /* argc */
2208 if (arg[1] != SPECIAL_VAR_SYMBOL)
2209 /* actually, it's a ${#var} */
2211 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2216 if (!G.global_argv[i])
2218 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2219 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2220 smallint sv = output->o_escape;
2221 /* unquoted var's contents should be globbed, so don't escape */
2222 output->o_escape = 0;
2223 while (G.global_argv[i]) {
2224 n = expand_on_ifs(output, n, G.global_argv[i]);
2225 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2226 if (G.global_argv[i++][0] && G.global_argv[i]) {
2227 /* this argv[] is not empty and not last:
2228 * put terminating NUL, start new word */
2229 o_addchr(output, '\0');
2230 debug_print_list("expand_vars_to_list[2]", output, n);
2231 n = o_save_ptr(output, n);
2232 debug_print_list("expand_vars_to_list[3]", output, n);
2235 output->o_escape = sv;
2237 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2238 * and in this case should treat it like '$*' - see 'else...' below */
2239 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2241 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2242 if (++i >= G.global_argc)
2244 o_addchr(output, '\0');
2245 debug_print_list("expand_vars_to_list[4]", output, n);
2246 n = o_save_ptr(output, n);
2248 } else { /* quoted $*: add as one word */
2250 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2251 if (!G.global_argv[++i])
2254 o_addchr(output, G.ifs[0]);
2258 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2259 /* "Empty variable", used to make "" etc to not disappear */
2263 #if ENABLE_HUSH_TICK
2264 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2267 /* Can't just stuff it into output o_string,
2268 * expanded result may need to be globbed
2269 * and $IFS-splitted */
2270 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2271 process_command_subs(&subst_result, arg);
2272 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2273 val = subst_result.data;
2276 #if ENABLE_SH_MATH_SUPPORT
2277 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2278 arith_eval_hooks_t hooks;
2283 arg++; /* skip '+' */
2284 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2285 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2287 exp_str = expand_pseudo_dquoted(arg);
2288 hooks.lookupvar = get_local_var_value;
2289 hooks.setvar = arith_set_local_var;
2290 hooks.endofname = endofname;
2291 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2295 const char *msg = "error in arithmetic";
2298 msg = "exponent less than 0";
2301 msg = "divide by 0";
2304 msg = "expression recursion loop detected";
2309 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2310 sprintf(arith_buf, arith_t_fmt, res);
2315 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2317 bool exp_len = false;
2318 bool exp_null = false;
2320 char exp_save = exp_save; /* for compiler */
2321 char exp_op = exp_op; /* for compiler */
2322 char *exp_word = exp_word; /* for compiler */
2326 arg[0] = first_ch & 0x7f;
2328 /* prepare for expansions */
2329 if (var[0] == '#') {
2330 /* handle length expansion ${#var} */
2334 /* maybe handle parameter expansion */
2335 exp_off = strcspn(var, ":-=+?%#");
2339 exp_save = var[exp_off];
2340 exp_null = exp_save == ':';
2341 exp_word = var + exp_off;
2344 exp_op = *exp_word++;
2345 var[exp_off] = '\0';
2349 /* lookup the variable in question */
2350 if (isdigit(var[0])) {
2351 /* handle_dollar() should have vetted var for us */
2353 if (i < G.global_argc)
2354 val = G.global_argv[i];
2355 /* else val remains NULL: $N with too big N */
2357 val = get_local_var_value(var);
2359 /* handle any expansions */
2361 debug_printf_expand("expand: length of '%s' = ", val);
2362 val = utoa(val ? strlen(val) : 0);
2363 debug_printf_expand("%s\n", val);
2364 } else if (exp_off) {
2365 if (exp_op == '%' || exp_op == '#') {
2367 /* we need to do a pattern match */
2370 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2371 if (exp_op == *exp_word) /* ## or %% */
2373 val = dyn_val = xstrdup(val);
2374 loc = scan(dyn_val, exp_word, match_at_left);
2375 if (match_at_left) /* # or ## */
2377 else if (loc) /* % or %% and match was found */
2381 /* we need to do an expansion */
2382 int exp_test = (!val || (exp_null && !val[0]));
2384 exp_test = !exp_test;
2385 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2386 exp_null ? "true" : "false", exp_test);
2388 if (exp_op == '?') {
2389 //TODO: how interactive bash aborts expansion mid-command?
2390 /* ${var?[error_msg_if_unset]} */
2391 /* ${var:?[error_msg_if_unset_or_null]} */
2392 /* mimic bash message */
2393 die_if_script("%s: %s",
2395 exp_word[0] ? exp_word : "parameter null or not set"
2401 if (exp_op == '=') {
2402 /* ${var=[word]} or ${var:=[word]} */
2403 if (isdigit(var[0]) || var[0] == '#') {
2404 /* mimic bash message */
2405 die_if_script("$%s: cannot assign in this way", var);
2408 char *new_var = xasprintf("%s=%s", var, val);
2409 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2415 var[exp_off] = exp_save;
2419 #if ENABLE_HUSH_TICK
2422 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2423 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2425 /* unquoted var's contents should be globbed, so don't escape */
2426 smallint sv = output->o_escape;
2427 output->o_escape = 0;
2428 n = expand_on_ifs(output, n, val);
2430 output->o_escape = sv;
2432 } else { /* quoted $VAR, val will be appended below */
2433 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2436 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2439 o_addQstr(output, val, strlen(val));
2442 /* Do the check to avoid writing to a const string */
2443 if (*p != SPECIAL_VAR_SYMBOL)
2444 *p = SPECIAL_VAR_SYMBOL;
2446 #if ENABLE_HUSH_TICK
2447 o_free(&subst_result);
2450 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2453 debug_print_list("expand_vars_to_list[a]", output, n);
2454 /* this part is literal, and it was already pre-quoted
2455 * if needed (much earlier), do not use o_addQstr here! */
2456 o_addstr_with_NUL(output, arg);
2457 debug_print_list("expand_vars_to_list[b]", output, n);
2458 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2459 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2462 /* allow to reuse list[n] later without re-growth */
2463 output->has_empty_slot = 1;
2465 o_addchr(output, '\0');
2470 static char **expand_variables(char **argv, int or_mask)
2475 o_string output = NULL_O_STRING;
2477 if (or_mask & 0x100) {
2478 output.o_escape = 1; /* protect against globbing for "$var" */
2479 /* (unquoted $var will temporarily switch it off) */
2486 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2489 debug_print_list("expand_variables", &output, n);
2491 /* output.data (malloced in one block) gets returned in "list" */
2492 list = o_finalize_list(&output, n);
2493 debug_print_strings("expand_variables[1]", list);
2497 static char **expand_strvec_to_strvec(char **argv)
2499 return expand_variables(argv, 0x100);
2502 #if ENABLE_HUSH_BASH_COMPAT
2503 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2505 return expand_variables(argv, 0x80);
2509 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2510 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2515 o_string output = NULL_O_STRING;
2520 int is_var = is_well_formed_var_name(*v, '=');
2521 /* is_var * 0x80: singleword expansion for vars */
2522 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2524 /* Subtle! expand_vars_to_list did not glob last word yet.
2525 * It does this only when fed with further data.
2526 * Therefore we set globbing flags AFTER it, not before:
2529 /* if it is not recognizably abc=...; then: */
2530 output.o_escape = !is_var; /* protect against globbing for "$var" */
2531 /* (unquoted $var will temporarily switch it off) */
2532 output.o_glob = !is_var; /* and indeed do globbing */
2535 debug_print_list("expand_cond", &output, n);
2537 /* output.data (malloced in one block) gets returned in "list" */
2538 list = o_finalize_list(&output, n);
2539 debug_print_strings("expand_cond[1]", list);
2544 /* Used for expansion of right hand of assignments */
2545 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2547 static char *expand_string_to_string(const char *str)
2549 char *argv[2], **list;
2551 argv[0] = (char*)str;
2553 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2555 if (!list[0] || list[1])
2556 bb_error_msg_and_die("BUG in varexp2");
2557 /* actually, just move string 2*sizeof(char*) bytes back */
2558 overlapping_strcpy((char*)list, list[0]);
2559 unbackslash((char*)list);
2560 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2564 /* Used for "eval" builtin */
2565 static char* expand_strvec_to_string(char **argv)
2569 list = expand_variables(argv, 0x80);
2570 /* Convert all NULs to spaces */
2575 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2576 bb_error_msg_and_die("BUG in varexp3");
2577 /* bash uses ' ' regardless of $IFS contents */
2582 overlapping_strcpy((char*)list, list[0]);
2583 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2587 static char **expand_assignments(char **argv, int count)
2591 /* Expand assignments into one string each */
2592 for (i = 0; i < count; i++) {
2593 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2601 void re_execute_shell(char ***to_free, const char *s,
2602 char *g_argv0, char **g_argv,
2603 char **builtin_argv) NORETURN;
2605 static void reset_traps_to_defaults(void)
2607 /* This function is always called in a child shell
2608 * after fork (not vfork, NOMMU doesn't use this function).
2613 /* Child shells are not interactive.
2614 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2615 * Testcase: (while :; do :; done) + ^Z should background.
2616 * Same goes for SIGTERM, SIGHUP, SIGINT.
2618 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2619 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
2621 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2622 * Stupid. It can be done with *single* &= op, but we can't use
2623 * the fact that G.blocked_set is implemented as a bitmask
2625 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2629 /* Careful. Only if no trap or trap is not "" */
2630 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2631 sigdelset(&G.blocked_set, sig);
2638 /* Our homegrown sig mask is saner to work with :) */
2639 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2641 /* Resetting all traps to default except empty ones */
2642 mask = G.non_DFL_mask;
2643 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2644 if (!G.traps[sig] || !G.traps[sig][0])
2647 G.traps[sig] = NULL;
2648 /* There is no signal for 0 (EXIT) */
2651 /* There was a trap handler, we just removed it.
2652 * But if sig still has non-DFL handling,
2653 * we should not unblock the sig. */
2656 sigdelset(&G.blocked_set, sig);
2658 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2663 static void re_execute_shell(char ***to_free, const char *s,
2664 char *g_argv0, char **g_argv,
2665 char **builtin_argv) NORETURN;
2666 static void re_execute_shell(char ***to_free, const char *s,
2667 char *g_argv0, char **g_argv,
2668 char **builtin_argv)
2670 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2671 char *heredoc_argv[4];
2672 struct variable *cur;
2673 #if ENABLE_HUSH_FUNCTIONS
2674 struct function *funcp;
2679 if (!g_argv0) { /* heredoc */
2680 argv = heredoc_argv;
2681 argv[0] = (char *) G.argv0_for_re_execing;
2682 argv[1] = (char *) "-<";
2683 argv[2] = (char *) s;
2685 pp = &argv[3]; /* used as pointer to empty environment */
2691 if (pp) while (*pp++)
2694 sprintf(param_buf, "-$%x:%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2695 , (unsigned) G.root_pid
2696 , (unsigned) G.root_ppid
2697 , (unsigned) G.last_bg_pid
2698 , (unsigned) G.last_exitcode
2700 IF_HUSH_LOOPS(, G.depth_of_loop)
2702 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2703 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2706 for (cur = G.top_var; cur; cur = cur->next) {
2707 if (!cur->flg_export || cur->flg_read_only)
2710 #if ENABLE_HUSH_FUNCTIONS
2711 for (funcp = G.top_func; funcp; funcp = funcp->next)
2717 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2718 *pp++ = (char *) G.argv0_for_re_execing;
2720 for (cur = G.top_var; cur; cur = cur->next) {
2721 if (cur->varstr == hush_version_str)
2723 if (cur->flg_read_only) {
2724 *pp++ = (char *) "-R";
2725 *pp++ = cur->varstr;
2726 } else if (!cur->flg_export) {
2727 *pp++ = (char *) "-V";
2728 *pp++ = cur->varstr;
2731 #if ENABLE_HUSH_FUNCTIONS
2732 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2733 *pp++ = (char *) "-F";
2734 *pp++ = funcp->name;
2735 *pp++ = funcp->body_as_string;
2738 /* We can pass activated traps here. Say, -Tnn:trap_string
2740 * However, POSIX says that subshells reset signals with traps
2742 * I tested bash-3.2 and it not only does that with true subshells
2743 * of the form ( list ), but with any forked children shells.
2744 * I set trap "echo W" WINCH; and then tried:
2746 * { echo 1; sleep 20; echo 2; } &
2747 * while true; do echo 1; sleep 20; echo 2; break; done &
2748 * true | { echo 1; sleep 20; echo 2; } | cat
2750 * In all these cases sending SIGWINCH to the child shell
2751 * did not run the trap. If I add trap "echo V" WINCH;
2752 * _inside_ group (just before echo 1), it works.
2754 * I conclude it means we don't need to pass active traps here.
2755 * exec syscall below resets them to SIG_DFL for us.
2757 *pp++ = (char *) "-c";
2760 while (*++builtin_argv)
2761 *pp++ = *builtin_argv;
2762 *pp++ = (char *) "";
2767 /* *pp = NULL; - is already there */
2771 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2772 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2773 execve(bb_busybox_exec_path, argv, pp);
2774 /* Fallback. Useful for init=/bin/hush usage etc */
2775 if (argv[0][0] == '/')
2776 execve(argv[0], argv, pp);
2777 xfunc_error_retval = 127;
2778 bb_error_msg_and_die("can't re-execute the shell");
2780 #endif /* !BB_MMU */
2783 static void setup_heredoc(struct redir_struct *redir)
2785 struct fd_pair pair;
2788 /* the _body_ of heredoc (misleading field name) */
2789 const char *heredoc = redir->rd_filename;
2796 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2797 expanded = expand_pseudo_dquoted(heredoc);
2801 len = strlen(heredoc);
2803 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2805 xmove_fd(pair.rd, redir->rd_fd);
2807 /* Try writing without forking. Newer kernels have
2808 * dynamically growing pipes. Must use non-blocking write! */
2811 written = write(pair.wr, heredoc, len);
2822 ndelay_off(pair.wr);
2824 /* Okay, pipe buffer was not big enough */
2825 /* Note: we must not create a stray child (bastard? :)
2826 * for the unsuspecting parent process. Child creates a grandchild
2827 * and exits before parent execs the process which consumes heredoc
2828 * (that exec happens after we return from this function) */
2834 bb_perror_msg_and_die("vfork");
2837 disable_restore_tty_pgrp_on_exit();
2838 pid = BB_MMU ? fork() : vfork();
2840 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2844 close(redir->rd_fd); /* read side of the pipe */
2846 full_write(pair.wr, heredoc, len); /* may loop or block */
2849 /* Delegate blocking writes to another process */
2850 xmove_fd(pair.wr, STDOUT_FILENO);
2851 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2855 #if ENABLE_HUSH_FAST
2857 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2859 enable_restore_tty_pgrp_on_exit();
2865 wait(NULL); /* wait till child has died */
2868 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2869 * and stderr if they are redirected. */
2870 static int setup_redirects(struct command *prog, int squirrel[])
2873 struct redir_struct *redir;
2875 for (redir = prog->redirects; redir; redir = redir->next) {
2876 if (redir->rd_type == REDIRECT_HEREDOC2) {
2877 /* rd_fd<<HERE case */
2878 if (squirrel && redir->rd_fd < 3
2879 && squirrel[redir->rd_fd] < 0
2881 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2883 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2885 debug_printf_parse("set heredoc '%s'\n",
2886 redir->rd_filename);
2887 setup_heredoc(redir);
2891 if (redir->rd_dup == REDIRFD_TO_FILE) {
2892 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2894 if (redir->rd_filename == NULL) {
2895 /* Something went wrong in the parse.
2896 * Pretend it didn't happen */
2897 bb_error_msg("bug in redirect parse");
2900 mode = redir_table[redir->rd_type].mode;
2901 p = expand_string_to_string(redir->rd_filename);
2902 openfd = open_or_warn(p, mode);
2905 /* this could get lost if stderr has been redirected, but
2906 * bash and ash both lose it as well (though zsh doesn't!) */
2907 //what the above comment tries to say?
2911 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2912 openfd = redir->rd_dup;
2915 if (openfd != redir->rd_fd) {
2916 if (squirrel && redir->rd_fd < 3
2917 && squirrel[redir->rd_fd] < 0
2919 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2921 if (openfd == REDIRFD_CLOSE) {
2922 /* "n>-" means "close me" */
2923 close(redir->rd_fd);
2925 xdup2(openfd, redir->rd_fd);
2926 if (redir->rd_dup == REDIRFD_TO_FILE)
2934 static void restore_redirects(int squirrel[])
2937 for (i = 0; i < 3; i++) {
2940 /* We simply die on error */
2947 static void free_pipe_list(struct pipe *head);
2949 /* Return code is the exit status of the pipe */
2950 static void free_pipe(struct pipe *pi)
2953 struct command *command;
2954 struct redir_struct *r, *rnext;
2957 if (pi->stopped_cmds > 0) /* why? */
2959 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2960 for (i = 0; i < pi->num_cmds; i++) {
2961 command = &pi->cmds[i];
2962 debug_printf_clean(" command %d:\n", i);
2963 if (command->argv) {
2964 for (a = 0, p = command->argv; *p; a++, p++) {
2965 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2967 free_strings(command->argv);
2968 command->argv = NULL;
2970 /* not "else if": on syntax error, we may have both! */
2971 if (command->group) {
2972 debug_printf_clean(" begin group (cmd_type:%d)\n",
2974 free_pipe_list(command->group);
2975 debug_printf_clean(" end group\n");
2976 command->group = NULL;
2978 /* else is crucial here.
2979 * If group != NULL, child_func is meaningless */
2980 #if ENABLE_HUSH_FUNCTIONS
2981 else if (command->child_func) {
2982 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2983 command->child_func->parent_cmd = NULL;
2987 free(command->group_as_string);
2988 command->group_as_string = NULL;
2990 for (r = command->redirects; r; r = rnext) {
2991 debug_printf_clean(" redirect %d%s",
2992 r->rd_fd, redir_table[r->rd_type].descrip);
2993 /* guard against the case >$FOO, where foo is unset or blank */
2994 if (r->rd_filename) {
2995 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2996 free(r->rd_filename);
2997 r->rd_filename = NULL;
2999 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3003 command->redirects = NULL;
3005 free(pi->cmds); /* children are an array, they get freed all at once */
3013 static void free_pipe_list(struct pipe *head)
3015 struct pipe *pi, *next;
3017 for (pi = head; pi; pi = next) {
3019 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3022 debug_printf_clean("pipe followup code %d\n", pi->followup);
3024 /*pi->next = NULL;*/
3030 static int run_list(struct pipe *pi);
3032 #define parse_stream(pstring, input, end_trigger) \
3033 parse_stream(input, end_trigger)
3035 static struct pipe *parse_stream(char **pstring,
3036 struct in_str *input,
3038 static void parse_and_run_string(const char *s);
3041 static char *find_in_path(const char *arg)
3044 const char *PATH = get_local_var_value("PATH");
3050 const char *end = strchrnul(PATH, ':');
3051 int sz = end - PATH; /* must be int! */
3055 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3057 /* We have xxx::yyyy in $PATH,
3058 * it means "use current dir" */
3061 if (access(ret, F_OK) == 0)
3074 static const struct built_in_command* find_builtin_helper(const char *name,
3075 const struct built_in_command *x,
3076 const struct built_in_command *end)
3079 if (strcmp(name, x->cmd) != 0) {
3083 debug_printf_exec("found builtin '%s'\n", name);
3088 static const struct built_in_command* find_builtin1(const char *name)
3090 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3092 static const struct built_in_command* find_builtin(const char *name)
3094 const struct built_in_command *x = find_builtin1(name);
3097 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3100 #if ENABLE_HUSH_FUNCTIONS
3101 static struct function **find_function_slot(const char *name)
3103 struct function **funcpp = &G.top_func;
3105 if (strcmp(name, (*funcpp)->name) == 0) {
3108 funcpp = &(*funcpp)->next;
3113 static const struct function *find_function(const char *name)
3115 const struct function *funcp = *find_function_slot(name);
3117 debug_printf_exec("found function '%s'\n", name);
3121 /* Note: takes ownership on name ptr */
3122 static struct function *new_function(char *name)
3124 struct function **funcpp = find_function_slot(name);
3125 struct function *funcp = *funcpp;
3127 if (funcp != NULL) {
3128 struct command *cmd = funcp->parent_cmd;
3129 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3131 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3133 /* Note: if !funcp->body, do not free body_as_string!
3134 * This is a special case of "-F name body" function:
3135 * body_as_string was not malloced! */
3137 free_pipe_list(funcp->body);
3139 free(funcp->body_as_string);
3143 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3144 cmd->argv[0] = funcp->name;
3145 cmd->group = funcp->body;
3147 cmd->group_as_string = funcp->body_as_string;
3151 debug_printf_exec("remembering new function '%s'\n", name);
3152 funcp = *funcpp = xzalloc(sizeof(*funcp));
3153 /*funcp->next = NULL;*/
3160 static void unset_func(const char *name)
3162 struct function **funcpp = find_function_slot(name);
3163 struct function *funcp = *funcpp;
3165 if (funcp != NULL) {
3166 debug_printf_exec("freeing function '%s'\n", funcp->name);
3167 *funcpp = funcp->next;
3168 /* funcp is unlinked now, deleting it.
3169 * Note: if !funcp->body, the function was created by
3170 * "-F name body", do not free ->body_as_string
3171 * and ->name as they were not malloced. */
3173 free_pipe_list(funcp->body);
3176 free(funcp->body_as_string);
3184 #define exec_function(to_free, funcp, argv) \
3185 exec_function(funcp, argv)
3187 static void exec_function(char ***to_free,
3188 const struct function *funcp,
3189 char **argv) NORETURN;
3190 static void exec_function(char ***to_free,
3191 const struct function *funcp,
3197 argv[0] = G.global_argv[0];
3198 G.global_argv = argv;
3202 /* On MMU, funcp->body is always non-NULL */
3203 n = run_list(funcp->body);
3207 re_execute_shell(to_free,
3208 funcp->body_as_string,
3215 static int run_function(const struct function *funcp, char **argv)
3221 save_and_replace_G_args(&sv, argv);
3223 /* "we are in function, ok to use return" */
3224 sv_flg = G.flag_return_in_progress;
3225 G.flag_return_in_progress = -1;
3226 #if ENABLE_HUSH_LOCAL
3227 G.func_nest_level++;
3230 /* On MMU, funcp->body is always non-NULL */
3233 /* Function defined by -F */
3234 parse_and_run_string(funcp->body_as_string);
3235 rc = G.last_exitcode;
3239 rc = run_list(funcp->body);
3242 #if ENABLE_HUSH_LOCAL
3244 struct variable *var;
3245 struct variable **var_pp;
3247 var_pp = &G.top_var;
3248 while ((var = *var_pp) != NULL) {
3249 if (var->func_nest_level < G.func_nest_level) {
3250 var_pp = &var->next;
3254 if (var->flg_export)
3255 bb_unsetenv(var->varstr);
3256 /* Remove from global list */
3257 *var_pp = var->next;
3263 G.func_nest_level--;
3266 G.flag_return_in_progress = sv_flg;
3268 restore_G_args(&sv, argv);
3272 #endif /* ENABLE_HUSH_FUNCTIONS */
3276 #define exec_builtin(to_free, x, argv) \
3277 exec_builtin(x, argv)
3279 #define exec_builtin(to_free, x, argv) \
3280 exec_builtin(to_free, argv)
3282 static void exec_builtin(char ***to_free,
3283 const struct built_in_command *x,
3284 char **argv) NORETURN;
3285 static void exec_builtin(char ***to_free,
3286 const struct built_in_command *x,
3290 int rcode = x->function(argv);
3294 /* On NOMMU, we must never block!
3295 * Example: { sleep 99 | read line; } & echo Ok
3297 re_execute_shell(to_free,
3307 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3308 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3309 #define pseudo_exec(nommu_save, command, argv_expanded) \
3310 pseudo_exec(command, argv_expanded)
3313 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3315 * Don't exit() here. If you don't exec, use _exit instead.
3316 * The at_exit handlers apparently confuse the calling process,
3317 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3318 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3319 char **argv, int assignment_cnt,
3320 char **argv_expanded) NORETURN;
3321 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3322 char **argv, int assignment_cnt,
3323 char **argv_expanded)
3327 /* Case when we are here: ... | var=val | ... */
3328 if (!argv[assignment_cnt])
3329 _exit(EXIT_SUCCESS);
3331 new_env = expand_assignments(argv, assignment_cnt);
3333 set_vars_and_save_old(new_env);
3334 free(new_env); /* optional */
3335 /* we can also destroy set_vars_and_save_old's return value,
3338 nommu_save->new_env = new_env;
3339 nommu_save->old_vars = set_vars_and_save_old(new_env);
3341 if (argv_expanded) {
3342 argv = argv_expanded;
3344 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3346 nommu_save->argv = argv;
3350 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3351 if (strchr(argv[0], '/') != NULL)
3355 /* Check if the command matches any of the builtins.
3356 * Depending on context, this might be redundant. But it's
3357 * easier to waste a few CPU cycles than it is to figure out
3358 * if this is one of those cases.
3361 /* On NOMMU, it is more expensive to re-execute shell
3362 * just in order to run echo or test builtin.
3363 * It's better to skip it here and run corresponding
3364 * non-builtin later. */
3365 const struct built_in_command *x;
3366 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3368 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3371 #if ENABLE_HUSH_FUNCTIONS
3372 /* Check if the command matches any functions */
3374 const struct function *funcp = find_function(argv[0]);
3376 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3381 #if ENABLE_FEATURE_SH_STANDALONE
3382 /* Check if the command matches any busybox applets */
3384 int a = find_applet_by_name(argv[0]);
3386 # if BB_MMU /* see above why on NOMMU it is not allowed */
3387 if (APPLET_IS_NOEXEC(a)) {
3388 debug_printf_exec("running applet '%s'\n", argv[0]);
3389 run_applet_no_and_exit(a, argv);
3392 /* Re-exec ourselves */
3393 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3394 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3395 execv(bb_busybox_exec_path, argv);
3396 /* If they called chroot or otherwise made the binary no longer
3397 * executable, fall through */
3402 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3405 debug_printf_exec("execing '%s'\n", argv[0]);
3406 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3407 execvp(argv[0], argv);
3408 bb_perror_msg("can't execute '%s'", argv[0]);
3409 _exit(EXIT_FAILURE);
3412 /* Called after [v]fork() in run_pipe
3414 static void pseudo_exec(nommu_save_t *nommu_save,
3415 struct command *command,
3416 char **argv_expanded) NORETURN;
3417 static void pseudo_exec(nommu_save_t *nommu_save,
3418 struct command *command,
3419 char **argv_expanded)
3421 if (command->argv) {
3422 pseudo_exec_argv(nommu_save, command->argv,
3423 command->assignment_cnt, argv_expanded);
3426 if (command->group) {
3427 /* Cases when we are here:
3430 * ... | ( list ) | ...
3431 * ... | { list } | ...
3435 debug_printf_exec("pseudo_exec: run_list\n");
3436 reset_traps_to_defaults();
3437 rcode = run_list(command->group);
3438 /* OK to leak memory by not calling free_pipe_list,
3439 * since this process is about to exit */
3442 re_execute_shell(&nommu_save->argv_from_re_execing,
3443 command->group_as_string,
3450 /* Case when we are here: ... | >file */
3451 debug_printf_exec("pseudo_exec'ed null command\n");
3452 _exit(EXIT_SUCCESS);
3456 static const char *get_cmdtext(struct pipe *pi)
3462 /* This is subtle. ->cmdtext is created only on first backgrounding.
3463 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3464 * On subsequent bg argv is trashed, but we won't use it */
3467 argv = pi->cmds[0].argv;
3468 if (!argv || !argv[0]) {
3469 pi->cmdtext = xzalloc(1);
3475 len += strlen(*argv) + 1;
3479 argv = pi->cmds[0].argv;
3481 len = strlen(*argv);
3482 memcpy(p, *argv, len);
3490 static void insert_bg_job(struct pipe *pi)
3492 struct pipe *job, **jobp;
3495 /* Linear search for the ID of the job to use */
3497 for (job = G.job_list; job; job = job->next)
3498 if (job->jobid >= pi->jobid)
3499 pi->jobid = job->jobid + 1;
3501 /* Add job to the list of running jobs */
3503 while ((job = *jobp) != NULL)
3505 job = *jobp = xmalloc(sizeof(*job));
3507 *job = *pi; /* physical copy */
3509 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3510 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3511 for (i = 0; i < pi->num_cmds; i++) {
3512 job->cmds[i].pid = pi->cmds[i].pid;
3513 /* all other fields are not used and stay zero */
3515 job->cmdtext = xstrdup(get_cmdtext(pi));
3517 if (G_interactive_fd)
3518 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3519 /* Last command's pid goes to $! */
3520 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3521 G.last_jobid = job->jobid;
3524 static void remove_bg_job(struct pipe *pi)
3526 struct pipe *prev_pipe;
3528 if (pi == G.job_list) {
3529 G.job_list = pi->next;
3531 prev_pipe = G.job_list;
3532 while (prev_pipe->next != pi)
3533 prev_pipe = prev_pipe->next;
3534 prev_pipe->next = pi->next;
3537 G.last_jobid = G.job_list->jobid;
3542 /* Remove a backgrounded job */
3543 static void delete_finished_bg_job(struct pipe *pi)
3546 pi->stopped_cmds = 0;
3552 /* Check to see if any processes have exited -- if they
3553 * have, figure out why and see if a job has completed */
3554 static int checkjobs(struct pipe* fg_pipe)
3564 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3566 attributes = WUNTRACED;
3567 if (fg_pipe == NULL)
3568 attributes |= WNOHANG;
3571 #if ENABLE_HUSH_FAST
3572 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3573 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3574 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3575 /* There was neither fork nor SIGCHLD since last waitpid */
3576 /* Avoid doing waitpid syscall if possible */
3577 if (!G.we_have_children) {
3581 if (fg_pipe == NULL) { /* is WNOHANG set? */
3582 /* We have children, but they did not exit
3583 * or stop yet (we saw no SIGCHLD) */
3586 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3590 /* Do we do this right?
3591 * bash-3.00# sleep 20 | false
3593 * [3]+ Stopped sleep 20 | false
3594 * bash-3.00# echo $?
3595 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3596 * [hush 1.14.0: yes we do it right]
3603 #if ENABLE_HUSH_FAST
3604 i = G.count_SIGCHLD;
3606 childpid = waitpid(-1, &status, attributes);
3607 if (childpid <= 0) {
3608 if (childpid && errno != ECHILD)
3609 bb_perror_msg("waitpid");
3610 #if ENABLE_HUSH_FAST
3611 else { /* Until next SIGCHLD, waitpid's are useless */
3612 G.we_have_children = (childpid == 0);
3613 G.handled_SIGCHLD = i;
3614 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3619 dead = WIFEXITED(status) || WIFSIGNALED(status);
3622 if (WIFSTOPPED(status))
3623 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3624 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3625 if (WIFSIGNALED(status))
3626 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3627 childpid, WTERMSIG(status), WEXITSTATUS(status));
3628 if (WIFEXITED(status))
3629 debug_printf_jobs("pid %d exited, exitcode %d\n",
3630 childpid, WEXITSTATUS(status));
3632 /* Were we asked to wait for fg pipe? */
3634 for (i = 0; i < fg_pipe->num_cmds; i++) {
3635 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3636 if (fg_pipe->cmds[i].pid != childpid)
3639 fg_pipe->cmds[i].pid = 0;
3640 fg_pipe->alive_cmds--;
3641 if (i == fg_pipe->num_cmds - 1) {
3642 /* last process gives overall exitstatus */
3643 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3644 rcode = WEXITSTATUS(status);
3645 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3646 /* bash prints killer signal's name for *last*
3647 * process in pipe (prints just newline for SIGINT).
3648 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
3650 if (WIFSIGNALED(status)) {
3651 int sig = WTERMSIG(status);
3652 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3656 fg_pipe->cmds[i].is_stopped = 1;
3657 fg_pipe->stopped_cmds++;
3659 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3660 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3661 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3662 /* All processes in fg pipe have exited or stopped */
3663 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3664 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3665 * and "killall -STOP cat" */
3666 if (G_interactive_fd) {
3668 if (fg_pipe->alive_cmds)
3669 insert_bg_job(fg_pipe);
3673 if (!fg_pipe->alive_cmds)
3676 /* There are still running processes in the fg pipe */
3677 goto wait_more; /* do waitpid again */
3679 /* it wasnt fg_pipe, look for process in bg pipes */
3683 /* We asked to wait for bg or orphaned children */
3684 /* No need to remember exitcode in this case */
3685 for (pi = G.job_list; pi; pi = pi->next) {
3686 for (i = 0; i < pi->num_cmds; i++) {
3687 if (pi->cmds[i].pid == childpid)
3688 goto found_pi_and_prognum;
3691 /* Happens when shell is used as init process (init=/bin/sh) */
3692 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3693 continue; /* do waitpid again */
3695 found_pi_and_prognum:
3698 pi->cmds[i].pid = 0;
3700 if (!pi->alive_cmds) {
3701 if (G_interactive_fd)
3702 printf(JOB_STATUS_FORMAT, pi->jobid,
3703 "Done", pi->cmdtext);
3704 delete_finished_bg_job(pi);
3708 pi->cmds[i].is_stopped = 1;
3712 } /* while (waitpid succeeds)... */
3718 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3721 int rcode = checkjobs(fg_pipe);
3722 if (G_saved_tty_pgrp) {
3723 /* Job finished, move the shell to the foreground */
3724 p = getpgrp(); /* our process group id */
3725 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3726 tcsetpgrp(G_interactive_fd, p);
3732 /* Start all the jobs, but don't wait for anything to finish.
3735 * Return code is normally -1, when the caller has to wait for children
3736 * to finish to determine the exit status of the pipe. If the pipe
3737 * is a simple builtin command, however, the action is done by the
3738 * time run_pipe returns, and the exit code is provided as the
3741 * Returns -1 only if started some children. IOW: we have to
3742 * mask out retvals of builtins etc with 0xff!
3744 * The only case when we do not need to [v]fork is when the pipe
3745 * is single, non-backgrounded, non-subshell command. Examples:
3746 * cmd ; ... { list } ; ...
3747 * cmd && ... { list } && ...
3748 * cmd || ... { list } || ...
3749 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3750 * or (if SH_STANDALONE) an applet, and we can run the { list }
3751 * with run_list. If it isn't one of these, we fork and exec cmd.
3753 * Cases when we must fork:
3754 * non-single: cmd | cmd
3755 * backgrounded: cmd & { list } &
3756 * subshell: ( list ) [&]
3758 static NOINLINE int run_pipe(struct pipe *pi)
3760 static const char *const null_ptr = NULL;
3763 struct command *command;
3764 char **argv_expanded;
3767 /* it is not always needed, but we aim to smaller code */
3768 int squirrel[] = { -1, -1, -1 };
3771 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3774 IF_HUSH_JOB(pi->pgrp = -1;)
3775 pi->stopped_cmds = 0;
3776 command = &(pi->cmds[0]);
3777 argv_expanded = NULL;
3779 if (pi->num_cmds != 1
3780 || pi->followup == PIPE_BG
3781 || command->cmd_type == CMD_SUBSHELL
3788 debug_printf_exec(": group:%p argv:'%s'\n",
3789 command->group, command->argv ? command->argv[0] : "NONE");
3791 if (command->group) {
3792 #if ENABLE_HUSH_FUNCTIONS
3793 if (command->cmd_type == CMD_FUNCDEF) {
3794 /* "executing" func () { list } */
3795 struct function *funcp;
3797 funcp = new_function(command->argv[0]);
3798 /* funcp->name is already set to argv[0] */
3799 funcp->body = command->group;
3801 funcp->body_as_string = command->group_as_string;
3802 command->group_as_string = NULL;
3804 command->group = NULL;
3805 command->argv[0] = NULL;
3806 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3807 funcp->parent_cmd = command;
3808 command->child_func = funcp;
3810 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3812 return EXIT_SUCCESS;
3816 debug_printf("non-subshell group\n");
3817 rcode = 1; /* exitcode if redir failed */
3818 if (setup_redirects(command, squirrel) == 0) {
3819 debug_printf_exec(": run_list\n");
3820 rcode = run_list(command->group) & 0xff;
3822 restore_redirects(squirrel);
3823 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3825 debug_printf_exec("run_pipe: return %d\n", rcode);
3829 argv = command->argv ? command->argv : (char **) &null_ptr;
3831 const struct built_in_command *x;
3832 #if ENABLE_HUSH_FUNCTIONS
3833 const struct function *funcp;
3837 char **new_env = NULL;
3838 struct variable *old_vars = NULL;
3840 if (argv[command->assignment_cnt] == NULL) {
3841 /* Assignments, but no command */
3842 /* Ensure redirects take effect. Try "a=t >file" */
3843 rcode = setup_redirects(command, squirrel);
3844 restore_redirects(squirrel);
3845 /* Set shell variables */
3847 p = expand_string_to_string(*argv);
3848 debug_printf_exec("set shell var:'%s'->'%s'\n",
3850 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3853 /* Do we need to flag set_local_var() errors?
3854 * "assignment to readonly var" and "putenv error"
3856 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3858 debug_printf_exec("run_pipe: return %d\n", rcode);
3862 /* Expand the rest into (possibly) many strings each */
3864 #if ENABLE_HUSH_BASH_COMPAT
3865 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3866 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3869 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3870 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3871 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3876 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3879 x = find_builtin(argv_expanded[0]);
3880 #if ENABLE_HUSH_FUNCTIONS
3883 funcp = find_function(argv_expanded[0]);
3887 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3888 debug_printf("exec with redirects only\n");
3889 rcode = setup_redirects(command, NULL);
3890 goto clean_up_and_ret1;
3893 /* setup_redirects acts on file descriptors, not FILEs.
3894 * This is perfect for work that comes after exec().
3895 * Is it really safe for inline use? Experimentally,
3896 * things seem to work. */
3897 rcode = setup_redirects(command, squirrel);
3899 new_env = expand_assignments(argv, command->assignment_cnt);
3900 old_vars = set_vars_and_save_old(new_env);
3902 debug_printf_exec(": builtin '%s' '%s'...\n",
3903 x->cmd, argv_expanded[1]);
3904 rcode = x->function(argv_expanded) & 0xff;
3907 #if ENABLE_HUSH_FUNCTIONS
3909 # if ENABLE_HUSH_LOCAL
3910 struct variable **sv;
3911 sv = G.shadowed_vars_pp;
3912 G.shadowed_vars_pp = &old_vars;
3914 debug_printf_exec(": function '%s' '%s'...\n",
3915 funcp->name, argv_expanded[1]);
3916 rcode = run_function(funcp, argv_expanded) & 0xff;
3917 # if ENABLE_HUSH_LOCAL
3918 G.shadowed_vars_pp = sv;
3923 #if ENABLE_FEATURE_SH_STANDALONE
3926 restore_redirects(squirrel);
3927 unset_vars(new_env);
3930 free(argv_expanded);
3931 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3933 debug_printf_exec("run_pipe return %d\n", rcode);
3937 #if ENABLE_FEATURE_SH_STANDALONE
3938 i = find_applet_by_name(argv_expanded[0]);
3939 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3940 rcode = setup_redirects(command, squirrel);
3942 new_env = expand_assignments(argv, command->assignment_cnt);
3943 old_vars = set_vars_and_save_old(new_env);
3944 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3945 argv_expanded[0], argv_expanded[1]);
3946 rcode = run_nofork_applet(i, argv_expanded);
3948 goto clean_up_and_ret;
3951 /* It is neither builtin nor applet. We must fork. */
3955 /* NB: argv_expanded may already be created, and that
3956 * might include `cmd` runs! Do not rerun it! We *must*
3957 * use argv_expanded if it's non-NULL */
3959 /* Going to fork a child per each pipe member */
3963 for (i = 0; i < pi->num_cmds; i++) {
3964 struct fd_pair pipefds;
3966 volatile nommu_save_t nommu_save;
3967 nommu_save.new_env = NULL;
3968 nommu_save.old_vars = NULL;
3969 nommu_save.argv = NULL;
3970 nommu_save.argv_from_re_execing = NULL;
3972 command = &(pi->cmds[i]);
3973 if (command->argv) {
3974 debug_printf_exec(": pipe member '%s' '%s'...\n",
3975 command->argv[0], command->argv[1]);
3977 debug_printf_exec(": pipe member with no argv\n");
3980 /* pipes are inserted between pairs of commands */
3983 if ((i + 1) < pi->num_cmds)
3984 xpiped_pair(pipefds);
3986 command->pid = BB_MMU ? fork() : vfork();
3987 if (!command->pid) { /* child */
3989 disable_restore_tty_pgrp_on_exit();
3991 /* Every child adds itself to new process group
3992 * with pgid == pid_of_first_child_in_pipe */
3993 if (G.run_list_level == 1 && G_interactive_fd) {
3996 if (pgrp < 0) /* true for 1st process only */
3998 if (setpgid(0, pgrp) == 0
3999 && pi->followup != PIPE_BG
4000 && G_saved_tty_pgrp /* we have ctty */
4002 /* We do it in *every* child, not just first,
4004 tcsetpgrp(G_interactive_fd, pgrp);
4008 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4009 /* 1st cmd in backgrounded pipe
4010 * should have its stdin /dev/null'ed */
4012 if (open(bb_dev_null, O_RDONLY))
4013 xopen("/", O_RDONLY);
4015 xmove_fd(nextin, 0);
4017 xmove_fd(pipefds.wr, 1);
4020 /* Like bash, explicit redirects override pipes,
4021 * and the pipe fd is available for dup'ing. */
4022 if (setup_redirects(command, NULL))
4025 /* Restore default handlers just prior to exec */
4026 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4028 /* Stores to nommu_save list of env vars putenv'ed
4029 * (NOMMU, on MMU we don't need that) */
4030 /* cast away volatility... */
4031 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4032 /* pseudo_exec() does not return */
4035 /* parent or error */
4036 #if ENABLE_HUSH_FAST
4038 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4040 enable_restore_tty_pgrp_on_exit();
4042 /* Clean up after vforked child */
4043 free(nommu_save.argv);
4044 free(nommu_save.argv_from_re_execing);
4045 unset_vars(nommu_save.new_env);
4046 add_vars(nommu_save.old_vars);
4048 free(argv_expanded);
4049 argv_expanded = NULL;
4050 if (command->pid < 0) { /* [v]fork failed */
4051 /* Clearly indicate, was it fork or vfork */
4052 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4056 /* Second and next children need to know pid of first one */
4058 pi->pgrp = command->pid;
4064 if ((i + 1) < pi->num_cmds)
4066 /* Pass read (output) pipe end to next iteration */
4067 nextin = pipefds.rd;
4070 if (!pi->alive_cmds) {
4072 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4077 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4081 #ifndef debug_print_tree
4082 static void debug_print_tree(struct pipe *pi, int lvl)
4084 static const char *const PIPE[] = {
4090 static const char *RES[] = {
4091 [RES_NONE ] = "NONE" ,
4094 [RES_THEN ] = "THEN" ,
4095 [RES_ELIF ] = "ELIF" ,
4096 [RES_ELSE ] = "ELSE" ,
4099 #if ENABLE_HUSH_LOOPS
4100 [RES_FOR ] = "FOR" ,
4101 [RES_WHILE] = "WHILE",
4102 [RES_UNTIL] = "UNTIL",
4104 [RES_DONE ] = "DONE" ,
4106 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4109 #if ENABLE_HUSH_CASE
4110 [RES_CASE ] = "CASE" ,
4111 [RES_CASE_IN ] = "CASE_IN" ,
4112 [RES_MATCH] = "MATCH",
4113 [RES_CASE_BODY] = "CASE_BODY",
4114 [RES_ESAC ] = "ESAC" ,
4116 [RES_XXXX ] = "XXXX" ,
4117 [RES_SNTX ] = "SNTX" ,
4119 static const char *const CMDTYPE[] = {
4123 #if ENABLE_HUSH_FUNCTIONS
4132 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4133 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4135 while (prn < pi->num_cmds) {
4136 struct command *command = &pi->cmds[prn];
4137 char **argv = command->argv;
4139 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4141 command->assignment_cnt);
4142 if (command->group) {
4143 fprintf(stderr, " group %s: (argv=%p)\n",
4144 CMDTYPE[command->cmd_type],
4146 debug_print_tree(command->group, lvl+1);
4150 if (argv) while (*argv) {
4151 fprintf(stderr, " '%s'", *argv);
4154 fprintf(stderr, "\n");
4163 /* NB: called by pseudo_exec, and therefore must not modify any
4164 * global data until exec/_exit (we can be a child after vfork!) */
4165 static int run_list(struct pipe *pi)
4167 #if ENABLE_HUSH_CASE
4168 char *case_word = NULL;
4170 #if ENABLE_HUSH_LOOPS
4171 struct pipe *loop_top = NULL;
4172 char **for_lcur = NULL;
4173 char **for_list = NULL;
4175 smallint last_followup;
4177 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4178 smalluint cond_code = 0;
4180 enum { cond_code = 0 };
4183 smallint rword; /* enum reserved_style */
4184 smallint last_rword; /* ditto */
4187 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4190 #if ENABLE_HUSH_LOOPS
4191 /* Check syntax for "for" */
4192 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4193 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4195 /* current word is FOR or IN (BOLD in comments below) */
4196 if (cpipe->next == NULL) {
4197 syntax_error("malformed for");
4199 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4202 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4203 if (cpipe->next->res_word == RES_DO)
4205 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4206 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4207 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4209 syntax_error("malformed for");
4211 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4217 /* Past this point, all code paths should jump to ret: label
4218 * in order to return, no direct "return" statements please.
4219 * This helps to ensure that no memory is leaked. */
4227 last_rword = RES_XXXX;
4229 last_followup = PIPE_SEQ;
4230 rcode = G.last_exitcode;
4232 /* Go through list of pipes, (maybe) executing them. */
4233 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4237 IF_HAS_KEYWORDS(rword = pi->res_word;)
4238 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4239 rword, cond_code, last_rword);
4240 #if ENABLE_HUSH_LOOPS
4241 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4242 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4244 /* start of a loop: remember where loop starts */
4249 /* Still in the same "if...", "then..." or "do..." branch? */
4250 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4251 if ((rcode == 0 && last_followup == PIPE_OR)
4252 || (rcode != 0 && last_followup == PIPE_AND)
4254 /* It is "<true> || CMD" or "<false> && CMD"
4255 * and we should not execute CMD */
4256 debug_printf_exec("skipped cmd because of || or &&\n");
4257 last_followup = pi->followup;
4261 last_followup = pi->followup;
4262 IF_HAS_KEYWORDS(last_rword = rword;)
4265 if (rword == RES_THEN) {
4266 /* if false; then ... fi has exitcode 0! */
4267 G.last_exitcode = rcode = EXIT_SUCCESS;
4268 /* "if <false> THEN cmd": skip cmd */
4272 if (rword == RES_ELSE || rword == RES_ELIF) {
4273 /* "if <true> then ... ELSE/ELIF cmd":
4274 * skip cmd and all following ones */
4279 #if ENABLE_HUSH_LOOPS
4280 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4282 /* first loop through for */
4284 static const char encoded_dollar_at[] ALIGN1 = {
4285 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4286 }; /* encoded representation of "$@" */
4287 static const char *const encoded_dollar_at_argv[] = {
4288 encoded_dollar_at, NULL
4289 }; /* argv list with one element: "$@" */
4292 vals = (char**)encoded_dollar_at_argv;
4293 if (pi->next->res_word == RES_IN) {
4294 /* if no variable values after "in" we skip "for" */
4295 if (!pi->next->cmds[0].argv) {
4296 G.last_exitcode = rcode = EXIT_SUCCESS;
4297 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4300 vals = pi->next->cmds[0].argv;
4301 } /* else: "for var; do..." -> assume "$@" list */
4302 /* create list of variable values */
4303 debug_print_strings("for_list made from", vals);
4304 for_list = expand_strvec_to_strvec(vals);
4305 for_lcur = for_list;
4306 debug_print_strings("for_list", for_list);
4309 /* "for" loop is over, clean up */
4315 /* Insert next value from for_lcur */
4316 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4317 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4320 if (rword == RES_IN) {
4321 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4323 if (rword == RES_DONE) {
4324 continue; /* "done" has no cmds too */
4327 #if ENABLE_HUSH_CASE
4328 if (rword == RES_CASE) {
4329 case_word = expand_strvec_to_string(pi->cmds->argv);
4332 if (rword == RES_MATCH) {
4335 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4337 /* all prev words didn't match, does this one match? */
4338 argv = pi->cmds->argv;
4340 char *pattern = expand_string_to_string(*argv);
4341 /* TODO: which FNM_xxx flags to use? */
4342 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4344 if (cond_code == 0) { /* match! we will execute this branch */
4345 free(case_word); /* make future "word)" stop */
4353 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4355 continue; /* not matched yet, skip this pipe */
4358 /* Just pressing <enter> in shell should check for jobs.
4359 * OTOH, in non-interactive shell this is useless
4360 * and only leads to extra job checks */
4361 if (pi->num_cmds == 0) {
4362 if (G_interactive_fd)
4363 goto check_jobs_and_continue;
4367 /* After analyzing all keywords and conditions, we decided
4368 * to execute this pipe. NB: have to do checkjobs(NULL)
4369 * after run_pipe to collect any background children,
4370 * even if list execution is to be stopped. */
4371 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4374 #if ENABLE_HUSH_LOOPS
4375 G.flag_break_continue = 0;
4377 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4379 /* We ran a builtin, function, or group.
4380 * rcode is already known
4381 * and we don't need to wait for anything. */
4382 G.last_exitcode = rcode;
4383 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4384 check_and_run_traps(0);
4385 #if ENABLE_HUSH_LOOPS
4386 /* Was it "break" or "continue"? */
4387 if (G.flag_break_continue) {
4388 smallint fbc = G.flag_break_continue;
4389 /* We might fall into outer *loop*,
4390 * don't want to break it too */
4392 G.depth_break_continue--;
4393 if (G.depth_break_continue == 0)
4394 G.flag_break_continue = 0;
4395 /* else: e.g. "continue 2" should *break* once, *then* continue */
4396 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4397 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4398 goto check_jobs_and_break;
4399 /* "continue": simulate end of loop */
4404 #if ENABLE_HUSH_FUNCTIONS
4405 if (G.flag_return_in_progress == 1) {
4406 /* same as "goto check_jobs_and_break" */
4411 } else if (pi->followup == PIPE_BG) {
4412 /* What does bash do with attempts to background builtins? */
4413 /* even bash 3.2 doesn't do that well with nested bg:
4414 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4415 * I'm NOT treating inner &'s as jobs */
4416 check_and_run_traps(0);
4418 if (G.run_list_level == 1)
4421 G.last_exitcode = rcode = EXIT_SUCCESS;
4422 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4425 if (G.run_list_level == 1 && G_interactive_fd) {
4426 /* Waits for completion, then fg's main shell */
4427 rcode = checkjobs_and_fg_shell(pi);
4428 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4429 check_and_run_traps(0);
4432 { /* This one just waits for completion */
4433 rcode = checkjobs(pi);
4434 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4435 check_and_run_traps(0);
4437 G.last_exitcode = rcode;
4441 /* Analyze how result affects subsequent commands */
4443 if (rword == RES_IF || rword == RES_ELIF)
4446 #if ENABLE_HUSH_LOOPS
4447 /* Beware of "while false; true; do ..."! */
4448 if (pi->next && pi->next->res_word == RES_DO) {
4449 if (rword == RES_WHILE) {
4451 /* "while false; do...done" - exitcode 0 */
4452 G.last_exitcode = rcode = EXIT_SUCCESS;
4453 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4454 goto check_jobs_and_break;
4457 if (rword == RES_UNTIL) {
4459 debug_printf_exec(": until expr is true: breaking\n");
4460 check_jobs_and_break:
4468 check_jobs_and_continue:
4475 #if ENABLE_HUSH_LOOPS
4480 #if ENABLE_HUSH_CASE
4484 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4488 /* Select which version we will use */
4489 static int run_and_free_list(struct pipe *pi)
4492 debug_printf_exec("run_and_free_list entered\n");
4494 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4495 rcode = run_list(pi);
4497 /* free_pipe_list has the side effect of clearing memory.
4498 * In the long run that function can be merged with run_list,
4499 * but doing that now would hobble the debugging effort. */
4501 debug_printf_exec("run_and_free_list return %d\n", rcode);
4506 static struct pipe *new_pipe(void)
4509 pi = xzalloc(sizeof(struct pipe));
4510 /*pi->followup = 0; - deliberately invalid value */
4511 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4515 /* Command (member of a pipe) is complete, or we start a new pipe
4516 * if ctx->command is NULL.
4517 * No errors possible here.
4519 static int done_command(struct parse_context *ctx)
4521 /* The command is really already in the pipe structure, so
4522 * advance the pipe counter and make a new, null command. */
4523 struct pipe *pi = ctx->pipe;
4524 struct command *command = ctx->command;
4527 if (IS_NULL_CMD(command)) {
4528 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4532 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4533 //debug_print_tree(ctx->list_head, 20);
4535 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4538 /* Only real trickiness here is that the uncommitted
4539 * command structure is not counted in pi->num_cmds. */
4540 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4541 ctx->command = command = &pi->cmds[pi->num_cmds];
4543 memset(command, 0, sizeof(*command));
4544 return pi->num_cmds; /* used only for 0/nonzero check */
4547 static void done_pipe(struct parse_context *ctx, pipe_style type)
4551 debug_printf_parse("done_pipe entered, followup %d\n", type);
4552 /* Close previous command */
4553 not_null = done_command(ctx);
4554 ctx->pipe->followup = type;
4556 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4557 ctx->ctx_inverted = 0;
4558 ctx->pipe->res_word = ctx->ctx_res_w;
4561 /* Without this check, even just <enter> on command line generates
4562 * tree of three NOPs (!). Which is harmless but annoying.
4563 * IOW: it is safe to do it unconditionally. */
4566 || ctx->ctx_res_w == RES_FI
4568 #if ENABLE_HUSH_LOOPS
4569 || ctx->ctx_res_w == RES_DONE
4570 || ctx->ctx_res_w == RES_FOR
4571 || ctx->ctx_res_w == RES_IN
4573 #if ENABLE_HUSH_CASE
4574 || ctx->ctx_res_w == RES_ESAC
4578 debug_printf_parse("done_pipe: adding new pipe: "
4579 "not_null:%d ctx->ctx_res_w:%d\n",
4580 not_null, ctx->ctx_res_w);
4582 ctx->pipe->next = new_p;
4584 /* RES_THEN, RES_DO etc are "sticky" -
4585 * they remain set for pipes inside if/while.
4586 * This is used to control execution.
4587 * RES_FOR and RES_IN are NOT sticky (needed to support
4588 * cases where variable or value happens to match a keyword):
4590 #if ENABLE_HUSH_LOOPS
4591 if (ctx->ctx_res_w == RES_FOR
4592 || ctx->ctx_res_w == RES_IN)
4593 ctx->ctx_res_w = RES_NONE;
4595 #if ENABLE_HUSH_CASE
4596 if (ctx->ctx_res_w == RES_MATCH)
4597 ctx->ctx_res_w = RES_CASE_BODY;
4598 if (ctx->ctx_res_w == RES_CASE)
4599 ctx->ctx_res_w = RES_CASE_IN;
4601 ctx->command = NULL; /* trick done_command below */
4602 /* Create the memory for command, roughly:
4603 * ctx->pipe->cmds = new struct command;
4604 * ctx->command = &ctx->pipe->cmds[0];
4607 //debug_print_tree(ctx->list_head, 10);
4609 debug_printf_parse("done_pipe return\n");
4612 static void initialize_context(struct parse_context *ctx)
4614 memset(ctx, 0, sizeof(*ctx));
4615 ctx->pipe = ctx->list_head = new_pipe();
4616 /* Create the memory for command, roughly:
4617 * ctx->pipe->cmds = new struct command;
4618 * ctx->command = &ctx->pipe->cmds[0];
4623 /* If a reserved word is found and processed, parse context is modified
4624 * and 1 is returned.
4627 struct reserved_combo {
4630 unsigned char assignment_flag;
4634 FLAG_END = (1 << RES_NONE ),
4636 FLAG_IF = (1 << RES_IF ),
4637 FLAG_THEN = (1 << RES_THEN ),
4638 FLAG_ELIF = (1 << RES_ELIF ),
4639 FLAG_ELSE = (1 << RES_ELSE ),
4640 FLAG_FI = (1 << RES_FI ),
4642 #if ENABLE_HUSH_LOOPS
4643 FLAG_FOR = (1 << RES_FOR ),
4644 FLAG_WHILE = (1 << RES_WHILE),
4645 FLAG_UNTIL = (1 << RES_UNTIL),
4646 FLAG_DO = (1 << RES_DO ),
4647 FLAG_DONE = (1 << RES_DONE ),
4648 FLAG_IN = (1 << RES_IN ),
4650 #if ENABLE_HUSH_CASE
4651 FLAG_MATCH = (1 << RES_MATCH),
4652 FLAG_ESAC = (1 << RES_ESAC ),
4654 FLAG_START = (1 << RES_XXXX ),
4657 static const struct reserved_combo* match_reserved_word(o_string *word)
4659 /* Mostly a list of accepted follow-up reserved words.
4660 * FLAG_END means we are done with the sequence, and are ready
4661 * to turn the compound list into a command.
4662 * FLAG_START means the word must start a new compound list.
4664 static const struct reserved_combo reserved_list[] = {
4666 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4667 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4668 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4669 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4670 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4671 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4673 #if ENABLE_HUSH_LOOPS
4674 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4675 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4676 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4677 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4678 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4679 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4681 #if ENABLE_HUSH_CASE
4682 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4683 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4686 const struct reserved_combo *r;
4688 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4689 if (strcmp(word->data, r->literal) == 0)
4694 /* Return 0: not a keyword, 1: keyword
4696 static int reserved_word(o_string *word, struct parse_context *ctx)
4698 #if ENABLE_HUSH_CASE
4699 static const struct reserved_combo reserved_match = {
4700 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4703 const struct reserved_combo *r;
4707 r = match_reserved_word(word);
4711 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4712 #if ENABLE_HUSH_CASE
4713 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4714 /* "case word IN ..." - IN part starts first MATCH part */
4715 r = &reserved_match;
4718 if (r->flag == 0) { /* '!' */
4719 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4720 syntax_error("! ! command");
4721 ctx->ctx_res_w = RES_SNTX;
4723 ctx->ctx_inverted = 1;
4726 if (r->flag & FLAG_START) {
4727 struct parse_context *old;
4729 old = xmalloc(sizeof(*old));
4730 debug_printf_parse("push stack %p\n", old);
4731 *old = *ctx; /* physical copy */
4732 initialize_context(ctx);
4734 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4735 syntax_error_at(word->data);
4736 ctx->ctx_res_w = RES_SNTX;
4739 /* "{...} fi" is ok. "{...} if" is not
4741 * if { echo foo; } then { echo bar; } fi */
4742 if (ctx->command->group)
4743 done_pipe(ctx, PIPE_SEQ);
4746 ctx->ctx_res_w = r->res;
4747 ctx->old_flag = r->flag;
4748 word->o_assignment = r->assignment_flag;
4750 if (ctx->old_flag & FLAG_END) {
4751 struct parse_context *old;
4753 done_pipe(ctx, PIPE_SEQ);
4754 debug_printf_parse("pop stack %p\n", ctx->stack);
4756 old->command->group = ctx->list_head;
4757 old->command->cmd_type = CMD_NORMAL;
4759 o_addstr(&old->as_string, ctx->as_string.data);
4760 o_free_unsafe(&ctx->as_string);
4761 old->command->group_as_string = xstrdup(old->as_string.data);
4762 debug_printf_parse("pop, remembering as:'%s'\n",
4763 old->command->group_as_string);
4765 *ctx = *old; /* physical copy */
4772 /* Word is complete, look at it and update parsing context.
4773 * Normal return is 0. Syntax errors return 1.
4774 * Note: on return, word is reset, but not o_free'd!
4776 static int done_word(o_string *word, struct parse_context *ctx)
4778 struct command *command = ctx->command;
4780 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4781 if (word->length == 0 && word->o_quoted == 0) {
4782 debug_printf_parse("done_word return 0: true null, ignored\n");
4786 if (ctx->pending_redirect) {
4787 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4788 * only if run as "bash", not "sh" */
4789 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4791 * ...the word that follows the redirection operator
4792 * shall be subjected to tilde expansion, parameter expansion,
4793 * command substitution, arithmetic expansion, and quote
4794 * removal. Pathname expansion shall not be performed
4795 * on the word by a non-interactive shell; an interactive
4796 * shell may perform it, but shall do so only when
4797 * the expansion would result in one word."
4799 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4800 /* Cater for >\file case:
4801 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4802 * Same with heredocs:
4803 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4805 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4806 unbackslash(ctx->pending_redirect->rd_filename);
4807 /* Is it <<"HEREDOC"? */
4808 if (word->o_quoted) {
4809 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4812 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4813 ctx->pending_redirect = NULL;
4815 /* If this word wasn't an assignment, next ones definitely
4816 * can't be assignments. Even if they look like ones. */
4817 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4818 && word->o_assignment != WORD_IS_KEYWORD
4820 word->o_assignment = NOT_ASSIGNMENT;
4822 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4823 command->assignment_cnt++;
4824 word->o_assignment = MAYBE_ASSIGNMENT;
4828 # if ENABLE_HUSH_CASE
4829 if (ctx->ctx_dsemicolon
4830 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4832 /* already done when ctx_dsemicolon was set to 1: */
4833 /* ctx->ctx_res_w = RES_MATCH; */
4834 ctx->ctx_dsemicolon = 0;
4837 if (!command->argv /* if it's the first word... */
4838 # if ENABLE_HUSH_LOOPS
4839 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4840 && ctx->ctx_res_w != RES_IN
4842 # if ENABLE_HUSH_CASE
4843 && ctx->ctx_res_w != RES_CASE
4846 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4847 if (reserved_word(word, ctx)) {
4848 o_reset_to_empty_unquoted(word);
4849 debug_printf_parse("done_word return %d\n",
4850 (ctx->ctx_res_w == RES_SNTX));
4851 return (ctx->ctx_res_w == RES_SNTX);
4853 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4854 if (strcmp(word->data, "export") == 0
4855 # if ENABLE_HUSH_LOCAL
4856 || strcmp(word->data, "local") == 0
4859 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4862 # if ENABLE_HUSH_BASH_COMPAT
4863 if (strcmp(word->data, "[[") == 0) {
4864 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4870 if (command->group) {
4871 /* "{ echo foo; } echo bar" - bad */
4872 syntax_error_at(word->data);
4873 debug_printf_parse("done_word return 1: syntax error, "
4874 "groups and arglists don't mix\n");
4877 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4878 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4879 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4880 /* (otherwise it's known to be not empty and is already safe) */
4882 /* exclude "$@" - it can expand to no word despite "" */
4883 char *p = word->data;
4884 while (p[0] == SPECIAL_VAR_SYMBOL
4885 && (p[1] & 0x7f) == '@'
4886 && p[2] == SPECIAL_VAR_SYMBOL
4890 if (p == word->data || p[0] != '\0') {
4891 /* saw no "$@", or not only "$@" but some
4892 * real text is there too */
4893 /* insert "empty variable" reference, this makes
4894 * e.g. "", $empty"" etc to not disappear */
4895 o_addchr(word, SPECIAL_VAR_SYMBOL);
4896 o_addchr(word, SPECIAL_VAR_SYMBOL);
4899 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4900 debug_print_strings("word appended to argv", command->argv);
4903 #if ENABLE_HUSH_LOOPS
4904 if (ctx->ctx_res_w == RES_FOR) {
4906 || !is_well_formed_var_name(command->argv[0], '\0')
4908 /* bash says just "not a valid identifier" */
4909 syntax_error("not a valid identifier in for");
4912 /* Force FOR to have just one word (variable name) */
4913 /* NB: basically, this makes hush see "for v in ..."
4914 * syntax as if it is "for v; in ...". FOR and IN become
4915 * two pipe structs in parse tree. */
4916 done_pipe(ctx, PIPE_SEQ);
4919 #if ENABLE_HUSH_CASE
4920 /* Force CASE to have just one word */
4921 if (ctx->ctx_res_w == RES_CASE) {
4922 done_pipe(ctx, PIPE_SEQ);
4926 o_reset_to_empty_unquoted(word);
4928 debug_printf_parse("done_word return 0\n");
4933 /* Peek ahead in the input to find out if we have a "&n" construct,
4934 * as in "2>&1", that represents duplicating a file descriptor.
4936 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4937 * REDIRFD_SYNTAX_ERR if syntax error,
4938 * REDIRFD_TO_FILE if no & was seen,
4939 * or the number found.
4942 #define parse_redir_right_fd(as_string, input) \
4943 parse_redir_right_fd(input)
4945 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4951 return REDIRFD_TO_FILE;
4953 ch = i_getch(input); /* get the & */
4954 nommu_addchr(as_string, ch);
4957 ch = i_getch(input);
4958 nommu_addchr(as_string, ch);
4959 return REDIRFD_CLOSE;
4963 while (ch != EOF && isdigit(ch)) {
4964 d = d*10 + (ch-'0');
4966 ch = i_getch(input);
4967 nommu_addchr(as_string, ch);
4972 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4974 bb_error_msg("ambiguous redirect");
4975 return REDIRFD_SYNTAX_ERR;
4978 /* Return code is 0 normal, 1 if a syntax error is detected
4980 static int parse_redirect(struct parse_context *ctx,
4983 struct in_str *input)
4985 struct command *command = ctx->command;
4986 struct redir_struct *redir;
4987 struct redir_struct **redirp;
4990 dup_num = REDIRFD_TO_FILE;
4991 if (style != REDIRECT_HEREDOC) {
4992 /* Check for a '>&1' type redirect */
4993 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4994 if (dup_num == REDIRFD_SYNTAX_ERR)
4997 int ch = i_peek(input);
4998 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4999 if (dup_num) { /* <<-... */
5000 ch = i_getch(input);
5001 nommu_addchr(&ctx->as_string, ch);
5006 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5007 int ch = i_peek(input);
5009 /* >|FILE redirect ("clobbering" >).
5010 * Since we do not support "set -o noclobber" yet,
5011 * >| and > are the same for now. Just eat |.
5013 ch = i_getch(input);
5014 nommu_addchr(&ctx->as_string, ch);
5018 /* Create a new redir_struct and append it to the linked list */
5019 redirp = &command->redirects;
5020 while ((redir = *redirp) != NULL) {
5021 redirp = &(redir->next);
5023 *redirp = redir = xzalloc(sizeof(*redir));
5024 /* redir->next = NULL; */
5025 /* redir->rd_filename = NULL; */
5026 redir->rd_type = style;
5027 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5029 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5030 redir_table[style].descrip);
5032 redir->rd_dup = dup_num;
5033 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5034 /* Erik had a check here that the file descriptor in question
5035 * is legit; I postpone that to "run time"
5036 * A "-" representation of "close me" shows up as a -3 here */
5037 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5038 redir->rd_fd, redir->rd_dup);
5040 /* Set ctx->pending_redirect, so we know what to do at the
5041 * end of the next parsed word. */
5042 ctx->pending_redirect = redir;
5047 /* If a redirect is immediately preceded by a number, that number is
5048 * supposed to tell which file descriptor to redirect. This routine
5049 * looks for such preceding numbers. In an ideal world this routine
5050 * needs to handle all the following classes of redirects...
5051 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5052 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5053 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5054 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5056 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5058 * ... If n is quoted, the number shall not be recognized as part of
5059 * the redirection expression. For example:
5061 * writes the character 2 into file a"
5062 * We are getting it right by setting ->o_quoted on any \<char>
5064 * A -1 return means no valid number was found,
5065 * the caller should use the appropriate default for this redirection.
5067 static int redirect_opt_num(o_string *o)
5071 if (o->data == NULL)
5073 num = bb_strtou(o->data, NULL, 10);
5074 if (errno || num < 0)
5076 o_reset_to_empty_unquoted(o);
5081 #define fetch_till_str(as_string, input, word, skip_tabs) \
5082 fetch_till_str(input, word, skip_tabs)
5084 static char *fetch_till_str(o_string *as_string,
5085 struct in_str *input,
5089 o_string heredoc = NULL_O_STRING;
5095 ch = i_getch(input);
5096 nommu_addchr(as_string, ch);
5098 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5099 heredoc.data[past_EOL] = '\0';
5100 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5101 return heredoc.data;
5104 o_addchr(&heredoc, ch);
5105 past_EOL = heredoc.length;
5108 ch = i_getch(input);
5109 nommu_addchr(as_string, ch);
5110 } while (skip_tabs && ch == '\t');
5111 } while (ch == '\n');
5114 o_free_unsafe(&heredoc);
5117 o_addchr(&heredoc, ch);
5118 nommu_addchr(as_string, ch);
5122 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5123 * and load them all. There should be exactly heredoc_cnt of them.
5125 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5127 struct pipe *pi = ctx->list_head;
5129 while (pi && heredoc_cnt) {
5131 struct command *cmd = pi->cmds;
5133 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5135 cmd->argv ? cmd->argv[0] : "NONE");
5136 for (i = 0; i < pi->num_cmds; i++) {
5137 struct redir_struct *redir = cmd->redirects;
5139 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5140 i, cmd->argv ? cmd->argv[0] : "NONE");
5142 if (redir->rd_type == REDIRECT_HEREDOC) {
5145 redir->rd_type = REDIRECT_HEREDOC2;
5146 /* redir->rd_dup is (ab)used to indicate <<- */
5147 p = fetch_till_str(&ctx->as_string, input,
5148 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5150 syntax_error("unexpected EOF in here document");
5153 free(redir->rd_filename);
5154 redir->rd_filename = p;
5157 redir = redir->next;
5164 /* Should be 0. If it isn't, it's a parse error */
5166 bb_error_msg_and_die("heredoc BUG 2");
5172 #if ENABLE_HUSH_TICK
5173 static FILE *generate_stream_from_string(const char *s)
5176 int pid, channel[2];
5182 pid = BB_MMU ? fork() : vfork();
5184 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5186 if (pid == 0) { /* child */
5187 disable_restore_tty_pgrp_on_exit();
5188 /* Process substitution is not considered to be usual
5189 * 'command execution'.
5190 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5197 close(channel[0]); /* NB: close _first_, then move fd! */
5198 xmove_fd(channel[1], 1);
5199 /* Prevent it from trying to handle ctrl-z etc */
5200 IF_HUSH_JOB(G.run_list_level = 1;)
5201 /* Awful hack for `trap` or $(trap).
5203 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5204 * contains an example where "trap" is executed in a subshell:
5206 * save_traps=$(trap)
5208 * eval "$save_traps"
5210 * Standard does not say that "trap" in subshell shall print
5211 * parent shell's traps. It only says that its output
5212 * must have suitable form, but then, in the above example
5213 * (which is not supposed to be normative), it implies that.
5215 * bash (and probably other shell) does implement it
5216 * (traps are reset to defaults, but "trap" still shows them),
5217 * but as a result, "trap" logic is hopelessly messed up:
5220 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5221 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5222 * # true | trap <--- trap is in subshell - no output (ditto)
5223 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5224 * trap -- 'echo Ho' SIGWINCH
5225 * # echo `(trap)` <--- in subshell in subshell - output
5226 * trap -- 'echo Ho' SIGWINCH
5227 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5228 * trap -- 'echo Ho' SIGWINCH
5230 * The rules when to forget and when to not forget traps
5231 * get really complex and nonsensical.
5233 * Our solution: ONLY bare $(trap) or `trap` is special.
5235 s = skip_whitespace(s);
5236 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5238 static const char *const argv[] = { NULL, NULL };
5239 builtin_trap((char**)argv);
5240 exit(0); /* not _exit() - we need to fflush */
5243 reset_traps_to_defaults();
5244 parse_and_run_string(s);
5245 _exit(G.last_exitcode);
5247 /* We re-execute after vfork on NOMMU. This makes this script safe:
5248 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5249 * huge=`cat BIG` # was blocking here forever
5252 re_execute_shell(&to_free,
5261 #if ENABLE_HUSH_FAST
5263 //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);
5265 enable_restore_tty_pgrp_on_exit();
5270 pf = fdopen(channel[0], "r");
5274 /* Return code is exit status of the process that is run. */
5275 static int process_command_subs(o_string *dest, const char *s)
5278 struct in_str pipe_str;
5281 pf = generate_stream_from_string(s);
5284 close_on_exec_on(fileno(pf));
5286 /* Now send results of command back into original context */
5287 setup_file_in_str(&pipe_str, pf);
5289 while ((ch = i_getch(&pipe_str)) != EOF) {
5295 o_addchr(dest, '\n');
5298 o_addQchr(dest, ch);
5301 debug_printf("done reading from pipe, pclose()ing\n");
5302 /* Note: we got EOF, and we just close the read end of the pipe.
5303 * We do not wait for the `cmd` child to terminate. bash and ash do.
5305 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5306 * `false`; echo $? - bash outputs "1"
5309 debug_printf("closed FILE from child. return 0\n");
5314 static int parse_group(o_string *dest, struct parse_context *ctx,
5315 struct in_str *input, int ch)
5317 /* dest contains characters seen prior to ( or {.
5318 * Typically it's empty, but for function defs,
5319 * it contains function name (without '()'). */
5320 struct pipe *pipe_list;
5322 struct command *command = ctx->command;
5324 debug_printf_parse("parse_group entered\n");
5325 #if ENABLE_HUSH_FUNCTIONS
5326 if (ch == '(' && !dest->o_quoted) {
5328 if (done_word(dest, ctx))
5331 goto skip; /* (... */
5332 if (command->argv[1]) { /* word word ... (... */
5333 syntax_error_unexpected_ch('(');
5336 /* it is "word(..." or "word (..." */
5338 ch = i_getch(input);
5339 while (ch == ' ' || ch == '\t');
5341 syntax_error_unexpected_ch(ch);
5344 nommu_addchr(&ctx->as_string, ch);
5346 ch = i_getch(input);
5347 while (ch == ' ' || ch == '\t' || ch == '\n');
5349 syntax_error_unexpected_ch(ch);
5352 nommu_addchr(&ctx->as_string, ch);
5353 command->cmd_type = CMD_FUNCDEF;
5357 if (command->argv /* word [word]{... */
5358 || dest->length /* word{... */
5359 || dest->o_quoted /* ""{... */
5362 debug_printf_parse("parse_group return 1: "
5363 "syntax error, groups and arglists don't mix\n");
5367 #if ENABLE_HUSH_FUNCTIONS
5373 command->cmd_type = CMD_SUBSHELL;
5375 /* bash does not allow "{echo...", requires whitespace */
5376 ch = i_getch(input);
5377 if (ch != ' ' && ch != '\t' && ch != '\n') {
5378 syntax_error_unexpected_ch(ch);
5381 nommu_addchr(&ctx->as_string, ch);
5386 char *as_string = NULL;
5388 pipe_list = parse_stream(&as_string, input, endch);
5391 o_addstr(&ctx->as_string, as_string);
5393 /* empty ()/{} or parse error? */
5394 if (!pipe_list || pipe_list == ERR_PTR) {
5395 /* parse_stream already emitted error msg */
5399 debug_printf_parse("parse_group return 1: "
5400 "parse_stream returned %p\n", pipe_list);
5403 command->group = pipe_list;
5405 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5406 command->group_as_string = as_string;
5407 debug_printf_parse("end of group, remembering as:'%s'\n",
5408 command->group_as_string);
5411 debug_printf_parse("parse_group return 0\n");
5413 /* command remains "open", available for possible redirects */
5416 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5417 /* Subroutines for copying $(...) and `...` things */
5418 static void add_till_backquote(o_string *dest, struct in_str *input);
5420 static void add_till_single_quote(o_string *dest, struct in_str *input)
5423 int ch = i_getch(input);
5425 syntax_error_unterm_ch('\'');
5426 /*xfunc_die(); - redundant */
5433 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5434 static void add_till_double_quote(o_string *dest, struct in_str *input)
5437 int ch = i_getch(input);
5439 syntax_error_unterm_ch('"');
5440 /*xfunc_die(); - redundant */
5444 if (ch == '\\') { /* \x. Copy both chars. */
5446 ch = i_getch(input);
5450 add_till_backquote(dest, input);
5454 //if (ch == '$') ...
5457 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5459 * "Within the backquoted style of command substitution, backslash
5460 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5461 * The search for the matching backquote shall be satisfied by the first
5462 * backquote found without a preceding backslash; during this search,
5463 * if a non-escaped backquote is encountered within a shell comment,
5464 * a here-document, an embedded command substitution of the $(command)
5465 * form, or a quoted string, undefined results occur. A single-quoted
5466 * or double-quoted string that begins, but does not end, within the
5467 * "`...`" sequence produces undefined results."
5469 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5471 static void add_till_backquote(o_string *dest, struct in_str *input)
5474 int ch = i_getch(input);
5476 syntax_error_unterm_ch('`');
5477 /*xfunc_die(); - redundant */
5482 /* \x. Copy both chars unless it is \` */
5483 int ch2 = i_getch(input);
5485 syntax_error_unterm_ch('`');
5486 /*xfunc_die(); - redundant */
5488 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5495 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5496 * quoting and nested ()s.
5497 * "With the $(command) style of command substitution, all characters
5498 * following the open parenthesis to the matching closing parenthesis
5499 * constitute the command. Any valid shell script can be used for command,
5500 * except a script consisting solely of redirections which produces
5501 * unspecified results."
5503 * echo $(echo '(TEST)' BEST) (TEST) BEST
5504 * echo $(echo 'TEST)' BEST) TEST) BEST
5505 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5507 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5511 int ch = i_getch(input);
5513 syntax_error_unterm_ch(')');
5514 /*xfunc_die(); - redundant */
5522 if (i_peek(input) == ')') {
5530 add_till_single_quote(dest, input);
5535 add_till_double_quote(dest, input);
5540 /* \x. Copy verbatim. Important for \(, \) */
5541 ch = i_getch(input);
5543 syntax_error_unterm_ch(')');
5544 /*xfunc_die(); - redundant */
5551 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5553 /* Return code: 0 for OK, 1 for syntax error */
5555 #define handle_dollar(as_string, dest, input) \
5556 handle_dollar(dest, input)
5558 static int handle_dollar(o_string *as_string,
5560 struct in_str *input)
5562 int ch = i_peek(input); /* first character after the $ */
5563 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5565 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5567 ch = i_getch(input);
5568 nommu_addchr(as_string, ch);
5570 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5572 debug_printf_parse(": '%c'\n", ch);
5573 o_addchr(dest, ch | quote_mask);
5576 if (!isalnum(ch) && ch != '_')
5578 ch = i_getch(input);
5579 nommu_addchr(as_string, ch);
5581 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5582 } else if (isdigit(ch)) {
5584 ch = i_getch(input);
5585 nommu_addchr(as_string, ch);
5586 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5587 debug_printf_parse(": '%c'\n", ch);
5588 o_addchr(dest, ch | quote_mask);
5589 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5590 } else switch (ch) {
5592 case '!': /* last bg pid */
5593 case '?': /* last exit code */
5594 case '#': /* number of args */
5595 case '*': /* args */
5596 case '@': /* args */
5597 goto make_one_char_var;
5599 bool first_char, all_digits;
5602 ch = i_getch(input);
5603 nommu_addchr(as_string, ch);
5604 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5606 /* TODO: maybe someone will try to escape the '}' */
5611 ch = i_getch(input);
5612 nommu_addchr(as_string, ch);
5619 /* ${#var}: length of var contents */
5626 /* They're being verbose and doing ${?} */
5627 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5632 && ( (all_digits && !isdigit(ch))
5633 || (!all_digits && !isalnum(ch) && ch != '_')
5636 /* handle parameter expansions
5637 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5642 case ':': /* null modifier */
5643 if (expansion == 0) {
5644 debug_printf_parse(": null modifier\n");
5649 case '#': /* remove prefix */
5650 case '%': /* remove suffix */
5651 if (expansion == 0) {
5652 debug_printf_parse(": remove suffix/prefix\n");
5657 case '-': /* default value */
5658 case '=': /* assign default */
5659 case '+': /* alternative */
5660 case '?': /* error indicate */
5661 debug_printf_parse(": parameter expansion\n");
5666 syntax_error_unterm_str("${name}");
5667 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5672 debug_printf_parse(": '%c'\n", ch);
5673 o_addchr(dest, ch | quote_mask);
5677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5680 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5685 ch = i_getch(input);
5686 nommu_addchr(as_string, ch);
5687 # if ENABLE_SH_MATH_SUPPORT
5688 if (i_peek(input) == '(') {
5689 ch = i_getch(input);
5690 nommu_addchr(as_string, ch);
5691 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5692 o_addchr(dest, /*quote_mask |*/ '+');
5696 add_till_closing_paren(dest, input, true);
5699 o_addstr(as_string, dest->data + pos);
5700 o_addchr(as_string, ')');
5701 o_addchr(as_string, ')');
5704 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5708 # if ENABLE_HUSH_TICK
5709 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5710 o_addchr(dest, quote_mask | '`');
5714 add_till_closing_paren(dest, input, false);
5717 o_addstr(as_string, dest->data + pos);
5718 o_addchr(as_string, '`');
5721 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5727 ch = i_getch(input);
5728 nommu_addchr(as_string, ch);
5730 if (isalnum(ch)) { /* it's $_name or $_123 */
5735 /* TODO: $_ and $-: */
5736 /* $_ Shell or shell script name; or last argument of last command
5737 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5738 * but in command's env, set to full pathname used to invoke it */
5739 /* $- Option flags set by set builtin or shell options (-i etc) */
5741 o_addQchr(dest, '$');
5743 debug_printf_parse("handle_dollar return 0\n");
5748 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5749 parse_stream_dquoted(dest, input, dquote_end)
5751 static int parse_stream_dquoted(o_string *as_string,
5753 struct in_str *input,
5760 ch = i_getch(input);
5762 nommu_addchr(as_string, ch);
5763 if (ch == dquote_end) { /* may be only '"' or EOF */
5764 if (dest->o_assignment == NOT_ASSIGNMENT)
5765 dest->o_escape ^= 1;
5766 debug_printf_parse("parse_stream_dquoted return 0\n");
5769 /* note: can't move it above ch == dquote_end check! */
5771 syntax_error_unterm_ch('"');
5772 /*xfunc_die(); - redundant */
5776 next = i_peek(input);
5778 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5779 ch, ch, dest->o_escape);
5782 syntax_error("\\<eof>");
5786 * "The backslash retains its special meaning [in "..."]
5787 * only when followed by one of the following characters:
5788 * $, `, ", \, or <newline>. A double quote may be quoted
5789 * within double quotes by preceding it with a backslash."
5791 if (strchr("$`\"\\\n", next) != NULL) {
5792 ch = i_getch(input);
5794 o_addqchr(dest, ch);
5795 nommu_addchr(as_string, ch);
5798 o_addqchr(dest, '\\');
5799 nommu_addchr(as_string, '\\');
5804 if (handle_dollar(as_string, dest, input) != 0) {
5805 debug_printf_parse("parse_stream_dquoted return 1: "
5806 "handle_dollar returned non-0\n");
5811 #if ENABLE_HUSH_TICK
5813 //int pos = dest->length;
5814 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5815 o_addchr(dest, 0x80 | '`');
5816 add_till_backquote(dest, input);
5817 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5818 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5822 o_addQchr(dest, ch);
5824 && (dest->o_assignment == MAYBE_ASSIGNMENT
5825 || dest->o_assignment == WORD_IS_KEYWORD)
5826 && is_well_formed_var_name(dest->data, '=')
5828 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5834 * Scan input until EOF or end_trigger char.
5835 * Return a list of pipes to execute, or NULL on EOF
5836 * or if end_trigger character is met.
5837 * On syntax error, exit is shell is not interactive,
5838 * reset parsing machinery and start parsing anew,
5839 * or return ERR_PTR.
5841 static struct pipe *parse_stream(char **pstring,
5842 struct in_str *input,
5845 struct parse_context ctx;
5846 o_string dest = NULL_O_STRING;
5850 /* Double-quote state is handled in the state variable is_in_dquote.
5851 * A single-quote triggers a bypass of the main loop until its mate is
5852 * found. When recursing, quote state is passed in via dest->o_escape.
5854 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5855 end_trigger ? end_trigger : 'X');
5858 G.ifs = get_local_var_value("IFS");
5863 #if ENABLE_HUSH_INTERACTIVE
5864 input->promptmode = 0; /* PS1 */
5866 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5867 initialize_context(&ctx);
5872 const char *is_special;
5876 redir_type redir_style;
5879 /* dest.o_quoted = 1; - already is (see below) */
5880 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5883 /* We reached closing '"' */
5886 ch = i_getch(input);
5887 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5888 ch, ch, dest.o_escape);
5893 syntax_error_unterm_str("here document");
5896 /* end_trigger == '}' case errors out earlier,
5897 * checking only ')' */
5898 if (end_trigger == ')') {
5899 syntax_error_unterm_ch('('); /* exits */
5900 /* goto parse_error; */
5903 if (done_word(&dest, &ctx)) {
5907 done_pipe(&ctx, PIPE_SEQ);
5909 /* If we got nothing... */
5910 /* (this makes bare "&" cmd a no-op.
5911 * bash says: "syntax error near unexpected token '&'") */
5912 if (pi->num_cmds == 0
5913 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5919 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5921 *pstring = ctx.as_string.data;
5923 o_free_unsafe(&ctx.as_string);
5926 debug_printf_parse("parse_stream return %p\n", pi);
5929 nommu_addchr(&ctx.as_string, ch);
5930 is_ifs = strchr(G.ifs, ch);
5931 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5932 "\\$\"" IF_HUSH_TICK("`") /* always special */
5935 if (!is_special && !is_ifs) { /* ordinary char */
5937 o_addQchr(&dest, ch);
5938 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5939 || dest.o_assignment == WORD_IS_KEYWORD)
5941 && is_well_formed_var_name(dest.data, '=')
5943 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5949 if (done_word(&dest, &ctx)) {
5953 #if ENABLE_HUSH_CASE
5954 /* "case ... in <newline> word) ..." -
5955 * newlines are ignored (but ';' wouldn't be) */
5956 if (ctx.command->argv == NULL
5957 && ctx.ctx_res_w == RES_MATCH
5962 /* Treat newline as a command separator. */
5963 done_pipe(&ctx, PIPE_SEQ);
5964 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5966 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5971 dest.o_assignment = MAYBE_ASSIGNMENT;
5973 /* note: if (is_ifs) continue;
5974 * will still trigger for us */
5978 /* "cmd}" or "cmd }..." without semicolon or &:
5979 * } is an ordinary char in this case, even inside { cmd; }
5980 * Pathological example: { ""}; } should exec "}" cmd
5983 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5984 || dest.length != 0 /* word} */
5985 || dest.o_quoted /* ""} */
5989 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5990 goto skip_end_trigger;
5991 /* else: } does terminate a group */
5994 if (end_trigger && end_trigger == ch
5995 && (ch != ';' || heredoc_cnt == 0)
5996 #if ENABLE_HUSH_CASE
5998 || ctx.ctx_res_w != RES_MATCH
5999 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6004 /* This is technically valid:
6005 * { cat <<HERE; }; echo Ok
6009 * but we don't support this.
6010 * We require heredoc to be in enclosing {}/(),
6013 syntax_error_unterm_str("here document");
6016 if (done_word(&dest, &ctx)) {
6019 done_pipe(&ctx, PIPE_SEQ);
6020 dest.o_assignment = MAYBE_ASSIGNMENT;
6021 /* Do we sit outside of any if's, loops or case's? */
6023 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6027 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6029 *pstring = ctx.as_string.data;
6031 o_free_unsafe(&ctx.as_string);
6034 debug_printf_parse("parse_stream return %p: "
6035 "end_trigger char found\n",
6037 return ctx.list_head;
6046 next = i_peek(input);
6049 /* Catch <, > before deciding whether this word is
6050 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6053 redir_fd = redirect_opt_num(&dest);
6054 if (done_word(&dest, &ctx)) {
6057 redir_style = REDIRECT_OVERWRITE;
6059 redir_style = REDIRECT_APPEND;
6060 ch = i_getch(input);
6061 nommu_addchr(&ctx.as_string, ch);
6064 else if (next == '(') {
6065 syntax_error(">(process) not supported");
6069 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6071 continue; /* back to top of while (1) */
6073 redir_fd = redirect_opt_num(&dest);
6074 if (done_word(&dest, &ctx)) {
6077 redir_style = REDIRECT_INPUT;
6079 redir_style = REDIRECT_HEREDOC;
6081 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6082 ch = i_getch(input);
6083 nommu_addchr(&ctx.as_string, ch);
6084 } else if (next == '>') {
6085 redir_style = REDIRECT_IO;
6086 ch = i_getch(input);
6087 nommu_addchr(&ctx.as_string, ch);
6090 else if (next == '(') {
6091 syntax_error("<(process) not supported");
6095 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6097 continue; /* back to top of while (1) */
6100 if (dest.o_assignment == MAYBE_ASSIGNMENT
6101 /* check that we are not in word in "a=1 2>word b=1": */
6102 && !ctx.pending_redirect
6104 /* ch is a special char and thus this word
6105 * cannot be an assignment */
6106 dest.o_assignment = NOT_ASSIGNMENT;
6109 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6113 if (dest.length == 0) {
6116 if (ch == EOF || ch == '\n')
6119 /* note: we do not add it to &ctx.as_string */
6121 nommu_addchr(&ctx.as_string, '\n');
6123 o_addQchr(&dest, ch);
6128 syntax_error("\\<eof>");
6131 ch = i_getch(input);
6133 o_addchr(&dest, '\\');
6134 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6135 o_addchr(&dest, ch);
6136 nommu_addchr(&ctx.as_string, ch);
6137 /* Example: echo Hello \2>file
6138 * we need to know that word 2 is quoted */
6142 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6143 ctx.as_string.data[--ctx.as_string.length] = '\0';
6148 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6149 debug_printf_parse("parse_stream parse error: "
6150 "handle_dollar returned non-0\n");
6157 ch = i_getch(input);
6159 syntax_error_unterm_ch('\'');
6160 /*xfunc_die(); - redundant */
6162 nommu_addchr(&ctx.as_string, ch);
6165 o_addqchr(&dest, ch);
6170 is_in_dquote ^= 1; /* invert */
6171 if (dest.o_assignment == NOT_ASSIGNMENT)
6174 #if ENABLE_HUSH_TICK
6179 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6180 o_addchr(&dest, '`');
6184 add_till_backquote(&dest, input);
6186 o_addstr(&ctx.as_string, dest.data + pos);
6187 o_addchr(&ctx.as_string, '`');
6189 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6190 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6195 #if ENABLE_HUSH_CASE
6198 if (done_word(&dest, &ctx)) {
6201 done_pipe(&ctx, PIPE_SEQ);
6202 #if ENABLE_HUSH_CASE
6203 /* Eat multiple semicolons, detect
6204 * whether it means something special */
6209 ch = i_getch(input);
6210 nommu_addchr(&ctx.as_string, ch);
6211 if (ctx.ctx_res_w == RES_CASE_BODY) {
6212 ctx.ctx_dsemicolon = 1;
6213 ctx.ctx_res_w = RES_MATCH;
6219 /* We just finished a cmd. New one may start
6220 * with an assignment */
6221 dest.o_assignment = MAYBE_ASSIGNMENT;
6224 if (done_word(&dest, &ctx)) {
6228 ch = i_getch(input);
6229 nommu_addchr(&ctx.as_string, ch);
6230 done_pipe(&ctx, PIPE_AND);
6232 done_pipe(&ctx, PIPE_BG);
6236 if (done_word(&dest, &ctx)) {
6239 #if ENABLE_HUSH_CASE
6240 if (ctx.ctx_res_w == RES_MATCH)
6241 break; /* we are in case's "word | word)" */
6243 if (next == '|') { /* || */
6244 ch = i_getch(input);
6245 nommu_addchr(&ctx.as_string, ch);
6246 done_pipe(&ctx, PIPE_OR);
6248 /* we could pick up a file descriptor choice here
6249 * with redirect_opt_num(), but bash doesn't do it.
6250 * "echo foo 2| cat" yields "foo 2". */
6255 #if ENABLE_HUSH_CASE
6256 /* "case... in [(]word)..." - skip '(' */
6257 if (ctx.ctx_res_w == RES_MATCH
6258 && ctx.command->argv == NULL /* not (word|(... */
6259 && dest.length == 0 /* not word(... */
6260 && dest.o_quoted == 0 /* not ""(... */
6266 if (parse_group(&dest, &ctx, input, ch) != 0) {
6271 #if ENABLE_HUSH_CASE
6272 if (ctx.ctx_res_w == RES_MATCH)
6276 /* proper use of this character is caught by end_trigger:
6277 * if we see {, we call parse_group(..., end_trigger='}')
6278 * and it will match } earlier (not here). */
6279 syntax_error_unexpected_ch(ch);
6283 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6289 struct parse_context *pctx;
6290 IF_HAS_KEYWORDS(struct parse_context *p2;)
6292 /* Clean up allocated tree.
6293 * Sample for finding leaks on syntax error recovery path.
6294 * Run it from interactive shell, watch pmap `pidof hush`.
6295 * while if false; then false; fi; do break; fi
6296 * Samples to catch leaks at execution:
6297 * while if (true | {true;}); then echo ok; fi; do break; done
6298 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6302 /* Update pipe/command counts,
6303 * otherwise freeing may miss some */
6304 done_pipe(pctx, PIPE_SEQ);
6305 debug_printf_clean("freeing list %p from ctx %p\n",
6306 pctx->list_head, pctx);
6307 debug_print_tree(pctx->list_head, 0);
6308 free_pipe_list(pctx->list_head);
6309 debug_printf_clean("freed list %p\n", pctx->list_head);
6311 o_free_unsafe(&pctx->as_string);
6313 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6317 IF_HAS_KEYWORDS(pctx = p2;)
6318 } while (HAS_KEYWORDS && pctx);
6319 /* Free text, clear all dest fields */
6321 /* If we are not in top-level parse, we return,
6322 * our caller will propagate error.
6324 if (end_trigger != ';') {
6332 /* Discard cached input, force prompt */
6334 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6339 /* Executing from string: eval, sh -c '...'
6340 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6341 * end_trigger controls how often we stop parsing
6342 * NUL: parse all, execute, return
6343 * ';': parse till ';' or newline, execute, repeat till EOF
6345 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6348 struct pipe *pipe_list;
6350 pipe_list = parse_stream(NULL, inp, end_trigger);
6351 if (!pipe_list) /* EOF */
6353 debug_print_tree(pipe_list, 0);
6354 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6355 run_and_free_list(pipe_list);
6359 static void parse_and_run_string(const char *s)
6361 struct in_str input;
6362 setup_string_in_str(&input, s);
6363 parse_and_run_stream(&input, '\0');
6366 static void parse_and_run_file(FILE *f)
6368 struct in_str input;
6369 setup_file_in_str(&input, f);
6370 parse_and_run_stream(&input, ';');
6373 /* Called a few times only (or even once if "sh -c") */
6374 static void block_signals(int second_time)
6379 mask = (1 << SIGQUIT);
6380 if (G_interactive_fd) {
6381 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6382 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6383 mask |= SPECIAL_JOB_SIGS;
6385 G.non_DFL_mask = mask;
6388 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6392 sigaddset(&G.blocked_set, sig);
6396 sigdelset(&G.blocked_set, SIGCHLD);
6398 sigprocmask(SIG_SETMASK, &G.blocked_set,
6399 second_time ? NULL : &G.inherited_set);
6400 /* POSIX allows shell to re-enable SIGCHLD
6401 * even if it was SIG_IGN on entry */
6402 #if ENABLE_HUSH_FAST
6403 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6405 signal(SIGCHLD, SIGCHLD_handler);
6408 signal(SIGCHLD, SIG_DFL);
6414 static void maybe_set_to_sigexit(int sig)
6416 void (*handler)(int);
6417 /* non_DFL_mask'ed signals are, well, masked,
6418 * no need to set handler for them.
6420 if (!((G.non_DFL_mask >> sig) & 1)) {
6421 handler = signal(sig, sigexit);
6422 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6423 signal(sig, handler);
6426 /* Set handlers to restore tty pgrp and exit */
6427 static void set_fatal_handlers(void)
6429 /* We _must_ restore tty pgrp on fatal signals */
6431 maybe_set_to_sigexit(SIGILL );
6432 maybe_set_to_sigexit(SIGFPE );
6433 maybe_set_to_sigexit(SIGBUS );
6434 maybe_set_to_sigexit(SIGSEGV);
6435 maybe_set_to_sigexit(SIGTRAP);
6436 } /* else: hush is perfect. what SEGV? */
6437 maybe_set_to_sigexit(SIGABRT);
6438 /* bash 3.2 seems to handle these just like 'fatal' ones */
6439 maybe_set_to_sigexit(SIGPIPE);
6440 maybe_set_to_sigexit(SIGALRM);
6441 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6442 * if we aren't interactive... but in this case
6443 * we never want to restore pgrp on exit, and this fn is not called */
6444 /*maybe_set_to_sigexit(SIGHUP );*/
6445 /*maybe_set_to_sigexit(SIGTERM);*/
6446 /*maybe_set_to_sigexit(SIGINT );*/
6450 static int set_mode(const char cstate, const char mode)
6452 int state = (cstate == '-' ? 1 : 0);
6454 case 'n': G.fake_mode = state; break;
6455 case 'x': /*G.debug_mode = state;*/ break;
6456 default: return EXIT_FAILURE;
6458 return EXIT_SUCCESS;
6461 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6462 int hush_main(int argc, char **argv)
6464 static const struct variable const_shell_ver = {
6466 .varstr = (char*)hush_version_str,
6467 .max_len = 1, /* 0 can provoke free(name) */
6471 int signal_mask_is_inited = 0;
6473 unsigned builtin_argc;
6475 struct variable *cur_var;
6478 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6479 G.last_exitcode = EXIT_SUCCESS;
6481 G.argv0_for_re_execing = argv[0];
6483 /* Deal with HUSH_VERSION */
6484 G.shell_ver = const_shell_ver; /* copying struct here */
6485 G.top_var = &G.shell_ver;
6486 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6487 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6488 /* Initialize our shell local variables with the values
6489 * currently living in the environment */
6490 cur_var = G.top_var;
6493 char *value = strchr(*e, '=');
6494 if (value) { /* paranoia */
6495 cur_var->next = xzalloc(sizeof(*cur_var));
6496 cur_var = cur_var->next;
6497 cur_var->varstr = *e;
6498 cur_var->max_len = strlen(*e);
6499 cur_var->flg_export = 1;
6503 /* reinstate HUSH_VERSION */
6504 debug_printf_env("putenv '%s'\n", hush_version_str);
6505 putenv((char *)hush_version_str);
6508 set_pwd_var(/*exp:*/ 1);
6509 /* bash also exports SHLVL and _,
6510 * and sets (but doesn't export) the following variables:
6512 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6513 * BASH_VERSION='3.2.0(1)-release'
6515 * MACHTYPE=i386-pc-linux-gnu
6517 * HOSTNAME=<xxxxxxxxxx>
6518 * PPID=<NNNNN> - we also do it elsewhere
6529 * PIPESTATUS=([0]="0")
6530 * HISTFILE=/<xxx>/.bash_history
6534 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6536 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6546 #if ENABLE_FEATURE_EDITING
6547 G.line_input_state = new_line_input_t(FOR_SHELL);
6549 G.global_argc = argc;
6550 G.global_argv = argv;
6551 /* Initialize some more globals to non-zero values */
6552 cmdedit_update_prompt();
6554 if (setjmp(die_jmp)) {
6555 /* xfunc has failed! die die die */
6556 /* no EXIT traps, this is an escape hatch! */
6558 hush_exit(xfunc_error_retval);
6561 /* Shell is non-interactive at first. We need to call
6562 * block_signals(0) if we are going to execute "sh <script>",
6563 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6564 * If we later decide that we are interactive, we run block_signals(0)
6565 * (or re-run block_signals(1) if we ran block_signals(0) before)
6566 * in order to intercept (more) signals.
6570 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6573 opt = getopt(argc, argv, "+c:xins"
6576 # if ENABLE_HUSH_FUNCTIONS
6586 * sh ... -c 'script'
6587 * sh ... -c 'script' ARG0 [ARG1...]
6588 * On NOMMU, if builtin_argc != 0,
6589 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6590 * "" needs to be replaced with NULL
6591 * and BARGV vector fed to builtin function.
6592 * Note: this form never happens:
6593 * sh ... -c 'builtin' [BARGV...] ""
6596 G.root_pid = getpid();
6597 G.root_ppid = getppid();
6599 G.global_argv = argv + optind;
6600 G.global_argc = argc - optind;
6602 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6603 const struct built_in_command *x;
6605 block_signals(0); /* 0: called 1st time */
6606 x = find_builtin(optarg);
6607 if (x) { /* paranoia */
6608 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6609 G.global_argv += builtin_argc;
6610 G.global_argv[-1] = NULL; /* replace "" */
6611 G.last_exitcode = x->function(argv + optind - 1);
6615 if (!G.global_argv[0]) {
6616 /* -c 'script' (no params): prevent empty $0 */
6617 G.global_argv--; /* points to argv[i] of 'script' */
6618 G.global_argv[0] = argv[0];
6620 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6621 block_signals(0); /* 0: called 1st time */
6622 parse_and_run_string(optarg);
6625 /* Well, we cannot just declare interactiveness,
6626 * we have to have some stuff (ctty, etc) */
6627 /* G_interactive_fd++; */
6630 /* "-s" means "read from stdin", but this is how we always
6631 * operate, so simply do nothing here. */
6634 case '<': /* "big heredoc" support */
6635 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6638 G.root_pid = bb_strtou(optarg, &optarg, 16);
6640 G.root_ppid = bb_strtou(optarg, &optarg, 16);
6642 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6644 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6646 builtin_argc = bb_strtou(optarg, &optarg, 16);
6647 # if ENABLE_HUSH_LOOPS
6649 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6654 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6656 # if ENABLE_HUSH_FUNCTIONS
6658 struct function *funcp = new_function(optarg);
6659 /* funcp->name is already set to optarg */
6660 /* funcp->body is set to NULL. It's a special case. */
6661 funcp->body_as_string = argv[optind];
6669 if (!set_mode('-', opt))
6673 fprintf(stderr, "Usage: sh [FILE]...\n"
6674 " or: sh -c command [args]...\n\n");
6680 } /* option parsing loop */
6683 G.root_pid = getpid();
6684 G.root_ppid = getppid();
6687 /* If we are login shell... */
6688 if (argv[0] && argv[0][0] == '-') {
6690 debug_printf("sourcing /etc/profile\n");
6691 input = fopen_for_read("/etc/profile");
6692 if (input != NULL) {
6693 close_on_exec_on(fileno(input));
6694 block_signals(0); /* 0: called 1st time */
6695 signal_mask_is_inited = 1;
6696 parse_and_run_file(input);
6699 /* bash: after sourcing /etc/profile,
6700 * tries to source (in the given order):
6701 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6702 * stopping on first found. --noprofile turns this off.
6703 * bash also sources ~/.bash_logout on exit.
6704 * If called as sh, skips .bash_XXX files.
6711 * "bash <script>" (which is never interactive (unless -i?))
6712 * sources $BASH_ENV here (without scanning $PATH).
6713 * If called as sh, does the same but with $ENV.
6715 debug_printf("running script '%s'\n", argv[optind]);
6716 G.global_argv = argv + optind;
6717 G.global_argc = argc - optind;
6718 input = xfopen_for_read(argv[optind]);
6719 close_on_exec_on(fileno(input));
6720 if (!signal_mask_is_inited)
6721 block_signals(0); /* 0: called 1st time */
6722 parse_and_run_file(input);
6723 #if ENABLE_FEATURE_CLEAN_UP
6729 /* Up to here, shell was non-interactive. Now it may become one.
6730 * NB: don't forget to (re)run block_signals(0/1) as needed.
6733 /* A shell is interactive if the '-i' flag was given,
6734 * or if all of the following conditions are met:
6736 * no arguments remaining or the -s flag given
6737 * standard input is a terminal
6738 * standard output is a terminal
6739 * Refer to Posix.2, the description of the 'sh' utility.
6742 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6743 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6744 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6745 if (G_saved_tty_pgrp < 0)
6746 G_saved_tty_pgrp = 0;
6748 /* try to dup stdin to high fd#, >= 255 */
6749 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6750 if (G_interactive_fd < 0) {
6751 /* try to dup to any fd */
6752 G_interactive_fd = dup(STDIN_FILENO);
6753 if (G_interactive_fd < 0) {
6755 G_interactive_fd = 0;
6756 G_saved_tty_pgrp = 0;
6759 // TODO: track & disallow any attempts of user
6760 // to (inadvertently) close/redirect G_interactive_fd
6762 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6763 if (G_interactive_fd) {
6764 close_on_exec_on(G_interactive_fd);
6766 if (G_saved_tty_pgrp) {
6767 /* If we were run as 'hush &', sleep until we are
6768 * in the foreground (tty pgrp == our pgrp).
6769 * If we get started under a job aware app (like bash),
6770 * make sure we are now in charge so we don't fight over
6771 * who gets the foreground */
6773 pid_t shell_pgrp = getpgrp();
6774 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6775 if (G_saved_tty_pgrp == shell_pgrp)
6777 /* send TTIN to ourself (should stop us) */
6778 kill(- shell_pgrp, SIGTTIN);
6782 /* Block some signals */
6783 block_signals(signal_mask_is_inited);
6785 if (G_saved_tty_pgrp) {
6786 /* Set other signals to restore saved_tty_pgrp */
6787 set_fatal_handlers();
6788 /* Put ourselves in our own process group
6789 * (bash, too, does this only if ctty is available) */
6790 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6791 /* Grab control of the terminal */
6792 tcsetpgrp(G_interactive_fd, getpid());
6794 /* -1 is special - makes xfuncs longjmp, not exit
6795 * (we reset die_sleep = 0 whereever we [v]fork) */
6796 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6797 } else if (!signal_mask_is_inited) {
6798 block_signals(0); /* 0: called 1st time */
6799 } /* else: block_signals(0) was done before */
6800 #elif ENABLE_HUSH_INTERACTIVE
6801 /* No job control compiled in, only prompt/line editing */
6802 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6803 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6804 if (G_interactive_fd < 0) {
6805 /* try to dup to any fd */
6806 G_interactive_fd = dup(STDIN_FILENO);
6807 if (G_interactive_fd < 0)
6809 G_interactive_fd = 0;
6812 if (G_interactive_fd) {
6813 close_on_exec_on(G_interactive_fd);
6814 block_signals(signal_mask_is_inited);
6815 } else if (!signal_mask_is_inited) {
6819 /* We have interactiveness code disabled */
6820 if (!signal_mask_is_inited) {
6825 * if interactive but not a login shell, sources ~/.bashrc
6826 * (--norc turns this off, --rcfile <file> overrides)
6829 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6830 /* note: ash and hush share this string */
6831 printf("\n\n%s %s\n"
6832 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
6835 "hush - the humble shell"
6839 parse_and_run_file(stdin);
6842 #if ENABLE_FEATURE_CLEAN_UP
6843 if (G.cwd != bb_msg_unknown)
6845 cur_var = G.top_var->next;
6847 struct variable *tmp = cur_var;
6848 if (!cur_var->max_len)
6849 free(cur_var->varstr);
6850 cur_var = cur_var->next;
6854 hush_exit(G.last_exitcode);
6859 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6860 int lash_main(int argc, char **argv)
6862 bb_error_msg("lash is deprecated, please use hush instead");
6863 return hush_main(argc, argv);
6868 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6869 int msh_main(int argc, char **argv)
6871 //bb_error_msg("msh is deprecated, please use hush instead");
6872 return hush_main(argc, argv);
6880 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6885 static int FAST_FUNC builtin_test(char **argv)
6892 return test_main(argc, argv - argc);
6895 static int FAST_FUNC builtin_echo(char **argv)
6902 return echo_main(argc, argv - argc);
6905 static int FAST_FUNC builtin_eval(char **argv)
6907 int rcode = EXIT_SUCCESS;
6910 char *str = expand_strvec_to_string(argv);
6912 * eval "echo Hi; done" ("done" is syntax error):
6913 * "echo Hi" will not execute too.
6915 parse_and_run_string(str);
6917 rcode = G.last_exitcode;
6922 static int FAST_FUNC builtin_cd(char **argv)
6924 const char *newdir = argv[1];
6925 if (newdir == NULL) {
6926 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6927 * bash says "bash: cd: HOME not set" and does nothing
6930 const char *home = get_local_var_value("HOME");
6931 newdir = home ? home : "/";
6933 if (chdir(newdir)) {
6934 /* Mimic bash message exactly */
6935 bb_perror_msg("cd: %s", newdir);
6936 return EXIT_FAILURE;
6938 /* Read current dir (get_cwd(1) is inside) and set PWD.
6939 * Note: do not enforce exporting. If PWD was unset or unexported,
6940 * set it again, but do not export. bash does the same.
6942 set_pwd_var(/*exp:*/ 0);
6943 return EXIT_SUCCESS;
6946 static int FAST_FUNC builtin_exec(char **argv)
6948 if (*++argv == NULL)
6949 return EXIT_SUCCESS; /* bash does this */
6954 /* TODO: if exec fails, bash does NOT exit! We do... */
6955 pseudo_exec_argv(&dummy, argv, 0, NULL);
6960 static int FAST_FUNC builtin_exit(char **argv)
6962 debug_printf_exec("%s()\n", __func__);
6964 /* interactive bash:
6965 * # trap "echo EEE" EXIT
6968 * There are stopped jobs.
6969 * (if there are _stopped_ jobs, running ones don't count)
6972 # EEE (then bash exits)
6974 * we can use G.exiting = -1 as indicator "last cmd was exit"
6977 /* note: EXIT trap is run by hush_exit */
6978 if (*++argv == NULL)
6979 hush_exit(G.last_exitcode);
6980 /* mimic bash: exit 123abc == exit 255 + error msg */
6981 xfunc_error_retval = 255;
6982 /* bash: exit -2 == exit 254, no error msg */
6983 hush_exit(xatoi(*argv) & 0xff);
6986 static void print_escaped(const char *s)
6991 const char *p = strchrnul(s, '\'');
6992 /* print 'xxxx', possibly just '' */
6993 printf("'%.*s'", (int)(p - s), s);
6998 /* s points to '; print "'''...'''" */
7000 do putchar('\''); while (*++s == '\'');
7005 #if !ENABLE_HUSH_LOCAL
7006 #define helper_export_local(argv, exp, lvl) \
7007 helper_export_local(argv, exp)
7009 static void helper_export_local(char **argv, int exp, int lvl)
7014 /* So far we do not check that name is valid (TODO?) */
7016 if (strchr(name, '=') == NULL) {
7017 struct variable *var;
7019 var = get_local_var(name);
7020 if (exp == -1) { /* unexporting? */
7021 /* export -n NAME (without =VALUE) */
7023 var->flg_export = 0;
7024 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7026 } /* else: export -n NOT_EXISTING_VAR: no-op */
7029 if (exp == 1) { /* exporting? */
7030 /* export NAME (without =VALUE) */
7032 var->flg_export = 1;
7033 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7034 putenv(var->varstr);
7038 /* Exporting non-existing variable.
7039 * bash does not put it in environment,
7040 * but remembers that it is exported,
7041 * and does put it in env when it is set later.
7042 * We just set it to "" and export. */
7043 /* Or, it's "local NAME" (without =VALUE).
7044 * bash sets the value to "". */
7045 name = xasprintf("%s=", name);
7047 /* (Un)exporting/making local NAME=VALUE */
7048 name = xstrdup(name);
7050 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7054 static int FAST_FUNC builtin_export(char **argv)
7056 unsigned opt_unexport;
7058 #if ENABLE_HUSH_EXPORT_N
7059 /* "!": do not abort on errors */
7060 opt_unexport = getopt32(argv, "!n");
7061 if (opt_unexport == (uint32_t)-1)
7062 return EXIT_FAILURE;
7069 if (argv[0] == NULL) {
7076 /* ash emits: export VAR='VAL'
7077 * bash: declare -x VAR="VAL"
7078 * we follow ash example */
7079 const char *s = *e++;
7080 const char *p = strchr(s, '=');
7082 if (!p) /* wtf? take next variable */
7085 printf("export %.*s", (int)(p - s) + 1, s);
7086 print_escaped(p + 1);
7090 /*fflush(stdout); - done after each builtin anyway */
7092 return EXIT_SUCCESS;
7095 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7097 return EXIT_SUCCESS;
7100 #if ENABLE_HUSH_LOCAL
7101 static int FAST_FUNC builtin_local(char **argv)
7103 if (G.func_nest_level == 0) {
7104 bb_error_msg("%s: not in a function", argv[0]);
7105 return EXIT_FAILURE; /* bash compat */
7107 helper_export_local(argv, 0, G.func_nest_level);
7108 return EXIT_SUCCESS;
7112 static int FAST_FUNC builtin_trap(char **argv)
7118 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7123 /* No args: print all trapped */
7124 for (i = 0; i < NSIG; ++i) {
7127 print_escaped(G.traps[i]);
7128 /* note: bash adds "SIG", but only if invoked
7129 * as "bash". If called as "sh", or if set -o posix,
7130 * then it prints short signal names.
7131 * We are printing short names: */
7132 printf(" %s\n", get_signame(i));
7135 /*fflush(stdout); - done after each builtin anyway */
7136 return EXIT_SUCCESS;
7140 /* If first arg is a number: reset all specified signals */
7141 sig = bb_strtou(*argv, NULL, 10);
7147 sig = get_signum(*argv++);
7148 if (sig < 0 || sig >= NSIG) {
7150 /* Mimic bash message exactly */
7151 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7156 G.traps[sig] = xstrdup(new_cmd);
7158 debug_printf("trap: setting SIG%s (%i) to '%s'",
7159 get_signame(sig), sig, G.traps[sig]);
7161 /* There is no signal for 0 (EXIT) */
7166 sigaddset(&G.blocked_set, sig);
7168 /* There was a trap handler, we are removing it
7169 * (if sig has non-DFL handling,
7170 * we don't need to do anything) */
7171 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7173 sigdelset(&G.blocked_set, sig);
7176 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7180 if (!argv[1]) { /* no second arg */
7181 bb_error_msg("trap: invalid arguments");
7182 return EXIT_FAILURE;
7185 /* First arg is "-": reset all specified to default */
7186 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7187 /* Everything else: set arg as signal handler
7188 * (includes "" case, which ignores signal) */
7189 if (argv[0][0] == '-') {
7190 if (argv[0][1] == '\0') { /* "-" */
7191 /* new_cmd remains NULL: "reset these sigs" */
7194 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7197 /* else: "-something", no special meaning */
7202 goto process_sig_list;
7205 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7206 static int FAST_FUNC builtin_type(char **argv)
7208 int ret = EXIT_SUCCESS;
7214 if (0) {} /* make conditional compile easier below */
7215 /*else if (find_alias(*argv))
7216 type = "an alias";*/
7217 #if ENABLE_HUSH_FUNCTIONS
7218 else if (find_function(*argv))
7219 type = "a function";
7221 else if (find_builtin(*argv))
7222 type = "a shell builtin";
7223 else if ((path = find_in_path(*argv)) != NULL)
7226 bb_error_msg("type: %s: not found", *argv);
7231 printf("%s is %s\n", *argv, type);
7239 /* built-in 'fg' and 'bg' handler */
7240 static int FAST_FUNC builtin_fg_bg(char **argv)
7245 if (!G_interactive_fd)
7246 return EXIT_FAILURE;
7248 /* If they gave us no args, assume they want the last backgrounded task */
7250 for (pi = G.job_list; pi; pi = pi->next) {
7251 if (pi->jobid == G.last_jobid) {
7255 bb_error_msg("%s: no current job", argv[0]);
7256 return EXIT_FAILURE;
7258 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7259 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7260 return EXIT_FAILURE;
7262 for (pi = G.job_list; pi; pi = pi->next) {
7263 if (pi->jobid == jobnum) {
7267 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7268 return EXIT_FAILURE;
7270 /* TODO: bash prints a string representation
7271 * of job being foregrounded (like "sleep 1 | cat") */
7272 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7273 /* Put the job into the foreground. */
7274 tcsetpgrp(G_interactive_fd, pi->pgrp);
7277 /* Restart the processes in the job */
7278 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7279 for (i = 0; i < pi->num_cmds; i++) {
7280 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7281 pi->cmds[i].is_stopped = 0;
7283 pi->stopped_cmds = 0;
7285 i = kill(- pi->pgrp, SIGCONT);
7287 if (errno == ESRCH) {
7288 delete_finished_bg_job(pi);
7289 return EXIT_SUCCESS;
7291 bb_perror_msg("kill (SIGCONT)");
7294 if (argv[0][0] == 'f') {
7296 return checkjobs_and_fg_shell(pi);
7298 return EXIT_SUCCESS;
7302 #if ENABLE_HUSH_HELP
7303 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7305 const struct built_in_command *x;
7308 "Built-in commands:\n"
7309 "------------------\n");
7310 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7312 printf("%s\t%s\n", x->cmd, x->descr);
7315 return EXIT_SUCCESS;
7320 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7323 const char *status_string;
7325 for (job = G.job_list; job; job = job->next) {
7326 if (job->alive_cmds == job->stopped_cmds)
7327 status_string = "Stopped";
7329 status_string = "Running";
7331 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7333 return EXIT_SUCCESS;
7338 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7343 #ifdef M_TRIM_THRESHOLD
7344 /* Optional. Reduces probability of false positives */
7347 /* Crude attempt to find where "free memory" starts,
7348 * sans fragmentation. */
7350 l = (unsigned long)p;
7353 if (l < (unsigned long)p) l = (unsigned long)p;
7356 if (!G.memleak_value)
7357 G.memleak_value = l;
7359 l -= G.memleak_value;
7366 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7371 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7374 return EXIT_SUCCESS;
7377 static int FAST_FUNC builtin_read(char **argv)
7380 const char *name = "REPLY";
7384 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7385 * and _after_ that_ it will complain */
7386 if (!is_well_formed_var_name(name, '\0')) {
7387 /* Mimic bash message */
7388 bb_error_msg("read: '%s': not a valid identifier", name);
7393 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7395 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7396 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7399 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7400 * built-in 'set' handler
7402 * set [-abCefhmnuvx] [-o option] [argument...]
7403 * set [+abCefhmnuvx] [+o option] [argument...]
7404 * set -- [argument...]
7407 * Implementations shall support the options in both their hyphen and
7408 * plus-sign forms. These options can also be specified as options to sh.
7410 * Write out all variables and their values: set
7411 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7412 * Turn on the -x and -v options: set -xv
7413 * Unset all positional parameters: set --
7414 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7415 * Set the positional parameters to the expansion of x, even if x expands
7416 * with a leading '-' or '+': set -- $x
7418 * So far, we only support "set -- [argument...]" and some of the short names.
7420 static int FAST_FUNC builtin_set(char **argv)
7423 char **pp, **g_argv;
7424 char *arg = *++argv;
7428 for (e = G.top_var; e; e = e->next)
7430 return EXIT_SUCCESS;
7434 if (!strcmp(arg, "--")) {
7438 if (arg[0] != '+' && arg[0] != '-')
7440 for (n = 1; arg[n]; ++n)
7441 if (set_mode(arg[0], arg[n]))
7443 } while ((arg = *++argv) != NULL);
7444 /* Now argv[0] is 1st argument */
7447 return EXIT_SUCCESS;
7450 /* NB: G.global_argv[0] ($0) is never freed/changed */
7451 g_argv = G.global_argv;
7452 if (G.global_args_malloced) {
7458 G.global_args_malloced = 1;
7459 pp = xzalloc(sizeof(pp[0]) * 2);
7460 pp[0] = g_argv[0]; /* retain $0 */
7463 /* This realloc's G.global_argv */
7464 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7471 return EXIT_SUCCESS;
7473 /* Nothing known, so abort */
7475 bb_error_msg("set: %s: invalid option", arg);
7476 return EXIT_FAILURE;
7479 static int FAST_FUNC builtin_shift(char **argv)
7485 if (n >= 0 && n < G.global_argc) {
7486 if (G.global_args_malloced) {
7489 free(G.global_argv[m++]);
7492 memmove(&G.global_argv[1], &G.global_argv[n+1],
7493 G.global_argc * sizeof(G.global_argv[0]));
7494 return EXIT_SUCCESS;
7496 return EXIT_FAILURE;
7499 static int FAST_FUNC builtin_source(char **argv)
7504 #if ENABLE_HUSH_FUNCTIONS
7508 if (*++argv == NULL)
7509 return EXIT_FAILURE;
7511 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7512 input = fopen_for_read(arg_path);
7515 input = fopen_or_warn(*argv, "r");
7517 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7518 return EXIT_FAILURE;
7520 close_on_exec_on(fileno(input));
7522 #if ENABLE_HUSH_FUNCTIONS
7523 sv_flg = G.flag_return_in_progress;
7524 /* "we are inside sourced file, ok to use return" */
7525 G.flag_return_in_progress = -1;
7527 save_and_replace_G_args(&sv, argv);
7529 parse_and_run_file(input);
7532 restore_G_args(&sv, argv);
7533 #if ENABLE_HUSH_FUNCTIONS
7534 G.flag_return_in_progress = sv_flg;
7537 return G.last_exitcode;
7540 static int FAST_FUNC builtin_umask(char **argv)
7547 mode_t old_mask = mask;
7550 rc = bb_parse_mode(argv[1], &mask);
7555 * bash: umask: 'q': invalid symbolic mode operator
7556 * bash: umask: 999: octal number out of range
7558 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7563 printf("%04o\n", (unsigned) mask);
7564 /* fall through and restore mask which we set to 0 */
7568 return !rc; /* rc != 0 - success */
7571 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7572 static int FAST_FUNC builtin_unset(char **argv)
7577 /* "!": do not abort on errors */
7578 /* "+": stop at 1st non-option */
7579 opts = getopt32(argv, "!+vf");
7580 if (opts == (unsigned)-1)
7581 return EXIT_FAILURE;
7583 bb_error_msg("unset: -v and -f are exclusive");
7584 return EXIT_FAILURE;
7590 if (!(opts & 2)) { /* not -f */
7591 if (unset_local_var(*argv)) {
7592 /* unset <nonexistent_var> doesn't fail.
7593 * Error is when one tries to unset RO var.
7594 * Message was printed by unset_local_var. */
7598 #if ENABLE_HUSH_FUNCTIONS
7608 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7609 static int FAST_FUNC builtin_wait(char **argv)
7611 int ret = EXIT_SUCCESS;
7614 if (*++argv == NULL) {
7615 /* Don't care about wait results */
7616 /* Note 1: must wait until there are no more children */
7617 /* Note 2: must be interruptible */
7619 * $ sleep 3 & sleep 6 & wait
7624 * $ sleep 3 & sleep 6 & wait
7628 * ^C <-- after ~4 sec from keyboard
7631 sigaddset(&G.blocked_set, SIGCHLD);
7632 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7635 if (errno == ECHILD)
7637 /* Wait for SIGCHLD or any other signal of interest */
7638 /* sigtimedwait with infinite timeout: */
7639 sig = sigwaitinfo(&G.blocked_set, NULL);
7641 sig = check_and_run_traps(sig);
7642 if (sig && sig != SIGCHLD) { /* see note 2 */
7648 sigdelset(&G.blocked_set, SIGCHLD);
7649 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7653 /* This is probably buggy wrt interruptible-ness */
7655 pid_t pid = bb_strtou(*argv, NULL, 10);
7657 /* mimic bash message */
7658 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7659 return EXIT_FAILURE;
7661 if (waitpid(pid, &status, 0) == pid) {
7662 if (WIFSIGNALED(status))
7663 ret = 128 + WTERMSIG(status);
7664 else if (WIFEXITED(status))
7665 ret = WEXITSTATUS(status);
7669 bb_perror_msg("wait %s", *argv);
7678 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7679 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7682 def = bb_strtou(argv[1], NULL, 10);
7683 if (errno || def < def_min || argv[2]) {
7684 bb_error_msg("%s: bad arguments", argv[0]);
7692 #if ENABLE_HUSH_LOOPS
7693 static int FAST_FUNC builtin_break(char **argv)
7696 if (G.depth_of_loop == 0) {
7697 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7698 return EXIT_SUCCESS; /* bash compat */
7700 G.flag_break_continue++; /* BC_BREAK = 1 */
7702 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7703 if (depth == UINT_MAX)
7704 G.flag_break_continue = BC_BREAK;
7705 if (G.depth_of_loop < depth)
7706 G.depth_break_continue = G.depth_of_loop;
7708 return EXIT_SUCCESS;
7711 static int FAST_FUNC builtin_continue(char **argv)
7713 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7714 return builtin_break(argv);
7718 #if ENABLE_HUSH_FUNCTIONS
7719 static int FAST_FUNC builtin_return(char **argv)
7723 if (G.flag_return_in_progress != -1) {
7724 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7725 return EXIT_FAILURE; /* bash compat */
7728 G.flag_return_in_progress = 1;
7731 * out of range: wraps around at 256, does not error out
7732 * non-numeric param:
7733 * f() { false; return qwe; }; f; echo $?
7734 * bash: return: qwe: numeric argument required <== we do this
7735 * 255 <== we also do this
7737 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);