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 * follow IFS rules more precisely, including update semantics
62 * export builtin should be special, its arguments are assignments
63 * and therefore expansion of them should be "one-word" expansion:
64 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
66 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
67 * ls: cannot access i=a: No such file or directory
68 * ls: cannot access b: No such file or directory
69 * Note1: same applies to local builtin.
70 * Note2: bash 3.2.33(1) does this only if export word itself
72 * $ export i=`echo 'aaa bbb'`; echo "$i"
74 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
79 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
81 /* #include <dmalloc.h> */
88 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
93 #define LEAK_HUNTING 0
94 #define BUILD_AS_NOMMU 0
95 /* Enable/disable sanity checks. Ok to enable in production,
96 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
97 * Keeping 1 for now even in released versions.
100 /* Slightly bigger (+200 bytes), but faster hush.
101 * So far it only enables a trick with counting SIGCHLDs and forks,
102 * which allows us to do fewer waitpid's.
103 * (we can detect a case where neither forks were done nor SIGCHLDs happened
104 * and therefore waitpid will return the same result as last time)
106 #define ENABLE_HUSH_FAST 0
111 # undef USE_FOR_NOMMU
114 # define USE_FOR_NOMMU(...) __VA_ARGS__
115 # define USE_FOR_MMU(...)
118 #if defined SINGLE_APPLET_MAIN
119 /* STANDALONE does not make sense, and won't compile */
120 # undef CONFIG_FEATURE_SH_STANDALONE
121 # undef ENABLE_FEATURE_SH_STANDALONE
122 # undef IF_FEATURE_SH_STANDALONE
123 # define IF_FEATURE_SH_STANDALONE(...)
124 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
125 # define ENABLE_FEATURE_SH_STANDALONE 0
128 #if !ENABLE_HUSH_INTERACTIVE
129 # undef ENABLE_FEATURE_EDITING
130 # define ENABLE_FEATURE_EDITING 0
131 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
132 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
135 /* Do we support ANY keywords? */
136 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
137 # define HAS_KEYWORDS 1
138 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
139 # define IF_HAS_NO_KEYWORDS(...)
141 # define HAS_KEYWORDS 0
142 # define IF_HAS_KEYWORDS(...)
143 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
146 /* If you comment out one of these below, it will be #defined later
147 * to perform debug printfs to stderr: */
148 #define debug_printf(...) do {} while (0)
149 /* Finer-grained debug switches */
150 #define debug_printf_parse(...) do {} while (0)
151 #define debug_print_tree(a, b) do {} while (0)
152 #define debug_printf_exec(...) do {} while (0)
153 #define debug_printf_env(...) do {} while (0)
154 #define debug_printf_jobs(...) do {} while (0)
155 #define debug_printf_expand(...) do {} while (0)
156 #define debug_printf_glob(...) do {} while (0)
157 #define debug_printf_list(...) do {} while (0)
158 #define debug_printf_subst(...) do {} while (0)
159 #define debug_printf_clean(...) do {} while (0)
161 #define ERR_PTR ((void*)(long)1)
163 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
165 #define SPECIAL_VAR_SYMBOL 3
169 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
171 /* This supports saving pointers malloced in vfork child,
172 * to be freed in the parent.
175 typedef struct nommu_save_t {
177 struct variable *old_vars;
179 char **argv_from_re_execing;
183 typedef enum reserved_style {
192 #if ENABLE_HUSH_LOOPS
199 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
204 /* three pseudo-keywords support contrived "case" syntax: */
205 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
206 RES_MATCH , /* "word)" */
207 RES_CASE_BODY, /* "this command is inside CASE" */
214 typedef struct o_string {
216 int length; /* position where data is appended */
218 /* Protect newly added chars against globbing
219 * (by prepending \ to *, ?, [, \) */
222 /* At least some part of the string was inside '' or "",
223 * possibly empty one: word"", wo''rd etc. */
225 smallint has_empty_slot;
226 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
229 MAYBE_ASSIGNMENT = 0,
230 DEFINITELY_ASSIGNMENT = 1,
232 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
234 /* Used for initialization: o_string foo = NULL_O_STRING; */
235 #define NULL_O_STRING { NULL }
237 /* I can almost use ordinary FILE*. Is open_memstream() universally
238 * available? Where is it documented? */
239 typedef struct in_str {
241 /* eof_flag=1: last char in ->p is really an EOF */
242 char eof_flag; /* meaningless if ->p == NULL */
244 #if ENABLE_HUSH_INTERACTIVE
246 smallint promptmode; /* 0: PS1, 1: PS2 */
249 int (*get) (struct in_str *) FAST_FUNC;
250 int (*peek) (struct in_str *) FAST_FUNC;
252 #define i_getch(input) ((input)->get(input))
253 #define i_peek(input) ((input)->peek(input))
255 /* The descrip member of this structure is only used to make
256 * debugging output pretty */
257 static const struct {
259 signed char default_fd;
262 { O_RDONLY, 0, "<" },
263 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
264 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
265 { O_CREAT|O_RDWR, 1, "<>" },
266 { O_RDONLY, 0, "<<" },
267 /* Should not be needed. Bogus default_fd helps in debugging */
268 /* { O_RDONLY, 77, "<<" }, */
271 struct redir_struct {
272 struct redir_struct *next;
273 char *rd_filename; /* filename */
274 int rd_fd; /* fd to redirect */
275 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
277 smallint rd_type; /* (enum redir_type) */
278 /* note: for heredocs, rd_filename contains heredoc delimiter,
279 * and subsequently heredoc itself; and rd_dup is a bitmask:
280 * bit 0: do we need to trim leading tabs?
281 * bit 1: is heredoc quoted (<<'delim' syntax) ?
284 typedef enum redir_type {
286 REDIRECT_OVERWRITE = 1,
289 REDIRECT_HEREDOC = 4,
290 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
293 REDIRFD_SYNTAX_ERR = -2,
294 REDIRFD_TO_FILE = -1,
295 /* otherwise, rd_fd is redirected to rd_dup */
297 HEREDOC_SKIPTABS = 1,
303 pid_t pid; /* 0 if exited */
304 int assignment_cnt; /* how many argv[i] are assignments? */
305 smallint is_stopped; /* is the command currently running? */
306 smallint cmd_type; /* CMD_xxx */
308 #define CMD_SUBSHELL 1
310 /* used for "[[ EXPR ]]" */
311 #if ENABLE_HUSH_BASH_COMPAT
312 # define CMD_SINGLEWORD_NOGLOB 2
314 // Basically, word splitting and pathname expansion should NOT be performed
316 // no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
317 // no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
318 // Additional operators:
319 // || and && should work as -o and -a
321 // == should do _pattern match_ against right side. bash does this:
322 // # [[ *a* == bab ]] && echo YES
323 // # [[ bab == *a* ]] && echo YES
325 // != does the negated == (i.e., also with pattern matching)
326 // Apart from the above, [[ expr ]] should work as [ expr ]
328 /* used for "export noglob=* glob* a=`echo a b`" */
329 /*#define CMD_SINGLEWORD_NOGLOB_COND 3 */
330 // It is hard to implement correctly, it adds significant amounts of tricky code,
331 // and all this is only useful for really obscure export statements
332 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
333 // guards the code which implements it, but I have doubts it works
334 // in all cases (especially with mixed globbed/non-globbed arguments)
336 #if ENABLE_HUSH_FUNCTIONS
337 # define CMD_FUNCDEF 3
340 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
343 char *group_as_string;
345 #if ENABLE_HUSH_FUNCTIONS
346 struct function *child_func;
347 /* This field is used to prevent a bug here:
348 * while...do f1() {a;}; f1; f1() {b;}; f1; done
349 * When we execute "f1() {a;}" cmd, we create new function and clear
350 * cmd->group, cmd->group_as_string, cmd->argv[0].
351 * When we execute "f1() {b;}", we notice that f1 exists,
352 * and that its "parent cmd" struct is still "alive",
353 * we put those fields back into cmd->xxx
354 * (struct function has ->parent_cmd ptr to facilitate that).
355 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
356 * Without this trick, loop would execute a;b;b;b;...
357 * instead of correct sequence a;b;a;b;...
358 * When command is freed, it severs the link
359 * (sets ->child_func->parent_cmd to NULL).
362 char **argv; /* command name and arguments */
363 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
364 * and on execution these are substituted with their values.
365 * Substitution can make _several_ words out of one argv[n]!
366 * Example: argv[0]=='.^C*^C.' here: echo .$*.
367 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
369 struct redir_struct *redirects; /* I/O redirections */
371 /* Is there anything in this command at all? */
372 #define IS_NULL_CMD(cmd) \
373 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
378 int num_cmds; /* total number of commands in pipe */
379 int alive_cmds; /* number of commands running (not exited) */
380 int stopped_cmds; /* number of commands alive, but stopped */
382 int jobid; /* job number */
383 pid_t pgrp; /* process group ID for the job */
384 char *cmdtext; /* name of job */
386 struct command *cmds; /* array of commands in pipe */
387 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
388 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
389 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
391 typedef enum pipe_style {
397 /* Is there anything in this pipe at all? */
398 #define IS_NULL_PIPE(pi) \
399 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
401 /* This holds pointers to the various results of parsing */
402 struct parse_context {
403 /* linked list of pipes */
404 struct pipe *list_head;
405 /* last pipe (being constructed right now) */
407 /* last command in pipe (being constructed right now) */
408 struct command *command;
409 /* last redirect in command->redirects list */
410 struct redir_struct *pending_redirect;
416 smallint ctx_inverted; /* "! cmd | cmd" */
418 smallint ctx_dsemicolon; /* ";;" seen */
420 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
422 /* group we are enclosed in:
423 * example: "if pipe1; pipe2; then pipe3; fi"
424 * when we see "if" or "then", we malloc and copy current context,
425 * and make ->stack point to it. then we parse pipeN.
426 * when closing "then" / fi" / whatever is found,
427 * we move list_head into ->stack->command->group,
428 * copy ->stack into current context, and delete ->stack.
429 * (parsing of { list } and ( list ) doesn't use this method)
431 struct parse_context *stack;
435 /* On program start, environ points to initial environment.
436 * putenv adds new pointers into it, unsetenv removes them.
437 * Neither of these (de)allocates the strings.
438 * setenv allocates new strings in malloc space and does putenv,
439 * and thus setenv is unusable (leaky) for shell's purposes */
440 #define setenv(...) setenv_is_leaky_dont_use()
442 struct variable *next;
443 char *varstr; /* points to "name=" portion */
444 #if ENABLE_HUSH_LOCAL
445 unsigned func_nest_level;
447 int max_len; /* if > 0, name is part of initial env; else name is malloced */
448 smallint flg_export; /* putenv should be done on this var */
449 smallint flg_read_only;
457 #if ENABLE_HUSH_FUNCTIONS
459 struct function *next;
461 struct command *parent_cmd;
464 char *body_as_string;
470 /* "Globals" within this file */
471 /* Sorted roughly by size (smaller offsets == smaller code) */
473 /* interactive_fd != 0 means we are an interactive shell.
474 * If we are, then saved_tty_pgrp can also be != 0, meaning
475 * that controlling tty is available. With saved_tty_pgrp == 0,
476 * job control still works, but terminal signals
477 * (^C, ^Z, ^Y, ^\) won't work at all, and background
478 * process groups can only be created with "cmd &".
479 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
480 * to give tty to the foreground process group,
481 * and will take it back when the group is stopped (^Z)
484 #if ENABLE_HUSH_INTERACTIVE
485 /* 'interactive_fd' is a fd# open to ctty, if we have one
486 * _AND_ if we decided to act interactively */
490 # define G_interactive_fd (G.interactive_fd)
492 # define G_interactive_fd 0
494 #if ENABLE_FEATURE_EDITING
495 line_input_t *line_input_state;
502 pid_t saved_tty_pgrp;
503 struct pipe *job_list;
504 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
506 # define G_saved_tty_pgrp 0
508 smallint flag_SIGINT;
509 #if ENABLE_HUSH_LOOPS
510 smallint flag_break_continue;
512 #if ENABLE_HUSH_FUNCTIONS
513 /* 0: outside of a function (or sourced file)
514 * -1: inside of a function, ok to use return builtin
515 * 1: return is invoked, skip all till end of func
517 smallint flag_return_in_progress;
520 smallint exiting; /* used to prevent EXIT trap recursion */
521 /* These four support $?, $#, and $1 */
522 smalluint last_exitcode;
523 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
524 smalluint global_args_malloced;
525 /* how many non-NULL argv's we have. NB: $# + 1 */
529 char *argv0_for_re_execing;
531 #if ENABLE_HUSH_LOOPS
532 unsigned depth_break_continue;
533 unsigned depth_of_loop;
537 struct variable *top_var; /* = &G.shell_ver (set in main()) */
538 struct variable shell_ver;
539 #if ENABLE_HUSH_FUNCTIONS
540 struct function *top_func;
541 # if ENABLE_HUSH_LOCAL
542 struct variable **shadowed_vars_pp;
543 unsigned func_nest_level;
546 /* Signal and trap handling */
548 unsigned count_SIGCHLD;
549 unsigned handled_SIGCHLD;
550 smallint we_have_children;
552 /* which signals have non-DFL handler (even with no traps set)? */
553 unsigned non_DFL_mask;
554 char **traps; /* char *traps[NSIG] */
555 sigset_t blocked_set;
556 sigset_t inherited_set;
558 unsigned long memleak_value;
561 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
563 #define G (*ptr_to_globals)
564 /* Not #defining name to G.name - this quickly gets unwieldy
565 * (too many defines). Also, I actually prefer to see when a variable
566 * is global, thus "G." prefix is a useful hint */
567 #define INIT_G() do { \
568 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
572 /* Function prototypes for builtins */
573 static int builtin_cd(char **argv) FAST_FUNC;
574 static int builtin_echo(char **argv) FAST_FUNC;
575 static int builtin_eval(char **argv) FAST_FUNC;
576 static int builtin_exec(char **argv) FAST_FUNC;
577 static int builtin_exit(char **argv) FAST_FUNC;
578 static int builtin_export(char **argv) FAST_FUNC;
580 static int builtin_fg_bg(char **argv) FAST_FUNC;
581 static int builtin_jobs(char **argv) FAST_FUNC;
584 static int builtin_help(char **argv) FAST_FUNC;
586 #if ENABLE_HUSH_LOCAL
587 static int builtin_local(char **argv) FAST_FUNC;
590 static int builtin_memleak(char **argv) FAST_FUNC;
592 static int builtin_pwd(char **argv) FAST_FUNC;
593 static int builtin_read(char **argv) FAST_FUNC;
594 static int builtin_set(char **argv) FAST_FUNC;
595 static int builtin_shift(char **argv) FAST_FUNC;
596 static int builtin_source(char **argv) FAST_FUNC;
597 static int builtin_test(char **argv) FAST_FUNC;
598 static int builtin_trap(char **argv) FAST_FUNC;
599 static int builtin_type(char **argv) FAST_FUNC;
600 static int builtin_true(char **argv) FAST_FUNC;
601 static int builtin_umask(char **argv) FAST_FUNC;
602 static int builtin_unset(char **argv) FAST_FUNC;
603 static int builtin_wait(char **argv) FAST_FUNC;
604 #if ENABLE_HUSH_LOOPS
605 static int builtin_break(char **argv) FAST_FUNC;
606 static int builtin_continue(char **argv) FAST_FUNC;
608 #if ENABLE_HUSH_FUNCTIONS
609 static int builtin_return(char **argv) FAST_FUNC;
612 /* Table of built-in functions. They can be forked or not, depending on
613 * context: within pipes, they fork. As simple commands, they do not.
614 * When used in non-forking context, they can change global variables
615 * in the parent shell process. If forked, of course they cannot.
616 * For example, 'unset foo | whatever' will parse and run, but foo will
617 * still be set at the end. */
618 struct built_in_command {
620 int (*function)(char **argv) FAST_FUNC;
623 # define BLTIN(cmd, func, help) { cmd, func, help }
625 # define BLTIN(cmd, func, help) { cmd, func }
629 static const struct built_in_command bltins1[] = {
630 BLTIN("." , builtin_source , "Run commands in a file"),
631 BLTIN(":" , builtin_true , NULL),
633 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
635 #if ENABLE_HUSH_LOOPS
636 BLTIN("break" , builtin_break , "Exit from a loop"),
638 BLTIN("cd" , builtin_cd , "Change directory"),
639 #if ENABLE_HUSH_LOOPS
640 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
642 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
643 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
644 BLTIN("exit" , builtin_exit , "Exit"),
645 BLTIN("export" , builtin_export , "Set environment variables"),
647 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
650 BLTIN("help" , builtin_help , NULL),
653 BLTIN("jobs" , builtin_jobs , "List jobs"),
655 #if ENABLE_HUSH_LOCAL
656 BLTIN("local" , builtin_local , "Set local variables"),
659 BLTIN("memleak" , builtin_memleak , NULL),
661 BLTIN("read" , builtin_read , "Input into variable"),
662 #if ENABLE_HUSH_FUNCTIONS
663 BLTIN("return" , builtin_return , "Return from a function"),
665 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
666 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
667 BLTIN("trap" , builtin_trap , "Trap signals"),
668 BLTIN("type" , builtin_type , "Write a description of command type"),
669 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
670 BLTIN("umask" , builtin_umask , "Set file creation mask"),
671 BLTIN("unset" , builtin_unset , "Unset variables"),
672 BLTIN("wait" , builtin_wait , "Wait for process"),
674 /* For now, echo and test are unconditionally enabled.
675 * Maybe make it configurable? */
676 static const struct built_in_command bltins2[] = {
677 BLTIN("[" , builtin_test , NULL),
678 BLTIN("echo" , builtin_echo , NULL),
679 BLTIN("pwd" , builtin_pwd , NULL),
680 BLTIN("test" , builtin_test , NULL),
687 /* prevent disasters with G.debug_indent < 0 */
688 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
689 # define debug_enter() (G.debug_indent++)
690 # define debug_leave() (G.debug_indent--)
692 # define indent() ((void)0)
693 # define debug_enter() ((void)0)
694 # define debug_leave() ((void)0)
698 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
701 #ifndef debug_printf_parse
702 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
705 #ifndef debug_printf_exec
706 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
709 #ifndef debug_printf_env
710 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
713 #ifndef debug_printf_jobs
714 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
715 # define DEBUG_JOBS 1
717 # define DEBUG_JOBS 0
720 #ifndef debug_printf_expand
721 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
722 # define DEBUG_EXPAND 1
724 # define DEBUG_EXPAND 0
727 #ifndef debug_printf_glob
728 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
729 # define DEBUG_GLOB 1
731 # define DEBUG_GLOB 0
734 #ifndef debug_printf_list
735 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
738 #ifndef debug_printf_subst
739 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
742 #ifndef debug_printf_clean
743 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
744 # define DEBUG_CLEAN 1
746 # define DEBUG_CLEAN 0
750 static void debug_print_strings(const char *prefix, char **vv)
753 fprintf(stderr, "%s:\n", prefix);
755 fprintf(stderr, " '%s'\n", *vv++);
758 # define debug_print_strings(prefix, vv) ((void)0)
762 /* Leak hunting. Use hush_leaktool.sh for post-processing.
765 static void *xxmalloc(int lineno, size_t size)
767 void *ptr = xmalloc((size + 0xff) & ~0xff);
768 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
771 static void *xxrealloc(int lineno, void *ptr, size_t size)
773 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
774 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
777 static char *xxstrdup(int lineno, const char *str)
779 char *ptr = xstrdup(str);
780 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
783 static void xxfree(void *ptr)
785 fdprintf(2, "free %p\n", ptr);
788 #define xmalloc(s) xxmalloc(__LINE__, s)
789 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
790 #define xstrdup(s) xxstrdup(__LINE__, s)
791 #define free(p) xxfree(p)
795 /* Syntax and runtime errors. They always abort scripts.
796 * In interactive use they usually discard unparsed and/or unexecuted commands
797 * and return to the prompt.
798 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
801 # define die_if_script(lineno, fmt...) die_if_script(fmt)
802 # define syntax_error(lineno, msg) syntax_error(msg)
803 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
804 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
805 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
806 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
809 static void die_if_script(unsigned lineno, const char *fmt, ...)
814 bb_error_msg("hush.c:%u", lineno);
817 bb_verror_msg(fmt, p, NULL);
819 if (!G_interactive_fd)
823 static void syntax_error(unsigned lineno, const char *msg)
826 die_if_script(lineno, "syntax error: %s", msg);
828 die_if_script(lineno, "syntax error", NULL);
831 static void syntax_error_at(unsigned lineno, const char *msg)
833 die_if_script(lineno, "syntax error at '%s'", msg);
836 static void syntax_error_unterm_str(unsigned lineno, const char *s)
838 die_if_script(lineno, "syntax error: unterminated %s", s);
841 /* It so happens that all such cases are totally fatal
842 * even if shell is interactive: EOF while looking for closing
843 * delimiter. There is nowhere to read stuff from after that,
844 * it's EOF! The only choice is to terminate.
846 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
847 static void syntax_error_unterm_ch(unsigned lineno, char ch)
849 char msg[2] = { ch, '\0' };
850 syntax_error_unterm_str(lineno, msg);
854 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
859 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
863 # undef die_if_script
865 # undef syntax_error_at
866 # undef syntax_error_unterm_ch
867 # undef syntax_error_unterm_str
868 # undef syntax_error_unexpected_ch
870 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
871 # define syntax_error(msg) syntax_error(__LINE__, msg)
872 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
873 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
874 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
875 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
879 #if ENABLE_HUSH_INTERACTIVE
880 static void cmdedit_update_prompt(void);
882 # define cmdedit_update_prompt() ((void)0)
888 static int glob_needed(const char *s)
893 if (*s == '*' || *s == '[' || *s == '?')
900 static int is_well_formed_var_name(const char *s, char terminator)
902 if (!s || !(isalpha(*s) || *s == '_'))
905 while (isalnum(*s) || *s == '_')
907 return *s == terminator;
910 /* Replace each \x with x in place, return ptr past NUL. */
911 static char *unbackslash(char *src)
917 if ((*dst++ = *src++) == '\0')
923 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
944 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
945 v[count1 + count2] = NULL;
948 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
952 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
954 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
955 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
958 #define add_strings_to_strings(strings, add, need_to_dup) \
959 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
962 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
963 static char **add_string_to_strings(char **strings, char *add)
968 return add_strings_to_strings(strings, v, /*dup:*/ 0);
971 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
973 char **ptr = add_string_to_strings(strings, add);
974 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
977 #define add_string_to_strings(strings, add) \
978 xx_add_string_to_strings(__LINE__, strings, add)
981 static void free_strings(char **strings)
996 /* Helpers for setting new $n and restoring them back
998 typedef struct save_arg_t {
1002 smallint sv_g_malloced;
1005 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1009 sv->sv_argv0 = argv[0];
1010 sv->sv_g_argv = G.global_argv;
1011 sv->sv_g_argc = G.global_argc;
1012 sv->sv_g_malloced = G.global_args_malloced;
1014 argv[0] = G.global_argv[0]; /* retain $0 */
1015 G.global_argv = argv;
1016 G.global_args_malloced = 0;
1024 static void restore_G_args(save_arg_t *sv, char **argv)
1028 if (G.global_args_malloced) {
1029 /* someone ran "set -- arg1 arg2 ...", undo */
1031 while (*++pp) /* note: does not free $0 */
1033 free(G.global_argv);
1035 argv[0] = sv->sv_argv0;
1036 G.global_argv = sv->sv_g_argv;
1037 G.global_argc = sv->sv_g_argc;
1038 G.global_args_malloced = sv->sv_g_malloced;
1042 /* Basic theory of signal handling in shell
1043 * ========================================
1044 * This does not describe what hush does, rather, it is current understanding
1045 * what it _should_ do. If it doesn't, it's a bug.
1046 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1048 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1049 * is finished or backgrounded. It is the same in interactive and
1050 * non-interactive shells, and is the same regardless of whether
1051 * a user trap handler is installed or a shell special one is in effect.
1052 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1053 * backgrounds (i.e. stops) or kills all members of currently running
1056 * Wait builtin in interruptible by signals for which user trap is set
1057 * or by SIGINT in interactive shell.
1059 * Trap handlers will execute even within trap handlers. (right?)
1061 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1063 * If job control is off, backgrounded commands ("cmd &")
1064 * have SIGINT, SIGQUIT set to SIG_IGN.
1066 * Commands which are run in command substitution ("`cmd`")
1067 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1069 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1070 * by the shell from its parent.
1072 * Signals which differ from SIG_DFL action
1073 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1076 * SIGTERM (interactive): ignore
1077 * SIGHUP (interactive):
1078 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1079 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1080 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1081 * that all pipe members are stopped. Try this in bash:
1082 * while :; do :; done - ^Z does not background it
1083 * (while :; do :; done) - ^Z backgrounds it
1084 * SIGINT (interactive): wait for last pipe, ignore the rest
1085 * of the command line, show prompt. NB: ^C does not send SIGINT
1086 * to interactive shell while shell is waiting for a pipe,
1087 * since shell is bg'ed (is not in foreground process group).
1088 * Example 1: this waits 5 sec, but does not execute ls:
1089 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1090 * Example 2: this does not wait and does not execute ls:
1091 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1092 * Example 3: this does not wait 5 sec, but executes ls:
1093 * "sleep 5; ls -l" + press ^C
1095 * (What happens to signals which are IGN on shell start?)
1096 * (What happens with signal mask on shell start?)
1098 * Implementation in hush
1099 * ======================
1100 * We use in-kernel pending signal mask to determine which signals were sent.
1101 * We block all signals which we don't want to take action immediately,
1102 * i.e. we block all signals which need to have special handling as described
1103 * above, and all signals which have traps set.
1104 * After each pipe execution, we extract any pending signals via sigtimedwait()
1107 * unsigned non_DFL_mask: a mask of such "special" signals
1108 * sigset_t blocked_set: current blocked signal set
1111 * clear bit in blocked_set unless it is also in non_DFL_mask
1112 * "trap 'cmd' SIGxxx":
1113 * set bit in blocked_set (even if 'cmd' is '')
1114 * after [v]fork, if we plan to be a shell:
1115 * unblock signals with special interactive handling
1116 * (child shell is not interactive),
1117 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1118 * after [v]fork, if we plan to exec:
1119 * POSIX says pending signal mask is cleared in child - no need to clear it.
1120 * Restore blocked signal set to one inherited by shell just prior to exec.
1122 * Note: as a result, we do not use signal handlers much. The only uses
1123 * are to count SIGCHLDs
1124 * and to restore tty pgrp on signal-induced exit.
1127 SPECIAL_INTERACTIVE_SIGS = 0
1132 SPECIAL_JOB_SIGS = 0
1140 #if ENABLE_HUSH_FAST
1141 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1144 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1150 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1151 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1152 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1153 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1155 /* Restores tty foreground process group, and exits.
1156 * May be called as signal handler for fatal signal
1157 * (will resend signal to itself, producing correct exit state)
1158 * or called directly with -EXITCODE.
1159 * We also call it if xfunc is exiting. */
1160 static void sigexit(int sig) NORETURN;
1161 static void sigexit(int sig)
1163 /* Disable all signals: job control, SIGPIPE, etc. */
1164 sigprocmask_allsigs(SIG_BLOCK);
1166 /* Careful: we can end up here after [v]fork. Do not restore
1167 * tty pgrp then, only top-level shell process does that */
1168 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1169 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1171 /* Not a signal, just exit */
1175 kill_myself_with_sig(sig); /* does not return */
1179 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1180 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1184 /* Restores tty foreground process group, and exits. */
1185 static void hush_exit(int exitcode) NORETURN;
1186 static void hush_exit(int exitcode)
1188 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1189 /* Prevent recursion:
1190 * trap "echo Hi; exit" EXIT; exit
1192 char *argv[] = { NULL, G.traps[0], NULL };
1200 fflush(NULL); /* flush all streams */
1201 sigexit(- (exitcode & 0xff));
1207 static int check_and_run_traps(int sig)
1209 static const struct timespec zero_timespec = { 0, 0 };
1210 smalluint save_rcode;
1216 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1221 if (G.traps && G.traps[sig]) {
1222 if (G.traps[sig][0]) {
1223 /* We have user-defined handler */
1224 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1225 save_rcode = G.last_exitcode;
1228 G.last_exitcode = save_rcode;
1229 } /* else: "" trap, ignoring signal */
1232 /* not a trap: special action */
1234 #if ENABLE_HUSH_FAST
1237 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1241 /* Builtin was ^C'ed, make it look prettier: */
1248 /* bash is observed to signal whole process groups,
1249 * not individual processes */
1250 for (job = G.job_list; job; job = job->next) {
1253 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1254 if (kill(- job->pgrp, SIGHUP) == 0)
1255 kill(- job->pgrp, SIGCONT);
1260 default: /* ignored: */
1261 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1269 static const char *get_cwd(int force)
1271 if (force || G.cwd == NULL) {
1272 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1273 * we must not try to free(bb_msg_unknown) */
1274 if (G.cwd == bb_msg_unknown)
1276 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1278 G.cwd = bb_msg_unknown;
1285 * Shell and environment variable support
1287 static struct variable **get_ptr_to_local_var(const char *name)
1289 struct variable **pp;
1290 struct variable *cur;
1295 while ((cur = *pp) != NULL) {
1296 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1303 static struct variable *get_local_var(const char *name)
1305 struct variable **pp = get_ptr_to_local_var(name);
1311 static const char *get_local_var_value(const char *name)
1313 struct variable **pp = get_ptr_to_local_var(name);
1315 return strchr((*pp)->varstr, '=') + 1;
1319 /* str holds "NAME=VAL" and is expected to be malloced.
1320 * We take ownership of it.
1322 * 0: do not change export flag
1323 * (if creating new variable, flag will be 0)
1324 * 1: set export flag and putenv the variable
1325 * -1: clear export flag and unsetenv the variable
1326 * flg_read_only is set only when we handle -R var=val
1328 #if !BB_MMU && ENABLE_HUSH_LOCAL
1329 /* all params are used */
1330 #elif BB_MMU && ENABLE_HUSH_LOCAL
1331 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1332 set_local_var(str, flg_export, local_lvl)
1333 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1334 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1335 set_local_var(str, flg_export)
1336 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1337 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1338 set_local_var(str, flg_export, flg_read_only)
1340 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1342 struct variable **var_pp;
1343 struct variable *cur;
1347 eq_sign = strchr(str, '=');
1348 if (!eq_sign) { /* not expected to ever happen? */
1353 name_len = eq_sign - str + 1; /* including '=' */
1354 var_pp = &G.top_var;
1355 while ((cur = *var_pp) != NULL) {
1356 if (strncmp(cur->varstr, str, name_len) != 0) {
1357 var_pp = &cur->next;
1360 /* We found an existing var with this name */
1361 if (cur->flg_read_only) {
1365 bb_error_msg("%s: readonly variable", str);
1369 if (flg_export == -1) { // "&& cur->flg_export" ?
1370 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1375 #if ENABLE_HUSH_LOCAL
1376 if (cur->func_nest_level < local_lvl) {
1377 /* New variable is declared as local,
1378 * and existing one is global, or local
1379 * from enclosing function.
1380 * Remove and save old one: */
1381 *var_pp = cur->next;
1382 cur->next = *G.shadowed_vars_pp;
1383 *G.shadowed_vars_pp = cur;
1384 /* bash 3.2.33(1) and exported vars:
1386 * # f() { local z=a; env | grep ^z; }
1392 if (cur->flg_export)
1397 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1402 if (cur->max_len != 0) {
1403 if (cur->max_len >= strlen(str)) {
1404 /* This one is from startup env, reuse space */
1405 strcpy(cur->varstr, str);
1409 /* max_len == 0 signifies "malloced" var, which we can
1410 * (and has to) free */
1414 goto set_str_and_exp;
1417 /* Not found - create new variable struct */
1418 cur = xzalloc(sizeof(*cur));
1419 #if ENABLE_HUSH_LOCAL
1420 cur->func_nest_level = local_lvl;
1422 cur->next = *var_pp;
1428 cur->flg_read_only = flg_read_only;
1431 if (flg_export == 1)
1432 cur->flg_export = 1;
1433 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1434 cmdedit_update_prompt();
1435 if (cur->flg_export) {
1436 if (flg_export == -1) {
1437 cur->flg_export = 0;
1438 /* unsetenv was already done */
1440 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1441 return putenv(cur->varstr);
1447 static int unset_local_var_len(const char *name, int name_len)
1449 struct variable *cur;
1450 struct variable **var_pp;
1453 return EXIT_SUCCESS;
1454 var_pp = &G.top_var;
1455 while ((cur = *var_pp) != NULL) {
1456 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1457 if (cur->flg_read_only) {
1458 bb_error_msg("%s: readonly variable", name);
1459 return EXIT_FAILURE;
1461 *var_pp = cur->next;
1462 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1463 bb_unsetenv(cur->varstr);
1464 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1465 cmdedit_update_prompt();
1469 return EXIT_SUCCESS;
1471 var_pp = &cur->next;
1473 return EXIT_SUCCESS;
1476 static int unset_local_var(const char *name)
1478 return unset_local_var_len(name, strlen(name));
1481 static void unset_vars(char **strings)
1489 const char *eq = strchrnul(*v, '=');
1490 unset_local_var_len(*v, (int)(eq - *v));
1496 #if ENABLE_SH_MATH_SUPPORT
1497 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1498 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1499 static char *endofname(const char *name)
1507 if (!is_in_name(*p))
1513 static void arith_set_local_var(const char *name, const char *val, int flags)
1515 /* arith code doesnt malloc space, so do it for it */
1516 char *var = xasprintf("%s=%s", name, val);
1517 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1523 * Helpers for "var1=val1 var2=val2 cmd" feature
1525 static void add_vars(struct variable *var)
1527 struct variable *next;
1531 var->next = G.top_var;
1533 if (var->flg_export) {
1534 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1535 putenv(var->varstr);
1537 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1543 static struct variable *set_vars_and_save_old(char **strings)
1546 struct variable *old = NULL;
1552 struct variable *var_p;
1553 struct variable **var_pp;
1556 eq = strchr(*s, '=');
1559 var_pp = get_ptr_to_local_var(*s);
1562 /* Remove variable from global linked list */
1564 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1565 *var_pp = var_p->next;
1566 /* Add it to returned list */
1570 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1581 static int FAST_FUNC static_get(struct in_str *i)
1590 static int FAST_FUNC static_peek(struct in_str *i)
1595 #if ENABLE_HUSH_INTERACTIVE
1597 static void cmdedit_update_prompt(void)
1599 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1600 G.PS1 = get_local_var_value("PS1");
1603 G.PS2 = get_local_var_value("PS2");
1611 static const char* setup_prompt_string(int promptmode)
1613 const char *prompt_str;
1614 debug_printf("setup_prompt_string %d ", promptmode);
1615 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1616 /* Set up the prompt */
1617 if (promptmode == 0) { /* PS1 */
1619 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1624 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1625 debug_printf("result '%s'\n", prompt_str);
1629 static void get_user_input(struct in_str *i)
1632 const char *prompt_str;
1634 prompt_str = setup_prompt_string(i->promptmode);
1635 #if ENABLE_FEATURE_EDITING
1636 /* Enable command line editing only while a command line
1637 * is actually being read */
1640 /* buglet: SIGINT will not make new prompt to appear _at once_,
1641 * only after <Enter>. (^C will work) */
1642 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1643 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1644 check_and_run_traps(0);
1645 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1646 i->eof_flag = (r < 0);
1647 if (i->eof_flag) { /* EOF/error detected */
1648 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1649 G.user_input_buf[1] = '\0';
1654 fputs(prompt_str, stdout);
1656 G.user_input_buf[0] = r = fgetc(i->file);
1657 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1658 //do we need check_and_run_traps(0)? (maybe only if stdin)
1659 } while (G.flag_SIGINT);
1660 i->eof_flag = (r == EOF);
1662 i->p = G.user_input_buf;
1665 #endif /* INTERACTIVE */
1667 /* This is the magic location that prints prompts
1668 * and gets data back from the user */
1669 static int FAST_FUNC file_get(struct in_str *i)
1673 /* If there is data waiting, eat it up */
1674 if (i->p && *i->p) {
1675 #if ENABLE_HUSH_INTERACTIVE
1679 if (i->eof_flag && !*i->p)
1681 /* note: ch is never NUL */
1683 /* need to double check i->file because we might be doing something
1684 * more complicated by now, like sourcing or substituting. */
1685 #if ENABLE_HUSH_INTERACTIVE
1686 if (G_interactive_fd && i->promptme && i->file == stdin) {
1689 } while (!*i->p); /* need non-empty line */
1690 i->promptmode = 1; /* PS2 */
1695 do ch = fgetc(i->file); while (ch == '\0');
1697 debug_printf("file_get: got '%c' %d\n", ch, ch);
1698 #if ENABLE_HUSH_INTERACTIVE
1705 /* All callers guarantee this routine will never
1706 * be used right after a newline, so prompting is not needed.
1708 static int FAST_FUNC file_peek(struct in_str *i)
1711 if (i->p && *i->p) {
1712 if (i->eof_flag && !i->p[1])
1715 /* note: ch is never NUL */
1717 do ch = fgetc(i->file); while (ch == '\0');
1718 i->eof_flag = (ch == EOF);
1719 i->peek_buf[0] = ch;
1720 i->peek_buf[1] = '\0';
1722 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1726 static void setup_file_in_str(struct in_str *i, FILE *f)
1728 i->peek = file_peek;
1730 #if ENABLE_HUSH_INTERACTIVE
1732 i->promptmode = 0; /* PS1 */
1738 static void setup_string_in_str(struct in_str *i, const char *s)
1740 i->peek = static_peek;
1741 i->get = static_get;
1742 #if ENABLE_HUSH_INTERACTIVE
1744 i->promptmode = 0; /* PS1 */
1754 #define B_CHUNK (32 * sizeof(char*))
1756 static void o_reset_to_empty_unquoted(o_string *o)
1764 static void o_free(o_string *o)
1767 memset(o, 0, sizeof(*o));
1770 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1775 static void o_grow_by(o_string *o, int len)
1777 if (o->length + len > o->maxlen) {
1778 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1779 o->data = xrealloc(o->data, 1 + o->maxlen);
1783 static void o_addchr(o_string *o, int ch)
1785 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1787 o->data[o->length] = ch;
1789 o->data[o->length] = '\0';
1792 static void o_addblock(o_string *o, const char *str, int len)
1795 memcpy(&o->data[o->length], str, len);
1797 o->data[o->length] = '\0';
1801 static void o_addstr(o_string *o, const char *str)
1803 o_addblock(o, str, strlen(str));
1805 static void nommu_addchr(o_string *o, int ch)
1811 # define nommu_addchr(o, str) ((void)0)
1814 static void o_addstr_with_NUL(o_string *o, const char *str)
1816 o_addblock(o, str, strlen(str) + 1);
1819 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1824 && (*str != '*' && *str != '?' && *str != '[')
1832 /* My analysis of quoting semantics tells me that state information
1833 * is associated with a destination, not a source.
1835 static void o_addqchr(o_string *o, int ch)
1838 char *found = strchr("*?[\\", ch);
1843 o->data[o->length] = '\\';
1846 o->data[o->length] = ch;
1848 o->data[o->length] = '\0';
1851 static void o_addQchr(o_string *o, int ch)
1854 if (o->o_escape && strchr("*?[\\", ch)) {
1856 o->data[o->length] = '\\';
1860 o->data[o->length] = ch;
1862 o->data[o->length] = '\0';
1865 static void o_addQstr(o_string *o, const char *str, int len)
1868 o_addblock(o, str, len);
1874 int ordinary_cnt = strcspn(str, "*?[\\");
1875 if (ordinary_cnt > len) /* paranoia */
1877 o_addblock(o, str, ordinary_cnt);
1878 if (ordinary_cnt == len)
1880 str += ordinary_cnt;
1881 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1885 if (ch) { /* it is necessarily one of "*?[\\" */
1887 o->data[o->length] = '\\';
1891 o->data[o->length] = ch;
1893 o->data[o->length] = '\0';
1897 /* A special kind of o_string for $VAR and `cmd` expansion.
1898 * It contains char* list[] at the beginning, which is grown in 16 element
1899 * increments. Actual string data starts at the next multiple of 16 * (char*).
1900 * list[i] contains an INDEX (int!) into this string data.
1901 * It means that if list[] needs to grow, data needs to be moved higher up
1902 * but list[i]'s need not be modified.
1903 * NB: remembering how many list[i]'s you have there is crucial.
1904 * o_finalize_list() operation post-processes this structure - calculates
1905 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1907 #if DEBUG_EXPAND || DEBUG_GLOB
1908 static void debug_print_list(const char *prefix, o_string *o, int n)
1910 char **list = (char**)o->data;
1911 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1915 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1916 prefix, list, n, string_start, o->length, o->maxlen);
1919 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1920 o->data + (int)list[i] + string_start,
1921 o->data + (int)list[i] + string_start);
1925 const char *p = o->data + (int)list[n - 1] + string_start;
1927 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1931 # define debug_print_list(prefix, o, n) ((void)0)
1934 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1935 * in list[n] so that it points past last stored byte so far.
1936 * It returns n+1. */
1937 static int o_save_ptr_helper(o_string *o, int n)
1939 char **list = (char**)o->data;
1943 if (!o->has_empty_slot) {
1944 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1945 string_len = o->length - string_start;
1946 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1947 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1948 /* list[n] points to string_start, make space for 16 more pointers */
1949 o->maxlen += 0x10 * sizeof(list[0]);
1950 o->data = xrealloc(o->data, o->maxlen + 1);
1951 list = (char**)o->data;
1952 memmove(list + n + 0x10, list + n, string_len);
1953 o->length += 0x10 * sizeof(list[0]);
1955 debug_printf_list("list[%d]=%d string_start=%d\n",
1956 n, string_len, string_start);
1959 /* We have empty slot at list[n], reuse without growth */
1960 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1961 string_len = o->length - string_start;
1962 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1963 n, string_len, string_start);
1964 o->has_empty_slot = 0;
1966 list[n] = (char*)(ptrdiff_t)string_len;
1970 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1971 static int o_get_last_ptr(o_string *o, int n)
1973 char **list = (char**)o->data;
1974 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1976 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1979 /* o_glob performs globbing on last list[], saving each result
1980 * as a new list[]. */
1981 static int o_glob(o_string *o, int n)
1987 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1989 return o_save_ptr_helper(o, n);
1990 pattern = o->data + o_get_last_ptr(o, n);
1991 debug_printf_glob("glob pattern '%s'\n", pattern);
1992 if (!glob_needed(pattern)) {
1994 o->length = unbackslash(pattern) - o->data;
1995 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1996 return o_save_ptr_helper(o, n);
1999 memset(&globdata, 0, sizeof(globdata));
2000 gr = glob(pattern, 0, NULL, &globdata);
2001 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2002 if (gr == GLOB_NOSPACE)
2003 bb_error_msg_and_die("out of memory during glob");
2004 if (gr == GLOB_NOMATCH) {
2005 globfree(&globdata);
2008 if (gr != 0) { /* GLOB_ABORTED ? */
2009 /* TODO: testcase for bad glob pattern behavior */
2010 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2012 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2013 char **argv = globdata.gl_pathv;
2014 o->length = pattern - o->data; /* "forget" pattern */
2016 o_addstr_with_NUL(o, *argv);
2017 n = o_save_ptr_helper(o, n);
2023 globfree(&globdata);
2025 debug_print_list("o_glob returning", o, n);
2029 /* If o->o_glob == 1, glob the string so far remembered.
2030 * Otherwise, just finish current list[] and start new */
2031 static int o_save_ptr(o_string *o, int n)
2033 if (o->o_glob) { /* if globbing is requested */
2034 /* If o->has_empty_slot, list[n] was already globbed
2035 * (if it was requested back then when it was filled)
2036 * so don't do that again! */
2037 if (!o->has_empty_slot)
2038 return o_glob(o, n); /* o_save_ptr_helper is inside */
2040 return o_save_ptr_helper(o, n);
2043 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2044 static char **o_finalize_list(o_string *o, int n)
2049 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2051 debug_print_list("finalized", o, n);
2052 debug_printf_expand("finalized n:%d\n", n);
2053 list = (char**)o->data;
2054 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2058 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2064 /* Expansion can recurse */
2065 #if ENABLE_HUSH_TICK
2066 static int process_command_subs(o_string *dest, const char *s);
2068 static char *expand_string_to_string(const char *str);
2070 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2071 parse_stream_dquoted(dest, input, dquote_end)
2073 static int parse_stream_dquoted(o_string *as_string,
2075 struct in_str *input,
2078 /* expand_strvec_to_strvec() takes a list of strings, expands
2079 * all variable references within and returns a pointer to
2080 * a list of expanded strings, possibly with larger number
2081 * of strings. (Think VAR="a b"; echo $VAR).
2082 * This new list is allocated as a single malloc block.
2083 * NULL-terminated list of char* pointers is at the beginning of it,
2084 * followed by strings themself.
2085 * Caller can deallocate entire list by single free(list). */
2087 /* Store given string, finalizing the word and starting new one whenever
2088 * we encounter IFS char(s). This is used for expanding variable values.
2089 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2090 static int expand_on_ifs(o_string *output, int n, const char *str)
2093 int word_len = strcspn(str, G.ifs);
2095 if (output->o_escape || !output->o_glob)
2096 o_addQstr(output, str, word_len);
2097 else /* protect backslashes against globbing up :) */
2098 o_addblock_duplicate_backslash(output, str, word_len);
2101 if (!*str) /* EOL - do not finalize word */
2103 o_addchr(output, '\0');
2104 debug_print_list("expand_on_ifs", output, n);
2105 n = o_save_ptr(output, n);
2106 str += strspn(str, G.ifs); /* skip ifs chars */
2108 debug_print_list("expand_on_ifs[1]", output, n);
2112 /* Helper to expand $((...)) and heredoc body. These act as if
2113 * they are in double quotes, with the exception that they are not :).
2114 * Just the rules are similar: "expand only $var and `cmd`"
2116 * Returns malloced string.
2117 * As an optimization, we return NULL if expansion is not needed.
2119 static char *expand_pseudo_dquoted(const char *str)
2122 struct in_str input;
2123 o_string dest = NULL_O_STRING;
2125 if (strchr(str, '$') == NULL
2126 #if ENABLE_HUSH_TICK
2127 && strchr(str, '`') == NULL
2133 /* We need to expand. Example:
2134 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2136 setup_string_in_str(&input, str);
2137 parse_stream_dquoted(NULL, &dest, &input, EOF);
2138 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2139 exp_str = expand_string_to_string(dest.data);
2140 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2141 o_free_unsafe(&dest);
2145 /* Expand all variable references in given string, adding words to list[]
2146 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2147 * to be filled). This routine is extremely tricky: has to deal with
2148 * variables/parameters with whitespace, $* and $@, and constructs like
2149 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2150 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2152 /* or_mask is either 0 (normal case) or 0x80 -
2153 * expansion of right-hand side of assignment == 1-element expand.
2154 * It will also do no globbing, and thus we must not backslash-quote!
2161 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2162 debug_print_list("expand_vars_to_list", output, n);
2163 n = o_save_ptr(output, n);
2164 debug_print_list("expand_vars_to_list[0]", output, n);
2166 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2169 char *dyn_val = NULL;
2170 const char *val = NULL;
2171 #if ENABLE_HUSH_TICK
2172 o_string subst_result = NULL_O_STRING;
2174 #if ENABLE_SH_MATH_SUPPORT
2175 char arith_buf[sizeof(arith_t)*3 + 2];
2177 o_addblock(output, arg, p - arg);
2178 debug_print_list("expand_vars_to_list[1]", output, n);
2180 p = strchr(p, SPECIAL_VAR_SYMBOL);
2182 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2183 /* "$@" is special. Even if quoted, it can still
2184 * expand to nothing (not even an empty string) */
2185 if ((first_ch & 0x7f) != '@')
2186 ored_ch |= first_ch;
2188 switch (first_ch & 0x7f) {
2189 /* Highest bit in first_ch indicates that var is double-quoted */
2191 val = utoa(G.root_pid);
2193 case '!': /* bg pid */
2194 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2196 case '?': /* exitcode */
2197 val = utoa(G.last_exitcode);
2199 case '#': /* argc */
2200 if (arg[1] != SPECIAL_VAR_SYMBOL)
2201 /* actually, it's a ${#var} */
2203 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2208 if (!G.global_argv[i])
2210 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2211 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2212 smallint sv = output->o_escape;
2213 /* unquoted var's contents should be globbed, so don't escape */
2214 output->o_escape = 0;
2215 while (G.global_argv[i]) {
2216 n = expand_on_ifs(output, n, G.global_argv[i]);
2217 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2218 if (G.global_argv[i++][0] && G.global_argv[i]) {
2219 /* this argv[] is not empty and not last:
2220 * put terminating NUL, start new word */
2221 o_addchr(output, '\0');
2222 debug_print_list("expand_vars_to_list[2]", output, n);
2223 n = o_save_ptr(output, n);
2224 debug_print_list("expand_vars_to_list[3]", output, n);
2227 output->o_escape = sv;
2229 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2230 * and in this case should treat it like '$*' - see 'else...' below */
2231 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2233 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2234 if (++i >= G.global_argc)
2236 o_addchr(output, '\0');
2237 debug_print_list("expand_vars_to_list[4]", output, n);
2238 n = o_save_ptr(output, n);
2240 } else { /* quoted $*: add as one word */
2242 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2243 if (!G.global_argv[++i])
2246 o_addchr(output, G.ifs[0]);
2250 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2251 /* "Empty variable", used to make "" etc to not disappear */
2255 #if ENABLE_HUSH_TICK
2256 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2259 /* Can't just stuff it into output o_string,
2260 * expanded result may need to be globbed
2261 * and $IFS-splitted */
2262 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2263 process_command_subs(&subst_result, arg);
2264 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2265 val = subst_result.data;
2268 #if ENABLE_SH_MATH_SUPPORT
2269 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2270 arith_eval_hooks_t hooks;
2275 arg++; /* skip '+' */
2276 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2277 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2279 exp_str = expand_pseudo_dquoted(arg);
2280 hooks.lookupvar = get_local_var_value;
2281 hooks.setvar = arith_set_local_var;
2282 hooks.endofname = endofname;
2283 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2287 const char *msg = "error in arithmetic";
2290 msg = "exponent less than 0";
2293 msg = "divide by 0";
2296 msg = "expression recursion loop detected";
2301 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2302 sprintf(arith_buf, arith_t_fmt, res);
2307 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2309 bool exp_len = false;
2310 bool exp_null = false;
2312 char exp_save = exp_save; /* for compiler */
2313 char exp_op = exp_op; /* for compiler */
2314 char *exp_word = exp_word; /* for compiler */
2318 arg[0] = first_ch & 0x7f;
2320 /* prepare for expansions */
2321 if (var[0] == '#') {
2322 /* handle length expansion ${#var} */
2326 /* maybe handle parameter expansion */
2327 exp_off = strcspn(var, ":-=+?%#");
2331 exp_save = var[exp_off];
2332 exp_null = exp_save == ':';
2333 exp_word = var + exp_off;
2336 exp_op = *exp_word++;
2337 var[exp_off] = '\0';
2341 /* lookup the variable in question */
2342 if (isdigit(var[0])) {
2343 /* handle_dollar() should have vetted var for us */
2345 if (i < G.global_argc)
2346 val = G.global_argv[i];
2347 /* else val remains NULL: $N with too big N */
2349 val = get_local_var_value(var);
2351 /* handle any expansions */
2353 debug_printf_expand("expand: length of '%s' = ", val);
2354 val = utoa(val ? strlen(val) : 0);
2355 debug_printf_expand("%s\n", val);
2356 } else if (exp_off) {
2357 if (exp_op == '%' || exp_op == '#') {
2359 /* we need to do a pattern match */
2362 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2363 if (exp_op == *exp_word) /* ## or %% */
2365 val = dyn_val = xstrdup(val);
2366 loc = scan(dyn_val, exp_word, match_at_left);
2367 if (match_at_left) /* # or ## */
2369 else if (loc) /* % or %% and match was found */
2373 /* we need to do an expansion */
2374 int exp_test = (!val || (exp_null && !val[0]));
2376 exp_test = !exp_test;
2377 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2378 exp_null ? "true" : "false", exp_test);
2380 if (exp_op == '?') {
2381 //TODO: how interactive bash aborts expansion mid-command?
2382 /* ${var?[error_msg_if_unset]} */
2383 /* ${var:?[error_msg_if_unset_or_null]} */
2384 /* mimic bash message */
2385 die_if_script("%s: %s",
2387 exp_word[0] ? exp_word : "parameter null or not set"
2393 if (exp_op == '=') {
2394 /* ${var=[word]} or ${var:=[word]} */
2395 if (isdigit(var[0]) || var[0] == '#') {
2396 /* mimic bash message */
2397 die_if_script("$%s: cannot assign in this way", var);
2400 char *new_var = xasprintf("%s=%s", var, val);
2401 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2407 var[exp_off] = exp_save;
2411 #if ENABLE_HUSH_TICK
2414 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2415 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2417 /* unquoted var's contents should be globbed, so don't escape */
2418 smallint sv = output->o_escape;
2419 output->o_escape = 0;
2420 n = expand_on_ifs(output, n, val);
2422 output->o_escape = sv;
2424 } else { /* quoted $VAR, val will be appended below */
2425 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2428 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2431 o_addQstr(output, val, strlen(val));
2434 /* Do the check to avoid writing to a const string */
2435 if (*p != SPECIAL_VAR_SYMBOL)
2436 *p = SPECIAL_VAR_SYMBOL;
2438 #if ENABLE_HUSH_TICK
2439 o_free(&subst_result);
2442 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2445 debug_print_list("expand_vars_to_list[a]", output, n);
2446 /* this part is literal, and it was already pre-quoted
2447 * if needed (much earlier), do not use o_addQstr here! */
2448 o_addstr_with_NUL(output, arg);
2449 debug_print_list("expand_vars_to_list[b]", output, n);
2450 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2451 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2454 /* allow to reuse list[n] later without re-growth */
2455 output->has_empty_slot = 1;
2457 o_addchr(output, '\0');
2462 static char **expand_variables(char **argv, int or_mask)
2467 o_string output = NULL_O_STRING;
2469 if (or_mask & 0x100) {
2470 output.o_escape = 1; /* protect against globbing for "$var" */
2471 /* (unquoted $var will temporarily switch it off) */
2478 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2481 debug_print_list("expand_variables", &output, n);
2483 /* output.data (malloced in one block) gets returned in "list" */
2484 list = o_finalize_list(&output, n);
2485 debug_print_strings("expand_variables[1]", list);
2489 static char **expand_strvec_to_strvec(char **argv)
2491 return expand_variables(argv, 0x100);
2494 #if ENABLE_HUSH_BASH_COMPAT
2495 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2497 return expand_variables(argv, 0x80);
2501 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2502 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2507 o_string output = NULL_O_STRING;
2512 int is_var = is_well_formed_var_name(*v, '=');
2513 /* is_var * 0x80: singleword expansion for vars */
2514 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2516 /* Subtle! expand_vars_to_list did not glob last word yet.
2517 * It does this only when fed with further data.
2518 * Therefore we set globbing flags AFTER it, not before:
2521 /* if it is not recognizably abc=...; then: */
2522 output.o_escape = !is_var; /* protect against globbing for "$var" */
2523 /* (unquoted $var will temporarily switch it off) */
2524 output.o_glob = !is_var; /* and indeed do globbing */
2527 debug_print_list("expand_cond", &output, n);
2529 /* output.data (malloced in one block) gets returned in "list" */
2530 list = o_finalize_list(&output, n);
2531 debug_print_strings("expand_cond[1]", list);
2536 /* Used for expansion of right hand of assignments */
2537 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2539 static char *expand_string_to_string(const char *str)
2541 char *argv[2], **list;
2543 argv[0] = (char*)str;
2545 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2547 if (!list[0] || list[1])
2548 bb_error_msg_and_die("BUG in varexp2");
2549 /* actually, just move string 2*sizeof(char*) bytes back */
2550 overlapping_strcpy((char*)list, list[0]);
2551 unbackslash((char*)list);
2552 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2556 /* Used for "eval" builtin */
2557 static char* expand_strvec_to_string(char **argv)
2561 list = expand_variables(argv, 0x80);
2562 /* Convert all NULs to spaces */
2567 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2568 bb_error_msg_and_die("BUG in varexp3");
2569 /* bash uses ' ' regardless of $IFS contents */
2574 overlapping_strcpy((char*)list, list[0]);
2575 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2579 static char **expand_assignments(char **argv, int count)
2583 /* Expand assignments into one string each */
2584 for (i = 0; i < count; i++) {
2585 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2593 void re_execute_shell(char ***to_free, const char *s,
2594 char *g_argv0, char **g_argv,
2595 char **builtin_argv) NORETURN;
2597 static void reset_traps_to_defaults(void)
2599 /* This function is always called in a child shell
2600 * after fork (not vfork, NOMMU doesn't use this function).
2601 * Child shells are not interactive.
2602 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2603 * Testcase: (while :; do :; done) + ^Z should background.
2604 * Same goes for SIGTERM, SIGHUP, SIGINT.
2609 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2612 /* Stupid. It can be done with *single* &= op, but we can't use
2613 * the fact that G.blocked_set is implemented as a bitmask... */
2614 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2618 sigdelset(&G.blocked_set, sig);
2625 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2626 mask = G.non_DFL_mask;
2627 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2631 G.traps[sig] = NULL;
2632 /* There is no signal for 0 (EXIT) */
2635 /* There was a trap handler, we are removing it.
2636 * But if sig still has non-DFL handling,
2637 * we should not unblock it. */
2640 sigdelset(&G.blocked_set, sig);
2642 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2647 static void re_execute_shell(char ***to_free, const char *s,
2648 char *g_argv0, char **g_argv,
2649 char **builtin_argv) NORETURN;
2650 static void re_execute_shell(char ***to_free, const char *s,
2651 char *g_argv0, char **g_argv,
2652 char **builtin_argv)
2654 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2655 char *heredoc_argv[4];
2656 struct variable *cur;
2657 #if ENABLE_HUSH_FUNCTIONS
2658 struct function *funcp;
2663 if (!g_argv0) { /* heredoc */
2664 argv = heredoc_argv;
2665 argv[0] = (char *) G.argv0_for_re_execing;
2666 argv[1] = (char *) "-<";
2667 argv[2] = (char *) s;
2669 pp = &argv[3]; /* used as pointer to empty environment */
2675 if (pp) while (*pp++)
2678 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2679 , (unsigned) G.root_pid
2680 , (unsigned) G.last_bg_pid
2681 , (unsigned) G.last_exitcode
2683 IF_HUSH_LOOPS(, G.depth_of_loop)
2685 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2686 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2689 for (cur = G.top_var; cur; cur = cur->next) {
2690 if (!cur->flg_export || cur->flg_read_only)
2693 #if ENABLE_HUSH_FUNCTIONS
2694 for (funcp = G.top_func; funcp; funcp = funcp->next)
2700 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2701 *pp++ = (char *) G.argv0_for_re_execing;
2703 for (cur = G.top_var; cur; cur = cur->next) {
2704 if (cur->varstr == hush_version_str)
2706 if (cur->flg_read_only) {
2707 *pp++ = (char *) "-R";
2708 *pp++ = cur->varstr;
2709 } else if (!cur->flg_export) {
2710 *pp++ = (char *) "-V";
2711 *pp++ = cur->varstr;
2714 #if ENABLE_HUSH_FUNCTIONS
2715 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2716 *pp++ = (char *) "-F";
2717 *pp++ = funcp->name;
2718 *pp++ = funcp->body_as_string;
2721 /* We can pass activated traps here. Say, -Tnn:trap_string
2723 * However, POSIX says that subshells reset signals with traps
2725 * I tested bash-3.2 and it not only does that with true subshells
2726 * of the form ( list ), but with any forked children shells.
2727 * I set trap "echo W" WINCH; and then tried:
2729 * { echo 1; sleep 20; echo 2; } &
2730 * while true; do echo 1; sleep 20; echo 2; break; done &
2731 * true | { echo 1; sleep 20; echo 2; } | cat
2733 * In all these cases sending SIGWINCH to the child shell
2734 * did not run the trap. If I add trap "echo V" WINCH;
2735 * _inside_ group (just before echo 1), it works.
2737 * I conclude it means we don't need to pass active traps here.
2738 * exec syscall below resets them to SIG_DFL for us.
2740 *pp++ = (char *) "-c";
2743 while (*++builtin_argv)
2744 *pp++ = *builtin_argv;
2745 *pp++ = (char *) "";
2750 /* *pp = NULL; - is already there */
2754 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2755 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2756 execve(bb_busybox_exec_path, argv, pp);
2757 /* Fallback. Useful for init=/bin/hush usage etc */
2758 if (argv[0][0] == '/')
2759 execve(argv[0], argv, pp);
2760 xfunc_error_retval = 127;
2761 bb_error_msg_and_die("can't re-execute the shell");
2763 #endif /* !BB_MMU */
2766 static void setup_heredoc(struct redir_struct *redir)
2768 struct fd_pair pair;
2771 /* the _body_ of heredoc (misleading field name) */
2772 const char *heredoc = redir->rd_filename;
2779 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2780 expanded = expand_pseudo_dquoted(heredoc);
2784 len = strlen(heredoc);
2786 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2788 xmove_fd(pair.rd, redir->rd_fd);
2790 /* Try writing without forking. Newer kernels have
2791 * dynamically growing pipes. Must use non-blocking write! */
2794 written = write(pair.wr, heredoc, len);
2805 ndelay_off(pair.wr);
2807 /* Okay, pipe buffer was not big enough */
2808 /* Note: we must not create a stray child (bastard? :)
2809 * for the unsuspecting parent process. Child creates a grandchild
2810 * and exits before parent execs the process which consumes heredoc
2811 * (that exec happens after we return from this function) */
2817 bb_perror_msg_and_die("vfork");
2820 disable_restore_tty_pgrp_on_exit();
2821 pid = BB_MMU ? fork() : vfork();
2823 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2827 close(redir->rd_fd); /* read side of the pipe */
2829 full_write(pair.wr, heredoc, len); /* may loop or block */
2832 /* Delegate blocking writes to another process */
2833 xmove_fd(pair.wr, STDOUT_FILENO);
2834 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2838 #if ENABLE_HUSH_FAST
2840 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2842 enable_restore_tty_pgrp_on_exit();
2848 wait(NULL); /* wait till child has died */
2851 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2852 * and stderr if they are redirected. */
2853 static int setup_redirects(struct command *prog, int squirrel[])
2856 struct redir_struct *redir;
2858 for (redir = prog->redirects; redir; redir = redir->next) {
2859 if (redir->rd_type == REDIRECT_HEREDOC2) {
2860 /* rd_fd<<HERE case */
2861 if (squirrel && redir->rd_fd < 3
2862 && squirrel[redir->rd_fd] < 0
2864 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2866 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2868 debug_printf_parse("set heredoc '%s'\n",
2869 redir->rd_filename);
2870 setup_heredoc(redir);
2874 if (redir->rd_dup == REDIRFD_TO_FILE) {
2875 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2877 if (redir->rd_filename == NULL) {
2878 /* Something went wrong in the parse.
2879 * Pretend it didn't happen */
2880 bb_error_msg("bug in redirect parse");
2883 mode = redir_table[redir->rd_type].mode;
2884 p = expand_string_to_string(redir->rd_filename);
2885 openfd = open_or_warn(p, mode);
2888 /* this could get lost if stderr has been redirected, but
2889 * bash and ash both lose it as well (though zsh doesn't!) */
2890 //what the above comment tries to say?
2894 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2895 openfd = redir->rd_dup;
2898 if (openfd != redir->rd_fd) {
2899 if (squirrel && redir->rd_fd < 3
2900 && squirrel[redir->rd_fd] < 0
2902 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2904 if (openfd == REDIRFD_CLOSE) {
2905 /* "n>-" means "close me" */
2906 close(redir->rd_fd);
2908 xdup2(openfd, redir->rd_fd);
2909 if (redir->rd_dup == REDIRFD_TO_FILE)
2917 static void restore_redirects(int squirrel[])
2920 for (i = 0; i < 3; i++) {
2923 /* We simply die on error */
2930 static void free_pipe_list(struct pipe *head);
2932 /* Return code is the exit status of the pipe */
2933 static void free_pipe(struct pipe *pi)
2936 struct command *command;
2937 struct redir_struct *r, *rnext;
2940 if (pi->stopped_cmds > 0) /* why? */
2942 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2943 for (i = 0; i < pi->num_cmds; i++) {
2944 command = &pi->cmds[i];
2945 debug_printf_clean(" command %d:\n", i);
2946 if (command->argv) {
2947 for (a = 0, p = command->argv; *p; a++, p++) {
2948 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2950 free_strings(command->argv);
2951 command->argv = NULL;
2953 /* not "else if": on syntax error, we may have both! */
2954 if (command->group) {
2955 debug_printf_clean(" begin group (cmd_type:%d)\n",
2957 free_pipe_list(command->group);
2958 debug_printf_clean(" end group\n");
2959 command->group = NULL;
2961 /* else is crucial here.
2962 * If group != NULL, child_func is meaningless */
2963 #if ENABLE_HUSH_FUNCTIONS
2964 else if (command->child_func) {
2965 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2966 command->child_func->parent_cmd = NULL;
2970 free(command->group_as_string);
2971 command->group_as_string = NULL;
2973 for (r = command->redirects; r; r = rnext) {
2974 debug_printf_clean(" redirect %d%s",
2975 r->rd_fd, redir_table[r->rd_type].descrip);
2976 /* guard against the case >$FOO, where foo is unset or blank */
2977 if (r->rd_filename) {
2978 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2979 free(r->rd_filename);
2980 r->rd_filename = NULL;
2982 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2986 command->redirects = NULL;
2988 free(pi->cmds); /* children are an array, they get freed all at once */
2996 static void free_pipe_list(struct pipe *head)
2998 struct pipe *pi, *next;
3000 for (pi = head; pi; pi = next) {
3002 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3005 debug_printf_clean("pipe followup code %d\n", pi->followup);
3007 /*pi->next = NULL;*/
3013 static int run_list(struct pipe *pi);
3015 #define parse_stream(pstring, input, end_trigger) \
3016 parse_stream(input, end_trigger)
3018 static struct pipe *parse_stream(char **pstring,
3019 struct in_str *input,
3021 static void parse_and_run_string(const char *s);
3024 static char *find_in_path(const char *arg)
3027 const char *PATH = get_local_var_value("PATH");
3033 const char *end = strchrnul(PATH, ':');
3034 int sz = end - PATH; /* must be int! */
3038 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3040 /* We have xxx::yyyy in $PATH,
3041 * it means "use current dir" */
3044 if (access(ret, F_OK) == 0)
3057 static const struct built_in_command* find_builtin_helper(const char *name,
3058 const struct built_in_command *x,
3059 const struct built_in_command *end)
3062 if (strcmp(name, x->cmd) != 0) {
3066 debug_printf_exec("found builtin '%s'\n", name);
3071 static const struct built_in_command* find_builtin1(const char *name)
3073 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3075 static const struct built_in_command* find_builtin(const char *name)
3077 const struct built_in_command *x = find_builtin1(name);
3080 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3083 #if ENABLE_HUSH_FUNCTIONS
3084 static const struct function *find_function(const char *name)
3086 const struct function *funcp = G.top_func;
3088 if (strcmp(name, funcp->name) == 0) {
3091 funcp = funcp->next;
3094 debug_printf_exec("found function '%s'\n", name);
3098 /* Note: takes ownership on name ptr */
3099 static struct function *new_function(char *name)
3101 struct function *funcp;
3102 struct function **funcpp = &G.top_func;
3104 while ((funcp = *funcpp) != NULL) {
3105 struct command *cmd;
3107 if (strcmp(funcp->name, name) != 0) {
3108 funcpp = &funcp->next;
3112 cmd = funcp->parent_cmd;
3113 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3115 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3117 /* Note: if !funcp->body, do not free body_as_string!
3118 * This is a special case of "-F name body" function:
3119 * body_as_string was not malloced! */
3121 free_pipe_list(funcp->body);
3123 free(funcp->body_as_string);
3127 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3128 cmd->argv[0] = funcp->name;
3129 cmd->group = funcp->body;
3131 cmd->group_as_string = funcp->body_as_string;
3136 debug_printf_exec("remembering new function '%s'\n", name);
3137 funcp = *funcpp = xzalloc(sizeof(*funcp));
3138 /*funcp->next = NULL;*/
3144 static void unset_func(const char *name)
3146 struct function *funcp;
3147 struct function **funcpp = &G.top_func;
3149 while ((funcp = *funcpp) != NULL) {
3150 if (strcmp(funcp->name, name) == 0) {
3151 *funcpp = funcp->next;
3152 /* funcp is unlinked now, deleting it.
3153 * Note: if !funcp->body, the function was created by
3154 * "-F name body", do not free ->body_as_string
3155 * and ->name as they were not malloced. */
3157 free_pipe_list(funcp->body);
3160 free(funcp->body_as_string);
3166 funcpp = &funcp->next;
3171 #define exec_function(to_free, funcp, argv) \
3172 exec_function(funcp, argv)
3174 static void exec_function(char ***to_free,
3175 const struct function *funcp,
3176 char **argv) NORETURN;
3177 static void exec_function(char ***to_free,
3178 const struct function *funcp,
3184 argv[0] = G.global_argv[0];
3185 G.global_argv = argv;
3189 /* On MMU, funcp->body is always non-NULL */
3190 n = run_list(funcp->body);
3194 re_execute_shell(to_free,
3195 funcp->body_as_string,
3202 static int run_function(const struct function *funcp, char **argv)
3208 save_and_replace_G_args(&sv, argv);
3210 /* "we are in function, ok to use return" */
3211 sv_flg = G.flag_return_in_progress;
3212 G.flag_return_in_progress = -1;
3213 #if ENABLE_HUSH_LOCAL
3214 G.func_nest_level++;
3217 /* On MMU, funcp->body is always non-NULL */
3220 /* Function defined by -F */
3221 parse_and_run_string(funcp->body_as_string);
3222 rc = G.last_exitcode;
3226 rc = run_list(funcp->body);
3229 #if ENABLE_HUSH_LOCAL
3231 struct variable *var;
3232 struct variable **var_pp;
3234 var_pp = &G.top_var;
3235 while ((var = *var_pp) != NULL) {
3236 if (var->func_nest_level < G.func_nest_level) {
3237 var_pp = &var->next;
3241 if (var->flg_export)
3242 bb_unsetenv(var->varstr);
3243 /* Remove from global list */
3244 *var_pp = var->next;
3250 G.func_nest_level--;
3253 G.flag_return_in_progress = sv_flg;
3255 restore_G_args(&sv, argv);
3259 #endif /* ENABLE_HUSH_FUNCTIONS */
3263 #define exec_builtin(to_free, x, argv) \
3264 exec_builtin(x, argv)
3266 #define exec_builtin(to_free, x, argv) \
3267 exec_builtin(to_free, argv)
3269 static void exec_builtin(char ***to_free,
3270 const struct built_in_command *x,
3271 char **argv) NORETURN;
3272 static void exec_builtin(char ***to_free,
3273 const struct built_in_command *x,
3277 int rcode = x->function(argv);
3281 /* On NOMMU, we must never block!
3282 * Example: { sleep 99 | read line; } & echo Ok
3284 re_execute_shell(to_free,
3294 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3295 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3296 #define pseudo_exec(nommu_save, command, argv_expanded) \
3297 pseudo_exec(command, argv_expanded)
3300 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3302 * Don't exit() here. If you don't exec, use _exit instead.
3303 * The at_exit handlers apparently confuse the calling process,
3304 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3305 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3306 char **argv, int assignment_cnt,
3307 char **argv_expanded) NORETURN;
3308 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3309 char **argv, int assignment_cnt,
3310 char **argv_expanded)
3314 /* Case when we are here: ... | var=val | ... */
3315 if (!argv[assignment_cnt])
3316 _exit(EXIT_SUCCESS);
3318 new_env = expand_assignments(argv, assignment_cnt);
3320 set_vars_and_save_old(new_env);
3321 free(new_env); /* optional */
3322 /* we can also destroy set_vars_and_save_old's return value,
3325 nommu_save->new_env = new_env;
3326 nommu_save->old_vars = set_vars_and_save_old(new_env);
3328 if (argv_expanded) {
3329 argv = argv_expanded;
3331 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3333 nommu_save->argv = argv;
3337 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3338 if (strchr(argv[0], '/') != NULL)
3342 /* Check if the command matches any of the builtins.
3343 * Depending on context, this might be redundant. But it's
3344 * easier to waste a few CPU cycles than it is to figure out
3345 * if this is one of those cases.
3348 /* On NOMMU, it is more expensive to re-execute shell
3349 * just in order to run echo or test builtin.
3350 * It's better to skip it here and run corresponding
3351 * non-builtin later. */
3352 const struct built_in_command *x;
3353 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3355 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3358 #if ENABLE_HUSH_FUNCTIONS
3359 /* Check if the command matches any functions */
3361 const struct function *funcp = find_function(argv[0]);
3363 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3368 #if ENABLE_FEATURE_SH_STANDALONE
3369 /* Check if the command matches any busybox applets */
3371 int a = find_applet_by_name(argv[0]);
3373 # if BB_MMU /* see above why on NOMMU it is not allowed */
3374 if (APPLET_IS_NOEXEC(a)) {
3375 debug_printf_exec("running applet '%s'\n", argv[0]);
3376 run_applet_no_and_exit(a, argv);
3379 /* Re-exec ourselves */
3380 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3381 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3382 execv(bb_busybox_exec_path, argv);
3383 /* If they called chroot or otherwise made the binary no longer
3384 * executable, fall through */
3389 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3392 debug_printf_exec("execing '%s'\n", argv[0]);
3393 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3394 execvp(argv[0], argv);
3395 bb_perror_msg("can't execute '%s'", argv[0]);
3396 _exit(EXIT_FAILURE);
3399 /* Called after [v]fork() in run_pipe
3401 static void pseudo_exec(nommu_save_t *nommu_save,
3402 struct command *command,
3403 char **argv_expanded) NORETURN;
3404 static void pseudo_exec(nommu_save_t *nommu_save,
3405 struct command *command,
3406 char **argv_expanded)
3408 if (command->argv) {
3409 pseudo_exec_argv(nommu_save, command->argv,
3410 command->assignment_cnt, argv_expanded);
3413 if (command->group) {
3414 /* Cases when we are here:
3417 * ... | ( list ) | ...
3418 * ... | { list } | ...
3422 debug_printf_exec("pseudo_exec: run_list\n");
3423 reset_traps_to_defaults();
3424 rcode = run_list(command->group);
3425 /* OK to leak memory by not calling free_pipe_list,
3426 * since this process is about to exit */
3429 re_execute_shell(&nommu_save->argv_from_re_execing,
3430 command->group_as_string,
3437 /* Case when we are here: ... | >file */
3438 debug_printf_exec("pseudo_exec'ed null command\n");
3439 _exit(EXIT_SUCCESS);
3443 static const char *get_cmdtext(struct pipe *pi)
3449 /* This is subtle. ->cmdtext is created only on first backgrounding.
3450 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3451 * On subsequent bg argv is trashed, but we won't use it */
3454 argv = pi->cmds[0].argv;
3455 if (!argv || !argv[0]) {
3456 pi->cmdtext = xzalloc(1);
3462 len += strlen(*argv) + 1;
3466 argv = pi->cmds[0].argv;
3468 len = strlen(*argv);
3469 memcpy(p, *argv, len);
3477 static void insert_bg_job(struct pipe *pi)
3479 struct pipe *job, **jobp;
3482 /* Linear search for the ID of the job to use */
3484 for (job = G.job_list; job; job = job->next)
3485 if (job->jobid >= pi->jobid)
3486 pi->jobid = job->jobid + 1;
3488 /* Add job to the list of running jobs */
3490 while ((job = *jobp) != NULL)
3492 job = *jobp = xmalloc(sizeof(*job));
3494 *job = *pi; /* physical copy */
3496 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3497 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3498 for (i = 0; i < pi->num_cmds; i++) {
3499 job->cmds[i].pid = pi->cmds[i].pid;
3500 /* all other fields are not used and stay zero */
3502 job->cmdtext = xstrdup(get_cmdtext(pi));
3504 if (G_interactive_fd)
3505 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3506 /* Last command's pid goes to $! */
3507 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3508 G.last_jobid = job->jobid;
3511 static void remove_bg_job(struct pipe *pi)
3513 struct pipe *prev_pipe;
3515 if (pi == G.job_list) {
3516 G.job_list = pi->next;
3518 prev_pipe = G.job_list;
3519 while (prev_pipe->next != pi)
3520 prev_pipe = prev_pipe->next;
3521 prev_pipe->next = pi->next;
3524 G.last_jobid = G.job_list->jobid;
3529 /* Remove a backgrounded job */
3530 static void delete_finished_bg_job(struct pipe *pi)
3533 pi->stopped_cmds = 0;
3539 /* Check to see if any processes have exited -- if they
3540 * have, figure out why and see if a job has completed */
3541 static int checkjobs(struct pipe* fg_pipe)
3551 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3553 attributes = WUNTRACED;
3554 if (fg_pipe == NULL)
3555 attributes |= WNOHANG;
3558 #if ENABLE_HUSH_FAST
3559 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3560 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3561 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3562 /* There was neither fork nor SIGCHLD since last waitpid */
3563 /* Avoid doing waitpid syscall if possible */
3564 if (!G.we_have_children) {
3568 if (fg_pipe == NULL) { /* is WNOHANG set? */
3569 /* We have children, but they did not exit
3570 * or stop yet (we saw no SIGCHLD) */
3573 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3577 /* Do we do this right?
3578 * bash-3.00# sleep 20 | false
3580 * [3]+ Stopped sleep 20 | false
3581 * bash-3.00# echo $?
3582 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3583 * [hush 1.14.0: yes we do it right]
3590 #if ENABLE_HUSH_FAST
3591 i = G.count_SIGCHLD;
3593 childpid = waitpid(-1, &status, attributes);
3594 if (childpid <= 0) {
3595 if (childpid && errno != ECHILD)
3596 bb_perror_msg("waitpid");
3597 #if ENABLE_HUSH_FAST
3598 else { /* Until next SIGCHLD, waitpid's are useless */
3599 G.we_have_children = (childpid == 0);
3600 G.handled_SIGCHLD = i;
3601 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3606 dead = WIFEXITED(status) || WIFSIGNALED(status);
3609 if (WIFSTOPPED(status))
3610 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3611 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3612 if (WIFSIGNALED(status))
3613 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3614 childpid, WTERMSIG(status), WEXITSTATUS(status));
3615 if (WIFEXITED(status))
3616 debug_printf_jobs("pid %d exited, exitcode %d\n",
3617 childpid, WEXITSTATUS(status));
3619 /* Were we asked to wait for fg pipe? */
3621 for (i = 0; i < fg_pipe->num_cmds; i++) {
3622 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3623 if (fg_pipe->cmds[i].pid != childpid)
3626 fg_pipe->cmds[i].pid = 0;
3627 fg_pipe->alive_cmds--;
3628 if (i == fg_pipe->num_cmds - 1) {
3629 /* last process gives overall exitstatus */
3630 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3631 rcode = WEXITSTATUS(status);
3632 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3633 /* bash prints killing signal's name for *last*
3634 * process in pipe (prints just newline for SIGINT).
3635 * Mimic this. Example: "sleep 5" + ^\
3637 if (WIFSIGNALED(status)) {
3638 int sig = WTERMSIG(status);
3639 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3643 fg_pipe->cmds[i].is_stopped = 1;
3644 fg_pipe->stopped_cmds++;
3646 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3647 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3648 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3649 /* All processes in fg pipe have exited or stopped */
3650 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3651 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3652 * and "killall -STOP cat" */
3653 if (G_interactive_fd) {
3655 if (fg_pipe->alive_cmds)
3656 insert_bg_job(fg_pipe);
3660 if (!fg_pipe->alive_cmds)
3663 /* There are still running processes in the fg pipe */
3664 goto wait_more; /* do waitpid again */
3666 /* it wasnt fg_pipe, look for process in bg pipes */
3670 /* We asked to wait for bg or orphaned children */
3671 /* No need to remember exitcode in this case */
3672 for (pi = G.job_list; pi; pi = pi->next) {
3673 for (i = 0; i < pi->num_cmds; i++) {
3674 if (pi->cmds[i].pid == childpid)
3675 goto found_pi_and_prognum;
3678 /* Happens when shell is used as init process (init=/bin/sh) */
3679 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3680 continue; /* do waitpid again */
3682 found_pi_and_prognum:
3685 pi->cmds[i].pid = 0;
3687 if (!pi->alive_cmds) {
3688 if (G_interactive_fd)
3689 printf(JOB_STATUS_FORMAT, pi->jobid,
3690 "Done", pi->cmdtext);
3691 delete_finished_bg_job(pi);
3695 pi->cmds[i].is_stopped = 1;
3699 } /* while (waitpid succeeds)... */
3705 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3708 int rcode = checkjobs(fg_pipe);
3709 if (G_saved_tty_pgrp) {
3710 /* Job finished, move the shell to the foreground */
3711 p = getpgrp(); /* our process group id */
3712 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3713 tcsetpgrp(G_interactive_fd, p);
3719 /* Start all the jobs, but don't wait for anything to finish.
3722 * Return code is normally -1, when the caller has to wait for children
3723 * to finish to determine the exit status of the pipe. If the pipe
3724 * is a simple builtin command, however, the action is done by the
3725 * time run_pipe returns, and the exit code is provided as the
3728 * Returns -1 only if started some children. IOW: we have to
3729 * mask out retvals of builtins etc with 0xff!
3731 * The only case when we do not need to [v]fork is when the pipe
3732 * is single, non-backgrounded, non-subshell command. Examples:
3733 * cmd ; ... { list } ; ...
3734 * cmd && ... { list } && ...
3735 * cmd || ... { list } || ...
3736 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3737 * or (if SH_STANDALONE) an applet, and we can run the { list }
3738 * with run_list. If it isn't one of these, we fork and exec cmd.
3740 * Cases when we must fork:
3741 * non-single: cmd | cmd
3742 * backgrounded: cmd & { list } &
3743 * subshell: ( list ) [&]
3745 static int run_pipe(struct pipe *pi)
3747 static const char *const null_ptr = NULL;
3750 struct command *command;
3751 char **argv_expanded;
3754 /* it is not always needed, but we aim to smaller code */
3755 int squirrel[] = { -1, -1, -1 };
3758 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3761 IF_HUSH_JOB(pi->pgrp = -1;)
3762 pi->stopped_cmds = 0;
3763 command = &(pi->cmds[0]);
3764 argv_expanded = NULL;
3766 if (pi->num_cmds != 1
3767 || pi->followup == PIPE_BG
3768 || command->cmd_type == CMD_SUBSHELL
3775 debug_printf_exec(": group:%p argv:'%s'\n",
3776 command->group, command->argv ? command->argv[0] : "NONE");
3778 if (command->group) {
3779 #if ENABLE_HUSH_FUNCTIONS
3780 if (command->cmd_type == CMD_FUNCDEF) {
3781 /* "executing" func () { list } */
3782 struct function *funcp;
3784 funcp = new_function(command->argv[0]);
3785 /* funcp->name is already set to argv[0] */
3786 funcp->body = command->group;
3788 funcp->body_as_string = command->group_as_string;
3789 command->group_as_string = NULL;
3791 command->group = NULL;
3792 command->argv[0] = NULL;
3793 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3794 funcp->parent_cmd = command;
3795 command->child_func = funcp;
3797 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3799 return EXIT_SUCCESS;
3803 debug_printf("non-subshell group\n");
3804 rcode = 1; /* exitcode if redir failed */
3805 if (setup_redirects(command, squirrel) == 0) {
3806 debug_printf_exec(": run_list\n");
3807 rcode = run_list(command->group) & 0xff;
3809 restore_redirects(squirrel);
3810 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3812 debug_printf_exec("run_pipe: return %d\n", rcode);
3816 argv = command->argv ? command->argv : (char **) &null_ptr;
3818 const struct built_in_command *x;
3819 #if ENABLE_HUSH_FUNCTIONS
3820 const struct function *funcp;
3824 char **new_env = NULL;
3825 struct variable *old_vars = NULL;
3827 if (argv[command->assignment_cnt] == NULL) {
3828 /* Assignments, but no command */
3829 /* Ensure redirects take effect. Try "a=t >file" */
3830 rcode = setup_redirects(command, squirrel);
3831 restore_redirects(squirrel);
3832 /* Set shell variables */
3834 p = expand_string_to_string(*argv);
3835 debug_printf_exec("set shell var:'%s'->'%s'\n",
3837 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3840 /* Do we need to flag set_local_var() errors?
3841 * "assignment to readonly var" and "putenv error"
3843 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3845 debug_printf_exec("run_pipe: return %d\n", rcode);
3849 /* Expand the rest into (possibly) many strings each */
3851 #if ENABLE_HUSH_BASH_COMPAT
3852 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3853 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3856 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3857 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3858 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3863 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3866 x = find_builtin(argv_expanded[0]);
3867 #if ENABLE_HUSH_FUNCTIONS
3870 funcp = find_function(argv_expanded[0]);
3874 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3875 debug_printf("exec with redirects only\n");
3876 rcode = setup_redirects(command, NULL);
3877 goto clean_up_and_ret1;
3880 /* setup_redirects acts on file descriptors, not FILEs.
3881 * This is perfect for work that comes after exec().
3882 * Is it really safe for inline use? Experimentally,
3883 * things seem to work. */
3884 rcode = setup_redirects(command, squirrel);
3886 new_env = expand_assignments(argv, command->assignment_cnt);
3887 old_vars = set_vars_and_save_old(new_env);
3889 debug_printf_exec(": builtin '%s' '%s'...\n",
3890 x->cmd, argv_expanded[1]);
3891 rcode = x->function(argv_expanded) & 0xff;
3894 #if ENABLE_HUSH_FUNCTIONS
3896 # if ENABLE_HUSH_LOCAL
3897 struct variable **sv;
3898 sv = G.shadowed_vars_pp;
3899 G.shadowed_vars_pp = &old_vars;
3901 debug_printf_exec(": function '%s' '%s'...\n",
3902 funcp->name, argv_expanded[1]);
3903 rcode = run_function(funcp, argv_expanded) & 0xff;
3904 # if ENABLE_HUSH_LOCAL
3905 G.shadowed_vars_pp = sv;
3910 #if ENABLE_FEATURE_SH_STANDALONE
3913 restore_redirects(squirrel);
3914 unset_vars(new_env);
3917 free(argv_expanded);
3918 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3920 debug_printf_exec("run_pipe return %d\n", rcode);
3924 #if ENABLE_FEATURE_SH_STANDALONE
3925 i = find_applet_by_name(argv_expanded[0]);
3926 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3927 rcode = setup_redirects(command, squirrel);
3929 new_env = expand_assignments(argv, command->assignment_cnt);
3930 old_vars = set_vars_and_save_old(new_env);
3931 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3932 argv_expanded[0], argv_expanded[1]);
3933 rcode = run_nofork_applet(i, argv_expanded);
3935 goto clean_up_and_ret;
3938 /* It is neither builtin nor applet. We must fork. */
3942 /* NB: argv_expanded may already be created, and that
3943 * might include `cmd` runs! Do not rerun it! We *must*
3944 * use argv_expanded if it's non-NULL */
3946 /* Going to fork a child per each pipe member */
3950 for (i = 0; i < pi->num_cmds; i++) {
3951 struct fd_pair pipefds;
3953 volatile nommu_save_t nommu_save;
3954 nommu_save.new_env = NULL;
3955 nommu_save.old_vars = NULL;
3956 nommu_save.argv = NULL;
3957 nommu_save.argv_from_re_execing = NULL;
3959 command = &(pi->cmds[i]);
3960 if (command->argv) {
3961 debug_printf_exec(": pipe member '%s' '%s'...\n",
3962 command->argv[0], command->argv[1]);
3964 debug_printf_exec(": pipe member with no argv\n");
3967 /* pipes are inserted between pairs of commands */
3970 if ((i + 1) < pi->num_cmds)
3971 xpiped_pair(pipefds);
3973 command->pid = BB_MMU ? fork() : vfork();
3974 if (!command->pid) { /* child */
3976 disable_restore_tty_pgrp_on_exit();
3978 /* Every child adds itself to new process group
3979 * with pgid == pid_of_first_child_in_pipe */
3980 if (G.run_list_level == 1 && G_interactive_fd) {
3983 if (pgrp < 0) /* true for 1st process only */
3985 if (setpgid(0, pgrp) == 0
3986 && pi->followup != PIPE_BG
3987 && G_saved_tty_pgrp /* we have ctty */
3989 /* We do it in *every* child, not just first,
3991 tcsetpgrp(G_interactive_fd, pgrp);
3995 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3996 /* 1st cmd in backgrounded pipe
3997 * should have its stdin /dev/null'ed */
3999 if (open(bb_dev_null, O_RDONLY))
4000 xopen("/", O_RDONLY);
4002 xmove_fd(nextin, 0);
4004 xmove_fd(pipefds.wr, 1);
4007 /* Like bash, explicit redirects override pipes,
4008 * and the pipe fd is available for dup'ing. */
4009 if (setup_redirects(command, NULL))
4012 /* Restore default handlers just prior to exec */
4013 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4015 /* Stores to nommu_save list of env vars putenv'ed
4016 * (NOMMU, on MMU we don't need that) */
4017 /* cast away volatility... */
4018 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4019 /* pseudo_exec() does not return */
4022 /* parent or error */
4023 #if ENABLE_HUSH_FAST
4025 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4027 enable_restore_tty_pgrp_on_exit();
4029 /* Clean up after vforked child */
4030 free(nommu_save.argv);
4031 free(nommu_save.argv_from_re_execing);
4032 unset_vars(nommu_save.new_env);
4033 add_vars(nommu_save.old_vars);
4035 free(argv_expanded);
4036 argv_expanded = NULL;
4037 if (command->pid < 0) { /* [v]fork failed */
4038 /* Clearly indicate, was it fork or vfork */
4039 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4043 /* Second and next children need to know pid of first one */
4045 pi->pgrp = command->pid;
4051 if ((i + 1) < pi->num_cmds)
4053 /* Pass read (output) pipe end to next iteration */
4054 nextin = pipefds.rd;
4057 if (!pi->alive_cmds) {
4059 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4064 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4068 #ifndef debug_print_tree
4069 static void debug_print_tree(struct pipe *pi, int lvl)
4071 static const char *const PIPE[] = {
4077 static const char *RES[] = {
4078 [RES_NONE ] = "NONE" ,
4081 [RES_THEN ] = "THEN" ,
4082 [RES_ELIF ] = "ELIF" ,
4083 [RES_ELSE ] = "ELSE" ,
4086 #if ENABLE_HUSH_LOOPS
4087 [RES_FOR ] = "FOR" ,
4088 [RES_WHILE] = "WHILE",
4089 [RES_UNTIL] = "UNTIL",
4091 [RES_DONE ] = "DONE" ,
4093 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4096 #if ENABLE_HUSH_CASE
4097 [RES_CASE ] = "CASE" ,
4098 [RES_CASE_IN ] = "CASE_IN" ,
4099 [RES_MATCH] = "MATCH",
4100 [RES_CASE_BODY] = "CASE_BODY",
4101 [RES_ESAC ] = "ESAC" ,
4103 [RES_XXXX ] = "XXXX" ,
4104 [RES_SNTX ] = "SNTX" ,
4106 static const char *const CMDTYPE[] = {
4110 #if ENABLE_HUSH_FUNCTIONS
4119 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4120 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4122 while (prn < pi->num_cmds) {
4123 struct command *command = &pi->cmds[prn];
4124 char **argv = command->argv;
4126 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4128 command->assignment_cnt);
4129 if (command->group) {
4130 fprintf(stderr, " group %s: (argv=%p)\n",
4131 CMDTYPE[command->cmd_type],
4133 debug_print_tree(command->group, lvl+1);
4137 if (argv) while (*argv) {
4138 fprintf(stderr, " '%s'", *argv);
4141 fprintf(stderr, "\n");
4150 /* NB: called by pseudo_exec, and therefore must not modify any
4151 * global data until exec/_exit (we can be a child after vfork!) */
4152 static int run_list(struct pipe *pi)
4154 #if ENABLE_HUSH_CASE
4155 char *case_word = NULL;
4157 #if ENABLE_HUSH_LOOPS
4158 struct pipe *loop_top = NULL;
4159 char **for_lcur = NULL;
4160 char **for_list = NULL;
4162 smallint last_followup;
4164 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4165 smalluint cond_code = 0;
4167 enum { cond_code = 0 };
4170 smallint rword; /* enum reserved_style */
4171 smallint last_rword; /* ditto */
4174 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4177 #if ENABLE_HUSH_LOOPS
4178 /* Check syntax for "for" */
4179 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4180 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4182 /* current word is FOR or IN (BOLD in comments below) */
4183 if (cpipe->next == NULL) {
4184 syntax_error("malformed for");
4186 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4189 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4190 if (cpipe->next->res_word == RES_DO)
4192 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4193 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4194 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4196 syntax_error("malformed for");
4198 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4204 /* Past this point, all code paths should jump to ret: label
4205 * in order to return, no direct "return" statements please.
4206 * This helps to ensure that no memory is leaked. */
4214 last_rword = RES_XXXX;
4216 last_followup = PIPE_SEQ;
4217 rcode = G.last_exitcode;
4219 /* Go through list of pipes, (maybe) executing them. */
4220 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4224 IF_HAS_KEYWORDS(rword = pi->res_word;)
4225 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4226 rword, cond_code, last_rword);
4227 #if ENABLE_HUSH_LOOPS
4228 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4229 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4231 /* start of a loop: remember where loop starts */
4236 /* Still in the same "if...", "then..." or "do..." branch? */
4237 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4238 if ((rcode == 0 && last_followup == PIPE_OR)
4239 || (rcode != 0 && last_followup == PIPE_AND)
4241 /* It is "<true> || CMD" or "<false> && CMD"
4242 * and we should not execute CMD */
4243 debug_printf_exec("skipped cmd because of || or &&\n");
4244 last_followup = pi->followup;
4248 last_followup = pi->followup;
4249 IF_HAS_KEYWORDS(last_rword = rword;)
4252 if (rword == RES_THEN) {
4253 /* if false; then ... fi has exitcode 0! */
4254 G.last_exitcode = rcode = EXIT_SUCCESS;
4255 /* "if <false> THEN cmd": skip cmd */
4259 if (rword == RES_ELSE || rword == RES_ELIF) {
4260 /* "if <true> then ... ELSE/ELIF cmd":
4261 * skip cmd and all following ones */
4266 #if ENABLE_HUSH_LOOPS
4267 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4269 /* first loop through for */
4271 static const char encoded_dollar_at[] ALIGN1 = {
4272 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4273 }; /* encoded representation of "$@" */
4274 static const char *const encoded_dollar_at_argv[] = {
4275 encoded_dollar_at, NULL
4276 }; /* argv list with one element: "$@" */
4279 vals = (char**)encoded_dollar_at_argv;
4280 if (pi->next->res_word == RES_IN) {
4281 /* if no variable values after "in" we skip "for" */
4282 if (!pi->next->cmds[0].argv) {
4283 G.last_exitcode = rcode = EXIT_SUCCESS;
4284 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4287 vals = pi->next->cmds[0].argv;
4288 } /* else: "for var; do..." -> assume "$@" list */
4289 /* create list of variable values */
4290 debug_print_strings("for_list made from", vals);
4291 for_list = expand_strvec_to_strvec(vals);
4292 for_lcur = for_list;
4293 debug_print_strings("for_list", for_list);
4296 /* "for" loop is over, clean up */
4302 /* Insert next value from for_lcur */
4303 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4304 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4307 if (rword == RES_IN) {
4308 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4310 if (rword == RES_DONE) {
4311 continue; /* "done" has no cmds too */
4314 #if ENABLE_HUSH_CASE
4315 if (rword == RES_CASE) {
4316 case_word = expand_strvec_to_string(pi->cmds->argv);
4319 if (rword == RES_MATCH) {
4322 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4324 /* all prev words didn't match, does this one match? */
4325 argv = pi->cmds->argv;
4327 char *pattern = expand_string_to_string(*argv);
4328 /* TODO: which FNM_xxx flags to use? */
4329 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4331 if (cond_code == 0) { /* match! we will execute this branch */
4332 free(case_word); /* make future "word)" stop */
4340 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4342 continue; /* not matched yet, skip this pipe */
4345 /* Just pressing <enter> in shell should check for jobs.
4346 * OTOH, in non-interactive shell this is useless
4347 * and only leads to extra job checks */
4348 if (pi->num_cmds == 0) {
4349 if (G_interactive_fd)
4350 goto check_jobs_and_continue;
4354 /* After analyzing all keywords and conditions, we decided
4355 * to execute this pipe. NB: have to do checkjobs(NULL)
4356 * after run_pipe to collect any background children,
4357 * even if list execution is to be stopped. */
4358 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4361 #if ENABLE_HUSH_LOOPS
4362 G.flag_break_continue = 0;
4364 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4366 /* We ran a builtin, function, or group.
4367 * rcode is already known
4368 * and we don't need to wait for anything. */
4369 G.last_exitcode = rcode;
4370 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4371 check_and_run_traps(0);
4372 #if ENABLE_HUSH_LOOPS
4373 /* Was it "break" or "continue"? */
4374 if (G.flag_break_continue) {
4375 smallint fbc = G.flag_break_continue;
4376 /* We might fall into outer *loop*,
4377 * don't want to break it too */
4379 G.depth_break_continue--;
4380 if (G.depth_break_continue == 0)
4381 G.flag_break_continue = 0;
4382 /* else: e.g. "continue 2" should *break* once, *then* continue */
4383 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4384 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4385 goto check_jobs_and_break;
4386 /* "continue": simulate end of loop */
4391 #if ENABLE_HUSH_FUNCTIONS
4392 if (G.flag_return_in_progress == 1) {
4393 /* same as "goto check_jobs_and_break" */
4398 } else if (pi->followup == PIPE_BG) {
4399 /* What does bash do with attempts to background builtins? */
4400 /* even bash 3.2 doesn't do that well with nested bg:
4401 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4402 * I'm NOT treating inner &'s as jobs */
4403 check_and_run_traps(0);
4405 if (G.run_list_level == 1)
4408 G.last_exitcode = rcode = EXIT_SUCCESS;
4409 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4412 if (G.run_list_level == 1 && G_interactive_fd) {
4413 /* Waits for completion, then fg's main shell */
4414 rcode = checkjobs_and_fg_shell(pi);
4415 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4416 check_and_run_traps(0);
4419 { /* This one just waits for completion */
4420 rcode = checkjobs(pi);
4421 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4422 check_and_run_traps(0);
4424 G.last_exitcode = rcode;
4428 /* Analyze how result affects subsequent commands */
4430 if (rword == RES_IF || rword == RES_ELIF)
4433 #if ENABLE_HUSH_LOOPS
4434 /* Beware of "while false; true; do ..."! */
4435 if (pi->next && pi->next->res_word == RES_DO) {
4436 if (rword == RES_WHILE) {
4438 /* "while false; do...done" - exitcode 0 */
4439 G.last_exitcode = rcode = EXIT_SUCCESS;
4440 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4441 goto check_jobs_and_break;
4444 if (rword == RES_UNTIL) {
4446 debug_printf_exec(": until expr is true: breaking\n");
4447 check_jobs_and_break:
4455 check_jobs_and_continue:
4462 #if ENABLE_HUSH_LOOPS
4467 #if ENABLE_HUSH_CASE
4471 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4475 /* Select which version we will use */
4476 static int run_and_free_list(struct pipe *pi)
4479 debug_printf_exec("run_and_free_list entered\n");
4481 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4482 rcode = run_list(pi);
4484 /* free_pipe_list has the side effect of clearing memory.
4485 * In the long run that function can be merged with run_list,
4486 * but doing that now would hobble the debugging effort. */
4488 debug_printf_exec("run_and_free_list return %d\n", rcode);
4493 static struct pipe *new_pipe(void)
4496 pi = xzalloc(sizeof(struct pipe));
4497 /*pi->followup = 0; - deliberately invalid value */
4498 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4502 /* Command (member of a pipe) is complete, or we start a new pipe
4503 * if ctx->command is NULL.
4504 * No errors possible here.
4506 static int done_command(struct parse_context *ctx)
4508 /* The command is really already in the pipe structure, so
4509 * advance the pipe counter and make a new, null command. */
4510 struct pipe *pi = ctx->pipe;
4511 struct command *command = ctx->command;
4514 if (IS_NULL_CMD(command)) {
4515 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4519 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4520 //debug_print_tree(ctx->list_head, 20);
4522 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4525 /* Only real trickiness here is that the uncommitted
4526 * command structure is not counted in pi->num_cmds. */
4527 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4528 ctx->command = command = &pi->cmds[pi->num_cmds];
4530 memset(command, 0, sizeof(*command));
4531 return pi->num_cmds; /* used only for 0/nonzero check */
4534 static void done_pipe(struct parse_context *ctx, pipe_style type)
4538 debug_printf_parse("done_pipe entered, followup %d\n", type);
4539 /* Close previous command */
4540 not_null = done_command(ctx);
4541 ctx->pipe->followup = type;
4543 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4544 ctx->ctx_inverted = 0;
4545 ctx->pipe->res_word = ctx->ctx_res_w;
4548 /* Without this check, even just <enter> on command line generates
4549 * tree of three NOPs (!). Which is harmless but annoying.
4550 * IOW: it is safe to do it unconditionally. */
4553 || ctx->ctx_res_w == RES_FI
4555 #if ENABLE_HUSH_LOOPS
4556 || ctx->ctx_res_w == RES_DONE
4557 || ctx->ctx_res_w == RES_FOR
4558 || ctx->ctx_res_w == RES_IN
4560 #if ENABLE_HUSH_CASE
4561 || ctx->ctx_res_w == RES_ESAC
4565 debug_printf_parse("done_pipe: adding new pipe: "
4566 "not_null:%d ctx->ctx_res_w:%d\n",
4567 not_null, ctx->ctx_res_w);
4569 ctx->pipe->next = new_p;
4571 /* RES_THEN, RES_DO etc are "sticky" -
4572 * they remain set for pipes inside if/while.
4573 * This is used to control execution.
4574 * RES_FOR and RES_IN are NOT sticky (needed to support
4575 * cases where variable or value happens to match a keyword):
4577 #if ENABLE_HUSH_LOOPS
4578 if (ctx->ctx_res_w == RES_FOR
4579 || ctx->ctx_res_w == RES_IN)
4580 ctx->ctx_res_w = RES_NONE;
4582 #if ENABLE_HUSH_CASE
4583 if (ctx->ctx_res_w == RES_MATCH)
4584 ctx->ctx_res_w = RES_CASE_BODY;
4585 if (ctx->ctx_res_w == RES_CASE)
4586 ctx->ctx_res_w = RES_CASE_IN;
4588 ctx->command = NULL; /* trick done_command below */
4589 /* Create the memory for command, roughly:
4590 * ctx->pipe->cmds = new struct command;
4591 * ctx->command = &ctx->pipe->cmds[0];
4594 //debug_print_tree(ctx->list_head, 10);
4596 debug_printf_parse("done_pipe return\n");
4599 static void initialize_context(struct parse_context *ctx)
4601 memset(ctx, 0, sizeof(*ctx));
4602 ctx->pipe = ctx->list_head = new_pipe();
4603 /* Create the memory for command, roughly:
4604 * ctx->pipe->cmds = new struct command;
4605 * ctx->command = &ctx->pipe->cmds[0];
4610 /* If a reserved word is found and processed, parse context is modified
4611 * and 1 is returned.
4614 struct reserved_combo {
4617 unsigned char assignment_flag;
4621 FLAG_END = (1 << RES_NONE ),
4623 FLAG_IF = (1 << RES_IF ),
4624 FLAG_THEN = (1 << RES_THEN ),
4625 FLAG_ELIF = (1 << RES_ELIF ),
4626 FLAG_ELSE = (1 << RES_ELSE ),
4627 FLAG_FI = (1 << RES_FI ),
4629 #if ENABLE_HUSH_LOOPS
4630 FLAG_FOR = (1 << RES_FOR ),
4631 FLAG_WHILE = (1 << RES_WHILE),
4632 FLAG_UNTIL = (1 << RES_UNTIL),
4633 FLAG_DO = (1 << RES_DO ),
4634 FLAG_DONE = (1 << RES_DONE ),
4635 FLAG_IN = (1 << RES_IN ),
4637 #if ENABLE_HUSH_CASE
4638 FLAG_MATCH = (1 << RES_MATCH),
4639 FLAG_ESAC = (1 << RES_ESAC ),
4641 FLAG_START = (1 << RES_XXXX ),
4644 static const struct reserved_combo* match_reserved_word(o_string *word)
4646 /* Mostly a list of accepted follow-up reserved words.
4647 * FLAG_END means we are done with the sequence, and are ready
4648 * to turn the compound list into a command.
4649 * FLAG_START means the word must start a new compound list.
4651 static const struct reserved_combo reserved_list[] = {
4653 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4654 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4655 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4656 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4657 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4658 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4660 #if ENABLE_HUSH_LOOPS
4661 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4662 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4663 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4664 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4665 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4666 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4668 #if ENABLE_HUSH_CASE
4669 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4670 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4673 const struct reserved_combo *r;
4675 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4676 if (strcmp(word->data, r->literal) == 0)
4681 /* Return 0: not a keyword, 1: keyword
4683 static int reserved_word(o_string *word, struct parse_context *ctx)
4685 #if ENABLE_HUSH_CASE
4686 static const struct reserved_combo reserved_match = {
4687 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4690 const struct reserved_combo *r;
4694 r = match_reserved_word(word);
4698 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4699 #if ENABLE_HUSH_CASE
4700 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4701 /* "case word IN ..." - IN part starts first MATCH part */
4702 r = &reserved_match;
4705 if (r->flag == 0) { /* '!' */
4706 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4707 syntax_error("! ! command");
4708 ctx->ctx_res_w = RES_SNTX;
4710 ctx->ctx_inverted = 1;
4713 if (r->flag & FLAG_START) {
4714 struct parse_context *old;
4716 old = xmalloc(sizeof(*old));
4717 debug_printf_parse("push stack %p\n", old);
4718 *old = *ctx; /* physical copy */
4719 initialize_context(ctx);
4721 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4722 syntax_error_at(word->data);
4723 ctx->ctx_res_w = RES_SNTX;
4726 /* "{...} fi" is ok. "{...} if" is not
4728 * if { echo foo; } then { echo bar; } fi */
4729 if (ctx->command->group)
4730 done_pipe(ctx, PIPE_SEQ);
4733 ctx->ctx_res_w = r->res;
4734 ctx->old_flag = r->flag;
4735 word->o_assignment = r->assignment_flag;
4737 if (ctx->old_flag & FLAG_END) {
4738 struct parse_context *old;
4740 done_pipe(ctx, PIPE_SEQ);
4741 debug_printf_parse("pop stack %p\n", ctx->stack);
4743 old->command->group = ctx->list_head;
4744 old->command->cmd_type = CMD_NORMAL;
4746 o_addstr(&old->as_string, ctx->as_string.data);
4747 o_free_unsafe(&ctx->as_string);
4748 old->command->group_as_string = xstrdup(old->as_string.data);
4749 debug_printf_parse("pop, remembering as:'%s'\n",
4750 old->command->group_as_string);
4752 *ctx = *old; /* physical copy */
4759 /* Word is complete, look at it and update parsing context.
4760 * Normal return is 0. Syntax errors return 1.
4761 * Note: on return, word is reset, but not o_free'd!
4763 static int done_word(o_string *word, struct parse_context *ctx)
4765 struct command *command = ctx->command;
4767 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4768 if (word->length == 0 && word->o_quoted == 0) {
4769 debug_printf_parse("done_word return 0: true null, ignored\n");
4773 if (ctx->pending_redirect) {
4774 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4775 * only if run as "bash", not "sh" */
4776 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4778 * ...the word that follows the redirection operator
4779 * shall be subjected to tilde expansion, parameter expansion,
4780 * command substitution, arithmetic expansion, and quote
4781 * removal. Pathname expansion shall not be performed
4782 * on the word by a non-interactive shell; an interactive
4783 * shell may perform it, but shall do so only when
4784 * the expansion would result in one word."
4786 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4787 /* Cater for >\file case:
4788 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4789 * Same with heredocs:
4790 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4792 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4793 unbackslash(ctx->pending_redirect->rd_filename);
4794 /* Is it <<"HEREDOC"? */
4795 if (word->o_quoted) {
4796 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4799 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4800 ctx->pending_redirect = NULL;
4802 /* If this word wasn't an assignment, next ones definitely
4803 * can't be assignments. Even if they look like ones. */
4804 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4805 && word->o_assignment != WORD_IS_KEYWORD
4807 word->o_assignment = NOT_ASSIGNMENT;
4809 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4810 command->assignment_cnt++;
4811 word->o_assignment = MAYBE_ASSIGNMENT;
4815 # if ENABLE_HUSH_CASE
4816 if (ctx->ctx_dsemicolon
4817 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4819 /* already done when ctx_dsemicolon was set to 1: */
4820 /* ctx->ctx_res_w = RES_MATCH; */
4821 ctx->ctx_dsemicolon = 0;
4824 if (!command->argv /* if it's the first word... */
4825 # if ENABLE_HUSH_LOOPS
4826 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4827 && ctx->ctx_res_w != RES_IN
4829 # if ENABLE_HUSH_CASE
4830 && ctx->ctx_res_w != RES_CASE
4833 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4834 if (reserved_word(word, ctx)) {
4835 o_reset_to_empty_unquoted(word);
4836 debug_printf_parse("done_word return %d\n",
4837 (ctx->ctx_res_w == RES_SNTX));
4838 return (ctx->ctx_res_w == RES_SNTX);
4840 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4841 if (strcmp(word->data, "export") == 0
4842 # if ENABLE_HUSH_LOCAL
4843 || strcmp(word->data, "local") == 0
4846 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4849 # if ENABLE_HUSH_BASH_COMPAT
4850 if (strcmp(word->data, "[[") == 0) {
4851 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4857 if (command->group) {
4858 /* "{ echo foo; } echo bar" - bad */
4859 syntax_error_at(word->data);
4860 debug_printf_parse("done_word return 1: syntax error, "
4861 "groups and arglists don't mix\n");
4864 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4865 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4866 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4867 /* (otherwise it's known to be not empty and is already safe) */
4869 /* exclude "$@" - it can expand to no word despite "" */
4870 char *p = word->data;
4871 while (p[0] == SPECIAL_VAR_SYMBOL
4872 && (p[1] & 0x7f) == '@'
4873 && p[2] == SPECIAL_VAR_SYMBOL
4877 if (p == word->data || p[0] != '\0') {
4878 /* saw no "$@", or not only "$@" but some
4879 * real text is there too */
4880 /* insert "empty variable" reference, this makes
4881 * e.g. "", $empty"" etc to not disappear */
4882 o_addchr(word, SPECIAL_VAR_SYMBOL);
4883 o_addchr(word, SPECIAL_VAR_SYMBOL);
4886 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4887 debug_print_strings("word appended to argv", command->argv);
4890 #if ENABLE_HUSH_LOOPS
4891 if (ctx->ctx_res_w == RES_FOR) {
4893 || !is_well_formed_var_name(command->argv[0], '\0')
4895 /* bash says just "not a valid identifier" */
4896 syntax_error("not a valid identifier in for");
4899 /* Force FOR to have just one word (variable name) */
4900 /* NB: basically, this makes hush see "for v in ..."
4901 * syntax as if it is "for v; in ...". FOR and IN become
4902 * two pipe structs in parse tree. */
4903 done_pipe(ctx, PIPE_SEQ);
4906 #if ENABLE_HUSH_CASE
4907 /* Force CASE to have just one word */
4908 if (ctx->ctx_res_w == RES_CASE) {
4909 done_pipe(ctx, PIPE_SEQ);
4913 o_reset_to_empty_unquoted(word);
4915 debug_printf_parse("done_word return 0\n");
4920 /* Peek ahead in the input to find out if we have a "&n" construct,
4921 * as in "2>&1", that represents duplicating a file descriptor.
4923 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4924 * REDIRFD_SYNTAX_ERR if syntax error,
4925 * REDIRFD_TO_FILE if no & was seen,
4926 * or the number found.
4929 #define parse_redir_right_fd(as_string, input) \
4930 parse_redir_right_fd(input)
4932 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4938 return REDIRFD_TO_FILE;
4940 ch = i_getch(input); /* get the & */
4941 nommu_addchr(as_string, ch);
4944 ch = i_getch(input);
4945 nommu_addchr(as_string, ch);
4946 return REDIRFD_CLOSE;
4950 while (ch != EOF && isdigit(ch)) {
4951 d = d*10 + (ch-'0');
4953 ch = i_getch(input);
4954 nommu_addchr(as_string, ch);
4959 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4961 bb_error_msg("ambiguous redirect");
4962 return REDIRFD_SYNTAX_ERR;
4965 /* Return code is 0 normal, 1 if a syntax error is detected
4967 static int parse_redirect(struct parse_context *ctx,
4970 struct in_str *input)
4972 struct command *command = ctx->command;
4973 struct redir_struct *redir;
4974 struct redir_struct **redirp;
4977 dup_num = REDIRFD_TO_FILE;
4978 if (style != REDIRECT_HEREDOC) {
4979 /* Check for a '>&1' type redirect */
4980 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4981 if (dup_num == REDIRFD_SYNTAX_ERR)
4984 int ch = i_peek(input);
4985 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4986 if (dup_num) { /* <<-... */
4987 ch = i_getch(input);
4988 nommu_addchr(&ctx->as_string, ch);
4993 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4994 int ch = i_peek(input);
4996 /* >|FILE redirect ("clobbering" >).
4997 * Since we do not support "set -o noclobber" yet,
4998 * >| and > are the same for now. Just eat |.
5000 ch = i_getch(input);
5001 nommu_addchr(&ctx->as_string, ch);
5005 /* Create a new redir_struct and append it to the linked list */
5006 redirp = &command->redirects;
5007 while ((redir = *redirp) != NULL) {
5008 redirp = &(redir->next);
5010 *redirp = redir = xzalloc(sizeof(*redir));
5011 /* redir->next = NULL; */
5012 /* redir->rd_filename = NULL; */
5013 redir->rd_type = style;
5014 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5016 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5017 redir_table[style].descrip);
5019 redir->rd_dup = dup_num;
5020 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5021 /* Erik had a check here that the file descriptor in question
5022 * is legit; I postpone that to "run time"
5023 * A "-" representation of "close me" shows up as a -3 here */
5024 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5025 redir->rd_fd, redir->rd_dup);
5027 /* Set ctx->pending_redirect, so we know what to do at the
5028 * end of the next parsed word. */
5029 ctx->pending_redirect = redir;
5034 /* If a redirect is immediately preceded by a number, that number is
5035 * supposed to tell which file descriptor to redirect. This routine
5036 * looks for such preceding numbers. In an ideal world this routine
5037 * needs to handle all the following classes of redirects...
5038 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5039 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5040 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5041 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5043 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5045 * ... If n is quoted, the number shall not be recognized as part of
5046 * the redirection expression. For example:
5048 * writes the character 2 into file a"
5049 * We are getting it right by setting ->o_quoted on any \<char>
5051 * A -1 return means no valid number was found,
5052 * the caller should use the appropriate default for this redirection.
5054 static int redirect_opt_num(o_string *o)
5058 if (o->data == NULL)
5060 num = bb_strtou(o->data, NULL, 10);
5061 if (errno || num < 0)
5063 o_reset_to_empty_unquoted(o);
5068 #define fetch_till_str(as_string, input, word, skip_tabs) \
5069 fetch_till_str(input, word, skip_tabs)
5071 static char *fetch_till_str(o_string *as_string,
5072 struct in_str *input,
5076 o_string heredoc = NULL_O_STRING;
5082 ch = i_getch(input);
5083 nommu_addchr(as_string, ch);
5085 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5086 heredoc.data[past_EOL] = '\0';
5087 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5088 return heredoc.data;
5091 o_addchr(&heredoc, ch);
5092 past_EOL = heredoc.length;
5095 ch = i_getch(input);
5096 nommu_addchr(as_string, ch);
5097 } while (skip_tabs && ch == '\t');
5098 } while (ch == '\n');
5101 o_free_unsafe(&heredoc);
5104 o_addchr(&heredoc, ch);
5105 nommu_addchr(as_string, ch);
5109 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5110 * and load them all. There should be exactly heredoc_cnt of them.
5112 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5114 struct pipe *pi = ctx->list_head;
5116 while (pi && heredoc_cnt) {
5118 struct command *cmd = pi->cmds;
5120 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5122 cmd->argv ? cmd->argv[0] : "NONE");
5123 for (i = 0; i < pi->num_cmds; i++) {
5124 struct redir_struct *redir = cmd->redirects;
5126 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5127 i, cmd->argv ? cmd->argv[0] : "NONE");
5129 if (redir->rd_type == REDIRECT_HEREDOC) {
5132 redir->rd_type = REDIRECT_HEREDOC2;
5133 /* redir->rd_dup is (ab)used to indicate <<- */
5134 p = fetch_till_str(&ctx->as_string, input,
5135 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5137 syntax_error("unexpected EOF in here document");
5140 free(redir->rd_filename);
5141 redir->rd_filename = p;
5144 redir = redir->next;
5151 /* Should be 0. If it isn't, it's a parse error */
5153 bb_error_msg_and_die("heredoc BUG 2");
5159 #if ENABLE_HUSH_TICK
5160 static FILE *generate_stream_from_string(const char *s)
5163 int pid, channel[2];
5169 pid = BB_MMU ? fork() : vfork();
5171 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5173 if (pid == 0) { /* child */
5174 disable_restore_tty_pgrp_on_exit();
5175 /* Process substitution is not considered to be usual
5176 * 'command execution'.
5177 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5184 close(channel[0]); /* NB: close _first_, then move fd! */
5185 xmove_fd(channel[1], 1);
5186 /* Prevent it from trying to handle ctrl-z etc */
5187 IF_HUSH_JOB(G.run_list_level = 1;)
5189 reset_traps_to_defaults();
5190 parse_and_run_string(s);
5191 _exit(G.last_exitcode);
5193 /* We re-execute after vfork on NOMMU. This makes this script safe:
5194 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5195 * huge=`cat BIG` # was blocking here forever
5198 re_execute_shell(&to_free,
5207 #if ENABLE_HUSH_FAST
5209 //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);
5211 enable_restore_tty_pgrp_on_exit();
5216 pf = fdopen(channel[0], "r");
5220 /* Return code is exit status of the process that is run. */
5221 static int process_command_subs(o_string *dest, const char *s)
5224 struct in_str pipe_str;
5227 pf = generate_stream_from_string(s);
5230 close_on_exec_on(fileno(pf));
5232 /* Now send results of command back into original context */
5233 setup_file_in_str(&pipe_str, pf);
5235 while ((ch = i_getch(&pipe_str)) != EOF) {
5241 o_addchr(dest, '\n');
5244 o_addQchr(dest, ch);
5247 debug_printf("done reading from pipe, pclose()ing\n");
5248 /* Note: we got EOF, and we just close the read end of the pipe.
5249 * We do not wait for the `cmd` child to terminate. bash and ash do.
5251 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5252 * `false`; echo $? - bash outputs "1"
5255 debug_printf("closed FILE from child. return 0\n");
5260 static int parse_group(o_string *dest, struct parse_context *ctx,
5261 struct in_str *input, int ch)
5263 /* dest contains characters seen prior to ( or {.
5264 * Typically it's empty, but for function defs,
5265 * it contains function name (without '()'). */
5266 struct pipe *pipe_list;
5268 struct command *command = ctx->command;
5270 debug_printf_parse("parse_group entered\n");
5271 #if ENABLE_HUSH_FUNCTIONS
5272 if (ch == '(' && !dest->o_quoted) {
5274 if (done_word(dest, ctx))
5277 goto skip; /* (... */
5278 if (command->argv[1]) { /* word word ... (... */
5279 syntax_error_unexpected_ch('(');
5282 /* it is "word(..." or "word (..." */
5284 ch = i_getch(input);
5285 while (ch == ' ' || ch == '\t');
5287 syntax_error_unexpected_ch(ch);
5290 nommu_addchr(&ctx->as_string, ch);
5292 ch = i_getch(input);
5293 while (ch == ' ' || ch == '\t' || ch == '\n');
5295 syntax_error_unexpected_ch(ch);
5298 nommu_addchr(&ctx->as_string, ch);
5299 command->cmd_type = CMD_FUNCDEF;
5303 if (command->argv /* word [word]{... */
5304 || dest->length /* word{... */
5305 || dest->o_quoted /* ""{... */
5308 debug_printf_parse("parse_group return 1: "
5309 "syntax error, groups and arglists don't mix\n");
5313 #if ENABLE_HUSH_FUNCTIONS
5319 command->cmd_type = CMD_SUBSHELL;
5321 /* bash does not allow "{echo...", requires whitespace */
5322 ch = i_getch(input);
5323 if (ch != ' ' && ch != '\t' && ch != '\n') {
5324 syntax_error_unexpected_ch(ch);
5327 nommu_addchr(&ctx->as_string, ch);
5332 char *as_string = NULL;
5334 pipe_list = parse_stream(&as_string, input, endch);
5337 o_addstr(&ctx->as_string, as_string);
5339 /* empty ()/{} or parse error? */
5340 if (!pipe_list || pipe_list == ERR_PTR) {
5341 /* parse_stream already emitted error msg */
5345 debug_printf_parse("parse_group return 1: "
5346 "parse_stream returned %p\n", pipe_list);
5349 command->group = pipe_list;
5351 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5352 command->group_as_string = as_string;
5353 debug_printf_parse("end of group, remembering as:'%s'\n",
5354 command->group_as_string);
5357 debug_printf_parse("parse_group return 0\n");
5359 /* command remains "open", available for possible redirects */
5362 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5363 /* Subroutines for copying $(...) and `...` things */
5364 static void add_till_backquote(o_string *dest, struct in_str *input);
5366 static void add_till_single_quote(o_string *dest, struct in_str *input)
5369 int ch = i_getch(input);
5371 syntax_error_unterm_ch('\'');
5372 /*xfunc_die(); - redundant */
5379 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5380 static void add_till_double_quote(o_string *dest, struct in_str *input)
5383 int ch = i_getch(input);
5385 syntax_error_unterm_ch('"');
5386 /*xfunc_die(); - redundant */
5390 if (ch == '\\') { /* \x. Copy both chars. */
5392 ch = i_getch(input);
5396 add_till_backquote(dest, input);
5400 //if (ch == '$') ...
5403 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5405 * "Within the backquoted style of command substitution, backslash
5406 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5407 * The search for the matching backquote shall be satisfied by the first
5408 * backquote found without a preceding backslash; during this search,
5409 * if a non-escaped backquote is encountered within a shell comment,
5410 * a here-document, an embedded command substitution of the $(command)
5411 * form, or a quoted string, undefined results occur. A single-quoted
5412 * or double-quoted string that begins, but does not end, within the
5413 * "`...`" sequence produces undefined results."
5415 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5417 static void add_till_backquote(o_string *dest, struct in_str *input)
5420 int ch = i_getch(input);
5422 syntax_error_unterm_ch('`');
5423 /*xfunc_die(); - redundant */
5428 /* \x. Copy both chars unless it is \` */
5429 int ch2 = i_getch(input);
5431 syntax_error_unterm_ch('`');
5432 /*xfunc_die(); - redundant */
5434 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5441 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5442 * quoting and nested ()s.
5443 * "With the $(command) style of command substitution, all characters
5444 * following the open parenthesis to the matching closing parenthesis
5445 * constitute the command. Any valid shell script can be used for command,
5446 * except a script consisting solely of redirections which produces
5447 * unspecified results."
5449 * echo $(echo '(TEST)' BEST) (TEST) BEST
5450 * echo $(echo 'TEST)' BEST) TEST) BEST
5451 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5453 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5457 int ch = i_getch(input);
5459 syntax_error_unterm_ch(')');
5460 /*xfunc_die(); - redundant */
5468 if (i_peek(input) == ')') {
5476 add_till_single_quote(dest, input);
5481 add_till_double_quote(dest, input);
5486 /* \x. Copy verbatim. Important for \(, \) */
5487 ch = i_getch(input);
5489 syntax_error_unterm_ch(')');
5490 /*xfunc_die(); - redundant */
5497 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5499 /* Return code: 0 for OK, 1 for syntax error */
5501 #define handle_dollar(as_string, dest, input) \
5502 handle_dollar(dest, input)
5504 static int handle_dollar(o_string *as_string,
5506 struct in_str *input)
5508 int ch = i_peek(input); /* first character after the $ */
5509 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5511 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5513 ch = i_getch(input);
5514 nommu_addchr(as_string, ch);
5516 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5518 debug_printf_parse(": '%c'\n", ch);
5519 o_addchr(dest, ch | quote_mask);
5522 if (!isalnum(ch) && ch != '_')
5524 ch = i_getch(input);
5525 nommu_addchr(as_string, ch);
5527 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5528 } else if (isdigit(ch)) {
5530 ch = i_getch(input);
5531 nommu_addchr(as_string, ch);
5532 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5533 debug_printf_parse(": '%c'\n", ch);
5534 o_addchr(dest, ch | quote_mask);
5535 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5536 } else switch (ch) {
5538 case '!': /* last bg pid */
5539 case '?': /* last exit code */
5540 case '#': /* number of args */
5541 case '*': /* args */
5542 case '@': /* args */
5543 goto make_one_char_var;
5545 bool first_char, all_digits;
5548 ch = i_getch(input);
5549 nommu_addchr(as_string, ch);
5550 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5552 /* TODO: maybe someone will try to escape the '}' */
5557 ch = i_getch(input);
5558 nommu_addchr(as_string, ch);
5565 /* ${#var}: length of var contents */
5572 /* They're being verbose and doing ${?} */
5573 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5578 && ( (all_digits && !isdigit(ch))
5579 || (!all_digits && !isalnum(ch) && ch != '_')
5582 /* handle parameter expansions
5583 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5588 case ':': /* null modifier */
5589 if (expansion == 0) {
5590 debug_printf_parse(": null modifier\n");
5595 case '#': /* remove prefix */
5596 case '%': /* remove suffix */
5597 if (expansion == 0) {
5598 debug_printf_parse(": remove suffix/prefix\n");
5603 case '-': /* default value */
5604 case '=': /* assign default */
5605 case '+': /* alternative */
5606 case '?': /* error indicate */
5607 debug_printf_parse(": parameter expansion\n");
5612 syntax_error_unterm_str("${name}");
5613 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5618 debug_printf_parse(": '%c'\n", ch);
5619 o_addchr(dest, ch | quote_mask);
5623 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5626 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5631 ch = i_getch(input);
5632 nommu_addchr(as_string, ch);
5633 # if ENABLE_SH_MATH_SUPPORT
5634 if (i_peek(input) == '(') {
5635 ch = i_getch(input);
5636 nommu_addchr(as_string, ch);
5637 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5638 o_addchr(dest, /*quote_mask |*/ '+');
5642 add_till_closing_paren(dest, input, true);
5645 o_addstr(as_string, dest->data + pos);
5646 o_addchr(as_string, ')');
5647 o_addchr(as_string, ')');
5650 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5654 # if ENABLE_HUSH_TICK
5655 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5656 o_addchr(dest, quote_mask | '`');
5660 add_till_closing_paren(dest, input, false);
5663 o_addstr(as_string, dest->data + pos);
5664 o_addchr(as_string, '`');
5667 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5673 ch = i_getch(input);
5674 nommu_addchr(as_string, ch);
5676 if (isalnum(ch)) { /* it's $_name or $_123 */
5682 /* $_ Shell or shell script name; or last cmd name */
5683 /* $- Option flags set by set builtin or shell options (-i etc) */
5685 o_addQchr(dest, '$');
5687 debug_printf_parse("handle_dollar return 0\n");
5692 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5693 parse_stream_dquoted(dest, input, dquote_end)
5695 static int parse_stream_dquoted(o_string *as_string,
5697 struct in_str *input,
5704 ch = i_getch(input);
5706 nommu_addchr(as_string, ch);
5707 if (ch == dquote_end) { /* may be only '"' or EOF */
5708 if (dest->o_assignment == NOT_ASSIGNMENT)
5709 dest->o_escape ^= 1;
5710 debug_printf_parse("parse_stream_dquoted return 0\n");
5713 /* note: can't move it above ch == dquote_end check! */
5715 syntax_error_unterm_ch('"');
5716 /*xfunc_die(); - redundant */
5720 next = i_peek(input);
5722 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5723 ch, ch, dest->o_escape);
5726 syntax_error("\\<eof>");
5730 * "The backslash retains its special meaning [in "..."]
5731 * only when followed by one of the following characters:
5732 * $, `, ", \, or <newline>. A double quote may be quoted
5733 * within double quotes by preceding it with a backslash."
5735 if (strchr("$`\"\\\n", next) != NULL) {
5736 ch = i_getch(input);
5738 o_addqchr(dest, ch);
5739 nommu_addchr(as_string, ch);
5742 o_addqchr(dest, '\\');
5743 nommu_addchr(as_string, '\\');
5748 if (handle_dollar(as_string, dest, input) != 0) {
5749 debug_printf_parse("parse_stream_dquoted return 1: "
5750 "handle_dollar returned non-0\n");
5755 #if ENABLE_HUSH_TICK
5757 //int pos = dest->length;
5758 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5759 o_addchr(dest, 0x80 | '`');
5760 add_till_backquote(dest, input);
5761 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5762 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5766 o_addQchr(dest, ch);
5768 && (dest->o_assignment == MAYBE_ASSIGNMENT
5769 || dest->o_assignment == WORD_IS_KEYWORD)
5770 && is_well_formed_var_name(dest->data, '=')
5772 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5778 * Scan input until EOF or end_trigger char.
5779 * Return a list of pipes to execute, or NULL on EOF
5780 * or if end_trigger character is met.
5781 * On syntax error, exit is shell is not interactive,
5782 * reset parsing machinery and start parsing anew,
5783 * or return ERR_PTR.
5785 static struct pipe *parse_stream(char **pstring,
5786 struct in_str *input,
5789 struct parse_context ctx;
5790 o_string dest = NULL_O_STRING;
5794 /* Double-quote state is handled in the state variable is_in_dquote.
5795 * A single-quote triggers a bypass of the main loop until its mate is
5796 * found. When recursing, quote state is passed in via dest->o_escape.
5798 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5799 end_trigger ? : 'X');
5802 G.ifs = get_local_var_value("IFS");
5807 #if ENABLE_HUSH_INTERACTIVE
5808 input->promptmode = 0; /* PS1 */
5810 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5811 initialize_context(&ctx);
5816 const char *is_special;
5820 redir_type redir_style;
5823 /* dest.o_quoted = 1; - already is (see below) */
5824 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5827 /* We reached closing '"' */
5830 ch = i_getch(input);
5831 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5832 ch, ch, dest.o_escape);
5837 syntax_error_unterm_str("here document");
5840 /* end_trigger == '}' case errors out earlier,
5841 * checking only ')' */
5842 if (end_trigger == ')') {
5843 syntax_error_unterm_ch('('); /* exits */
5844 /* goto parse_error; */
5847 if (done_word(&dest, &ctx)) {
5851 done_pipe(&ctx, PIPE_SEQ);
5853 /* If we got nothing... */
5854 /* (this makes bare "&" cmd a no-op.
5855 * bash says: "syntax error near unexpected token '&'") */
5856 if (pi->num_cmds == 0
5857 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5863 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5865 *pstring = ctx.as_string.data;
5867 o_free_unsafe(&ctx.as_string);
5870 debug_printf_parse("parse_stream return %p\n", pi);
5873 nommu_addchr(&ctx.as_string, ch);
5874 is_ifs = strchr(G.ifs, ch);
5875 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5876 "\\$\"" IF_HUSH_TICK("`") /* always special */
5879 if (!is_special && !is_ifs) { /* ordinary char */
5881 o_addQchr(&dest, ch);
5882 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5883 || dest.o_assignment == WORD_IS_KEYWORD)
5885 && is_well_formed_var_name(dest.data, '=')
5887 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5893 if (done_word(&dest, &ctx)) {
5897 #if ENABLE_HUSH_CASE
5898 /* "case ... in <newline> word) ..." -
5899 * newlines are ignored (but ';' wouldn't be) */
5900 if (ctx.command->argv == NULL
5901 && ctx.ctx_res_w == RES_MATCH
5906 /* Treat newline as a command separator. */
5907 done_pipe(&ctx, PIPE_SEQ);
5908 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5910 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5915 dest.o_assignment = MAYBE_ASSIGNMENT;
5917 /* note: if (is_ifs) continue;
5918 * will still trigger for us */
5922 /* "cmd}" or "cmd }..." without semicolon or &:
5923 * } is an ordinary char in this case, even inside { cmd; }
5924 * Pathological example: { ""}; } should exec "}" cmd
5927 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5928 || dest.length != 0 /* word} */
5929 || dest.o_quoted /* ""} */
5933 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5934 goto skip_end_trigger;
5935 /* else: } does terminate a group */
5938 if (end_trigger && end_trigger == ch
5939 && (ch != ';' || heredoc_cnt == 0)
5940 #if ENABLE_HUSH_CASE
5942 || ctx.ctx_res_w != RES_MATCH
5943 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5948 /* This is technically valid:
5949 * { cat <<HERE; }; echo Ok
5953 * but we don't support this.
5954 * We require heredoc to be in enclosing {}/(),
5957 syntax_error_unterm_str("here document");
5960 if (done_word(&dest, &ctx)) {
5963 done_pipe(&ctx, PIPE_SEQ);
5964 dest.o_assignment = MAYBE_ASSIGNMENT;
5965 /* Do we sit outside of any if's, loops or case's? */
5967 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5971 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5973 *pstring = ctx.as_string.data;
5975 o_free_unsafe(&ctx.as_string);
5978 debug_printf_parse("parse_stream return %p: "
5979 "end_trigger char found\n",
5981 return ctx.list_head;
5990 next = i_peek(input);
5993 /* Catch <, > before deciding whether this word is
5994 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5997 redir_fd = redirect_opt_num(&dest);
5998 if (done_word(&dest, &ctx)) {
6001 redir_style = REDIRECT_OVERWRITE;
6003 redir_style = REDIRECT_APPEND;
6004 ch = i_getch(input);
6005 nommu_addchr(&ctx.as_string, ch);
6008 else if (next == '(') {
6009 syntax_error(">(process) not supported");
6013 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6015 continue; /* back to top of while (1) */
6017 redir_fd = redirect_opt_num(&dest);
6018 if (done_word(&dest, &ctx)) {
6021 redir_style = REDIRECT_INPUT;
6023 redir_style = REDIRECT_HEREDOC;
6025 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6026 ch = i_getch(input);
6027 nommu_addchr(&ctx.as_string, ch);
6028 } else if (next == '>') {
6029 redir_style = REDIRECT_IO;
6030 ch = i_getch(input);
6031 nommu_addchr(&ctx.as_string, ch);
6034 else if (next == '(') {
6035 syntax_error("<(process) not supported");
6039 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6041 continue; /* back to top of while (1) */
6044 if (dest.o_assignment == MAYBE_ASSIGNMENT
6045 /* check that we are not in word in "a=1 2>word b=1": */
6046 && !ctx.pending_redirect
6048 /* ch is a special char and thus this word
6049 * cannot be an assignment */
6050 dest.o_assignment = NOT_ASSIGNMENT;
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, '\\');
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 */
6085 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6086 debug_printf_parse("parse_stream parse error: "
6087 "handle_dollar returned non-0\n");
6094 ch = i_getch(input);
6096 syntax_error_unterm_ch('\'');
6097 /*xfunc_die(); - redundant */
6099 nommu_addchr(&ctx.as_string, ch);
6102 o_addqchr(&dest, ch);
6107 is_in_dquote ^= 1; /* invert */
6108 if (dest.o_assignment == NOT_ASSIGNMENT)
6111 #if ENABLE_HUSH_TICK
6116 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6117 o_addchr(&dest, '`');
6121 add_till_backquote(&dest, input);
6123 o_addstr(&ctx.as_string, dest.data + pos);
6124 o_addchr(&ctx.as_string, '`');
6126 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6127 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6132 #if ENABLE_HUSH_CASE
6135 if (done_word(&dest, &ctx)) {
6138 done_pipe(&ctx, PIPE_SEQ);
6139 #if ENABLE_HUSH_CASE
6140 /* Eat multiple semicolons, detect
6141 * whether it means something special */
6146 ch = i_getch(input);
6147 nommu_addchr(&ctx.as_string, ch);
6148 if (ctx.ctx_res_w == RES_CASE_BODY) {
6149 ctx.ctx_dsemicolon = 1;
6150 ctx.ctx_res_w = RES_MATCH;
6156 /* We just finished a cmd. New one may start
6157 * with an assignment */
6158 dest.o_assignment = MAYBE_ASSIGNMENT;
6161 if (done_word(&dest, &ctx)) {
6165 ch = i_getch(input);
6166 nommu_addchr(&ctx.as_string, ch);
6167 done_pipe(&ctx, PIPE_AND);
6169 done_pipe(&ctx, PIPE_BG);
6173 if (done_word(&dest, &ctx)) {
6176 #if ENABLE_HUSH_CASE
6177 if (ctx.ctx_res_w == RES_MATCH)
6178 break; /* we are in case's "word | word)" */
6180 if (next == '|') { /* || */
6181 ch = i_getch(input);
6182 nommu_addchr(&ctx.as_string, ch);
6183 done_pipe(&ctx, PIPE_OR);
6185 /* we could pick up a file descriptor choice here
6186 * with redirect_opt_num(), but bash doesn't do it.
6187 * "echo foo 2| cat" yields "foo 2". */
6192 #if ENABLE_HUSH_CASE
6193 /* "case... in [(]word)..." - skip '(' */
6194 if (ctx.ctx_res_w == RES_MATCH
6195 && ctx.command->argv == NULL /* not (word|(... */
6196 && dest.length == 0 /* not word(... */
6197 && dest.o_quoted == 0 /* not ""(... */
6203 if (parse_group(&dest, &ctx, input, ch) != 0) {
6208 #if ENABLE_HUSH_CASE
6209 if (ctx.ctx_res_w == RES_MATCH)
6213 /* proper use of this character is caught by end_trigger:
6214 * if we see {, we call parse_group(..., end_trigger='}')
6215 * and it will match } earlier (not here). */
6216 syntax_error_unexpected_ch(ch);
6220 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6226 struct parse_context *pctx;
6227 IF_HAS_KEYWORDS(struct parse_context *p2;)
6229 /* Clean up allocated tree.
6230 * Sample for finding leaks on syntax error recovery path.
6231 * Run it from interactive shell, watch pmap `pidof hush`.
6232 * while if false; then false; fi; do break; fi
6233 * Samples to catch leaks at execution:
6234 * while if (true | {true;}); then echo ok; fi; do break; done
6235 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6239 /* Update pipe/command counts,
6240 * otherwise freeing may miss some */
6241 done_pipe(pctx, PIPE_SEQ);
6242 debug_printf_clean("freeing list %p from ctx %p\n",
6243 pctx->list_head, pctx);
6244 debug_print_tree(pctx->list_head, 0);
6245 free_pipe_list(pctx->list_head);
6246 debug_printf_clean("freed list %p\n", pctx->list_head);
6248 o_free_unsafe(&pctx->as_string);
6250 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6254 IF_HAS_KEYWORDS(pctx = p2;)
6255 } while (HAS_KEYWORDS && pctx);
6256 /* Free text, clear all dest fields */
6258 /* If we are not in top-level parse, we return,
6259 * our caller will propagate error.
6261 if (end_trigger != ';') {
6269 /* Discard cached input, force prompt */
6271 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6276 /* Executing from string: eval, sh -c '...'
6277 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6278 * end_trigger controls how often we stop parsing
6279 * NUL: parse all, execute, return
6280 * ';': parse till ';' or newline, execute, repeat till EOF
6282 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6285 struct pipe *pipe_list;
6287 pipe_list = parse_stream(NULL, inp, end_trigger);
6288 if (!pipe_list) /* EOF */
6290 debug_print_tree(pipe_list, 0);
6291 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6292 run_and_free_list(pipe_list);
6296 static void parse_and_run_string(const char *s)
6298 struct in_str input;
6299 setup_string_in_str(&input, s);
6300 parse_and_run_stream(&input, '\0');
6303 static void parse_and_run_file(FILE *f)
6305 struct in_str input;
6306 setup_file_in_str(&input, f);
6307 parse_and_run_stream(&input, ';');
6310 /* Called a few times only (or even once if "sh -c") */
6311 static void block_signals(int second_time)
6316 mask = (1 << SIGQUIT);
6317 if (G_interactive_fd) {
6318 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6319 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6320 mask |= SPECIAL_JOB_SIGS;
6322 G.non_DFL_mask = mask;
6325 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6329 sigaddset(&G.blocked_set, sig);
6333 sigdelset(&G.blocked_set, SIGCHLD);
6335 sigprocmask(SIG_SETMASK, &G.blocked_set,
6336 second_time ? NULL : &G.inherited_set);
6337 /* POSIX allows shell to re-enable SIGCHLD
6338 * even if it was SIG_IGN on entry */
6339 #if ENABLE_HUSH_FAST
6340 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6342 signal(SIGCHLD, SIGCHLD_handler);
6345 signal(SIGCHLD, SIG_DFL);
6351 static void maybe_set_to_sigexit(int sig)
6353 void (*handler)(int);
6354 /* non_DFL_mask'ed signals are, well, masked,
6355 * no need to set handler for them.
6357 if (!((G.non_DFL_mask >> sig) & 1)) {
6358 handler = signal(sig, sigexit);
6359 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6360 signal(sig, handler);
6363 /* Set handlers to restore tty pgrp and exit */
6364 static void set_fatal_handlers(void)
6366 /* We _must_ restore tty pgrp on fatal signals */
6368 maybe_set_to_sigexit(SIGILL );
6369 maybe_set_to_sigexit(SIGFPE );
6370 maybe_set_to_sigexit(SIGBUS );
6371 maybe_set_to_sigexit(SIGSEGV);
6372 maybe_set_to_sigexit(SIGTRAP);
6373 } /* else: hush is perfect. what SEGV? */
6374 maybe_set_to_sigexit(SIGABRT);
6375 /* bash 3.2 seems to handle these just like 'fatal' ones */
6376 maybe_set_to_sigexit(SIGPIPE);
6377 maybe_set_to_sigexit(SIGALRM);
6378 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6379 * if we aren't interactive... but in this case
6380 * we never want to restore pgrp on exit, and this fn is not called */
6381 /*maybe_set_to_sigexit(SIGHUP );*/
6382 /*maybe_set_to_sigexit(SIGTERM);*/
6383 /*maybe_set_to_sigexit(SIGINT );*/
6387 static int set_mode(const char cstate, const char mode)
6389 int state = (cstate == '-' ? 1 : 0);
6391 case 'n': G.fake_mode = state; break;
6392 case 'x': /*G.debug_mode = state;*/ break;
6393 default: return EXIT_FAILURE;
6395 return EXIT_SUCCESS;
6398 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6399 int hush_main(int argc, char **argv)
6401 static const struct variable const_shell_ver = {
6403 .varstr = (char*)hush_version_str,
6404 .max_len = 1, /* 0 can provoke free(name) */
6408 int signal_mask_is_inited = 0;
6410 unsigned builtin_argc;
6412 struct variable *cur_var;
6415 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6416 G.last_exitcode = EXIT_SUCCESS;
6418 G.argv0_for_re_execing = argv[0];
6420 /* Deal with HUSH_VERSION */
6421 G.shell_ver = const_shell_ver; /* copying struct here */
6422 G.top_var = &G.shell_ver;
6423 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6424 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6425 /* Initialize our shell local variables with the values
6426 * currently living in the environment */
6427 cur_var = G.top_var;
6430 char *value = strchr(*e, '=');
6431 if (value) { /* paranoia */
6432 cur_var->next = xzalloc(sizeof(*cur_var));
6433 cur_var = cur_var->next;
6434 cur_var->varstr = *e;
6435 cur_var->max_len = strlen(*e);
6436 cur_var->flg_export = 1;
6440 debug_printf_env("putenv '%s'\n", hush_version_str);
6441 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6442 #if ENABLE_FEATURE_EDITING
6443 G.line_input_state = new_line_input_t(FOR_SHELL);
6445 G.global_argc = argc;
6446 G.global_argv = argv;
6447 /* Initialize some more globals to non-zero values */
6448 cmdedit_update_prompt();
6450 if (setjmp(die_jmp)) {
6451 /* xfunc has failed! die die die */
6452 /* no EXIT traps, this is an escape hatch! */
6454 hush_exit(xfunc_error_retval);
6457 /* Shell is non-interactive at first. We need to call
6458 * block_signals(0) if we are going to execute "sh <script>",
6459 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6460 * If we later decide that we are interactive, we run block_signals(0)
6461 * (or re-run block_signals(1) if we ran block_signals(0) before)
6462 * in order to intercept (more) signals.
6466 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6469 opt = getopt(argc, argv, "c:xins"
6472 # if ENABLE_HUSH_FUNCTIONS
6482 * sh ... -c 'script'
6483 * sh ... -c 'script' ARG0 [ARG1...]
6484 * On NOMMU, if builtin_argc != 0,
6485 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6486 * "" needs to be replaced with NULL
6487 * and BARGV vector fed to builtin function.
6488 * Note: this form never happens:
6489 * sh ... -c 'builtin' [BARGV...] ""
6492 G.root_pid = getpid();
6493 G.global_argv = argv + optind;
6494 G.global_argc = argc - optind;
6496 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6497 const struct built_in_command *x;
6499 block_signals(0); /* 0: called 1st time */
6500 x = find_builtin(optarg);
6501 if (x) { /* paranoia */
6502 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6503 G.global_argv += builtin_argc;
6504 G.global_argv[-1] = NULL; /* replace "" */
6505 G.last_exitcode = x->function(argv + optind - 1);
6509 if (!G.global_argv[0]) {
6510 /* -c 'script' (no params): prevent empty $0 */
6511 G.global_argv--; /* points to argv[i] of 'script' */
6512 G.global_argv[0] = argv[0];
6514 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6515 block_signals(0); /* 0: called 1st time */
6516 parse_and_run_string(optarg);
6519 /* Well, we cannot just declare interactiveness,
6520 * we have to have some stuff (ctty, etc) */
6521 /* G_interactive_fd++; */
6524 /* "-s" means "read from stdin", but this is how we always
6525 * operate, so simply do nothing here. */
6528 case '<': /* "big heredoc" support */
6529 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6532 G.root_pid = bb_strtou(optarg, &optarg, 16);
6534 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6536 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6538 builtin_argc = bb_strtou(optarg, &optarg, 16);
6539 # if ENABLE_HUSH_LOOPS
6541 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6546 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6548 # if ENABLE_HUSH_FUNCTIONS
6550 struct function *funcp = new_function(optarg);
6551 /* funcp->name is already set to optarg */
6552 /* funcp->body is set to NULL. It's a special case. */
6553 funcp->body_as_string = argv[optind];
6561 if (!set_mode('-', opt))
6565 fprintf(stderr, "Usage: sh [FILE]...\n"
6566 " or: sh -c command [args]...\n\n");
6572 } /* option parsing loop */
6575 G.root_pid = getpid();
6577 /* If we are login shell... */
6578 if (argv[0] && argv[0][0] == '-') {
6580 debug_printf("sourcing /etc/profile\n");
6581 input = fopen_for_read("/etc/profile");
6582 if (input != NULL) {
6583 close_on_exec_on(fileno(input));
6584 block_signals(0); /* 0: called 1st time */
6585 signal_mask_is_inited = 1;
6586 parse_and_run_file(input);
6589 /* bash: after sourcing /etc/profile,
6590 * tries to source (in the given order):
6591 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6592 * stopping on first found. --noprofile turns this off.
6593 * bash also sources ~/.bash_logout on exit.
6594 * If called as sh, skips .bash_XXX files.
6601 * "bash <script>" (which is never interactive (unless -i?))
6602 * sources $BASH_ENV here (without scanning $PATH).
6603 * If called as sh, does the same but with $ENV.
6605 debug_printf("running script '%s'\n", argv[optind]);
6606 G.global_argv = argv + optind;
6607 G.global_argc = argc - optind;
6608 input = xfopen_for_read(argv[optind]);
6609 close_on_exec_on(fileno(input));
6610 if (!signal_mask_is_inited)
6611 block_signals(0); /* 0: called 1st time */
6612 parse_and_run_file(input);
6613 #if ENABLE_FEATURE_CLEAN_UP
6619 /* Up to here, shell was non-interactive. Now it may become one.
6620 * NB: don't forget to (re)run block_signals(0/1) as needed.
6623 /* A shell is interactive if the '-i' flag was given,
6624 * or if all of the following conditions are met:
6626 * no arguments remaining or the -s flag given
6627 * standard input is a terminal
6628 * standard output is a terminal
6629 * Refer to Posix.2, the description of the 'sh' utility.
6632 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6633 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6634 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6635 if (G_saved_tty_pgrp < 0)
6636 G_saved_tty_pgrp = 0;
6638 /* try to dup stdin to high fd#, >= 255 */
6639 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6640 if (G_interactive_fd < 0) {
6641 /* try to dup to any fd */
6642 G_interactive_fd = dup(STDIN_FILENO);
6643 if (G_interactive_fd < 0) {
6645 G_interactive_fd = 0;
6646 G_saved_tty_pgrp = 0;
6649 // TODO: track & disallow any attempts of user
6650 // to (inadvertently) close/redirect G_interactive_fd
6652 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6653 if (G_interactive_fd) {
6654 close_on_exec_on(G_interactive_fd);
6656 if (G_saved_tty_pgrp) {
6657 /* If we were run as 'hush &', sleep until we are
6658 * in the foreground (tty pgrp == our pgrp).
6659 * If we get started under a job aware app (like bash),
6660 * make sure we are now in charge so we don't fight over
6661 * who gets the foreground */
6663 pid_t shell_pgrp = getpgrp();
6664 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6665 if (G_saved_tty_pgrp == shell_pgrp)
6667 /* send TTIN to ourself (should stop us) */
6668 kill(- shell_pgrp, SIGTTIN);
6672 /* Block some signals */
6673 block_signals(signal_mask_is_inited);
6675 if (G_saved_tty_pgrp) {
6676 /* Set other signals to restore saved_tty_pgrp */
6677 set_fatal_handlers();
6678 /* Put ourselves in our own process group
6679 * (bash, too, does this only if ctty is available) */
6680 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6681 /* Grab control of the terminal */
6682 tcsetpgrp(G_interactive_fd, getpid());
6684 /* -1 is special - makes xfuncs longjmp, not exit
6685 * (we reset die_sleep = 0 whereever we [v]fork) */
6686 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6687 } else if (!signal_mask_is_inited) {
6688 block_signals(0); /* 0: called 1st time */
6689 } /* else: block_signals(0) was done before */
6690 #elif ENABLE_HUSH_INTERACTIVE
6691 /* No job control compiled in, only prompt/line editing */
6692 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6693 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6694 if (G_interactive_fd < 0) {
6695 /* try to dup to any fd */
6696 G_interactive_fd = dup(STDIN_FILENO);
6697 if (G_interactive_fd < 0)
6699 G_interactive_fd = 0;
6702 if (G_interactive_fd) {
6703 close_on_exec_on(G_interactive_fd);
6704 block_signals(signal_mask_is_inited);
6705 } else if (!signal_mask_is_inited) {
6709 /* We have interactiveness code disabled */
6710 if (!signal_mask_is_inited) {
6715 * if interactive but not a login shell, sources ~/.bashrc
6716 * (--norc turns this off, --rcfile <file> overrides)
6719 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6720 printf("\n\n%s hush - the humble shell\n", bb_banner);
6721 if (ENABLE_HUSH_HELP)
6722 puts("Enter 'help' for a list of built-in commands.");
6726 parse_and_run_file(stdin);
6729 #if ENABLE_FEATURE_CLEAN_UP
6730 if (G.cwd != bb_msg_unknown)
6732 cur_var = G.top_var->next;
6734 struct variable *tmp = cur_var;
6735 if (!cur_var->max_len)
6736 free(cur_var->varstr);
6737 cur_var = cur_var->next;
6741 hush_exit(G.last_exitcode);
6746 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6747 int lash_main(int argc, char **argv)
6749 //bb_error_msg("lash is deprecated, please use hush instead");
6750 return hush_main(argc, argv);
6758 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6763 static int FAST_FUNC builtin_test(char **argv)
6770 return test_main(argc, argv - argc);
6773 static int FAST_FUNC builtin_echo(char **argv)
6780 return echo_main(argc, argv - argc);
6783 static int FAST_FUNC builtin_eval(char **argv)
6785 int rcode = EXIT_SUCCESS;
6788 char *str = expand_strvec_to_string(argv);
6790 * eval "echo Hi; done" ("done" is syntax error):
6791 * "echo Hi" will not execute too.
6793 parse_and_run_string(str);
6795 rcode = G.last_exitcode;
6800 static int FAST_FUNC builtin_cd(char **argv)
6802 const char *newdir = argv[1];
6803 if (newdir == NULL) {
6804 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6805 * bash says "bash: cd: HOME not set" and does nothing
6808 newdir = get_local_var_value("HOME") ? : "/";
6810 if (chdir(newdir)) {
6811 /* Mimic bash message exactly */
6812 bb_perror_msg("cd: %s", newdir);
6813 return EXIT_FAILURE;
6816 return EXIT_SUCCESS;
6819 static int FAST_FUNC builtin_exec(char **argv)
6821 if (*++argv == NULL)
6822 return EXIT_SUCCESS; /* bash does this */
6827 /* TODO: if exec fails, bash does NOT exit! We do... */
6828 pseudo_exec_argv(&dummy, argv, 0, NULL);
6833 static int FAST_FUNC builtin_exit(char **argv)
6835 debug_printf_exec("%s()\n", __func__);
6837 /* interactive bash:
6838 * # trap "echo EEE" EXIT
6841 * There are stopped jobs.
6842 * (if there are _stopped_ jobs, running ones don't count)
6845 # EEE (then bash exits)
6847 * we can use G.exiting = -1 as indicator "last cmd was exit"
6850 /* note: EXIT trap is run by hush_exit */
6851 if (*++argv == NULL)
6852 hush_exit(G.last_exitcode);
6853 /* mimic bash: exit 123abc == exit 255 + error msg */
6854 xfunc_error_retval = 255;
6855 /* bash: exit -2 == exit 254, no error msg */
6856 hush_exit(xatoi(*argv) & 0xff);
6859 static void print_escaped(const char *s)
6864 const char *p = strchrnul(s, '\'');
6865 /* print 'xxxx', possibly just '' */
6866 printf("'%.*s'", (int)(p - s), s);
6871 /* s points to '; print "'''...'''" */
6873 do putchar('\''); while (*++s == '\'');
6878 #if !ENABLE_HUSH_LOCAL
6879 #define helper_export_local(argv, exp, lvl) \
6880 helper_export_local(argv, exp)
6882 static void helper_export_local(char **argv, int exp, int lvl)
6887 /* So far we do not check that name is valid (TODO?) */
6889 if (strchr(name, '=') == NULL) {
6890 struct variable *var;
6892 var = get_local_var(name);
6893 if (exp == -1) { /* unexporting? */
6894 /* export -n NAME (without =VALUE) */
6896 var->flg_export = 0;
6897 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6899 } /* else: export -n NOT_EXISTING_VAR: no-op */
6902 if (exp == 1) { /* exporting? */
6903 /* export NAME (without =VALUE) */
6905 var->flg_export = 1;
6906 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6907 putenv(var->varstr);
6911 /* Exporting non-existing variable.
6912 * bash does not put it in environment,
6913 * but remembers that it is exported,
6914 * and does put it in env when it is set later.
6915 * We just set it to "" and export. */
6916 /* Or, it's "local NAME" (without =VALUE).
6917 * bash sets the value to "". */
6918 name = xasprintf("%s=", name);
6920 /* (Un)exporting/making local NAME=VALUE */
6921 name = xstrdup(name);
6923 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6927 static int FAST_FUNC builtin_export(char **argv)
6929 unsigned opt_unexport;
6931 #if ENABLE_HUSH_EXPORT_N
6932 /* "!": do not abort on errors */
6933 opt_unexport = getopt32(argv, "!n");
6934 if (opt_unexport == (uint32_t)-1)
6935 return EXIT_FAILURE;
6942 if (argv[0] == NULL) {
6949 /* ash emits: export VAR='VAL'
6950 * bash: declare -x VAR="VAL"
6951 * we follow ash example */
6952 const char *s = *e++;
6953 const char *p = strchr(s, '=');
6955 if (!p) /* wtf? take next variable */
6958 printf("export %.*s", (int)(p - s) + 1, s);
6959 print_escaped(p + 1);
6963 /*fflush(stdout); - done after each builtin anyway */
6965 return EXIT_SUCCESS;
6968 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
6970 return EXIT_SUCCESS;
6973 #if ENABLE_HUSH_LOCAL
6974 static int FAST_FUNC builtin_local(char **argv)
6976 if (G.func_nest_level == 0) {
6977 bb_error_msg("%s: not in a function", argv[0]);
6978 return EXIT_FAILURE; /* bash compat */
6980 helper_export_local(argv, 0, G.func_nest_level);
6981 return EXIT_SUCCESS;
6985 static int FAST_FUNC builtin_trap(char **argv)
6991 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6996 /* No args: print all trapped */
6997 for (i = 0; i < NSIG; ++i) {
7000 print_escaped(G.traps[i]);
7001 printf(" %s\n", get_signame(i));
7004 /*fflush(stdout); - done after each builtin anyway */
7005 return EXIT_SUCCESS;
7009 /* If first arg is a number: reset all specified signals */
7010 sig = bb_strtou(*argv, NULL, 10);
7016 sig = get_signum(*argv++);
7017 if (sig < 0 || sig >= NSIG) {
7019 /* Mimic bash message exactly */
7020 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7025 G.traps[sig] = xstrdup(new_cmd);
7027 debug_printf("trap: setting SIG%s (%i) to '%s'",
7028 get_signame(sig), sig, G.traps[sig]);
7030 /* There is no signal for 0 (EXIT) */
7035 sigaddset(&G.blocked_set, sig);
7037 /* There was a trap handler, we are removing it
7038 * (if sig has non-DFL handling,
7039 * we don't need to do anything) */
7040 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7042 sigdelset(&G.blocked_set, sig);
7045 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7049 if (!argv[1]) { /* no second arg */
7050 bb_error_msg("trap: invalid arguments");
7051 return EXIT_FAILURE;
7054 /* First arg is "-": reset all specified to default */
7055 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7056 /* Everything else: set arg as signal handler
7057 * (includes "" case, which ignores signal) */
7058 if (argv[0][0] == '-') {
7059 if (argv[0][1] == '\0') { /* "-" */
7060 /* new_cmd remains NULL: "reset these sigs" */
7063 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7066 /* else: "-something", no special meaning */
7071 goto process_sig_list;
7074 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7075 static int FAST_FUNC builtin_type(char **argv)
7077 int ret = EXIT_SUCCESS;
7083 if (0) {} /* make conditional compile easier below */
7084 /*else if (find_alias(*argv))
7085 type = "an alias";*/
7086 #if ENABLE_HUSH_FUNCTIONS
7087 else if (find_function(*argv))
7088 type = "a function";
7090 else if (find_builtin(*argv))
7091 type = "a shell builtin";
7092 else if ((path = find_in_path(*argv)) != NULL)
7095 bb_error_msg("type: %s: not found", *argv);
7100 printf("%s is %s\n", *argv, type);
7108 /* built-in 'fg' and 'bg' handler */
7109 static int FAST_FUNC builtin_fg_bg(char **argv)
7114 if (!G_interactive_fd)
7115 return EXIT_FAILURE;
7117 /* If they gave us no args, assume they want the last backgrounded task */
7119 for (pi = G.job_list; pi; pi = pi->next) {
7120 if (pi->jobid == G.last_jobid) {
7124 bb_error_msg("%s: no current job", argv[0]);
7125 return EXIT_FAILURE;
7127 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7128 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7129 return EXIT_FAILURE;
7131 for (pi = G.job_list; pi; pi = pi->next) {
7132 if (pi->jobid == jobnum) {
7136 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7137 return EXIT_FAILURE;
7139 /* TODO: bash prints a string representation
7140 * of job being foregrounded (like "sleep 1 | cat") */
7141 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7142 /* Put the job into the foreground. */
7143 tcsetpgrp(G_interactive_fd, pi->pgrp);
7146 /* Restart the processes in the job */
7147 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7148 for (i = 0; i < pi->num_cmds; i++) {
7149 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7150 pi->cmds[i].is_stopped = 0;
7152 pi->stopped_cmds = 0;
7154 i = kill(- pi->pgrp, SIGCONT);
7156 if (errno == ESRCH) {
7157 delete_finished_bg_job(pi);
7158 return EXIT_SUCCESS;
7160 bb_perror_msg("kill (SIGCONT)");
7163 if (argv[0][0] == 'f') {
7165 return checkjobs_and_fg_shell(pi);
7167 return EXIT_SUCCESS;
7171 #if ENABLE_HUSH_HELP
7172 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7174 const struct built_in_command *x;
7177 "Built-in commands:\n"
7178 "------------------\n");
7179 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7181 printf("%s\t%s\n", x->cmd, x->descr);
7184 return EXIT_SUCCESS;
7189 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7192 const char *status_string;
7194 for (job = G.job_list; job; job = job->next) {
7195 if (job->alive_cmds == job->stopped_cmds)
7196 status_string = "Stopped";
7198 status_string = "Running";
7200 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7202 return EXIT_SUCCESS;
7207 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7212 /* Crude attempt to find where "free memory" starts,
7213 * sans fragmentation. */
7215 l = (unsigned long)p;
7218 if (l < (unsigned long)p) l = (unsigned long)p;
7221 if (!G.memleak_value)
7222 G.memleak_value = l;
7224 l -= G.memleak_value;
7231 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7236 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7239 return EXIT_SUCCESS;
7242 static int FAST_FUNC builtin_read(char **argv)
7245 const char *name = "REPLY";
7249 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7250 * and _after_ that_ it will complain */
7251 if (!is_well_formed_var_name(name, '\0')) {
7252 /* Mimic bash message */
7253 bb_error_msg("read: '%s': not a valid identifier", name);
7258 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7260 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7261 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7264 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7265 * built-in 'set' handler
7267 * set [-abCefhmnuvx] [-o option] [argument...]
7268 * set [+abCefhmnuvx] [+o option] [argument...]
7269 * set -- [argument...]
7272 * Implementations shall support the options in both their hyphen and
7273 * plus-sign forms. These options can also be specified as options to sh.
7275 * Write out all variables and their values: set
7276 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7277 * Turn on the -x and -v options: set -xv
7278 * Unset all positional parameters: set --
7279 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7280 * Set the positional parameters to the expansion of x, even if x expands
7281 * with a leading '-' or '+': set -- $x
7283 * So far, we only support "set -- [argument...]" and some of the short names.
7285 static int FAST_FUNC builtin_set(char **argv)
7288 char **pp, **g_argv;
7289 char *arg = *++argv;
7293 for (e = G.top_var; e; e = e->next)
7295 return EXIT_SUCCESS;
7299 if (!strcmp(arg, "--")) {
7303 if (arg[0] != '+' && arg[0] != '-')
7305 for (n = 1; arg[n]; ++n)
7306 if (set_mode(arg[0], arg[n]))
7308 } while ((arg = *++argv) != NULL);
7309 /* Now argv[0] is 1st argument */
7312 return EXIT_SUCCESS;
7315 /* NB: G.global_argv[0] ($0) is never freed/changed */
7316 g_argv = G.global_argv;
7317 if (G.global_args_malloced) {
7323 G.global_args_malloced = 1;
7324 pp = xzalloc(sizeof(pp[0]) * 2);
7325 pp[0] = g_argv[0]; /* retain $0 */
7328 /* This realloc's G.global_argv */
7329 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7336 return EXIT_SUCCESS;
7338 /* Nothing known, so abort */
7340 bb_error_msg("set: %s: invalid option", arg);
7341 return EXIT_FAILURE;
7344 static int FAST_FUNC builtin_shift(char **argv)
7350 if (n >= 0 && n < G.global_argc) {
7351 if (G.global_args_malloced) {
7354 free(G.global_argv[m++]);
7357 memmove(&G.global_argv[1], &G.global_argv[n+1],
7358 G.global_argc * sizeof(G.global_argv[0]));
7359 return EXIT_SUCCESS;
7361 return EXIT_FAILURE;
7364 static int FAST_FUNC builtin_source(char **argv)
7369 #if ENABLE_HUSH_FUNCTIONS
7373 if (*++argv == NULL)
7374 return EXIT_FAILURE;
7376 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7377 input = fopen_for_read(arg_path);
7380 input = fopen_or_warn(*argv, "r");
7382 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7383 return EXIT_FAILURE;
7385 close_on_exec_on(fileno(input));
7387 #if ENABLE_HUSH_FUNCTIONS
7388 sv_flg = G.flag_return_in_progress;
7389 /* "we are inside sourced file, ok to use return" */
7390 G.flag_return_in_progress = -1;
7392 save_and_replace_G_args(&sv, argv);
7394 parse_and_run_file(input);
7397 restore_G_args(&sv, argv);
7398 #if ENABLE_HUSH_FUNCTIONS
7399 G.flag_return_in_progress = sv_flg;
7402 return G.last_exitcode;
7405 static int FAST_FUNC builtin_umask(char **argv)
7412 mode_t old_mask = mask;
7415 rc = bb_parse_mode(argv[1], &mask);
7420 * bash: umask: 'q': invalid symbolic mode operator
7421 * bash: umask: 999: octal number out of range
7423 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7428 printf("%04o\n", (unsigned) mask);
7429 /* fall through and restore mask which we set to 0 */
7433 return !rc; /* rc != 0 - success */
7436 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7437 static int FAST_FUNC builtin_unset(char **argv)
7442 /* "!": do not abort on errors */
7443 /* "+": stop at 1st non-option */
7444 opts = getopt32(argv, "!+vf");
7445 if (opts == (unsigned)-1)
7446 return EXIT_FAILURE;
7448 bb_error_msg("unset: -v and -f are exclusive");
7449 return EXIT_FAILURE;
7455 if (!(opts & 2)) { /* not -f */
7456 if (unset_local_var(*argv)) {
7457 /* unset <nonexistent_var> doesn't fail.
7458 * Error is when one tries to unset RO var.
7459 * Message was printed by unset_local_var. */
7463 #if ENABLE_HUSH_FUNCTIONS
7473 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7474 static int FAST_FUNC builtin_wait(char **argv)
7476 int ret = EXIT_SUCCESS;
7479 if (*++argv == NULL) {
7480 /* Don't care about wait results */
7481 /* Note 1: must wait until there are no more children */
7482 /* Note 2: must be interruptible */
7484 * $ sleep 3 & sleep 6 & wait
7489 * $ sleep 3 & sleep 6 & wait
7493 * ^C <-- after ~4 sec from keyboard
7496 sigaddset(&G.blocked_set, SIGCHLD);
7497 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7500 if (errno == ECHILD)
7502 /* Wait for SIGCHLD or any other signal of interest */
7503 /* sigtimedwait with infinite timeout: */
7504 sig = sigwaitinfo(&G.blocked_set, NULL);
7506 sig = check_and_run_traps(sig);
7507 if (sig && sig != SIGCHLD) { /* see note 2 */
7513 sigdelset(&G.blocked_set, SIGCHLD);
7514 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7518 /* This is probably buggy wrt interruptible-ness */
7520 pid_t pid = bb_strtou(*argv, NULL, 10);
7522 /* mimic bash message */
7523 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7524 return EXIT_FAILURE;
7526 if (waitpid(pid, &status, 0) == pid) {
7527 if (WIFSIGNALED(status))
7528 ret = 128 + WTERMSIG(status);
7529 else if (WIFEXITED(status))
7530 ret = WEXITSTATUS(status);
7534 bb_perror_msg("wait %s", *argv);
7543 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7544 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7547 def = bb_strtou(argv[1], NULL, 10);
7548 if (errno || def < def_min || argv[2]) {
7549 bb_error_msg("%s: bad arguments", argv[0]);
7557 #if ENABLE_HUSH_LOOPS
7558 static int FAST_FUNC builtin_break(char **argv)
7561 if (G.depth_of_loop == 0) {
7562 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7563 return EXIT_SUCCESS; /* bash compat */
7565 G.flag_break_continue++; /* BC_BREAK = 1 */
7567 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7568 if (depth == UINT_MAX)
7569 G.flag_break_continue = BC_BREAK;
7570 if (G.depth_of_loop < depth)
7571 G.depth_break_continue = G.depth_of_loop;
7573 return EXIT_SUCCESS;
7576 static int FAST_FUNC builtin_continue(char **argv)
7578 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7579 return builtin_break(argv);
7583 #if ENABLE_HUSH_FUNCTIONS
7584 static int FAST_FUNC builtin_return(char **argv)
7588 if (G.flag_return_in_progress != -1) {
7589 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7590 return EXIT_FAILURE; /* bash compat */
7593 G.flag_return_in_progress = 1;
7596 * out of range: wraps around at 256, does not error out
7597 * non-numeric param:
7598 * f() { false; return qwe; }; f; echo $?
7599 * bash: return: qwe: numeric argument required <== we do this
7600 * 255 <== we also do this
7602 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);