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;
491 pid_t saved_tty_pgrp;
492 struct pipe *job_list;
493 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
495 # define G_saved_tty_pgrp 0
497 smallint flag_SIGINT;
498 #if ENABLE_HUSH_LOOPS
499 smallint flag_break_continue;
501 #if ENABLE_HUSH_FUNCTIONS
502 /* 0: outside of a function (or sourced file)
503 * -1: inside of a function, ok to use return builtin
504 * 1: return is invoked, skip all till end of func
506 smallint flag_return_in_progress;
509 smallint exiting; /* used to prevent EXIT trap recursion */
510 /* These four support $?, $#, and $1 */
511 smalluint last_exitcode;
512 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
513 smalluint global_args_malloced;
514 /* how many non-NULL argv's we have. NB: $# + 1 */
518 char *argv0_for_re_execing;
520 #if ENABLE_HUSH_LOOPS
521 unsigned depth_break_continue;
522 unsigned depth_of_loop;
526 struct variable *top_var; /* = &G.shell_ver (set in main()) */
527 struct variable shell_ver;
528 #if ENABLE_HUSH_FUNCTIONS
529 struct function *top_func;
530 # if ENABLE_HUSH_LOCAL
531 struct variable **shadowed_vars_pp;
532 unsigned func_nest_level;
535 /* Signal and trap handling */
537 unsigned count_SIGCHLD;
538 unsigned handled_SIGCHLD;
539 smallint we_have_children;
541 /* which signals have non-DFL handler (even with no traps set)? */
542 unsigned non_DFL_mask;
543 char **traps; /* char *traps[NSIG] */
544 sigset_t blocked_set;
545 sigset_t inherited_set;
547 unsigned long memleak_value;
550 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
552 #define G (*ptr_to_globals)
553 /* Not #defining name to G.name - this quickly gets unwieldy
554 * (too many defines). Also, I actually prefer to see when a variable
555 * is global, thus "G." prefix is a useful hint */
556 #define INIT_G() do { \
557 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
561 /* Function prototypes for builtins */
562 static int builtin_cd(char **argv) FAST_FUNC;
563 static int builtin_echo(char **argv) FAST_FUNC;
564 static int builtin_eval(char **argv) FAST_FUNC;
565 static int builtin_exec(char **argv) FAST_FUNC;
566 static int builtin_exit(char **argv) FAST_FUNC;
567 static int builtin_export(char **argv) FAST_FUNC;
569 static int builtin_fg_bg(char **argv) FAST_FUNC;
570 static int builtin_jobs(char **argv) FAST_FUNC;
573 static int builtin_help(char **argv) FAST_FUNC;
575 #if ENABLE_HUSH_LOCAL
576 static int builtin_local(char **argv) FAST_FUNC;
579 static int builtin_memleak(char **argv) FAST_FUNC;
581 static int builtin_pwd(char **argv) FAST_FUNC;
582 static int builtin_read(char **argv) FAST_FUNC;
583 static int builtin_set(char **argv) FAST_FUNC;
584 static int builtin_shift(char **argv) FAST_FUNC;
585 static int builtin_source(char **argv) FAST_FUNC;
586 static int builtin_test(char **argv) FAST_FUNC;
587 static int builtin_trap(char **argv) FAST_FUNC;
588 static int builtin_type(char **argv) FAST_FUNC;
589 static int builtin_true(char **argv) FAST_FUNC;
590 static int builtin_umask(char **argv) FAST_FUNC;
591 static int builtin_unset(char **argv) FAST_FUNC;
592 static int builtin_wait(char **argv) FAST_FUNC;
593 #if ENABLE_HUSH_LOOPS
594 static int builtin_break(char **argv) FAST_FUNC;
595 static int builtin_continue(char **argv) FAST_FUNC;
597 #if ENABLE_HUSH_FUNCTIONS
598 static int builtin_return(char **argv) FAST_FUNC;
601 /* Table of built-in functions. They can be forked or not, depending on
602 * context: within pipes, they fork. As simple commands, they do not.
603 * When used in non-forking context, they can change global variables
604 * in the parent shell process. If forked, of course they cannot.
605 * For example, 'unset foo | whatever' will parse and run, but foo will
606 * still be set at the end. */
607 struct built_in_command {
609 int (*function)(char **argv) FAST_FUNC;
612 # define BLTIN(cmd, func, help) { cmd, func, help }
614 # define BLTIN(cmd, func, help) { cmd, func }
618 static const struct built_in_command bltins1[] = {
619 BLTIN("." , builtin_source , "Run commands in a file"),
620 BLTIN(":" , builtin_true , NULL),
622 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
624 #if ENABLE_HUSH_LOOPS
625 BLTIN("break" , builtin_break , "Exit from a loop"),
627 BLTIN("cd" , builtin_cd , "Change directory"),
628 #if ENABLE_HUSH_LOOPS
629 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
631 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
632 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
633 BLTIN("exit" , builtin_exit , "Exit"),
634 BLTIN("export" , builtin_export , "Set environment variables"),
636 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
639 BLTIN("help" , builtin_help , NULL),
642 BLTIN("jobs" , builtin_jobs , "List jobs"),
644 #if ENABLE_HUSH_LOCAL
645 BLTIN("local" , builtin_local , "Set local variables"),
648 BLTIN("memleak" , builtin_memleak , NULL),
650 BLTIN("read" , builtin_read , "Input into variable"),
651 #if ENABLE_HUSH_FUNCTIONS
652 BLTIN("return" , builtin_return , "Return from a function"),
654 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
655 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
656 BLTIN("trap" , builtin_trap , "Trap signals"),
657 BLTIN("type" , builtin_type , "Write a description of command type"),
658 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
659 BLTIN("umask" , builtin_umask , "Set file creation mask"),
660 BLTIN("unset" , builtin_unset , "Unset variables"),
661 BLTIN("wait" , builtin_wait , "Wait for process"),
663 /* For now, echo and test are unconditionally enabled.
664 * Maybe make it configurable? */
665 static const struct built_in_command bltins2[] = {
666 BLTIN("[" , builtin_test , NULL),
667 BLTIN("echo" , builtin_echo , NULL),
668 BLTIN("pwd" , builtin_pwd , NULL),
669 BLTIN("test" , builtin_test , NULL),
676 /* prevent disasters with G.debug_indent < 0 */
677 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
678 # define debug_enter() (G.debug_indent++)
679 # define debug_leave() (G.debug_indent--)
681 # define indent() ((void)0)
682 # define debug_enter() ((void)0)
683 # define debug_leave() ((void)0)
687 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
690 #ifndef debug_printf_parse
691 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
694 #ifndef debug_printf_exec
695 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
698 #ifndef debug_printf_env
699 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
702 #ifndef debug_printf_jobs
703 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
704 # define DEBUG_JOBS 1
706 # define DEBUG_JOBS 0
709 #ifndef debug_printf_expand
710 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
711 # define DEBUG_EXPAND 1
713 # define DEBUG_EXPAND 0
716 #ifndef debug_printf_glob
717 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
718 # define DEBUG_GLOB 1
720 # define DEBUG_GLOB 0
723 #ifndef debug_printf_list
724 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
727 #ifndef debug_printf_subst
728 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
731 #ifndef debug_printf_clean
732 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
733 # define DEBUG_CLEAN 1
735 # define DEBUG_CLEAN 0
739 static void debug_print_strings(const char *prefix, char **vv)
742 fprintf(stderr, "%s:\n", prefix);
744 fprintf(stderr, " '%s'\n", *vv++);
747 # define debug_print_strings(prefix, vv) ((void)0)
751 /* Leak hunting. Use hush_leaktool.sh for post-processing.
754 static void *xxmalloc(int lineno, size_t size)
756 void *ptr = xmalloc((size + 0xff) & ~0xff);
757 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
760 static void *xxrealloc(int lineno, void *ptr, size_t size)
762 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
763 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
766 static char *xxstrdup(int lineno, const char *str)
768 char *ptr = xstrdup(str);
769 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
772 static void xxfree(void *ptr)
774 fdprintf(2, "free %p\n", ptr);
777 #define xmalloc(s) xxmalloc(__LINE__, s)
778 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
779 #define xstrdup(s) xxstrdup(__LINE__, s)
780 #define free(p) xxfree(p)
784 /* Syntax and runtime errors. They always abort scripts.
785 * In interactive use they usually discard unparsed and/or unexecuted commands
786 * and return to the prompt.
787 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
790 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
791 # define syntax_error(lineno, msg) syntax_error(msg)
792 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
793 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
794 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
795 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
798 static void die_if_script(unsigned lineno, const char *fmt, ...)
803 bb_error_msg("hush.c:%u", lineno);
806 bb_verror_msg(fmt, p, NULL);
808 if (!G_interactive_fd)
812 static void syntax_error(unsigned lineno, const char *msg)
815 die_if_script(lineno, "syntax error: %s", msg);
817 die_if_script(lineno, "syntax error", NULL);
820 static void syntax_error_at(unsigned lineno, const char *msg)
822 die_if_script(lineno, "syntax error at '%s'", msg);
825 static void syntax_error_unterm_str(unsigned lineno, const char *s)
827 die_if_script(lineno, "syntax error: unterminated %s", s);
830 /* It so happens that all such cases are totally fatal
831 * even if shell is interactive: EOF while looking for closing
832 * delimiter. There is nowhere to read stuff from after that,
833 * it's EOF! The only choice is to terminate.
835 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
836 static void syntax_error_unterm_ch(unsigned lineno, char ch)
838 char msg[2] = { ch, '\0' };
839 syntax_error_unterm_str(lineno, msg);
843 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
848 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
852 # undef die_if_script
854 # undef syntax_error_at
855 # undef syntax_error_unterm_ch
856 # undef syntax_error_unterm_str
857 # undef syntax_error_unexpected_ch
859 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
860 # define syntax_error(msg) syntax_error(__LINE__, msg)
861 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
862 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
863 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
864 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
868 #if ENABLE_HUSH_INTERACTIVE
869 static void cmdedit_update_prompt(void);
871 # define cmdedit_update_prompt() ((void)0)
877 static int glob_needed(const char *s)
882 if (*s == '*' || *s == '[' || *s == '?')
889 static int is_well_formed_var_name(const char *s, char terminator)
891 if (!s || !(isalpha(*s) || *s == '_'))
894 while (isalnum(*s) || *s == '_')
896 return *s == terminator;
899 /* Replace each \x with x in place, return ptr past NUL. */
900 static char *unbackslash(char *src)
902 char *dst = src = strchrnul(src, '\\');
906 if ((*dst++ = *src++) == '\0')
912 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
933 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
934 v[count1 + count2] = NULL;
937 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
941 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
943 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
944 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
947 #define add_strings_to_strings(strings, add, need_to_dup) \
948 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
951 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
952 static char **add_string_to_strings(char **strings, char *add)
957 return add_strings_to_strings(strings, v, /*dup:*/ 0);
960 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
962 char **ptr = add_string_to_strings(strings, add);
963 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
966 #define add_string_to_strings(strings, add) \
967 xx_add_string_to_strings(__LINE__, strings, add)
970 static void free_strings(char **strings)
985 /* Helpers for setting new $n and restoring them back
987 typedef struct save_arg_t {
991 smallint sv_g_malloced;
994 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
998 sv->sv_argv0 = argv[0];
999 sv->sv_g_argv = G.global_argv;
1000 sv->sv_g_argc = G.global_argc;
1001 sv->sv_g_malloced = G.global_args_malloced;
1003 argv[0] = G.global_argv[0]; /* retain $0 */
1004 G.global_argv = argv;
1005 G.global_args_malloced = 0;
1013 static void restore_G_args(save_arg_t *sv, char **argv)
1017 if (G.global_args_malloced) {
1018 /* someone ran "set -- arg1 arg2 ...", undo */
1020 while (*++pp) /* note: does not free $0 */
1022 free(G.global_argv);
1024 argv[0] = sv->sv_argv0;
1025 G.global_argv = sv->sv_g_argv;
1026 G.global_argc = sv->sv_g_argc;
1027 G.global_args_malloced = sv->sv_g_malloced;
1031 /* Basic theory of signal handling in shell
1032 * ========================================
1033 * This does not describe what hush does, rather, it is current understanding
1034 * what it _should_ do. If it doesn't, it's a bug.
1035 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1037 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1038 * is finished or backgrounded. It is the same in interactive and
1039 * non-interactive shells, and is the same regardless of whether
1040 * a user trap handler is installed or a shell special one is in effect.
1041 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1042 * backgrounds (i.e. stops) or kills all members of currently running
1045 * Wait builtin in interruptible by signals for which user trap is set
1046 * or by SIGINT in interactive shell.
1048 * Trap handlers will execute even within trap handlers. (right?)
1050 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1052 * If job control is off, backgrounded commands ("cmd &")
1053 * have SIGINT, SIGQUIT set to SIG_IGN.
1055 * Commands which are run in command substitution ("`cmd`")
1056 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1058 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1059 * by the shell from its parent.
1061 * Signals which differ from SIG_DFL action
1062 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1065 * SIGTERM (interactive): ignore
1066 * SIGHUP (interactive):
1067 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1068 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1069 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1070 * that all pipe members are stopped. Try this in bash:
1071 * while :; do :; done - ^Z does not background it
1072 * (while :; do :; done) - ^Z backgrounds it
1073 * SIGINT (interactive): wait for last pipe, ignore the rest
1074 * of the command line, show prompt. NB: ^C does not send SIGINT
1075 * to interactive shell while shell is waiting for a pipe,
1076 * since shell is bg'ed (is not in foreground process group).
1077 * Example 1: this waits 5 sec, but does not execute ls:
1078 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1079 * Example 2: this does not wait and does not execute ls:
1080 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1081 * Example 3: this does not wait 5 sec, but executes ls:
1082 * "sleep 5; ls -l" + press ^C
1084 * (What happens to signals which are IGN on shell start?)
1085 * (What happens with signal mask on shell start?)
1087 * Implementation in hush
1088 * ======================
1089 * We use in-kernel pending signal mask to determine which signals were sent.
1090 * We block all signals which we don't want to take action immediately,
1091 * i.e. we block all signals which need to have special handling as described
1092 * above, and all signals which have traps set.
1093 * After each pipe execution, we extract any pending signals via sigtimedwait()
1096 * unsigned non_DFL_mask: a mask of such "special" signals
1097 * sigset_t blocked_set: current blocked signal set
1100 * clear bit in blocked_set unless it is also in non_DFL_mask
1101 * "trap 'cmd' SIGxxx":
1102 * set bit in blocked_set (even if 'cmd' is '')
1103 * after [v]fork, if we plan to be a shell:
1104 * unblock signals with special interactive handling
1105 * (child shell is not interactive),
1106 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1107 * after [v]fork, if we plan to exec:
1108 * POSIX says fork clears pending signal mask in child - no need to clear it.
1109 * Restore blocked signal set to one inherited by shell just prior to exec.
1111 * Note: as a result, we do not use signal handlers much. The only uses
1112 * are to count SIGCHLDs
1113 * and to restore tty pgrp on signal-induced exit.
1116 * Standard says "When a subshell is entered, traps that are not being ignored
1117 * are set to the default actions". bash interprets it so that traps which
1118 * are set to "" (ignore) are NOT reset to defaults. We do the same.
1121 SPECIAL_INTERACTIVE_SIGS = 0
1126 SPECIAL_JOB_SIGS = 0
1134 #if ENABLE_HUSH_FAST
1135 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1138 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1144 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1145 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1146 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1147 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1149 /* Restores tty foreground process group, and exits.
1150 * May be called as signal handler for fatal signal
1151 * (will resend signal to itself, producing correct exit state)
1152 * or called directly with -EXITCODE.
1153 * We also call it if xfunc is exiting. */
1154 static void sigexit(int sig) NORETURN;
1155 static void sigexit(int sig)
1157 /* Disable all signals: job control, SIGPIPE, etc. */
1158 sigprocmask_allsigs(SIG_BLOCK);
1160 /* Careful: we can end up here after [v]fork. Do not restore
1161 * tty pgrp then, only top-level shell process does that */
1162 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1163 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1165 /* Not a signal, just exit */
1169 kill_myself_with_sig(sig); /* does not return */
1173 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1174 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1178 /* Restores tty foreground process group, and exits. */
1179 static void hush_exit(int exitcode) NORETURN;
1180 static void hush_exit(int exitcode)
1182 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1183 /* Prevent recursion:
1184 * trap "echo Hi; exit" EXIT; exit
1186 char *argv[] = { NULL, G.traps[0], NULL };
1194 fflush(NULL); /* flush all streams */
1195 sigexit(- (exitcode & 0xff));
1201 static int check_and_run_traps(int sig)
1203 static const struct timespec zero_timespec = { 0, 0 };
1204 smalluint save_rcode;
1210 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1215 if (G.traps && G.traps[sig]) {
1216 if (G.traps[sig][0]) {
1217 /* We have user-defined handler */
1218 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1219 save_rcode = G.last_exitcode;
1222 G.last_exitcode = save_rcode;
1223 } /* else: "" trap, ignoring signal */
1226 /* not a trap: special action */
1228 #if ENABLE_HUSH_FAST
1231 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1235 /* Builtin was ^C'ed, make it look prettier: */
1242 /* bash is observed to signal whole process groups,
1243 * not individual processes */
1244 for (job = G.job_list; job; job = job->next) {
1247 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1248 if (kill(- job->pgrp, SIGHUP) == 0)
1249 kill(- job->pgrp, SIGCONT);
1254 default: /* ignored: */
1255 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1263 static const char *get_cwd(int force)
1265 if (force || G.cwd == NULL) {
1266 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1267 * we must not try to free(bb_msg_unknown) */
1268 if (G.cwd == bb_msg_unknown)
1270 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1272 G.cwd = bb_msg_unknown;
1279 * Shell and environment variable support
1281 static struct variable **get_ptr_to_local_var(const char *name)
1283 struct variable **pp;
1284 struct variable *cur;
1289 while ((cur = *pp) != NULL) {
1290 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1297 static struct variable *get_local_var(const char *name)
1299 struct variable **pp = get_ptr_to_local_var(name);
1305 static const char *get_local_var_value(const char *name)
1307 struct variable **pp = get_ptr_to_local_var(name);
1309 return strchr((*pp)->varstr, '=') + 1;
1313 /* str holds "NAME=VAL" and is expected to be malloced.
1314 * We take ownership of it.
1316 * 0: do not change export flag
1317 * (if creating new variable, flag will be 0)
1318 * 1: set export flag and putenv the variable
1319 * -1: clear export flag and unsetenv the variable
1320 * flg_read_only is set only when we handle -R var=val
1322 #if !BB_MMU && ENABLE_HUSH_LOCAL
1323 /* all params are used */
1324 #elif BB_MMU && ENABLE_HUSH_LOCAL
1325 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1326 set_local_var(str, flg_export, local_lvl)
1327 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1328 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1329 set_local_var(str, flg_export)
1330 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1331 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1332 set_local_var(str, flg_export, flg_read_only)
1334 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1336 struct variable **var_pp;
1337 struct variable *cur;
1341 eq_sign = strchr(str, '=');
1342 if (!eq_sign) { /* not expected to ever happen? */
1347 name_len = eq_sign - str + 1; /* including '=' */
1348 var_pp = &G.top_var;
1349 while ((cur = *var_pp) != NULL) {
1350 if (strncmp(cur->varstr, str, name_len) != 0) {
1351 var_pp = &cur->next;
1354 /* We found an existing var with this name */
1355 if (cur->flg_read_only) {
1359 bb_error_msg("%s: readonly variable", str);
1363 if (flg_export == -1) { // "&& cur->flg_export" ?
1364 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1369 #if ENABLE_HUSH_LOCAL
1370 if (cur->func_nest_level < local_lvl) {
1371 /* New variable is declared as local,
1372 * and existing one is global, or local
1373 * from enclosing function.
1374 * Remove and save old one: */
1375 *var_pp = cur->next;
1376 cur->next = *G.shadowed_vars_pp;
1377 *G.shadowed_vars_pp = cur;
1378 /* bash 3.2.33(1) and exported vars:
1380 * # f() { local z=a; env | grep ^z; }
1386 if (cur->flg_export)
1391 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1396 if (cur->max_len != 0) {
1397 if (cur->max_len >= strlen(str)) {
1398 /* This one is from startup env, reuse space */
1399 strcpy(cur->varstr, str);
1403 /* max_len == 0 signifies "malloced" var, which we can
1404 * (and has to) free */
1408 goto set_str_and_exp;
1411 /* Not found - create new variable struct */
1412 cur = xzalloc(sizeof(*cur));
1413 #if ENABLE_HUSH_LOCAL
1414 cur->func_nest_level = local_lvl;
1416 cur->next = *var_pp;
1422 cur->flg_read_only = flg_read_only;
1425 if (flg_export == 1)
1426 cur->flg_export = 1;
1427 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1428 cmdedit_update_prompt();
1429 if (cur->flg_export) {
1430 if (flg_export == -1) {
1431 cur->flg_export = 0;
1432 /* unsetenv was already done */
1434 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1435 return putenv(cur->varstr);
1441 /* Used at startup and after each cd */
1442 static void set_pwd_var(int exp)
1444 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1445 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1448 static int unset_local_var_len(const char *name, int name_len)
1450 struct variable *cur;
1451 struct variable **var_pp;
1454 return EXIT_SUCCESS;
1455 var_pp = &G.top_var;
1456 while ((cur = *var_pp) != NULL) {
1457 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1458 if (cur->flg_read_only) {
1459 bb_error_msg("%s: readonly variable", name);
1460 return EXIT_FAILURE;
1462 *var_pp = cur->next;
1463 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1464 bb_unsetenv(cur->varstr);
1465 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1466 cmdedit_update_prompt();
1470 return EXIT_SUCCESS;
1472 var_pp = &cur->next;
1474 return EXIT_SUCCESS;
1477 static int unset_local_var(const char *name)
1479 return unset_local_var_len(name, strlen(name));
1482 static void unset_vars(char **strings)
1490 const char *eq = strchrnul(*v, '=');
1491 unset_local_var_len(*v, (int)(eq - *v));
1497 #if ENABLE_SH_MATH_SUPPORT
1498 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1499 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1500 static char *endofname(const char *name)
1508 if (!is_in_name(*p))
1514 static void arith_set_local_var(const char *name, const char *val, int flags)
1516 /* arith code doesnt malloc space, so do it for it */
1517 char *var = xasprintf("%s=%s", name, val);
1518 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1524 * Helpers for "var1=val1 var2=val2 cmd" feature
1526 static void add_vars(struct variable *var)
1528 struct variable *next;
1532 var->next = G.top_var;
1534 if (var->flg_export) {
1535 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1536 putenv(var->varstr);
1538 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1544 static struct variable *set_vars_and_save_old(char **strings)
1547 struct variable *old = NULL;
1553 struct variable *var_p;
1554 struct variable **var_pp;
1557 eq = strchr(*s, '=');
1560 var_pp = get_ptr_to_local_var(*s);
1563 /* Remove variable from global linked list */
1565 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1566 *var_pp = var_p->next;
1567 /* Add it to returned list */
1571 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1582 static int FAST_FUNC static_get(struct in_str *i)
1591 static int FAST_FUNC static_peek(struct in_str *i)
1596 #if ENABLE_HUSH_INTERACTIVE
1598 static void cmdedit_update_prompt(void)
1600 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1601 G.PS1 = get_local_var_value("PS1");
1604 G.PS2 = get_local_var_value("PS2");
1612 static const char* setup_prompt_string(int promptmode)
1614 const char *prompt_str;
1615 debug_printf("setup_prompt_string %d ", promptmode);
1616 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1617 /* Set up the prompt */
1618 if (promptmode == 0) { /* PS1 */
1620 /* bash uses $PWD value, even if it is set by user.
1621 * It uses current dir only if PWD is unset.
1622 * We always use current dir. */
1623 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1628 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1629 debug_printf("result '%s'\n", prompt_str);
1633 static void get_user_input(struct in_str *i)
1636 const char *prompt_str;
1638 prompt_str = setup_prompt_string(i->promptmode);
1639 #if ENABLE_FEATURE_EDITING
1640 /* Enable command line editing only while a command line
1641 * is actually being read */
1644 /* buglet: SIGINT will not make new prompt to appear _at once_,
1645 * only after <Enter>. (^C will work) */
1646 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1647 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1648 check_and_run_traps(0);
1649 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1650 i->eof_flag = (r < 0);
1651 if (i->eof_flag) { /* EOF/error detected */
1652 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1653 G.user_input_buf[1] = '\0';
1658 fputs(prompt_str, stdout);
1660 G.user_input_buf[0] = r = fgetc(i->file);
1661 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1662 //do we need check_and_run_traps(0)? (maybe only if stdin)
1663 } while (G.flag_SIGINT);
1664 i->eof_flag = (r == EOF);
1666 i->p = G.user_input_buf;
1669 #endif /* INTERACTIVE */
1671 /* This is the magic location that prints prompts
1672 * and gets data back from the user */
1673 static int FAST_FUNC file_get(struct in_str *i)
1677 /* If there is data waiting, eat it up */
1678 if (i->p && *i->p) {
1679 #if ENABLE_HUSH_INTERACTIVE
1683 if (i->eof_flag && !*i->p)
1685 /* note: ch is never NUL */
1687 /* need to double check i->file because we might be doing something
1688 * more complicated by now, like sourcing or substituting. */
1689 #if ENABLE_HUSH_INTERACTIVE
1690 if (G_interactive_fd && i->promptme && i->file == stdin) {
1693 } while (!*i->p); /* need non-empty line */
1694 i->promptmode = 1; /* PS2 */
1699 do ch = fgetc(i->file); while (ch == '\0');
1701 debug_printf("file_get: got '%c' %d\n", ch, ch);
1702 #if ENABLE_HUSH_INTERACTIVE
1709 /* All callers guarantee this routine will never
1710 * be used right after a newline, so prompting is not needed.
1712 static int FAST_FUNC file_peek(struct in_str *i)
1715 if (i->p && *i->p) {
1716 if (i->eof_flag && !i->p[1])
1719 /* note: ch is never NUL */
1721 do ch = fgetc(i->file); while (ch == '\0');
1722 i->eof_flag = (ch == EOF);
1723 i->peek_buf[0] = ch;
1724 i->peek_buf[1] = '\0';
1726 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1730 static void setup_file_in_str(struct in_str *i, FILE *f)
1732 i->peek = file_peek;
1734 #if ENABLE_HUSH_INTERACTIVE
1736 i->promptmode = 0; /* PS1 */
1742 static void setup_string_in_str(struct in_str *i, const char *s)
1744 i->peek = static_peek;
1745 i->get = static_get;
1746 #if ENABLE_HUSH_INTERACTIVE
1748 i->promptmode = 0; /* PS1 */
1758 #define B_CHUNK (32 * sizeof(char*))
1760 static void o_reset_to_empty_unquoted(o_string *o)
1768 static void o_free(o_string *o)
1771 memset(o, 0, sizeof(*o));
1774 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1779 static void o_grow_by(o_string *o, int len)
1781 if (o->length + len > o->maxlen) {
1782 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1783 o->data = xrealloc(o->data, 1 + o->maxlen);
1787 static void o_addchr(o_string *o, int ch)
1789 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1791 o->data[o->length] = ch;
1793 o->data[o->length] = '\0';
1796 static void o_addblock(o_string *o, const char *str, int len)
1799 memcpy(&o->data[o->length], str, len);
1801 o->data[o->length] = '\0';
1805 static void o_addstr(o_string *o, const char *str)
1807 o_addblock(o, str, strlen(str));
1809 static void nommu_addchr(o_string *o, int ch)
1815 # define nommu_addchr(o, str) ((void)0)
1818 static void o_addstr_with_NUL(o_string *o, const char *str)
1820 o_addblock(o, str, strlen(str) + 1);
1823 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1828 && (*str != '*' && *str != '?' && *str != '[')
1836 /* My analysis of quoting semantics tells me that state information
1837 * is associated with a destination, not a source.
1839 static void o_addqchr(o_string *o, int ch)
1842 char *found = strchr("*?[\\", ch);
1847 o->data[o->length] = '\\';
1850 o->data[o->length] = ch;
1852 o->data[o->length] = '\0';
1855 static void o_addQchr(o_string *o, int ch)
1858 if (o->o_escape && strchr("*?[\\", ch)) {
1860 o->data[o->length] = '\\';
1864 o->data[o->length] = ch;
1866 o->data[o->length] = '\0';
1869 static void o_addQstr(o_string *o, const char *str, int len)
1872 o_addblock(o, str, len);
1878 int ordinary_cnt = strcspn(str, "*?[\\");
1879 if (ordinary_cnt > len) /* paranoia */
1881 o_addblock(o, str, ordinary_cnt);
1882 if (ordinary_cnt == len)
1884 str += ordinary_cnt;
1885 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1889 if (ch) { /* it is necessarily one of "*?[\\" */
1891 o->data[o->length] = '\\';
1895 o->data[o->length] = ch;
1897 o->data[o->length] = '\0';
1901 /* A special kind of o_string for $VAR and `cmd` expansion.
1902 * It contains char* list[] at the beginning, which is grown in 16 element
1903 * increments. Actual string data starts at the next multiple of 16 * (char*).
1904 * list[i] contains an INDEX (int!) into this string data.
1905 * It means that if list[] needs to grow, data needs to be moved higher up
1906 * but list[i]'s need not be modified.
1907 * NB: remembering how many list[i]'s you have there is crucial.
1908 * o_finalize_list() operation post-processes this structure - calculates
1909 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1911 #if DEBUG_EXPAND || DEBUG_GLOB
1912 static void debug_print_list(const char *prefix, o_string *o, int n)
1914 char **list = (char**)o->data;
1915 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1919 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1920 prefix, list, n, string_start, o->length, o->maxlen);
1923 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1924 o->data + (int)list[i] + string_start,
1925 o->data + (int)list[i] + string_start);
1929 const char *p = o->data + (int)list[n - 1] + string_start;
1931 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1935 # define debug_print_list(prefix, o, n) ((void)0)
1938 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1939 * in list[n] so that it points past last stored byte so far.
1940 * It returns n+1. */
1941 static int o_save_ptr_helper(o_string *o, int n)
1943 char **list = (char**)o->data;
1947 if (!o->has_empty_slot) {
1948 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1949 string_len = o->length - string_start;
1950 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1951 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1952 /* list[n] points to string_start, make space for 16 more pointers */
1953 o->maxlen += 0x10 * sizeof(list[0]);
1954 o->data = xrealloc(o->data, o->maxlen + 1);
1955 list = (char**)o->data;
1956 memmove(list + n + 0x10, list + n, string_len);
1957 o->length += 0x10 * sizeof(list[0]);
1959 debug_printf_list("list[%d]=%d string_start=%d\n",
1960 n, string_len, string_start);
1963 /* We have empty slot at list[n], reuse without growth */
1964 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1965 string_len = o->length - string_start;
1966 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1967 n, string_len, string_start);
1968 o->has_empty_slot = 0;
1970 list[n] = (char*)(ptrdiff_t)string_len;
1974 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1975 static int o_get_last_ptr(o_string *o, int n)
1977 char **list = (char**)o->data;
1978 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1980 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1983 /* o_glob performs globbing on last list[], saving each result
1984 * as a new list[]. */
1985 static int o_glob(o_string *o, int n)
1991 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1993 return o_save_ptr_helper(o, n);
1994 pattern = o->data + o_get_last_ptr(o, n);
1995 debug_printf_glob("glob pattern '%s'\n", pattern);
1996 if (!glob_needed(pattern)) {
1998 o->length = unbackslash(pattern) - o->data;
1999 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2000 return o_save_ptr_helper(o, n);
2003 memset(&globdata, 0, sizeof(globdata));
2004 gr = glob(pattern, 0, NULL, &globdata);
2005 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2006 if (gr == GLOB_NOSPACE)
2007 bb_error_msg_and_die("out of memory during glob");
2008 if (gr == GLOB_NOMATCH) {
2009 globfree(&globdata);
2012 if (gr != 0) { /* GLOB_ABORTED ? */
2013 /* TODO: testcase for bad glob pattern behavior */
2014 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2016 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2017 char **argv = globdata.gl_pathv;
2018 o->length = pattern - o->data; /* "forget" pattern */
2020 o_addstr_with_NUL(o, *argv);
2021 n = o_save_ptr_helper(o, n);
2027 globfree(&globdata);
2029 debug_print_list("o_glob returning", o, n);
2033 /* If o->o_glob == 1, glob the string so far remembered.
2034 * Otherwise, just finish current list[] and start new */
2035 static int o_save_ptr(o_string *o, int n)
2037 if (o->o_glob) { /* if globbing is requested */
2038 /* If o->has_empty_slot, list[n] was already globbed
2039 * (if it was requested back then when it was filled)
2040 * so don't do that again! */
2041 if (!o->has_empty_slot)
2042 return o_glob(o, n); /* o_save_ptr_helper is inside */
2044 return o_save_ptr_helper(o, n);
2047 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2048 static char **o_finalize_list(o_string *o, int n)
2053 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2055 debug_print_list("finalized", o, n);
2056 debug_printf_expand("finalized n:%d\n", n);
2057 list = (char**)o->data;
2058 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2062 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2068 /* Expansion can recurse */
2069 #if ENABLE_HUSH_TICK
2070 static int process_command_subs(o_string *dest, const char *s);
2072 static char *expand_string_to_string(const char *str);
2074 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2075 parse_stream_dquoted(dest, input, dquote_end)
2077 static int parse_stream_dquoted(o_string *as_string,
2079 struct in_str *input,
2082 /* expand_strvec_to_strvec() takes a list of strings, expands
2083 * all variable references within and returns a pointer to
2084 * a list of expanded strings, possibly with larger number
2085 * of strings. (Think VAR="a b"; echo $VAR).
2086 * This new list is allocated as a single malloc block.
2087 * NULL-terminated list of char* pointers is at the beginning of it,
2088 * followed by strings themself.
2089 * Caller can deallocate entire list by single free(list). */
2091 /* Store given string, finalizing the word and starting new one whenever
2092 * we encounter IFS char(s). This is used for expanding variable values.
2093 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2094 static int expand_on_ifs(o_string *output, int n, const char *str)
2097 int word_len = strcspn(str, G.ifs);
2099 if (output->o_escape || !output->o_glob)
2100 o_addQstr(output, str, word_len);
2101 else /* protect backslashes against globbing up :) */
2102 o_addblock_duplicate_backslash(output, str, word_len);
2105 if (!*str) /* EOL - do not finalize word */
2107 o_addchr(output, '\0');
2108 debug_print_list("expand_on_ifs", output, n);
2109 n = o_save_ptr(output, n);
2110 str += strspn(str, G.ifs); /* skip ifs chars */
2112 debug_print_list("expand_on_ifs[1]", output, n);
2116 /* Helper to expand $((...)) and heredoc body. These act as if
2117 * they are in double quotes, with the exception that they are not :).
2118 * Just the rules are similar: "expand only $var and `cmd`"
2120 * Returns malloced string.
2121 * As an optimization, we return NULL if expansion is not needed.
2123 static char *expand_pseudo_dquoted(const char *str)
2126 struct in_str input;
2127 o_string dest = NULL_O_STRING;
2129 if (strchr(str, '$') == NULL
2130 #if ENABLE_HUSH_TICK
2131 && strchr(str, '`') == NULL
2137 /* We need to expand. Example:
2138 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2140 setup_string_in_str(&input, str);
2141 parse_stream_dquoted(NULL, &dest, &input, EOF);
2142 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2143 exp_str = expand_string_to_string(dest.data);
2144 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2145 o_free_unsafe(&dest);
2149 /* Expand all variable references in given string, adding words to list[]
2150 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2151 * to be filled). This routine is extremely tricky: has to deal with
2152 * variables/parameters with whitespace, $* and $@, and constructs like
2153 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2154 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2156 /* or_mask is either 0 (normal case) or 0x80 -
2157 * expansion of right-hand side of assignment == 1-element expand.
2158 * It will also do no globbing, and thus we must not backslash-quote!
2165 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2166 debug_print_list("expand_vars_to_list", output, n);
2167 n = o_save_ptr(output, n);
2168 debug_print_list("expand_vars_to_list[0]", output, n);
2170 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2173 char *dyn_val = NULL;
2174 const char *val = NULL;
2175 #if ENABLE_HUSH_TICK
2176 o_string subst_result = NULL_O_STRING;
2178 #if ENABLE_SH_MATH_SUPPORT
2179 char arith_buf[sizeof(arith_t)*3 + 2];
2181 o_addblock(output, arg, p - arg);
2182 debug_print_list("expand_vars_to_list[1]", output, n);
2184 p = strchr(p, SPECIAL_VAR_SYMBOL);
2186 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2187 /* "$@" is special. Even if quoted, it can still
2188 * expand to nothing (not even an empty string) */
2189 if ((first_ch & 0x7f) != '@')
2190 ored_ch |= first_ch;
2192 switch (first_ch & 0x7f) {
2193 /* Highest bit in first_ch indicates that var is double-quoted */
2195 val = utoa(G.root_pid);
2197 case '!': /* bg pid */
2198 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2200 case '?': /* exitcode */
2201 val = utoa(G.last_exitcode);
2203 case '#': /* argc */
2204 if (arg[1] != SPECIAL_VAR_SYMBOL)
2205 /* actually, it's a ${#var} */
2207 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2212 if (!G.global_argv[i])
2214 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2215 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2216 smallint sv = output->o_escape;
2217 /* unquoted var's contents should be globbed, so don't escape */
2218 output->o_escape = 0;
2219 while (G.global_argv[i]) {
2220 n = expand_on_ifs(output, n, G.global_argv[i]);
2221 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2222 if (G.global_argv[i++][0] && G.global_argv[i]) {
2223 /* this argv[] is not empty and not last:
2224 * put terminating NUL, start new word */
2225 o_addchr(output, '\0');
2226 debug_print_list("expand_vars_to_list[2]", output, n);
2227 n = o_save_ptr(output, n);
2228 debug_print_list("expand_vars_to_list[3]", output, n);
2231 output->o_escape = sv;
2233 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2234 * and in this case should treat it like '$*' - see 'else...' below */
2235 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2237 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2238 if (++i >= G.global_argc)
2240 o_addchr(output, '\0');
2241 debug_print_list("expand_vars_to_list[4]", output, n);
2242 n = o_save_ptr(output, n);
2244 } else { /* quoted $*: add as one word */
2246 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2247 if (!G.global_argv[++i])
2250 o_addchr(output, G.ifs[0]);
2254 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2255 /* "Empty variable", used to make "" etc to not disappear */
2259 #if ENABLE_HUSH_TICK
2260 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2263 /* Can't just stuff it into output o_string,
2264 * expanded result may need to be globbed
2265 * and $IFS-splitted */
2266 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2267 process_command_subs(&subst_result, arg);
2268 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2269 val = subst_result.data;
2272 #if ENABLE_SH_MATH_SUPPORT
2273 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2274 arith_eval_hooks_t hooks;
2279 arg++; /* skip '+' */
2280 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2281 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2283 exp_str = expand_pseudo_dquoted(arg);
2284 hooks.lookupvar = get_local_var_value;
2285 hooks.setvar = arith_set_local_var;
2286 hooks.endofname = endofname;
2287 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2291 const char *msg = "error in arithmetic";
2294 msg = "exponent less than 0";
2297 msg = "divide by 0";
2300 msg = "expression recursion loop detected";
2305 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2306 sprintf(arith_buf, arith_t_fmt, res);
2311 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2313 bool exp_len = false;
2314 bool exp_null = false;
2316 char exp_save = exp_save; /* for compiler */
2317 char exp_op = exp_op; /* for compiler */
2318 char *exp_word = exp_word; /* for compiler */
2322 arg[0] = first_ch & 0x7f;
2324 /* prepare for expansions */
2325 if (var[0] == '#') {
2326 /* handle length expansion ${#var} */
2330 /* maybe handle parameter expansion */
2331 exp_off = strcspn(var, ":-=+?%#");
2335 exp_save = var[exp_off];
2336 exp_null = exp_save == ':';
2337 exp_word = var + exp_off;
2340 exp_op = *exp_word++;
2341 var[exp_off] = '\0';
2345 /* lookup the variable in question */
2346 if (isdigit(var[0])) {
2347 /* handle_dollar() should have vetted var for us */
2349 if (i < G.global_argc)
2350 val = G.global_argv[i];
2351 /* else val remains NULL: $N with too big N */
2353 val = get_local_var_value(var);
2355 /* handle any expansions */
2357 debug_printf_expand("expand: length of '%s' = ", val);
2358 val = utoa(val ? strlen(val) : 0);
2359 debug_printf_expand("%s\n", val);
2360 } else if (exp_off) {
2361 if (exp_op == '%' || exp_op == '#') {
2363 /* we need to do a pattern match */
2366 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2367 if (exp_op == *exp_word) /* ## or %% */
2369 val = dyn_val = xstrdup(val);
2370 loc = scan(dyn_val, exp_word, match_at_left);
2371 if (match_at_left) /* # or ## */
2373 else if (loc) /* % or %% and match was found */
2377 /* we need to do an expansion */
2378 int exp_test = (!val || (exp_null && !val[0]));
2380 exp_test = !exp_test;
2381 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2382 exp_null ? "true" : "false", exp_test);
2384 if (exp_op == '?') {
2385 //TODO: how interactive bash aborts expansion mid-command?
2386 /* ${var?[error_msg_if_unset]} */
2387 /* ${var:?[error_msg_if_unset_or_null]} */
2388 /* mimic bash message */
2389 die_if_script("%s: %s",
2391 exp_word[0] ? exp_word : "parameter null or not set"
2397 if (exp_op == '=') {
2398 /* ${var=[word]} or ${var:=[word]} */
2399 if (isdigit(var[0]) || var[0] == '#') {
2400 /* mimic bash message */
2401 die_if_script("$%s: cannot assign in this way", var);
2404 char *new_var = xasprintf("%s=%s", var, val);
2405 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2411 var[exp_off] = exp_save;
2415 #if ENABLE_HUSH_TICK
2418 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2419 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2421 /* unquoted var's contents should be globbed, so don't escape */
2422 smallint sv = output->o_escape;
2423 output->o_escape = 0;
2424 n = expand_on_ifs(output, n, val);
2426 output->o_escape = sv;
2428 } else { /* quoted $VAR, val will be appended below */
2429 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2432 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2435 o_addQstr(output, val, strlen(val));
2438 /* Do the check to avoid writing to a const string */
2439 if (*p != SPECIAL_VAR_SYMBOL)
2440 *p = SPECIAL_VAR_SYMBOL;
2442 #if ENABLE_HUSH_TICK
2443 o_free(&subst_result);
2446 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2449 debug_print_list("expand_vars_to_list[a]", output, n);
2450 /* this part is literal, and it was already pre-quoted
2451 * if needed (much earlier), do not use o_addQstr here! */
2452 o_addstr_with_NUL(output, arg);
2453 debug_print_list("expand_vars_to_list[b]", output, n);
2454 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2455 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2458 /* allow to reuse list[n] later without re-growth */
2459 output->has_empty_slot = 1;
2461 o_addchr(output, '\0');
2466 static char **expand_variables(char **argv, int or_mask)
2471 o_string output = NULL_O_STRING;
2473 if (or_mask & 0x100) {
2474 output.o_escape = 1; /* protect against globbing for "$var" */
2475 /* (unquoted $var will temporarily switch it off) */
2482 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2485 debug_print_list("expand_variables", &output, n);
2487 /* output.data (malloced in one block) gets returned in "list" */
2488 list = o_finalize_list(&output, n);
2489 debug_print_strings("expand_variables[1]", list);
2493 static char **expand_strvec_to_strvec(char **argv)
2495 return expand_variables(argv, 0x100);
2498 #if ENABLE_HUSH_BASH_COMPAT
2499 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2501 return expand_variables(argv, 0x80);
2505 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2506 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2511 o_string output = NULL_O_STRING;
2516 int is_var = is_well_formed_var_name(*v, '=');
2517 /* is_var * 0x80: singleword expansion for vars */
2518 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2520 /* Subtle! expand_vars_to_list did not glob last word yet.
2521 * It does this only when fed with further data.
2522 * Therefore we set globbing flags AFTER it, not before:
2525 /* if it is not recognizably abc=...; then: */
2526 output.o_escape = !is_var; /* protect against globbing for "$var" */
2527 /* (unquoted $var will temporarily switch it off) */
2528 output.o_glob = !is_var; /* and indeed do globbing */
2531 debug_print_list("expand_cond", &output, n);
2533 /* output.data (malloced in one block) gets returned in "list" */
2534 list = o_finalize_list(&output, n);
2535 debug_print_strings("expand_cond[1]", list);
2540 /* Used for expansion of right hand of assignments */
2541 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2543 static char *expand_string_to_string(const char *str)
2545 char *argv[2], **list;
2547 argv[0] = (char*)str;
2549 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2551 if (!list[0] || list[1])
2552 bb_error_msg_and_die("BUG in varexp2");
2553 /* actually, just move string 2*sizeof(char*) bytes back */
2554 overlapping_strcpy((char*)list, list[0]);
2555 unbackslash((char*)list);
2556 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2560 /* Used for "eval" builtin */
2561 static char* expand_strvec_to_string(char **argv)
2565 list = expand_variables(argv, 0x80);
2566 /* Convert all NULs to spaces */
2571 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2572 bb_error_msg_and_die("BUG in varexp3");
2573 /* bash uses ' ' regardless of $IFS contents */
2578 overlapping_strcpy((char*)list, list[0]);
2579 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2583 static char **expand_assignments(char **argv, int count)
2587 /* Expand assignments into one string each */
2588 for (i = 0; i < count; i++) {
2589 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2597 void re_execute_shell(char ***to_free, const char *s,
2598 char *g_argv0, char **g_argv,
2599 char **builtin_argv) NORETURN;
2601 static void reset_traps_to_defaults(void)
2603 /* This function is always called in a child shell
2604 * after fork (not vfork, NOMMU doesn't use this function).
2609 /* Child shells are not interactive.
2610 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2611 * Testcase: (while :; do :; done) + ^Z should background.
2612 * Same goes for SIGTERM, SIGHUP, SIGINT.
2614 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2615 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
2617 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2618 * Stupid. It can be done with *single* &= op, but we can't use
2619 * the fact that G.blocked_set is implemented as a bitmask
2621 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2625 /* Careful. Only if no trap or trap is not "" */
2626 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2627 sigdelset(&G.blocked_set, sig);
2634 /* Our homegrown sig mask is saner to work with :) */
2635 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2637 /* Resetting all traps to default except empty ones */
2638 mask = G.non_DFL_mask;
2639 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2640 if (!G.traps[sig] || !G.traps[sig][0])
2643 G.traps[sig] = NULL;
2644 /* There is no signal for 0 (EXIT) */
2647 /* There was a trap handler, we just removed it.
2648 * But if sig still has non-DFL handling,
2649 * we should not unblock the sig. */
2652 sigdelset(&G.blocked_set, sig);
2654 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2659 static void re_execute_shell(char ***to_free, const char *s,
2660 char *g_argv0, char **g_argv,
2661 char **builtin_argv) NORETURN;
2662 static void re_execute_shell(char ***to_free, const char *s,
2663 char *g_argv0, char **g_argv,
2664 char **builtin_argv)
2666 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2667 char *heredoc_argv[4];
2668 struct variable *cur;
2669 #if ENABLE_HUSH_FUNCTIONS
2670 struct function *funcp;
2675 if (!g_argv0) { /* heredoc */
2676 argv = heredoc_argv;
2677 argv[0] = (char *) G.argv0_for_re_execing;
2678 argv[1] = (char *) "-<";
2679 argv[2] = (char *) s;
2681 pp = &argv[3]; /* used as pointer to empty environment */
2687 if (pp) while (*pp++)
2690 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2691 , (unsigned) G.root_pid
2692 , (unsigned) G.last_bg_pid
2693 , (unsigned) G.last_exitcode
2695 IF_HUSH_LOOPS(, G.depth_of_loop)
2697 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2698 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2701 for (cur = G.top_var; cur; cur = cur->next) {
2702 if (!cur->flg_export || cur->flg_read_only)
2705 #if ENABLE_HUSH_FUNCTIONS
2706 for (funcp = G.top_func; funcp; funcp = funcp->next)
2712 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2713 *pp++ = (char *) G.argv0_for_re_execing;
2715 for (cur = G.top_var; cur; cur = cur->next) {
2716 if (cur->varstr == hush_version_str)
2718 if (cur->flg_read_only) {
2719 *pp++ = (char *) "-R";
2720 *pp++ = cur->varstr;
2721 } else if (!cur->flg_export) {
2722 *pp++ = (char *) "-V";
2723 *pp++ = cur->varstr;
2726 #if ENABLE_HUSH_FUNCTIONS
2727 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2728 *pp++ = (char *) "-F";
2729 *pp++ = funcp->name;
2730 *pp++ = funcp->body_as_string;
2733 /* We can pass activated traps here. Say, -Tnn:trap_string
2735 * However, POSIX says that subshells reset signals with traps
2737 * I tested bash-3.2 and it not only does that with true subshells
2738 * of the form ( list ), but with any forked children shells.
2739 * I set trap "echo W" WINCH; and then tried:
2741 * { echo 1; sleep 20; echo 2; } &
2742 * while true; do echo 1; sleep 20; echo 2; break; done &
2743 * true | { echo 1; sleep 20; echo 2; } | cat
2745 * In all these cases sending SIGWINCH to the child shell
2746 * did not run the trap. If I add trap "echo V" WINCH;
2747 * _inside_ group (just before echo 1), it works.
2749 * I conclude it means we don't need to pass active traps here.
2750 * exec syscall below resets them to SIG_DFL for us.
2752 *pp++ = (char *) "-c";
2755 while (*++builtin_argv)
2756 *pp++ = *builtin_argv;
2757 *pp++ = (char *) "";
2762 /* *pp = NULL; - is already there */
2766 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2767 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2768 execve(bb_busybox_exec_path, argv, pp);
2769 /* Fallback. Useful for init=/bin/hush usage etc */
2770 if (argv[0][0] == '/')
2771 execve(argv[0], argv, pp);
2772 xfunc_error_retval = 127;
2773 bb_error_msg_and_die("can't re-execute the shell");
2775 #endif /* !BB_MMU */
2778 static void setup_heredoc(struct redir_struct *redir)
2780 struct fd_pair pair;
2783 /* the _body_ of heredoc (misleading field name) */
2784 const char *heredoc = redir->rd_filename;
2791 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2792 expanded = expand_pseudo_dquoted(heredoc);
2796 len = strlen(heredoc);
2798 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2800 xmove_fd(pair.rd, redir->rd_fd);
2802 /* Try writing without forking. Newer kernels have
2803 * dynamically growing pipes. Must use non-blocking write! */
2806 written = write(pair.wr, heredoc, len);
2817 ndelay_off(pair.wr);
2819 /* Okay, pipe buffer was not big enough */
2820 /* Note: we must not create a stray child (bastard? :)
2821 * for the unsuspecting parent process. Child creates a grandchild
2822 * and exits before parent execs the process which consumes heredoc
2823 * (that exec happens after we return from this function) */
2829 bb_perror_msg_and_die("vfork");
2832 disable_restore_tty_pgrp_on_exit();
2833 pid = BB_MMU ? fork() : vfork();
2835 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2839 close(redir->rd_fd); /* read side of the pipe */
2841 full_write(pair.wr, heredoc, len); /* may loop or block */
2844 /* Delegate blocking writes to another process */
2845 xmove_fd(pair.wr, STDOUT_FILENO);
2846 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2850 #if ENABLE_HUSH_FAST
2852 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2854 enable_restore_tty_pgrp_on_exit();
2860 wait(NULL); /* wait till child has died */
2863 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2864 * and stderr if they are redirected. */
2865 static int setup_redirects(struct command *prog, int squirrel[])
2868 struct redir_struct *redir;
2870 for (redir = prog->redirects; redir; redir = redir->next) {
2871 if (redir->rd_type == REDIRECT_HEREDOC2) {
2872 /* rd_fd<<HERE case */
2873 if (squirrel && redir->rd_fd < 3
2874 && squirrel[redir->rd_fd] < 0
2876 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2878 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2880 debug_printf_parse("set heredoc '%s'\n",
2881 redir->rd_filename);
2882 setup_heredoc(redir);
2886 if (redir->rd_dup == REDIRFD_TO_FILE) {
2887 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2889 if (redir->rd_filename == NULL) {
2890 /* Something went wrong in the parse.
2891 * Pretend it didn't happen */
2892 bb_error_msg("bug in redirect parse");
2895 mode = redir_table[redir->rd_type].mode;
2896 p = expand_string_to_string(redir->rd_filename);
2897 openfd = open_or_warn(p, mode);
2900 /* this could get lost if stderr has been redirected, but
2901 * bash and ash both lose it as well (though zsh doesn't!) */
2902 //what the above comment tries to say?
2906 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2907 openfd = redir->rd_dup;
2910 if (openfd != redir->rd_fd) {
2911 if (squirrel && redir->rd_fd < 3
2912 && squirrel[redir->rd_fd] < 0
2914 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2916 if (openfd == REDIRFD_CLOSE) {
2917 /* "n>-" means "close me" */
2918 close(redir->rd_fd);
2920 xdup2(openfd, redir->rd_fd);
2921 if (redir->rd_dup == REDIRFD_TO_FILE)
2929 static void restore_redirects(int squirrel[])
2932 for (i = 0; i < 3; i++) {
2935 /* We simply die on error */
2942 static void free_pipe_list(struct pipe *head);
2944 /* Return code is the exit status of the pipe */
2945 static void free_pipe(struct pipe *pi)
2948 struct command *command;
2949 struct redir_struct *r, *rnext;
2952 if (pi->stopped_cmds > 0) /* why? */
2954 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2955 for (i = 0; i < pi->num_cmds; i++) {
2956 command = &pi->cmds[i];
2957 debug_printf_clean(" command %d:\n", i);
2958 if (command->argv) {
2959 for (a = 0, p = command->argv; *p; a++, p++) {
2960 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2962 free_strings(command->argv);
2963 command->argv = NULL;
2965 /* not "else if": on syntax error, we may have both! */
2966 if (command->group) {
2967 debug_printf_clean(" begin group (cmd_type:%d)\n",
2969 free_pipe_list(command->group);
2970 debug_printf_clean(" end group\n");
2971 command->group = NULL;
2973 /* else is crucial here.
2974 * If group != NULL, child_func is meaningless */
2975 #if ENABLE_HUSH_FUNCTIONS
2976 else if (command->child_func) {
2977 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2978 command->child_func->parent_cmd = NULL;
2982 free(command->group_as_string);
2983 command->group_as_string = NULL;
2985 for (r = command->redirects; r; r = rnext) {
2986 debug_printf_clean(" redirect %d%s",
2987 r->rd_fd, redir_table[r->rd_type].descrip);
2988 /* guard against the case >$FOO, where foo is unset or blank */
2989 if (r->rd_filename) {
2990 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2991 free(r->rd_filename);
2992 r->rd_filename = NULL;
2994 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2998 command->redirects = NULL;
3000 free(pi->cmds); /* children are an array, they get freed all at once */
3008 static void free_pipe_list(struct pipe *head)
3010 struct pipe *pi, *next;
3012 for (pi = head; pi; pi = next) {
3014 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3017 debug_printf_clean("pipe followup code %d\n", pi->followup);
3019 /*pi->next = NULL;*/
3025 static int run_list(struct pipe *pi);
3027 #define parse_stream(pstring, input, end_trigger) \
3028 parse_stream(input, end_trigger)
3030 static struct pipe *parse_stream(char **pstring,
3031 struct in_str *input,
3033 static void parse_and_run_string(const char *s);
3036 static char *find_in_path(const char *arg)
3039 const char *PATH = get_local_var_value("PATH");
3045 const char *end = strchrnul(PATH, ':');
3046 int sz = end - PATH; /* must be int! */
3050 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3052 /* We have xxx::yyyy in $PATH,
3053 * it means "use current dir" */
3056 if (access(ret, F_OK) == 0)
3069 static const struct built_in_command* find_builtin_helper(const char *name,
3070 const struct built_in_command *x,
3071 const struct built_in_command *end)
3074 if (strcmp(name, x->cmd) != 0) {
3078 debug_printf_exec("found builtin '%s'\n", name);
3083 static const struct built_in_command* find_builtin1(const char *name)
3085 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3087 static const struct built_in_command* find_builtin(const char *name)
3089 const struct built_in_command *x = find_builtin1(name);
3092 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3095 #if ENABLE_HUSH_FUNCTIONS
3096 static struct function **find_function_slot(const char *name)
3098 struct function **funcpp = &G.top_func;
3100 if (strcmp(name, (*funcpp)->name) == 0) {
3103 funcpp = &(*funcpp)->next;
3108 static const struct function *find_function(const char *name)
3110 const struct function *funcp = *find_function_slot(name);
3112 debug_printf_exec("found function '%s'\n", name);
3116 /* Note: takes ownership on name ptr */
3117 static struct function *new_function(char *name)
3119 struct function **funcpp = find_function_slot(name);
3120 struct function *funcp = *funcpp;
3122 if (funcp != NULL) {
3123 struct command *cmd = funcp->parent_cmd;
3124 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3126 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3128 /* Note: if !funcp->body, do not free body_as_string!
3129 * This is a special case of "-F name body" function:
3130 * body_as_string was not malloced! */
3132 free_pipe_list(funcp->body);
3134 free(funcp->body_as_string);
3138 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3139 cmd->argv[0] = funcp->name;
3140 cmd->group = funcp->body;
3142 cmd->group_as_string = funcp->body_as_string;
3146 debug_printf_exec("remembering new function '%s'\n", name);
3147 funcp = *funcpp = xzalloc(sizeof(*funcp));
3148 /*funcp->next = NULL;*/
3155 static void unset_func(const char *name)
3157 struct function **funcpp = find_function_slot(name);
3158 struct function *funcp = *funcpp;
3160 if (funcp != NULL) {
3161 debug_printf_exec("freeing function '%s'\n", funcp->name);
3162 *funcpp = funcp->next;
3163 /* funcp is unlinked now, deleting it.
3164 * Note: if !funcp->body, the function was created by
3165 * "-F name body", do not free ->body_as_string
3166 * and ->name as they were not malloced. */
3168 free_pipe_list(funcp->body);
3171 free(funcp->body_as_string);
3179 #define exec_function(to_free, funcp, argv) \
3180 exec_function(funcp, argv)
3182 static void exec_function(char ***to_free,
3183 const struct function *funcp,
3184 char **argv) NORETURN;
3185 static void exec_function(char ***to_free,
3186 const struct function *funcp,
3192 argv[0] = G.global_argv[0];
3193 G.global_argv = argv;
3197 /* On MMU, funcp->body is always non-NULL */
3198 n = run_list(funcp->body);
3202 re_execute_shell(to_free,
3203 funcp->body_as_string,
3210 static int run_function(const struct function *funcp, char **argv)
3216 save_and_replace_G_args(&sv, argv);
3218 /* "we are in function, ok to use return" */
3219 sv_flg = G.flag_return_in_progress;
3220 G.flag_return_in_progress = -1;
3221 #if ENABLE_HUSH_LOCAL
3222 G.func_nest_level++;
3225 /* On MMU, funcp->body is always non-NULL */
3228 /* Function defined by -F */
3229 parse_and_run_string(funcp->body_as_string);
3230 rc = G.last_exitcode;
3234 rc = run_list(funcp->body);
3237 #if ENABLE_HUSH_LOCAL
3239 struct variable *var;
3240 struct variable **var_pp;
3242 var_pp = &G.top_var;
3243 while ((var = *var_pp) != NULL) {
3244 if (var->func_nest_level < G.func_nest_level) {
3245 var_pp = &var->next;
3249 if (var->flg_export)
3250 bb_unsetenv(var->varstr);
3251 /* Remove from global list */
3252 *var_pp = var->next;
3258 G.func_nest_level--;
3261 G.flag_return_in_progress = sv_flg;
3263 restore_G_args(&sv, argv);
3267 #endif /* ENABLE_HUSH_FUNCTIONS */
3271 #define exec_builtin(to_free, x, argv) \
3272 exec_builtin(x, argv)
3274 #define exec_builtin(to_free, x, argv) \
3275 exec_builtin(to_free, argv)
3277 static void exec_builtin(char ***to_free,
3278 const struct built_in_command *x,
3279 char **argv) NORETURN;
3280 static void exec_builtin(char ***to_free,
3281 const struct built_in_command *x,
3285 int rcode = x->function(argv);
3289 /* On NOMMU, we must never block!
3290 * Example: { sleep 99 | read line; } & echo Ok
3292 re_execute_shell(to_free,
3302 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3303 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3304 #define pseudo_exec(nommu_save, command, argv_expanded) \
3305 pseudo_exec(command, argv_expanded)
3308 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3310 * Don't exit() here. If you don't exec, use _exit instead.
3311 * The at_exit handlers apparently confuse the calling process,
3312 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3313 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3314 char **argv, int assignment_cnt,
3315 char **argv_expanded) NORETURN;
3316 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3317 char **argv, int assignment_cnt,
3318 char **argv_expanded)
3322 /* Case when we are here: ... | var=val | ... */
3323 if (!argv[assignment_cnt])
3324 _exit(EXIT_SUCCESS);
3326 new_env = expand_assignments(argv, assignment_cnt);
3328 set_vars_and_save_old(new_env);
3329 free(new_env); /* optional */
3330 /* we can also destroy set_vars_and_save_old's return value,
3333 nommu_save->new_env = new_env;
3334 nommu_save->old_vars = set_vars_and_save_old(new_env);
3336 if (argv_expanded) {
3337 argv = argv_expanded;
3339 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3341 nommu_save->argv = argv;
3345 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3346 if (strchr(argv[0], '/') != NULL)
3350 /* Check if the command matches any of the builtins.
3351 * Depending on context, this might be redundant. But it's
3352 * easier to waste a few CPU cycles than it is to figure out
3353 * if this is one of those cases.
3356 /* On NOMMU, it is more expensive to re-execute shell
3357 * just in order to run echo or test builtin.
3358 * It's better to skip it here and run corresponding
3359 * non-builtin later. */
3360 const struct built_in_command *x;
3361 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3363 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3366 #if ENABLE_HUSH_FUNCTIONS
3367 /* Check if the command matches any functions */
3369 const struct function *funcp = find_function(argv[0]);
3371 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3376 #if ENABLE_FEATURE_SH_STANDALONE
3377 /* Check if the command matches any busybox applets */
3379 int a = find_applet_by_name(argv[0]);
3381 # if BB_MMU /* see above why on NOMMU it is not allowed */
3382 if (APPLET_IS_NOEXEC(a)) {
3383 debug_printf_exec("running applet '%s'\n", argv[0]);
3384 run_applet_no_and_exit(a, argv);
3387 /* Re-exec ourselves */
3388 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3389 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3390 execv(bb_busybox_exec_path, argv);
3391 /* If they called chroot or otherwise made the binary no longer
3392 * executable, fall through */
3397 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3400 debug_printf_exec("execing '%s'\n", argv[0]);
3401 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3402 execvp(argv[0], argv);
3403 bb_perror_msg("can't execute '%s'", argv[0]);
3404 _exit(EXIT_FAILURE);
3407 /* Called after [v]fork() in run_pipe
3409 static void pseudo_exec(nommu_save_t *nommu_save,
3410 struct command *command,
3411 char **argv_expanded) NORETURN;
3412 static void pseudo_exec(nommu_save_t *nommu_save,
3413 struct command *command,
3414 char **argv_expanded)
3416 if (command->argv) {
3417 pseudo_exec_argv(nommu_save, command->argv,
3418 command->assignment_cnt, argv_expanded);
3421 if (command->group) {
3422 /* Cases when we are here:
3425 * ... | ( list ) | ...
3426 * ... | { list } | ...
3430 debug_printf_exec("pseudo_exec: run_list\n");
3431 reset_traps_to_defaults();
3432 rcode = run_list(command->group);
3433 /* OK to leak memory by not calling free_pipe_list,
3434 * since this process is about to exit */
3437 re_execute_shell(&nommu_save->argv_from_re_execing,
3438 command->group_as_string,
3445 /* Case when we are here: ... | >file */
3446 debug_printf_exec("pseudo_exec'ed null command\n");
3447 _exit(EXIT_SUCCESS);
3451 static const char *get_cmdtext(struct pipe *pi)
3457 /* This is subtle. ->cmdtext is created only on first backgrounding.
3458 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3459 * On subsequent bg argv is trashed, but we won't use it */
3462 argv = pi->cmds[0].argv;
3463 if (!argv || !argv[0]) {
3464 pi->cmdtext = xzalloc(1);
3470 len += strlen(*argv) + 1;
3474 argv = pi->cmds[0].argv;
3476 len = strlen(*argv);
3477 memcpy(p, *argv, len);
3485 static void insert_bg_job(struct pipe *pi)
3487 struct pipe *job, **jobp;
3490 /* Linear search for the ID of the job to use */
3492 for (job = G.job_list; job; job = job->next)
3493 if (job->jobid >= pi->jobid)
3494 pi->jobid = job->jobid + 1;
3496 /* Add job to the list of running jobs */
3498 while ((job = *jobp) != NULL)
3500 job = *jobp = xmalloc(sizeof(*job));
3502 *job = *pi; /* physical copy */
3504 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3505 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3506 for (i = 0; i < pi->num_cmds; i++) {
3507 job->cmds[i].pid = pi->cmds[i].pid;
3508 /* all other fields are not used and stay zero */
3510 job->cmdtext = xstrdup(get_cmdtext(pi));
3512 if (G_interactive_fd)
3513 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3514 /* Last command's pid goes to $! */
3515 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3516 G.last_jobid = job->jobid;
3519 static void remove_bg_job(struct pipe *pi)
3521 struct pipe *prev_pipe;
3523 if (pi == G.job_list) {
3524 G.job_list = pi->next;
3526 prev_pipe = G.job_list;
3527 while (prev_pipe->next != pi)
3528 prev_pipe = prev_pipe->next;
3529 prev_pipe->next = pi->next;
3532 G.last_jobid = G.job_list->jobid;
3537 /* Remove a backgrounded job */
3538 static void delete_finished_bg_job(struct pipe *pi)
3541 pi->stopped_cmds = 0;
3547 /* Check to see if any processes have exited -- if they
3548 * have, figure out why and see if a job has completed */
3549 static int checkjobs(struct pipe* fg_pipe)
3559 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3561 attributes = WUNTRACED;
3562 if (fg_pipe == NULL)
3563 attributes |= WNOHANG;
3566 #if ENABLE_HUSH_FAST
3567 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3568 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3569 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3570 /* There was neither fork nor SIGCHLD since last waitpid */
3571 /* Avoid doing waitpid syscall if possible */
3572 if (!G.we_have_children) {
3576 if (fg_pipe == NULL) { /* is WNOHANG set? */
3577 /* We have children, but they did not exit
3578 * or stop yet (we saw no SIGCHLD) */
3581 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3585 /* Do we do this right?
3586 * bash-3.00# sleep 20 | false
3588 * [3]+ Stopped sleep 20 | false
3589 * bash-3.00# echo $?
3590 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3591 * [hush 1.14.0: yes we do it right]
3598 #if ENABLE_HUSH_FAST
3599 i = G.count_SIGCHLD;
3601 childpid = waitpid(-1, &status, attributes);
3602 if (childpid <= 0) {
3603 if (childpid && errno != ECHILD)
3604 bb_perror_msg("waitpid");
3605 #if ENABLE_HUSH_FAST
3606 else { /* Until next SIGCHLD, waitpid's are useless */
3607 G.we_have_children = (childpid == 0);
3608 G.handled_SIGCHLD = i;
3609 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3614 dead = WIFEXITED(status) || WIFSIGNALED(status);
3617 if (WIFSTOPPED(status))
3618 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3619 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3620 if (WIFSIGNALED(status))
3621 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3622 childpid, WTERMSIG(status), WEXITSTATUS(status));
3623 if (WIFEXITED(status))
3624 debug_printf_jobs("pid %d exited, exitcode %d\n",
3625 childpid, WEXITSTATUS(status));
3627 /* Were we asked to wait for fg pipe? */
3629 for (i = 0; i < fg_pipe->num_cmds; i++) {
3630 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3631 if (fg_pipe->cmds[i].pid != childpid)
3634 fg_pipe->cmds[i].pid = 0;
3635 fg_pipe->alive_cmds--;
3636 if (i == fg_pipe->num_cmds - 1) {
3637 /* last process gives overall exitstatus */
3638 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3639 rcode = WEXITSTATUS(status);
3640 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3641 /* bash prints killer signal's name for *last*
3642 * process in pipe (prints just newline for SIGINT).
3643 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
3645 if (WIFSIGNALED(status)) {
3646 int sig = WTERMSIG(status);
3647 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3651 fg_pipe->cmds[i].is_stopped = 1;
3652 fg_pipe->stopped_cmds++;
3654 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3655 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3656 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3657 /* All processes in fg pipe have exited or stopped */
3658 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3659 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3660 * and "killall -STOP cat" */
3661 if (G_interactive_fd) {
3663 if (fg_pipe->alive_cmds)
3664 insert_bg_job(fg_pipe);
3668 if (!fg_pipe->alive_cmds)
3671 /* There are still running processes in the fg pipe */
3672 goto wait_more; /* do waitpid again */
3674 /* it wasnt fg_pipe, look for process in bg pipes */
3678 /* We asked to wait for bg or orphaned children */
3679 /* No need to remember exitcode in this case */
3680 for (pi = G.job_list; pi; pi = pi->next) {
3681 for (i = 0; i < pi->num_cmds; i++) {
3682 if (pi->cmds[i].pid == childpid)
3683 goto found_pi_and_prognum;
3686 /* Happens when shell is used as init process (init=/bin/sh) */
3687 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3688 continue; /* do waitpid again */
3690 found_pi_and_prognum:
3693 pi->cmds[i].pid = 0;
3695 if (!pi->alive_cmds) {
3696 if (G_interactive_fd)
3697 printf(JOB_STATUS_FORMAT, pi->jobid,
3698 "Done", pi->cmdtext);
3699 delete_finished_bg_job(pi);
3703 pi->cmds[i].is_stopped = 1;
3707 } /* while (waitpid succeeds)... */
3713 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3716 int rcode = checkjobs(fg_pipe);
3717 if (G_saved_tty_pgrp) {
3718 /* Job finished, move the shell to the foreground */
3719 p = getpgrp(); /* our process group id */
3720 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3721 tcsetpgrp(G_interactive_fd, p);
3727 /* Start all the jobs, but don't wait for anything to finish.
3730 * Return code is normally -1, when the caller has to wait for children
3731 * to finish to determine the exit status of the pipe. If the pipe
3732 * is a simple builtin command, however, the action is done by the
3733 * time run_pipe returns, and the exit code is provided as the
3736 * Returns -1 only if started some children. IOW: we have to
3737 * mask out retvals of builtins etc with 0xff!
3739 * The only case when we do not need to [v]fork is when the pipe
3740 * is single, non-backgrounded, non-subshell command. Examples:
3741 * cmd ; ... { list } ; ...
3742 * cmd && ... { list } && ...
3743 * cmd || ... { list } || ...
3744 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3745 * or (if SH_STANDALONE) an applet, and we can run the { list }
3746 * with run_list. If it isn't one of these, we fork and exec cmd.
3748 * Cases when we must fork:
3749 * non-single: cmd | cmd
3750 * backgrounded: cmd & { list } &
3751 * subshell: ( list ) [&]
3753 static int run_pipe(struct pipe *pi)
3755 static const char *const null_ptr = NULL;
3758 struct command *command;
3759 char **argv_expanded;
3762 /* it is not always needed, but we aim to smaller code */
3763 int squirrel[] = { -1, -1, -1 };
3766 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3769 IF_HUSH_JOB(pi->pgrp = -1;)
3770 pi->stopped_cmds = 0;
3771 command = &(pi->cmds[0]);
3772 argv_expanded = NULL;
3774 if (pi->num_cmds != 1
3775 || pi->followup == PIPE_BG
3776 || command->cmd_type == CMD_SUBSHELL
3783 debug_printf_exec(": group:%p argv:'%s'\n",
3784 command->group, command->argv ? command->argv[0] : "NONE");
3786 if (command->group) {
3787 #if ENABLE_HUSH_FUNCTIONS
3788 if (command->cmd_type == CMD_FUNCDEF) {
3789 /* "executing" func () { list } */
3790 struct function *funcp;
3792 funcp = new_function(command->argv[0]);
3793 /* funcp->name is already set to argv[0] */
3794 funcp->body = command->group;
3796 funcp->body_as_string = command->group_as_string;
3797 command->group_as_string = NULL;
3799 command->group = NULL;
3800 command->argv[0] = NULL;
3801 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3802 funcp->parent_cmd = command;
3803 command->child_func = funcp;
3805 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3807 return EXIT_SUCCESS;
3811 debug_printf("non-subshell group\n");
3812 rcode = 1; /* exitcode if redir failed */
3813 if (setup_redirects(command, squirrel) == 0) {
3814 debug_printf_exec(": run_list\n");
3815 rcode = run_list(command->group) & 0xff;
3817 restore_redirects(squirrel);
3818 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3820 debug_printf_exec("run_pipe: return %d\n", rcode);
3824 argv = command->argv ? command->argv : (char **) &null_ptr;
3826 const struct built_in_command *x;
3827 #if ENABLE_HUSH_FUNCTIONS
3828 const struct function *funcp;
3832 char **new_env = NULL;
3833 struct variable *old_vars = NULL;
3835 if (argv[command->assignment_cnt] == NULL) {
3836 /* Assignments, but no command */
3837 /* Ensure redirects take effect. Try "a=t >file" */
3838 rcode = setup_redirects(command, squirrel);
3839 restore_redirects(squirrel);
3840 /* Set shell variables */
3842 p = expand_string_to_string(*argv);
3843 debug_printf_exec("set shell var:'%s'->'%s'\n",
3845 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3848 /* Do we need to flag set_local_var() errors?
3849 * "assignment to readonly var" and "putenv error"
3851 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3853 debug_printf_exec("run_pipe: return %d\n", rcode);
3857 /* Expand the rest into (possibly) many strings each */
3859 #if ENABLE_HUSH_BASH_COMPAT
3860 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3861 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3864 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3865 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3866 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3871 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3874 x = find_builtin(argv_expanded[0]);
3875 #if ENABLE_HUSH_FUNCTIONS
3878 funcp = find_function(argv_expanded[0]);
3882 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3883 debug_printf("exec with redirects only\n");
3884 rcode = setup_redirects(command, NULL);
3885 goto clean_up_and_ret1;
3888 /* setup_redirects acts on file descriptors, not FILEs.
3889 * This is perfect for work that comes after exec().
3890 * Is it really safe for inline use? Experimentally,
3891 * things seem to work. */
3892 rcode = setup_redirects(command, squirrel);
3894 new_env = expand_assignments(argv, command->assignment_cnt);
3895 old_vars = set_vars_and_save_old(new_env);
3897 debug_printf_exec(": builtin '%s' '%s'...\n",
3898 x->cmd, argv_expanded[1]);
3899 rcode = x->function(argv_expanded) & 0xff;
3902 #if ENABLE_HUSH_FUNCTIONS
3904 # if ENABLE_HUSH_LOCAL
3905 struct variable **sv;
3906 sv = G.shadowed_vars_pp;
3907 G.shadowed_vars_pp = &old_vars;
3909 debug_printf_exec(": function '%s' '%s'...\n",
3910 funcp->name, argv_expanded[1]);
3911 rcode = run_function(funcp, argv_expanded) & 0xff;
3912 # if ENABLE_HUSH_LOCAL
3913 G.shadowed_vars_pp = sv;
3918 #if ENABLE_FEATURE_SH_STANDALONE
3921 restore_redirects(squirrel);
3922 unset_vars(new_env);
3925 free(argv_expanded);
3926 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3928 debug_printf_exec("run_pipe return %d\n", rcode);
3932 #if ENABLE_FEATURE_SH_STANDALONE
3933 i = find_applet_by_name(argv_expanded[0]);
3934 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3935 rcode = setup_redirects(command, squirrel);
3937 new_env = expand_assignments(argv, command->assignment_cnt);
3938 old_vars = set_vars_and_save_old(new_env);
3939 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3940 argv_expanded[0], argv_expanded[1]);
3941 rcode = run_nofork_applet(i, argv_expanded);
3943 goto clean_up_and_ret;
3946 /* It is neither builtin nor applet. We must fork. */
3950 /* NB: argv_expanded may already be created, and that
3951 * might include `cmd` runs! Do not rerun it! We *must*
3952 * use argv_expanded if it's non-NULL */
3954 /* Going to fork a child per each pipe member */
3958 for (i = 0; i < pi->num_cmds; i++) {
3959 struct fd_pair pipefds;
3961 volatile nommu_save_t nommu_save;
3962 nommu_save.new_env = NULL;
3963 nommu_save.old_vars = NULL;
3964 nommu_save.argv = NULL;
3965 nommu_save.argv_from_re_execing = NULL;
3967 command = &(pi->cmds[i]);
3968 if (command->argv) {
3969 debug_printf_exec(": pipe member '%s' '%s'...\n",
3970 command->argv[0], command->argv[1]);
3972 debug_printf_exec(": pipe member with no argv\n");
3975 /* pipes are inserted between pairs of commands */
3978 if ((i + 1) < pi->num_cmds)
3979 xpiped_pair(pipefds);
3981 command->pid = BB_MMU ? fork() : vfork();
3982 if (!command->pid) { /* child */
3984 disable_restore_tty_pgrp_on_exit();
3986 /* Every child adds itself to new process group
3987 * with pgid == pid_of_first_child_in_pipe */
3988 if (G.run_list_level == 1 && G_interactive_fd) {
3991 if (pgrp < 0) /* true for 1st process only */
3993 if (setpgid(0, pgrp) == 0
3994 && pi->followup != PIPE_BG
3995 && G_saved_tty_pgrp /* we have ctty */
3997 /* We do it in *every* child, not just first,
3999 tcsetpgrp(G_interactive_fd, pgrp);
4003 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4004 /* 1st cmd in backgrounded pipe
4005 * should have its stdin /dev/null'ed */
4007 if (open(bb_dev_null, O_RDONLY))
4008 xopen("/", O_RDONLY);
4010 xmove_fd(nextin, 0);
4012 xmove_fd(pipefds.wr, 1);
4015 /* Like bash, explicit redirects override pipes,
4016 * and the pipe fd is available for dup'ing. */
4017 if (setup_redirects(command, NULL))
4020 /* Restore default handlers just prior to exec */
4021 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4023 /* Stores to nommu_save list of env vars putenv'ed
4024 * (NOMMU, on MMU we don't need that) */
4025 /* cast away volatility... */
4026 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4027 /* pseudo_exec() does not return */
4030 /* parent or error */
4031 #if ENABLE_HUSH_FAST
4033 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4035 enable_restore_tty_pgrp_on_exit();
4037 /* Clean up after vforked child */
4038 free(nommu_save.argv);
4039 free(nommu_save.argv_from_re_execing);
4040 unset_vars(nommu_save.new_env);
4041 add_vars(nommu_save.old_vars);
4043 free(argv_expanded);
4044 argv_expanded = NULL;
4045 if (command->pid < 0) { /* [v]fork failed */
4046 /* Clearly indicate, was it fork or vfork */
4047 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4051 /* Second and next children need to know pid of first one */
4053 pi->pgrp = command->pid;
4059 if ((i + 1) < pi->num_cmds)
4061 /* Pass read (output) pipe end to next iteration */
4062 nextin = pipefds.rd;
4065 if (!pi->alive_cmds) {
4067 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4072 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4076 #ifndef debug_print_tree
4077 static void debug_print_tree(struct pipe *pi, int lvl)
4079 static const char *const PIPE[] = {
4085 static const char *RES[] = {
4086 [RES_NONE ] = "NONE" ,
4089 [RES_THEN ] = "THEN" ,
4090 [RES_ELIF ] = "ELIF" ,
4091 [RES_ELSE ] = "ELSE" ,
4094 #if ENABLE_HUSH_LOOPS
4095 [RES_FOR ] = "FOR" ,
4096 [RES_WHILE] = "WHILE",
4097 [RES_UNTIL] = "UNTIL",
4099 [RES_DONE ] = "DONE" ,
4101 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4104 #if ENABLE_HUSH_CASE
4105 [RES_CASE ] = "CASE" ,
4106 [RES_CASE_IN ] = "CASE_IN" ,
4107 [RES_MATCH] = "MATCH",
4108 [RES_CASE_BODY] = "CASE_BODY",
4109 [RES_ESAC ] = "ESAC" ,
4111 [RES_XXXX ] = "XXXX" ,
4112 [RES_SNTX ] = "SNTX" ,
4114 static const char *const CMDTYPE[] = {
4118 #if ENABLE_HUSH_FUNCTIONS
4127 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4128 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4130 while (prn < pi->num_cmds) {
4131 struct command *command = &pi->cmds[prn];
4132 char **argv = command->argv;
4134 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4136 command->assignment_cnt);
4137 if (command->group) {
4138 fprintf(stderr, " group %s: (argv=%p)\n",
4139 CMDTYPE[command->cmd_type],
4141 debug_print_tree(command->group, lvl+1);
4145 if (argv) while (*argv) {
4146 fprintf(stderr, " '%s'", *argv);
4149 fprintf(stderr, "\n");
4158 /* NB: called by pseudo_exec, and therefore must not modify any
4159 * global data until exec/_exit (we can be a child after vfork!) */
4160 static int run_list(struct pipe *pi)
4162 #if ENABLE_HUSH_CASE
4163 char *case_word = NULL;
4165 #if ENABLE_HUSH_LOOPS
4166 struct pipe *loop_top = NULL;
4167 char **for_lcur = NULL;
4168 char **for_list = NULL;
4170 smallint last_followup;
4172 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4173 smalluint cond_code = 0;
4175 enum { cond_code = 0 };
4178 smallint rword; /* enum reserved_style */
4179 smallint last_rword; /* ditto */
4182 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4185 #if ENABLE_HUSH_LOOPS
4186 /* Check syntax for "for" */
4187 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4188 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4190 /* current word is FOR or IN (BOLD in comments below) */
4191 if (cpipe->next == NULL) {
4192 syntax_error("malformed for");
4194 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4197 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4198 if (cpipe->next->res_word == RES_DO)
4200 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4201 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4202 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4204 syntax_error("malformed for");
4206 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4212 /* Past this point, all code paths should jump to ret: label
4213 * in order to return, no direct "return" statements please.
4214 * This helps to ensure that no memory is leaked. */
4222 last_rword = RES_XXXX;
4224 last_followup = PIPE_SEQ;
4225 rcode = G.last_exitcode;
4227 /* Go through list of pipes, (maybe) executing them. */
4228 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4232 IF_HAS_KEYWORDS(rword = pi->res_word;)
4233 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4234 rword, cond_code, last_rword);
4235 #if ENABLE_HUSH_LOOPS
4236 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4237 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4239 /* start of a loop: remember where loop starts */
4244 /* Still in the same "if...", "then..." or "do..." branch? */
4245 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4246 if ((rcode == 0 && last_followup == PIPE_OR)
4247 || (rcode != 0 && last_followup == PIPE_AND)
4249 /* It is "<true> || CMD" or "<false> && CMD"
4250 * and we should not execute CMD */
4251 debug_printf_exec("skipped cmd because of || or &&\n");
4252 last_followup = pi->followup;
4256 last_followup = pi->followup;
4257 IF_HAS_KEYWORDS(last_rword = rword;)
4260 if (rword == RES_THEN) {
4261 /* if false; then ... fi has exitcode 0! */
4262 G.last_exitcode = rcode = EXIT_SUCCESS;
4263 /* "if <false> THEN cmd": skip cmd */
4267 if (rword == RES_ELSE || rword == RES_ELIF) {
4268 /* "if <true> then ... ELSE/ELIF cmd":
4269 * skip cmd and all following ones */
4274 #if ENABLE_HUSH_LOOPS
4275 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4277 /* first loop through for */
4279 static const char encoded_dollar_at[] ALIGN1 = {
4280 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4281 }; /* encoded representation of "$@" */
4282 static const char *const encoded_dollar_at_argv[] = {
4283 encoded_dollar_at, NULL
4284 }; /* argv list with one element: "$@" */
4287 vals = (char**)encoded_dollar_at_argv;
4288 if (pi->next->res_word == RES_IN) {
4289 /* if no variable values after "in" we skip "for" */
4290 if (!pi->next->cmds[0].argv) {
4291 G.last_exitcode = rcode = EXIT_SUCCESS;
4292 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4295 vals = pi->next->cmds[0].argv;
4296 } /* else: "for var; do..." -> assume "$@" list */
4297 /* create list of variable values */
4298 debug_print_strings("for_list made from", vals);
4299 for_list = expand_strvec_to_strvec(vals);
4300 for_lcur = for_list;
4301 debug_print_strings("for_list", for_list);
4304 /* "for" loop is over, clean up */
4310 /* Insert next value from for_lcur */
4311 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4312 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4315 if (rword == RES_IN) {
4316 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4318 if (rword == RES_DONE) {
4319 continue; /* "done" has no cmds too */
4322 #if ENABLE_HUSH_CASE
4323 if (rword == RES_CASE) {
4324 case_word = expand_strvec_to_string(pi->cmds->argv);
4327 if (rword == RES_MATCH) {
4330 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4332 /* all prev words didn't match, does this one match? */
4333 argv = pi->cmds->argv;
4335 char *pattern = expand_string_to_string(*argv);
4336 /* TODO: which FNM_xxx flags to use? */
4337 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4339 if (cond_code == 0) { /* match! we will execute this branch */
4340 free(case_word); /* make future "word)" stop */
4348 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4350 continue; /* not matched yet, skip this pipe */
4353 /* Just pressing <enter> in shell should check for jobs.
4354 * OTOH, in non-interactive shell this is useless
4355 * and only leads to extra job checks */
4356 if (pi->num_cmds == 0) {
4357 if (G_interactive_fd)
4358 goto check_jobs_and_continue;
4362 /* After analyzing all keywords and conditions, we decided
4363 * to execute this pipe. NB: have to do checkjobs(NULL)
4364 * after run_pipe to collect any background children,
4365 * even if list execution is to be stopped. */
4366 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4369 #if ENABLE_HUSH_LOOPS
4370 G.flag_break_continue = 0;
4372 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4374 /* We ran a builtin, function, or group.
4375 * rcode is already known
4376 * and we don't need to wait for anything. */
4377 G.last_exitcode = rcode;
4378 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4379 check_and_run_traps(0);
4380 #if ENABLE_HUSH_LOOPS
4381 /* Was it "break" or "continue"? */
4382 if (G.flag_break_continue) {
4383 smallint fbc = G.flag_break_continue;
4384 /* We might fall into outer *loop*,
4385 * don't want to break it too */
4387 G.depth_break_continue--;
4388 if (G.depth_break_continue == 0)
4389 G.flag_break_continue = 0;
4390 /* else: e.g. "continue 2" should *break* once, *then* continue */
4391 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4392 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4393 goto check_jobs_and_break;
4394 /* "continue": simulate end of loop */
4399 #if ENABLE_HUSH_FUNCTIONS
4400 if (G.flag_return_in_progress == 1) {
4401 /* same as "goto check_jobs_and_break" */
4406 } else if (pi->followup == PIPE_BG) {
4407 /* What does bash do with attempts to background builtins? */
4408 /* even bash 3.2 doesn't do that well with nested bg:
4409 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4410 * I'm NOT treating inner &'s as jobs */
4411 check_and_run_traps(0);
4413 if (G.run_list_level == 1)
4416 G.last_exitcode = rcode = EXIT_SUCCESS;
4417 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4420 if (G.run_list_level == 1 && G_interactive_fd) {
4421 /* Waits for completion, then fg's main shell */
4422 rcode = checkjobs_and_fg_shell(pi);
4423 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4424 check_and_run_traps(0);
4427 { /* This one just waits for completion */
4428 rcode = checkjobs(pi);
4429 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4430 check_and_run_traps(0);
4432 G.last_exitcode = rcode;
4436 /* Analyze how result affects subsequent commands */
4438 if (rword == RES_IF || rword == RES_ELIF)
4441 #if ENABLE_HUSH_LOOPS
4442 /* Beware of "while false; true; do ..."! */
4443 if (pi->next && pi->next->res_word == RES_DO) {
4444 if (rword == RES_WHILE) {
4446 /* "while false; do...done" - exitcode 0 */
4447 G.last_exitcode = rcode = EXIT_SUCCESS;
4448 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4449 goto check_jobs_and_break;
4452 if (rword == RES_UNTIL) {
4454 debug_printf_exec(": until expr is true: breaking\n");
4455 check_jobs_and_break:
4463 check_jobs_and_continue:
4470 #if ENABLE_HUSH_LOOPS
4475 #if ENABLE_HUSH_CASE
4479 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4483 /* Select which version we will use */
4484 static int run_and_free_list(struct pipe *pi)
4487 debug_printf_exec("run_and_free_list entered\n");
4489 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4490 rcode = run_list(pi);
4492 /* free_pipe_list has the side effect of clearing memory.
4493 * In the long run that function can be merged with run_list,
4494 * but doing that now would hobble the debugging effort. */
4496 debug_printf_exec("run_and_free_list return %d\n", rcode);
4501 static struct pipe *new_pipe(void)
4504 pi = xzalloc(sizeof(struct pipe));
4505 /*pi->followup = 0; - deliberately invalid value */
4506 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4510 /* Command (member of a pipe) is complete, or we start a new pipe
4511 * if ctx->command is NULL.
4512 * No errors possible here.
4514 static int done_command(struct parse_context *ctx)
4516 /* The command is really already in the pipe structure, so
4517 * advance the pipe counter and make a new, null command. */
4518 struct pipe *pi = ctx->pipe;
4519 struct command *command = ctx->command;
4522 if (IS_NULL_CMD(command)) {
4523 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4527 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4528 //debug_print_tree(ctx->list_head, 20);
4530 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4533 /* Only real trickiness here is that the uncommitted
4534 * command structure is not counted in pi->num_cmds. */
4535 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4536 ctx->command = command = &pi->cmds[pi->num_cmds];
4538 memset(command, 0, sizeof(*command));
4539 return pi->num_cmds; /* used only for 0/nonzero check */
4542 static void done_pipe(struct parse_context *ctx, pipe_style type)
4546 debug_printf_parse("done_pipe entered, followup %d\n", type);
4547 /* Close previous command */
4548 not_null = done_command(ctx);
4549 ctx->pipe->followup = type;
4551 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4552 ctx->ctx_inverted = 0;
4553 ctx->pipe->res_word = ctx->ctx_res_w;
4556 /* Without this check, even just <enter> on command line generates
4557 * tree of three NOPs (!). Which is harmless but annoying.
4558 * IOW: it is safe to do it unconditionally. */
4561 || ctx->ctx_res_w == RES_FI
4563 #if ENABLE_HUSH_LOOPS
4564 || ctx->ctx_res_w == RES_DONE
4565 || ctx->ctx_res_w == RES_FOR
4566 || ctx->ctx_res_w == RES_IN
4568 #if ENABLE_HUSH_CASE
4569 || ctx->ctx_res_w == RES_ESAC
4573 debug_printf_parse("done_pipe: adding new pipe: "
4574 "not_null:%d ctx->ctx_res_w:%d\n",
4575 not_null, ctx->ctx_res_w);
4577 ctx->pipe->next = new_p;
4579 /* RES_THEN, RES_DO etc are "sticky" -
4580 * they remain set for pipes inside if/while.
4581 * This is used to control execution.
4582 * RES_FOR and RES_IN are NOT sticky (needed to support
4583 * cases where variable or value happens to match a keyword):
4585 #if ENABLE_HUSH_LOOPS
4586 if (ctx->ctx_res_w == RES_FOR
4587 || ctx->ctx_res_w == RES_IN)
4588 ctx->ctx_res_w = RES_NONE;
4590 #if ENABLE_HUSH_CASE
4591 if (ctx->ctx_res_w == RES_MATCH)
4592 ctx->ctx_res_w = RES_CASE_BODY;
4593 if (ctx->ctx_res_w == RES_CASE)
4594 ctx->ctx_res_w = RES_CASE_IN;
4596 ctx->command = NULL; /* trick done_command below */
4597 /* Create the memory for command, roughly:
4598 * ctx->pipe->cmds = new struct command;
4599 * ctx->command = &ctx->pipe->cmds[0];
4602 //debug_print_tree(ctx->list_head, 10);
4604 debug_printf_parse("done_pipe return\n");
4607 static void initialize_context(struct parse_context *ctx)
4609 memset(ctx, 0, sizeof(*ctx));
4610 ctx->pipe = ctx->list_head = new_pipe();
4611 /* Create the memory for command, roughly:
4612 * ctx->pipe->cmds = new struct command;
4613 * ctx->command = &ctx->pipe->cmds[0];
4618 /* If a reserved word is found and processed, parse context is modified
4619 * and 1 is returned.
4622 struct reserved_combo {
4625 unsigned char assignment_flag;
4629 FLAG_END = (1 << RES_NONE ),
4631 FLAG_IF = (1 << RES_IF ),
4632 FLAG_THEN = (1 << RES_THEN ),
4633 FLAG_ELIF = (1 << RES_ELIF ),
4634 FLAG_ELSE = (1 << RES_ELSE ),
4635 FLAG_FI = (1 << RES_FI ),
4637 #if ENABLE_HUSH_LOOPS
4638 FLAG_FOR = (1 << RES_FOR ),
4639 FLAG_WHILE = (1 << RES_WHILE),
4640 FLAG_UNTIL = (1 << RES_UNTIL),
4641 FLAG_DO = (1 << RES_DO ),
4642 FLAG_DONE = (1 << RES_DONE ),
4643 FLAG_IN = (1 << RES_IN ),
4645 #if ENABLE_HUSH_CASE
4646 FLAG_MATCH = (1 << RES_MATCH),
4647 FLAG_ESAC = (1 << RES_ESAC ),
4649 FLAG_START = (1 << RES_XXXX ),
4652 static const struct reserved_combo* match_reserved_word(o_string *word)
4654 /* Mostly a list of accepted follow-up reserved words.
4655 * FLAG_END means we are done with the sequence, and are ready
4656 * to turn the compound list into a command.
4657 * FLAG_START means the word must start a new compound list.
4659 static const struct reserved_combo reserved_list[] = {
4661 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4662 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4663 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4664 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4665 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4666 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4668 #if ENABLE_HUSH_LOOPS
4669 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4670 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4671 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4672 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4673 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4674 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4676 #if ENABLE_HUSH_CASE
4677 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4678 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4681 const struct reserved_combo *r;
4683 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4684 if (strcmp(word->data, r->literal) == 0)
4689 /* Return 0: not a keyword, 1: keyword
4691 static int reserved_word(o_string *word, struct parse_context *ctx)
4693 #if ENABLE_HUSH_CASE
4694 static const struct reserved_combo reserved_match = {
4695 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4698 const struct reserved_combo *r;
4702 r = match_reserved_word(word);
4706 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4707 #if ENABLE_HUSH_CASE
4708 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4709 /* "case word IN ..." - IN part starts first MATCH part */
4710 r = &reserved_match;
4713 if (r->flag == 0) { /* '!' */
4714 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4715 syntax_error("! ! command");
4716 ctx->ctx_res_w = RES_SNTX;
4718 ctx->ctx_inverted = 1;
4721 if (r->flag & FLAG_START) {
4722 struct parse_context *old;
4724 old = xmalloc(sizeof(*old));
4725 debug_printf_parse("push stack %p\n", old);
4726 *old = *ctx; /* physical copy */
4727 initialize_context(ctx);
4729 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4730 syntax_error_at(word->data);
4731 ctx->ctx_res_w = RES_SNTX;
4734 /* "{...} fi" is ok. "{...} if" is not
4736 * if { echo foo; } then { echo bar; } fi */
4737 if (ctx->command->group)
4738 done_pipe(ctx, PIPE_SEQ);
4741 ctx->ctx_res_w = r->res;
4742 ctx->old_flag = r->flag;
4743 word->o_assignment = r->assignment_flag;
4745 if (ctx->old_flag & FLAG_END) {
4746 struct parse_context *old;
4748 done_pipe(ctx, PIPE_SEQ);
4749 debug_printf_parse("pop stack %p\n", ctx->stack);
4751 old->command->group = ctx->list_head;
4752 old->command->cmd_type = CMD_NORMAL;
4754 o_addstr(&old->as_string, ctx->as_string.data);
4755 o_free_unsafe(&ctx->as_string);
4756 old->command->group_as_string = xstrdup(old->as_string.data);
4757 debug_printf_parse("pop, remembering as:'%s'\n",
4758 old->command->group_as_string);
4760 *ctx = *old; /* physical copy */
4767 /* Word is complete, look at it and update parsing context.
4768 * Normal return is 0. Syntax errors return 1.
4769 * Note: on return, word is reset, but not o_free'd!
4771 static int done_word(o_string *word, struct parse_context *ctx)
4773 struct command *command = ctx->command;
4775 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4776 if (word->length == 0 && word->o_quoted == 0) {
4777 debug_printf_parse("done_word return 0: true null, ignored\n");
4781 if (ctx->pending_redirect) {
4782 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4783 * only if run as "bash", not "sh" */
4784 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4786 * ...the word that follows the redirection operator
4787 * shall be subjected to tilde expansion, parameter expansion,
4788 * command substitution, arithmetic expansion, and quote
4789 * removal. Pathname expansion shall not be performed
4790 * on the word by a non-interactive shell; an interactive
4791 * shell may perform it, but shall do so only when
4792 * the expansion would result in one word."
4794 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4795 /* Cater for >\file case:
4796 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4797 * Same with heredocs:
4798 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4800 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4801 unbackslash(ctx->pending_redirect->rd_filename);
4802 /* Is it <<"HEREDOC"? */
4803 if (word->o_quoted) {
4804 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4807 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4808 ctx->pending_redirect = NULL;
4810 /* If this word wasn't an assignment, next ones definitely
4811 * can't be assignments. Even if they look like ones. */
4812 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4813 && word->o_assignment != WORD_IS_KEYWORD
4815 word->o_assignment = NOT_ASSIGNMENT;
4817 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4818 command->assignment_cnt++;
4819 word->o_assignment = MAYBE_ASSIGNMENT;
4823 # if ENABLE_HUSH_CASE
4824 if (ctx->ctx_dsemicolon
4825 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4827 /* already done when ctx_dsemicolon was set to 1: */
4828 /* ctx->ctx_res_w = RES_MATCH; */
4829 ctx->ctx_dsemicolon = 0;
4832 if (!command->argv /* if it's the first word... */
4833 # if ENABLE_HUSH_LOOPS
4834 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4835 && ctx->ctx_res_w != RES_IN
4837 # if ENABLE_HUSH_CASE
4838 && ctx->ctx_res_w != RES_CASE
4841 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4842 if (reserved_word(word, ctx)) {
4843 o_reset_to_empty_unquoted(word);
4844 debug_printf_parse("done_word return %d\n",
4845 (ctx->ctx_res_w == RES_SNTX));
4846 return (ctx->ctx_res_w == RES_SNTX);
4848 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4849 if (strcmp(word->data, "export") == 0
4850 # if ENABLE_HUSH_LOCAL
4851 || strcmp(word->data, "local") == 0
4854 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4857 # if ENABLE_HUSH_BASH_COMPAT
4858 if (strcmp(word->data, "[[") == 0) {
4859 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4865 if (command->group) {
4866 /* "{ echo foo; } echo bar" - bad */
4867 syntax_error_at(word->data);
4868 debug_printf_parse("done_word return 1: syntax error, "
4869 "groups and arglists don't mix\n");
4872 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4873 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4874 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4875 /* (otherwise it's known to be not empty and is already safe) */
4877 /* exclude "$@" - it can expand to no word despite "" */
4878 char *p = word->data;
4879 while (p[0] == SPECIAL_VAR_SYMBOL
4880 && (p[1] & 0x7f) == '@'
4881 && p[2] == SPECIAL_VAR_SYMBOL
4885 if (p == word->data || p[0] != '\0') {
4886 /* saw no "$@", or not only "$@" but some
4887 * real text is there too */
4888 /* insert "empty variable" reference, this makes
4889 * e.g. "", $empty"" etc to not disappear */
4890 o_addchr(word, SPECIAL_VAR_SYMBOL);
4891 o_addchr(word, SPECIAL_VAR_SYMBOL);
4894 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4895 debug_print_strings("word appended to argv", command->argv);
4898 #if ENABLE_HUSH_LOOPS
4899 if (ctx->ctx_res_w == RES_FOR) {
4901 || !is_well_formed_var_name(command->argv[0], '\0')
4903 /* bash says just "not a valid identifier" */
4904 syntax_error("not a valid identifier in for");
4907 /* Force FOR to have just one word (variable name) */
4908 /* NB: basically, this makes hush see "for v in ..."
4909 * syntax as if it is "for v; in ...". FOR and IN become
4910 * two pipe structs in parse tree. */
4911 done_pipe(ctx, PIPE_SEQ);
4914 #if ENABLE_HUSH_CASE
4915 /* Force CASE to have just one word */
4916 if (ctx->ctx_res_w == RES_CASE) {
4917 done_pipe(ctx, PIPE_SEQ);
4921 o_reset_to_empty_unquoted(word);
4923 debug_printf_parse("done_word return 0\n");
4928 /* Peek ahead in the input to find out if we have a "&n" construct,
4929 * as in "2>&1", that represents duplicating a file descriptor.
4931 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4932 * REDIRFD_SYNTAX_ERR if syntax error,
4933 * REDIRFD_TO_FILE if no & was seen,
4934 * or the number found.
4937 #define parse_redir_right_fd(as_string, input) \
4938 parse_redir_right_fd(input)
4940 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4946 return REDIRFD_TO_FILE;
4948 ch = i_getch(input); /* get the & */
4949 nommu_addchr(as_string, ch);
4952 ch = i_getch(input);
4953 nommu_addchr(as_string, ch);
4954 return REDIRFD_CLOSE;
4958 while (ch != EOF && isdigit(ch)) {
4959 d = d*10 + (ch-'0');
4961 ch = i_getch(input);
4962 nommu_addchr(as_string, ch);
4967 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4969 bb_error_msg("ambiguous redirect");
4970 return REDIRFD_SYNTAX_ERR;
4973 /* Return code is 0 normal, 1 if a syntax error is detected
4975 static int parse_redirect(struct parse_context *ctx,
4978 struct in_str *input)
4980 struct command *command = ctx->command;
4981 struct redir_struct *redir;
4982 struct redir_struct **redirp;
4985 dup_num = REDIRFD_TO_FILE;
4986 if (style != REDIRECT_HEREDOC) {
4987 /* Check for a '>&1' type redirect */
4988 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4989 if (dup_num == REDIRFD_SYNTAX_ERR)
4992 int ch = i_peek(input);
4993 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4994 if (dup_num) { /* <<-... */
4995 ch = i_getch(input);
4996 nommu_addchr(&ctx->as_string, ch);
5001 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5002 int ch = i_peek(input);
5004 /* >|FILE redirect ("clobbering" >).
5005 * Since we do not support "set -o noclobber" yet,
5006 * >| and > are the same for now. Just eat |.
5008 ch = i_getch(input);
5009 nommu_addchr(&ctx->as_string, ch);
5013 /* Create a new redir_struct and append it to the linked list */
5014 redirp = &command->redirects;
5015 while ((redir = *redirp) != NULL) {
5016 redirp = &(redir->next);
5018 *redirp = redir = xzalloc(sizeof(*redir));
5019 /* redir->next = NULL; */
5020 /* redir->rd_filename = NULL; */
5021 redir->rd_type = style;
5022 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5024 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5025 redir_table[style].descrip);
5027 redir->rd_dup = dup_num;
5028 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5029 /* Erik had a check here that the file descriptor in question
5030 * is legit; I postpone that to "run time"
5031 * A "-" representation of "close me" shows up as a -3 here */
5032 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5033 redir->rd_fd, redir->rd_dup);
5035 /* Set ctx->pending_redirect, so we know what to do at the
5036 * end of the next parsed word. */
5037 ctx->pending_redirect = redir;
5042 /* If a redirect is immediately preceded by a number, that number is
5043 * supposed to tell which file descriptor to redirect. This routine
5044 * looks for such preceding numbers. In an ideal world this routine
5045 * needs to handle all the following classes of redirects...
5046 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5047 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5048 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5049 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5051 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5053 * ... If n is quoted, the number shall not be recognized as part of
5054 * the redirection expression. For example:
5056 * writes the character 2 into file a"
5057 * We are getting it right by setting ->o_quoted on any \<char>
5059 * A -1 return means no valid number was found,
5060 * the caller should use the appropriate default for this redirection.
5062 static int redirect_opt_num(o_string *o)
5066 if (o->data == NULL)
5068 num = bb_strtou(o->data, NULL, 10);
5069 if (errno || num < 0)
5071 o_reset_to_empty_unquoted(o);
5076 #define fetch_till_str(as_string, input, word, skip_tabs) \
5077 fetch_till_str(input, word, skip_tabs)
5079 static char *fetch_till_str(o_string *as_string,
5080 struct in_str *input,
5084 o_string heredoc = NULL_O_STRING;
5090 ch = i_getch(input);
5091 nommu_addchr(as_string, ch);
5093 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5094 heredoc.data[past_EOL] = '\0';
5095 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5096 return heredoc.data;
5099 o_addchr(&heredoc, ch);
5100 past_EOL = heredoc.length;
5103 ch = i_getch(input);
5104 nommu_addchr(as_string, ch);
5105 } while (skip_tabs && ch == '\t');
5106 } while (ch == '\n');
5109 o_free_unsafe(&heredoc);
5112 o_addchr(&heredoc, ch);
5113 nommu_addchr(as_string, ch);
5117 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5118 * and load them all. There should be exactly heredoc_cnt of them.
5120 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5122 struct pipe *pi = ctx->list_head;
5124 while (pi && heredoc_cnt) {
5126 struct command *cmd = pi->cmds;
5128 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5130 cmd->argv ? cmd->argv[0] : "NONE");
5131 for (i = 0; i < pi->num_cmds; i++) {
5132 struct redir_struct *redir = cmd->redirects;
5134 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5135 i, cmd->argv ? cmd->argv[0] : "NONE");
5137 if (redir->rd_type == REDIRECT_HEREDOC) {
5140 redir->rd_type = REDIRECT_HEREDOC2;
5141 /* redir->rd_dup is (ab)used to indicate <<- */
5142 p = fetch_till_str(&ctx->as_string, input,
5143 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5145 syntax_error("unexpected EOF in here document");
5148 free(redir->rd_filename);
5149 redir->rd_filename = p;
5152 redir = redir->next;
5159 /* Should be 0. If it isn't, it's a parse error */
5161 bb_error_msg_and_die("heredoc BUG 2");
5167 #if ENABLE_HUSH_TICK
5168 static FILE *generate_stream_from_string(const char *s)
5171 int pid, channel[2];
5177 pid = BB_MMU ? fork() : vfork();
5179 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5181 if (pid == 0) { /* child */
5182 disable_restore_tty_pgrp_on_exit();
5183 /* Process substitution is not considered to be usual
5184 * 'command execution'.
5185 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5192 close(channel[0]); /* NB: close _first_, then move fd! */
5193 xmove_fd(channel[1], 1);
5194 /* Prevent it from trying to handle ctrl-z etc */
5195 IF_HUSH_JOB(G.run_list_level = 1;)
5196 /* Awful hack for `trap` or $(trap).
5198 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5199 * contains an example where "trap" is executed in a subshell:
5201 * save_traps=$(trap)
5203 * eval "$save_traps"
5205 * Standard does not say that "trap" in subshell shall print
5206 * parent shell's traps. It only says that its output
5207 * must have suitable form, but then, in the above example
5208 * (which is not supposed to be normative), it implies that.
5210 * bash (and probably other shell) does implement it
5211 * (traps are reset to defaults, but "trap" still shows them),
5212 * but as a result, "trap" logic is hopelessly messed up:
5215 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5216 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5217 * # true | trap <--- trap is in subshell - no output (ditto)
5218 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5219 * trap -- 'echo Ho' SIGWINCH
5220 * # echo `(trap)` <--- in subshell in subshell - output
5221 * trap -- 'echo Ho' SIGWINCH
5222 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5223 * trap -- 'echo Ho' SIGWINCH
5225 * The rules when to forget and when to not forget traps
5226 * get really complex and nonsensical.
5228 * Our solution: ONLY bare $(trap) or `trap` is special.
5230 s = skip_whitespace(s);
5231 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5233 static const char *const argv[] = { NULL, NULL };
5234 builtin_trap((char**)argv);
5235 exit(0); /* not _exit() - we need to fflush */
5238 reset_traps_to_defaults();
5239 parse_and_run_string(s);
5240 _exit(G.last_exitcode);
5242 /* We re-execute after vfork on NOMMU. This makes this script safe:
5243 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5244 * huge=`cat BIG` # was blocking here forever
5247 re_execute_shell(&to_free,
5256 #if ENABLE_HUSH_FAST
5258 //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);
5260 enable_restore_tty_pgrp_on_exit();
5265 pf = fdopen(channel[0], "r");
5269 /* Return code is exit status of the process that is run. */
5270 static int process_command_subs(o_string *dest, const char *s)
5273 struct in_str pipe_str;
5276 pf = generate_stream_from_string(s);
5279 close_on_exec_on(fileno(pf));
5281 /* Now send results of command back into original context */
5282 setup_file_in_str(&pipe_str, pf);
5284 while ((ch = i_getch(&pipe_str)) != EOF) {
5290 o_addchr(dest, '\n');
5293 o_addQchr(dest, ch);
5296 debug_printf("done reading from pipe, pclose()ing\n");
5297 /* Note: we got EOF, and we just close the read end of the pipe.
5298 * We do not wait for the `cmd` child to terminate. bash and ash do.
5300 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5301 * `false`; echo $? - bash outputs "1"
5304 debug_printf("closed FILE from child. return 0\n");
5309 static int parse_group(o_string *dest, struct parse_context *ctx,
5310 struct in_str *input, int ch)
5312 /* dest contains characters seen prior to ( or {.
5313 * Typically it's empty, but for function defs,
5314 * it contains function name (without '()'). */
5315 struct pipe *pipe_list;
5317 struct command *command = ctx->command;
5319 debug_printf_parse("parse_group entered\n");
5320 #if ENABLE_HUSH_FUNCTIONS
5321 if (ch == '(' && !dest->o_quoted) {
5323 if (done_word(dest, ctx))
5326 goto skip; /* (... */
5327 if (command->argv[1]) { /* word word ... (... */
5328 syntax_error_unexpected_ch('(');
5331 /* it is "word(..." or "word (..." */
5333 ch = i_getch(input);
5334 while (ch == ' ' || ch == '\t');
5336 syntax_error_unexpected_ch(ch);
5339 nommu_addchr(&ctx->as_string, ch);
5341 ch = i_getch(input);
5342 while (ch == ' ' || ch == '\t' || ch == '\n');
5344 syntax_error_unexpected_ch(ch);
5347 nommu_addchr(&ctx->as_string, ch);
5348 command->cmd_type = CMD_FUNCDEF;
5352 if (command->argv /* word [word]{... */
5353 || dest->length /* word{... */
5354 || dest->o_quoted /* ""{... */
5357 debug_printf_parse("parse_group return 1: "
5358 "syntax error, groups and arglists don't mix\n");
5362 #if ENABLE_HUSH_FUNCTIONS
5368 command->cmd_type = CMD_SUBSHELL;
5370 /* bash does not allow "{echo...", requires whitespace */
5371 ch = i_getch(input);
5372 if (ch != ' ' && ch != '\t' && ch != '\n') {
5373 syntax_error_unexpected_ch(ch);
5376 nommu_addchr(&ctx->as_string, ch);
5381 char *as_string = NULL;
5383 pipe_list = parse_stream(&as_string, input, endch);
5386 o_addstr(&ctx->as_string, as_string);
5388 /* empty ()/{} or parse error? */
5389 if (!pipe_list || pipe_list == ERR_PTR) {
5390 /* parse_stream already emitted error msg */
5394 debug_printf_parse("parse_group return 1: "
5395 "parse_stream returned %p\n", pipe_list);
5398 command->group = pipe_list;
5400 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5401 command->group_as_string = as_string;
5402 debug_printf_parse("end of group, remembering as:'%s'\n",
5403 command->group_as_string);
5406 debug_printf_parse("parse_group return 0\n");
5408 /* command remains "open", available for possible redirects */
5411 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5412 /* Subroutines for copying $(...) and `...` things */
5413 static void add_till_backquote(o_string *dest, struct in_str *input);
5415 static void add_till_single_quote(o_string *dest, struct in_str *input)
5418 int ch = i_getch(input);
5420 syntax_error_unterm_ch('\'');
5421 /*xfunc_die(); - redundant */
5428 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5429 static void add_till_double_quote(o_string *dest, struct in_str *input)
5432 int ch = i_getch(input);
5434 syntax_error_unterm_ch('"');
5435 /*xfunc_die(); - redundant */
5439 if (ch == '\\') { /* \x. Copy both chars. */
5441 ch = i_getch(input);
5445 add_till_backquote(dest, input);
5449 //if (ch == '$') ...
5452 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5454 * "Within the backquoted style of command substitution, backslash
5455 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5456 * The search for the matching backquote shall be satisfied by the first
5457 * backquote found without a preceding backslash; during this search,
5458 * if a non-escaped backquote is encountered within a shell comment,
5459 * a here-document, an embedded command substitution of the $(command)
5460 * form, or a quoted string, undefined results occur. A single-quoted
5461 * or double-quoted string that begins, but does not end, within the
5462 * "`...`" sequence produces undefined results."
5464 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5466 static void add_till_backquote(o_string *dest, struct in_str *input)
5469 int ch = i_getch(input);
5471 syntax_error_unterm_ch('`');
5472 /*xfunc_die(); - redundant */
5477 /* \x. Copy both chars unless it is \` */
5478 int ch2 = i_getch(input);
5480 syntax_error_unterm_ch('`');
5481 /*xfunc_die(); - redundant */
5483 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5490 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5491 * quoting and nested ()s.
5492 * "With the $(command) style of command substitution, all characters
5493 * following the open parenthesis to the matching closing parenthesis
5494 * constitute the command. Any valid shell script can be used for command,
5495 * except a script consisting solely of redirections which produces
5496 * unspecified results."
5498 * echo $(echo '(TEST)' BEST) (TEST) BEST
5499 * echo $(echo 'TEST)' BEST) TEST) BEST
5500 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5502 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5506 int ch = i_getch(input);
5508 syntax_error_unterm_ch(')');
5509 /*xfunc_die(); - redundant */
5517 if (i_peek(input) == ')') {
5525 add_till_single_quote(dest, input);
5530 add_till_double_quote(dest, input);
5535 /* \x. Copy verbatim. Important for \(, \) */
5536 ch = i_getch(input);
5538 syntax_error_unterm_ch(')');
5539 /*xfunc_die(); - redundant */
5546 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5548 /* Return code: 0 for OK, 1 for syntax error */
5550 #define handle_dollar(as_string, dest, input) \
5551 handle_dollar(dest, input)
5553 static int handle_dollar(o_string *as_string,
5555 struct in_str *input)
5557 int ch = i_peek(input); /* first character after the $ */
5558 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5560 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5562 ch = i_getch(input);
5563 nommu_addchr(as_string, ch);
5565 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5567 debug_printf_parse(": '%c'\n", ch);
5568 o_addchr(dest, ch | quote_mask);
5571 if (!isalnum(ch) && ch != '_')
5573 ch = i_getch(input);
5574 nommu_addchr(as_string, ch);
5576 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5577 } else if (isdigit(ch)) {
5579 ch = i_getch(input);
5580 nommu_addchr(as_string, ch);
5581 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5582 debug_printf_parse(": '%c'\n", ch);
5583 o_addchr(dest, ch | quote_mask);
5584 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5585 } else switch (ch) {
5587 case '!': /* last bg pid */
5588 case '?': /* last exit code */
5589 case '#': /* number of args */
5590 case '*': /* args */
5591 case '@': /* args */
5592 goto make_one_char_var;
5594 bool first_char, all_digits;
5597 ch = i_getch(input);
5598 nommu_addchr(as_string, ch);
5599 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5601 /* TODO: maybe someone will try to escape the '}' */
5606 ch = i_getch(input);
5607 nommu_addchr(as_string, ch);
5614 /* ${#var}: length of var contents */
5621 /* They're being verbose and doing ${?} */
5622 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5627 && ( (all_digits && !isdigit(ch))
5628 || (!all_digits && !isalnum(ch) && ch != '_')
5631 /* handle parameter expansions
5632 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5637 case ':': /* null modifier */
5638 if (expansion == 0) {
5639 debug_printf_parse(": null modifier\n");
5644 case '#': /* remove prefix */
5645 case '%': /* remove suffix */
5646 if (expansion == 0) {
5647 debug_printf_parse(": remove suffix/prefix\n");
5652 case '-': /* default value */
5653 case '=': /* assign default */
5654 case '+': /* alternative */
5655 case '?': /* error indicate */
5656 debug_printf_parse(": parameter expansion\n");
5661 syntax_error_unterm_str("${name}");
5662 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5667 debug_printf_parse(": '%c'\n", ch);
5668 o_addchr(dest, ch | quote_mask);
5672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5675 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5680 ch = i_getch(input);
5681 nommu_addchr(as_string, ch);
5682 # if ENABLE_SH_MATH_SUPPORT
5683 if (i_peek(input) == '(') {
5684 ch = i_getch(input);
5685 nommu_addchr(as_string, ch);
5686 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5687 o_addchr(dest, /*quote_mask |*/ '+');
5691 add_till_closing_paren(dest, input, true);
5694 o_addstr(as_string, dest->data + pos);
5695 o_addchr(as_string, ')');
5696 o_addchr(as_string, ')');
5699 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5703 # if ENABLE_HUSH_TICK
5704 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5705 o_addchr(dest, quote_mask | '`');
5709 add_till_closing_paren(dest, input, false);
5712 o_addstr(as_string, dest->data + pos);
5713 o_addchr(as_string, '`');
5716 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5722 ch = i_getch(input);
5723 nommu_addchr(as_string, ch);
5725 if (isalnum(ch)) { /* it's $_name or $_123 */
5730 /* TODO: $_ and $-: */
5731 /* $_ Shell or shell script name; or last argument of last command
5732 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5733 * but in command's env, set to full pathname used to invoke it */
5734 /* $- Option flags set by set builtin or shell options (-i etc) */
5736 o_addQchr(dest, '$');
5738 debug_printf_parse("handle_dollar return 0\n");
5743 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5744 parse_stream_dquoted(dest, input, dquote_end)
5746 static int parse_stream_dquoted(o_string *as_string,
5748 struct in_str *input,
5755 ch = i_getch(input);
5757 nommu_addchr(as_string, ch);
5758 if (ch == dquote_end) { /* may be only '"' or EOF */
5759 if (dest->o_assignment == NOT_ASSIGNMENT)
5760 dest->o_escape ^= 1;
5761 debug_printf_parse("parse_stream_dquoted return 0\n");
5764 /* note: can't move it above ch == dquote_end check! */
5766 syntax_error_unterm_ch('"');
5767 /*xfunc_die(); - redundant */
5771 next = i_peek(input);
5773 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5774 ch, ch, dest->o_escape);
5777 syntax_error("\\<eof>");
5781 * "The backslash retains its special meaning [in "..."]
5782 * only when followed by one of the following characters:
5783 * $, `, ", \, or <newline>. A double quote may be quoted
5784 * within double quotes by preceding it with a backslash."
5786 if (strchr("$`\"\\\n", next) != NULL) {
5787 ch = i_getch(input);
5789 o_addqchr(dest, ch);
5790 nommu_addchr(as_string, ch);
5793 o_addqchr(dest, '\\');
5794 nommu_addchr(as_string, '\\');
5799 if (handle_dollar(as_string, dest, input) != 0) {
5800 debug_printf_parse("parse_stream_dquoted return 1: "
5801 "handle_dollar returned non-0\n");
5806 #if ENABLE_HUSH_TICK
5808 //int pos = dest->length;
5809 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5810 o_addchr(dest, 0x80 | '`');
5811 add_till_backquote(dest, input);
5812 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5813 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5817 o_addQchr(dest, ch);
5819 && (dest->o_assignment == MAYBE_ASSIGNMENT
5820 || dest->o_assignment == WORD_IS_KEYWORD)
5821 && is_well_formed_var_name(dest->data, '=')
5823 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5829 * Scan input until EOF or end_trigger char.
5830 * Return a list of pipes to execute, or NULL on EOF
5831 * or if end_trigger character is met.
5832 * On syntax error, exit is shell is not interactive,
5833 * reset parsing machinery and start parsing anew,
5834 * or return ERR_PTR.
5836 static struct pipe *parse_stream(char **pstring,
5837 struct in_str *input,
5840 struct parse_context ctx;
5841 o_string dest = NULL_O_STRING;
5845 /* Double-quote state is handled in the state variable is_in_dquote.
5846 * A single-quote triggers a bypass of the main loop until its mate is
5847 * found. When recursing, quote state is passed in via dest->o_escape.
5849 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5850 end_trigger ? end_trigger : 'X');
5853 G.ifs = get_local_var_value("IFS");
5858 #if ENABLE_HUSH_INTERACTIVE
5859 input->promptmode = 0; /* PS1 */
5861 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5862 initialize_context(&ctx);
5867 const char *is_special;
5871 redir_type redir_style;
5874 /* dest.o_quoted = 1; - already is (see below) */
5875 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5878 /* We reached closing '"' */
5881 ch = i_getch(input);
5882 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5883 ch, ch, dest.o_escape);
5888 syntax_error_unterm_str("here document");
5891 /* end_trigger == '}' case errors out earlier,
5892 * checking only ')' */
5893 if (end_trigger == ')') {
5894 syntax_error_unterm_ch('('); /* exits */
5895 /* goto parse_error; */
5898 if (done_word(&dest, &ctx)) {
5902 done_pipe(&ctx, PIPE_SEQ);
5904 /* If we got nothing... */
5905 /* (this makes bare "&" cmd a no-op.
5906 * bash says: "syntax error near unexpected token '&'") */
5907 if (pi->num_cmds == 0
5908 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5914 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5916 *pstring = ctx.as_string.data;
5918 o_free_unsafe(&ctx.as_string);
5921 debug_printf_parse("parse_stream return %p\n", pi);
5924 nommu_addchr(&ctx.as_string, ch);
5925 is_ifs = strchr(G.ifs, ch);
5926 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5927 "\\$\"" IF_HUSH_TICK("`") /* always special */
5930 if (!is_special && !is_ifs) { /* ordinary char */
5932 o_addQchr(&dest, ch);
5933 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5934 || dest.o_assignment == WORD_IS_KEYWORD)
5936 && is_well_formed_var_name(dest.data, '=')
5938 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5944 if (done_word(&dest, &ctx)) {
5948 #if ENABLE_HUSH_CASE
5949 /* "case ... in <newline> word) ..." -
5950 * newlines are ignored (but ';' wouldn't be) */
5951 if (ctx.command->argv == NULL
5952 && ctx.ctx_res_w == RES_MATCH
5957 /* Treat newline as a command separator. */
5958 done_pipe(&ctx, PIPE_SEQ);
5959 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5961 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5966 dest.o_assignment = MAYBE_ASSIGNMENT;
5968 /* note: if (is_ifs) continue;
5969 * will still trigger for us */
5973 /* "cmd}" or "cmd }..." without semicolon or &:
5974 * } is an ordinary char in this case, even inside { cmd; }
5975 * Pathological example: { ""}; } should exec "}" cmd
5978 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5979 || dest.length != 0 /* word} */
5980 || dest.o_quoted /* ""} */
5984 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5985 goto skip_end_trigger;
5986 /* else: } does terminate a group */
5989 if (end_trigger && end_trigger == ch
5990 && (ch != ';' || heredoc_cnt == 0)
5991 #if ENABLE_HUSH_CASE
5993 || ctx.ctx_res_w != RES_MATCH
5994 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5999 /* This is technically valid:
6000 * { cat <<HERE; }; echo Ok
6004 * but we don't support this.
6005 * We require heredoc to be in enclosing {}/(),
6008 syntax_error_unterm_str("here document");
6011 if (done_word(&dest, &ctx)) {
6014 done_pipe(&ctx, PIPE_SEQ);
6015 dest.o_assignment = MAYBE_ASSIGNMENT;
6016 /* Do we sit outside of any if's, loops or case's? */
6018 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6022 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6024 *pstring = ctx.as_string.data;
6026 o_free_unsafe(&ctx.as_string);
6029 debug_printf_parse("parse_stream return %p: "
6030 "end_trigger char found\n",
6032 return ctx.list_head;
6041 next = i_peek(input);
6044 /* Catch <, > before deciding whether this word is
6045 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6048 redir_fd = redirect_opt_num(&dest);
6049 if (done_word(&dest, &ctx)) {
6052 redir_style = REDIRECT_OVERWRITE;
6054 redir_style = REDIRECT_APPEND;
6055 ch = i_getch(input);
6056 nommu_addchr(&ctx.as_string, ch);
6059 else if (next == '(') {
6060 syntax_error(">(process) not supported");
6064 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6066 continue; /* back to top of while (1) */
6068 redir_fd = redirect_opt_num(&dest);
6069 if (done_word(&dest, &ctx)) {
6072 redir_style = REDIRECT_INPUT;
6074 redir_style = REDIRECT_HEREDOC;
6076 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6077 ch = i_getch(input);
6078 nommu_addchr(&ctx.as_string, ch);
6079 } else if (next == '>') {
6080 redir_style = REDIRECT_IO;
6081 ch = i_getch(input);
6082 nommu_addchr(&ctx.as_string, ch);
6085 else if (next == '(') {
6086 syntax_error("<(process) not supported");
6090 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6092 continue; /* back to top of while (1) */
6095 if (dest.o_assignment == MAYBE_ASSIGNMENT
6096 /* check that we are not in word in "a=1 2>word b=1": */
6097 && !ctx.pending_redirect
6099 /* ch is a special char and thus this word
6100 * cannot be an assignment */
6101 dest.o_assignment = NOT_ASSIGNMENT;
6104 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6108 if (dest.length == 0) {
6111 if (ch == EOF || ch == '\n')
6114 /* note: we do not add it to &ctx.as_string */
6116 nommu_addchr(&ctx.as_string, '\n');
6118 o_addQchr(&dest, ch);
6123 syntax_error("\\<eof>");
6126 ch = i_getch(input);
6128 o_addchr(&dest, '\\');
6129 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6130 o_addchr(&dest, ch);
6131 nommu_addchr(&ctx.as_string, ch);
6132 /* Example: echo Hello \2>file
6133 * we need to know that word 2 is quoted */
6137 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6138 ctx.as_string.data[--ctx.as_string.length] = '\0';
6143 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6144 debug_printf_parse("parse_stream parse error: "
6145 "handle_dollar returned non-0\n");
6152 ch = i_getch(input);
6154 syntax_error_unterm_ch('\'');
6155 /*xfunc_die(); - redundant */
6157 nommu_addchr(&ctx.as_string, ch);
6160 o_addqchr(&dest, ch);
6165 is_in_dquote ^= 1; /* invert */
6166 if (dest.o_assignment == NOT_ASSIGNMENT)
6169 #if ENABLE_HUSH_TICK
6174 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6175 o_addchr(&dest, '`');
6179 add_till_backquote(&dest, input);
6181 o_addstr(&ctx.as_string, dest.data + pos);
6182 o_addchr(&ctx.as_string, '`');
6184 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6185 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6190 #if ENABLE_HUSH_CASE
6193 if (done_word(&dest, &ctx)) {
6196 done_pipe(&ctx, PIPE_SEQ);
6197 #if ENABLE_HUSH_CASE
6198 /* Eat multiple semicolons, detect
6199 * whether it means something special */
6204 ch = i_getch(input);
6205 nommu_addchr(&ctx.as_string, ch);
6206 if (ctx.ctx_res_w == RES_CASE_BODY) {
6207 ctx.ctx_dsemicolon = 1;
6208 ctx.ctx_res_w = RES_MATCH;
6214 /* We just finished a cmd. New one may start
6215 * with an assignment */
6216 dest.o_assignment = MAYBE_ASSIGNMENT;
6219 if (done_word(&dest, &ctx)) {
6223 ch = i_getch(input);
6224 nommu_addchr(&ctx.as_string, ch);
6225 done_pipe(&ctx, PIPE_AND);
6227 done_pipe(&ctx, PIPE_BG);
6231 if (done_word(&dest, &ctx)) {
6234 #if ENABLE_HUSH_CASE
6235 if (ctx.ctx_res_w == RES_MATCH)
6236 break; /* we are in case's "word | word)" */
6238 if (next == '|') { /* || */
6239 ch = i_getch(input);
6240 nommu_addchr(&ctx.as_string, ch);
6241 done_pipe(&ctx, PIPE_OR);
6243 /* we could pick up a file descriptor choice here
6244 * with redirect_opt_num(), but bash doesn't do it.
6245 * "echo foo 2| cat" yields "foo 2". */
6250 #if ENABLE_HUSH_CASE
6251 /* "case... in [(]word)..." - skip '(' */
6252 if (ctx.ctx_res_w == RES_MATCH
6253 && ctx.command->argv == NULL /* not (word|(... */
6254 && dest.length == 0 /* not word(... */
6255 && dest.o_quoted == 0 /* not ""(... */
6261 if (parse_group(&dest, &ctx, input, ch) != 0) {
6266 #if ENABLE_HUSH_CASE
6267 if (ctx.ctx_res_w == RES_MATCH)
6271 /* proper use of this character is caught by end_trigger:
6272 * if we see {, we call parse_group(..., end_trigger='}')
6273 * and it will match } earlier (not here). */
6274 syntax_error_unexpected_ch(ch);
6278 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6284 struct parse_context *pctx;
6285 IF_HAS_KEYWORDS(struct parse_context *p2;)
6287 /* Clean up allocated tree.
6288 * Sample for finding leaks on syntax error recovery path.
6289 * Run it from interactive shell, watch pmap `pidof hush`.
6290 * while if false; then false; fi; do break; fi
6291 * Samples to catch leaks at execution:
6292 * while if (true | {true;}); then echo ok; fi; do break; done
6293 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6297 /* Update pipe/command counts,
6298 * otherwise freeing may miss some */
6299 done_pipe(pctx, PIPE_SEQ);
6300 debug_printf_clean("freeing list %p from ctx %p\n",
6301 pctx->list_head, pctx);
6302 debug_print_tree(pctx->list_head, 0);
6303 free_pipe_list(pctx->list_head);
6304 debug_printf_clean("freed list %p\n", pctx->list_head);
6306 o_free_unsafe(&pctx->as_string);
6308 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6312 IF_HAS_KEYWORDS(pctx = p2;)
6313 } while (HAS_KEYWORDS && pctx);
6314 /* Free text, clear all dest fields */
6316 /* If we are not in top-level parse, we return,
6317 * our caller will propagate error.
6319 if (end_trigger != ';') {
6327 /* Discard cached input, force prompt */
6329 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6334 /* Executing from string: eval, sh -c '...'
6335 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6336 * end_trigger controls how often we stop parsing
6337 * NUL: parse all, execute, return
6338 * ';': parse till ';' or newline, execute, repeat till EOF
6340 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6343 struct pipe *pipe_list;
6345 pipe_list = parse_stream(NULL, inp, end_trigger);
6346 if (!pipe_list) /* EOF */
6348 debug_print_tree(pipe_list, 0);
6349 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6350 run_and_free_list(pipe_list);
6354 static void parse_and_run_string(const char *s)
6356 struct in_str input;
6357 setup_string_in_str(&input, s);
6358 parse_and_run_stream(&input, '\0');
6361 static void parse_and_run_file(FILE *f)
6363 struct in_str input;
6364 setup_file_in_str(&input, f);
6365 parse_and_run_stream(&input, ';');
6368 /* Called a few times only (or even once if "sh -c") */
6369 static void block_signals(int second_time)
6374 mask = (1 << SIGQUIT);
6375 if (G_interactive_fd) {
6376 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6377 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6378 mask |= SPECIAL_JOB_SIGS;
6380 G.non_DFL_mask = mask;
6383 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6387 sigaddset(&G.blocked_set, sig);
6391 sigdelset(&G.blocked_set, SIGCHLD);
6393 sigprocmask(SIG_SETMASK, &G.blocked_set,
6394 second_time ? NULL : &G.inherited_set);
6395 /* POSIX allows shell to re-enable SIGCHLD
6396 * even if it was SIG_IGN on entry */
6397 #if ENABLE_HUSH_FAST
6398 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6400 signal(SIGCHLD, SIGCHLD_handler);
6403 signal(SIGCHLD, SIG_DFL);
6409 static void maybe_set_to_sigexit(int sig)
6411 void (*handler)(int);
6412 /* non_DFL_mask'ed signals are, well, masked,
6413 * no need to set handler for them.
6415 if (!((G.non_DFL_mask >> sig) & 1)) {
6416 handler = signal(sig, sigexit);
6417 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6418 signal(sig, handler);
6421 /* Set handlers to restore tty pgrp and exit */
6422 static void set_fatal_handlers(void)
6424 /* We _must_ restore tty pgrp on fatal signals */
6426 maybe_set_to_sigexit(SIGILL );
6427 maybe_set_to_sigexit(SIGFPE );
6428 maybe_set_to_sigexit(SIGBUS );
6429 maybe_set_to_sigexit(SIGSEGV);
6430 maybe_set_to_sigexit(SIGTRAP);
6431 } /* else: hush is perfect. what SEGV? */
6432 maybe_set_to_sigexit(SIGABRT);
6433 /* bash 3.2 seems to handle these just like 'fatal' ones */
6434 maybe_set_to_sigexit(SIGPIPE);
6435 maybe_set_to_sigexit(SIGALRM);
6436 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6437 * if we aren't interactive... but in this case
6438 * we never want to restore pgrp on exit, and this fn is not called */
6439 /*maybe_set_to_sigexit(SIGHUP );*/
6440 /*maybe_set_to_sigexit(SIGTERM);*/
6441 /*maybe_set_to_sigexit(SIGINT );*/
6445 static int set_mode(const char cstate, const char mode)
6447 int state = (cstate == '-' ? 1 : 0);
6449 case 'n': G.fake_mode = state; break;
6450 case 'x': /*G.debug_mode = state;*/ break;
6451 default: return EXIT_FAILURE;
6453 return EXIT_SUCCESS;
6456 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6457 int hush_main(int argc, char **argv)
6459 static const struct variable const_shell_ver = {
6461 .varstr = (char*)hush_version_str,
6462 .max_len = 1, /* 0 can provoke free(name) */
6466 int signal_mask_is_inited = 0;
6468 unsigned builtin_argc;
6470 struct variable *cur_var;
6473 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6474 G.last_exitcode = EXIT_SUCCESS;
6476 G.argv0_for_re_execing = argv[0];
6478 /* Deal with HUSH_VERSION */
6479 G.shell_ver = const_shell_ver; /* copying struct here */
6480 G.top_var = &G.shell_ver;
6481 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6482 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6483 /* Initialize our shell local variables with the values
6484 * currently living in the environment */
6485 cur_var = G.top_var;
6488 char *value = strchr(*e, '=');
6489 if (value) { /* paranoia */
6490 cur_var->next = xzalloc(sizeof(*cur_var));
6491 cur_var = cur_var->next;
6492 cur_var->varstr = *e;
6493 cur_var->max_len = strlen(*e);
6494 cur_var->flg_export = 1;
6498 /* reinstate HUSH_VERSION */
6499 debug_printf_env("putenv '%s'\n", hush_version_str);
6500 putenv((char *)hush_version_str);
6503 set_pwd_var(/*exp:*/ 1);
6504 /* bash also exports SHLVL and _,
6505 * and sets (but doesn't export) the following variables:
6507 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6508 * BASH_VERSION='3.2.0(1)-release'
6510 * MACHTYPE=i386-pc-linux-gnu
6512 * HOSTNAME=<xxxxxxxxxx>
6524 * PIPESTATUS=([0]="0")
6525 * HISTFILE=/<xxx>/.bash_history
6529 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6531 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6541 #if ENABLE_FEATURE_EDITING
6542 G.line_input_state = new_line_input_t(FOR_SHELL);
6544 G.global_argc = argc;
6545 G.global_argv = argv;
6546 /* Initialize some more globals to non-zero values */
6547 cmdedit_update_prompt();
6549 if (setjmp(die_jmp)) {
6550 /* xfunc has failed! die die die */
6551 /* no EXIT traps, this is an escape hatch! */
6553 hush_exit(xfunc_error_retval);
6556 /* Shell is non-interactive at first. We need to call
6557 * block_signals(0) if we are going to execute "sh <script>",
6558 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6559 * If we later decide that we are interactive, we run block_signals(0)
6560 * (or re-run block_signals(1) if we ran block_signals(0) before)
6561 * in order to intercept (more) signals.
6565 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6568 opt = getopt(argc, argv, "+c:xins"
6571 # if ENABLE_HUSH_FUNCTIONS
6581 * sh ... -c 'script'
6582 * sh ... -c 'script' ARG0 [ARG1...]
6583 * On NOMMU, if builtin_argc != 0,
6584 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6585 * "" needs to be replaced with NULL
6586 * and BARGV vector fed to builtin function.
6587 * Note: this form never happens:
6588 * sh ... -c 'builtin' [BARGV...] ""
6591 G.root_pid = getpid();
6592 G.global_argv = argv + optind;
6593 G.global_argc = argc - optind;
6595 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6596 const struct built_in_command *x;
6598 block_signals(0); /* 0: called 1st time */
6599 x = find_builtin(optarg);
6600 if (x) { /* paranoia */
6601 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6602 G.global_argv += builtin_argc;
6603 G.global_argv[-1] = NULL; /* replace "" */
6604 G.last_exitcode = x->function(argv + optind - 1);
6608 if (!G.global_argv[0]) {
6609 /* -c 'script' (no params): prevent empty $0 */
6610 G.global_argv--; /* points to argv[i] of 'script' */
6611 G.global_argv[0] = argv[0];
6613 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6614 block_signals(0); /* 0: called 1st time */
6615 parse_and_run_string(optarg);
6618 /* Well, we cannot just declare interactiveness,
6619 * we have to have some stuff (ctty, etc) */
6620 /* G_interactive_fd++; */
6623 /* "-s" means "read from stdin", but this is how we always
6624 * operate, so simply do nothing here. */
6627 case '<': /* "big heredoc" support */
6628 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6631 G.root_pid = bb_strtou(optarg, &optarg, 16);
6633 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6635 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6637 builtin_argc = bb_strtou(optarg, &optarg, 16);
6638 # if ENABLE_HUSH_LOOPS
6640 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6645 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6647 # if ENABLE_HUSH_FUNCTIONS
6649 struct function *funcp = new_function(optarg);
6650 /* funcp->name is already set to optarg */
6651 /* funcp->body is set to NULL. It's a special case. */
6652 funcp->body_as_string = argv[optind];
6660 if (!set_mode('-', opt))
6664 fprintf(stderr, "Usage: sh [FILE]...\n"
6665 " or: sh -c command [args]...\n\n");
6671 } /* option parsing loop */
6674 G.root_pid = getpid();
6676 /* If we are login shell... */
6677 if (argv[0] && argv[0][0] == '-') {
6679 debug_printf("sourcing /etc/profile\n");
6680 input = fopen_for_read("/etc/profile");
6681 if (input != NULL) {
6682 close_on_exec_on(fileno(input));
6683 block_signals(0); /* 0: called 1st time */
6684 signal_mask_is_inited = 1;
6685 parse_and_run_file(input);
6688 /* bash: after sourcing /etc/profile,
6689 * tries to source (in the given order):
6690 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6691 * stopping on first found. --noprofile turns this off.
6692 * bash also sources ~/.bash_logout on exit.
6693 * If called as sh, skips .bash_XXX files.
6700 * "bash <script>" (which is never interactive (unless -i?))
6701 * sources $BASH_ENV here (without scanning $PATH).
6702 * If called as sh, does the same but with $ENV.
6704 debug_printf("running script '%s'\n", argv[optind]);
6705 G.global_argv = argv + optind;
6706 G.global_argc = argc - optind;
6707 input = xfopen_for_read(argv[optind]);
6708 close_on_exec_on(fileno(input));
6709 if (!signal_mask_is_inited)
6710 block_signals(0); /* 0: called 1st time */
6711 parse_and_run_file(input);
6712 #if ENABLE_FEATURE_CLEAN_UP
6718 /* Up to here, shell was non-interactive. Now it may become one.
6719 * NB: don't forget to (re)run block_signals(0/1) as needed.
6722 /* A shell is interactive if the '-i' flag was given,
6723 * or if all of the following conditions are met:
6725 * no arguments remaining or the -s flag given
6726 * standard input is a terminal
6727 * standard output is a terminal
6728 * Refer to Posix.2, the description of the 'sh' utility.
6731 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6732 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6733 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6734 if (G_saved_tty_pgrp < 0)
6735 G_saved_tty_pgrp = 0;
6737 /* try to dup stdin to high fd#, >= 255 */
6738 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6739 if (G_interactive_fd < 0) {
6740 /* try to dup to any fd */
6741 G_interactive_fd = dup(STDIN_FILENO);
6742 if (G_interactive_fd < 0) {
6744 G_interactive_fd = 0;
6745 G_saved_tty_pgrp = 0;
6748 // TODO: track & disallow any attempts of user
6749 // to (inadvertently) close/redirect G_interactive_fd
6751 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6752 if (G_interactive_fd) {
6753 close_on_exec_on(G_interactive_fd);
6755 if (G_saved_tty_pgrp) {
6756 /* If we were run as 'hush &', sleep until we are
6757 * in the foreground (tty pgrp == our pgrp).
6758 * If we get started under a job aware app (like bash),
6759 * make sure we are now in charge so we don't fight over
6760 * who gets the foreground */
6762 pid_t shell_pgrp = getpgrp();
6763 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6764 if (G_saved_tty_pgrp == shell_pgrp)
6766 /* send TTIN to ourself (should stop us) */
6767 kill(- shell_pgrp, SIGTTIN);
6771 /* Block some signals */
6772 block_signals(signal_mask_is_inited);
6774 if (G_saved_tty_pgrp) {
6775 /* Set other signals to restore saved_tty_pgrp */
6776 set_fatal_handlers();
6777 /* Put ourselves in our own process group
6778 * (bash, too, does this only if ctty is available) */
6779 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6780 /* Grab control of the terminal */
6781 tcsetpgrp(G_interactive_fd, getpid());
6783 /* -1 is special - makes xfuncs longjmp, not exit
6784 * (we reset die_sleep = 0 whereever we [v]fork) */
6785 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6786 } else if (!signal_mask_is_inited) {
6787 block_signals(0); /* 0: called 1st time */
6788 } /* else: block_signals(0) was done before */
6789 #elif ENABLE_HUSH_INTERACTIVE
6790 /* No job control compiled in, only prompt/line editing */
6791 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6792 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6793 if (G_interactive_fd < 0) {
6794 /* try to dup to any fd */
6795 G_interactive_fd = dup(STDIN_FILENO);
6796 if (G_interactive_fd < 0)
6798 G_interactive_fd = 0;
6801 if (G_interactive_fd) {
6802 close_on_exec_on(G_interactive_fd);
6803 block_signals(signal_mask_is_inited);
6804 } else if (!signal_mask_is_inited) {
6808 /* We have interactiveness code disabled */
6809 if (!signal_mask_is_inited) {
6814 * if interactive but not a login shell, sources ~/.bashrc
6815 * (--norc turns this off, --rcfile <file> overrides)
6818 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6819 printf("\n\n%s hush - the humble shell\n", bb_banner);
6820 if (ENABLE_HUSH_HELP)
6821 puts("Enter 'help' for a list of built-in commands.");
6825 parse_and_run_file(stdin);
6828 #if ENABLE_FEATURE_CLEAN_UP
6829 if (G.cwd != bb_msg_unknown)
6831 cur_var = G.top_var->next;
6833 struct variable *tmp = cur_var;
6834 if (!cur_var->max_len)
6835 free(cur_var->varstr);
6836 cur_var = cur_var->next;
6840 hush_exit(G.last_exitcode);
6845 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6846 int lash_main(int argc, char **argv)
6848 bb_error_msg("lash is deprecated, please use hush instead");
6849 return hush_main(argc, argv);
6854 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6855 int msh_main(int argc, char **argv)
6857 //bb_error_msg("msh is deprecated, please use hush instead");
6858 return hush_main(argc, argv);
6866 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6871 static int FAST_FUNC builtin_test(char **argv)
6878 return test_main(argc, argv - argc);
6881 static int FAST_FUNC builtin_echo(char **argv)
6888 return echo_main(argc, argv - argc);
6891 static int FAST_FUNC builtin_eval(char **argv)
6893 int rcode = EXIT_SUCCESS;
6896 char *str = expand_strvec_to_string(argv);
6898 * eval "echo Hi; done" ("done" is syntax error):
6899 * "echo Hi" will not execute too.
6901 parse_and_run_string(str);
6903 rcode = G.last_exitcode;
6908 static int FAST_FUNC builtin_cd(char **argv)
6910 const char *newdir = argv[1];
6911 if (newdir == NULL) {
6912 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6913 * bash says "bash: cd: HOME not set" and does nothing
6916 const char *home = get_local_var_value("HOME");
6917 newdir = home ? home : "/";
6919 if (chdir(newdir)) {
6920 /* Mimic bash message exactly */
6921 bb_perror_msg("cd: %s", newdir);
6922 return EXIT_FAILURE;
6924 /* Read current dir (get_cwd(1) is inside) and set PWD.
6925 * Note: do not enforce exporting. If PWD was unset or unexported,
6926 * set it again, but do not export. bash does the same.
6928 set_pwd_var(/*exp:*/ 0);
6929 return EXIT_SUCCESS;
6932 static int FAST_FUNC builtin_exec(char **argv)
6934 if (*++argv == NULL)
6935 return EXIT_SUCCESS; /* bash does this */
6940 /* TODO: if exec fails, bash does NOT exit! We do... */
6941 pseudo_exec_argv(&dummy, argv, 0, NULL);
6946 static int FAST_FUNC builtin_exit(char **argv)
6948 debug_printf_exec("%s()\n", __func__);
6950 /* interactive bash:
6951 * # trap "echo EEE" EXIT
6954 * There are stopped jobs.
6955 * (if there are _stopped_ jobs, running ones don't count)
6958 # EEE (then bash exits)
6960 * we can use G.exiting = -1 as indicator "last cmd was exit"
6963 /* note: EXIT trap is run by hush_exit */
6964 if (*++argv == NULL)
6965 hush_exit(G.last_exitcode);
6966 /* mimic bash: exit 123abc == exit 255 + error msg */
6967 xfunc_error_retval = 255;
6968 /* bash: exit -2 == exit 254, no error msg */
6969 hush_exit(xatoi(*argv) & 0xff);
6972 static void print_escaped(const char *s)
6977 const char *p = strchrnul(s, '\'');
6978 /* print 'xxxx', possibly just '' */
6979 printf("'%.*s'", (int)(p - s), s);
6984 /* s points to '; print "'''...'''" */
6986 do putchar('\''); while (*++s == '\'');
6991 #if !ENABLE_HUSH_LOCAL
6992 #define helper_export_local(argv, exp, lvl) \
6993 helper_export_local(argv, exp)
6995 static void helper_export_local(char **argv, int exp, int lvl)
7000 /* So far we do not check that name is valid (TODO?) */
7002 if (strchr(name, '=') == NULL) {
7003 struct variable *var;
7005 var = get_local_var(name);
7006 if (exp == -1) { /* unexporting? */
7007 /* export -n NAME (without =VALUE) */
7009 var->flg_export = 0;
7010 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7012 } /* else: export -n NOT_EXISTING_VAR: no-op */
7015 if (exp == 1) { /* exporting? */
7016 /* export NAME (without =VALUE) */
7018 var->flg_export = 1;
7019 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7020 putenv(var->varstr);
7024 /* Exporting non-existing variable.
7025 * bash does not put it in environment,
7026 * but remembers that it is exported,
7027 * and does put it in env when it is set later.
7028 * We just set it to "" and export. */
7029 /* Or, it's "local NAME" (without =VALUE).
7030 * bash sets the value to "". */
7031 name = xasprintf("%s=", name);
7033 /* (Un)exporting/making local NAME=VALUE */
7034 name = xstrdup(name);
7036 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7040 static int FAST_FUNC builtin_export(char **argv)
7042 unsigned opt_unexport;
7044 #if ENABLE_HUSH_EXPORT_N
7045 /* "!": do not abort on errors */
7046 opt_unexport = getopt32(argv, "!n");
7047 if (opt_unexport == (uint32_t)-1)
7048 return EXIT_FAILURE;
7055 if (argv[0] == NULL) {
7062 /* ash emits: export VAR='VAL'
7063 * bash: declare -x VAR="VAL"
7064 * we follow ash example */
7065 const char *s = *e++;
7066 const char *p = strchr(s, '=');
7068 if (!p) /* wtf? take next variable */
7071 printf("export %.*s", (int)(p - s) + 1, s);
7072 print_escaped(p + 1);
7076 /*fflush(stdout); - done after each builtin anyway */
7078 return EXIT_SUCCESS;
7081 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7083 return EXIT_SUCCESS;
7086 #if ENABLE_HUSH_LOCAL
7087 static int FAST_FUNC builtin_local(char **argv)
7089 if (G.func_nest_level == 0) {
7090 bb_error_msg("%s: not in a function", argv[0]);
7091 return EXIT_FAILURE; /* bash compat */
7093 helper_export_local(argv, 0, G.func_nest_level);
7094 return EXIT_SUCCESS;
7098 static int FAST_FUNC builtin_trap(char **argv)
7104 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7109 /* No args: print all trapped */
7110 for (i = 0; i < NSIG; ++i) {
7113 print_escaped(G.traps[i]);
7114 /* note: bash adds "SIG", but only if invoked
7115 * as "bash". If called as "sh", or if set -o posix,
7116 * then it prints short signal names.
7117 * We are printing short names: */
7118 printf(" %s\n", get_signame(i));
7121 /*fflush(stdout); - done after each builtin anyway */
7122 return EXIT_SUCCESS;
7126 /* If first arg is a number: reset all specified signals */
7127 sig = bb_strtou(*argv, NULL, 10);
7133 sig = get_signum(*argv++);
7134 if (sig < 0 || sig >= NSIG) {
7136 /* Mimic bash message exactly */
7137 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7142 G.traps[sig] = xstrdup(new_cmd);
7144 debug_printf("trap: setting SIG%s (%i) to '%s'",
7145 get_signame(sig), sig, G.traps[sig]);
7147 /* There is no signal for 0 (EXIT) */
7152 sigaddset(&G.blocked_set, sig);
7154 /* There was a trap handler, we are removing it
7155 * (if sig has non-DFL handling,
7156 * we don't need to do anything) */
7157 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7159 sigdelset(&G.blocked_set, sig);
7162 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7166 if (!argv[1]) { /* no second arg */
7167 bb_error_msg("trap: invalid arguments");
7168 return EXIT_FAILURE;
7171 /* First arg is "-": reset all specified to default */
7172 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7173 /* Everything else: set arg as signal handler
7174 * (includes "" case, which ignores signal) */
7175 if (argv[0][0] == '-') {
7176 if (argv[0][1] == '\0') { /* "-" */
7177 /* new_cmd remains NULL: "reset these sigs" */
7180 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7183 /* else: "-something", no special meaning */
7188 goto process_sig_list;
7191 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7192 static int FAST_FUNC builtin_type(char **argv)
7194 int ret = EXIT_SUCCESS;
7200 if (0) {} /* make conditional compile easier below */
7201 /*else if (find_alias(*argv))
7202 type = "an alias";*/
7203 #if ENABLE_HUSH_FUNCTIONS
7204 else if (find_function(*argv))
7205 type = "a function";
7207 else if (find_builtin(*argv))
7208 type = "a shell builtin";
7209 else if ((path = find_in_path(*argv)) != NULL)
7212 bb_error_msg("type: %s: not found", *argv);
7217 printf("%s is %s\n", *argv, type);
7225 /* built-in 'fg' and 'bg' handler */
7226 static int FAST_FUNC builtin_fg_bg(char **argv)
7231 if (!G_interactive_fd)
7232 return EXIT_FAILURE;
7234 /* If they gave us no args, assume they want the last backgrounded task */
7236 for (pi = G.job_list; pi; pi = pi->next) {
7237 if (pi->jobid == G.last_jobid) {
7241 bb_error_msg("%s: no current job", argv[0]);
7242 return EXIT_FAILURE;
7244 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7245 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7246 return EXIT_FAILURE;
7248 for (pi = G.job_list; pi; pi = pi->next) {
7249 if (pi->jobid == jobnum) {
7253 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7254 return EXIT_FAILURE;
7256 /* TODO: bash prints a string representation
7257 * of job being foregrounded (like "sleep 1 | cat") */
7258 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7259 /* Put the job into the foreground. */
7260 tcsetpgrp(G_interactive_fd, pi->pgrp);
7263 /* Restart the processes in the job */
7264 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7265 for (i = 0; i < pi->num_cmds; i++) {
7266 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7267 pi->cmds[i].is_stopped = 0;
7269 pi->stopped_cmds = 0;
7271 i = kill(- pi->pgrp, SIGCONT);
7273 if (errno == ESRCH) {
7274 delete_finished_bg_job(pi);
7275 return EXIT_SUCCESS;
7277 bb_perror_msg("kill (SIGCONT)");
7280 if (argv[0][0] == 'f') {
7282 return checkjobs_and_fg_shell(pi);
7284 return EXIT_SUCCESS;
7288 #if ENABLE_HUSH_HELP
7289 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7291 const struct built_in_command *x;
7294 "Built-in commands:\n"
7295 "------------------\n");
7296 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7298 printf("%s\t%s\n", x->cmd, x->descr);
7301 return EXIT_SUCCESS;
7306 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7309 const char *status_string;
7311 for (job = G.job_list; job; job = job->next) {
7312 if (job->alive_cmds == job->stopped_cmds)
7313 status_string = "Stopped";
7315 status_string = "Running";
7317 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7319 return EXIT_SUCCESS;
7324 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7329 #ifdef M_TRIM_THRESHOLD
7330 /* Optional. Reduces probability of false positives */
7333 /* Crude attempt to find where "free memory" starts,
7334 * sans fragmentation. */
7336 l = (unsigned long)p;
7339 if (l < (unsigned long)p) l = (unsigned long)p;
7342 if (!G.memleak_value)
7343 G.memleak_value = l;
7345 l -= G.memleak_value;
7352 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7357 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7360 return EXIT_SUCCESS;
7363 static int FAST_FUNC builtin_read(char **argv)
7366 const char *name = "REPLY";
7370 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7371 * and _after_ that_ it will complain */
7372 if (!is_well_formed_var_name(name, '\0')) {
7373 /* Mimic bash message */
7374 bb_error_msg("read: '%s': not a valid identifier", name);
7379 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7381 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7382 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7385 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7386 * built-in 'set' handler
7388 * set [-abCefhmnuvx] [-o option] [argument...]
7389 * set [+abCefhmnuvx] [+o option] [argument...]
7390 * set -- [argument...]
7393 * Implementations shall support the options in both their hyphen and
7394 * plus-sign forms. These options can also be specified as options to sh.
7396 * Write out all variables and their values: set
7397 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7398 * Turn on the -x and -v options: set -xv
7399 * Unset all positional parameters: set --
7400 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7401 * Set the positional parameters to the expansion of x, even if x expands
7402 * with a leading '-' or '+': set -- $x
7404 * So far, we only support "set -- [argument...]" and some of the short names.
7406 static int FAST_FUNC builtin_set(char **argv)
7409 char **pp, **g_argv;
7410 char *arg = *++argv;
7414 for (e = G.top_var; e; e = e->next)
7416 return EXIT_SUCCESS;
7420 if (!strcmp(arg, "--")) {
7424 if (arg[0] != '+' && arg[0] != '-')
7426 for (n = 1; arg[n]; ++n)
7427 if (set_mode(arg[0], arg[n]))
7429 } while ((arg = *++argv) != NULL);
7430 /* Now argv[0] is 1st argument */
7433 return EXIT_SUCCESS;
7436 /* NB: G.global_argv[0] ($0) is never freed/changed */
7437 g_argv = G.global_argv;
7438 if (G.global_args_malloced) {
7444 G.global_args_malloced = 1;
7445 pp = xzalloc(sizeof(pp[0]) * 2);
7446 pp[0] = g_argv[0]; /* retain $0 */
7449 /* This realloc's G.global_argv */
7450 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7457 return EXIT_SUCCESS;
7459 /* Nothing known, so abort */
7461 bb_error_msg("set: %s: invalid option", arg);
7462 return EXIT_FAILURE;
7465 static int FAST_FUNC builtin_shift(char **argv)
7471 if (n >= 0 && n < G.global_argc) {
7472 if (G.global_args_malloced) {
7475 free(G.global_argv[m++]);
7478 memmove(&G.global_argv[1], &G.global_argv[n+1],
7479 G.global_argc * sizeof(G.global_argv[0]));
7480 return EXIT_SUCCESS;
7482 return EXIT_FAILURE;
7485 static int FAST_FUNC builtin_source(char **argv)
7490 #if ENABLE_HUSH_FUNCTIONS
7494 if (*++argv == NULL)
7495 return EXIT_FAILURE;
7497 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7498 input = fopen_for_read(arg_path);
7501 input = fopen_or_warn(*argv, "r");
7503 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7504 return EXIT_FAILURE;
7506 close_on_exec_on(fileno(input));
7508 #if ENABLE_HUSH_FUNCTIONS
7509 sv_flg = G.flag_return_in_progress;
7510 /* "we are inside sourced file, ok to use return" */
7511 G.flag_return_in_progress = -1;
7513 save_and_replace_G_args(&sv, argv);
7515 parse_and_run_file(input);
7518 restore_G_args(&sv, argv);
7519 #if ENABLE_HUSH_FUNCTIONS
7520 G.flag_return_in_progress = sv_flg;
7523 return G.last_exitcode;
7526 static int FAST_FUNC builtin_umask(char **argv)
7533 mode_t old_mask = mask;
7536 rc = bb_parse_mode(argv[1], &mask);
7541 * bash: umask: 'q': invalid symbolic mode operator
7542 * bash: umask: 999: octal number out of range
7544 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7549 printf("%04o\n", (unsigned) mask);
7550 /* fall through and restore mask which we set to 0 */
7554 return !rc; /* rc != 0 - success */
7557 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7558 static int FAST_FUNC builtin_unset(char **argv)
7563 /* "!": do not abort on errors */
7564 /* "+": stop at 1st non-option */
7565 opts = getopt32(argv, "!+vf");
7566 if (opts == (unsigned)-1)
7567 return EXIT_FAILURE;
7569 bb_error_msg("unset: -v and -f are exclusive");
7570 return EXIT_FAILURE;
7576 if (!(opts & 2)) { /* not -f */
7577 if (unset_local_var(*argv)) {
7578 /* unset <nonexistent_var> doesn't fail.
7579 * Error is when one tries to unset RO var.
7580 * Message was printed by unset_local_var. */
7584 #if ENABLE_HUSH_FUNCTIONS
7594 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7595 static int FAST_FUNC builtin_wait(char **argv)
7597 int ret = EXIT_SUCCESS;
7600 if (*++argv == NULL) {
7601 /* Don't care about wait results */
7602 /* Note 1: must wait until there are no more children */
7603 /* Note 2: must be interruptible */
7605 * $ sleep 3 & sleep 6 & wait
7610 * $ sleep 3 & sleep 6 & wait
7614 * ^C <-- after ~4 sec from keyboard
7617 sigaddset(&G.blocked_set, SIGCHLD);
7618 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7621 if (errno == ECHILD)
7623 /* Wait for SIGCHLD or any other signal of interest */
7624 /* sigtimedwait with infinite timeout: */
7625 sig = sigwaitinfo(&G.blocked_set, NULL);
7627 sig = check_and_run_traps(sig);
7628 if (sig && sig != SIGCHLD) { /* see note 2 */
7634 sigdelset(&G.blocked_set, SIGCHLD);
7635 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7639 /* This is probably buggy wrt interruptible-ness */
7641 pid_t pid = bb_strtou(*argv, NULL, 10);
7643 /* mimic bash message */
7644 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7645 return EXIT_FAILURE;
7647 if (waitpid(pid, &status, 0) == pid) {
7648 if (WIFSIGNALED(status))
7649 ret = 128 + WTERMSIG(status);
7650 else if (WIFEXITED(status))
7651 ret = WEXITSTATUS(status);
7655 bb_perror_msg("wait %s", *argv);
7664 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7665 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7668 def = bb_strtou(argv[1], NULL, 10);
7669 if (errno || def < def_min || argv[2]) {
7670 bb_error_msg("%s: bad arguments", argv[0]);
7678 #if ENABLE_HUSH_LOOPS
7679 static int FAST_FUNC builtin_break(char **argv)
7682 if (G.depth_of_loop == 0) {
7683 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7684 return EXIT_SUCCESS; /* bash compat */
7686 G.flag_break_continue++; /* BC_BREAK = 1 */
7688 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7689 if (depth == UINT_MAX)
7690 G.flag_break_continue = BC_BREAK;
7691 if (G.depth_of_loop < depth)
7692 G.depth_break_continue = G.depth_of_loop;
7694 return EXIT_SUCCESS;
7697 static int FAST_FUNC builtin_continue(char **argv)
7699 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7700 return builtin_break(argv);
7704 #if ENABLE_HUSH_FUNCTIONS
7705 static int FAST_FUNC builtin_return(char **argv)
7709 if (G.flag_return_in_progress != -1) {
7710 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7711 return EXIT_FAILURE; /* bash compat */
7714 G.flag_return_in_progress = 1;
7717 * out of range: wraps around at 256, does not error out
7718 * non-numeric param:
7719 * f() { false; return qwe; }; f; echo $?
7720 * bash: return: qwe: numeric argument required <== we do this
7721 * 255 <== we also do this
7723 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);