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 */
82 /* #include <dmalloc.h> */
89 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
94 #define LEAK_HUNTING 0
95 #define BUILD_AS_NOMMU 0
96 /* Enable/disable sanity checks. Ok to enable in production,
97 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
98 * Keeping 1 for now even in released versions.
101 /* Slightly bigger (+200 bytes), but faster hush.
102 * So far it only enables a trick with counting SIGCHLDs and forks,
103 * which allows us to do fewer waitpid's.
104 * (we can detect a case where neither forks were done nor SIGCHLDs happened
105 * and therefore waitpid will return the same result as last time)
107 #define ENABLE_HUSH_FAST 0
112 # undef USE_FOR_NOMMU
115 # define USE_FOR_NOMMU(...) __VA_ARGS__
116 # define USE_FOR_MMU(...)
119 #if defined SINGLE_APPLET_MAIN
120 /* STANDALONE does not make sense, and won't compile */
121 # undef CONFIG_FEATURE_SH_STANDALONE
122 # undef ENABLE_FEATURE_SH_STANDALONE
123 # undef IF_FEATURE_SH_STANDALONE
124 # define IF_FEATURE_SH_STANDALONE(...)
125 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
126 # define ENABLE_FEATURE_SH_STANDALONE 0
129 #if !ENABLE_HUSH_INTERACTIVE
130 # undef ENABLE_FEATURE_EDITING
131 # define ENABLE_FEATURE_EDITING 0
132 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
133 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
136 /* Do we support ANY keywords? */
137 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
138 # define HAS_KEYWORDS 1
139 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
140 # define IF_HAS_NO_KEYWORDS(...)
142 # define HAS_KEYWORDS 0
143 # define IF_HAS_KEYWORDS(...)
144 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
147 /* If you comment out one of these below, it will be #defined later
148 * to perform debug printfs to stderr: */
149 #define debug_printf(...) do {} while (0)
150 /* Finer-grained debug switches */
151 #define debug_printf_parse(...) do {} while (0)
152 #define debug_print_tree(a, b) do {} while (0)
153 #define debug_printf_exec(...) do {} while (0)
154 #define debug_printf_env(...) do {} while (0)
155 #define debug_printf_jobs(...) do {} while (0)
156 #define debug_printf_expand(...) do {} while (0)
157 #define debug_printf_glob(...) do {} while (0)
158 #define debug_printf_list(...) do {} while (0)
159 #define debug_printf_subst(...) do {} while (0)
160 #define debug_printf_clean(...) do {} while (0)
162 #define ERR_PTR ((void*)(long)1)
164 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
166 #define SPECIAL_VAR_SYMBOL 3
170 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
172 /* This supports saving pointers malloced in vfork child,
173 * to be freed in the parent.
176 typedef struct nommu_save_t {
178 struct variable *old_vars;
180 char **argv_from_re_execing;
184 typedef enum reserved_style {
193 #if ENABLE_HUSH_LOOPS
200 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
205 /* three pseudo-keywords support contrived "case" syntax: */
206 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
207 RES_MATCH , /* "word)" */
208 RES_CASE_BODY, /* "this command is inside CASE" */
215 typedef struct o_string {
217 int length; /* position where data is appended */
219 /* Protect newly added chars against globbing
220 * (by prepending \ to *, ?, [, \) */
223 /* At least some part of the string was inside '' or "",
224 * possibly empty one: word"", wo''rd etc. */
226 smallint has_empty_slot;
227 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
230 MAYBE_ASSIGNMENT = 0,
231 DEFINITELY_ASSIGNMENT = 1,
233 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
235 /* Used for initialization: o_string foo = NULL_O_STRING; */
236 #define NULL_O_STRING { NULL }
238 /* I can almost use ordinary FILE*. Is open_memstream() universally
239 * available? Where is it documented? */
240 typedef struct in_str {
242 /* eof_flag=1: last char in ->p is really an EOF */
243 char eof_flag; /* meaningless if ->p == NULL */
245 #if ENABLE_HUSH_INTERACTIVE
247 smallint promptmode; /* 0: PS1, 1: PS2 */
250 int (*get) (struct in_str *) FAST_FUNC;
251 int (*peek) (struct in_str *) FAST_FUNC;
253 #define i_getch(input) ((input)->get(input))
254 #define i_peek(input) ((input)->peek(input))
256 /* The descrip member of this structure is only used to make
257 * debugging output pretty */
258 static const struct {
260 signed char default_fd;
263 { O_RDONLY, 0, "<" },
264 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
265 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
266 { O_CREAT|O_RDWR, 1, "<>" },
267 { O_RDONLY, 0, "<<" },
268 /* Should not be needed. Bogus default_fd helps in debugging */
269 /* { O_RDONLY, 77, "<<" }, */
272 struct redir_struct {
273 struct redir_struct *next;
274 char *rd_filename; /* filename */
275 int rd_fd; /* fd to redirect */
276 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
278 smallint rd_type; /* (enum redir_type) */
279 /* note: for heredocs, rd_filename contains heredoc delimiter,
280 * and subsequently heredoc itself; and rd_dup is a bitmask:
281 * bit 0: do we need to trim leading tabs?
282 * bit 1: is heredoc quoted (<<'delim' syntax) ?
285 typedef enum redir_type {
287 REDIRECT_OVERWRITE = 1,
290 REDIRECT_HEREDOC = 4,
291 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
294 REDIRFD_SYNTAX_ERR = -2,
295 REDIRFD_TO_FILE = -1,
296 /* otherwise, rd_fd is redirected to rd_dup */
298 HEREDOC_SKIPTABS = 1,
304 pid_t pid; /* 0 if exited */
305 int assignment_cnt; /* how many argv[i] are assignments? */
306 smallint is_stopped; /* is the command currently running? */
307 smallint cmd_type; /* CMD_xxx */
309 #define CMD_SUBSHELL 1
311 /* used for "[[ EXPR ]]" */
312 #if ENABLE_HUSH_BASH_COMPAT
313 # define CMD_SINGLEWORD_NOGLOB 2
316 /* used for "export noglob=* glob* a=`echo a b`" */
317 //#define CMD_SINGLEWORD_NOGLOB_COND 3
318 // It is hard to implement correctly, it adds significant amounts of tricky code,
319 // and all this is only useful for really obscure export statements
320 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
321 // guards the code which implements it, but I have doubts it works
322 // in all cases (especially with mixed globbed/non-globbed arguments)
324 #if ENABLE_HUSH_FUNCTIONS
325 # define CMD_FUNCDEF 3
328 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
331 char *group_as_string;
333 #if ENABLE_HUSH_FUNCTIONS
334 struct function *child_func;
335 /* This field is used to prevent a bug here:
336 * while...do f1() {a;}; f1; f1() {b;}; f1; done
337 * When we execute "f1() {a;}" cmd, we create new function and clear
338 * cmd->group, cmd->group_as_string, cmd->argv[0].
339 * When we execute "f1() {b;}", we notice that f1 exists,
340 * and that its "parent cmd" struct is still "alive",
341 * we put those fields back into cmd->xxx
342 * (struct function has ->parent_cmd ptr to facilitate that).
343 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
344 * Without this trick, loop would execute a;b;b;b;...
345 * instead of correct sequence a;b;a;b;...
346 * When command is freed, it severs the link
347 * (sets ->child_func->parent_cmd to NULL).
350 char **argv; /* command name and arguments */
351 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
352 * and on execution these are substituted with their values.
353 * Substitution can make _several_ words out of one argv[n]!
354 * Example: argv[0]=='.^C*^C.' here: echo .$*.
355 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
357 struct redir_struct *redirects; /* I/O redirections */
359 /* Is there anything in this command at all? */
360 #define IS_NULL_CMD(cmd) \
361 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
366 int num_cmds; /* total number of commands in pipe */
367 int alive_cmds; /* number of commands running (not exited) */
368 int stopped_cmds; /* number of commands alive, but stopped */
370 int jobid; /* job number */
371 pid_t pgrp; /* process group ID for the job */
372 char *cmdtext; /* name of job */
374 struct command *cmds; /* array of commands in pipe */
375 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
376 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
377 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
379 typedef enum pipe_style {
385 /* Is there anything in this pipe at all? */
386 #define IS_NULL_PIPE(pi) \
387 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
389 /* This holds pointers to the various results of parsing */
390 struct parse_context {
391 /* linked list of pipes */
392 struct pipe *list_head;
393 /* last pipe (being constructed right now) */
395 /* last command in pipe (being constructed right now) */
396 struct command *command;
397 /* last redirect in command->redirects list */
398 struct redir_struct *pending_redirect;
404 smallint ctx_inverted; /* "! cmd | cmd" */
406 smallint ctx_dsemicolon; /* ";;" seen */
408 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
410 /* group we are enclosed in:
411 * example: "if pipe1; pipe2; then pipe3; fi"
412 * when we see "if" or "then", we malloc and copy current context,
413 * and make ->stack point to it. then we parse pipeN.
414 * when closing "then" / fi" / whatever is found,
415 * we move list_head into ->stack->command->group,
416 * copy ->stack into current context, and delete ->stack.
417 * (parsing of { list } and ( list ) doesn't use this method)
419 struct parse_context *stack;
423 /* On program start, environ points to initial environment.
424 * putenv adds new pointers into it, unsetenv removes them.
425 * Neither of these (de)allocates the strings.
426 * setenv allocates new strings in malloc space and does putenv,
427 * and thus setenv is unusable (leaky) for shell's purposes */
428 #define setenv(...) setenv_is_leaky_dont_use()
430 struct variable *next;
431 char *varstr; /* points to "name=" portion */
432 #if ENABLE_HUSH_LOCAL
433 unsigned func_nest_level;
435 int max_len; /* if > 0, name is part of initial env; else name is malloced */
436 smallint flg_export; /* putenv should be done on this var */
437 smallint flg_read_only;
445 #if ENABLE_HUSH_FUNCTIONS
447 struct function *next;
449 struct command *parent_cmd;
452 char *body_as_string;
458 /* "Globals" within this file */
459 /* Sorted roughly by size (smaller offsets == smaller code) */
461 /* interactive_fd != 0 means we are an interactive shell.
462 * If we are, then saved_tty_pgrp can also be != 0, meaning
463 * that controlling tty is available. With saved_tty_pgrp == 0,
464 * job control still works, but terminal signals
465 * (^C, ^Z, ^Y, ^\) won't work at all, and background
466 * process groups can only be created with "cmd &".
467 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
468 * to give tty to the foreground process group,
469 * and will take it back when the group is stopped (^Z)
472 #if ENABLE_HUSH_INTERACTIVE
473 /* 'interactive_fd' is a fd# open to ctty, if we have one
474 * _AND_ if we decided to act interactively */
478 # define G_interactive_fd (G.interactive_fd)
480 # define G_interactive_fd 0
482 #if ENABLE_FEATURE_EDITING
483 line_input_t *line_input_state;
490 pid_t saved_tty_pgrp;
491 struct pipe *job_list;
492 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
494 # define G_saved_tty_pgrp 0
496 smallint flag_SIGINT;
497 #if ENABLE_HUSH_LOOPS
498 smallint flag_break_continue;
500 #if ENABLE_HUSH_FUNCTIONS
501 /* 0: outside of a function (or sourced file)
502 * -1: inside of a function, ok to use return builtin
503 * 1: return is invoked, skip all till end of func
505 smallint flag_return_in_progress;
508 smallint exiting; /* used to prevent EXIT trap recursion */
509 /* These four support $?, $#, and $1 */
510 smalluint last_exitcode;
511 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
512 smalluint global_args_malloced;
513 /* how many non-NULL argv's we have. NB: $# + 1 */
517 char *argv0_for_re_execing;
519 #if ENABLE_HUSH_LOOPS
520 unsigned depth_break_continue;
521 unsigned depth_of_loop;
525 struct variable *top_var; /* = &G.shell_ver (set in main()) */
526 struct variable shell_ver;
527 #if ENABLE_HUSH_FUNCTIONS
528 struct function *top_func;
529 # if ENABLE_HUSH_LOCAL
530 struct variable **shadowed_vars_pp;
531 unsigned func_nest_level;
534 /* Signal and trap handling */
536 unsigned count_SIGCHLD;
537 unsigned handled_SIGCHLD;
538 smallint we_have_children;
540 /* which signals have non-DFL handler (even with no traps set)? */
541 unsigned non_DFL_mask;
542 char **traps; /* char *traps[NSIG] */
543 sigset_t blocked_set;
544 sigset_t inherited_set;
546 unsigned long memleak_value;
549 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
551 #define G (*ptr_to_globals)
552 /* Not #defining name to G.name - this quickly gets unwieldy
553 * (too many defines). Also, I actually prefer to see when a variable
554 * is global, thus "G." prefix is a useful hint */
555 #define INIT_G() do { \
556 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
560 /* Function prototypes for builtins */
561 static int builtin_cd(char **argv) FAST_FUNC;
562 static int builtin_echo(char **argv) FAST_FUNC;
563 static int builtin_eval(char **argv) FAST_FUNC;
564 static int builtin_exec(char **argv) FAST_FUNC;
565 static int builtin_exit(char **argv) FAST_FUNC;
566 static int builtin_export(char **argv) FAST_FUNC;
568 static int builtin_fg_bg(char **argv) FAST_FUNC;
569 static int builtin_jobs(char **argv) FAST_FUNC;
572 static int builtin_help(char **argv) FAST_FUNC;
574 #if ENABLE_HUSH_LOCAL
575 static int builtin_local(char **argv) FAST_FUNC;
578 static int builtin_memleak(char **argv) FAST_FUNC;
580 static int builtin_pwd(char **argv) FAST_FUNC;
581 static int builtin_read(char **argv) FAST_FUNC;
582 static int builtin_set(char **argv) FAST_FUNC;
583 static int builtin_shift(char **argv) FAST_FUNC;
584 static int builtin_source(char **argv) FAST_FUNC;
585 static int builtin_test(char **argv) FAST_FUNC;
586 static int builtin_trap(char **argv) FAST_FUNC;
587 static int builtin_type(char **argv) FAST_FUNC;
588 static int builtin_true(char **argv) FAST_FUNC;
589 static int builtin_umask(char **argv) FAST_FUNC;
590 static int builtin_unset(char **argv) FAST_FUNC;
591 static int builtin_wait(char **argv) FAST_FUNC;
592 #if ENABLE_HUSH_LOOPS
593 static int builtin_break(char **argv) FAST_FUNC;
594 static int builtin_continue(char **argv) FAST_FUNC;
596 #if ENABLE_HUSH_FUNCTIONS
597 static int builtin_return(char **argv) FAST_FUNC;
600 /* Table of built-in functions. They can be forked or not, depending on
601 * context: within pipes, they fork. As simple commands, they do not.
602 * When used in non-forking context, they can change global variables
603 * in the parent shell process. If forked, of course they cannot.
604 * For example, 'unset foo | whatever' will parse and run, but foo will
605 * still be set at the end. */
606 struct built_in_command {
608 int (*function)(char **argv) FAST_FUNC;
611 # define BLTIN(cmd, func, help) { cmd, func, help }
613 # define BLTIN(cmd, func, help) { cmd, func }
617 static const struct built_in_command bltins1[] = {
618 BLTIN("." , builtin_source , "Run commands in a file"),
619 BLTIN(":" , builtin_true , NULL),
621 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
623 #if ENABLE_HUSH_LOOPS
624 BLTIN("break" , builtin_break , "Exit from a loop"),
626 BLTIN("cd" , builtin_cd , "Change directory"),
627 #if ENABLE_HUSH_LOOPS
628 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
630 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
631 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
632 BLTIN("exit" , builtin_exit , "Exit"),
633 BLTIN("export" , builtin_export , "Set environment variables"),
635 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
638 BLTIN("help" , builtin_help , NULL),
641 BLTIN("jobs" , builtin_jobs , "List jobs"),
643 #if ENABLE_HUSH_LOCAL
644 BLTIN("local" , builtin_local , "Set local variables"),
647 BLTIN("memleak" , builtin_memleak , NULL),
649 BLTIN("read" , builtin_read , "Input into variable"),
650 #if ENABLE_HUSH_FUNCTIONS
651 BLTIN("return" , builtin_return , "Return from a function"),
653 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
654 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
655 BLTIN("trap" , builtin_trap , "Trap signals"),
656 BLTIN("type" , builtin_type , "Write a description of command type"),
657 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
658 BLTIN("umask" , builtin_umask , "Set file creation mask"),
659 BLTIN("unset" , builtin_unset , "Unset variables"),
660 BLTIN("wait" , builtin_wait , "Wait for process"),
662 /* For now, echo and test are unconditionally enabled.
663 * Maybe make it configurable? */
664 static const struct built_in_command bltins2[] = {
665 BLTIN("[" , builtin_test , NULL),
666 BLTIN("echo" , builtin_echo , NULL),
667 BLTIN("pwd" , builtin_pwd , NULL),
668 BLTIN("test" , builtin_test , NULL),
675 /* prevent disasters with G.debug_indent < 0 */
676 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
677 # define debug_enter() (G.debug_indent++)
678 # define debug_leave() (G.debug_indent--)
680 # define indent() ((void)0)
681 # define debug_enter() ((void)0)
682 # define debug_leave() ((void)0)
686 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
689 #ifndef debug_printf_parse
690 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
693 #ifndef debug_printf_exec
694 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
697 #ifndef debug_printf_env
698 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
701 #ifndef debug_printf_jobs
702 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
703 # define DEBUG_JOBS 1
705 # define DEBUG_JOBS 0
708 #ifndef debug_printf_expand
709 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
710 # define DEBUG_EXPAND 1
712 # define DEBUG_EXPAND 0
715 #ifndef debug_printf_glob
716 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
717 # define DEBUG_GLOB 1
719 # define DEBUG_GLOB 0
722 #ifndef debug_printf_list
723 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
726 #ifndef debug_printf_subst
727 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
730 #ifndef debug_printf_clean
731 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
732 # define DEBUG_CLEAN 1
734 # define DEBUG_CLEAN 0
738 static void debug_print_strings(const char *prefix, char **vv)
741 fprintf(stderr, "%s:\n", prefix);
743 fprintf(stderr, " '%s'\n", *vv++);
746 # define debug_print_strings(prefix, vv) ((void)0)
750 /* Leak hunting. Use hush_leaktool.sh for post-processing.
753 static void *xxmalloc(int lineno, size_t size)
755 void *ptr = xmalloc((size + 0xff) & ~0xff);
756 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
759 static void *xxrealloc(int lineno, void *ptr, size_t size)
761 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
762 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
765 static char *xxstrdup(int lineno, const char *str)
767 char *ptr = xstrdup(str);
768 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
771 static void xxfree(void *ptr)
773 fdprintf(2, "free %p\n", ptr);
776 #define xmalloc(s) xxmalloc(__LINE__, s)
777 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
778 #define xstrdup(s) xxstrdup(__LINE__, s)
779 #define free(p) xxfree(p)
783 /* Syntax and runtime errors. They always abort scripts.
784 * In interactive use they usually discard unparsed and/or unexecuted commands
785 * and return to the prompt.
786 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
789 # define die_if_script(lineno, fmt...) die_if_script(fmt)
790 # define syntax_error(lineno, msg) syntax_error(msg)
791 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
792 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
793 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
794 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
797 static void die_if_script(unsigned lineno, const char *fmt, ...)
802 bb_error_msg("hush.c:%u", lineno);
805 bb_verror_msg(fmt, p, NULL);
807 if (!G_interactive_fd)
811 static void syntax_error(unsigned lineno, const char *msg)
814 die_if_script(lineno, "syntax error: %s", msg);
816 die_if_script(lineno, "syntax error", NULL);
819 static void syntax_error_at(unsigned lineno, const char *msg)
821 die_if_script(lineno, "syntax error at '%s'", msg);
824 static void syntax_error_unterm_str(unsigned lineno, const char *s)
826 die_if_script(lineno, "syntax error: unterminated %s", s);
829 /* It so happens that all such cases are totally fatal
830 * even if shell is interactive: EOF while looking for closing
831 * delimiter. There is nowhere to read stuff from after that,
832 * it's EOF! The only choice is to terminate.
834 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
835 static void syntax_error_unterm_ch(unsigned lineno, char ch)
837 char msg[2] = { ch, '\0' };
838 syntax_error_unterm_str(lineno, msg);
842 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
847 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
851 # undef die_if_script
853 # undef syntax_error_at
854 # undef syntax_error_unterm_ch
855 # undef syntax_error_unterm_str
856 # undef syntax_error_unexpected_ch
858 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
859 # define syntax_error(msg) syntax_error(__LINE__, msg)
860 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
861 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
862 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
863 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
867 #if ENABLE_HUSH_INTERACTIVE
868 static void cmdedit_update_prompt(void);
870 # define cmdedit_update_prompt() ((void)0)
876 static int glob_needed(const char *s)
881 if (*s == '*' || *s == '[' || *s == '?')
888 static int is_well_formed_var_name(const char *s, char terminator)
890 if (!s || !(isalpha(*s) || *s == '_'))
893 while (isalnum(*s) || *s == '_')
895 return *s == terminator;
898 /* Replace each \x with x in place, return ptr past NUL. */
899 static char *unbackslash(char *src)
905 if ((*dst++ = *src++) == '\0')
911 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
932 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
933 v[count1 + count2] = NULL;
936 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
940 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
942 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
943 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
946 #define add_strings_to_strings(strings, add, need_to_dup) \
947 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
950 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
951 static char **add_string_to_strings(char **strings, char *add)
956 return add_strings_to_strings(strings, v, /*dup:*/ 0);
959 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
961 char **ptr = add_string_to_strings(strings, add);
962 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
965 #define add_string_to_strings(strings, add) \
966 xx_add_string_to_strings(__LINE__, strings, add)
969 static void free_strings(char **strings)
984 /* Helpers for setting new $n and restoring them back
986 typedef struct save_arg_t {
990 smallint sv_g_malloced;
993 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
997 sv->sv_argv0 = argv[0];
998 sv->sv_g_argv = G.global_argv;
999 sv->sv_g_argc = G.global_argc;
1000 sv->sv_g_malloced = G.global_args_malloced;
1002 argv[0] = G.global_argv[0]; /* retain $0 */
1003 G.global_argv = argv;
1004 G.global_args_malloced = 0;
1012 static void restore_G_args(save_arg_t *sv, char **argv)
1016 if (G.global_args_malloced) {
1017 /* someone ran "set -- arg1 arg2 ...", undo */
1019 while (*++pp) /* note: does not free $0 */
1021 free(G.global_argv);
1023 argv[0] = sv->sv_argv0;
1024 G.global_argv = sv->sv_g_argv;
1025 G.global_argc = sv->sv_g_argc;
1026 G.global_args_malloced = sv->sv_g_malloced;
1030 /* Basic theory of signal handling in shell
1031 * ========================================
1032 * This does not describe what hush does, rather, it is current understanding
1033 * what it _should_ do. If it doesn't, it's a bug.
1034 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1036 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1037 * is finished or backgrounded. It is the same in interactive and
1038 * non-interactive shells, and is the same regardless of whether
1039 * a user trap handler is installed or a shell special one is in effect.
1040 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1041 * backgrounds (i.e. stops) or kills all members of currently running
1044 * Wait builtin in interruptible by signals for which user trap is set
1045 * or by SIGINT in interactive shell.
1047 * Trap handlers will execute even within trap handlers. (right?)
1049 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1051 * If job control is off, backgrounded commands ("cmd &")
1052 * have SIGINT, SIGQUIT set to SIG_IGN.
1054 * Commands which are run in command substitution ("`cmd`")
1055 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1057 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1058 * by the shell from its parent.
1060 * Signals which differ from SIG_DFL action
1061 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1064 * SIGTERM (interactive): ignore
1065 * SIGHUP (interactive):
1066 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1067 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1068 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1069 * that all pipe members are stopped. Try this in bash:
1070 * while :; do :; done - ^Z does not background it
1071 * (while :; do :; done) - ^Z backgrounds it
1072 * SIGINT (interactive): wait for last pipe, ignore the rest
1073 * of the command line, show prompt. NB: ^C does not send SIGINT
1074 * to interactive shell while shell is waiting for a pipe,
1075 * since shell is bg'ed (is not in foreground process group).
1076 * Example 1: this waits 5 sec, but does not execute ls:
1077 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1078 * Example 2: this does not wait and does not execute ls:
1079 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1080 * Example 3: this does not wait 5 sec, but executes ls:
1081 * "sleep 5; ls -l" + press ^C
1083 * (What happens to signals which are IGN on shell start?)
1084 * (What happens with signal mask on shell start?)
1086 * Implementation in hush
1087 * ======================
1088 * We use in-kernel pending signal mask to determine which signals were sent.
1089 * We block all signals which we don't want to take action immediately,
1090 * i.e. we block all signals which need to have special handling as described
1091 * above, and all signals which have traps set.
1092 * After each pipe execution, we extract any pending signals via sigtimedwait()
1095 * unsigned non_DFL_mask: a mask of such "special" signals
1096 * sigset_t blocked_set: current blocked signal set
1099 * clear bit in blocked_set unless it is also in non_DFL_mask
1100 * "trap 'cmd' SIGxxx":
1101 * set bit in blocked_set (even if 'cmd' is '')
1102 * after [v]fork, if we plan to be a shell:
1103 * unblock signals with special interactive handling
1104 * (child shell is not interactive),
1105 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1106 * after [v]fork, if we plan to exec:
1107 * POSIX says pending signal mask is cleared in child - no need to clear it.
1108 * Restore blocked signal set to one inherited by shell just prior to exec.
1110 * Note: as a result, we do not use signal handlers much. The only uses
1111 * are to count SIGCHLDs
1112 * and to restore tty pgrp on signal-induced exit.
1115 SPECIAL_INTERACTIVE_SIGS = 0
1120 SPECIAL_JOB_SIGS = 0
1128 #if ENABLE_HUSH_FAST
1129 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1132 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1138 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1139 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1140 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1141 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1143 /* Restores tty foreground process group, and exits.
1144 * May be called as signal handler for fatal signal
1145 * (will resend signal to itself, producing correct exit state)
1146 * or called directly with -EXITCODE.
1147 * We also call it if xfunc is exiting. */
1148 static void sigexit(int sig) NORETURN;
1149 static void sigexit(int sig)
1151 /* Disable all signals: job control, SIGPIPE, etc. */
1152 sigprocmask_allsigs(SIG_BLOCK);
1154 /* Careful: we can end up here after [v]fork. Do not restore
1155 * tty pgrp then, only top-level shell process does that */
1156 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1157 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1159 /* Not a signal, just exit */
1163 kill_myself_with_sig(sig); /* does not return */
1167 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1168 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1172 /* Restores tty foreground process group, and exits. */
1173 static void hush_exit(int exitcode) NORETURN;
1174 static void hush_exit(int exitcode)
1176 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1177 /* Prevent recursion:
1178 * trap "echo Hi; exit" EXIT; exit
1180 char *argv[] = { NULL, G.traps[0], NULL };
1188 fflush(NULL); /* flush all streams */
1189 sigexit(- (exitcode & 0xff));
1195 static int check_and_run_traps(int sig)
1197 static const struct timespec zero_timespec = { 0, 0 };
1198 smalluint save_rcode;
1204 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1209 if (G.traps && G.traps[sig]) {
1210 if (G.traps[sig][0]) {
1211 /* We have user-defined handler */
1212 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1213 save_rcode = G.last_exitcode;
1216 G.last_exitcode = save_rcode;
1217 } /* else: "" trap, ignoring signal */
1220 /* not a trap: special action */
1222 #if ENABLE_HUSH_FAST
1225 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1229 /* Builtin was ^C'ed, make it look prettier: */
1236 /* bash is observed to signal whole process groups,
1237 * not individual processes */
1238 for (job = G.job_list; job; job = job->next) {
1241 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1242 if (kill(- job->pgrp, SIGHUP) == 0)
1243 kill(- job->pgrp, SIGCONT);
1248 default: /* ignored: */
1249 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1257 static const char *get_cwd(int force)
1259 if (force || G.cwd == NULL) {
1260 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1261 * we must not try to free(bb_msg_unknown) */
1262 if (G.cwd == bb_msg_unknown)
1264 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1266 G.cwd = bb_msg_unknown;
1273 * Shell and environment variable support
1275 static struct variable **get_ptr_to_local_var(const char *name)
1277 struct variable **pp;
1278 struct variable *cur;
1283 while ((cur = *pp) != NULL) {
1284 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1291 static struct variable *get_local_var(const char *name)
1293 struct variable **pp = get_ptr_to_local_var(name);
1299 static const char *get_local_var_value(const char *name)
1301 struct variable **pp = get_ptr_to_local_var(name);
1303 return strchr((*pp)->varstr, '=') + 1;
1307 /* str holds "NAME=VAL" and is expected to be malloced.
1308 * We take ownership of it.
1310 * 0: do not change export flag
1311 * (if creating new variable, flag will be 0)
1312 * 1: set export flag and putenv the variable
1313 * -1: clear export flag and unsetenv the variable
1314 * flg_read_only is set only when we handle -R var=val
1316 #if !BB_MMU && ENABLE_HUSH_LOCAL
1317 /* all params are used */
1318 #elif BB_MMU && ENABLE_HUSH_LOCAL
1319 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1320 set_local_var(str, flg_export, local_lvl)
1321 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1322 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1323 set_local_var(str, flg_export)
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, flg_read_only)
1328 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1330 struct variable **var_pp;
1331 struct variable *cur;
1335 eq_sign = strchr(str, '=');
1336 if (!eq_sign) { /* not expected to ever happen? */
1341 name_len = eq_sign - str + 1; /* including '=' */
1342 var_pp = &G.top_var;
1343 while ((cur = *var_pp) != NULL) {
1344 if (strncmp(cur->varstr, str, name_len) != 0) {
1345 var_pp = &cur->next;
1348 /* We found an existing var with this name */
1349 if (cur->flg_read_only) {
1353 bb_error_msg("%s: readonly variable", str);
1357 if (flg_export == -1) { // "&& cur->flg_export" ?
1358 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1363 #if ENABLE_HUSH_LOCAL
1364 if (cur->func_nest_level < local_lvl) {
1365 /* New variable is declared as local,
1366 * and existing one is global, or local
1367 * from enclosing function.
1368 * Remove and save old one: */
1369 *var_pp = cur->next;
1370 cur->next = *G.shadowed_vars_pp;
1371 *G.shadowed_vars_pp = cur;
1372 /* bash 3.2.33(1) and exported vars:
1374 * # f() { local z=a; env | grep ^z; }
1380 if (cur->flg_export)
1385 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1390 if (cur->max_len != 0) {
1391 if (cur->max_len >= strlen(str)) {
1392 /* This one is from startup env, reuse space */
1393 strcpy(cur->varstr, str);
1397 /* max_len == 0 signifies "malloced" var, which we can
1398 * (and has to) free */
1402 goto set_str_and_exp;
1405 /* Not found - create new variable struct */
1406 cur = xzalloc(sizeof(*cur));
1407 #if ENABLE_HUSH_LOCAL
1408 cur->func_nest_level = local_lvl;
1410 cur->next = *var_pp;
1416 cur->flg_read_only = flg_read_only;
1419 if (flg_export == 1)
1420 cur->flg_export = 1;
1421 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1422 cmdedit_update_prompt();
1423 if (cur->flg_export) {
1424 if (flg_export == -1) {
1425 cur->flg_export = 0;
1426 /* unsetenv was already done */
1428 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1429 return putenv(cur->varstr);
1435 /* Used at startup and after each cd */
1436 static void set_pwd_var(int exp)
1438 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1439 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1442 static int unset_local_var_len(const char *name, int name_len)
1444 struct variable *cur;
1445 struct variable **var_pp;
1448 return EXIT_SUCCESS;
1449 var_pp = &G.top_var;
1450 while ((cur = *var_pp) != NULL) {
1451 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1452 if (cur->flg_read_only) {
1453 bb_error_msg("%s: readonly variable", name);
1454 return EXIT_FAILURE;
1456 *var_pp = cur->next;
1457 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1458 bb_unsetenv(cur->varstr);
1459 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1460 cmdedit_update_prompt();
1464 return EXIT_SUCCESS;
1466 var_pp = &cur->next;
1468 return EXIT_SUCCESS;
1471 static int unset_local_var(const char *name)
1473 return unset_local_var_len(name, strlen(name));
1476 static void unset_vars(char **strings)
1484 const char *eq = strchrnul(*v, '=');
1485 unset_local_var_len(*v, (int)(eq - *v));
1491 #if ENABLE_SH_MATH_SUPPORT
1492 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1493 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1494 static char *endofname(const char *name)
1502 if (!is_in_name(*p))
1508 static void arith_set_local_var(const char *name, const char *val, int flags)
1510 /* arith code doesnt malloc space, so do it for it */
1511 char *var = xasprintf("%s=%s", name, val);
1512 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1518 * Helpers for "var1=val1 var2=val2 cmd" feature
1520 static void add_vars(struct variable *var)
1522 struct variable *next;
1526 var->next = G.top_var;
1528 if (var->flg_export) {
1529 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1530 putenv(var->varstr);
1532 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1538 static struct variable *set_vars_and_save_old(char **strings)
1541 struct variable *old = NULL;
1547 struct variable *var_p;
1548 struct variable **var_pp;
1551 eq = strchr(*s, '=');
1554 var_pp = get_ptr_to_local_var(*s);
1557 /* Remove variable from global linked list */
1559 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1560 *var_pp = var_p->next;
1561 /* Add it to returned list */
1565 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1576 static int FAST_FUNC static_get(struct in_str *i)
1585 static int FAST_FUNC static_peek(struct in_str *i)
1590 #if ENABLE_HUSH_INTERACTIVE
1592 static void cmdedit_update_prompt(void)
1594 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1595 G.PS1 = get_local_var_value("PS1");
1598 G.PS2 = get_local_var_value("PS2");
1606 static const char* setup_prompt_string(int promptmode)
1608 const char *prompt_str;
1609 debug_printf("setup_prompt_string %d ", promptmode);
1610 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1611 /* Set up the prompt */
1612 if (promptmode == 0) { /* PS1 */
1614 /* bash uses $PWD value, even if it is set by user.
1615 * It uses current dir only if PWD is unset.
1616 * We always use current dir. */
1617 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1622 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1623 debug_printf("result '%s'\n", prompt_str);
1627 static void get_user_input(struct in_str *i)
1630 const char *prompt_str;
1632 prompt_str = setup_prompt_string(i->promptmode);
1633 #if ENABLE_FEATURE_EDITING
1634 /* Enable command line editing only while a command line
1635 * is actually being read */
1638 /* buglet: SIGINT will not make new prompt to appear _at once_,
1639 * only after <Enter>. (^C will work) */
1640 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1641 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1642 check_and_run_traps(0);
1643 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1644 i->eof_flag = (r < 0);
1645 if (i->eof_flag) { /* EOF/error detected */
1646 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1647 G.user_input_buf[1] = '\0';
1652 fputs(prompt_str, stdout);
1654 G.user_input_buf[0] = r = fgetc(i->file);
1655 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1656 //do we need check_and_run_traps(0)? (maybe only if stdin)
1657 } while (G.flag_SIGINT);
1658 i->eof_flag = (r == EOF);
1660 i->p = G.user_input_buf;
1663 #endif /* INTERACTIVE */
1665 /* This is the magic location that prints prompts
1666 * and gets data back from the user */
1667 static int FAST_FUNC file_get(struct in_str *i)
1671 /* If there is data waiting, eat it up */
1672 if (i->p && *i->p) {
1673 #if ENABLE_HUSH_INTERACTIVE
1677 if (i->eof_flag && !*i->p)
1679 /* note: ch is never NUL */
1681 /* need to double check i->file because we might be doing something
1682 * more complicated by now, like sourcing or substituting. */
1683 #if ENABLE_HUSH_INTERACTIVE
1684 if (G_interactive_fd && i->promptme && i->file == stdin) {
1687 } while (!*i->p); /* need non-empty line */
1688 i->promptmode = 1; /* PS2 */
1693 do ch = fgetc(i->file); while (ch == '\0');
1695 debug_printf("file_get: got '%c' %d\n", ch, ch);
1696 #if ENABLE_HUSH_INTERACTIVE
1703 /* All callers guarantee this routine will never
1704 * be used right after a newline, so prompting is not needed.
1706 static int FAST_FUNC file_peek(struct in_str *i)
1709 if (i->p && *i->p) {
1710 if (i->eof_flag && !i->p[1])
1713 /* note: ch is never NUL */
1715 do ch = fgetc(i->file); while (ch == '\0');
1716 i->eof_flag = (ch == EOF);
1717 i->peek_buf[0] = ch;
1718 i->peek_buf[1] = '\0';
1720 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1724 static void setup_file_in_str(struct in_str *i, FILE *f)
1726 i->peek = file_peek;
1728 #if ENABLE_HUSH_INTERACTIVE
1730 i->promptmode = 0; /* PS1 */
1736 static void setup_string_in_str(struct in_str *i, const char *s)
1738 i->peek = static_peek;
1739 i->get = static_get;
1740 #if ENABLE_HUSH_INTERACTIVE
1742 i->promptmode = 0; /* PS1 */
1752 #define B_CHUNK (32 * sizeof(char*))
1754 static void o_reset_to_empty_unquoted(o_string *o)
1762 static void o_free(o_string *o)
1765 memset(o, 0, sizeof(*o));
1768 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1773 static void o_grow_by(o_string *o, int len)
1775 if (o->length + len > o->maxlen) {
1776 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1777 o->data = xrealloc(o->data, 1 + o->maxlen);
1781 static void o_addchr(o_string *o, int ch)
1783 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1785 o->data[o->length] = ch;
1787 o->data[o->length] = '\0';
1790 static void o_addblock(o_string *o, const char *str, int len)
1793 memcpy(&o->data[o->length], str, len);
1795 o->data[o->length] = '\0';
1799 static void o_addstr(o_string *o, const char *str)
1801 o_addblock(o, str, strlen(str));
1803 static void nommu_addchr(o_string *o, int ch)
1809 # define nommu_addchr(o, str) ((void)0)
1812 static void o_addstr_with_NUL(o_string *o, const char *str)
1814 o_addblock(o, str, strlen(str) + 1);
1817 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1822 && (*str != '*' && *str != '?' && *str != '[')
1830 /* My analysis of quoting semantics tells me that state information
1831 * is associated with a destination, not a source.
1833 static void o_addqchr(o_string *o, int ch)
1836 char *found = strchr("*?[\\", ch);
1841 o->data[o->length] = '\\';
1844 o->data[o->length] = ch;
1846 o->data[o->length] = '\0';
1849 static void o_addQchr(o_string *o, int ch)
1852 if (o->o_escape && strchr("*?[\\", ch)) {
1854 o->data[o->length] = '\\';
1858 o->data[o->length] = ch;
1860 o->data[o->length] = '\0';
1863 static void o_addQstr(o_string *o, const char *str, int len)
1866 o_addblock(o, str, len);
1872 int ordinary_cnt = strcspn(str, "*?[\\");
1873 if (ordinary_cnt > len) /* paranoia */
1875 o_addblock(o, str, ordinary_cnt);
1876 if (ordinary_cnt == len)
1878 str += ordinary_cnt;
1879 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1883 if (ch) { /* it is necessarily one of "*?[\\" */
1885 o->data[o->length] = '\\';
1889 o->data[o->length] = ch;
1891 o->data[o->length] = '\0';
1895 /* A special kind of o_string for $VAR and `cmd` expansion.
1896 * It contains char* list[] at the beginning, which is grown in 16 element
1897 * increments. Actual string data starts at the next multiple of 16 * (char*).
1898 * list[i] contains an INDEX (int!) into this string data.
1899 * It means that if list[] needs to grow, data needs to be moved higher up
1900 * but list[i]'s need not be modified.
1901 * NB: remembering how many list[i]'s you have there is crucial.
1902 * o_finalize_list() operation post-processes this structure - calculates
1903 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1905 #if DEBUG_EXPAND || DEBUG_GLOB
1906 static void debug_print_list(const char *prefix, o_string *o, int n)
1908 char **list = (char**)o->data;
1909 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1913 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1914 prefix, list, n, string_start, o->length, o->maxlen);
1917 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1918 o->data + (int)list[i] + string_start,
1919 o->data + (int)list[i] + string_start);
1923 const char *p = o->data + (int)list[n - 1] + string_start;
1925 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1929 # define debug_print_list(prefix, o, n) ((void)0)
1932 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1933 * in list[n] so that it points past last stored byte so far.
1934 * It returns n+1. */
1935 static int o_save_ptr_helper(o_string *o, int n)
1937 char **list = (char**)o->data;
1941 if (!o->has_empty_slot) {
1942 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1943 string_len = o->length - string_start;
1944 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1945 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1946 /* list[n] points to string_start, make space for 16 more pointers */
1947 o->maxlen += 0x10 * sizeof(list[0]);
1948 o->data = xrealloc(o->data, o->maxlen + 1);
1949 list = (char**)o->data;
1950 memmove(list + n + 0x10, list + n, string_len);
1951 o->length += 0x10 * sizeof(list[0]);
1953 debug_printf_list("list[%d]=%d string_start=%d\n",
1954 n, string_len, string_start);
1957 /* We have empty slot at list[n], reuse without growth */
1958 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1959 string_len = o->length - string_start;
1960 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1961 n, string_len, string_start);
1962 o->has_empty_slot = 0;
1964 list[n] = (char*)(ptrdiff_t)string_len;
1968 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1969 static int o_get_last_ptr(o_string *o, int n)
1971 char **list = (char**)o->data;
1972 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1974 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1977 /* o_glob performs globbing on last list[], saving each result
1978 * as a new list[]. */
1979 static int o_glob(o_string *o, int n)
1985 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1987 return o_save_ptr_helper(o, n);
1988 pattern = o->data + o_get_last_ptr(o, n);
1989 debug_printf_glob("glob pattern '%s'\n", pattern);
1990 if (!glob_needed(pattern)) {
1992 o->length = unbackslash(pattern) - o->data;
1993 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1994 return o_save_ptr_helper(o, n);
1997 memset(&globdata, 0, sizeof(globdata));
1998 gr = glob(pattern, 0, NULL, &globdata);
1999 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2000 if (gr == GLOB_NOSPACE)
2001 bb_error_msg_and_die("out of memory during glob");
2002 if (gr == GLOB_NOMATCH) {
2003 globfree(&globdata);
2006 if (gr != 0) { /* GLOB_ABORTED ? */
2007 /* TODO: testcase for bad glob pattern behavior */
2008 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2010 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2011 char **argv = globdata.gl_pathv;
2012 o->length = pattern - o->data; /* "forget" pattern */
2014 o_addstr_with_NUL(o, *argv);
2015 n = o_save_ptr_helper(o, n);
2021 globfree(&globdata);
2023 debug_print_list("o_glob returning", o, n);
2027 /* If o->o_glob == 1, glob the string so far remembered.
2028 * Otherwise, just finish current list[] and start new */
2029 static int o_save_ptr(o_string *o, int n)
2031 if (o->o_glob) { /* if globbing is requested */
2032 /* If o->has_empty_slot, list[n] was already globbed
2033 * (if it was requested back then when it was filled)
2034 * so don't do that again! */
2035 if (!o->has_empty_slot)
2036 return o_glob(o, n); /* o_save_ptr_helper is inside */
2038 return o_save_ptr_helper(o, n);
2041 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2042 static char **o_finalize_list(o_string *o, int n)
2047 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2049 debug_print_list("finalized", o, n);
2050 debug_printf_expand("finalized n:%d\n", n);
2051 list = (char**)o->data;
2052 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2056 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2062 /* Expansion can recurse */
2063 #if ENABLE_HUSH_TICK
2064 static int process_command_subs(o_string *dest, const char *s);
2066 static char *expand_string_to_string(const char *str);
2068 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2069 parse_stream_dquoted(dest, input, dquote_end)
2071 static int parse_stream_dquoted(o_string *as_string,
2073 struct in_str *input,
2076 /* expand_strvec_to_strvec() takes a list of strings, expands
2077 * all variable references within and returns a pointer to
2078 * a list of expanded strings, possibly with larger number
2079 * of strings. (Think VAR="a b"; echo $VAR).
2080 * This new list is allocated as a single malloc block.
2081 * NULL-terminated list of char* pointers is at the beginning of it,
2082 * followed by strings themself.
2083 * Caller can deallocate entire list by single free(list). */
2085 /* Store given string, finalizing the word and starting new one whenever
2086 * we encounter IFS char(s). This is used for expanding variable values.
2087 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2088 static int expand_on_ifs(o_string *output, int n, const char *str)
2091 int word_len = strcspn(str, G.ifs);
2093 if (output->o_escape || !output->o_glob)
2094 o_addQstr(output, str, word_len);
2095 else /* protect backslashes against globbing up :) */
2096 o_addblock_duplicate_backslash(output, str, word_len);
2099 if (!*str) /* EOL - do not finalize word */
2101 o_addchr(output, '\0');
2102 debug_print_list("expand_on_ifs", output, n);
2103 n = o_save_ptr(output, n);
2104 str += strspn(str, G.ifs); /* skip ifs chars */
2106 debug_print_list("expand_on_ifs[1]", output, n);
2110 /* Helper to expand $((...)) and heredoc body. These act as if
2111 * they are in double quotes, with the exception that they are not :).
2112 * Just the rules are similar: "expand only $var and `cmd`"
2114 * Returns malloced string.
2115 * As an optimization, we return NULL if expansion is not needed.
2117 static char *expand_pseudo_dquoted(const char *str)
2120 struct in_str input;
2121 o_string dest = NULL_O_STRING;
2123 if (strchr(str, '$') == NULL
2124 #if ENABLE_HUSH_TICK
2125 && strchr(str, '`') == NULL
2131 /* We need to expand. Example:
2132 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2134 setup_string_in_str(&input, str);
2135 parse_stream_dquoted(NULL, &dest, &input, EOF);
2136 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2137 exp_str = expand_string_to_string(dest.data);
2138 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2139 o_free_unsafe(&dest);
2143 /* Expand all variable references in given string, adding words to list[]
2144 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2145 * to be filled). This routine is extremely tricky: has to deal with
2146 * variables/parameters with whitespace, $* and $@, and constructs like
2147 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2148 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2150 /* or_mask is either 0 (normal case) or 0x80 -
2151 * expansion of right-hand side of assignment == 1-element expand.
2152 * It will also do no globbing, and thus we must not backslash-quote!
2159 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2160 debug_print_list("expand_vars_to_list", output, n);
2161 n = o_save_ptr(output, n);
2162 debug_print_list("expand_vars_to_list[0]", output, n);
2164 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2167 char *dyn_val = NULL;
2168 const char *val = NULL;
2169 #if ENABLE_HUSH_TICK
2170 o_string subst_result = NULL_O_STRING;
2172 #if ENABLE_SH_MATH_SUPPORT
2173 char arith_buf[sizeof(arith_t)*3 + 2];
2175 o_addblock(output, arg, p - arg);
2176 debug_print_list("expand_vars_to_list[1]", output, n);
2178 p = strchr(p, SPECIAL_VAR_SYMBOL);
2180 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2181 /* "$@" is special. Even if quoted, it can still
2182 * expand to nothing (not even an empty string) */
2183 if ((first_ch & 0x7f) != '@')
2184 ored_ch |= first_ch;
2186 switch (first_ch & 0x7f) {
2187 /* Highest bit in first_ch indicates that var is double-quoted */
2189 val = utoa(G.root_pid);
2191 case '!': /* bg pid */
2192 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2194 case '?': /* exitcode */
2195 val = utoa(G.last_exitcode);
2197 case '#': /* argc */
2198 if (arg[1] != SPECIAL_VAR_SYMBOL)
2199 /* actually, it's a ${#var} */
2201 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2206 if (!G.global_argv[i])
2208 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2209 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2210 smallint sv = output->o_escape;
2211 /* unquoted var's contents should be globbed, so don't escape */
2212 output->o_escape = 0;
2213 while (G.global_argv[i]) {
2214 n = expand_on_ifs(output, n, G.global_argv[i]);
2215 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2216 if (G.global_argv[i++][0] && G.global_argv[i]) {
2217 /* this argv[] is not empty and not last:
2218 * put terminating NUL, start new word */
2219 o_addchr(output, '\0');
2220 debug_print_list("expand_vars_to_list[2]", output, n);
2221 n = o_save_ptr(output, n);
2222 debug_print_list("expand_vars_to_list[3]", output, n);
2225 output->o_escape = sv;
2227 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2228 * and in this case should treat it like '$*' - see 'else...' below */
2229 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2231 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2232 if (++i >= G.global_argc)
2234 o_addchr(output, '\0');
2235 debug_print_list("expand_vars_to_list[4]", output, n);
2236 n = o_save_ptr(output, n);
2238 } else { /* quoted $*: add as one word */
2240 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2241 if (!G.global_argv[++i])
2244 o_addchr(output, G.ifs[0]);
2248 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2249 /* "Empty variable", used to make "" etc to not disappear */
2253 #if ENABLE_HUSH_TICK
2254 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2257 /* Can't just stuff it into output o_string,
2258 * expanded result may need to be globbed
2259 * and $IFS-splitted */
2260 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2261 process_command_subs(&subst_result, arg);
2262 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2263 val = subst_result.data;
2266 #if ENABLE_SH_MATH_SUPPORT
2267 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2268 arith_eval_hooks_t hooks;
2273 arg++; /* skip '+' */
2274 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2275 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2277 exp_str = expand_pseudo_dquoted(arg);
2278 hooks.lookupvar = get_local_var_value;
2279 hooks.setvar = arith_set_local_var;
2280 hooks.endofname = endofname;
2281 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2285 const char *msg = "error in arithmetic";
2288 msg = "exponent less than 0";
2291 msg = "divide by 0";
2294 msg = "expression recursion loop detected";
2299 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2300 sprintf(arith_buf, arith_t_fmt, res);
2305 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2307 bool exp_len = false;
2308 bool exp_null = false;
2310 char exp_save = exp_save; /* for compiler */
2311 char exp_op = exp_op; /* for compiler */
2312 char *exp_word = exp_word; /* for compiler */
2316 arg[0] = first_ch & 0x7f;
2318 /* prepare for expansions */
2319 if (var[0] == '#') {
2320 /* handle length expansion ${#var} */
2324 /* maybe handle parameter expansion */
2325 exp_off = strcspn(var, ":-=+?%#");
2329 exp_save = var[exp_off];
2330 exp_null = exp_save == ':';
2331 exp_word = var + exp_off;
2334 exp_op = *exp_word++;
2335 var[exp_off] = '\0';
2339 /* lookup the variable in question */
2340 if (isdigit(var[0])) {
2341 /* handle_dollar() should have vetted var for us */
2343 if (i < G.global_argc)
2344 val = G.global_argv[i];
2345 /* else val remains NULL: $N with too big N */
2347 val = get_local_var_value(var);
2349 /* handle any expansions */
2351 debug_printf_expand("expand: length of '%s' = ", val);
2352 val = utoa(val ? strlen(val) : 0);
2353 debug_printf_expand("%s\n", val);
2354 } else if (exp_off) {
2355 if (exp_op == '%' || exp_op == '#') {
2357 /* we need to do a pattern match */
2360 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2361 if (exp_op == *exp_word) /* ## or %% */
2363 val = dyn_val = xstrdup(val);
2364 loc = scan(dyn_val, exp_word, match_at_left);
2365 if (match_at_left) /* # or ## */
2367 else if (loc) /* % or %% and match was found */
2371 /* we need to do an expansion */
2372 int exp_test = (!val || (exp_null && !val[0]));
2374 exp_test = !exp_test;
2375 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2376 exp_null ? "true" : "false", exp_test);
2378 if (exp_op == '?') {
2379 //TODO: how interactive bash aborts expansion mid-command?
2380 /* ${var?[error_msg_if_unset]} */
2381 /* ${var:?[error_msg_if_unset_or_null]} */
2382 /* mimic bash message */
2383 die_if_script("%s: %s",
2385 exp_word[0] ? exp_word : "parameter null or not set"
2391 if (exp_op == '=') {
2392 /* ${var=[word]} or ${var:=[word]} */
2393 if (isdigit(var[0]) || var[0] == '#') {
2394 /* mimic bash message */
2395 die_if_script("$%s: cannot assign in this way", var);
2398 char *new_var = xasprintf("%s=%s", var, val);
2399 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2405 var[exp_off] = exp_save;
2409 #if ENABLE_HUSH_TICK
2412 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2413 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2415 /* unquoted var's contents should be globbed, so don't escape */
2416 smallint sv = output->o_escape;
2417 output->o_escape = 0;
2418 n = expand_on_ifs(output, n, val);
2420 output->o_escape = sv;
2422 } else { /* quoted $VAR, val will be appended below */
2423 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2426 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2429 o_addQstr(output, val, strlen(val));
2432 /* Do the check to avoid writing to a const string */
2433 if (*p != SPECIAL_VAR_SYMBOL)
2434 *p = SPECIAL_VAR_SYMBOL;
2436 #if ENABLE_HUSH_TICK
2437 o_free(&subst_result);
2440 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2443 debug_print_list("expand_vars_to_list[a]", output, n);
2444 /* this part is literal, and it was already pre-quoted
2445 * if needed (much earlier), do not use o_addQstr here! */
2446 o_addstr_with_NUL(output, arg);
2447 debug_print_list("expand_vars_to_list[b]", output, n);
2448 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2449 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2452 /* allow to reuse list[n] later without re-growth */
2453 output->has_empty_slot = 1;
2455 o_addchr(output, '\0');
2460 static char **expand_variables(char **argv, int or_mask)
2465 o_string output = NULL_O_STRING;
2467 if (or_mask & 0x100) {
2468 output.o_escape = 1; /* protect against globbing for "$var" */
2469 /* (unquoted $var will temporarily switch it off) */
2476 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2479 debug_print_list("expand_variables", &output, n);
2481 /* output.data (malloced in one block) gets returned in "list" */
2482 list = o_finalize_list(&output, n);
2483 debug_print_strings("expand_variables[1]", list);
2487 static char **expand_strvec_to_strvec(char **argv)
2489 return expand_variables(argv, 0x100);
2492 #if ENABLE_HUSH_BASH_COMPAT
2493 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2495 return expand_variables(argv, 0x80);
2499 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2500 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2505 o_string output = NULL_O_STRING;
2510 int is_var = is_well_formed_var_name(*v, '=');
2511 /* is_var * 0x80: singleword expansion for vars */
2512 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2514 /* Subtle! expand_vars_to_list did not glob last word yet.
2515 * It does this only when fed with further data.
2516 * Therefore we set globbing flags AFTER it, not before:
2519 /* if it is not recognizably abc=...; then: */
2520 output.o_escape = !is_var; /* protect against globbing for "$var" */
2521 /* (unquoted $var will temporarily switch it off) */
2522 output.o_glob = !is_var; /* and indeed do globbing */
2525 debug_print_list("expand_cond", &output, n);
2527 /* output.data (malloced in one block) gets returned in "list" */
2528 list = o_finalize_list(&output, n);
2529 debug_print_strings("expand_cond[1]", list);
2534 /* Used for expansion of right hand of assignments */
2535 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2537 static char *expand_string_to_string(const char *str)
2539 char *argv[2], **list;
2541 argv[0] = (char*)str;
2543 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2545 if (!list[0] || list[1])
2546 bb_error_msg_and_die("BUG in varexp2");
2547 /* actually, just move string 2*sizeof(char*) bytes back */
2548 overlapping_strcpy((char*)list, list[0]);
2549 unbackslash((char*)list);
2550 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2554 /* Used for "eval" builtin */
2555 static char* expand_strvec_to_string(char **argv)
2559 list = expand_variables(argv, 0x80);
2560 /* Convert all NULs to spaces */
2565 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2566 bb_error_msg_and_die("BUG in varexp3");
2567 /* bash uses ' ' regardless of $IFS contents */
2572 overlapping_strcpy((char*)list, list[0]);
2573 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2577 static char **expand_assignments(char **argv, int count)
2581 /* Expand assignments into one string each */
2582 for (i = 0; i < count; i++) {
2583 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2591 void re_execute_shell(char ***to_free, const char *s,
2592 char *g_argv0, char **g_argv,
2593 char **builtin_argv) NORETURN;
2595 static void reset_traps_to_defaults(void)
2597 /* This function is always called in a child shell
2598 * after fork (not vfork, NOMMU doesn't use this function).
2599 * Child shells are not interactive.
2600 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2601 * Testcase: (while :; do :; done) + ^Z should background.
2602 * Same goes for SIGTERM, SIGHUP, SIGINT.
2607 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2610 /* Stupid. It can be done with *single* &= op, but we can't use
2611 * the fact that G.blocked_set is implemented as a bitmask... */
2612 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2616 sigdelset(&G.blocked_set, sig);
2623 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2624 mask = G.non_DFL_mask;
2625 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2629 G.traps[sig] = NULL;
2630 /* There is no signal for 0 (EXIT) */
2633 /* There was a trap handler, we are removing it.
2634 * But if sig still has non-DFL handling,
2635 * we should not unblock it. */
2638 sigdelset(&G.blocked_set, sig);
2640 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2645 static void re_execute_shell(char ***to_free, const char *s,
2646 char *g_argv0, char **g_argv,
2647 char **builtin_argv) NORETURN;
2648 static void re_execute_shell(char ***to_free, const char *s,
2649 char *g_argv0, char **g_argv,
2650 char **builtin_argv)
2652 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2653 char *heredoc_argv[4];
2654 struct variable *cur;
2655 #if ENABLE_HUSH_FUNCTIONS
2656 struct function *funcp;
2661 if (!g_argv0) { /* heredoc */
2662 argv = heredoc_argv;
2663 argv[0] = (char *) G.argv0_for_re_execing;
2664 argv[1] = (char *) "-<";
2665 argv[2] = (char *) s;
2667 pp = &argv[3]; /* used as pointer to empty environment */
2673 if (pp) while (*pp++)
2676 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2677 , (unsigned) G.root_pid
2678 , (unsigned) G.last_bg_pid
2679 , (unsigned) G.last_exitcode
2681 IF_HUSH_LOOPS(, G.depth_of_loop)
2683 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2684 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2687 for (cur = G.top_var; cur; cur = cur->next) {
2688 if (!cur->flg_export || cur->flg_read_only)
2691 #if ENABLE_HUSH_FUNCTIONS
2692 for (funcp = G.top_func; funcp; funcp = funcp->next)
2698 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2699 *pp++ = (char *) G.argv0_for_re_execing;
2701 for (cur = G.top_var; cur; cur = cur->next) {
2702 if (cur->varstr == hush_version_str)
2704 if (cur->flg_read_only) {
2705 *pp++ = (char *) "-R";
2706 *pp++ = cur->varstr;
2707 } else if (!cur->flg_export) {
2708 *pp++ = (char *) "-V";
2709 *pp++ = cur->varstr;
2712 #if ENABLE_HUSH_FUNCTIONS
2713 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2714 *pp++ = (char *) "-F";
2715 *pp++ = funcp->name;
2716 *pp++ = funcp->body_as_string;
2719 /* We can pass activated traps here. Say, -Tnn:trap_string
2721 * However, POSIX says that subshells reset signals with traps
2723 * I tested bash-3.2 and it not only does that with true subshells
2724 * of the form ( list ), but with any forked children shells.
2725 * I set trap "echo W" WINCH; and then tried:
2727 * { echo 1; sleep 20; echo 2; } &
2728 * while true; do echo 1; sleep 20; echo 2; break; done &
2729 * true | { echo 1; sleep 20; echo 2; } | cat
2731 * In all these cases sending SIGWINCH to the child shell
2732 * did not run the trap. If I add trap "echo V" WINCH;
2733 * _inside_ group (just before echo 1), it works.
2735 * I conclude it means we don't need to pass active traps here.
2736 * exec syscall below resets them to SIG_DFL for us.
2738 *pp++ = (char *) "-c";
2741 while (*++builtin_argv)
2742 *pp++ = *builtin_argv;
2743 *pp++ = (char *) "";
2748 /* *pp = NULL; - is already there */
2752 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2753 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2754 execve(bb_busybox_exec_path, argv, pp);
2755 /* Fallback. Useful for init=/bin/hush usage etc */
2756 if (argv[0][0] == '/')
2757 execve(argv[0], argv, pp);
2758 xfunc_error_retval = 127;
2759 bb_error_msg_and_die("can't re-execute the shell");
2761 #endif /* !BB_MMU */
2764 static void setup_heredoc(struct redir_struct *redir)
2766 struct fd_pair pair;
2769 /* the _body_ of heredoc (misleading field name) */
2770 const char *heredoc = redir->rd_filename;
2777 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2778 expanded = expand_pseudo_dquoted(heredoc);
2782 len = strlen(heredoc);
2784 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2786 xmove_fd(pair.rd, redir->rd_fd);
2788 /* Try writing without forking. Newer kernels have
2789 * dynamically growing pipes. Must use non-blocking write! */
2792 written = write(pair.wr, heredoc, len);
2803 ndelay_off(pair.wr);
2805 /* Okay, pipe buffer was not big enough */
2806 /* Note: we must not create a stray child (bastard? :)
2807 * for the unsuspecting parent process. Child creates a grandchild
2808 * and exits before parent execs the process which consumes heredoc
2809 * (that exec happens after we return from this function) */
2815 bb_perror_msg_and_die("vfork");
2818 disable_restore_tty_pgrp_on_exit();
2819 pid = BB_MMU ? fork() : vfork();
2821 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2825 close(redir->rd_fd); /* read side of the pipe */
2827 full_write(pair.wr, heredoc, len); /* may loop or block */
2830 /* Delegate blocking writes to another process */
2831 xmove_fd(pair.wr, STDOUT_FILENO);
2832 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2836 #if ENABLE_HUSH_FAST
2838 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2840 enable_restore_tty_pgrp_on_exit();
2846 wait(NULL); /* wait till child has died */
2849 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2850 * and stderr if they are redirected. */
2851 static int setup_redirects(struct command *prog, int squirrel[])
2854 struct redir_struct *redir;
2856 for (redir = prog->redirects; redir; redir = redir->next) {
2857 if (redir->rd_type == REDIRECT_HEREDOC2) {
2858 /* rd_fd<<HERE case */
2859 if (squirrel && redir->rd_fd < 3
2860 && squirrel[redir->rd_fd] < 0
2862 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2864 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2866 debug_printf_parse("set heredoc '%s'\n",
2867 redir->rd_filename);
2868 setup_heredoc(redir);
2872 if (redir->rd_dup == REDIRFD_TO_FILE) {
2873 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2875 if (redir->rd_filename == NULL) {
2876 /* Something went wrong in the parse.
2877 * Pretend it didn't happen */
2878 bb_error_msg("bug in redirect parse");
2881 mode = redir_table[redir->rd_type].mode;
2882 p = expand_string_to_string(redir->rd_filename);
2883 openfd = open_or_warn(p, mode);
2886 /* this could get lost if stderr has been redirected, but
2887 * bash and ash both lose it as well (though zsh doesn't!) */
2888 //what the above comment tries to say?
2892 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2893 openfd = redir->rd_dup;
2896 if (openfd != redir->rd_fd) {
2897 if (squirrel && redir->rd_fd < 3
2898 && squirrel[redir->rd_fd] < 0
2900 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2902 if (openfd == REDIRFD_CLOSE) {
2903 /* "n>-" means "close me" */
2904 close(redir->rd_fd);
2906 xdup2(openfd, redir->rd_fd);
2907 if (redir->rd_dup == REDIRFD_TO_FILE)
2915 static void restore_redirects(int squirrel[])
2918 for (i = 0; i < 3; i++) {
2921 /* We simply die on error */
2928 static void free_pipe_list(struct pipe *head);
2930 /* Return code is the exit status of the pipe */
2931 static void free_pipe(struct pipe *pi)
2934 struct command *command;
2935 struct redir_struct *r, *rnext;
2938 if (pi->stopped_cmds > 0) /* why? */
2940 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2941 for (i = 0; i < pi->num_cmds; i++) {
2942 command = &pi->cmds[i];
2943 debug_printf_clean(" command %d:\n", i);
2944 if (command->argv) {
2945 for (a = 0, p = command->argv; *p; a++, p++) {
2946 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2948 free_strings(command->argv);
2949 command->argv = NULL;
2951 /* not "else if": on syntax error, we may have both! */
2952 if (command->group) {
2953 debug_printf_clean(" begin group (cmd_type:%d)\n",
2955 free_pipe_list(command->group);
2956 debug_printf_clean(" end group\n");
2957 command->group = NULL;
2959 /* else is crucial here.
2960 * If group != NULL, child_func is meaningless */
2961 #if ENABLE_HUSH_FUNCTIONS
2962 else if (command->child_func) {
2963 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2964 command->child_func->parent_cmd = NULL;
2968 free(command->group_as_string);
2969 command->group_as_string = NULL;
2971 for (r = command->redirects; r; r = rnext) {
2972 debug_printf_clean(" redirect %d%s",
2973 r->rd_fd, redir_table[r->rd_type].descrip);
2974 /* guard against the case >$FOO, where foo is unset or blank */
2975 if (r->rd_filename) {
2976 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2977 free(r->rd_filename);
2978 r->rd_filename = NULL;
2980 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2984 command->redirects = NULL;
2986 free(pi->cmds); /* children are an array, they get freed all at once */
2994 static void free_pipe_list(struct pipe *head)
2996 struct pipe *pi, *next;
2998 for (pi = head; pi; pi = next) {
3000 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3003 debug_printf_clean("pipe followup code %d\n", pi->followup);
3005 /*pi->next = NULL;*/
3011 static int run_list(struct pipe *pi);
3013 #define parse_stream(pstring, input, end_trigger) \
3014 parse_stream(input, end_trigger)
3016 static struct pipe *parse_stream(char **pstring,
3017 struct in_str *input,
3019 static void parse_and_run_string(const char *s);
3022 static char *find_in_path(const char *arg)
3025 const char *PATH = get_local_var_value("PATH");
3031 const char *end = strchrnul(PATH, ':');
3032 int sz = end - PATH; /* must be int! */
3036 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3038 /* We have xxx::yyyy in $PATH,
3039 * it means "use current dir" */
3042 if (access(ret, F_OK) == 0)
3055 static const struct built_in_command* find_builtin_helper(const char *name,
3056 const struct built_in_command *x,
3057 const struct built_in_command *end)
3060 if (strcmp(name, x->cmd) != 0) {
3064 debug_printf_exec("found builtin '%s'\n", name);
3069 static const struct built_in_command* find_builtin1(const char *name)
3071 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3073 static const struct built_in_command* find_builtin(const char *name)
3075 const struct built_in_command *x = find_builtin1(name);
3078 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3081 #if ENABLE_HUSH_FUNCTIONS
3082 static const struct function *find_function(const char *name)
3084 const struct function *funcp = G.top_func;
3086 if (strcmp(name, funcp->name) == 0) {
3089 funcp = funcp->next;
3092 debug_printf_exec("found function '%s'\n", name);
3096 /* Note: takes ownership on name ptr */
3097 static struct function *new_function(char *name)
3099 struct function *funcp;
3100 struct function **funcpp = &G.top_func;
3102 while ((funcp = *funcpp) != NULL) {
3103 struct command *cmd;
3105 if (strcmp(funcp->name, name) != 0) {
3106 funcpp = &funcp->next;
3110 cmd = funcp->parent_cmd;
3111 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3113 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3115 /* Note: if !funcp->body, do not free body_as_string!
3116 * This is a special case of "-F name body" function:
3117 * body_as_string was not malloced! */
3119 free_pipe_list(funcp->body);
3121 free(funcp->body_as_string);
3125 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3126 cmd->argv[0] = funcp->name;
3127 cmd->group = funcp->body;
3129 cmd->group_as_string = funcp->body_as_string;
3134 debug_printf_exec("remembering new function '%s'\n", name);
3135 funcp = *funcpp = xzalloc(sizeof(*funcp));
3136 /*funcp->next = NULL;*/
3142 static void unset_func(const char *name)
3144 struct function *funcp;
3145 struct function **funcpp = &G.top_func;
3147 while ((funcp = *funcpp) != NULL) {
3148 if (strcmp(funcp->name, name) == 0) {
3149 *funcpp = funcp->next;
3150 /* funcp is unlinked now, deleting it.
3151 * Note: if !funcp->body, the function was created by
3152 * "-F name body", do not free ->body_as_string
3153 * and ->name as they were not malloced. */
3155 free_pipe_list(funcp->body);
3158 free(funcp->body_as_string);
3164 funcpp = &funcp->next;
3169 #define exec_function(to_free, funcp, argv) \
3170 exec_function(funcp, argv)
3172 static void exec_function(char ***to_free,
3173 const struct function *funcp,
3174 char **argv) NORETURN;
3175 static void exec_function(char ***to_free,
3176 const struct function *funcp,
3182 argv[0] = G.global_argv[0];
3183 G.global_argv = argv;
3187 /* On MMU, funcp->body is always non-NULL */
3188 n = run_list(funcp->body);
3192 re_execute_shell(to_free,
3193 funcp->body_as_string,
3200 static int run_function(const struct function *funcp, char **argv)
3206 save_and_replace_G_args(&sv, argv);
3208 /* "we are in function, ok to use return" */
3209 sv_flg = G.flag_return_in_progress;
3210 G.flag_return_in_progress = -1;
3211 #if ENABLE_HUSH_LOCAL
3212 G.func_nest_level++;
3215 /* On MMU, funcp->body is always non-NULL */
3218 /* Function defined by -F */
3219 parse_and_run_string(funcp->body_as_string);
3220 rc = G.last_exitcode;
3224 rc = run_list(funcp->body);
3227 #if ENABLE_HUSH_LOCAL
3229 struct variable *var;
3230 struct variable **var_pp;
3232 var_pp = &G.top_var;
3233 while ((var = *var_pp) != NULL) {
3234 if (var->func_nest_level < G.func_nest_level) {
3235 var_pp = &var->next;
3239 if (var->flg_export)
3240 bb_unsetenv(var->varstr);
3241 /* Remove from global list */
3242 *var_pp = var->next;
3248 G.func_nest_level--;
3251 G.flag_return_in_progress = sv_flg;
3253 restore_G_args(&sv, argv);
3257 #endif /* ENABLE_HUSH_FUNCTIONS */
3261 #define exec_builtin(to_free, x, argv) \
3262 exec_builtin(x, argv)
3264 #define exec_builtin(to_free, x, argv) \
3265 exec_builtin(to_free, argv)
3267 static void exec_builtin(char ***to_free,
3268 const struct built_in_command *x,
3269 char **argv) NORETURN;
3270 static void exec_builtin(char ***to_free,
3271 const struct built_in_command *x,
3275 int rcode = x->function(argv);
3279 /* On NOMMU, we must never block!
3280 * Example: { sleep 99 | read line; } & echo Ok
3282 re_execute_shell(to_free,
3292 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3293 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3294 #define pseudo_exec(nommu_save, command, argv_expanded) \
3295 pseudo_exec(command, argv_expanded)
3298 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3300 * Don't exit() here. If you don't exec, use _exit instead.
3301 * The at_exit handlers apparently confuse the calling process,
3302 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3303 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3304 char **argv, int assignment_cnt,
3305 char **argv_expanded) NORETURN;
3306 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3307 char **argv, int assignment_cnt,
3308 char **argv_expanded)
3312 /* Case when we are here: ... | var=val | ... */
3313 if (!argv[assignment_cnt])
3314 _exit(EXIT_SUCCESS);
3316 new_env = expand_assignments(argv, assignment_cnt);
3318 set_vars_and_save_old(new_env);
3319 free(new_env); /* optional */
3320 /* we can also destroy set_vars_and_save_old's return value,
3323 nommu_save->new_env = new_env;
3324 nommu_save->old_vars = set_vars_and_save_old(new_env);
3326 if (argv_expanded) {
3327 argv = argv_expanded;
3329 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3331 nommu_save->argv = argv;
3335 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3336 if (strchr(argv[0], '/') != NULL)
3340 /* Check if the command matches any of the builtins.
3341 * Depending on context, this might be redundant. But it's
3342 * easier to waste a few CPU cycles than it is to figure out
3343 * if this is one of those cases.
3346 /* On NOMMU, it is more expensive to re-execute shell
3347 * just in order to run echo or test builtin.
3348 * It's better to skip it here and run corresponding
3349 * non-builtin later. */
3350 const struct built_in_command *x;
3351 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3353 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3356 #if ENABLE_HUSH_FUNCTIONS
3357 /* Check if the command matches any functions */
3359 const struct function *funcp = find_function(argv[0]);
3361 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3366 #if ENABLE_FEATURE_SH_STANDALONE
3367 /* Check if the command matches any busybox applets */
3369 int a = find_applet_by_name(argv[0]);
3371 # if BB_MMU /* see above why on NOMMU it is not allowed */
3372 if (APPLET_IS_NOEXEC(a)) {
3373 debug_printf_exec("running applet '%s'\n", argv[0]);
3374 run_applet_no_and_exit(a, argv);
3377 /* Re-exec ourselves */
3378 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3379 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3380 execv(bb_busybox_exec_path, argv);
3381 /* If they called chroot or otherwise made the binary no longer
3382 * executable, fall through */
3387 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3390 debug_printf_exec("execing '%s'\n", argv[0]);
3391 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3392 execvp(argv[0], argv);
3393 bb_perror_msg("can't execute '%s'", argv[0]);
3394 _exit(EXIT_FAILURE);
3397 /* Called after [v]fork() in run_pipe
3399 static void pseudo_exec(nommu_save_t *nommu_save,
3400 struct command *command,
3401 char **argv_expanded) NORETURN;
3402 static void pseudo_exec(nommu_save_t *nommu_save,
3403 struct command *command,
3404 char **argv_expanded)
3406 if (command->argv) {
3407 pseudo_exec_argv(nommu_save, command->argv,
3408 command->assignment_cnt, argv_expanded);
3411 if (command->group) {
3412 /* Cases when we are here:
3415 * ... | ( list ) | ...
3416 * ... | { list } | ...
3420 debug_printf_exec("pseudo_exec: run_list\n");
3421 reset_traps_to_defaults();
3422 rcode = run_list(command->group);
3423 /* OK to leak memory by not calling free_pipe_list,
3424 * since this process is about to exit */
3427 re_execute_shell(&nommu_save->argv_from_re_execing,
3428 command->group_as_string,
3435 /* Case when we are here: ... | >file */
3436 debug_printf_exec("pseudo_exec'ed null command\n");
3437 _exit(EXIT_SUCCESS);
3441 static const char *get_cmdtext(struct pipe *pi)
3447 /* This is subtle. ->cmdtext is created only on first backgrounding.
3448 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3449 * On subsequent bg argv is trashed, but we won't use it */
3452 argv = pi->cmds[0].argv;
3453 if (!argv || !argv[0]) {
3454 pi->cmdtext = xzalloc(1);
3460 len += strlen(*argv) + 1;
3464 argv = pi->cmds[0].argv;
3466 len = strlen(*argv);
3467 memcpy(p, *argv, len);
3475 static void insert_bg_job(struct pipe *pi)
3477 struct pipe *job, **jobp;
3480 /* Linear search for the ID of the job to use */
3482 for (job = G.job_list; job; job = job->next)
3483 if (job->jobid >= pi->jobid)
3484 pi->jobid = job->jobid + 1;
3486 /* Add job to the list of running jobs */
3488 while ((job = *jobp) != NULL)
3490 job = *jobp = xmalloc(sizeof(*job));
3492 *job = *pi; /* physical copy */
3494 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3495 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3496 for (i = 0; i < pi->num_cmds; i++) {
3497 job->cmds[i].pid = pi->cmds[i].pid;
3498 /* all other fields are not used and stay zero */
3500 job->cmdtext = xstrdup(get_cmdtext(pi));
3502 if (G_interactive_fd)
3503 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3504 /* Last command's pid goes to $! */
3505 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3506 G.last_jobid = job->jobid;
3509 static void remove_bg_job(struct pipe *pi)
3511 struct pipe *prev_pipe;
3513 if (pi == G.job_list) {
3514 G.job_list = pi->next;
3516 prev_pipe = G.job_list;
3517 while (prev_pipe->next != pi)
3518 prev_pipe = prev_pipe->next;
3519 prev_pipe->next = pi->next;
3522 G.last_jobid = G.job_list->jobid;
3527 /* Remove a backgrounded job */
3528 static void delete_finished_bg_job(struct pipe *pi)
3531 pi->stopped_cmds = 0;
3537 /* Check to see if any processes have exited -- if they
3538 * have, figure out why and see if a job has completed */
3539 static int checkjobs(struct pipe* fg_pipe)
3549 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3551 attributes = WUNTRACED;
3552 if (fg_pipe == NULL)
3553 attributes |= WNOHANG;
3556 #if ENABLE_HUSH_FAST
3557 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3558 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3559 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3560 /* There was neither fork nor SIGCHLD since last waitpid */
3561 /* Avoid doing waitpid syscall if possible */
3562 if (!G.we_have_children) {
3566 if (fg_pipe == NULL) { /* is WNOHANG set? */
3567 /* We have children, but they did not exit
3568 * or stop yet (we saw no SIGCHLD) */
3571 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3575 /* Do we do this right?
3576 * bash-3.00# sleep 20 | false
3578 * [3]+ Stopped sleep 20 | false
3579 * bash-3.00# echo $?
3580 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3581 * [hush 1.14.0: yes we do it right]
3588 #if ENABLE_HUSH_FAST
3589 i = G.count_SIGCHLD;
3591 childpid = waitpid(-1, &status, attributes);
3592 if (childpid <= 0) {
3593 if (childpid && errno != ECHILD)
3594 bb_perror_msg("waitpid");
3595 #if ENABLE_HUSH_FAST
3596 else { /* Until next SIGCHLD, waitpid's are useless */
3597 G.we_have_children = (childpid == 0);
3598 G.handled_SIGCHLD = i;
3599 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3604 dead = WIFEXITED(status) || WIFSIGNALED(status);
3607 if (WIFSTOPPED(status))
3608 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3609 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3610 if (WIFSIGNALED(status))
3611 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3612 childpid, WTERMSIG(status), WEXITSTATUS(status));
3613 if (WIFEXITED(status))
3614 debug_printf_jobs("pid %d exited, exitcode %d\n",
3615 childpid, WEXITSTATUS(status));
3617 /* Were we asked to wait for fg pipe? */
3619 for (i = 0; i < fg_pipe->num_cmds; i++) {
3620 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3621 if (fg_pipe->cmds[i].pid != childpid)
3624 fg_pipe->cmds[i].pid = 0;
3625 fg_pipe->alive_cmds--;
3626 if (i == fg_pipe->num_cmds - 1) {
3627 /* last process gives overall exitstatus */
3628 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3629 rcode = WEXITSTATUS(status);
3630 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3631 /* bash prints killing signal's name for *last*
3632 * process in pipe (prints just newline for SIGINT).
3633 * Mimic this. Example: "sleep 5" + ^\
3635 if (WIFSIGNALED(status)) {
3636 int sig = WTERMSIG(status);
3637 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3641 fg_pipe->cmds[i].is_stopped = 1;
3642 fg_pipe->stopped_cmds++;
3644 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3645 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3646 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3647 /* All processes in fg pipe have exited or stopped */
3648 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3649 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3650 * and "killall -STOP cat" */
3651 if (G_interactive_fd) {
3653 if (fg_pipe->alive_cmds)
3654 insert_bg_job(fg_pipe);
3658 if (!fg_pipe->alive_cmds)
3661 /* There are still running processes in the fg pipe */
3662 goto wait_more; /* do waitpid again */
3664 /* it wasnt fg_pipe, look for process in bg pipes */
3668 /* We asked to wait for bg or orphaned children */
3669 /* No need to remember exitcode in this case */
3670 for (pi = G.job_list; pi; pi = pi->next) {
3671 for (i = 0; i < pi->num_cmds; i++) {
3672 if (pi->cmds[i].pid == childpid)
3673 goto found_pi_and_prognum;
3676 /* Happens when shell is used as init process (init=/bin/sh) */
3677 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3678 continue; /* do waitpid again */
3680 found_pi_and_prognum:
3683 pi->cmds[i].pid = 0;
3685 if (!pi->alive_cmds) {
3686 if (G_interactive_fd)
3687 printf(JOB_STATUS_FORMAT, pi->jobid,
3688 "Done", pi->cmdtext);
3689 delete_finished_bg_job(pi);
3693 pi->cmds[i].is_stopped = 1;
3697 } /* while (waitpid succeeds)... */
3703 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3706 int rcode = checkjobs(fg_pipe);
3707 if (G_saved_tty_pgrp) {
3708 /* Job finished, move the shell to the foreground */
3709 p = getpgrp(); /* our process group id */
3710 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3711 tcsetpgrp(G_interactive_fd, p);
3717 /* Start all the jobs, but don't wait for anything to finish.
3720 * Return code is normally -1, when the caller has to wait for children
3721 * to finish to determine the exit status of the pipe. If the pipe
3722 * is a simple builtin command, however, the action is done by the
3723 * time run_pipe returns, and the exit code is provided as the
3726 * Returns -1 only if started some children. IOW: we have to
3727 * mask out retvals of builtins etc with 0xff!
3729 * The only case when we do not need to [v]fork is when the pipe
3730 * is single, non-backgrounded, non-subshell command. Examples:
3731 * cmd ; ... { list } ; ...
3732 * cmd && ... { list } && ...
3733 * cmd || ... { list } || ...
3734 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3735 * or (if SH_STANDALONE) an applet, and we can run the { list }
3736 * with run_list. If it isn't one of these, we fork and exec cmd.
3738 * Cases when we must fork:
3739 * non-single: cmd | cmd
3740 * backgrounded: cmd & { list } &
3741 * subshell: ( list ) [&]
3743 static int run_pipe(struct pipe *pi)
3745 static const char *const null_ptr = NULL;
3748 struct command *command;
3749 char **argv_expanded;
3752 /* it is not always needed, but we aim to smaller code */
3753 int squirrel[] = { -1, -1, -1 };
3756 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3759 IF_HUSH_JOB(pi->pgrp = -1;)
3760 pi->stopped_cmds = 0;
3761 command = &(pi->cmds[0]);
3762 argv_expanded = NULL;
3764 if (pi->num_cmds != 1
3765 || pi->followup == PIPE_BG
3766 || command->cmd_type == CMD_SUBSHELL
3773 debug_printf_exec(": group:%p argv:'%s'\n",
3774 command->group, command->argv ? command->argv[0] : "NONE");
3776 if (command->group) {
3777 #if ENABLE_HUSH_FUNCTIONS
3778 if (command->cmd_type == CMD_FUNCDEF) {
3779 /* "executing" func () { list } */
3780 struct function *funcp;
3782 funcp = new_function(command->argv[0]);
3783 /* funcp->name is already set to argv[0] */
3784 funcp->body = command->group;
3786 funcp->body_as_string = command->group_as_string;
3787 command->group_as_string = NULL;
3789 command->group = NULL;
3790 command->argv[0] = NULL;
3791 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3792 funcp->parent_cmd = command;
3793 command->child_func = funcp;
3795 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3797 return EXIT_SUCCESS;
3801 debug_printf("non-subshell group\n");
3802 rcode = 1; /* exitcode if redir failed */
3803 if (setup_redirects(command, squirrel) == 0) {
3804 debug_printf_exec(": run_list\n");
3805 rcode = run_list(command->group) & 0xff;
3807 restore_redirects(squirrel);
3808 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3810 debug_printf_exec("run_pipe: return %d\n", rcode);
3814 argv = command->argv ? command->argv : (char **) &null_ptr;
3816 const struct built_in_command *x;
3817 #if ENABLE_HUSH_FUNCTIONS
3818 const struct function *funcp;
3822 char **new_env = NULL;
3823 struct variable *old_vars = NULL;
3825 if (argv[command->assignment_cnt] == NULL) {
3826 /* Assignments, but no command */
3827 /* Ensure redirects take effect. Try "a=t >file" */
3828 rcode = setup_redirects(command, squirrel);
3829 restore_redirects(squirrel);
3830 /* Set shell variables */
3832 p = expand_string_to_string(*argv);
3833 debug_printf_exec("set shell var:'%s'->'%s'\n",
3835 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3838 /* Do we need to flag set_local_var() errors?
3839 * "assignment to readonly var" and "putenv error"
3841 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3843 debug_printf_exec("run_pipe: return %d\n", rcode);
3847 /* Expand the rest into (possibly) many strings each */
3849 #if ENABLE_HUSH_BASH_COMPAT
3850 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3851 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3854 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3855 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3856 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3861 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3864 x = find_builtin(argv_expanded[0]);
3865 #if ENABLE_HUSH_FUNCTIONS
3868 funcp = find_function(argv_expanded[0]);
3872 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3873 debug_printf("exec with redirects only\n");
3874 rcode = setup_redirects(command, NULL);
3875 goto clean_up_and_ret1;
3878 /* setup_redirects acts on file descriptors, not FILEs.
3879 * This is perfect for work that comes after exec().
3880 * Is it really safe for inline use? Experimentally,
3881 * things seem to work. */
3882 rcode = setup_redirects(command, squirrel);
3884 new_env = expand_assignments(argv, command->assignment_cnt);
3885 old_vars = set_vars_and_save_old(new_env);
3887 debug_printf_exec(": builtin '%s' '%s'...\n",
3888 x->cmd, argv_expanded[1]);
3889 rcode = x->function(argv_expanded) & 0xff;
3892 #if ENABLE_HUSH_FUNCTIONS
3894 # if ENABLE_HUSH_LOCAL
3895 struct variable **sv;
3896 sv = G.shadowed_vars_pp;
3897 G.shadowed_vars_pp = &old_vars;
3899 debug_printf_exec(": function '%s' '%s'...\n",
3900 funcp->name, argv_expanded[1]);
3901 rcode = run_function(funcp, argv_expanded) & 0xff;
3902 # if ENABLE_HUSH_LOCAL
3903 G.shadowed_vars_pp = sv;
3908 #if ENABLE_FEATURE_SH_STANDALONE
3911 restore_redirects(squirrel);
3912 unset_vars(new_env);
3915 free(argv_expanded);
3916 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3918 debug_printf_exec("run_pipe return %d\n", rcode);
3922 #if ENABLE_FEATURE_SH_STANDALONE
3923 i = find_applet_by_name(argv_expanded[0]);
3924 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3925 rcode = setup_redirects(command, squirrel);
3927 new_env = expand_assignments(argv, command->assignment_cnt);
3928 old_vars = set_vars_and_save_old(new_env);
3929 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3930 argv_expanded[0], argv_expanded[1]);
3931 rcode = run_nofork_applet(i, argv_expanded);
3933 goto clean_up_and_ret;
3936 /* It is neither builtin nor applet. We must fork. */
3940 /* NB: argv_expanded may already be created, and that
3941 * might include `cmd` runs! Do not rerun it! We *must*
3942 * use argv_expanded if it's non-NULL */
3944 /* Going to fork a child per each pipe member */
3948 for (i = 0; i < pi->num_cmds; i++) {
3949 struct fd_pair pipefds;
3951 volatile nommu_save_t nommu_save;
3952 nommu_save.new_env = NULL;
3953 nommu_save.old_vars = NULL;
3954 nommu_save.argv = NULL;
3955 nommu_save.argv_from_re_execing = NULL;
3957 command = &(pi->cmds[i]);
3958 if (command->argv) {
3959 debug_printf_exec(": pipe member '%s' '%s'...\n",
3960 command->argv[0], command->argv[1]);
3962 debug_printf_exec(": pipe member with no argv\n");
3965 /* pipes are inserted between pairs of commands */
3968 if ((i + 1) < pi->num_cmds)
3969 xpiped_pair(pipefds);
3971 command->pid = BB_MMU ? fork() : vfork();
3972 if (!command->pid) { /* child */
3974 disable_restore_tty_pgrp_on_exit();
3976 /* Every child adds itself to new process group
3977 * with pgid == pid_of_first_child_in_pipe */
3978 if (G.run_list_level == 1 && G_interactive_fd) {
3981 if (pgrp < 0) /* true for 1st process only */
3983 if (setpgid(0, pgrp) == 0
3984 && pi->followup != PIPE_BG
3985 && G_saved_tty_pgrp /* we have ctty */
3987 /* We do it in *every* child, not just first,
3989 tcsetpgrp(G_interactive_fd, pgrp);
3993 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3994 /* 1st cmd in backgrounded pipe
3995 * should have its stdin /dev/null'ed */
3997 if (open(bb_dev_null, O_RDONLY))
3998 xopen("/", O_RDONLY);
4000 xmove_fd(nextin, 0);
4002 xmove_fd(pipefds.wr, 1);
4005 /* Like bash, explicit redirects override pipes,
4006 * and the pipe fd is available for dup'ing. */
4007 if (setup_redirects(command, NULL))
4010 /* Restore default handlers just prior to exec */
4011 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4013 /* Stores to nommu_save list of env vars putenv'ed
4014 * (NOMMU, on MMU we don't need that) */
4015 /* cast away volatility... */
4016 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4017 /* pseudo_exec() does not return */
4020 /* parent or error */
4021 #if ENABLE_HUSH_FAST
4023 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4025 enable_restore_tty_pgrp_on_exit();
4027 /* Clean up after vforked child */
4028 free(nommu_save.argv);
4029 free(nommu_save.argv_from_re_execing);
4030 unset_vars(nommu_save.new_env);
4031 add_vars(nommu_save.old_vars);
4033 free(argv_expanded);
4034 argv_expanded = NULL;
4035 if (command->pid < 0) { /* [v]fork failed */
4036 /* Clearly indicate, was it fork or vfork */
4037 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4041 /* Second and next children need to know pid of first one */
4043 pi->pgrp = command->pid;
4049 if ((i + 1) < pi->num_cmds)
4051 /* Pass read (output) pipe end to next iteration */
4052 nextin = pipefds.rd;
4055 if (!pi->alive_cmds) {
4057 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4062 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4066 #ifndef debug_print_tree
4067 static void debug_print_tree(struct pipe *pi, int lvl)
4069 static const char *const PIPE[] = {
4075 static const char *RES[] = {
4076 [RES_NONE ] = "NONE" ,
4079 [RES_THEN ] = "THEN" ,
4080 [RES_ELIF ] = "ELIF" ,
4081 [RES_ELSE ] = "ELSE" ,
4084 #if ENABLE_HUSH_LOOPS
4085 [RES_FOR ] = "FOR" ,
4086 [RES_WHILE] = "WHILE",
4087 [RES_UNTIL] = "UNTIL",
4089 [RES_DONE ] = "DONE" ,
4091 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4094 #if ENABLE_HUSH_CASE
4095 [RES_CASE ] = "CASE" ,
4096 [RES_CASE_IN ] = "CASE_IN" ,
4097 [RES_MATCH] = "MATCH",
4098 [RES_CASE_BODY] = "CASE_BODY",
4099 [RES_ESAC ] = "ESAC" ,
4101 [RES_XXXX ] = "XXXX" ,
4102 [RES_SNTX ] = "SNTX" ,
4104 static const char *const CMDTYPE[] = {
4108 #if ENABLE_HUSH_FUNCTIONS
4117 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4118 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4120 while (prn < pi->num_cmds) {
4121 struct command *command = &pi->cmds[prn];
4122 char **argv = command->argv;
4124 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4126 command->assignment_cnt);
4127 if (command->group) {
4128 fprintf(stderr, " group %s: (argv=%p)\n",
4129 CMDTYPE[command->cmd_type],
4131 debug_print_tree(command->group, lvl+1);
4135 if (argv) while (*argv) {
4136 fprintf(stderr, " '%s'", *argv);
4139 fprintf(stderr, "\n");
4148 /* NB: called by pseudo_exec, and therefore must not modify any
4149 * global data until exec/_exit (we can be a child after vfork!) */
4150 static int run_list(struct pipe *pi)
4152 #if ENABLE_HUSH_CASE
4153 char *case_word = NULL;
4155 #if ENABLE_HUSH_LOOPS
4156 struct pipe *loop_top = NULL;
4157 char **for_lcur = NULL;
4158 char **for_list = NULL;
4160 smallint last_followup;
4162 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4163 smalluint cond_code = 0;
4165 enum { cond_code = 0 };
4168 smallint rword; /* enum reserved_style */
4169 smallint last_rword; /* ditto */
4172 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4175 #if ENABLE_HUSH_LOOPS
4176 /* Check syntax for "for" */
4177 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4178 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4180 /* current word is FOR or IN (BOLD in comments below) */
4181 if (cpipe->next == NULL) {
4182 syntax_error("malformed for");
4184 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4187 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4188 if (cpipe->next->res_word == RES_DO)
4190 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4191 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4192 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4194 syntax_error("malformed for");
4196 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4202 /* Past this point, all code paths should jump to ret: label
4203 * in order to return, no direct "return" statements please.
4204 * This helps to ensure that no memory is leaked. */
4212 last_rword = RES_XXXX;
4214 last_followup = PIPE_SEQ;
4215 rcode = G.last_exitcode;
4217 /* Go through list of pipes, (maybe) executing them. */
4218 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4222 IF_HAS_KEYWORDS(rword = pi->res_word;)
4223 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4224 rword, cond_code, last_rword);
4225 #if ENABLE_HUSH_LOOPS
4226 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4227 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4229 /* start of a loop: remember where loop starts */
4234 /* Still in the same "if...", "then..." or "do..." branch? */
4235 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4236 if ((rcode == 0 && last_followup == PIPE_OR)
4237 || (rcode != 0 && last_followup == PIPE_AND)
4239 /* It is "<true> || CMD" or "<false> && CMD"
4240 * and we should not execute CMD */
4241 debug_printf_exec("skipped cmd because of || or &&\n");
4242 last_followup = pi->followup;
4246 last_followup = pi->followup;
4247 IF_HAS_KEYWORDS(last_rword = rword;)
4250 if (rword == RES_THEN) {
4251 /* if false; then ... fi has exitcode 0! */
4252 G.last_exitcode = rcode = EXIT_SUCCESS;
4253 /* "if <false> THEN cmd": skip cmd */
4257 if (rword == RES_ELSE || rword == RES_ELIF) {
4258 /* "if <true> then ... ELSE/ELIF cmd":
4259 * skip cmd and all following ones */
4264 #if ENABLE_HUSH_LOOPS
4265 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4267 /* first loop through for */
4269 static const char encoded_dollar_at[] ALIGN1 = {
4270 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4271 }; /* encoded representation of "$@" */
4272 static const char *const encoded_dollar_at_argv[] = {
4273 encoded_dollar_at, NULL
4274 }; /* argv list with one element: "$@" */
4277 vals = (char**)encoded_dollar_at_argv;
4278 if (pi->next->res_word == RES_IN) {
4279 /* if no variable values after "in" we skip "for" */
4280 if (!pi->next->cmds[0].argv) {
4281 G.last_exitcode = rcode = EXIT_SUCCESS;
4282 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4285 vals = pi->next->cmds[0].argv;
4286 } /* else: "for var; do..." -> assume "$@" list */
4287 /* create list of variable values */
4288 debug_print_strings("for_list made from", vals);
4289 for_list = expand_strvec_to_strvec(vals);
4290 for_lcur = for_list;
4291 debug_print_strings("for_list", for_list);
4294 /* "for" loop is over, clean up */
4300 /* Insert next value from for_lcur */
4301 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4302 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4305 if (rword == RES_IN) {
4306 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4308 if (rword == RES_DONE) {
4309 continue; /* "done" has no cmds too */
4312 #if ENABLE_HUSH_CASE
4313 if (rword == RES_CASE) {
4314 case_word = expand_strvec_to_string(pi->cmds->argv);
4317 if (rword == RES_MATCH) {
4320 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4322 /* all prev words didn't match, does this one match? */
4323 argv = pi->cmds->argv;
4325 char *pattern = expand_string_to_string(*argv);
4326 /* TODO: which FNM_xxx flags to use? */
4327 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4329 if (cond_code == 0) { /* match! we will execute this branch */
4330 free(case_word); /* make future "word)" stop */
4338 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4340 continue; /* not matched yet, skip this pipe */
4343 /* Just pressing <enter> in shell should check for jobs.
4344 * OTOH, in non-interactive shell this is useless
4345 * and only leads to extra job checks */
4346 if (pi->num_cmds == 0) {
4347 if (G_interactive_fd)
4348 goto check_jobs_and_continue;
4352 /* After analyzing all keywords and conditions, we decided
4353 * to execute this pipe. NB: have to do checkjobs(NULL)
4354 * after run_pipe to collect any background children,
4355 * even if list execution is to be stopped. */
4356 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4359 #if ENABLE_HUSH_LOOPS
4360 G.flag_break_continue = 0;
4362 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4364 /* We ran a builtin, function, or group.
4365 * rcode is already known
4366 * and we don't need to wait for anything. */
4367 G.last_exitcode = rcode;
4368 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4369 check_and_run_traps(0);
4370 #if ENABLE_HUSH_LOOPS
4371 /* Was it "break" or "continue"? */
4372 if (G.flag_break_continue) {
4373 smallint fbc = G.flag_break_continue;
4374 /* We might fall into outer *loop*,
4375 * don't want to break it too */
4377 G.depth_break_continue--;
4378 if (G.depth_break_continue == 0)
4379 G.flag_break_continue = 0;
4380 /* else: e.g. "continue 2" should *break* once, *then* continue */
4381 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4382 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4383 goto check_jobs_and_break;
4384 /* "continue": simulate end of loop */
4389 #if ENABLE_HUSH_FUNCTIONS
4390 if (G.flag_return_in_progress == 1) {
4391 /* same as "goto check_jobs_and_break" */
4396 } else if (pi->followup == PIPE_BG) {
4397 /* What does bash do with attempts to background builtins? */
4398 /* even bash 3.2 doesn't do that well with nested bg:
4399 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4400 * I'm NOT treating inner &'s as jobs */
4401 check_and_run_traps(0);
4403 if (G.run_list_level == 1)
4406 G.last_exitcode = rcode = EXIT_SUCCESS;
4407 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4410 if (G.run_list_level == 1 && G_interactive_fd) {
4411 /* Waits for completion, then fg's main shell */
4412 rcode = checkjobs_and_fg_shell(pi);
4413 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4414 check_and_run_traps(0);
4417 { /* This one just waits for completion */
4418 rcode = checkjobs(pi);
4419 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4420 check_and_run_traps(0);
4422 G.last_exitcode = rcode;
4426 /* Analyze how result affects subsequent commands */
4428 if (rword == RES_IF || rword == RES_ELIF)
4431 #if ENABLE_HUSH_LOOPS
4432 /* Beware of "while false; true; do ..."! */
4433 if (pi->next && pi->next->res_word == RES_DO) {
4434 if (rword == RES_WHILE) {
4436 /* "while false; do...done" - exitcode 0 */
4437 G.last_exitcode = rcode = EXIT_SUCCESS;
4438 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4439 goto check_jobs_and_break;
4442 if (rword == RES_UNTIL) {
4444 debug_printf_exec(": until expr is true: breaking\n");
4445 check_jobs_and_break:
4453 check_jobs_and_continue:
4460 #if ENABLE_HUSH_LOOPS
4465 #if ENABLE_HUSH_CASE
4469 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4473 /* Select which version we will use */
4474 static int run_and_free_list(struct pipe *pi)
4477 debug_printf_exec("run_and_free_list entered\n");
4479 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4480 rcode = run_list(pi);
4482 /* free_pipe_list has the side effect of clearing memory.
4483 * In the long run that function can be merged with run_list,
4484 * but doing that now would hobble the debugging effort. */
4486 debug_printf_exec("run_and_free_list return %d\n", rcode);
4491 static struct pipe *new_pipe(void)
4494 pi = xzalloc(sizeof(struct pipe));
4495 /*pi->followup = 0; - deliberately invalid value */
4496 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4500 /* Command (member of a pipe) is complete, or we start a new pipe
4501 * if ctx->command is NULL.
4502 * No errors possible here.
4504 static int done_command(struct parse_context *ctx)
4506 /* The command is really already in the pipe structure, so
4507 * advance the pipe counter and make a new, null command. */
4508 struct pipe *pi = ctx->pipe;
4509 struct command *command = ctx->command;
4512 if (IS_NULL_CMD(command)) {
4513 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4517 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4518 //debug_print_tree(ctx->list_head, 20);
4520 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4523 /* Only real trickiness here is that the uncommitted
4524 * command structure is not counted in pi->num_cmds. */
4525 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4526 ctx->command = command = &pi->cmds[pi->num_cmds];
4528 memset(command, 0, sizeof(*command));
4529 return pi->num_cmds; /* used only for 0/nonzero check */
4532 static void done_pipe(struct parse_context *ctx, pipe_style type)
4536 debug_printf_parse("done_pipe entered, followup %d\n", type);
4537 /* Close previous command */
4538 not_null = done_command(ctx);
4539 ctx->pipe->followup = type;
4541 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4542 ctx->ctx_inverted = 0;
4543 ctx->pipe->res_word = ctx->ctx_res_w;
4546 /* Without this check, even just <enter> on command line generates
4547 * tree of three NOPs (!). Which is harmless but annoying.
4548 * IOW: it is safe to do it unconditionally. */
4551 || ctx->ctx_res_w == RES_FI
4553 #if ENABLE_HUSH_LOOPS
4554 || ctx->ctx_res_w == RES_DONE
4555 || ctx->ctx_res_w == RES_FOR
4556 || ctx->ctx_res_w == RES_IN
4558 #if ENABLE_HUSH_CASE
4559 || ctx->ctx_res_w == RES_ESAC
4563 debug_printf_parse("done_pipe: adding new pipe: "
4564 "not_null:%d ctx->ctx_res_w:%d\n",
4565 not_null, ctx->ctx_res_w);
4567 ctx->pipe->next = new_p;
4569 /* RES_THEN, RES_DO etc are "sticky" -
4570 * they remain set for pipes inside if/while.
4571 * This is used to control execution.
4572 * RES_FOR and RES_IN are NOT sticky (needed to support
4573 * cases where variable or value happens to match a keyword):
4575 #if ENABLE_HUSH_LOOPS
4576 if (ctx->ctx_res_w == RES_FOR
4577 || ctx->ctx_res_w == RES_IN)
4578 ctx->ctx_res_w = RES_NONE;
4580 #if ENABLE_HUSH_CASE
4581 if (ctx->ctx_res_w == RES_MATCH)
4582 ctx->ctx_res_w = RES_CASE_BODY;
4583 if (ctx->ctx_res_w == RES_CASE)
4584 ctx->ctx_res_w = RES_CASE_IN;
4586 ctx->command = NULL; /* trick done_command below */
4587 /* Create the memory for command, roughly:
4588 * ctx->pipe->cmds = new struct command;
4589 * ctx->command = &ctx->pipe->cmds[0];
4592 //debug_print_tree(ctx->list_head, 10);
4594 debug_printf_parse("done_pipe return\n");
4597 static void initialize_context(struct parse_context *ctx)
4599 memset(ctx, 0, sizeof(*ctx));
4600 ctx->pipe = ctx->list_head = new_pipe();
4601 /* Create the memory for command, roughly:
4602 * ctx->pipe->cmds = new struct command;
4603 * ctx->command = &ctx->pipe->cmds[0];
4608 /* If a reserved word is found and processed, parse context is modified
4609 * and 1 is returned.
4612 struct reserved_combo {
4615 unsigned char assignment_flag;
4619 FLAG_END = (1 << RES_NONE ),
4621 FLAG_IF = (1 << RES_IF ),
4622 FLAG_THEN = (1 << RES_THEN ),
4623 FLAG_ELIF = (1 << RES_ELIF ),
4624 FLAG_ELSE = (1 << RES_ELSE ),
4625 FLAG_FI = (1 << RES_FI ),
4627 #if ENABLE_HUSH_LOOPS
4628 FLAG_FOR = (1 << RES_FOR ),
4629 FLAG_WHILE = (1 << RES_WHILE),
4630 FLAG_UNTIL = (1 << RES_UNTIL),
4631 FLAG_DO = (1 << RES_DO ),
4632 FLAG_DONE = (1 << RES_DONE ),
4633 FLAG_IN = (1 << RES_IN ),
4635 #if ENABLE_HUSH_CASE
4636 FLAG_MATCH = (1 << RES_MATCH),
4637 FLAG_ESAC = (1 << RES_ESAC ),
4639 FLAG_START = (1 << RES_XXXX ),
4642 static const struct reserved_combo* match_reserved_word(o_string *word)
4644 /* Mostly a list of accepted follow-up reserved words.
4645 * FLAG_END means we are done with the sequence, and are ready
4646 * to turn the compound list into a command.
4647 * FLAG_START means the word must start a new compound list.
4649 static const struct reserved_combo reserved_list[] = {
4651 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4652 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4653 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4654 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4655 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4656 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4658 #if ENABLE_HUSH_LOOPS
4659 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4660 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4661 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4662 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4663 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4664 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4666 #if ENABLE_HUSH_CASE
4667 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4668 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4671 const struct reserved_combo *r;
4673 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4674 if (strcmp(word->data, r->literal) == 0)
4679 /* Return 0: not a keyword, 1: keyword
4681 static int reserved_word(o_string *word, struct parse_context *ctx)
4683 #if ENABLE_HUSH_CASE
4684 static const struct reserved_combo reserved_match = {
4685 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4688 const struct reserved_combo *r;
4692 r = match_reserved_word(word);
4696 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4697 #if ENABLE_HUSH_CASE
4698 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4699 /* "case word IN ..." - IN part starts first MATCH part */
4700 r = &reserved_match;
4703 if (r->flag == 0) { /* '!' */
4704 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4705 syntax_error("! ! command");
4706 ctx->ctx_res_w = RES_SNTX;
4708 ctx->ctx_inverted = 1;
4711 if (r->flag & FLAG_START) {
4712 struct parse_context *old;
4714 old = xmalloc(sizeof(*old));
4715 debug_printf_parse("push stack %p\n", old);
4716 *old = *ctx; /* physical copy */
4717 initialize_context(ctx);
4719 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4720 syntax_error_at(word->data);
4721 ctx->ctx_res_w = RES_SNTX;
4724 /* "{...} fi" is ok. "{...} if" is not
4726 * if { echo foo; } then { echo bar; } fi */
4727 if (ctx->command->group)
4728 done_pipe(ctx, PIPE_SEQ);
4731 ctx->ctx_res_w = r->res;
4732 ctx->old_flag = r->flag;
4733 word->o_assignment = r->assignment_flag;
4735 if (ctx->old_flag & FLAG_END) {
4736 struct parse_context *old;
4738 done_pipe(ctx, PIPE_SEQ);
4739 debug_printf_parse("pop stack %p\n", ctx->stack);
4741 old->command->group = ctx->list_head;
4742 old->command->cmd_type = CMD_NORMAL;
4744 o_addstr(&old->as_string, ctx->as_string.data);
4745 o_free_unsafe(&ctx->as_string);
4746 old->command->group_as_string = xstrdup(old->as_string.data);
4747 debug_printf_parse("pop, remembering as:'%s'\n",
4748 old->command->group_as_string);
4750 *ctx = *old; /* physical copy */
4757 /* Word is complete, look at it and update parsing context.
4758 * Normal return is 0. Syntax errors return 1.
4759 * Note: on return, word is reset, but not o_free'd!
4761 static int done_word(o_string *word, struct parse_context *ctx)
4763 struct command *command = ctx->command;
4765 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4766 if (word->length == 0 && word->o_quoted == 0) {
4767 debug_printf_parse("done_word return 0: true null, ignored\n");
4771 if (ctx->pending_redirect) {
4772 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4773 * only if run as "bash", not "sh" */
4774 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4776 * ...the word that follows the redirection operator
4777 * shall be subjected to tilde expansion, parameter expansion,
4778 * command substitution, arithmetic expansion, and quote
4779 * removal. Pathname expansion shall not be performed
4780 * on the word by a non-interactive shell; an interactive
4781 * shell may perform it, but shall do so only when
4782 * the expansion would result in one word."
4784 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4785 /* Cater for >\file case:
4786 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4787 * Same with heredocs:
4788 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4790 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4791 unbackslash(ctx->pending_redirect->rd_filename);
4792 /* Is it <<"HEREDOC"? */
4793 if (word->o_quoted) {
4794 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4797 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4798 ctx->pending_redirect = NULL;
4800 /* If this word wasn't an assignment, next ones definitely
4801 * can't be assignments. Even if they look like ones. */
4802 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4803 && word->o_assignment != WORD_IS_KEYWORD
4805 word->o_assignment = NOT_ASSIGNMENT;
4807 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4808 command->assignment_cnt++;
4809 word->o_assignment = MAYBE_ASSIGNMENT;
4813 # if ENABLE_HUSH_CASE
4814 if (ctx->ctx_dsemicolon
4815 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4817 /* already done when ctx_dsemicolon was set to 1: */
4818 /* ctx->ctx_res_w = RES_MATCH; */
4819 ctx->ctx_dsemicolon = 0;
4822 if (!command->argv /* if it's the first word... */
4823 # if ENABLE_HUSH_LOOPS
4824 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4825 && ctx->ctx_res_w != RES_IN
4827 # if ENABLE_HUSH_CASE
4828 && ctx->ctx_res_w != RES_CASE
4831 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4832 if (reserved_word(word, ctx)) {
4833 o_reset_to_empty_unquoted(word);
4834 debug_printf_parse("done_word return %d\n",
4835 (ctx->ctx_res_w == RES_SNTX));
4836 return (ctx->ctx_res_w == RES_SNTX);
4838 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4839 if (strcmp(word->data, "export") == 0
4840 # if ENABLE_HUSH_LOCAL
4841 || strcmp(word->data, "local") == 0
4844 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4847 # if ENABLE_HUSH_BASH_COMPAT
4848 if (strcmp(word->data, "[[") == 0) {
4849 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4855 if (command->group) {
4856 /* "{ echo foo; } echo bar" - bad */
4857 syntax_error_at(word->data);
4858 debug_printf_parse("done_word return 1: syntax error, "
4859 "groups and arglists don't mix\n");
4862 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4863 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4864 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4865 /* (otherwise it's known to be not empty and is already safe) */
4867 /* exclude "$@" - it can expand to no word despite "" */
4868 char *p = word->data;
4869 while (p[0] == SPECIAL_VAR_SYMBOL
4870 && (p[1] & 0x7f) == '@'
4871 && p[2] == SPECIAL_VAR_SYMBOL
4875 if (p == word->data || p[0] != '\0') {
4876 /* saw no "$@", or not only "$@" but some
4877 * real text is there too */
4878 /* insert "empty variable" reference, this makes
4879 * e.g. "", $empty"" etc to not disappear */
4880 o_addchr(word, SPECIAL_VAR_SYMBOL);
4881 o_addchr(word, SPECIAL_VAR_SYMBOL);
4884 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4885 debug_print_strings("word appended to argv", command->argv);
4888 #if ENABLE_HUSH_LOOPS
4889 if (ctx->ctx_res_w == RES_FOR) {
4891 || !is_well_formed_var_name(command->argv[0], '\0')
4893 /* bash says just "not a valid identifier" */
4894 syntax_error("not a valid identifier in for");
4897 /* Force FOR to have just one word (variable name) */
4898 /* NB: basically, this makes hush see "for v in ..."
4899 * syntax as if it is "for v; in ...". FOR and IN become
4900 * two pipe structs in parse tree. */
4901 done_pipe(ctx, PIPE_SEQ);
4904 #if ENABLE_HUSH_CASE
4905 /* Force CASE to have just one word */
4906 if (ctx->ctx_res_w == RES_CASE) {
4907 done_pipe(ctx, PIPE_SEQ);
4911 o_reset_to_empty_unquoted(word);
4913 debug_printf_parse("done_word return 0\n");
4918 /* Peek ahead in the input to find out if we have a "&n" construct,
4919 * as in "2>&1", that represents duplicating a file descriptor.
4921 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4922 * REDIRFD_SYNTAX_ERR if syntax error,
4923 * REDIRFD_TO_FILE if no & was seen,
4924 * or the number found.
4927 #define parse_redir_right_fd(as_string, input) \
4928 parse_redir_right_fd(input)
4930 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4936 return REDIRFD_TO_FILE;
4938 ch = i_getch(input); /* get the & */
4939 nommu_addchr(as_string, ch);
4942 ch = i_getch(input);
4943 nommu_addchr(as_string, ch);
4944 return REDIRFD_CLOSE;
4948 while (ch != EOF && isdigit(ch)) {
4949 d = d*10 + (ch-'0');
4951 ch = i_getch(input);
4952 nommu_addchr(as_string, ch);
4957 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4959 bb_error_msg("ambiguous redirect");
4960 return REDIRFD_SYNTAX_ERR;
4963 /* Return code is 0 normal, 1 if a syntax error is detected
4965 static int parse_redirect(struct parse_context *ctx,
4968 struct in_str *input)
4970 struct command *command = ctx->command;
4971 struct redir_struct *redir;
4972 struct redir_struct **redirp;
4975 dup_num = REDIRFD_TO_FILE;
4976 if (style != REDIRECT_HEREDOC) {
4977 /* Check for a '>&1' type redirect */
4978 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4979 if (dup_num == REDIRFD_SYNTAX_ERR)
4982 int ch = i_peek(input);
4983 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4984 if (dup_num) { /* <<-... */
4985 ch = i_getch(input);
4986 nommu_addchr(&ctx->as_string, ch);
4991 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4992 int ch = i_peek(input);
4994 /* >|FILE redirect ("clobbering" >).
4995 * Since we do not support "set -o noclobber" yet,
4996 * >| and > are the same for now. Just eat |.
4998 ch = i_getch(input);
4999 nommu_addchr(&ctx->as_string, ch);
5003 /* Create a new redir_struct and append it to the linked list */
5004 redirp = &command->redirects;
5005 while ((redir = *redirp) != NULL) {
5006 redirp = &(redir->next);
5008 *redirp = redir = xzalloc(sizeof(*redir));
5009 /* redir->next = NULL; */
5010 /* redir->rd_filename = NULL; */
5011 redir->rd_type = style;
5012 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5014 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5015 redir_table[style].descrip);
5017 redir->rd_dup = dup_num;
5018 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5019 /* Erik had a check here that the file descriptor in question
5020 * is legit; I postpone that to "run time"
5021 * A "-" representation of "close me" shows up as a -3 here */
5022 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5023 redir->rd_fd, redir->rd_dup);
5025 /* Set ctx->pending_redirect, so we know what to do at the
5026 * end of the next parsed word. */
5027 ctx->pending_redirect = redir;
5032 /* If a redirect is immediately preceded by a number, that number is
5033 * supposed to tell which file descriptor to redirect. This routine
5034 * looks for such preceding numbers. In an ideal world this routine
5035 * needs to handle all the following classes of redirects...
5036 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5037 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5038 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5039 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5041 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5043 * ... If n is quoted, the number shall not be recognized as part of
5044 * the redirection expression. For example:
5046 * writes the character 2 into file a"
5047 * We are getting it right by setting ->o_quoted on any \<char>
5049 * A -1 return means no valid number was found,
5050 * the caller should use the appropriate default for this redirection.
5052 static int redirect_opt_num(o_string *o)
5056 if (o->data == NULL)
5058 num = bb_strtou(o->data, NULL, 10);
5059 if (errno || num < 0)
5061 o_reset_to_empty_unquoted(o);
5066 #define fetch_till_str(as_string, input, word, skip_tabs) \
5067 fetch_till_str(input, word, skip_tabs)
5069 static char *fetch_till_str(o_string *as_string,
5070 struct in_str *input,
5074 o_string heredoc = NULL_O_STRING;
5080 ch = i_getch(input);
5081 nommu_addchr(as_string, ch);
5083 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5084 heredoc.data[past_EOL] = '\0';
5085 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5086 return heredoc.data;
5089 o_addchr(&heredoc, ch);
5090 past_EOL = heredoc.length;
5093 ch = i_getch(input);
5094 nommu_addchr(as_string, ch);
5095 } while (skip_tabs && ch == '\t');
5096 } while (ch == '\n');
5099 o_free_unsafe(&heredoc);
5102 o_addchr(&heredoc, ch);
5103 nommu_addchr(as_string, ch);
5107 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5108 * and load them all. There should be exactly heredoc_cnt of them.
5110 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5112 struct pipe *pi = ctx->list_head;
5114 while (pi && heredoc_cnt) {
5116 struct command *cmd = pi->cmds;
5118 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5120 cmd->argv ? cmd->argv[0] : "NONE");
5121 for (i = 0; i < pi->num_cmds; i++) {
5122 struct redir_struct *redir = cmd->redirects;
5124 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5125 i, cmd->argv ? cmd->argv[0] : "NONE");
5127 if (redir->rd_type == REDIRECT_HEREDOC) {
5130 redir->rd_type = REDIRECT_HEREDOC2;
5131 /* redir->rd_dup is (ab)used to indicate <<- */
5132 p = fetch_till_str(&ctx->as_string, input,
5133 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5135 syntax_error("unexpected EOF in here document");
5138 free(redir->rd_filename);
5139 redir->rd_filename = p;
5142 redir = redir->next;
5149 /* Should be 0. If it isn't, it's a parse error */
5151 bb_error_msg_and_die("heredoc BUG 2");
5157 #if ENABLE_HUSH_TICK
5158 static FILE *generate_stream_from_string(const char *s)
5161 int pid, channel[2];
5167 pid = BB_MMU ? fork() : vfork();
5169 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5171 if (pid == 0) { /* child */
5172 disable_restore_tty_pgrp_on_exit();
5173 /* Process substitution is not considered to be usual
5174 * 'command execution'.
5175 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5182 close(channel[0]); /* NB: close _first_, then move fd! */
5183 xmove_fd(channel[1], 1);
5184 /* Prevent it from trying to handle ctrl-z etc */
5185 IF_HUSH_JOB(G.run_list_level = 1;)
5187 reset_traps_to_defaults();
5188 parse_and_run_string(s);
5189 _exit(G.last_exitcode);
5191 /* We re-execute after vfork on NOMMU. This makes this script safe:
5192 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5193 * huge=`cat BIG` # was blocking here forever
5196 re_execute_shell(&to_free,
5205 #if ENABLE_HUSH_FAST
5207 //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);
5209 enable_restore_tty_pgrp_on_exit();
5214 pf = fdopen(channel[0], "r");
5218 /* Return code is exit status of the process that is run. */
5219 static int process_command_subs(o_string *dest, const char *s)
5222 struct in_str pipe_str;
5225 pf = generate_stream_from_string(s);
5228 close_on_exec_on(fileno(pf));
5230 /* Now send results of command back into original context */
5231 setup_file_in_str(&pipe_str, pf);
5233 while ((ch = i_getch(&pipe_str)) != EOF) {
5239 o_addchr(dest, '\n');
5242 o_addQchr(dest, ch);
5245 debug_printf("done reading from pipe, pclose()ing\n");
5246 /* Note: we got EOF, and we just close the read end of the pipe.
5247 * We do not wait for the `cmd` child to terminate. bash and ash do.
5249 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5250 * `false`; echo $? - bash outputs "1"
5253 debug_printf("closed FILE from child. return 0\n");
5258 static int parse_group(o_string *dest, struct parse_context *ctx,
5259 struct in_str *input, int ch)
5261 /* dest contains characters seen prior to ( or {.
5262 * Typically it's empty, but for function defs,
5263 * it contains function name (without '()'). */
5264 struct pipe *pipe_list;
5266 struct command *command = ctx->command;
5268 debug_printf_parse("parse_group entered\n");
5269 #if ENABLE_HUSH_FUNCTIONS
5270 if (ch == '(' && !dest->o_quoted) {
5272 if (done_word(dest, ctx))
5275 goto skip; /* (... */
5276 if (command->argv[1]) { /* word word ... (... */
5277 syntax_error_unexpected_ch('(');
5280 /* it is "word(..." or "word (..." */
5282 ch = i_getch(input);
5283 while (ch == ' ' || ch == '\t');
5285 syntax_error_unexpected_ch(ch);
5288 nommu_addchr(&ctx->as_string, ch);
5290 ch = i_getch(input);
5291 while (ch == ' ' || ch == '\t' || ch == '\n');
5293 syntax_error_unexpected_ch(ch);
5296 nommu_addchr(&ctx->as_string, ch);
5297 command->cmd_type = CMD_FUNCDEF;
5301 if (command->argv /* word [word]{... */
5302 || dest->length /* word{... */
5303 || dest->o_quoted /* ""{... */
5306 debug_printf_parse("parse_group return 1: "
5307 "syntax error, groups and arglists don't mix\n");
5311 #if ENABLE_HUSH_FUNCTIONS
5317 command->cmd_type = CMD_SUBSHELL;
5319 /* bash does not allow "{echo...", requires whitespace */
5320 ch = i_getch(input);
5321 if (ch != ' ' && ch != '\t' && ch != '\n') {
5322 syntax_error_unexpected_ch(ch);
5325 nommu_addchr(&ctx->as_string, ch);
5330 char *as_string = NULL;
5332 pipe_list = parse_stream(&as_string, input, endch);
5335 o_addstr(&ctx->as_string, as_string);
5337 /* empty ()/{} or parse error? */
5338 if (!pipe_list || pipe_list == ERR_PTR) {
5339 /* parse_stream already emitted error msg */
5343 debug_printf_parse("parse_group return 1: "
5344 "parse_stream returned %p\n", pipe_list);
5347 command->group = pipe_list;
5349 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5350 command->group_as_string = as_string;
5351 debug_printf_parse("end of group, remembering as:'%s'\n",
5352 command->group_as_string);
5355 debug_printf_parse("parse_group return 0\n");
5357 /* command remains "open", available for possible redirects */
5360 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5361 /* Subroutines for copying $(...) and `...` things */
5362 static void add_till_backquote(o_string *dest, struct in_str *input);
5364 static void add_till_single_quote(o_string *dest, struct in_str *input)
5367 int ch = i_getch(input);
5369 syntax_error_unterm_ch('\'');
5370 /*xfunc_die(); - redundant */
5377 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5378 static void add_till_double_quote(o_string *dest, struct in_str *input)
5381 int ch = i_getch(input);
5383 syntax_error_unterm_ch('"');
5384 /*xfunc_die(); - redundant */
5388 if (ch == '\\') { /* \x. Copy both chars. */
5390 ch = i_getch(input);
5394 add_till_backquote(dest, input);
5398 //if (ch == '$') ...
5401 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5403 * "Within the backquoted style of command substitution, backslash
5404 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5405 * The search for the matching backquote shall be satisfied by the first
5406 * backquote found without a preceding backslash; during this search,
5407 * if a non-escaped backquote is encountered within a shell comment,
5408 * a here-document, an embedded command substitution of the $(command)
5409 * form, or a quoted string, undefined results occur. A single-quoted
5410 * or double-quoted string that begins, but does not end, within the
5411 * "`...`" sequence produces undefined results."
5413 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5415 static void add_till_backquote(o_string *dest, struct in_str *input)
5418 int ch = i_getch(input);
5420 syntax_error_unterm_ch('`');
5421 /*xfunc_die(); - redundant */
5426 /* \x. Copy both chars unless it is \` */
5427 int ch2 = i_getch(input);
5429 syntax_error_unterm_ch('`');
5430 /*xfunc_die(); - redundant */
5432 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5439 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5440 * quoting and nested ()s.
5441 * "With the $(command) style of command substitution, all characters
5442 * following the open parenthesis to the matching closing parenthesis
5443 * constitute the command. Any valid shell script can be used for command,
5444 * except a script consisting solely of redirections which produces
5445 * unspecified results."
5447 * echo $(echo '(TEST)' BEST) (TEST) BEST
5448 * echo $(echo 'TEST)' BEST) TEST) BEST
5449 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5451 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5455 int ch = i_getch(input);
5457 syntax_error_unterm_ch(')');
5458 /*xfunc_die(); - redundant */
5466 if (i_peek(input) == ')') {
5474 add_till_single_quote(dest, input);
5479 add_till_double_quote(dest, input);
5484 /* \x. Copy verbatim. Important for \(, \) */
5485 ch = i_getch(input);
5487 syntax_error_unterm_ch(')');
5488 /*xfunc_die(); - redundant */
5495 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5497 /* Return code: 0 for OK, 1 for syntax error */
5499 #define handle_dollar(as_string, dest, input) \
5500 handle_dollar(dest, input)
5502 static int handle_dollar(o_string *as_string,
5504 struct in_str *input)
5506 int ch = i_peek(input); /* first character after the $ */
5507 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5509 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5511 ch = i_getch(input);
5512 nommu_addchr(as_string, ch);
5514 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5516 debug_printf_parse(": '%c'\n", ch);
5517 o_addchr(dest, ch | quote_mask);
5520 if (!isalnum(ch) && ch != '_')
5522 ch = i_getch(input);
5523 nommu_addchr(as_string, ch);
5525 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5526 } else if (isdigit(ch)) {
5528 ch = i_getch(input);
5529 nommu_addchr(as_string, ch);
5530 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5531 debug_printf_parse(": '%c'\n", ch);
5532 o_addchr(dest, ch | quote_mask);
5533 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5534 } else switch (ch) {
5536 case '!': /* last bg pid */
5537 case '?': /* last exit code */
5538 case '#': /* number of args */
5539 case '*': /* args */
5540 case '@': /* args */
5541 goto make_one_char_var;
5543 bool first_char, all_digits;
5546 ch = i_getch(input);
5547 nommu_addchr(as_string, ch);
5548 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5550 /* TODO: maybe someone will try to escape the '}' */
5555 ch = i_getch(input);
5556 nommu_addchr(as_string, ch);
5563 /* ${#var}: length of var contents */
5570 /* They're being verbose and doing ${?} */
5571 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5576 && ( (all_digits && !isdigit(ch))
5577 || (!all_digits && !isalnum(ch) && ch != '_')
5580 /* handle parameter expansions
5581 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5586 case ':': /* null modifier */
5587 if (expansion == 0) {
5588 debug_printf_parse(": null modifier\n");
5593 case '#': /* remove prefix */
5594 case '%': /* remove suffix */
5595 if (expansion == 0) {
5596 debug_printf_parse(": remove suffix/prefix\n");
5601 case '-': /* default value */
5602 case '=': /* assign default */
5603 case '+': /* alternative */
5604 case '?': /* error indicate */
5605 debug_printf_parse(": parameter expansion\n");
5610 syntax_error_unterm_str("${name}");
5611 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5616 debug_printf_parse(": '%c'\n", ch);
5617 o_addchr(dest, ch | quote_mask);
5621 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5624 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5629 ch = i_getch(input);
5630 nommu_addchr(as_string, ch);
5631 # if ENABLE_SH_MATH_SUPPORT
5632 if (i_peek(input) == '(') {
5633 ch = i_getch(input);
5634 nommu_addchr(as_string, ch);
5635 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5636 o_addchr(dest, /*quote_mask |*/ '+');
5640 add_till_closing_paren(dest, input, true);
5643 o_addstr(as_string, dest->data + pos);
5644 o_addchr(as_string, ')');
5645 o_addchr(as_string, ')');
5648 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5652 # if ENABLE_HUSH_TICK
5653 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5654 o_addchr(dest, quote_mask | '`');
5658 add_till_closing_paren(dest, input, false);
5661 o_addstr(as_string, dest->data + pos);
5662 o_addchr(as_string, '`');
5665 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5671 ch = i_getch(input);
5672 nommu_addchr(as_string, ch);
5674 if (isalnum(ch)) { /* it's $_name or $_123 */
5680 /* $_ Shell or shell script name; or last cmd name */
5681 /* $- Option flags set by set builtin or shell options (-i etc) */
5683 o_addQchr(dest, '$');
5685 debug_printf_parse("handle_dollar return 0\n");
5690 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5691 parse_stream_dquoted(dest, input, dquote_end)
5693 static int parse_stream_dquoted(o_string *as_string,
5695 struct in_str *input,
5702 ch = i_getch(input);
5704 nommu_addchr(as_string, ch);
5705 if (ch == dquote_end) { /* may be only '"' or EOF */
5706 if (dest->o_assignment == NOT_ASSIGNMENT)
5707 dest->o_escape ^= 1;
5708 debug_printf_parse("parse_stream_dquoted return 0\n");
5711 /* note: can't move it above ch == dquote_end check! */
5713 syntax_error_unterm_ch('"');
5714 /*xfunc_die(); - redundant */
5718 next = i_peek(input);
5720 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5721 ch, ch, dest->o_escape);
5724 syntax_error("\\<eof>");
5728 * "The backslash retains its special meaning [in "..."]
5729 * only when followed by one of the following characters:
5730 * $, `, ", \, or <newline>. A double quote may be quoted
5731 * within double quotes by preceding it with a backslash."
5733 if (strchr("$`\"\\\n", next) != NULL) {
5734 ch = i_getch(input);
5736 o_addqchr(dest, ch);
5737 nommu_addchr(as_string, ch);
5740 o_addqchr(dest, '\\');
5741 nommu_addchr(as_string, '\\');
5746 if (handle_dollar(as_string, dest, input) != 0) {
5747 debug_printf_parse("parse_stream_dquoted return 1: "
5748 "handle_dollar returned non-0\n");
5753 #if ENABLE_HUSH_TICK
5755 //int pos = dest->length;
5756 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5757 o_addchr(dest, 0x80 | '`');
5758 add_till_backquote(dest, input);
5759 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5760 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5764 o_addQchr(dest, ch);
5766 && (dest->o_assignment == MAYBE_ASSIGNMENT
5767 || dest->o_assignment == WORD_IS_KEYWORD)
5768 && is_well_formed_var_name(dest->data, '=')
5770 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5776 * Scan input until EOF or end_trigger char.
5777 * Return a list of pipes to execute, or NULL on EOF
5778 * or if end_trigger character is met.
5779 * On syntax error, exit is shell is not interactive,
5780 * reset parsing machinery and start parsing anew,
5781 * or return ERR_PTR.
5783 static struct pipe *parse_stream(char **pstring,
5784 struct in_str *input,
5787 struct parse_context ctx;
5788 o_string dest = NULL_O_STRING;
5792 /* Double-quote state is handled in the state variable is_in_dquote.
5793 * A single-quote triggers a bypass of the main loop until its mate is
5794 * found. When recursing, quote state is passed in via dest->o_escape.
5796 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5797 end_trigger ? end_trigger : 'X');
5800 G.ifs = get_local_var_value("IFS");
5805 #if ENABLE_HUSH_INTERACTIVE
5806 input->promptmode = 0; /* PS1 */
5808 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5809 initialize_context(&ctx);
5814 const char *is_special;
5818 redir_type redir_style;
5821 /* dest.o_quoted = 1; - already is (see below) */
5822 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5825 /* We reached closing '"' */
5828 ch = i_getch(input);
5829 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5830 ch, ch, dest.o_escape);
5835 syntax_error_unterm_str("here document");
5838 /* end_trigger == '}' case errors out earlier,
5839 * checking only ')' */
5840 if (end_trigger == ')') {
5841 syntax_error_unterm_ch('('); /* exits */
5842 /* goto parse_error; */
5845 if (done_word(&dest, &ctx)) {
5849 done_pipe(&ctx, PIPE_SEQ);
5851 /* If we got nothing... */
5852 /* (this makes bare "&" cmd a no-op.
5853 * bash says: "syntax error near unexpected token '&'") */
5854 if (pi->num_cmds == 0
5855 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5861 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5863 *pstring = ctx.as_string.data;
5865 o_free_unsafe(&ctx.as_string);
5868 debug_printf_parse("parse_stream return %p\n", pi);
5871 nommu_addchr(&ctx.as_string, ch);
5872 is_ifs = strchr(G.ifs, ch);
5873 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5874 "\\$\"" IF_HUSH_TICK("`") /* always special */
5877 if (!is_special && !is_ifs) { /* ordinary char */
5879 o_addQchr(&dest, ch);
5880 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5881 || dest.o_assignment == WORD_IS_KEYWORD)
5883 && is_well_formed_var_name(dest.data, '=')
5885 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5891 if (done_word(&dest, &ctx)) {
5895 #if ENABLE_HUSH_CASE
5896 /* "case ... in <newline> word) ..." -
5897 * newlines are ignored (but ';' wouldn't be) */
5898 if (ctx.command->argv == NULL
5899 && ctx.ctx_res_w == RES_MATCH
5904 /* Treat newline as a command separator. */
5905 done_pipe(&ctx, PIPE_SEQ);
5906 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5908 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5913 dest.o_assignment = MAYBE_ASSIGNMENT;
5915 /* note: if (is_ifs) continue;
5916 * will still trigger for us */
5920 /* "cmd}" or "cmd }..." without semicolon or &:
5921 * } is an ordinary char in this case, even inside { cmd; }
5922 * Pathological example: { ""}; } should exec "}" cmd
5925 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5926 || dest.length != 0 /* word} */
5927 || dest.o_quoted /* ""} */
5931 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5932 goto skip_end_trigger;
5933 /* else: } does terminate a group */
5936 if (end_trigger && end_trigger == ch
5937 && (ch != ';' || heredoc_cnt == 0)
5938 #if ENABLE_HUSH_CASE
5940 || ctx.ctx_res_w != RES_MATCH
5941 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5946 /* This is technically valid:
5947 * { cat <<HERE; }; echo Ok
5951 * but we don't support this.
5952 * We require heredoc to be in enclosing {}/(),
5955 syntax_error_unterm_str("here document");
5958 if (done_word(&dest, &ctx)) {
5961 done_pipe(&ctx, PIPE_SEQ);
5962 dest.o_assignment = MAYBE_ASSIGNMENT;
5963 /* Do we sit outside of any if's, loops or case's? */
5965 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5969 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5971 *pstring = ctx.as_string.data;
5973 o_free_unsafe(&ctx.as_string);
5976 debug_printf_parse("parse_stream return %p: "
5977 "end_trigger char found\n",
5979 return ctx.list_head;
5988 next = i_peek(input);
5991 /* Catch <, > before deciding whether this word is
5992 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5995 redir_fd = redirect_opt_num(&dest);
5996 if (done_word(&dest, &ctx)) {
5999 redir_style = REDIRECT_OVERWRITE;
6001 redir_style = REDIRECT_APPEND;
6002 ch = i_getch(input);
6003 nommu_addchr(&ctx.as_string, ch);
6006 else if (next == '(') {
6007 syntax_error(">(process) not supported");
6011 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6013 continue; /* back to top of while (1) */
6015 redir_fd = redirect_opt_num(&dest);
6016 if (done_word(&dest, &ctx)) {
6019 redir_style = REDIRECT_INPUT;
6021 redir_style = REDIRECT_HEREDOC;
6023 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6024 ch = i_getch(input);
6025 nommu_addchr(&ctx.as_string, ch);
6026 } else if (next == '>') {
6027 redir_style = REDIRECT_IO;
6028 ch = i_getch(input);
6029 nommu_addchr(&ctx.as_string, ch);
6032 else if (next == '(') {
6033 syntax_error("<(process) not supported");
6037 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6039 continue; /* back to top of while (1) */
6042 if (dest.o_assignment == MAYBE_ASSIGNMENT
6043 /* check that we are not in word in "a=1 2>word b=1": */
6044 && !ctx.pending_redirect
6046 /* ch is a special char and thus this word
6047 * cannot be an assignment */
6048 dest.o_assignment = NOT_ASSIGNMENT;
6051 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6055 if (dest.length == 0) {
6058 if (ch == EOF || ch == '\n')
6061 /* note: we do not add it to &ctx.as_string */
6063 nommu_addchr(&ctx.as_string, '\n');
6065 o_addQchr(&dest, ch);
6070 syntax_error("\\<eof>");
6073 ch = i_getch(input);
6075 o_addchr(&dest, '\\');
6076 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6077 o_addchr(&dest, ch);
6078 nommu_addchr(&ctx.as_string, ch);
6079 /* Example: echo Hello \2>file
6080 * we need to know that word 2 is quoted */
6084 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6085 ctx.as_string.data[--ctx.as_string.length] = '\0';
6090 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6091 debug_printf_parse("parse_stream parse error: "
6092 "handle_dollar returned non-0\n");
6099 ch = i_getch(input);
6101 syntax_error_unterm_ch('\'');
6102 /*xfunc_die(); - redundant */
6104 nommu_addchr(&ctx.as_string, ch);
6107 o_addqchr(&dest, ch);
6112 is_in_dquote ^= 1; /* invert */
6113 if (dest.o_assignment == NOT_ASSIGNMENT)
6116 #if ENABLE_HUSH_TICK
6121 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6122 o_addchr(&dest, '`');
6126 add_till_backquote(&dest, input);
6128 o_addstr(&ctx.as_string, dest.data + pos);
6129 o_addchr(&ctx.as_string, '`');
6131 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6132 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6137 #if ENABLE_HUSH_CASE
6140 if (done_word(&dest, &ctx)) {
6143 done_pipe(&ctx, PIPE_SEQ);
6144 #if ENABLE_HUSH_CASE
6145 /* Eat multiple semicolons, detect
6146 * whether it means something special */
6151 ch = i_getch(input);
6152 nommu_addchr(&ctx.as_string, ch);
6153 if (ctx.ctx_res_w == RES_CASE_BODY) {
6154 ctx.ctx_dsemicolon = 1;
6155 ctx.ctx_res_w = RES_MATCH;
6161 /* We just finished a cmd. New one may start
6162 * with an assignment */
6163 dest.o_assignment = MAYBE_ASSIGNMENT;
6166 if (done_word(&dest, &ctx)) {
6170 ch = i_getch(input);
6171 nommu_addchr(&ctx.as_string, ch);
6172 done_pipe(&ctx, PIPE_AND);
6174 done_pipe(&ctx, PIPE_BG);
6178 if (done_word(&dest, &ctx)) {
6181 #if ENABLE_HUSH_CASE
6182 if (ctx.ctx_res_w == RES_MATCH)
6183 break; /* we are in case's "word | word)" */
6185 if (next == '|') { /* || */
6186 ch = i_getch(input);
6187 nommu_addchr(&ctx.as_string, ch);
6188 done_pipe(&ctx, PIPE_OR);
6190 /* we could pick up a file descriptor choice here
6191 * with redirect_opt_num(), but bash doesn't do it.
6192 * "echo foo 2| cat" yields "foo 2". */
6197 #if ENABLE_HUSH_CASE
6198 /* "case... in [(]word)..." - skip '(' */
6199 if (ctx.ctx_res_w == RES_MATCH
6200 && ctx.command->argv == NULL /* not (word|(... */
6201 && dest.length == 0 /* not word(... */
6202 && dest.o_quoted == 0 /* not ""(... */
6208 if (parse_group(&dest, &ctx, input, ch) != 0) {
6213 #if ENABLE_HUSH_CASE
6214 if (ctx.ctx_res_w == RES_MATCH)
6218 /* proper use of this character is caught by end_trigger:
6219 * if we see {, we call parse_group(..., end_trigger='}')
6220 * and it will match } earlier (not here). */
6221 syntax_error_unexpected_ch(ch);
6225 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6231 struct parse_context *pctx;
6232 IF_HAS_KEYWORDS(struct parse_context *p2;)
6234 /* Clean up allocated tree.
6235 * Sample for finding leaks on syntax error recovery path.
6236 * Run it from interactive shell, watch pmap `pidof hush`.
6237 * while if false; then false; fi; do break; fi
6238 * Samples to catch leaks at execution:
6239 * while if (true | {true;}); then echo ok; fi; do break; done
6240 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6244 /* Update pipe/command counts,
6245 * otherwise freeing may miss some */
6246 done_pipe(pctx, PIPE_SEQ);
6247 debug_printf_clean("freeing list %p from ctx %p\n",
6248 pctx->list_head, pctx);
6249 debug_print_tree(pctx->list_head, 0);
6250 free_pipe_list(pctx->list_head);
6251 debug_printf_clean("freed list %p\n", pctx->list_head);
6253 o_free_unsafe(&pctx->as_string);
6255 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6259 IF_HAS_KEYWORDS(pctx = p2;)
6260 } while (HAS_KEYWORDS && pctx);
6261 /* Free text, clear all dest fields */
6263 /* If we are not in top-level parse, we return,
6264 * our caller will propagate error.
6266 if (end_trigger != ';') {
6274 /* Discard cached input, force prompt */
6276 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6281 /* Executing from string: eval, sh -c '...'
6282 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6283 * end_trigger controls how often we stop parsing
6284 * NUL: parse all, execute, return
6285 * ';': parse till ';' or newline, execute, repeat till EOF
6287 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6290 struct pipe *pipe_list;
6292 pipe_list = parse_stream(NULL, inp, end_trigger);
6293 if (!pipe_list) /* EOF */
6295 debug_print_tree(pipe_list, 0);
6296 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6297 run_and_free_list(pipe_list);
6301 static void parse_and_run_string(const char *s)
6303 struct in_str input;
6304 setup_string_in_str(&input, s);
6305 parse_and_run_stream(&input, '\0');
6308 static void parse_and_run_file(FILE *f)
6310 struct in_str input;
6311 setup_file_in_str(&input, f);
6312 parse_and_run_stream(&input, ';');
6315 /* Called a few times only (or even once if "sh -c") */
6316 static void block_signals(int second_time)
6321 mask = (1 << SIGQUIT);
6322 if (G_interactive_fd) {
6323 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6324 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6325 mask |= SPECIAL_JOB_SIGS;
6327 G.non_DFL_mask = mask;
6330 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6334 sigaddset(&G.blocked_set, sig);
6338 sigdelset(&G.blocked_set, SIGCHLD);
6340 sigprocmask(SIG_SETMASK, &G.blocked_set,
6341 second_time ? NULL : &G.inherited_set);
6342 /* POSIX allows shell to re-enable SIGCHLD
6343 * even if it was SIG_IGN on entry */
6344 #if ENABLE_HUSH_FAST
6345 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6347 signal(SIGCHLD, SIGCHLD_handler);
6350 signal(SIGCHLD, SIG_DFL);
6356 static void maybe_set_to_sigexit(int sig)
6358 void (*handler)(int);
6359 /* non_DFL_mask'ed signals are, well, masked,
6360 * no need to set handler for them.
6362 if (!((G.non_DFL_mask >> sig) & 1)) {
6363 handler = signal(sig, sigexit);
6364 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6365 signal(sig, handler);
6368 /* Set handlers to restore tty pgrp and exit */
6369 static void set_fatal_handlers(void)
6371 /* We _must_ restore tty pgrp on fatal signals */
6373 maybe_set_to_sigexit(SIGILL );
6374 maybe_set_to_sigexit(SIGFPE );
6375 maybe_set_to_sigexit(SIGBUS );
6376 maybe_set_to_sigexit(SIGSEGV);
6377 maybe_set_to_sigexit(SIGTRAP);
6378 } /* else: hush is perfect. what SEGV? */
6379 maybe_set_to_sigexit(SIGABRT);
6380 /* bash 3.2 seems to handle these just like 'fatal' ones */
6381 maybe_set_to_sigexit(SIGPIPE);
6382 maybe_set_to_sigexit(SIGALRM);
6383 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6384 * if we aren't interactive... but in this case
6385 * we never want to restore pgrp on exit, and this fn is not called */
6386 /*maybe_set_to_sigexit(SIGHUP );*/
6387 /*maybe_set_to_sigexit(SIGTERM);*/
6388 /*maybe_set_to_sigexit(SIGINT );*/
6392 static int set_mode(const char cstate, const char mode)
6394 int state = (cstate == '-' ? 1 : 0);
6396 case 'n': G.fake_mode = state; break;
6397 case 'x': /*G.debug_mode = state;*/ break;
6398 default: return EXIT_FAILURE;
6400 return EXIT_SUCCESS;
6403 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6404 int hush_main(int argc, char **argv)
6406 static const struct variable const_shell_ver = {
6408 .varstr = (char*)hush_version_str,
6409 .max_len = 1, /* 0 can provoke free(name) */
6413 int signal_mask_is_inited = 0;
6415 unsigned builtin_argc;
6417 struct variable *cur_var;
6420 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6421 G.last_exitcode = EXIT_SUCCESS;
6423 G.argv0_for_re_execing = argv[0];
6425 /* Deal with HUSH_VERSION */
6426 G.shell_ver = const_shell_ver; /* copying struct here */
6427 G.top_var = &G.shell_ver;
6428 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6429 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6430 /* Initialize our shell local variables with the values
6431 * currently living in the environment */
6432 cur_var = G.top_var;
6435 char *value = strchr(*e, '=');
6436 if (value) { /* paranoia */
6437 cur_var->next = xzalloc(sizeof(*cur_var));
6438 cur_var = cur_var->next;
6439 cur_var->varstr = *e;
6440 cur_var->max_len = strlen(*e);
6441 cur_var->flg_export = 1;
6445 /* reinstate HUSH_VERSION */
6446 debug_printf_env("putenv '%s'\n", hush_version_str);
6447 putenv((char *)hush_version_str);
6450 set_pwd_var(/*exp:*/ 1);
6451 /* bash also exports SHLVL and _,
6452 * and sets (but doesn't export) the following variables:
6454 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6455 * BASH_VERSION='3.2.0(1)-release'
6457 * MACHTYPE=i386-pc-linux-gnu
6459 * HOSTNAME=<xxxxxxxxxx>
6471 * PIPESTATUS=([0]="0")
6472 * HISTFILE=/<xxx>/.bash_history
6476 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6478 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6488 #if ENABLE_FEATURE_EDITING
6489 G.line_input_state = new_line_input_t(FOR_SHELL);
6491 G.global_argc = argc;
6492 G.global_argv = argv;
6493 /* Initialize some more globals to non-zero values */
6494 cmdedit_update_prompt();
6496 if (setjmp(die_jmp)) {
6497 /* xfunc has failed! die die die */
6498 /* no EXIT traps, this is an escape hatch! */
6500 hush_exit(xfunc_error_retval);
6503 /* Shell is non-interactive at first. We need to call
6504 * block_signals(0) if we are going to execute "sh <script>",
6505 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6506 * If we later decide that we are interactive, we run block_signals(0)
6507 * (or re-run block_signals(1) if we ran block_signals(0) before)
6508 * in order to intercept (more) signals.
6512 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6515 opt = getopt(argc, argv, "+c:xins"
6518 # if ENABLE_HUSH_FUNCTIONS
6528 * sh ... -c 'script'
6529 * sh ... -c 'script' ARG0 [ARG1...]
6530 * On NOMMU, if builtin_argc != 0,
6531 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6532 * "" needs to be replaced with NULL
6533 * and BARGV vector fed to builtin function.
6534 * Note: this form never happens:
6535 * sh ... -c 'builtin' [BARGV...] ""
6538 G.root_pid = getpid();
6539 G.global_argv = argv + optind;
6540 G.global_argc = argc - optind;
6542 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6543 const struct built_in_command *x;
6545 block_signals(0); /* 0: called 1st time */
6546 x = find_builtin(optarg);
6547 if (x) { /* paranoia */
6548 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6549 G.global_argv += builtin_argc;
6550 G.global_argv[-1] = NULL; /* replace "" */
6551 G.last_exitcode = x->function(argv + optind - 1);
6555 if (!G.global_argv[0]) {
6556 /* -c 'script' (no params): prevent empty $0 */
6557 G.global_argv--; /* points to argv[i] of 'script' */
6558 G.global_argv[0] = argv[0];
6560 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6561 block_signals(0); /* 0: called 1st time */
6562 parse_and_run_string(optarg);
6565 /* Well, we cannot just declare interactiveness,
6566 * we have to have some stuff (ctty, etc) */
6567 /* G_interactive_fd++; */
6570 /* "-s" means "read from stdin", but this is how we always
6571 * operate, so simply do nothing here. */
6574 case '<': /* "big heredoc" support */
6575 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6578 G.root_pid = bb_strtou(optarg, &optarg, 16);
6580 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6582 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6584 builtin_argc = bb_strtou(optarg, &optarg, 16);
6585 # if ENABLE_HUSH_LOOPS
6587 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6592 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6594 # if ENABLE_HUSH_FUNCTIONS
6596 struct function *funcp = new_function(optarg);
6597 /* funcp->name is already set to optarg */
6598 /* funcp->body is set to NULL. It's a special case. */
6599 funcp->body_as_string = argv[optind];
6607 if (!set_mode('-', opt))
6611 fprintf(stderr, "Usage: sh [FILE]...\n"
6612 " or: sh -c command [args]...\n\n");
6618 } /* option parsing loop */
6621 G.root_pid = getpid();
6623 /* If we are login shell... */
6624 if (argv[0] && argv[0][0] == '-') {
6626 debug_printf("sourcing /etc/profile\n");
6627 input = fopen_for_read("/etc/profile");
6628 if (input != NULL) {
6629 close_on_exec_on(fileno(input));
6630 block_signals(0); /* 0: called 1st time */
6631 signal_mask_is_inited = 1;
6632 parse_and_run_file(input);
6635 /* bash: after sourcing /etc/profile,
6636 * tries to source (in the given order):
6637 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6638 * stopping on first found. --noprofile turns this off.
6639 * bash also sources ~/.bash_logout on exit.
6640 * If called as sh, skips .bash_XXX files.
6647 * "bash <script>" (which is never interactive (unless -i?))
6648 * sources $BASH_ENV here (without scanning $PATH).
6649 * If called as sh, does the same but with $ENV.
6651 debug_printf("running script '%s'\n", argv[optind]);
6652 G.global_argv = argv + optind;
6653 G.global_argc = argc - optind;
6654 input = xfopen_for_read(argv[optind]);
6655 close_on_exec_on(fileno(input));
6656 if (!signal_mask_is_inited)
6657 block_signals(0); /* 0: called 1st time */
6658 parse_and_run_file(input);
6659 #if ENABLE_FEATURE_CLEAN_UP
6665 /* Up to here, shell was non-interactive. Now it may become one.
6666 * NB: don't forget to (re)run block_signals(0/1) as needed.
6669 /* A shell is interactive if the '-i' flag was given,
6670 * or if all of the following conditions are met:
6672 * no arguments remaining or the -s flag given
6673 * standard input is a terminal
6674 * standard output is a terminal
6675 * Refer to Posix.2, the description of the 'sh' utility.
6678 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6679 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6680 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6681 if (G_saved_tty_pgrp < 0)
6682 G_saved_tty_pgrp = 0;
6684 /* try to dup stdin to high fd#, >= 255 */
6685 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6686 if (G_interactive_fd < 0) {
6687 /* try to dup to any fd */
6688 G_interactive_fd = dup(STDIN_FILENO);
6689 if (G_interactive_fd < 0) {
6691 G_interactive_fd = 0;
6692 G_saved_tty_pgrp = 0;
6695 // TODO: track & disallow any attempts of user
6696 // to (inadvertently) close/redirect G_interactive_fd
6698 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6699 if (G_interactive_fd) {
6700 close_on_exec_on(G_interactive_fd);
6702 if (G_saved_tty_pgrp) {
6703 /* If we were run as 'hush &', sleep until we are
6704 * in the foreground (tty pgrp == our pgrp).
6705 * If we get started under a job aware app (like bash),
6706 * make sure we are now in charge so we don't fight over
6707 * who gets the foreground */
6709 pid_t shell_pgrp = getpgrp();
6710 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6711 if (G_saved_tty_pgrp == shell_pgrp)
6713 /* send TTIN to ourself (should stop us) */
6714 kill(- shell_pgrp, SIGTTIN);
6718 /* Block some signals */
6719 block_signals(signal_mask_is_inited);
6721 if (G_saved_tty_pgrp) {
6722 /* Set other signals to restore saved_tty_pgrp */
6723 set_fatal_handlers();
6724 /* Put ourselves in our own process group
6725 * (bash, too, does this only if ctty is available) */
6726 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6727 /* Grab control of the terminal */
6728 tcsetpgrp(G_interactive_fd, getpid());
6730 /* -1 is special - makes xfuncs longjmp, not exit
6731 * (we reset die_sleep = 0 whereever we [v]fork) */
6732 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6733 } else if (!signal_mask_is_inited) {
6734 block_signals(0); /* 0: called 1st time */
6735 } /* else: block_signals(0) was done before */
6736 #elif ENABLE_HUSH_INTERACTIVE
6737 /* No job control compiled in, only prompt/line editing */
6738 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6739 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6740 if (G_interactive_fd < 0) {
6741 /* try to dup to any fd */
6742 G_interactive_fd = dup(STDIN_FILENO);
6743 if (G_interactive_fd < 0)
6745 G_interactive_fd = 0;
6748 if (G_interactive_fd) {
6749 close_on_exec_on(G_interactive_fd);
6750 block_signals(signal_mask_is_inited);
6751 } else if (!signal_mask_is_inited) {
6755 /* We have interactiveness code disabled */
6756 if (!signal_mask_is_inited) {
6761 * if interactive but not a login shell, sources ~/.bashrc
6762 * (--norc turns this off, --rcfile <file> overrides)
6765 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6766 printf("\n\n%s hush - the humble shell\n", bb_banner);
6767 if (ENABLE_HUSH_HELP)
6768 puts("Enter 'help' for a list of built-in commands.");
6772 parse_and_run_file(stdin);
6775 #if ENABLE_FEATURE_CLEAN_UP
6776 if (G.cwd != bb_msg_unknown)
6778 cur_var = G.top_var->next;
6780 struct variable *tmp = cur_var;
6781 if (!cur_var->max_len)
6782 free(cur_var->varstr);
6783 cur_var = cur_var->next;
6787 hush_exit(G.last_exitcode);
6792 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6793 int lash_main(int argc, char **argv)
6795 bb_error_msg("lash is deprecated, please use hush instead");
6796 return hush_main(argc, argv);
6801 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6802 int msh_main(int argc, char **argv)
6804 //bb_error_msg("msh is deprecated, please use hush instead");
6805 return hush_main(argc, argv);
6813 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6818 static int FAST_FUNC builtin_test(char **argv)
6825 return test_main(argc, argv - argc);
6828 static int FAST_FUNC builtin_echo(char **argv)
6835 return echo_main(argc, argv - argc);
6838 static int FAST_FUNC builtin_eval(char **argv)
6840 int rcode = EXIT_SUCCESS;
6843 char *str = expand_strvec_to_string(argv);
6845 * eval "echo Hi; done" ("done" is syntax error):
6846 * "echo Hi" will not execute too.
6848 parse_and_run_string(str);
6850 rcode = G.last_exitcode;
6855 static int FAST_FUNC builtin_cd(char **argv)
6857 const char *newdir = argv[1];
6858 if (newdir == NULL) {
6859 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6860 * bash says "bash: cd: HOME not set" and does nothing
6863 const char *home = get_local_var_value("HOME");
6864 newdir = home ? home : "/";
6866 if (chdir(newdir)) {
6867 /* Mimic bash message exactly */
6868 bb_perror_msg("cd: %s", newdir);
6869 return EXIT_FAILURE;
6871 /* Read current dir (get_cwd(1) is inside) and set PWD.
6872 * Note: do not enforce exporting. If PWD was unset or unexported,
6873 * set it again, but do not export. bash does the same.
6875 set_pwd_var(/*exp:*/ 0);
6876 return EXIT_SUCCESS;
6879 static int FAST_FUNC builtin_exec(char **argv)
6881 if (*++argv == NULL)
6882 return EXIT_SUCCESS; /* bash does this */
6887 /* TODO: if exec fails, bash does NOT exit! We do... */
6888 pseudo_exec_argv(&dummy, argv, 0, NULL);
6893 static int FAST_FUNC builtin_exit(char **argv)
6895 debug_printf_exec("%s()\n", __func__);
6897 /* interactive bash:
6898 * # trap "echo EEE" EXIT
6901 * There are stopped jobs.
6902 * (if there are _stopped_ jobs, running ones don't count)
6905 # EEE (then bash exits)
6907 * we can use G.exiting = -1 as indicator "last cmd was exit"
6910 /* note: EXIT trap is run by hush_exit */
6911 if (*++argv == NULL)
6912 hush_exit(G.last_exitcode);
6913 /* mimic bash: exit 123abc == exit 255 + error msg */
6914 xfunc_error_retval = 255;
6915 /* bash: exit -2 == exit 254, no error msg */
6916 hush_exit(xatoi(*argv) & 0xff);
6919 static void print_escaped(const char *s)
6924 const char *p = strchrnul(s, '\'');
6925 /* print 'xxxx', possibly just '' */
6926 printf("'%.*s'", (int)(p - s), s);
6931 /* s points to '; print "'''...'''" */
6933 do putchar('\''); while (*++s == '\'');
6938 #if !ENABLE_HUSH_LOCAL
6939 #define helper_export_local(argv, exp, lvl) \
6940 helper_export_local(argv, exp)
6942 static void helper_export_local(char **argv, int exp, int lvl)
6947 /* So far we do not check that name is valid (TODO?) */
6949 if (strchr(name, '=') == NULL) {
6950 struct variable *var;
6952 var = get_local_var(name);
6953 if (exp == -1) { /* unexporting? */
6954 /* export -n NAME (without =VALUE) */
6956 var->flg_export = 0;
6957 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6959 } /* else: export -n NOT_EXISTING_VAR: no-op */
6962 if (exp == 1) { /* exporting? */
6963 /* export NAME (without =VALUE) */
6965 var->flg_export = 1;
6966 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6967 putenv(var->varstr);
6971 /* Exporting non-existing variable.
6972 * bash does not put it in environment,
6973 * but remembers that it is exported,
6974 * and does put it in env when it is set later.
6975 * We just set it to "" and export. */
6976 /* Or, it's "local NAME" (without =VALUE).
6977 * bash sets the value to "". */
6978 name = xasprintf("%s=", name);
6980 /* (Un)exporting/making local NAME=VALUE */
6981 name = xstrdup(name);
6983 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6987 static int FAST_FUNC builtin_export(char **argv)
6989 unsigned opt_unexport;
6991 #if ENABLE_HUSH_EXPORT_N
6992 /* "!": do not abort on errors */
6993 opt_unexport = getopt32(argv, "!n");
6994 if (opt_unexport == (uint32_t)-1)
6995 return EXIT_FAILURE;
7002 if (argv[0] == NULL) {
7009 /* ash emits: export VAR='VAL'
7010 * bash: declare -x VAR="VAL"
7011 * we follow ash example */
7012 const char *s = *e++;
7013 const char *p = strchr(s, '=');
7015 if (!p) /* wtf? take next variable */
7018 printf("export %.*s", (int)(p - s) + 1, s);
7019 print_escaped(p + 1);
7023 /*fflush(stdout); - done after each builtin anyway */
7025 return EXIT_SUCCESS;
7028 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7030 return EXIT_SUCCESS;
7033 #if ENABLE_HUSH_LOCAL
7034 static int FAST_FUNC builtin_local(char **argv)
7036 if (G.func_nest_level == 0) {
7037 bb_error_msg("%s: not in a function", argv[0]);
7038 return EXIT_FAILURE; /* bash compat */
7040 helper_export_local(argv, 0, G.func_nest_level);
7041 return EXIT_SUCCESS;
7045 static int FAST_FUNC builtin_trap(char **argv)
7051 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7056 /* No args: print all trapped */
7057 for (i = 0; i < NSIG; ++i) {
7060 print_escaped(G.traps[i]);
7061 printf(" %s\n", get_signame(i));
7064 /*fflush(stdout); - done after each builtin anyway */
7065 return EXIT_SUCCESS;
7069 /* If first arg is a number: reset all specified signals */
7070 sig = bb_strtou(*argv, NULL, 10);
7076 sig = get_signum(*argv++);
7077 if (sig < 0 || sig >= NSIG) {
7079 /* Mimic bash message exactly */
7080 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7085 G.traps[sig] = xstrdup(new_cmd);
7087 debug_printf("trap: setting SIG%s (%i) to '%s'",
7088 get_signame(sig), sig, G.traps[sig]);
7090 /* There is no signal for 0 (EXIT) */
7095 sigaddset(&G.blocked_set, sig);
7097 /* There was a trap handler, we are removing it
7098 * (if sig has non-DFL handling,
7099 * we don't need to do anything) */
7100 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7102 sigdelset(&G.blocked_set, sig);
7105 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7109 if (!argv[1]) { /* no second arg */
7110 bb_error_msg("trap: invalid arguments");
7111 return EXIT_FAILURE;
7114 /* First arg is "-": reset all specified to default */
7115 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7116 /* Everything else: set arg as signal handler
7117 * (includes "" case, which ignores signal) */
7118 if (argv[0][0] == '-') {
7119 if (argv[0][1] == '\0') { /* "-" */
7120 /* new_cmd remains NULL: "reset these sigs" */
7123 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7126 /* else: "-something", no special meaning */
7131 goto process_sig_list;
7134 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7135 static int FAST_FUNC builtin_type(char **argv)
7137 int ret = EXIT_SUCCESS;
7143 if (0) {} /* make conditional compile easier below */
7144 /*else if (find_alias(*argv))
7145 type = "an alias";*/
7146 #if ENABLE_HUSH_FUNCTIONS
7147 else if (find_function(*argv))
7148 type = "a function";
7150 else if (find_builtin(*argv))
7151 type = "a shell builtin";
7152 else if ((path = find_in_path(*argv)) != NULL)
7155 bb_error_msg("type: %s: not found", *argv);
7160 printf("%s is %s\n", *argv, type);
7168 /* built-in 'fg' and 'bg' handler */
7169 static int FAST_FUNC builtin_fg_bg(char **argv)
7174 if (!G_interactive_fd)
7175 return EXIT_FAILURE;
7177 /* If they gave us no args, assume they want the last backgrounded task */
7179 for (pi = G.job_list; pi; pi = pi->next) {
7180 if (pi->jobid == G.last_jobid) {
7184 bb_error_msg("%s: no current job", argv[0]);
7185 return EXIT_FAILURE;
7187 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7188 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7189 return EXIT_FAILURE;
7191 for (pi = G.job_list; pi; pi = pi->next) {
7192 if (pi->jobid == jobnum) {
7196 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7197 return EXIT_FAILURE;
7199 /* TODO: bash prints a string representation
7200 * of job being foregrounded (like "sleep 1 | cat") */
7201 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7202 /* Put the job into the foreground. */
7203 tcsetpgrp(G_interactive_fd, pi->pgrp);
7206 /* Restart the processes in the job */
7207 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7208 for (i = 0; i < pi->num_cmds; i++) {
7209 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7210 pi->cmds[i].is_stopped = 0;
7212 pi->stopped_cmds = 0;
7214 i = kill(- pi->pgrp, SIGCONT);
7216 if (errno == ESRCH) {
7217 delete_finished_bg_job(pi);
7218 return EXIT_SUCCESS;
7220 bb_perror_msg("kill (SIGCONT)");
7223 if (argv[0][0] == 'f') {
7225 return checkjobs_and_fg_shell(pi);
7227 return EXIT_SUCCESS;
7231 #if ENABLE_HUSH_HELP
7232 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7234 const struct built_in_command *x;
7237 "Built-in commands:\n"
7238 "------------------\n");
7239 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7241 printf("%s\t%s\n", x->cmd, x->descr);
7244 return EXIT_SUCCESS;
7249 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7252 const char *status_string;
7254 for (job = G.job_list; job; job = job->next) {
7255 if (job->alive_cmds == job->stopped_cmds)
7256 status_string = "Stopped";
7258 status_string = "Running";
7260 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7262 return EXIT_SUCCESS;
7267 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7272 /* Crude attempt to find where "free memory" starts,
7273 * sans fragmentation. */
7275 l = (unsigned long)p;
7278 if (l < (unsigned long)p) l = (unsigned long)p;
7281 if (!G.memleak_value)
7282 G.memleak_value = l;
7284 l -= G.memleak_value;
7291 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7296 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7299 return EXIT_SUCCESS;
7302 static int FAST_FUNC builtin_read(char **argv)
7305 const char *name = "REPLY";
7309 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7310 * and _after_ that_ it will complain */
7311 if (!is_well_formed_var_name(name, '\0')) {
7312 /* Mimic bash message */
7313 bb_error_msg("read: '%s': not a valid identifier", name);
7318 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7320 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7321 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7324 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7325 * built-in 'set' handler
7327 * set [-abCefhmnuvx] [-o option] [argument...]
7328 * set [+abCefhmnuvx] [+o option] [argument...]
7329 * set -- [argument...]
7332 * Implementations shall support the options in both their hyphen and
7333 * plus-sign forms. These options can also be specified as options to sh.
7335 * Write out all variables and their values: set
7336 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7337 * Turn on the -x and -v options: set -xv
7338 * Unset all positional parameters: set --
7339 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7340 * Set the positional parameters to the expansion of x, even if x expands
7341 * with a leading '-' or '+': set -- $x
7343 * So far, we only support "set -- [argument...]" and some of the short names.
7345 static int FAST_FUNC builtin_set(char **argv)
7348 char **pp, **g_argv;
7349 char *arg = *++argv;
7353 for (e = G.top_var; e; e = e->next)
7355 return EXIT_SUCCESS;
7359 if (!strcmp(arg, "--")) {
7363 if (arg[0] != '+' && arg[0] != '-')
7365 for (n = 1; arg[n]; ++n)
7366 if (set_mode(arg[0], arg[n]))
7368 } while ((arg = *++argv) != NULL);
7369 /* Now argv[0] is 1st argument */
7372 return EXIT_SUCCESS;
7375 /* NB: G.global_argv[0] ($0) is never freed/changed */
7376 g_argv = G.global_argv;
7377 if (G.global_args_malloced) {
7383 G.global_args_malloced = 1;
7384 pp = xzalloc(sizeof(pp[0]) * 2);
7385 pp[0] = g_argv[0]; /* retain $0 */
7388 /* This realloc's G.global_argv */
7389 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7396 return EXIT_SUCCESS;
7398 /* Nothing known, so abort */
7400 bb_error_msg("set: %s: invalid option", arg);
7401 return EXIT_FAILURE;
7404 static int FAST_FUNC builtin_shift(char **argv)
7410 if (n >= 0 && n < G.global_argc) {
7411 if (G.global_args_malloced) {
7414 free(G.global_argv[m++]);
7417 memmove(&G.global_argv[1], &G.global_argv[n+1],
7418 G.global_argc * sizeof(G.global_argv[0]));
7419 return EXIT_SUCCESS;
7421 return EXIT_FAILURE;
7424 static int FAST_FUNC builtin_source(char **argv)
7429 #if ENABLE_HUSH_FUNCTIONS
7433 if (*++argv == NULL)
7434 return EXIT_FAILURE;
7436 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7437 input = fopen_for_read(arg_path);
7440 input = fopen_or_warn(*argv, "r");
7442 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7443 return EXIT_FAILURE;
7445 close_on_exec_on(fileno(input));
7447 #if ENABLE_HUSH_FUNCTIONS
7448 sv_flg = G.flag_return_in_progress;
7449 /* "we are inside sourced file, ok to use return" */
7450 G.flag_return_in_progress = -1;
7452 save_and_replace_G_args(&sv, argv);
7454 parse_and_run_file(input);
7457 restore_G_args(&sv, argv);
7458 #if ENABLE_HUSH_FUNCTIONS
7459 G.flag_return_in_progress = sv_flg;
7462 return G.last_exitcode;
7465 static int FAST_FUNC builtin_umask(char **argv)
7472 mode_t old_mask = mask;
7475 rc = bb_parse_mode(argv[1], &mask);
7480 * bash: umask: 'q': invalid symbolic mode operator
7481 * bash: umask: 999: octal number out of range
7483 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7488 printf("%04o\n", (unsigned) mask);
7489 /* fall through and restore mask which we set to 0 */
7493 return !rc; /* rc != 0 - success */
7496 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7497 static int FAST_FUNC builtin_unset(char **argv)
7502 /* "!": do not abort on errors */
7503 /* "+": stop at 1st non-option */
7504 opts = getopt32(argv, "!+vf");
7505 if (opts == (unsigned)-1)
7506 return EXIT_FAILURE;
7508 bb_error_msg("unset: -v and -f are exclusive");
7509 return EXIT_FAILURE;
7515 if (!(opts & 2)) { /* not -f */
7516 if (unset_local_var(*argv)) {
7517 /* unset <nonexistent_var> doesn't fail.
7518 * Error is when one tries to unset RO var.
7519 * Message was printed by unset_local_var. */
7523 #if ENABLE_HUSH_FUNCTIONS
7533 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7534 static int FAST_FUNC builtin_wait(char **argv)
7536 int ret = EXIT_SUCCESS;
7539 if (*++argv == NULL) {
7540 /* Don't care about wait results */
7541 /* Note 1: must wait until there are no more children */
7542 /* Note 2: must be interruptible */
7544 * $ sleep 3 & sleep 6 & wait
7549 * $ sleep 3 & sleep 6 & wait
7553 * ^C <-- after ~4 sec from keyboard
7556 sigaddset(&G.blocked_set, SIGCHLD);
7557 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7560 if (errno == ECHILD)
7562 /* Wait for SIGCHLD or any other signal of interest */
7563 /* sigtimedwait with infinite timeout: */
7564 sig = sigwaitinfo(&G.blocked_set, NULL);
7566 sig = check_and_run_traps(sig);
7567 if (sig && sig != SIGCHLD) { /* see note 2 */
7573 sigdelset(&G.blocked_set, SIGCHLD);
7574 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7578 /* This is probably buggy wrt interruptible-ness */
7580 pid_t pid = bb_strtou(*argv, NULL, 10);
7582 /* mimic bash message */
7583 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7584 return EXIT_FAILURE;
7586 if (waitpid(pid, &status, 0) == pid) {
7587 if (WIFSIGNALED(status))
7588 ret = 128 + WTERMSIG(status);
7589 else if (WIFEXITED(status))
7590 ret = WEXITSTATUS(status);
7594 bb_perror_msg("wait %s", *argv);
7603 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7604 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7607 def = bb_strtou(argv[1], NULL, 10);
7608 if (errno || def < def_min || argv[2]) {
7609 bb_error_msg("%s: bad arguments", argv[0]);
7617 #if ENABLE_HUSH_LOOPS
7618 static int FAST_FUNC builtin_break(char **argv)
7621 if (G.depth_of_loop == 0) {
7622 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7623 return EXIT_SUCCESS; /* bash compat */
7625 G.flag_break_continue++; /* BC_BREAK = 1 */
7627 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7628 if (depth == UINT_MAX)
7629 G.flag_break_continue = BC_BREAK;
7630 if (G.depth_of_loop < depth)
7631 G.depth_break_continue = G.depth_of_loop;
7633 return EXIT_SUCCESS;
7636 static int FAST_FUNC builtin_continue(char **argv)
7638 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7639 return builtin_break(argv);
7643 #if ENABLE_HUSH_FUNCTIONS
7644 static int FAST_FUNC builtin_return(char **argv)
7648 if (G.flag_return_in_progress != -1) {
7649 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7650 return EXIT_FAILURE; /* bash compat */
7653 G.flag_return_in_progress = 1;
7656 * out of range: wraps around at 256, does not error out
7657 * non-numeric param:
7658 * f() { false; return qwe; }; f; echo $?
7659 * bash: return: qwe: numeric argument required <== we do this
7660 * 255 <== we also do this
7662 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);