1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
45 * Bash stuff (maybe optionally enable?):
46 * &> and >& redirection of stdout+stderr
48 * reserved words: [[ ]] function select
49 * substrings ${var:1:5}
52 * grep for "TODO" and fix (some of them are easy)
54 * follow IFS rules more precisely, including update semantics
55 * export builtin should be special, its arguments are assignments
56 * and therefore expansion of them should be "one-word" expansion:
57 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
59 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
60 * ls: cannot access i=a: No such file or directory
61 * ls: cannot access b: No such file or directory
62 * Note1: same applies to local builtin when we'll have it.
63 * Note2: bash 3.2.33(1) does this only if export word itself
65 * $ export i=`echo 'aaa bbb'`; echo "$i"
67 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
70 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
72 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
74 /* #include <dmalloc.h> */
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
86 #define LEAK_HUNTING 0
87 #define BUILD_AS_NOMMU 0
88 /* Enable/disable sanity checks. Ok to enable in production,
89 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
90 * Keeping 1 for now even in released versions.
93 /* Slightly bigger (+200 bytes), but faster hush.
94 * So far it only enables a trick with counting SIGCHLDs and forks,
95 * which allows us to do fewer waitpid's.
96 * (we can detect a case where neither forks were done nor SIGCHLDs happened
97 * and therefore waitpid will return the same result as last time)
99 #define ENABLE_HUSH_FAST 0
104 # undef USE_FOR_NOMMU
107 # define USE_FOR_NOMMU(...) __VA_ARGS__
108 # define USE_FOR_MMU(...)
111 #if defined SINGLE_APPLET_MAIN
112 /* STANDALONE does not make sense, and won't compile */
113 # undef CONFIG_FEATURE_SH_STANDALONE
114 # undef ENABLE_FEATURE_SH_STANDALONE
115 # undef IF_FEATURE_SH_STANDALONE
116 # define IF_FEATURE_SH_STANDALONE(...)
117 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
118 # define ENABLE_FEATURE_SH_STANDALONE 0
121 #if !ENABLE_HUSH_INTERACTIVE
122 # undef ENABLE_FEATURE_EDITING
123 # define ENABLE_FEATURE_EDITING 0
124 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
125 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
128 /* Do we support ANY keywords? */
129 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
130 # define HAS_KEYWORDS 1
131 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
132 # define IF_HAS_NO_KEYWORDS(...)
134 # define HAS_KEYWORDS 0
135 # define IF_HAS_KEYWORDS(...)
136 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
139 /* If you comment out one of these below, it will be #defined later
140 * to perform debug printfs to stderr: */
141 #define debug_printf(...) do {} while (0)
142 /* Finer-grained debug switches */
143 #define debug_printf_parse(...) do {} while (0)
144 #define debug_print_tree(a, b) do {} while (0)
145 #define debug_printf_exec(...) do {} while (0)
146 #define debug_printf_env(...) do {} while (0)
147 #define debug_printf_jobs(...) do {} while (0)
148 #define debug_printf_expand(...) do {} while (0)
149 #define debug_printf_glob(...) do {} while (0)
150 #define debug_printf_list(...) do {} while (0)
151 #define debug_printf_subst(...) do {} while (0)
152 #define debug_printf_clean(...) do {} while (0)
154 #define ERR_PTR ((void*)(long)1)
156 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
158 #define SPECIAL_VAR_SYMBOL 3
162 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
164 /* This supports saving pointers malloced in vfork child,
165 * to be freed in the parent.
168 typedef struct nommu_save_t {
170 struct variable *old_vars;
172 char **argv_from_re_execing;
176 typedef enum reserved_style {
185 #if ENABLE_HUSH_LOOPS
192 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
197 /* three pseudo-keywords support contrived "case" syntax: */
198 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
199 RES_MATCH , /* "word)" */
200 RES_CASE_BODY, /* "this command is inside CASE" */
207 typedef struct o_string {
209 int length; /* position where data is appended */
211 /* Protect newly added chars against globbing
212 * (by prepending \ to *, ?, [, \) */
215 /* At least some part of the string was inside '' or "",
216 * possibly empty one: word"", wo''rd etc. */
218 smallint has_empty_slot;
219 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
222 MAYBE_ASSIGNMENT = 0,
223 DEFINITELY_ASSIGNMENT = 1,
225 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
227 /* Used for initialization: o_string foo = NULL_O_STRING; */
228 #define NULL_O_STRING { NULL }
230 /* I can almost use ordinary FILE*. Is open_memstream() universally
231 * available? Where is it documented? */
232 typedef struct in_str {
234 /* eof_flag=1: last char in ->p is really an EOF */
235 char eof_flag; /* meaningless if ->p == NULL */
237 #if ENABLE_HUSH_INTERACTIVE
239 smallint promptmode; /* 0: PS1, 1: PS2 */
242 int (*get) (struct in_str *) FAST_FUNC;
243 int (*peek) (struct in_str *) FAST_FUNC;
245 #define i_getch(input) ((input)->get(input))
246 #define i_peek(input) ((input)->peek(input))
248 /* The descrip member of this structure is only used to make
249 * debugging output pretty */
250 static const struct {
252 signed char default_fd;
255 { O_RDONLY, 0, "<" },
256 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
257 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
258 { O_CREAT|O_RDWR, 1, "<>" },
259 { O_RDONLY, 0, "<<" },
260 /* Should not be needed. Bogus default_fd helps in debugging */
261 /* { O_RDONLY, 77, "<<" }, */
264 struct redir_struct {
265 struct redir_struct *next;
266 char *rd_filename; /* filename */
267 int rd_fd; /* fd to redirect */
268 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
270 smallint rd_type; /* (enum redir_type) */
271 /* note: for heredocs, rd_filename contains heredoc delimiter,
272 * and subsequently heredoc itself; and rd_dup is a bitmask:
273 * bit 0: do we need to trim leading tabs?
274 * bit 1: is heredoc quoted (<<'delim' syntax) ?
277 typedef enum redir_type {
279 REDIRECT_OVERWRITE = 1,
282 REDIRECT_HEREDOC = 4,
283 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
286 REDIRFD_SYNTAX_ERR = -2,
287 REDIRFD_TO_FILE = -1,
288 /* otherwise, rd_fd is redirected to rd_dup */
290 HEREDOC_SKIPTABS = 1,
296 pid_t pid; /* 0 if exited */
297 int assignment_cnt; /* how many argv[i] are assignments? */
298 smallint is_stopped; /* is the command currently running? */
299 smallint cmd_type; /* CMD_xxx */
301 #define CMD_SUBSHELL 1
302 /* used for "[[ EXPR ]]" */
303 #define CMD_SINGLEWORD_NOGLOB 2
304 /* used for "export noglob=* glob* a=`echo a b`" */
305 /* #define CMD_SINGLEWORD_NOGLOB_COND 3 */
306 // It is hard to implement correctly, adds significant amounts of tricky code,
307 // and all this only useful for really obscure export statements
308 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
309 // guard the code which implement it, but I have doubts it works
310 // in all cases (especially with mixed globbed/non-globbed arguments)
311 #if ENABLE_HUSH_FUNCTIONS
312 # define CMD_FUNCDEF 4
315 //#define CMD_ARITH - let EXPR, ((EXPR))
317 // Each EXPR is an arithmetic expression to be evaluated (ARITHMETIC EVALUATION)
318 // If the last arg evaluates to 0, let returns 1; 0 is returned otherwise.
319 // NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
321 // The EXPR is evaluated according to ARITHMETIC EVALUATION.
322 // This is exactly equivalent to let "expression".
324 // Basically, word splitting and pathname expansion should NOT be performed
326 // no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
327 // no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
328 // Additional operators:
329 // || and && should work as -o and -a
331 // Apart from the above, [[ expr ]] should work as [ expr ]
333 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
336 char *group_as_string;
338 #if ENABLE_HUSH_FUNCTIONS
339 struct function *child_func;
340 /* This field is used to prevent a bug here:
341 * while...do f1() {a;}; f1; f1() {b;}; f1; done
342 * When we execute "f1() {a;}" cmd, we create new function and clear
343 * cmd->group, cmd->group_as_string, cmd->argv[0].
344 * When we execute "f1() {b;}", we notice that f1 exists,
345 * and that its "parent cmd" struct is still "alive",
346 * we put those fields back into cmd->xxx
347 * (struct function has ->parent_cmd ptr to facilitate that).
348 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
349 * Without this trick, loop would execute a;b;b;b;...
350 * instead of correct sequence a;b;a;b;...
351 * When command is freed, it severs the link
352 * (sets ->child_func->parent_cmd to NULL).
355 char **argv; /* command name and arguments */
356 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
357 * and on execution these are substituted with their values.
358 * Substitution can make _several_ words out of one argv[n]!
359 * Example: argv[0]=='.^C*^C.' here: echo .$*.
360 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
362 struct redir_struct *redirects; /* I/O redirections */
364 /* Is there anything in this command at all? */
365 #define IS_NULL_CMD(cmd) \
366 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
371 int num_cmds; /* total number of commands in pipe */
372 int alive_cmds; /* number of commands running (not exited) */
373 int stopped_cmds; /* number of commands alive, but stopped */
375 int jobid; /* job number */
376 pid_t pgrp; /* process group ID for the job */
377 char *cmdtext; /* name of job */
379 struct command *cmds; /* array of commands in pipe */
380 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
381 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
382 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
384 typedef enum pipe_style {
390 /* Is there anything in this pipe at all? */
391 #define IS_NULL_PIPE(pi) \
392 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
394 /* This holds pointers to the various results of parsing */
395 struct parse_context {
396 /* linked list of pipes */
397 struct pipe *list_head;
398 /* last pipe (being constructed right now) */
400 /* last command in pipe (being constructed right now) */
401 struct command *command;
402 /* last redirect in command->redirects list */
403 struct redir_struct *pending_redirect;
409 smallint ctx_inverted; /* "! cmd | cmd" */
411 smallint ctx_dsemicolon; /* ";;" seen */
413 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
415 /* group we are enclosed in:
416 * example: "if pipe1; pipe2; then pipe3; fi"
417 * when we see "if" or "then", we malloc and copy current context,
418 * and make ->stack point to it. then we parse pipeN.
419 * when closing "then" / fi" / whatever is found,
420 * we move list_head into ->stack->command->group,
421 * copy ->stack into current context, and delete ->stack.
422 * (parsing of { list } and ( list ) doesn't use this method)
424 struct parse_context *stack;
428 /* On program start, environ points to initial environment.
429 * putenv adds new pointers into it, unsetenv removes them.
430 * Neither of these (de)allocates the strings.
431 * setenv allocates new strings in malloc space and does putenv,
432 * and thus setenv is unusable (leaky) for shell's purposes */
433 #define setenv(...) setenv_is_leaky_dont_use()
435 struct variable *next;
436 char *varstr; /* points to "name=" portion */
437 #if ENABLE_HUSH_LOCAL
438 unsigned func_nest_level;
440 int max_len; /* if > 0, name is part of initial env; else name is malloced */
441 smallint flg_export; /* putenv should be done on this var */
442 smallint flg_read_only;
450 #if ENABLE_HUSH_FUNCTIONS
452 struct function *next;
454 struct command *parent_cmd;
457 char *body_as_string;
463 /* "Globals" within this file */
464 /* Sorted roughly by size (smaller offsets == smaller code) */
466 /* interactive_fd != 0 means we are an interactive shell.
467 * If we are, then saved_tty_pgrp can also be != 0, meaning
468 * that controlling tty is available. With saved_tty_pgrp == 0,
469 * job control still works, but terminal signals
470 * (^C, ^Z, ^Y, ^\) won't work at all, and background
471 * process groups can only be created with "cmd &".
472 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
473 * to give tty to the foreground process group,
474 * and will take it back when the group is stopped (^Z)
477 #if ENABLE_HUSH_INTERACTIVE
478 /* 'interactive_fd' is a fd# open to ctty, if we have one
479 * _AND_ if we decided to act interactively */
483 # define G_interactive_fd (G.interactive_fd)
485 # define G_interactive_fd 0
487 #if ENABLE_FEATURE_EDITING
488 line_input_t *line_input_state;
495 pid_t saved_tty_pgrp;
496 struct pipe *job_list;
497 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
499 # define G_saved_tty_pgrp 0
501 smallint flag_SIGINT;
502 #if ENABLE_HUSH_LOOPS
503 smallint flag_break_continue;
505 #if ENABLE_HUSH_FUNCTIONS
506 /* 0: outside of a function (or sourced file)
507 * -1: inside of a function, ok to use return builtin
508 * 1: return is invoked, skip all till end of func
510 smallint flag_return_in_progress;
513 smallint exiting; /* used to prevent EXIT trap recursion */
514 /* These four support $?, $#, and $1 */
515 smalluint last_exitcode;
516 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
517 smalluint global_args_malloced;
518 /* how many non-NULL argv's we have. NB: $# + 1 */
522 char *argv0_for_re_execing;
524 #if ENABLE_HUSH_LOOPS
525 unsigned depth_break_continue;
526 unsigned depth_of_loop;
530 struct variable *top_var; /* = &G.shell_ver (set in main()) */
531 struct variable shell_ver;
532 #if ENABLE_HUSH_FUNCTIONS
533 struct function *top_func;
534 # if ENABLE_HUSH_LOCAL
535 struct variable **shadowed_vars_pp;
536 unsigned func_nest_level;
539 /* Signal and trap handling */
541 unsigned count_SIGCHLD;
542 unsigned handled_SIGCHLD;
543 smallint we_have_children;
545 /* which signals have non-DFL handler (even with no traps set)? */
546 unsigned non_DFL_mask;
547 char **traps; /* char *traps[NSIG] */
548 sigset_t blocked_set;
549 sigset_t inherited_set;
551 unsigned long memleak_value;
554 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
556 #define G (*ptr_to_globals)
557 /* Not #defining name to G.name - this quickly gets unwieldy
558 * (too many defines). Also, I actually prefer to see when a variable
559 * is global, thus "G." prefix is a useful hint */
560 #define INIT_G() do { \
561 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
565 /* Function prototypes for builtins */
566 static int builtin_cd(char **argv) FAST_FUNC;
567 static int builtin_echo(char **argv) FAST_FUNC;
568 static int builtin_eval(char **argv) FAST_FUNC;
569 static int builtin_exec(char **argv) FAST_FUNC;
570 static int builtin_exit(char **argv) FAST_FUNC;
571 static int builtin_export(char **argv) FAST_FUNC;
573 static int builtin_fg_bg(char **argv) FAST_FUNC;
574 static int builtin_jobs(char **argv) FAST_FUNC;
577 static int builtin_help(char **argv) FAST_FUNC;
579 #if ENABLE_HUSH_LOCAL
580 static int builtin_local(char **argv) FAST_FUNC;
583 static int builtin_memleak(char **argv) FAST_FUNC;
585 static int builtin_pwd(char **argv) FAST_FUNC;
586 static int builtin_read(char **argv) FAST_FUNC;
587 static int builtin_set(char **argv) FAST_FUNC;
588 static int builtin_shift(char **argv) FAST_FUNC;
589 static int builtin_source(char **argv) FAST_FUNC;
590 static int builtin_test(char **argv) FAST_FUNC;
591 static int builtin_trap(char **argv) FAST_FUNC;
592 static int builtin_type(char **argv) FAST_FUNC;
593 static int builtin_true(char **argv) FAST_FUNC;
594 static int builtin_umask(char **argv) FAST_FUNC;
595 static int builtin_unset(char **argv) FAST_FUNC;
596 static int builtin_wait(char **argv) FAST_FUNC;
597 #if ENABLE_HUSH_LOOPS
598 static int builtin_break(char **argv) FAST_FUNC;
599 static int builtin_continue(char **argv) FAST_FUNC;
601 #if ENABLE_HUSH_FUNCTIONS
602 static int builtin_return(char **argv) FAST_FUNC;
605 /* Table of built-in functions. They can be forked or not, depending on
606 * context: within pipes, they fork. As simple commands, they do not.
607 * When used in non-forking context, they can change global variables
608 * in the parent shell process. If forked, of course they cannot.
609 * For example, 'unset foo | whatever' will parse and run, but foo will
610 * still be set at the end. */
611 struct built_in_command {
613 int (*function)(char **argv) FAST_FUNC;
616 # define BLTIN(cmd, func, help) { cmd, func, help }
618 # define BLTIN(cmd, func, help) { cmd, func }
622 static const struct built_in_command bltins1[] = {
623 BLTIN("." , builtin_source , "Run commands in a file"),
624 BLTIN(":" , builtin_true , NULL),
626 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
628 #if ENABLE_HUSH_LOOPS
629 BLTIN("break" , builtin_break , "Exit from a loop"),
631 BLTIN("cd" , builtin_cd , "Change directory"),
632 #if ENABLE_HUSH_LOOPS
633 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
635 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
636 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
637 BLTIN("exit" , builtin_exit , "Exit"),
638 BLTIN("export" , builtin_export , "Set environment variables"),
640 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
643 BLTIN("help" , builtin_help , NULL),
646 BLTIN("jobs" , builtin_jobs , "List jobs"),
648 #if ENABLE_HUSH_LOCAL
649 BLTIN("local" , builtin_local , "Set local variables"),
652 BLTIN("memleak" , builtin_memleak , NULL),
654 BLTIN("read" , builtin_read , "Input into variable"),
655 #if ENABLE_HUSH_FUNCTIONS
656 BLTIN("return" , builtin_return , "Return from a function"),
658 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
659 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
660 BLTIN("trap" , builtin_trap , "Trap signals"),
661 BLTIN("type" , builtin_type , "Write a description of command type"),
662 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
663 BLTIN("umask" , builtin_umask , "Set file creation mask"),
664 BLTIN("unset" , builtin_unset , "Unset variables"),
665 BLTIN("wait" , builtin_wait , "Wait for process"),
667 /* For now, echo and test are unconditionally enabled.
668 * Maybe make it configurable? */
669 static const struct built_in_command bltins2[] = {
670 BLTIN("[" , builtin_test , NULL),
671 BLTIN("echo" , builtin_echo , NULL),
672 BLTIN("pwd" , builtin_pwd , NULL),
673 BLTIN("test" , builtin_test , NULL),
680 /* prevent disasters with G.debug_indent < 0 */
681 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
682 # define debug_enter() (G.debug_indent++)
683 # define debug_leave() (G.debug_indent--)
685 # define indent() ((void)0)
686 # define debug_enter() ((void)0)
687 # define debug_leave() ((void)0)
691 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
694 #ifndef debug_printf_parse
695 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
698 #ifndef debug_printf_exec
699 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
702 #ifndef debug_printf_env
703 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
706 #ifndef debug_printf_jobs
707 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
708 # define DEBUG_JOBS 1
710 # define DEBUG_JOBS 0
713 #ifndef debug_printf_expand
714 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
715 # define DEBUG_EXPAND 1
717 # define DEBUG_EXPAND 0
720 #ifndef debug_printf_glob
721 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
722 # define DEBUG_GLOB 1
724 # define DEBUG_GLOB 0
727 #ifndef debug_printf_list
728 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
731 #ifndef debug_printf_subst
732 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
735 #ifndef debug_printf_clean
736 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
737 # define DEBUG_CLEAN 1
739 # define DEBUG_CLEAN 0
743 static void debug_print_strings(const char *prefix, char **vv)
746 fprintf(stderr, "%s:\n", prefix);
748 fprintf(stderr, " '%s'\n", *vv++);
751 # define debug_print_strings(prefix, vv) ((void)0)
755 /* Leak hunting. Use hush_leaktool.sh for post-processing.
758 static void *xxmalloc(int lineno, size_t size)
760 void *ptr = xmalloc((size + 0xff) & ~0xff);
761 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
764 static void *xxrealloc(int lineno, void *ptr, size_t size)
766 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
767 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
770 static char *xxstrdup(int lineno, const char *str)
772 char *ptr = xstrdup(str);
773 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
776 static void xxfree(void *ptr)
778 fdprintf(2, "free %p\n", ptr);
781 #define xmalloc(s) xxmalloc(__LINE__, s)
782 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
783 #define xstrdup(s) xxstrdup(__LINE__, s)
784 #define free(p) xxfree(p)
788 /* Syntax and runtime errors. They always abort scripts.
789 * In interactive use they usually discard unparsed and/or unexecuted commands
790 * and return to the prompt.
791 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
794 # define die_if_script(lineno, fmt...) die_if_script(fmt)
795 # define syntax_error(lineno, msg) syntax_error(msg)
796 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
797 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
798 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
799 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
802 static void die_if_script(unsigned lineno, const char *fmt, ...)
807 bb_error_msg("hush.c:%u", lineno);
810 bb_verror_msg(fmt, p, NULL);
812 if (!G_interactive_fd)
816 static void syntax_error(unsigned lineno, const char *msg)
819 die_if_script(lineno, "syntax error: %s", msg);
821 die_if_script(lineno, "syntax error", NULL);
824 static void syntax_error_at(unsigned lineno, const char *msg)
826 die_if_script(lineno, "syntax error at '%s'", msg);
829 static void syntax_error_unterm_str(unsigned lineno, const char *s)
831 die_if_script(lineno, "syntax error: unterminated %s", s);
834 /* It so happens that all such cases are totally fatal
835 * even if shell is interactive: EOF while looking for closing
836 * delimiter. There is nowhere to read stuff from after that,
837 * it's EOF! The only choice is to terminate.
839 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
840 static void syntax_error_unterm_ch(unsigned lineno, char ch)
842 char msg[2] = { ch, '\0' };
843 syntax_error_unterm_str(lineno, msg);
847 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
852 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
856 # undef die_if_script
858 # undef syntax_error_at
859 # undef syntax_error_unterm_ch
860 # undef syntax_error_unterm_str
861 # undef syntax_error_unexpected_ch
863 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
864 # define syntax_error(msg) syntax_error(__LINE__, msg)
865 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
866 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
867 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
868 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
872 #if ENABLE_HUSH_INTERACTIVE
873 static void cmdedit_update_prompt(void);
875 # define cmdedit_update_prompt() ((void)0)
881 static int glob_needed(const char *s)
886 if (*s == '*' || *s == '[' || *s == '?')
893 static int is_well_formed_var_name(const char *s, char terminator)
895 if (!s || !(isalpha(*s) || *s == '_'))
898 while (isalnum(*s) || *s == '_')
900 return *s == terminator;
903 /* Replace each \x with x in place, return ptr past NUL. */
904 static char *unbackslash(char *src)
910 if ((*dst++ = *src++) == '\0')
916 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
937 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
938 v[count1 + count2] = NULL;
941 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
945 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
947 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
948 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
951 #define add_strings_to_strings(strings, add, need_to_dup) \
952 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
955 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
956 static char **add_string_to_strings(char **strings, char *add)
961 return add_strings_to_strings(strings, v, /*dup:*/ 0);
964 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
966 char **ptr = add_string_to_strings(strings, add);
967 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
970 #define add_string_to_strings(strings, add) \
971 xx_add_string_to_strings(__LINE__, strings, add)
974 static void free_strings(char **strings)
989 /* Helpers for setting new $n and restoring them back
991 typedef struct save_arg_t {
995 smallint sv_g_malloced;
998 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1002 sv->sv_argv0 = argv[0];
1003 sv->sv_g_argv = G.global_argv;
1004 sv->sv_g_argc = G.global_argc;
1005 sv->sv_g_malloced = G.global_args_malloced;
1007 argv[0] = G.global_argv[0]; /* retain $0 */
1008 G.global_argv = argv;
1009 G.global_args_malloced = 0;
1017 static void restore_G_args(save_arg_t *sv, char **argv)
1021 if (G.global_args_malloced) {
1022 /* someone ran "set -- arg1 arg2 ...", undo */
1024 while (*++pp) /* note: does not free $0 */
1026 free(G.global_argv);
1028 argv[0] = sv->sv_argv0;
1029 G.global_argv = sv->sv_g_argv;
1030 G.global_argc = sv->sv_g_argc;
1031 G.global_args_malloced = sv->sv_g_malloced;
1035 /* Basic theory of signal handling in shell
1036 * ========================================
1037 * This does not describe what hush does, rather, it is current understanding
1038 * what it _should_ do. If it doesn't, it's a bug.
1039 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1041 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1042 * is finished or backgrounded. It is the same in interactive and
1043 * non-interactive shells, and is the same regardless of whether
1044 * a user trap handler is installed or a shell special one is in effect.
1045 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1046 * backgrounds (i.e. stops) or kills all members of currently running
1049 * Wait builtin in interruptible by signals for which user trap is set
1050 * or by SIGINT in interactive shell.
1052 * Trap handlers will execute even within trap handlers. (right?)
1054 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1056 * If job control is off, backgrounded commands ("cmd &")
1057 * have SIGINT, SIGQUIT set to SIG_IGN.
1059 * Commands which are run in command substitution ("`cmd`")
1060 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1062 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1063 * by the shell from its parent.
1065 * Signals which differ from SIG_DFL action
1066 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1069 * SIGTERM (interactive): ignore
1070 * SIGHUP (interactive):
1071 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1072 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1073 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1074 * that all pipe members are stopped. Try this in bash:
1075 * while :; do :; done - ^Z does not background it
1076 * (while :; do :; done) - ^Z backgrounds it
1077 * SIGINT (interactive): wait for last pipe, ignore the rest
1078 * of the command line, show prompt. NB: ^C does not send SIGINT
1079 * to interactive shell while shell is waiting for a pipe,
1080 * since shell is bg'ed (is not in foreground process group).
1081 * Example 1: this waits 5 sec, but does not execute ls:
1082 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1083 * Example 2: this does not wait and does not execute ls:
1084 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1085 * Example 3: this does not wait 5 sec, but executes ls:
1086 * "sleep 5; ls -l" + press ^C
1088 * (What happens to signals which are IGN on shell start?)
1089 * (What happens with signal mask on shell start?)
1091 * Implementation in hush
1092 * ======================
1093 * We use in-kernel pending signal mask to determine which signals were sent.
1094 * We block all signals which we don't want to take action immediately,
1095 * i.e. we block all signals which need to have special handling as described
1096 * above, and all signals which have traps set.
1097 * After each pipe execution, we extract any pending signals via sigtimedwait()
1100 * unsigned non_DFL_mask: a mask of such "special" signals
1101 * sigset_t blocked_set: current blocked signal set
1104 * clear bit in blocked_set unless it is also in non_DFL_mask
1105 * "trap 'cmd' SIGxxx":
1106 * set bit in blocked_set (even if 'cmd' is '')
1107 * after [v]fork, if we plan to be a shell:
1108 * unblock signals with special interactive handling
1109 * (child shell is not interactive),
1110 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1111 * after [v]fork, if we plan to exec:
1112 * POSIX says pending signal mask is cleared in child - no need to clear it.
1113 * Restore blocked signal set to one inherited by shell just prior to exec.
1115 * Note: as a result, we do not use signal handlers much. The only uses
1116 * are to count SIGCHLDs
1117 * and to restore tty pgrp on signal-induced exit.
1120 SPECIAL_INTERACTIVE_SIGS = 0
1125 SPECIAL_JOB_SIGS = 0
1133 #if ENABLE_HUSH_FAST
1134 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1137 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1143 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1144 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1145 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1146 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1148 /* Restores tty foreground process group, and exits.
1149 * May be called as signal handler for fatal signal
1150 * (will resend signal to itself, producing correct exit state)
1151 * or called directly with -EXITCODE.
1152 * We also call it if xfunc is exiting. */
1153 static void sigexit(int sig) NORETURN;
1154 static void sigexit(int sig)
1156 /* Disable all signals: job control, SIGPIPE, etc. */
1157 sigprocmask_allsigs(SIG_BLOCK);
1159 /* Careful: we can end up here after [v]fork. Do not restore
1160 * tty pgrp then, only top-level shell process does that */
1161 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1162 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1164 /* Not a signal, just exit */
1168 kill_myself_with_sig(sig); /* does not return */
1172 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1173 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1177 /* Restores tty foreground process group, and exits. */
1178 static void hush_exit(int exitcode) NORETURN;
1179 static void hush_exit(int exitcode)
1181 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1182 /* Prevent recursion:
1183 * trap "echo Hi; exit" EXIT; exit
1185 char *argv[] = { NULL, G.traps[0], NULL };
1193 fflush(NULL); /* flush all streams */
1194 sigexit(- (exitcode & 0xff));
1200 static int check_and_run_traps(int sig)
1202 static const struct timespec zero_timespec = { 0, 0 };
1203 smalluint save_rcode;
1209 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1214 if (G.traps && G.traps[sig]) {
1215 if (G.traps[sig][0]) {
1216 /* We have user-defined handler */
1217 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1218 save_rcode = G.last_exitcode;
1221 G.last_exitcode = save_rcode;
1222 } /* else: "" trap, ignoring signal */
1225 /* not a trap: special action */
1227 #if ENABLE_HUSH_FAST
1230 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1234 /* Builtin was ^C'ed, make it look prettier: */
1241 /* bash is observed to signal whole process groups,
1242 * not individual processes */
1243 for (job = G.job_list; job; job = job->next) {
1246 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1247 if (kill(- job->pgrp, SIGHUP) == 0)
1248 kill(- job->pgrp, SIGCONT);
1253 default: /* ignored: */
1254 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1262 static const char *get_cwd(int force)
1264 if (force || G.cwd == NULL) {
1265 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1266 * we must not try to free(bb_msg_unknown) */
1267 if (G.cwd == bb_msg_unknown)
1269 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1271 G.cwd = bb_msg_unknown;
1278 * Shell and environment variable support
1280 static struct variable **get_ptr_to_local_var(const char *name)
1282 struct variable **pp;
1283 struct variable *cur;
1288 while ((cur = *pp) != NULL) {
1289 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1296 static struct variable *get_local_var(const char *name)
1298 struct variable **pp = get_ptr_to_local_var(name);
1304 static const char *get_local_var_value(const char *name)
1306 struct variable **pp = get_ptr_to_local_var(name);
1308 return strchr((*pp)->varstr, '=') + 1;
1312 /* str holds "NAME=VAL" and is expected to be malloced.
1313 * We take ownership of it.
1315 * 0: do not change export flag
1316 * (if creating new variable, flag will be 0)
1317 * 1: set export flag and putenv the variable
1318 * -1: clear export flag and unsetenv the variable
1319 * flg_read_only is set only when we handle -R var=val
1321 #if !BB_MMU && ENABLE_HUSH_LOCAL
1322 /* all params are used */
1323 #elif BB_MMU && ENABLE_HUSH_LOCAL
1324 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1325 set_local_var(str, flg_export, local_lvl)
1326 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1327 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1328 set_local_var(str, flg_export)
1329 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1330 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1331 set_local_var(str, flg_export, flg_read_only)
1333 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1335 struct variable **var_pp;
1336 struct variable *cur;
1340 eq_sign = strchr(str, '=');
1341 if (!eq_sign) { /* not expected to ever happen? */
1346 name_len = eq_sign - str + 1; /* including '=' */
1347 var_pp = &G.top_var;
1348 while ((cur = *var_pp) != NULL) {
1349 if (strncmp(cur->varstr, str, name_len) != 0) {
1350 var_pp = &cur->next;
1353 /* We found an existing var with this name */
1354 if (cur->flg_read_only) {
1358 bb_error_msg("%s: readonly variable", str);
1362 if (flg_export == -1) { // "&& cur->flg_export" ?
1363 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1368 #if ENABLE_HUSH_LOCAL
1369 if (cur->func_nest_level < local_lvl) {
1370 /* New variable is declared as local,
1371 * and existing one is global, or local
1372 * from enclosing function.
1373 * Remove and save old one: */
1374 *var_pp = cur->next;
1375 cur->next = *G.shadowed_vars_pp;
1376 *G.shadowed_vars_pp = cur;
1377 /* bash 3.2.33(1) and exported vars:
1379 * # f() { local z=a; env | grep ^z; }
1385 if (cur->flg_export)
1390 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1395 if (cur->max_len != 0) {
1396 if (cur->max_len >= strlen(str)) {
1397 /* This one is from startup env, reuse space */
1398 strcpy(cur->varstr, str);
1402 /* max_len == 0 signifies "malloced" var, which we can
1403 * (and has to) free */
1407 goto set_str_and_exp;
1410 /* Not found - create new variable struct */
1411 cur = xzalloc(sizeof(*cur));
1412 #if ENABLE_HUSH_LOCAL
1413 cur->func_nest_level = local_lvl;
1415 cur->next = *var_pp;
1421 cur->flg_read_only = flg_read_only;
1424 if (flg_export == 1)
1425 cur->flg_export = 1;
1426 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1427 cmdedit_update_prompt();
1428 if (cur->flg_export) {
1429 if (flg_export == -1) {
1430 cur->flg_export = 0;
1431 /* unsetenv was already done */
1433 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1434 return putenv(cur->varstr);
1440 static int unset_local_var_len(const char *name, int name_len)
1442 struct variable *cur;
1443 struct variable **var_pp;
1446 return EXIT_SUCCESS;
1447 var_pp = &G.top_var;
1448 while ((cur = *var_pp) != NULL) {
1449 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1450 if (cur->flg_read_only) {
1451 bb_error_msg("%s: readonly variable", name);
1452 return EXIT_FAILURE;
1454 *var_pp = cur->next;
1455 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1456 bb_unsetenv(cur->varstr);
1457 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1458 cmdedit_update_prompt();
1462 return EXIT_SUCCESS;
1464 var_pp = &cur->next;
1466 return EXIT_SUCCESS;
1469 static int unset_local_var(const char *name)
1471 return unset_local_var_len(name, strlen(name));
1474 static void unset_vars(char **strings)
1482 const char *eq = strchrnul(*v, '=');
1483 unset_local_var_len(*v, (int)(eq - *v));
1489 #if ENABLE_SH_MATH_SUPPORT
1490 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1491 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1492 static char *endofname(const char *name)
1500 if (!is_in_name(*p))
1506 static void arith_set_local_var(const char *name, const char *val, int flags)
1508 /* arith code doesnt malloc space, so do it for it */
1509 char *var = xasprintf("%s=%s", name, val);
1510 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1516 * Helpers for "var1=val1 var2=val2 cmd" feature
1518 static void add_vars(struct variable *var)
1520 struct variable *next;
1524 var->next = G.top_var;
1526 if (var->flg_export) {
1527 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1528 putenv(var->varstr);
1530 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1536 static struct variable *set_vars_and_save_old(char **strings)
1539 struct variable *old = NULL;
1545 struct variable *var_p;
1546 struct variable **var_pp;
1549 eq = strchr(*s, '=');
1552 var_pp = get_ptr_to_local_var(*s);
1555 /* Remove variable from global linked list */
1557 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1558 *var_pp = var_p->next;
1559 /* Add it to returned list */
1563 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1574 static int FAST_FUNC static_get(struct in_str *i)
1583 static int FAST_FUNC static_peek(struct in_str *i)
1588 #if ENABLE_HUSH_INTERACTIVE
1590 static void cmdedit_update_prompt(void)
1592 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1593 G.PS1 = get_local_var_value("PS1");
1596 G.PS2 = get_local_var_value("PS2");
1604 static const char* setup_prompt_string(int promptmode)
1606 const char *prompt_str;
1607 debug_printf("setup_prompt_string %d ", promptmode);
1608 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1609 /* Set up the prompt */
1610 if (promptmode == 0) { /* PS1 */
1612 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1617 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1618 debug_printf("result '%s'\n", prompt_str);
1622 static void get_user_input(struct in_str *i)
1625 const char *prompt_str;
1627 prompt_str = setup_prompt_string(i->promptmode);
1628 #if ENABLE_FEATURE_EDITING
1629 /* Enable command line editing only while a command line
1630 * is actually being read */
1633 /* buglet: SIGINT will not make new prompt to appear _at once_,
1634 * only after <Enter>. (^C will work) */
1635 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1636 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1637 check_and_run_traps(0);
1638 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1639 i->eof_flag = (r < 0);
1640 if (i->eof_flag) { /* EOF/error detected */
1641 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1642 G.user_input_buf[1] = '\0';
1647 fputs(prompt_str, stdout);
1649 G.user_input_buf[0] = r = fgetc(i->file);
1650 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1651 //do we need check_and_run_traps(0)? (maybe only if stdin)
1652 } while (G.flag_SIGINT);
1653 i->eof_flag = (r == EOF);
1655 i->p = G.user_input_buf;
1658 #endif /* INTERACTIVE */
1660 /* This is the magic location that prints prompts
1661 * and gets data back from the user */
1662 static int FAST_FUNC file_get(struct in_str *i)
1666 /* If there is data waiting, eat it up */
1667 if (i->p && *i->p) {
1668 #if ENABLE_HUSH_INTERACTIVE
1672 if (i->eof_flag && !*i->p)
1674 /* note: ch is never NUL */
1676 /* need to double check i->file because we might be doing something
1677 * more complicated by now, like sourcing or substituting. */
1678 #if ENABLE_HUSH_INTERACTIVE
1679 if (G_interactive_fd && i->promptme && i->file == stdin) {
1682 } while (!*i->p); /* need non-empty line */
1683 i->promptmode = 1; /* PS2 */
1688 do ch = fgetc(i->file); while (ch == '\0');
1690 debug_printf("file_get: got '%c' %d\n", ch, ch);
1691 #if ENABLE_HUSH_INTERACTIVE
1698 /* All callers guarantee this routine will never
1699 * be used right after a newline, so prompting is not needed.
1701 static int FAST_FUNC file_peek(struct in_str *i)
1704 if (i->p && *i->p) {
1705 if (i->eof_flag && !i->p[1])
1708 /* note: ch is never NUL */
1710 do ch = fgetc(i->file); while (ch == '\0');
1711 i->eof_flag = (ch == EOF);
1712 i->peek_buf[0] = ch;
1713 i->peek_buf[1] = '\0';
1715 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1719 static void setup_file_in_str(struct in_str *i, FILE *f)
1721 i->peek = file_peek;
1723 #if ENABLE_HUSH_INTERACTIVE
1725 i->promptmode = 0; /* PS1 */
1731 static void setup_string_in_str(struct in_str *i, const char *s)
1733 i->peek = static_peek;
1734 i->get = static_get;
1735 #if ENABLE_HUSH_INTERACTIVE
1737 i->promptmode = 0; /* PS1 */
1747 #define B_CHUNK (32 * sizeof(char*))
1749 static void o_reset_to_empty_unquoted(o_string *o)
1757 static void o_free(o_string *o)
1760 memset(o, 0, sizeof(*o));
1763 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1768 static void o_grow_by(o_string *o, int len)
1770 if (o->length + len > o->maxlen) {
1771 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1772 o->data = xrealloc(o->data, 1 + o->maxlen);
1776 static void o_addchr(o_string *o, int ch)
1778 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1780 o->data[o->length] = ch;
1782 o->data[o->length] = '\0';
1785 static void o_addblock(o_string *o, const char *str, int len)
1788 memcpy(&o->data[o->length], str, len);
1790 o->data[o->length] = '\0';
1794 static void o_addstr(o_string *o, const char *str)
1796 o_addblock(o, str, strlen(str));
1798 static void nommu_addchr(o_string *o, int ch)
1804 # define nommu_addchr(o, str) ((void)0)
1807 static void o_addstr_with_NUL(o_string *o, const char *str)
1809 o_addblock(o, str, strlen(str) + 1);
1812 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1817 && (*str != '*' && *str != '?' && *str != '[')
1825 /* My analysis of quoting semantics tells me that state information
1826 * is associated with a destination, not a source.
1828 static void o_addqchr(o_string *o, int ch)
1831 char *found = strchr("*?[\\", ch);
1836 o->data[o->length] = '\\';
1839 o->data[o->length] = ch;
1841 o->data[o->length] = '\0';
1844 static void o_addQchr(o_string *o, int ch)
1847 if (o->o_escape && strchr("*?[\\", ch)) {
1849 o->data[o->length] = '\\';
1853 o->data[o->length] = ch;
1855 o->data[o->length] = '\0';
1858 static void o_addQstr(o_string *o, const char *str, int len)
1861 o_addblock(o, str, len);
1867 int ordinary_cnt = strcspn(str, "*?[\\");
1868 if (ordinary_cnt > len) /* paranoia */
1870 o_addblock(o, str, ordinary_cnt);
1871 if (ordinary_cnt == len)
1873 str += ordinary_cnt;
1874 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1878 if (ch) { /* it is necessarily one of "*?[\\" */
1880 o->data[o->length] = '\\';
1884 o->data[o->length] = ch;
1886 o->data[o->length] = '\0';
1890 /* A special kind of o_string for $VAR and `cmd` expansion.
1891 * It contains char* list[] at the beginning, which is grown in 16 element
1892 * increments. Actual string data starts at the next multiple of 16 * (char*).
1893 * list[i] contains an INDEX (int!) into this string data.
1894 * It means that if list[] needs to grow, data needs to be moved higher up
1895 * but list[i]'s need not be modified.
1896 * NB: remembering how many list[i]'s you have there is crucial.
1897 * o_finalize_list() operation post-processes this structure - calculates
1898 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1900 #if DEBUG_EXPAND || DEBUG_GLOB
1901 static void debug_print_list(const char *prefix, o_string *o, int n)
1903 char **list = (char**)o->data;
1904 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1908 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1909 prefix, list, n, string_start, o->length, o->maxlen);
1912 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1913 o->data + (int)list[i] + string_start,
1914 o->data + (int)list[i] + string_start);
1918 const char *p = o->data + (int)list[n - 1] + string_start;
1920 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1924 # define debug_print_list(prefix, o, n) ((void)0)
1927 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1928 * in list[n] so that it points past last stored byte so far.
1929 * It returns n+1. */
1930 static int o_save_ptr_helper(o_string *o, int n)
1932 char **list = (char**)o->data;
1936 if (!o->has_empty_slot) {
1937 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1938 string_len = o->length - string_start;
1939 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1940 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1941 /* list[n] points to string_start, make space for 16 more pointers */
1942 o->maxlen += 0x10 * sizeof(list[0]);
1943 o->data = xrealloc(o->data, o->maxlen + 1);
1944 list = (char**)o->data;
1945 memmove(list + n + 0x10, list + n, string_len);
1946 o->length += 0x10 * sizeof(list[0]);
1948 debug_printf_list("list[%d]=%d string_start=%d\n",
1949 n, string_len, string_start);
1952 /* We have empty slot at list[n], reuse without growth */
1953 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1954 string_len = o->length - string_start;
1955 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1956 n, string_len, string_start);
1957 o->has_empty_slot = 0;
1959 list[n] = (char*)(ptrdiff_t)string_len;
1963 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1964 static int o_get_last_ptr(o_string *o, int n)
1966 char **list = (char**)o->data;
1967 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1969 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1972 /* o_glob performs globbing on last list[], saving each result
1973 * as a new list[]. */
1974 static int o_glob(o_string *o, int n)
1980 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1982 return o_save_ptr_helper(o, n);
1983 pattern = o->data + o_get_last_ptr(o, n);
1984 debug_printf_glob("glob pattern '%s'\n", pattern);
1985 if (!glob_needed(pattern)) {
1987 o->length = unbackslash(pattern) - o->data;
1988 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1989 return o_save_ptr_helper(o, n);
1992 memset(&globdata, 0, sizeof(globdata));
1993 gr = glob(pattern, 0, NULL, &globdata);
1994 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1995 if (gr == GLOB_NOSPACE)
1996 bb_error_msg_and_die("out of memory during glob");
1997 if (gr == GLOB_NOMATCH) {
1998 globfree(&globdata);
2001 if (gr != 0) { /* GLOB_ABORTED ? */
2002 /* TODO: testcase for bad glob pattern behavior */
2003 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2005 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2006 char **argv = globdata.gl_pathv;
2007 o->length = pattern - o->data; /* "forget" pattern */
2009 o_addstr_with_NUL(o, *argv);
2010 n = o_save_ptr_helper(o, n);
2016 globfree(&globdata);
2018 debug_print_list("o_glob returning", o, n);
2022 /* If o->o_glob == 1, glob the string so far remembered.
2023 * Otherwise, just finish current list[] and start new */
2024 static int o_save_ptr(o_string *o, int n)
2026 if (o->o_glob) { /* if globbing is requested */
2027 /* If o->has_empty_slot, list[n] was already globbed
2028 * (if it was requested back then when it was filled)
2029 * so don't do that again! */
2030 if (!o->has_empty_slot)
2031 return o_glob(o, n); /* o_save_ptr_helper is inside */
2033 return o_save_ptr_helper(o, n);
2036 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2037 static char **o_finalize_list(o_string *o, int n)
2042 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2044 debug_print_list("finalized", o, n);
2045 debug_printf_expand("finalized n:%d\n", n);
2046 list = (char**)o->data;
2047 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2051 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2057 /* Expansion can recurse */
2058 #if ENABLE_HUSH_TICK
2059 static int process_command_subs(o_string *dest, const char *s);
2061 static char *expand_string_to_string(const char *str);
2063 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2064 parse_stream_dquoted(dest, input, dquote_end)
2066 static int parse_stream_dquoted(o_string *as_string,
2068 struct in_str *input,
2071 /* expand_strvec_to_strvec() takes a list of strings, expands
2072 * all variable references within and returns a pointer to
2073 * a list of expanded strings, possibly with larger number
2074 * of strings. (Think VAR="a b"; echo $VAR).
2075 * This new list is allocated as a single malloc block.
2076 * NULL-terminated list of char* pointers is at the beginning of it,
2077 * followed by strings themself.
2078 * Caller can deallocate entire list by single free(list). */
2080 /* Store given string, finalizing the word and starting new one whenever
2081 * we encounter IFS char(s). This is used for expanding variable values.
2082 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2083 static int expand_on_ifs(o_string *output, int n, const char *str)
2086 int word_len = strcspn(str, G.ifs);
2088 if (output->o_escape || !output->o_glob)
2089 o_addQstr(output, str, word_len);
2090 else /* protect backslashes against globbing up :) */
2091 o_addblock_duplicate_backslash(output, str, word_len);
2094 if (!*str) /* EOL - do not finalize word */
2096 o_addchr(output, '\0');
2097 debug_print_list("expand_on_ifs", output, n);
2098 n = o_save_ptr(output, n);
2099 str += strspn(str, G.ifs); /* skip ifs chars */
2101 debug_print_list("expand_on_ifs[1]", output, n);
2105 /* Helper to expand $((...)) and heredoc body. These act as if
2106 * they are in double quotes, with the exception that they are not :).
2107 * Just the rules are similar: "expand only $var and `cmd`"
2109 * Returns malloced string.
2110 * As an optimization, we return NULL if expansion is not needed.
2112 static char *expand_pseudo_dquoted(const char *str)
2115 struct in_str input;
2116 o_string dest = NULL_O_STRING;
2118 if (strchr(str, '$') == NULL
2119 #if ENABLE_HUSH_TICK
2120 && strchr(str, '`') == NULL
2126 /* We need to expand. Example:
2127 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2129 setup_string_in_str(&input, str);
2130 parse_stream_dquoted(NULL, &dest, &input, EOF);
2131 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2132 exp_str = expand_string_to_string(dest.data);
2133 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2134 o_free_unsafe(&dest);
2138 /* Expand all variable references in given string, adding words to list[]
2139 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2140 * to be filled). This routine is extremely tricky: has to deal with
2141 * variables/parameters with whitespace, $* and $@, and constructs like
2142 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2143 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2145 /* or_mask is either 0 (normal case) or 0x80 -
2146 * expansion of right-hand side of assignment == 1-element expand.
2147 * It will also do no globbing, and thus we must not backslash-quote!
2154 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2155 debug_print_list("expand_vars_to_list", output, n);
2156 n = o_save_ptr(output, n);
2157 debug_print_list("expand_vars_to_list[0]", output, n);
2159 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2162 char *dyn_val = NULL;
2163 const char *val = NULL;
2164 #if ENABLE_HUSH_TICK
2165 o_string subst_result = NULL_O_STRING;
2167 #if ENABLE_SH_MATH_SUPPORT
2168 char arith_buf[sizeof(arith_t)*3 + 2];
2170 o_addblock(output, arg, p - arg);
2171 debug_print_list("expand_vars_to_list[1]", output, n);
2173 p = strchr(p, SPECIAL_VAR_SYMBOL);
2175 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2176 /* "$@" is special. Even if quoted, it can still
2177 * expand to nothing (not even an empty string) */
2178 if ((first_ch & 0x7f) != '@')
2179 ored_ch |= first_ch;
2181 switch (first_ch & 0x7f) {
2182 /* Highest bit in first_ch indicates that var is double-quoted */
2184 val = utoa(G.root_pid);
2186 case '!': /* bg pid */
2187 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2189 case '?': /* exitcode */
2190 val = utoa(G.last_exitcode);
2192 case '#': /* argc */
2193 if (arg[1] != SPECIAL_VAR_SYMBOL)
2194 /* actually, it's a ${#var} */
2196 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2201 if (!G.global_argv[i])
2203 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2204 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2205 smallint sv = output->o_escape;
2206 /* unquoted var's contents should be globbed, so don't escape */
2207 output->o_escape = 0;
2208 while (G.global_argv[i]) {
2209 n = expand_on_ifs(output, n, G.global_argv[i]);
2210 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2211 if (G.global_argv[i++][0] && G.global_argv[i]) {
2212 /* this argv[] is not empty and not last:
2213 * put terminating NUL, start new word */
2214 o_addchr(output, '\0');
2215 debug_print_list("expand_vars_to_list[2]", output, n);
2216 n = o_save_ptr(output, n);
2217 debug_print_list("expand_vars_to_list[3]", output, n);
2220 output->o_escape = sv;
2222 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2223 * and in this case should treat it like '$*' - see 'else...' below */
2224 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2226 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2227 if (++i >= G.global_argc)
2229 o_addchr(output, '\0');
2230 debug_print_list("expand_vars_to_list[4]", output, n);
2231 n = o_save_ptr(output, n);
2233 } else { /* quoted $*: add as one word */
2235 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2236 if (!G.global_argv[++i])
2239 o_addchr(output, G.ifs[0]);
2243 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2244 /* "Empty variable", used to make "" etc to not disappear */
2248 #if ENABLE_HUSH_TICK
2249 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2252 /* Can't just stuff it into output o_string,
2253 * expanded result may need to be globbed
2254 * and $IFS-splitted */
2255 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2256 process_command_subs(&subst_result, arg);
2257 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2258 val = subst_result.data;
2261 #if ENABLE_SH_MATH_SUPPORT
2262 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2263 arith_eval_hooks_t hooks;
2268 arg++; /* skip '+' */
2269 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2270 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2272 exp_str = expand_pseudo_dquoted(arg);
2273 hooks.lookupvar = get_local_var_value;
2274 hooks.setvar = arith_set_local_var;
2275 hooks.endofname = endofname;
2276 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2280 const char *msg = "error in arithmetic";
2283 msg = "exponent less than 0";
2286 msg = "divide by 0";
2289 msg = "expression recursion loop detected";
2294 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2295 sprintf(arith_buf, arith_t_fmt, res);
2300 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2302 bool exp_len = false;
2303 bool exp_null = false;
2305 char exp_save = exp_save; /* for compiler */
2306 char exp_op = exp_op; /* for compiler */
2307 char *exp_word = exp_word; /* for compiler */
2311 arg[0] = first_ch & 0x7f;
2313 /* prepare for expansions */
2314 if (var[0] == '#') {
2315 /* handle length expansion ${#var} */
2319 /* maybe handle parameter expansion */
2320 exp_off = strcspn(var, ":-=+?%#");
2324 exp_save = var[exp_off];
2325 exp_null = exp_save == ':';
2326 exp_word = var + exp_off;
2329 exp_op = *exp_word++;
2330 var[exp_off] = '\0';
2334 /* lookup the variable in question */
2335 if (isdigit(var[0])) {
2336 /* handle_dollar() should have vetted var for us */
2338 if (i < G.global_argc)
2339 val = G.global_argv[i];
2340 /* else val remains NULL: $N with too big N */
2342 val = get_local_var_value(var);
2344 /* handle any expansions */
2346 debug_printf_expand("expand: length of '%s' = ", val);
2347 val = utoa(val ? strlen(val) : 0);
2348 debug_printf_expand("%s\n", val);
2349 } else if (exp_off) {
2350 if (exp_op == '%' || exp_op == '#') {
2352 /* we need to do a pattern match */
2355 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2356 if (exp_op == *exp_word) /* ## or %% */
2358 val = dyn_val = xstrdup(val);
2359 loc = scan(dyn_val, exp_word, match_at_left);
2360 if (match_at_left) /* # or ## */
2362 else if (loc) /* % or %% and match was found */
2366 /* we need to do an expansion */
2367 int exp_test = (!val || (exp_null && !val[0]));
2369 exp_test = !exp_test;
2370 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2371 exp_null ? "true" : "false", exp_test);
2373 if (exp_op == '?') {
2374 //TODO: how interactive bash aborts expansion mid-command?
2375 /* ${var?[error_msg_if_unset]} */
2376 /* ${var:?[error_msg_if_unset_or_null]} */
2377 /* mimic bash message */
2378 die_if_script("%s: %s",
2380 exp_word[0] ? exp_word : "parameter null or not set"
2386 if (exp_op == '=') {
2387 /* ${var=[word]} or ${var:=[word]} */
2388 if (isdigit(var[0]) || var[0] == '#') {
2389 /* mimic bash message */
2390 die_if_script("$%s: cannot assign in this way", var);
2393 char *new_var = xasprintf("%s=%s", var, val);
2394 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2400 var[exp_off] = exp_save;
2404 #if ENABLE_HUSH_TICK
2407 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2408 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2410 /* unquoted var's contents should be globbed, so don't escape */
2411 smallint sv = output->o_escape;
2412 output->o_escape = 0;
2413 n = expand_on_ifs(output, n, val);
2415 output->o_escape = sv;
2417 } else { /* quoted $VAR, val will be appended below */
2418 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2421 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2424 o_addQstr(output, val, strlen(val));
2427 /* Do the check to avoid writing to a const string */
2428 if (*p != SPECIAL_VAR_SYMBOL)
2429 *p = SPECIAL_VAR_SYMBOL;
2431 #if ENABLE_HUSH_TICK
2432 o_free(&subst_result);
2435 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2438 debug_print_list("expand_vars_to_list[a]", output, n);
2439 /* this part is literal, and it was already pre-quoted
2440 * if needed (much earlier), do not use o_addQstr here! */
2441 o_addstr_with_NUL(output, arg);
2442 debug_print_list("expand_vars_to_list[b]", output, n);
2443 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2444 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2447 /* allow to reuse list[n] later without re-growth */
2448 output->has_empty_slot = 1;
2450 o_addchr(output, '\0');
2455 static char **expand_variables(char **argv, int or_mask)
2460 o_string output = NULL_O_STRING;
2462 if (or_mask & 0x100) {
2463 output.o_escape = 1; /* protect against globbing for "$var" */
2464 /* (unquoted $var will temporarily switch it off) */
2471 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2474 debug_print_list("expand_variables", &output, n);
2476 /* output.data (malloced in one block) gets returned in "list" */
2477 list = o_finalize_list(&output, n);
2478 debug_print_strings("expand_variables[1]", list);
2482 static char **expand_strvec_to_strvec(char **argv)
2484 return expand_variables(argv, 0x100);
2487 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2489 return expand_variables(argv, 0x80);
2492 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2493 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2498 o_string output = NULL_O_STRING;
2503 int is_var = is_well_formed_var_name(*v, '=');
2504 /* is_var * 0x80: singleword expansion for vars */
2505 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2507 /* Subtle! expand_vars_to_list did not glob last word yet.
2508 * It does this only when fed with further data.
2509 * Therefore we set globbing flags AFTER it, not before:
2512 /* if it is not recognizably abc=...; then: */
2513 output.o_escape = !is_var; /* protect against globbing for "$var" */
2514 /* (unquoted $var will temporarily switch it off) */
2515 output.o_glob = !is_var; /* and indeed do globbing */
2518 debug_print_list("expand_cond", &output, n);
2520 /* output.data (malloced in one block) gets returned in "list" */
2521 list = o_finalize_list(&output, n);
2522 debug_print_strings("expand_cond[1]", list);
2527 /* Used for expansion of right hand of assignments */
2528 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2530 static char *expand_string_to_string(const char *str)
2532 char *argv[2], **list;
2534 argv[0] = (char*)str;
2536 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2538 if (!list[0] || list[1])
2539 bb_error_msg_and_die("BUG in varexp2");
2540 /* actually, just move string 2*sizeof(char*) bytes back */
2541 overlapping_strcpy((char*)list, list[0]);
2542 unbackslash((char*)list);
2543 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2547 /* Used for "eval" builtin */
2548 static char* expand_strvec_to_string(char **argv)
2552 list = expand_variables(argv, 0x80);
2553 /* Convert all NULs to spaces */
2558 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2559 bb_error_msg_and_die("BUG in varexp3");
2560 /* bash uses ' ' regardless of $IFS contents */
2565 overlapping_strcpy((char*)list, list[0]);
2566 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2570 static char **expand_assignments(char **argv, int count)
2574 /* Expand assignments into one string each */
2575 for (i = 0; i < count; i++) {
2576 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2584 void re_execute_shell(char ***to_free, const char *s,
2585 char *g_argv0, char **g_argv,
2586 char **builtin_argv) NORETURN;
2588 static void reset_traps_to_defaults(void)
2590 /* This function is always called in a child shell
2591 * after fork (not vfork, NOMMU doesn't use this function).
2592 * Child shells are not interactive.
2593 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2594 * Testcase: (while :; do :; done) + ^Z should background.
2595 * Same goes for SIGTERM, SIGHUP, SIGINT.
2600 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2603 /* Stupid. It can be done with *single* &= op, but we can't use
2604 * the fact that G.blocked_set is implemented as a bitmask... */
2605 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2609 sigdelset(&G.blocked_set, sig);
2616 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2617 mask = G.non_DFL_mask;
2618 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2622 G.traps[sig] = NULL;
2623 /* There is no signal for 0 (EXIT) */
2626 /* There was a trap handler, we are removing it.
2627 * But if sig still has non-DFL handling,
2628 * we should not unblock it. */
2631 sigdelset(&G.blocked_set, sig);
2633 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2638 static void re_execute_shell(char ***to_free, const char *s,
2639 char *g_argv0, char **g_argv,
2640 char **builtin_argv) NORETURN;
2641 static void re_execute_shell(char ***to_free, const char *s,
2642 char *g_argv0, char **g_argv,
2643 char **builtin_argv)
2645 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2646 char *heredoc_argv[4];
2647 struct variable *cur;
2648 #if ENABLE_HUSH_FUNCTIONS
2649 struct function *funcp;
2654 if (!g_argv0) { /* heredoc */
2655 argv = heredoc_argv;
2656 argv[0] = (char *) G.argv0_for_re_execing;
2657 argv[1] = (char *) "-<";
2658 argv[2] = (char *) s;
2660 pp = &argv[3]; /* used as pointer to empty environment */
2666 if (pp) while (*pp++)
2669 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2670 , (unsigned) G.root_pid
2671 , (unsigned) G.last_bg_pid
2672 , (unsigned) G.last_exitcode
2674 IF_HUSH_LOOPS(, G.depth_of_loop)
2676 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2677 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2680 for (cur = G.top_var; cur; cur = cur->next) {
2681 if (!cur->flg_export || cur->flg_read_only)
2684 #if ENABLE_HUSH_FUNCTIONS
2685 for (funcp = G.top_func; funcp; funcp = funcp->next)
2691 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2692 *pp++ = (char *) G.argv0_for_re_execing;
2694 for (cur = G.top_var; cur; cur = cur->next) {
2695 if (cur->varstr == hush_version_str)
2697 if (cur->flg_read_only) {
2698 *pp++ = (char *) "-R";
2699 *pp++ = cur->varstr;
2700 } else if (!cur->flg_export) {
2701 *pp++ = (char *) "-V";
2702 *pp++ = cur->varstr;
2705 #if ENABLE_HUSH_FUNCTIONS
2706 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2707 *pp++ = (char *) "-F";
2708 *pp++ = funcp->name;
2709 *pp++ = funcp->body_as_string;
2712 /* We can pass activated traps here. Say, -Tnn:trap_string
2714 * However, POSIX says that subshells reset signals with traps
2716 * I tested bash-3.2 and it not only does that with true subshells
2717 * of the form ( list ), but with any forked children shells.
2718 * I set trap "echo W" WINCH; and then tried:
2720 * { echo 1; sleep 20; echo 2; } &
2721 * while true; do echo 1; sleep 20; echo 2; break; done &
2722 * true | { echo 1; sleep 20; echo 2; } | cat
2724 * In all these cases sending SIGWINCH to the child shell
2725 * did not run the trap. If I add trap "echo V" WINCH;
2726 * _inside_ group (just before echo 1), it works.
2728 * I conclude it means we don't need to pass active traps here.
2729 * exec syscall below resets them to SIG_DFL for us.
2731 *pp++ = (char *) "-c";
2734 while (*++builtin_argv)
2735 *pp++ = *builtin_argv;
2736 *pp++ = (char *) "";
2741 /* *pp = NULL; - is already there */
2745 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2746 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2747 execve(bb_busybox_exec_path, argv, pp);
2748 /* Fallback. Useful for init=/bin/hush usage etc */
2749 if (argv[0][0] == '/')
2750 execve(argv[0], argv, pp);
2751 xfunc_error_retval = 127;
2752 bb_error_msg_and_die("can't re-execute the shell");
2754 #endif /* !BB_MMU */
2757 static void setup_heredoc(struct redir_struct *redir)
2759 struct fd_pair pair;
2762 /* the _body_ of heredoc (misleading field name) */
2763 const char *heredoc = redir->rd_filename;
2770 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2771 expanded = expand_pseudo_dquoted(heredoc);
2775 len = strlen(heredoc);
2777 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2779 xmove_fd(pair.rd, redir->rd_fd);
2781 /* Try writing without forking. Newer kernels have
2782 * dynamically growing pipes. Must use non-blocking write! */
2785 written = write(pair.wr, heredoc, len);
2796 ndelay_off(pair.wr);
2798 /* Okay, pipe buffer was not big enough */
2799 /* Note: we must not create a stray child (bastard? :)
2800 * for the unsuspecting parent process. Child creates a grandchild
2801 * and exits before parent execs the process which consumes heredoc
2802 * (that exec happens after we return from this function) */
2808 bb_perror_msg_and_die("vfork");
2811 disable_restore_tty_pgrp_on_exit();
2812 pid = BB_MMU ? fork() : vfork();
2814 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2818 close(redir->rd_fd); /* read side of the pipe */
2820 full_write(pair.wr, heredoc, len); /* may loop or block */
2823 /* Delegate blocking writes to another process */
2824 xmove_fd(pair.wr, STDOUT_FILENO);
2825 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2829 #if ENABLE_HUSH_FAST
2831 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2833 enable_restore_tty_pgrp_on_exit();
2839 wait(NULL); /* wait till child has died */
2842 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2843 * and stderr if they are redirected. */
2844 static int setup_redirects(struct command *prog, int squirrel[])
2847 struct redir_struct *redir;
2849 for (redir = prog->redirects; redir; redir = redir->next) {
2850 if (redir->rd_type == REDIRECT_HEREDOC2) {
2851 /* rd_fd<<HERE case */
2852 if (squirrel && redir->rd_fd < 3
2853 && squirrel[redir->rd_fd] < 0
2855 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2857 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2859 debug_printf_parse("set heredoc '%s'\n",
2860 redir->rd_filename);
2861 setup_heredoc(redir);
2865 if (redir->rd_dup == REDIRFD_TO_FILE) {
2866 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2868 if (redir->rd_filename == NULL) {
2869 /* Something went wrong in the parse.
2870 * Pretend it didn't happen */
2871 bb_error_msg("bug in redirect parse");
2874 mode = redir_table[redir->rd_type].mode;
2875 p = expand_string_to_string(redir->rd_filename);
2876 openfd = open_or_warn(p, mode);
2879 /* this could get lost if stderr has been redirected, but
2880 * bash and ash both lose it as well (though zsh doesn't!) */
2881 //what the above comment tries to say?
2885 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2886 openfd = redir->rd_dup;
2889 if (openfd != redir->rd_fd) {
2890 if (squirrel && redir->rd_fd < 3
2891 && squirrel[redir->rd_fd] < 0
2893 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2895 if (openfd == REDIRFD_CLOSE) {
2896 /* "n>-" means "close me" */
2897 close(redir->rd_fd);
2899 xdup2(openfd, redir->rd_fd);
2900 if (redir->rd_dup == REDIRFD_TO_FILE)
2908 static void restore_redirects(int squirrel[])
2911 for (i = 0; i < 3; i++) {
2914 /* We simply die on error */
2921 static void free_pipe_list(struct pipe *head);
2923 /* Return code is the exit status of the pipe */
2924 static void free_pipe(struct pipe *pi)
2927 struct command *command;
2928 struct redir_struct *r, *rnext;
2931 if (pi->stopped_cmds > 0) /* why? */
2933 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2934 for (i = 0; i < pi->num_cmds; i++) {
2935 command = &pi->cmds[i];
2936 debug_printf_clean(" command %d:\n", i);
2937 if (command->argv) {
2938 for (a = 0, p = command->argv; *p; a++, p++) {
2939 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2941 free_strings(command->argv);
2942 command->argv = NULL;
2944 /* not "else if": on syntax error, we may have both! */
2945 if (command->group) {
2946 debug_printf_clean(" begin group (cmd_type:%d)\n",
2948 free_pipe_list(command->group);
2949 debug_printf_clean(" end group\n");
2950 command->group = NULL;
2952 /* else is crucial here.
2953 * If group != NULL, child_func is meaningless */
2954 #if ENABLE_HUSH_FUNCTIONS
2955 else if (command->child_func) {
2956 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2957 command->child_func->parent_cmd = NULL;
2961 free(command->group_as_string);
2962 command->group_as_string = NULL;
2964 for (r = command->redirects; r; r = rnext) {
2965 debug_printf_clean(" redirect %d%s",
2966 r->rd_fd, redir_table[r->rd_type].descrip);
2967 /* guard against the case >$FOO, where foo is unset or blank */
2968 if (r->rd_filename) {
2969 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2970 free(r->rd_filename);
2971 r->rd_filename = NULL;
2973 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2977 command->redirects = NULL;
2979 free(pi->cmds); /* children are an array, they get freed all at once */
2987 static void free_pipe_list(struct pipe *head)
2989 struct pipe *pi, *next;
2991 for (pi = head; pi; pi = next) {
2993 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2996 debug_printf_clean("pipe followup code %d\n", pi->followup);
2998 /*pi->next = NULL;*/
3004 static int run_list(struct pipe *pi);
3006 #define parse_stream(pstring, input, end_trigger) \
3007 parse_stream(input, end_trigger)
3009 static struct pipe *parse_stream(char **pstring,
3010 struct in_str *input,
3012 static void parse_and_run_string(const char *s);
3015 static char *find_in_path(const char *arg)
3018 const char *PATH = get_local_var_value("PATH");
3024 const char *end = strchrnul(PATH, ':');
3025 int sz = end - PATH; /* must be int! */
3029 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3031 /* We have xxx::yyyy in $PATH,
3032 * it means "use current dir" */
3035 if (access(ret, F_OK) == 0)
3048 static const struct built_in_command* find_builtin_helper(const char *name,
3049 const struct built_in_command *x,
3050 const struct built_in_command *end)
3053 if (strcmp(name, x->cmd) != 0) {
3057 debug_printf_exec("found builtin '%s'\n", name);
3062 static const struct built_in_command* find_builtin1(const char *name)
3064 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3066 static const struct built_in_command* find_builtin(const char *name)
3068 const struct built_in_command *x = find_builtin1(name);
3071 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3074 #if ENABLE_HUSH_FUNCTIONS
3075 static const struct function *find_function(const char *name)
3077 const struct function *funcp = G.top_func;
3079 if (strcmp(name, funcp->name) == 0) {
3082 funcp = funcp->next;
3085 debug_printf_exec("found function '%s'\n", name);
3089 /* Note: takes ownership on name ptr */
3090 static struct function *new_function(char *name)
3092 struct function *funcp;
3093 struct function **funcpp = &G.top_func;
3095 while ((funcp = *funcpp) != NULL) {
3096 struct command *cmd;
3098 if (strcmp(funcp->name, name) != 0) {
3099 funcpp = &funcp->next;
3103 cmd = funcp->parent_cmd;
3104 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3106 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3108 /* Note: if !funcp->body, do not free body_as_string!
3109 * This is a special case of "-F name body" function:
3110 * body_as_string was not malloced! */
3112 free_pipe_list(funcp->body);
3114 free(funcp->body_as_string);
3118 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3119 cmd->argv[0] = funcp->name;
3120 cmd->group = funcp->body;
3122 cmd->group_as_string = funcp->body_as_string;
3127 debug_printf_exec("remembering new function '%s'\n", name);
3128 funcp = *funcpp = xzalloc(sizeof(*funcp));
3129 /*funcp->next = NULL;*/
3135 static void unset_func(const char *name)
3137 struct function *funcp;
3138 struct function **funcpp = &G.top_func;
3140 while ((funcp = *funcpp) != NULL) {
3141 if (strcmp(funcp->name, name) == 0) {
3142 *funcpp = funcp->next;
3143 /* funcp is unlinked now, deleting it.
3144 * Note: if !funcp->body, the function was created by
3145 * "-F name body", do not free ->body_as_string
3146 * and ->name as they were not malloced. */
3148 free_pipe_list(funcp->body);
3151 free(funcp->body_as_string);
3157 funcpp = &funcp->next;
3162 #define exec_function(to_free, funcp, argv) \
3163 exec_function(funcp, argv)
3165 static void exec_function(char ***to_free,
3166 const struct function *funcp,
3167 char **argv) NORETURN;
3168 static void exec_function(char ***to_free,
3169 const struct function *funcp,
3175 argv[0] = G.global_argv[0];
3176 G.global_argv = argv;
3180 /* On MMU, funcp->body is always non-NULL */
3181 n = run_list(funcp->body);
3185 re_execute_shell(to_free,
3186 funcp->body_as_string,
3193 static int run_function(const struct function *funcp, char **argv)
3199 save_and_replace_G_args(&sv, argv);
3201 /* "we are in function, ok to use return" */
3202 sv_flg = G.flag_return_in_progress;
3203 G.flag_return_in_progress = -1;
3204 #if ENABLE_HUSH_LOCAL
3205 G.func_nest_level++;
3208 /* On MMU, funcp->body is always non-NULL */
3211 /* Function defined by -F */
3212 parse_and_run_string(funcp->body_as_string);
3213 rc = G.last_exitcode;
3217 rc = run_list(funcp->body);
3220 #if ENABLE_HUSH_LOCAL
3222 struct variable *var;
3223 struct variable **var_pp;
3225 var_pp = &G.top_var;
3226 while ((var = *var_pp) != NULL) {
3227 if (var->func_nest_level < G.func_nest_level) {
3228 var_pp = &var->next;
3232 if (var->flg_export)
3233 bb_unsetenv(var->varstr);
3234 /* Remove from global list */
3235 *var_pp = var->next;
3241 G.func_nest_level--;
3244 G.flag_return_in_progress = sv_flg;
3246 restore_G_args(&sv, argv);
3250 #endif /* ENABLE_HUSH_FUNCTIONS */
3254 #define exec_builtin(to_free, x, argv) \
3255 exec_builtin(x, argv)
3257 #define exec_builtin(to_free, x, argv) \
3258 exec_builtin(to_free, argv)
3260 static void exec_builtin(char ***to_free,
3261 const struct built_in_command *x,
3262 char **argv) NORETURN;
3263 static void exec_builtin(char ***to_free,
3264 const struct built_in_command *x,
3268 int rcode = x->function(argv);
3272 /* On NOMMU, we must never block!
3273 * Example: { sleep 99 | read line; } & echo Ok
3275 re_execute_shell(to_free,
3285 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3286 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3287 #define pseudo_exec(nommu_save, command, argv_expanded) \
3288 pseudo_exec(command, argv_expanded)
3291 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3293 * Don't exit() here. If you don't exec, use _exit instead.
3294 * The at_exit handlers apparently confuse the calling process,
3295 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3296 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3297 char **argv, int assignment_cnt,
3298 char **argv_expanded) NORETURN;
3299 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3300 char **argv, int assignment_cnt,
3301 char **argv_expanded)
3305 /* Case when we are here: ... | var=val | ... */
3306 if (!argv[assignment_cnt])
3307 _exit(EXIT_SUCCESS);
3309 new_env = expand_assignments(argv, assignment_cnt);
3311 set_vars_and_save_old(new_env);
3312 free(new_env); /* optional */
3313 /* we can also destroy set_vars_and_save_old's return value,
3316 nommu_save->new_env = new_env;
3317 nommu_save->old_vars = set_vars_and_save_old(new_env);
3319 if (argv_expanded) {
3320 argv = argv_expanded;
3322 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3324 nommu_save->argv = argv;
3328 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3329 if (strchr(argv[0], '/') != NULL)
3333 /* Check if the command matches any of the builtins.
3334 * Depending on context, this might be redundant. But it's
3335 * easier to waste a few CPU cycles than it is to figure out
3336 * if this is one of those cases.
3339 /* On NOMMU, it is more expensive to re-execute shell
3340 * just in order to run echo or test builtin.
3341 * It's better to skip it here and run corresponding
3342 * non-builtin later. */
3343 const struct built_in_command *x;
3344 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3346 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3349 #if ENABLE_HUSH_FUNCTIONS
3350 /* Check if the command matches any functions */
3352 const struct function *funcp = find_function(argv[0]);
3354 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3359 #if ENABLE_FEATURE_SH_STANDALONE
3360 /* Check if the command matches any busybox applets */
3362 int a = find_applet_by_name(argv[0]);
3364 # if BB_MMU /* see above why on NOMMU it is not allowed */
3365 if (APPLET_IS_NOEXEC(a)) {
3366 debug_printf_exec("running applet '%s'\n", argv[0]);
3367 run_applet_no_and_exit(a, argv);
3370 /* Re-exec ourselves */
3371 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3372 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3373 execv(bb_busybox_exec_path, argv);
3374 /* If they called chroot or otherwise made the binary no longer
3375 * executable, fall through */
3380 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3383 debug_printf_exec("execing '%s'\n", argv[0]);
3384 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3385 execvp(argv[0], argv);
3386 bb_perror_msg("can't execute '%s'", argv[0]);
3387 _exit(EXIT_FAILURE);
3390 /* Called after [v]fork() in run_pipe
3392 static void pseudo_exec(nommu_save_t *nommu_save,
3393 struct command *command,
3394 char **argv_expanded) NORETURN;
3395 static void pseudo_exec(nommu_save_t *nommu_save,
3396 struct command *command,
3397 char **argv_expanded)
3399 if (command->argv) {
3400 pseudo_exec_argv(nommu_save, command->argv,
3401 command->assignment_cnt, argv_expanded);
3404 if (command->group) {
3405 /* Cases when we are here:
3408 * ... | ( list ) | ...
3409 * ... | { list } | ...
3413 debug_printf_exec("pseudo_exec: run_list\n");
3414 reset_traps_to_defaults();
3415 rcode = run_list(command->group);
3416 /* OK to leak memory by not calling free_pipe_list,
3417 * since this process is about to exit */
3420 re_execute_shell(&nommu_save->argv_from_re_execing,
3421 command->group_as_string,
3428 /* Case when we are here: ... | >file */
3429 debug_printf_exec("pseudo_exec'ed null command\n");
3430 _exit(EXIT_SUCCESS);
3434 static const char *get_cmdtext(struct pipe *pi)
3440 /* This is subtle. ->cmdtext is created only on first backgrounding.
3441 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3442 * On subsequent bg argv is trashed, but we won't use it */
3445 argv = pi->cmds[0].argv;
3446 if (!argv || !argv[0]) {
3447 pi->cmdtext = xzalloc(1);
3453 len += strlen(*argv) + 1;
3457 argv = pi->cmds[0].argv;
3459 len = strlen(*argv);
3460 memcpy(p, *argv, len);
3468 static void insert_bg_job(struct pipe *pi)
3470 struct pipe *job, **jobp;
3473 /* Linear search for the ID of the job to use */
3475 for (job = G.job_list; job; job = job->next)
3476 if (job->jobid >= pi->jobid)
3477 pi->jobid = job->jobid + 1;
3479 /* Add job to the list of running jobs */
3481 while ((job = *jobp) != NULL)
3483 job = *jobp = xmalloc(sizeof(*job));
3485 *job = *pi; /* physical copy */
3487 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3488 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3489 for (i = 0; i < pi->num_cmds; i++) {
3490 job->cmds[i].pid = pi->cmds[i].pid;
3491 /* all other fields are not used and stay zero */
3493 job->cmdtext = xstrdup(get_cmdtext(pi));
3495 if (G_interactive_fd)
3496 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3497 /* Last command's pid goes to $! */
3498 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3499 G.last_jobid = job->jobid;
3502 static void remove_bg_job(struct pipe *pi)
3504 struct pipe *prev_pipe;
3506 if (pi == G.job_list) {
3507 G.job_list = pi->next;
3509 prev_pipe = G.job_list;
3510 while (prev_pipe->next != pi)
3511 prev_pipe = prev_pipe->next;
3512 prev_pipe->next = pi->next;
3515 G.last_jobid = G.job_list->jobid;
3520 /* Remove a backgrounded job */
3521 static void delete_finished_bg_job(struct pipe *pi)
3524 pi->stopped_cmds = 0;
3530 /* Check to see if any processes have exited -- if they
3531 * have, figure out why and see if a job has completed */
3532 static int checkjobs(struct pipe* fg_pipe)
3542 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3544 attributes = WUNTRACED;
3545 if (fg_pipe == NULL)
3546 attributes |= WNOHANG;
3549 #if ENABLE_HUSH_FAST
3550 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3551 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3552 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3553 /* There was neither fork nor SIGCHLD since last waitpid */
3554 /* Avoid doing waitpid syscall if possible */
3555 if (!G.we_have_children) {
3559 if (fg_pipe == NULL) { /* is WNOHANG set? */
3560 /* We have children, but they did not exit
3561 * or stop yet (we saw no SIGCHLD) */
3564 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3568 /* Do we do this right?
3569 * bash-3.00# sleep 20 | false
3571 * [3]+ Stopped sleep 20 | false
3572 * bash-3.00# echo $?
3573 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3574 * [hush 1.14.0: yes we do it right]
3581 #if ENABLE_HUSH_FAST
3582 i = G.count_SIGCHLD;
3584 childpid = waitpid(-1, &status, attributes);
3585 if (childpid <= 0) {
3586 if (childpid && errno != ECHILD)
3587 bb_perror_msg("waitpid");
3588 #if ENABLE_HUSH_FAST
3589 else { /* Until next SIGCHLD, waitpid's are useless */
3590 G.we_have_children = (childpid == 0);
3591 G.handled_SIGCHLD = i;
3592 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3597 dead = WIFEXITED(status) || WIFSIGNALED(status);
3600 if (WIFSTOPPED(status))
3601 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3602 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3603 if (WIFSIGNALED(status))
3604 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3605 childpid, WTERMSIG(status), WEXITSTATUS(status));
3606 if (WIFEXITED(status))
3607 debug_printf_jobs("pid %d exited, exitcode %d\n",
3608 childpid, WEXITSTATUS(status));
3610 /* Were we asked to wait for fg pipe? */
3612 for (i = 0; i < fg_pipe->num_cmds; i++) {
3613 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3614 if (fg_pipe->cmds[i].pid != childpid)
3617 fg_pipe->cmds[i].pid = 0;
3618 fg_pipe->alive_cmds--;
3619 if (i == fg_pipe->num_cmds - 1) {
3620 /* last process gives overall exitstatus */
3621 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3622 rcode = WEXITSTATUS(status);
3623 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3624 /* bash prints killing signal's name for *last*
3625 * process in pipe (prints just newline for SIGINT).
3626 * Mimic this. Example: "sleep 5" + ^\
3628 if (WIFSIGNALED(status)) {
3629 int sig = WTERMSIG(status);
3630 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3634 fg_pipe->cmds[i].is_stopped = 1;
3635 fg_pipe->stopped_cmds++;
3637 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3638 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3639 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3640 /* All processes in fg pipe have exited or stopped */
3641 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3642 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3643 * and "killall -STOP cat" */
3644 if (G_interactive_fd) {
3646 if (fg_pipe->alive_cmds)
3647 insert_bg_job(fg_pipe);
3651 if (!fg_pipe->alive_cmds)
3654 /* There are still running processes in the fg pipe */
3655 goto wait_more; /* do waitpid again */
3657 /* it wasnt fg_pipe, look for process in bg pipes */
3661 /* We asked to wait for bg or orphaned children */
3662 /* No need to remember exitcode in this case */
3663 for (pi = G.job_list; pi; pi = pi->next) {
3664 for (i = 0; i < pi->num_cmds; i++) {
3665 if (pi->cmds[i].pid == childpid)
3666 goto found_pi_and_prognum;
3669 /* Happens when shell is used as init process (init=/bin/sh) */
3670 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3671 continue; /* do waitpid again */
3673 found_pi_and_prognum:
3676 pi->cmds[i].pid = 0;
3678 if (!pi->alive_cmds) {
3679 if (G_interactive_fd)
3680 printf(JOB_STATUS_FORMAT, pi->jobid,
3681 "Done", pi->cmdtext);
3682 delete_finished_bg_job(pi);
3686 pi->cmds[i].is_stopped = 1;
3690 } /* while (waitpid succeeds)... */
3696 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3699 int rcode = checkjobs(fg_pipe);
3700 if (G_saved_tty_pgrp) {
3701 /* Job finished, move the shell to the foreground */
3702 p = getpgrp(); /* our process group id */
3703 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3704 tcsetpgrp(G_interactive_fd, p);
3710 /* Start all the jobs, but don't wait for anything to finish.
3713 * Return code is normally -1, when the caller has to wait for children
3714 * to finish to determine the exit status of the pipe. If the pipe
3715 * is a simple builtin command, however, the action is done by the
3716 * time run_pipe returns, and the exit code is provided as the
3719 * Returns -1 only if started some children. IOW: we have to
3720 * mask out retvals of builtins etc with 0xff!
3722 * The only case when we do not need to [v]fork is when the pipe
3723 * is single, non-backgrounded, non-subshell command. Examples:
3724 * cmd ; ... { list } ; ...
3725 * cmd && ... { list } && ...
3726 * cmd || ... { list } || ...
3727 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3728 * or (if SH_STANDALONE) an applet, and we can run the { list }
3729 * with run_list. If it isn't one of these, we fork and exec cmd.
3731 * Cases when we must fork:
3732 * non-single: cmd | cmd
3733 * backgrounded: cmd & { list } &
3734 * subshell: ( list ) [&]
3736 static int run_pipe(struct pipe *pi)
3738 static const char *const null_ptr = NULL;
3741 struct command *command;
3742 char **argv_expanded;
3745 /* it is not always needed, but we aim to smaller code */
3746 int squirrel[] = { -1, -1, -1 };
3749 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3752 IF_HUSH_JOB(pi->pgrp = -1;)
3753 pi->stopped_cmds = 0;
3754 command = &(pi->cmds[0]);
3755 argv_expanded = NULL;
3757 if (pi->num_cmds != 1
3758 || pi->followup == PIPE_BG
3759 || command->cmd_type == CMD_SUBSHELL
3766 debug_printf_exec(": group:%p argv:'%s'\n",
3767 command->group, command->argv ? command->argv[0] : "NONE");
3769 if (command->group) {
3770 #if ENABLE_HUSH_FUNCTIONS
3771 if (command->cmd_type == CMD_FUNCDEF) {
3772 /* "executing" func () { list } */
3773 struct function *funcp;
3775 funcp = new_function(command->argv[0]);
3776 /* funcp->name is already set to argv[0] */
3777 funcp->body = command->group;
3779 funcp->body_as_string = command->group_as_string;
3780 command->group_as_string = NULL;
3782 command->group = NULL;
3783 command->argv[0] = NULL;
3784 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3785 funcp->parent_cmd = command;
3786 command->child_func = funcp;
3788 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3790 return EXIT_SUCCESS;
3794 debug_printf("non-subshell group\n");
3795 rcode = 1; /* exitcode if redir failed */
3796 if (setup_redirects(command, squirrel) == 0) {
3797 debug_printf_exec(": run_list\n");
3798 rcode = run_list(command->group) & 0xff;
3800 restore_redirects(squirrel);
3801 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3803 debug_printf_exec("run_pipe: return %d\n", rcode);
3807 argv = command->argv ? command->argv : (char **) &null_ptr;
3809 const struct built_in_command *x;
3810 #if ENABLE_HUSH_FUNCTIONS
3811 const struct function *funcp;
3815 char **new_env = NULL;
3816 struct variable *old_vars = NULL;
3818 if (argv[command->assignment_cnt] == NULL) {
3819 /* Assignments, but no command */
3820 /* Ensure redirects take effect. Try "a=t >file" */
3821 rcode = setup_redirects(command, squirrel);
3822 restore_redirects(squirrel);
3823 /* Set shell variables */
3825 p = expand_string_to_string(*argv);
3826 debug_printf_exec("set shell var:'%s'->'%s'\n",
3828 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3831 /* Do we need to flag set_local_var() errors?
3832 * "assignment to readonly var" and "putenv error"
3834 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3836 debug_printf_exec("run_pipe: return %d\n", rcode);
3840 /* Expand the rest into (possibly) many strings each */
3841 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3842 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3844 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3845 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3846 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3851 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3854 x = find_builtin(argv_expanded[0]);
3855 #if ENABLE_HUSH_FUNCTIONS
3858 funcp = find_function(argv_expanded[0]);
3862 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3863 debug_printf("exec with redirects only\n");
3864 rcode = setup_redirects(command, NULL);
3865 goto clean_up_and_ret1;
3868 /* setup_redirects acts on file descriptors, not FILEs.
3869 * This is perfect for work that comes after exec().
3870 * Is it really safe for inline use? Experimentally,
3871 * things seem to work. */
3872 rcode = setup_redirects(command, squirrel);
3874 new_env = expand_assignments(argv, command->assignment_cnt);
3875 old_vars = set_vars_and_save_old(new_env);
3877 debug_printf_exec(": builtin '%s' '%s'...\n",
3878 x->cmd, argv_expanded[1]);
3879 rcode = x->function(argv_expanded) & 0xff;
3882 #if ENABLE_HUSH_FUNCTIONS
3884 # if ENABLE_HUSH_LOCAL
3885 struct variable **sv;
3886 sv = G.shadowed_vars_pp;
3887 G.shadowed_vars_pp = &old_vars;
3889 debug_printf_exec(": function '%s' '%s'...\n",
3890 funcp->name, argv_expanded[1]);
3891 rcode = run_function(funcp, argv_expanded) & 0xff;
3892 # if ENABLE_HUSH_LOCAL
3893 G.shadowed_vars_pp = sv;
3898 #if ENABLE_FEATURE_SH_STANDALONE
3901 restore_redirects(squirrel);
3902 unset_vars(new_env);
3905 free(argv_expanded);
3906 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3908 debug_printf_exec("run_pipe return %d\n", rcode);
3912 #if ENABLE_FEATURE_SH_STANDALONE
3913 i = find_applet_by_name(argv_expanded[0]);
3914 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3915 rcode = setup_redirects(command, squirrel);
3917 new_env = expand_assignments(argv, command->assignment_cnt);
3918 old_vars = set_vars_and_save_old(new_env);
3919 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3920 argv_expanded[0], argv_expanded[1]);
3921 rcode = run_nofork_applet(i, argv_expanded);
3923 goto clean_up_and_ret;
3926 /* It is neither builtin nor applet. We must fork. */
3930 /* NB: argv_expanded may already be created, and that
3931 * might include `cmd` runs! Do not rerun it! We *must*
3932 * use argv_expanded if it's non-NULL */
3934 /* Going to fork a child per each pipe member */
3938 for (i = 0; i < pi->num_cmds; i++) {
3939 struct fd_pair pipefds;
3941 volatile nommu_save_t nommu_save;
3942 nommu_save.new_env = NULL;
3943 nommu_save.old_vars = NULL;
3944 nommu_save.argv = NULL;
3945 nommu_save.argv_from_re_execing = NULL;
3947 command = &(pi->cmds[i]);
3948 if (command->argv) {
3949 debug_printf_exec(": pipe member '%s' '%s'...\n",
3950 command->argv[0], command->argv[1]);
3952 debug_printf_exec(": pipe member with no argv\n");
3955 /* pipes are inserted between pairs of commands */
3958 if ((i + 1) < pi->num_cmds)
3959 xpiped_pair(pipefds);
3961 command->pid = BB_MMU ? fork() : vfork();
3962 if (!command->pid) { /* child */
3964 disable_restore_tty_pgrp_on_exit();
3966 /* Every child adds itself to new process group
3967 * with pgid == pid_of_first_child_in_pipe */
3968 if (G.run_list_level == 1 && G_interactive_fd) {
3971 if (pgrp < 0) /* true for 1st process only */
3973 if (setpgid(0, pgrp) == 0
3974 && pi->followup != PIPE_BG
3975 && G_saved_tty_pgrp /* we have ctty */
3977 /* We do it in *every* child, not just first,
3979 tcsetpgrp(G_interactive_fd, pgrp);
3983 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3984 /* 1st cmd in backgrounded pipe
3985 * should have its stdin /dev/null'ed */
3987 if (open(bb_dev_null, O_RDONLY))
3988 xopen("/", O_RDONLY);
3990 xmove_fd(nextin, 0);
3992 xmove_fd(pipefds.wr, 1);
3995 /* Like bash, explicit redirects override pipes,
3996 * and the pipe fd is available for dup'ing. */
3997 if (setup_redirects(command, NULL))
4000 /* Restore default handlers just prior to exec */
4001 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4003 /* Stores to nommu_save list of env vars putenv'ed
4004 * (NOMMU, on MMU we don't need that) */
4005 /* cast away volatility... */
4006 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4007 /* pseudo_exec() does not return */
4010 /* parent or error */
4011 #if ENABLE_HUSH_FAST
4013 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4015 enable_restore_tty_pgrp_on_exit();
4017 /* Clean up after vforked child */
4018 free(nommu_save.argv);
4019 free(nommu_save.argv_from_re_execing);
4020 unset_vars(nommu_save.new_env);
4021 add_vars(nommu_save.old_vars);
4023 free(argv_expanded);
4024 argv_expanded = NULL;
4025 if (command->pid < 0) { /* [v]fork failed */
4026 /* Clearly indicate, was it fork or vfork */
4027 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4031 /* Second and next children need to know pid of first one */
4033 pi->pgrp = command->pid;
4039 if ((i + 1) < pi->num_cmds)
4041 /* Pass read (output) pipe end to next iteration */
4042 nextin = pipefds.rd;
4045 if (!pi->alive_cmds) {
4047 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4052 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4056 #ifndef debug_print_tree
4057 static void debug_print_tree(struct pipe *pi, int lvl)
4059 static const char *const PIPE[] = {
4065 static const char *RES[] = {
4066 [RES_NONE ] = "NONE" ,
4069 [RES_THEN ] = "THEN" ,
4070 [RES_ELIF ] = "ELIF" ,
4071 [RES_ELSE ] = "ELSE" ,
4074 #if ENABLE_HUSH_LOOPS
4075 [RES_FOR ] = "FOR" ,
4076 [RES_WHILE] = "WHILE",
4077 [RES_UNTIL] = "UNTIL",
4079 [RES_DONE ] = "DONE" ,
4081 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4084 #if ENABLE_HUSH_CASE
4085 [RES_CASE ] = "CASE" ,
4086 [RES_CASE_IN ] = "CASE_IN" ,
4087 [RES_MATCH] = "MATCH",
4088 [RES_CASE_BODY] = "CASE_BODY",
4089 [RES_ESAC ] = "ESAC" ,
4091 [RES_XXXX ] = "XXXX" ,
4092 [RES_SNTX ] = "SNTX" ,
4094 static const char *const CMDTYPE[] = {
4097 #if ENABLE_HUSH_FUNCTIONS
4106 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4107 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4109 while (prn < pi->num_cmds) {
4110 struct command *command = &pi->cmds[prn];
4111 char **argv = command->argv;
4113 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4115 command->assignment_cnt);
4116 if (command->group) {
4117 fprintf(stderr, " group %s: (argv=%p)\n",
4118 CMDTYPE[command->cmd_type],
4120 debug_print_tree(command->group, lvl+1);
4124 if (argv) while (*argv) {
4125 fprintf(stderr, " '%s'", *argv);
4128 fprintf(stderr, "\n");
4137 /* NB: called by pseudo_exec, and therefore must not modify any
4138 * global data until exec/_exit (we can be a child after vfork!) */
4139 static int run_list(struct pipe *pi)
4141 #if ENABLE_HUSH_CASE
4142 char *case_word = NULL;
4144 #if ENABLE_HUSH_LOOPS
4145 struct pipe *loop_top = NULL;
4146 char **for_lcur = NULL;
4147 char **for_list = NULL;
4149 smallint last_followup;
4151 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4152 smalluint cond_code = 0;
4154 enum { cond_code = 0 };
4157 smallint rword; /* enum reserved_style */
4158 smallint last_rword; /* ditto */
4161 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4164 #if ENABLE_HUSH_LOOPS
4165 /* Check syntax for "for" */
4166 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4167 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4169 /* current word is FOR or IN (BOLD in comments below) */
4170 if (cpipe->next == NULL) {
4171 syntax_error("malformed for");
4173 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4176 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4177 if (cpipe->next->res_word == RES_DO)
4179 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4180 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4181 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4183 syntax_error("malformed for");
4185 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4191 /* Past this point, all code paths should jump to ret: label
4192 * in order to return, no direct "return" statements please.
4193 * This helps to ensure that no memory is leaked. */
4201 last_rword = RES_XXXX;
4203 last_followup = PIPE_SEQ;
4204 rcode = G.last_exitcode;
4206 /* Go through list of pipes, (maybe) executing them. */
4207 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4211 IF_HAS_KEYWORDS(rword = pi->res_word;)
4212 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4213 rword, cond_code, last_rword);
4214 #if ENABLE_HUSH_LOOPS
4215 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4216 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4218 /* start of a loop: remember where loop starts */
4223 /* Still in the same "if...", "then..." or "do..." branch? */
4224 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4225 if ((rcode == 0 && last_followup == PIPE_OR)
4226 || (rcode != 0 && last_followup == PIPE_AND)
4228 /* It is "<true> || CMD" or "<false> && CMD"
4229 * and we should not execute CMD */
4230 debug_printf_exec("skipped cmd because of || or &&\n");
4231 last_followup = pi->followup;
4235 last_followup = pi->followup;
4236 IF_HAS_KEYWORDS(last_rword = rword;)
4239 if (rword == RES_THEN) {
4240 /* if false; then ... fi has exitcode 0! */
4241 G.last_exitcode = rcode = EXIT_SUCCESS;
4242 /* "if <false> THEN cmd": skip cmd */
4246 if (rword == RES_ELSE || rword == RES_ELIF) {
4247 /* "if <true> then ... ELSE/ELIF cmd":
4248 * skip cmd and all following ones */
4253 #if ENABLE_HUSH_LOOPS
4254 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4256 /* first loop through for */
4258 static const char encoded_dollar_at[] ALIGN1 = {
4259 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4260 }; /* encoded representation of "$@" */
4261 static const char *const encoded_dollar_at_argv[] = {
4262 encoded_dollar_at, NULL
4263 }; /* argv list with one element: "$@" */
4266 vals = (char**)encoded_dollar_at_argv;
4267 if (pi->next->res_word == RES_IN) {
4268 /* if no variable values after "in" we skip "for" */
4269 if (!pi->next->cmds[0].argv) {
4270 G.last_exitcode = rcode = EXIT_SUCCESS;
4271 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4274 vals = pi->next->cmds[0].argv;
4275 } /* else: "for var; do..." -> assume "$@" list */
4276 /* create list of variable values */
4277 debug_print_strings("for_list made from", vals);
4278 for_list = expand_strvec_to_strvec(vals);
4279 for_lcur = for_list;
4280 debug_print_strings("for_list", for_list);
4283 /* "for" loop is over, clean up */
4289 /* Insert next value from for_lcur */
4290 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4291 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4294 if (rword == RES_IN) {
4295 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4297 if (rword == RES_DONE) {
4298 continue; /* "done" has no cmds too */
4301 #if ENABLE_HUSH_CASE
4302 if (rword == RES_CASE) {
4303 case_word = expand_strvec_to_string(pi->cmds->argv);
4306 if (rword == RES_MATCH) {
4309 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4311 /* all prev words didn't match, does this one match? */
4312 argv = pi->cmds->argv;
4314 char *pattern = expand_string_to_string(*argv);
4315 /* TODO: which FNM_xxx flags to use? */
4316 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4318 if (cond_code == 0) { /* match! we will execute this branch */
4319 free(case_word); /* make future "word)" stop */
4327 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4329 continue; /* not matched yet, skip this pipe */
4332 /* Just pressing <enter> in shell should check for jobs.
4333 * OTOH, in non-interactive shell this is useless
4334 * and only leads to extra job checks */
4335 if (pi->num_cmds == 0) {
4336 if (G_interactive_fd)
4337 goto check_jobs_and_continue;
4341 /* After analyzing all keywords and conditions, we decided
4342 * to execute this pipe. NB: have to do checkjobs(NULL)
4343 * after run_pipe to collect any background children,
4344 * even if list execution is to be stopped. */
4345 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4348 #if ENABLE_HUSH_LOOPS
4349 G.flag_break_continue = 0;
4351 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4353 /* We ran a builtin, function, or group.
4354 * rcode is already known
4355 * and we don't need to wait for anything. */
4356 G.last_exitcode = rcode;
4357 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4358 check_and_run_traps(0);
4359 #if ENABLE_HUSH_LOOPS
4360 /* Was it "break" or "continue"? */
4361 if (G.flag_break_continue) {
4362 smallint fbc = G.flag_break_continue;
4363 /* We might fall into outer *loop*,
4364 * don't want to break it too */
4366 G.depth_break_continue--;
4367 if (G.depth_break_continue == 0)
4368 G.flag_break_continue = 0;
4369 /* else: e.g. "continue 2" should *break* once, *then* continue */
4370 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4371 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4372 goto check_jobs_and_break;
4373 /* "continue": simulate end of loop */
4378 #if ENABLE_HUSH_FUNCTIONS
4379 if (G.flag_return_in_progress == 1) {
4380 /* same as "goto check_jobs_and_break" */
4385 } else if (pi->followup == PIPE_BG) {
4386 /* What does bash do with attempts to background builtins? */
4387 /* even bash 3.2 doesn't do that well with nested bg:
4388 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4389 * I'm NOT treating inner &'s as jobs */
4390 check_and_run_traps(0);
4392 if (G.run_list_level == 1)
4395 G.last_exitcode = rcode = EXIT_SUCCESS;
4396 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4399 if (G.run_list_level == 1 && G_interactive_fd) {
4400 /* Waits for completion, then fg's main shell */
4401 rcode = checkjobs_and_fg_shell(pi);
4402 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4403 check_and_run_traps(0);
4406 { /* This one just waits for completion */
4407 rcode = checkjobs(pi);
4408 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4409 check_and_run_traps(0);
4411 G.last_exitcode = rcode;
4415 /* Analyze how result affects subsequent commands */
4417 if (rword == RES_IF || rword == RES_ELIF)
4420 #if ENABLE_HUSH_LOOPS
4421 /* Beware of "while false; true; do ..."! */
4422 if (pi->next && pi->next->res_word == RES_DO) {
4423 if (rword == RES_WHILE) {
4425 /* "while false; do...done" - exitcode 0 */
4426 G.last_exitcode = rcode = EXIT_SUCCESS;
4427 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4428 goto check_jobs_and_break;
4431 if (rword == RES_UNTIL) {
4433 debug_printf_exec(": until expr is true: breaking\n");
4434 check_jobs_and_break:
4442 check_jobs_and_continue:
4449 #if ENABLE_HUSH_LOOPS
4454 #if ENABLE_HUSH_CASE
4458 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4462 /* Select which version we will use */
4463 static int run_and_free_list(struct pipe *pi)
4466 debug_printf_exec("run_and_free_list entered\n");
4468 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4469 rcode = run_list(pi);
4471 /* free_pipe_list has the side effect of clearing memory.
4472 * In the long run that function can be merged with run_list,
4473 * but doing that now would hobble the debugging effort. */
4475 debug_printf_exec("run_and_free_list return %d\n", rcode);
4480 static struct pipe *new_pipe(void)
4483 pi = xzalloc(sizeof(struct pipe));
4484 /*pi->followup = 0; - deliberately invalid value */
4485 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4489 /* Command (member of a pipe) is complete, or we start a new pipe
4490 * if ctx->command is NULL.
4491 * No errors possible here.
4493 static int done_command(struct parse_context *ctx)
4495 /* The command is really already in the pipe structure, so
4496 * advance the pipe counter and make a new, null command. */
4497 struct pipe *pi = ctx->pipe;
4498 struct command *command = ctx->command;
4501 if (IS_NULL_CMD(command)) {
4502 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4506 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4507 //debug_print_tree(ctx->list_head, 20);
4509 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4512 /* Only real trickiness here is that the uncommitted
4513 * command structure is not counted in pi->num_cmds. */
4514 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4515 ctx->command = command = &pi->cmds[pi->num_cmds];
4517 memset(command, 0, sizeof(*command));
4518 return pi->num_cmds; /* used only for 0/nonzero check */
4521 static void done_pipe(struct parse_context *ctx, pipe_style type)
4525 debug_printf_parse("done_pipe entered, followup %d\n", type);
4526 /* Close previous command */
4527 not_null = done_command(ctx);
4528 ctx->pipe->followup = type;
4530 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4531 ctx->ctx_inverted = 0;
4532 ctx->pipe->res_word = ctx->ctx_res_w;
4535 /* Without this check, even just <enter> on command line generates
4536 * tree of three NOPs (!). Which is harmless but annoying.
4537 * IOW: it is safe to do it unconditionally. */
4540 || ctx->ctx_res_w == RES_FI
4542 #if ENABLE_HUSH_LOOPS
4543 || ctx->ctx_res_w == RES_DONE
4544 || ctx->ctx_res_w == RES_FOR
4545 || ctx->ctx_res_w == RES_IN
4547 #if ENABLE_HUSH_CASE
4548 || ctx->ctx_res_w == RES_ESAC
4552 debug_printf_parse("done_pipe: adding new pipe: "
4553 "not_null:%d ctx->ctx_res_w:%d\n",
4554 not_null, ctx->ctx_res_w);
4556 ctx->pipe->next = new_p;
4558 /* RES_THEN, RES_DO etc are "sticky" -
4559 * they remain set for pipes inside if/while.
4560 * This is used to control execution.
4561 * RES_FOR and RES_IN are NOT sticky (needed to support
4562 * cases where variable or value happens to match a keyword):
4564 #if ENABLE_HUSH_LOOPS
4565 if (ctx->ctx_res_w == RES_FOR
4566 || ctx->ctx_res_w == RES_IN)
4567 ctx->ctx_res_w = RES_NONE;
4569 #if ENABLE_HUSH_CASE
4570 if (ctx->ctx_res_w == RES_MATCH)
4571 ctx->ctx_res_w = RES_CASE_BODY;
4572 if (ctx->ctx_res_w == RES_CASE)
4573 ctx->ctx_res_w = RES_CASE_IN;
4575 ctx->command = NULL; /* trick done_command below */
4576 /* Create the memory for command, roughly:
4577 * ctx->pipe->cmds = new struct command;
4578 * ctx->command = &ctx->pipe->cmds[0];
4581 //debug_print_tree(ctx->list_head, 10);
4583 debug_printf_parse("done_pipe return\n");
4586 static void initialize_context(struct parse_context *ctx)
4588 memset(ctx, 0, sizeof(*ctx));
4589 ctx->pipe = ctx->list_head = new_pipe();
4590 /* Create the memory for command, roughly:
4591 * ctx->pipe->cmds = new struct command;
4592 * ctx->command = &ctx->pipe->cmds[0];
4597 /* If a reserved word is found and processed, parse context is modified
4598 * and 1 is returned.
4601 struct reserved_combo {
4604 unsigned char assignment_flag;
4608 FLAG_END = (1 << RES_NONE ),
4610 FLAG_IF = (1 << RES_IF ),
4611 FLAG_THEN = (1 << RES_THEN ),
4612 FLAG_ELIF = (1 << RES_ELIF ),
4613 FLAG_ELSE = (1 << RES_ELSE ),
4614 FLAG_FI = (1 << RES_FI ),
4616 #if ENABLE_HUSH_LOOPS
4617 FLAG_FOR = (1 << RES_FOR ),
4618 FLAG_WHILE = (1 << RES_WHILE),
4619 FLAG_UNTIL = (1 << RES_UNTIL),
4620 FLAG_DO = (1 << RES_DO ),
4621 FLAG_DONE = (1 << RES_DONE ),
4622 FLAG_IN = (1 << RES_IN ),
4624 #if ENABLE_HUSH_CASE
4625 FLAG_MATCH = (1 << RES_MATCH),
4626 FLAG_ESAC = (1 << RES_ESAC ),
4628 FLAG_START = (1 << RES_XXXX ),
4631 static const struct reserved_combo* match_reserved_word(o_string *word)
4633 /* Mostly a list of accepted follow-up reserved words.
4634 * FLAG_END means we are done with the sequence, and are ready
4635 * to turn the compound list into a command.
4636 * FLAG_START means the word must start a new compound list.
4638 static const struct reserved_combo reserved_list[] = {
4640 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4641 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4642 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4643 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4644 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4645 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4647 #if ENABLE_HUSH_LOOPS
4648 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4649 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4650 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4651 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4652 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4653 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4655 #if ENABLE_HUSH_CASE
4656 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4657 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4660 const struct reserved_combo *r;
4662 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4663 if (strcmp(word->data, r->literal) == 0)
4668 /* Return 0: not a keyword, 1: keyword
4670 static int reserved_word(o_string *word, struct parse_context *ctx)
4672 #if ENABLE_HUSH_CASE
4673 static const struct reserved_combo reserved_match = {
4674 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4677 const struct reserved_combo *r;
4681 r = match_reserved_word(word);
4685 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4686 #if ENABLE_HUSH_CASE
4687 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4688 /* "case word IN ..." - IN part starts first MATCH part */
4689 r = &reserved_match;
4692 if (r->flag == 0) { /* '!' */
4693 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4694 syntax_error("! ! command");
4695 ctx->ctx_res_w = RES_SNTX;
4697 ctx->ctx_inverted = 1;
4700 if (r->flag & FLAG_START) {
4701 struct parse_context *old;
4703 old = xmalloc(sizeof(*old));
4704 debug_printf_parse("push stack %p\n", old);
4705 *old = *ctx; /* physical copy */
4706 initialize_context(ctx);
4708 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4709 syntax_error_at(word->data);
4710 ctx->ctx_res_w = RES_SNTX;
4713 /* "{...} fi" is ok. "{...} if" is not
4715 * if { echo foo; } then { echo bar; } fi */
4716 if (ctx->command->group)
4717 done_pipe(ctx, PIPE_SEQ);
4720 ctx->ctx_res_w = r->res;
4721 ctx->old_flag = r->flag;
4722 word->o_assignment = r->assignment_flag;
4724 if (ctx->old_flag & FLAG_END) {
4725 struct parse_context *old;
4727 done_pipe(ctx, PIPE_SEQ);
4728 debug_printf_parse("pop stack %p\n", ctx->stack);
4730 old->command->group = ctx->list_head;
4731 old->command->cmd_type = CMD_NORMAL;
4733 o_addstr(&old->as_string, ctx->as_string.data);
4734 o_free_unsafe(&ctx->as_string);
4735 old->command->group_as_string = xstrdup(old->as_string.data);
4736 debug_printf_parse("pop, remembering as:'%s'\n",
4737 old->command->group_as_string);
4739 *ctx = *old; /* physical copy */
4746 /* Word is complete, look at it and update parsing context.
4747 * Normal return is 0. Syntax errors return 1.
4748 * Note: on return, word is reset, but not o_free'd!
4750 static int done_word(o_string *word, struct parse_context *ctx)
4752 struct command *command = ctx->command;
4754 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4755 if (word->length == 0 && word->o_quoted == 0) {
4756 debug_printf_parse("done_word return 0: true null, ignored\n");
4760 if (ctx->pending_redirect) {
4761 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4762 * only if run as "bash", not "sh" */
4763 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4765 * ...the word that follows the redirection operator
4766 * shall be subjected to tilde expansion, parameter expansion,
4767 * command substitution, arithmetic expansion, and quote
4768 * removal. Pathname expansion shall not be performed
4769 * on the word by a non-interactive shell; an interactive
4770 * shell may perform it, but shall do so only when
4771 * the expansion would result in one word."
4773 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4774 /* Cater for >\file case:
4775 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4776 * Same with heredocs:
4777 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4779 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4780 unbackslash(ctx->pending_redirect->rd_filename);
4781 /* Is it <<"HEREDOC"? */
4782 if (word->o_quoted) {
4783 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4786 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4787 ctx->pending_redirect = NULL;
4789 /* If this word wasn't an assignment, next ones definitely
4790 * can't be assignments. Even if they look like ones. */
4791 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4792 && word->o_assignment != WORD_IS_KEYWORD
4794 word->o_assignment = NOT_ASSIGNMENT;
4796 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4797 command->assignment_cnt++;
4798 word->o_assignment = MAYBE_ASSIGNMENT;
4802 # if ENABLE_HUSH_CASE
4803 if (ctx->ctx_dsemicolon
4804 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4806 /* already done when ctx_dsemicolon was set to 1: */
4807 /* ctx->ctx_res_w = RES_MATCH; */
4808 ctx->ctx_dsemicolon = 0;
4811 if (!command->argv /* if it's the first word... */
4812 # if ENABLE_HUSH_LOOPS
4813 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4814 && ctx->ctx_res_w != RES_IN
4816 # if ENABLE_HUSH_CASE
4817 && ctx->ctx_res_w != RES_CASE
4820 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4821 if (reserved_word(word, ctx)) {
4822 o_reset_to_empty_unquoted(word);
4823 debug_printf_parse("done_word return %d\n",
4824 (ctx->ctx_res_w == RES_SNTX));
4825 return (ctx->ctx_res_w == RES_SNTX);
4827 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4828 if (strcmp(word->data, "export") == 0
4829 # if ENABLE_HUSH_LOCAL
4830 || strcmp(word->data, "local") == 0
4833 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4836 if (strcmp(word->data, "[[") == 0) {
4837 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4842 if (command->group) {
4843 /* "{ echo foo; } echo bar" - bad */
4844 syntax_error_at(word->data);
4845 debug_printf_parse("done_word return 1: syntax error, "
4846 "groups and arglists don't mix\n");
4849 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4850 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4851 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4852 /* (otherwise it's known to be not empty and is already safe) */
4854 /* exclude "$@" - it can expand to no word despite "" */
4855 char *p = word->data;
4856 while (p[0] == SPECIAL_VAR_SYMBOL
4857 && (p[1] & 0x7f) == '@'
4858 && p[2] == SPECIAL_VAR_SYMBOL
4862 if (p == word->data || p[0] != '\0') {
4863 /* saw no "$@", or not only "$@" but some
4864 * real text is there too */
4865 /* insert "empty variable" reference, this makes
4866 * e.g. "", $empty"" etc to not disappear */
4867 o_addchr(word, SPECIAL_VAR_SYMBOL);
4868 o_addchr(word, SPECIAL_VAR_SYMBOL);
4871 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4872 debug_print_strings("word appended to argv", command->argv);
4875 #if ENABLE_HUSH_LOOPS
4876 if (ctx->ctx_res_w == RES_FOR) {
4878 || !is_well_formed_var_name(command->argv[0], '\0')
4880 /* bash says just "not a valid identifier" */
4881 syntax_error("not a valid identifier in for");
4884 /* Force FOR to have just one word (variable name) */
4885 /* NB: basically, this makes hush see "for v in ..."
4886 * syntax as if it is "for v; in ...". FOR and IN become
4887 * two pipe structs in parse tree. */
4888 done_pipe(ctx, PIPE_SEQ);
4891 #if ENABLE_HUSH_CASE
4892 /* Force CASE to have just one word */
4893 if (ctx->ctx_res_w == RES_CASE) {
4894 done_pipe(ctx, PIPE_SEQ);
4898 o_reset_to_empty_unquoted(word);
4900 debug_printf_parse("done_word return 0\n");
4905 /* Peek ahead in the input to find out if we have a "&n" construct,
4906 * as in "2>&1", that represents duplicating a file descriptor.
4908 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4909 * REDIRFD_SYNTAX_ERR if syntax error,
4910 * REDIRFD_TO_FILE if no & was seen,
4911 * or the number found.
4914 #define parse_redir_right_fd(as_string, input) \
4915 parse_redir_right_fd(input)
4917 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4923 return REDIRFD_TO_FILE;
4925 ch = i_getch(input); /* get the & */
4926 nommu_addchr(as_string, ch);
4929 ch = i_getch(input);
4930 nommu_addchr(as_string, ch);
4931 return REDIRFD_CLOSE;
4935 while (ch != EOF && isdigit(ch)) {
4936 d = d*10 + (ch-'0');
4938 ch = i_getch(input);
4939 nommu_addchr(as_string, ch);
4944 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4946 bb_error_msg("ambiguous redirect");
4947 return REDIRFD_SYNTAX_ERR;
4950 /* Return code is 0 normal, 1 if a syntax error is detected
4952 static int parse_redirect(struct parse_context *ctx,
4955 struct in_str *input)
4957 struct command *command = ctx->command;
4958 struct redir_struct *redir;
4959 struct redir_struct **redirp;
4962 dup_num = REDIRFD_TO_FILE;
4963 if (style != REDIRECT_HEREDOC) {
4964 /* Check for a '>&1' type redirect */
4965 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4966 if (dup_num == REDIRFD_SYNTAX_ERR)
4969 int ch = i_peek(input);
4970 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4971 if (dup_num) { /* <<-... */
4972 ch = i_getch(input);
4973 nommu_addchr(&ctx->as_string, ch);
4978 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4979 int ch = i_peek(input);
4981 /* >|FILE redirect ("clobbering" >).
4982 * Since we do not support "set -o noclobber" yet,
4983 * >| and > are the same for now. Just eat |.
4985 ch = i_getch(input);
4986 nommu_addchr(&ctx->as_string, ch);
4990 /* Create a new redir_struct and append it to the linked list */
4991 redirp = &command->redirects;
4992 while ((redir = *redirp) != NULL) {
4993 redirp = &(redir->next);
4995 *redirp = redir = xzalloc(sizeof(*redir));
4996 /* redir->next = NULL; */
4997 /* redir->rd_filename = NULL; */
4998 redir->rd_type = style;
4999 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5001 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5002 redir_table[style].descrip);
5004 redir->rd_dup = dup_num;
5005 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5006 /* Erik had a check here that the file descriptor in question
5007 * is legit; I postpone that to "run time"
5008 * A "-" representation of "close me" shows up as a -3 here */
5009 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5010 redir->rd_fd, redir->rd_dup);
5012 /* Set ctx->pending_redirect, so we know what to do at the
5013 * end of the next parsed word. */
5014 ctx->pending_redirect = redir;
5019 /* If a redirect is immediately preceded by a number, that number is
5020 * supposed to tell which file descriptor to redirect. This routine
5021 * looks for such preceding numbers. In an ideal world this routine
5022 * needs to handle all the following classes of redirects...
5023 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5024 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5025 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5026 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5028 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5030 * ... If n is quoted, the number shall not be recognized as part of
5031 * the redirection expression. For example:
5033 * writes the character 2 into file a"
5034 * We are getting it right by setting ->o_quoted on any \<char>
5036 * A -1 return means no valid number was found,
5037 * the caller should use the appropriate default for this redirection.
5039 static int redirect_opt_num(o_string *o)
5043 if (o->data == NULL)
5045 num = bb_strtou(o->data, NULL, 10);
5046 if (errno || num < 0)
5048 o_reset_to_empty_unquoted(o);
5053 #define fetch_till_str(as_string, input, word, skip_tabs) \
5054 fetch_till_str(input, word, skip_tabs)
5056 static char *fetch_till_str(o_string *as_string,
5057 struct in_str *input,
5061 o_string heredoc = NULL_O_STRING;
5067 ch = i_getch(input);
5068 nommu_addchr(as_string, ch);
5070 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5071 heredoc.data[past_EOL] = '\0';
5072 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5073 return heredoc.data;
5076 o_addchr(&heredoc, ch);
5077 past_EOL = heredoc.length;
5080 ch = i_getch(input);
5081 nommu_addchr(as_string, ch);
5082 } while (skip_tabs && ch == '\t');
5083 } while (ch == '\n');
5086 o_free_unsafe(&heredoc);
5089 o_addchr(&heredoc, ch);
5090 nommu_addchr(as_string, ch);
5094 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5095 * and load them all. There should be exactly heredoc_cnt of them.
5097 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5099 struct pipe *pi = ctx->list_head;
5101 while (pi && heredoc_cnt) {
5103 struct command *cmd = pi->cmds;
5105 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5107 cmd->argv ? cmd->argv[0] : "NONE");
5108 for (i = 0; i < pi->num_cmds; i++) {
5109 struct redir_struct *redir = cmd->redirects;
5111 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5112 i, cmd->argv ? cmd->argv[0] : "NONE");
5114 if (redir->rd_type == REDIRECT_HEREDOC) {
5117 redir->rd_type = REDIRECT_HEREDOC2;
5118 /* redir->rd_dup is (ab)used to indicate <<- */
5119 p = fetch_till_str(&ctx->as_string, input,
5120 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5122 syntax_error("unexpected EOF in here document");
5125 free(redir->rd_filename);
5126 redir->rd_filename = p;
5129 redir = redir->next;
5136 /* Should be 0. If it isn't, it's a parse error */
5138 bb_error_msg_and_die("heredoc BUG 2");
5144 #if ENABLE_HUSH_TICK
5145 static FILE *generate_stream_from_string(const char *s)
5148 int pid, channel[2];
5154 pid = BB_MMU ? fork() : vfork();
5156 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5158 if (pid == 0) { /* child */
5159 disable_restore_tty_pgrp_on_exit();
5160 /* Process substitution is not considered to be usual
5161 * 'command execution'.
5162 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5169 close(channel[0]); /* NB: close _first_, then move fd! */
5170 xmove_fd(channel[1], 1);
5171 /* Prevent it from trying to handle ctrl-z etc */
5172 IF_HUSH_JOB(G.run_list_level = 1;)
5174 reset_traps_to_defaults();
5175 parse_and_run_string(s);
5176 _exit(G.last_exitcode);
5178 /* We re-execute after vfork on NOMMU. This makes this script safe:
5179 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5180 * huge=`cat BIG` # was blocking here forever
5183 re_execute_shell(&to_free,
5192 #if ENABLE_HUSH_FAST
5194 //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);
5196 enable_restore_tty_pgrp_on_exit();
5201 pf = fdopen(channel[0], "r");
5205 /* Return code is exit status of the process that is run. */
5206 static int process_command_subs(o_string *dest, const char *s)
5209 struct in_str pipe_str;
5212 pf = generate_stream_from_string(s);
5215 close_on_exec_on(fileno(pf));
5217 /* Now send results of command back into original context */
5218 setup_file_in_str(&pipe_str, pf);
5220 while ((ch = i_getch(&pipe_str)) != EOF) {
5226 o_addchr(dest, '\n');
5229 o_addQchr(dest, ch);
5232 debug_printf("done reading from pipe, pclose()ing\n");
5233 /* Note: we got EOF, and we just close the read end of the pipe.
5234 * We do not wait for the `cmd` child to terminate. bash and ash do.
5236 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5237 * `false`; echo $? - bash outputs "1"
5240 debug_printf("closed FILE from child. return 0\n");
5245 static int parse_group(o_string *dest, struct parse_context *ctx,
5246 struct in_str *input, int ch)
5248 /* dest contains characters seen prior to ( or {.
5249 * Typically it's empty, but for function defs,
5250 * it contains function name (without '()'). */
5251 struct pipe *pipe_list;
5253 struct command *command = ctx->command;
5255 debug_printf_parse("parse_group entered\n");
5256 #if ENABLE_HUSH_FUNCTIONS
5257 if (ch == '(' && !dest->o_quoted) {
5259 if (done_word(dest, ctx))
5262 goto skip; /* (... */
5263 if (command->argv[1]) { /* word word ... (... */
5264 syntax_error_unexpected_ch('(');
5267 /* it is "word(..." or "word (..." */
5269 ch = i_getch(input);
5270 while (ch == ' ' || ch == '\t');
5272 syntax_error_unexpected_ch(ch);
5275 nommu_addchr(&ctx->as_string, ch);
5277 ch = i_getch(input);
5278 while (ch == ' ' || ch == '\t' || ch == '\n');
5280 syntax_error_unexpected_ch(ch);
5283 nommu_addchr(&ctx->as_string, ch);
5284 command->cmd_type = CMD_FUNCDEF;
5288 if (command->argv /* word [word]{... */
5289 || dest->length /* word{... */
5290 || dest->o_quoted /* ""{... */
5293 debug_printf_parse("parse_group return 1: "
5294 "syntax error, groups and arglists don't mix\n");
5298 #if ENABLE_HUSH_FUNCTIONS
5304 command->cmd_type = CMD_SUBSHELL;
5306 /* bash does not allow "{echo...", requires whitespace */
5307 ch = i_getch(input);
5308 if (ch != ' ' && ch != '\t' && ch != '\n') {
5309 syntax_error_unexpected_ch(ch);
5312 nommu_addchr(&ctx->as_string, ch);
5317 char *as_string = NULL;
5319 pipe_list = parse_stream(&as_string, input, endch);
5322 o_addstr(&ctx->as_string, as_string);
5324 /* empty ()/{} or parse error? */
5325 if (!pipe_list || pipe_list == ERR_PTR) {
5326 /* parse_stream already emitted error msg */
5330 debug_printf_parse("parse_group return 1: "
5331 "parse_stream returned %p\n", pipe_list);
5334 command->group = pipe_list;
5336 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5337 command->group_as_string = as_string;
5338 debug_printf_parse("end of group, remembering as:'%s'\n",
5339 command->group_as_string);
5342 debug_printf_parse("parse_group return 0\n");
5344 /* command remains "open", available for possible redirects */
5347 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5348 /* Subroutines for copying $(...) and `...` things */
5349 static void add_till_backquote(o_string *dest, struct in_str *input);
5351 static void add_till_single_quote(o_string *dest, struct in_str *input)
5354 int ch = i_getch(input);
5356 syntax_error_unterm_ch('\'');
5357 /*xfunc_die(); - redundant */
5364 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5365 static void add_till_double_quote(o_string *dest, struct in_str *input)
5368 int ch = i_getch(input);
5370 syntax_error_unterm_ch('"');
5371 /*xfunc_die(); - redundant */
5375 if (ch == '\\') { /* \x. Copy both chars. */
5377 ch = i_getch(input);
5381 add_till_backquote(dest, input);
5385 //if (ch == '$') ...
5388 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5390 * "Within the backquoted style of command substitution, backslash
5391 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5392 * The search for the matching backquote shall be satisfied by the first
5393 * backquote found without a preceding backslash; during this search,
5394 * if a non-escaped backquote is encountered within a shell comment,
5395 * a here-document, an embedded command substitution of the $(command)
5396 * form, or a quoted string, undefined results occur. A single-quoted
5397 * or double-quoted string that begins, but does not end, within the
5398 * "`...`" sequence produces undefined results."
5400 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5402 static void add_till_backquote(o_string *dest, struct in_str *input)
5405 int ch = i_getch(input);
5407 syntax_error_unterm_ch('`');
5408 /*xfunc_die(); - redundant */
5413 /* \x. Copy both chars unless it is \` */
5414 int ch2 = i_getch(input);
5416 syntax_error_unterm_ch('`');
5417 /*xfunc_die(); - redundant */
5419 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5426 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5427 * quoting and nested ()s.
5428 * "With the $(command) style of command substitution, all characters
5429 * following the open parenthesis to the matching closing parenthesis
5430 * constitute the command. Any valid shell script can be used for command,
5431 * except a script consisting solely of redirections which produces
5432 * unspecified results."
5434 * echo $(echo '(TEST)' BEST) (TEST) BEST
5435 * echo $(echo 'TEST)' BEST) TEST) BEST
5436 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5438 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5442 int ch = i_getch(input);
5444 syntax_error_unterm_ch(')');
5445 /*xfunc_die(); - redundant */
5453 if (i_peek(input) == ')') {
5461 add_till_single_quote(dest, input);
5466 add_till_double_quote(dest, input);
5471 /* \x. Copy verbatim. Important for \(, \) */
5472 ch = i_getch(input);
5474 syntax_error_unterm_ch(')');
5475 /*xfunc_die(); - redundant */
5482 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5484 /* Return code: 0 for OK, 1 for syntax error */
5486 #define handle_dollar(as_string, dest, input) \
5487 handle_dollar(dest, input)
5489 static int handle_dollar(o_string *as_string,
5491 struct in_str *input)
5493 int ch = i_peek(input); /* first character after the $ */
5494 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5496 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5498 ch = i_getch(input);
5499 nommu_addchr(as_string, ch);
5501 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5503 debug_printf_parse(": '%c'\n", ch);
5504 o_addchr(dest, ch | quote_mask);
5507 if (!isalnum(ch) && ch != '_')
5509 ch = i_getch(input);
5510 nommu_addchr(as_string, ch);
5512 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5513 } else if (isdigit(ch)) {
5515 ch = i_getch(input);
5516 nommu_addchr(as_string, ch);
5517 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5518 debug_printf_parse(": '%c'\n", ch);
5519 o_addchr(dest, ch | quote_mask);
5520 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5521 } else switch (ch) {
5523 case '!': /* last bg pid */
5524 case '?': /* last exit code */
5525 case '#': /* number of args */
5526 case '*': /* args */
5527 case '@': /* args */
5528 goto make_one_char_var;
5530 bool first_char, all_digits;
5533 ch = i_getch(input);
5534 nommu_addchr(as_string, ch);
5535 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5537 /* TODO: maybe someone will try to escape the '}' */
5542 ch = i_getch(input);
5543 nommu_addchr(as_string, ch);
5550 /* ${#var}: length of var contents */
5557 /* They're being verbose and doing ${?} */
5558 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5563 && ( (all_digits && !isdigit(ch))
5564 || (!all_digits && !isalnum(ch) && ch != '_')
5567 /* handle parameter expansions
5568 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5573 case ':': /* null modifier */
5574 if (expansion == 0) {
5575 debug_printf_parse(": null modifier\n");
5580 case '#': /* remove prefix */
5581 case '%': /* remove suffix */
5582 if (expansion == 0) {
5583 debug_printf_parse(": remove suffix/prefix\n");
5588 case '-': /* default value */
5589 case '=': /* assign default */
5590 case '+': /* alternative */
5591 case '?': /* error indicate */
5592 debug_printf_parse(": parameter expansion\n");
5597 syntax_error_unterm_str("${name}");
5598 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5603 debug_printf_parse(": '%c'\n", ch);
5604 o_addchr(dest, ch | quote_mask);
5608 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5611 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5616 ch = i_getch(input);
5617 nommu_addchr(as_string, ch);
5618 # if ENABLE_SH_MATH_SUPPORT
5619 if (i_peek(input) == '(') {
5620 ch = i_getch(input);
5621 nommu_addchr(as_string, ch);
5622 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5623 o_addchr(dest, /*quote_mask |*/ '+');
5627 add_till_closing_paren(dest, input, true);
5630 o_addstr(as_string, dest->data + pos);
5631 o_addchr(as_string, ')');
5632 o_addchr(as_string, ')');
5635 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5639 # if ENABLE_HUSH_TICK
5640 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5641 o_addchr(dest, quote_mask | '`');
5645 add_till_closing_paren(dest, input, false);
5648 o_addstr(as_string, dest->data + pos);
5649 o_addchr(as_string, '`');
5652 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5658 ch = i_getch(input);
5659 nommu_addchr(as_string, ch);
5661 if (isalnum(ch)) { /* it's $_name or $_123 */
5667 /* $_ Shell or shell script name; or last cmd name */
5668 /* $- Option flags set by set builtin or shell options (-i etc) */
5670 o_addQchr(dest, '$');
5672 debug_printf_parse("handle_dollar return 0\n");
5677 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5678 parse_stream_dquoted(dest, input, dquote_end)
5680 static int parse_stream_dquoted(o_string *as_string,
5682 struct in_str *input,
5689 ch = i_getch(input);
5691 nommu_addchr(as_string, ch);
5692 if (ch == dquote_end) { /* may be only '"' or EOF */
5693 if (dest->o_assignment == NOT_ASSIGNMENT)
5694 dest->o_escape ^= 1;
5695 debug_printf_parse("parse_stream_dquoted return 0\n");
5698 /* note: can't move it above ch == dquote_end check! */
5700 syntax_error_unterm_ch('"');
5701 /*xfunc_die(); - redundant */
5705 next = i_peek(input);
5707 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5708 ch, ch, dest->o_escape);
5711 syntax_error("\\<eof>");
5715 * "The backslash retains its special meaning [in "..."]
5716 * only when followed by one of the following characters:
5717 * $, `, ", \, or <newline>. A double quote may be quoted
5718 * within double quotes by preceding it with a backslash."
5720 if (strchr("$`\"\\\n", next) != NULL) {
5721 ch = i_getch(input);
5723 o_addqchr(dest, ch);
5724 nommu_addchr(as_string, ch);
5727 o_addqchr(dest, '\\');
5728 nommu_addchr(as_string, '\\');
5733 if (handle_dollar(as_string, dest, input) != 0) {
5734 debug_printf_parse("parse_stream_dquoted return 1: "
5735 "handle_dollar returned non-0\n");
5740 #if ENABLE_HUSH_TICK
5742 //int pos = dest->length;
5743 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5744 o_addchr(dest, 0x80 | '`');
5745 add_till_backquote(dest, input);
5746 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5747 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5751 o_addQchr(dest, ch);
5753 && (dest->o_assignment == MAYBE_ASSIGNMENT
5754 || dest->o_assignment == WORD_IS_KEYWORD)
5755 && is_well_formed_var_name(dest->data, '=')
5757 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5763 * Scan input until EOF or end_trigger char.
5764 * Return a list of pipes to execute, or NULL on EOF
5765 * or if end_trigger character is met.
5766 * On syntax error, exit is shell is not interactive,
5767 * reset parsing machinery and start parsing anew,
5768 * or return ERR_PTR.
5770 static struct pipe *parse_stream(char **pstring,
5771 struct in_str *input,
5774 struct parse_context ctx;
5775 o_string dest = NULL_O_STRING;
5779 /* Double-quote state is handled in the state variable is_in_dquote.
5780 * A single-quote triggers a bypass of the main loop until its mate is
5781 * found. When recursing, quote state is passed in via dest->o_escape.
5783 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5784 end_trigger ? : 'X');
5787 G.ifs = get_local_var_value("IFS");
5792 #if ENABLE_HUSH_INTERACTIVE
5793 input->promptmode = 0; /* PS1 */
5795 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5796 initialize_context(&ctx);
5801 const char *is_special;
5805 redir_type redir_style;
5808 /* dest.o_quoted = 1; - already is (see below) */
5809 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5812 /* We reached closing '"' */
5815 ch = i_getch(input);
5816 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5817 ch, ch, dest.o_escape);
5822 syntax_error_unterm_str("here document");
5825 /* end_trigger == '}' case errors out earlier,
5826 * checking only ')' */
5827 if (end_trigger == ')') {
5828 syntax_error_unterm_ch('('); /* exits */
5829 /* goto parse_error; */
5832 if (done_word(&dest, &ctx)) {
5836 done_pipe(&ctx, PIPE_SEQ);
5838 /* If we got nothing... */
5839 /* (this makes bare "&" cmd a no-op.
5840 * bash says: "syntax error near unexpected token '&'") */
5841 if (pi->num_cmds == 0
5842 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5848 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5850 *pstring = ctx.as_string.data;
5852 o_free_unsafe(&ctx.as_string);
5855 debug_printf_parse("parse_stream return %p\n", pi);
5858 nommu_addchr(&ctx.as_string, ch);
5859 is_ifs = strchr(G.ifs, ch);
5860 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5861 "\\$\"" IF_HUSH_TICK("`") /* always special */
5864 if (!is_special && !is_ifs) { /* ordinary char */
5866 o_addQchr(&dest, ch);
5867 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5868 || dest.o_assignment == WORD_IS_KEYWORD)
5870 && is_well_formed_var_name(dest.data, '=')
5872 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5878 if (done_word(&dest, &ctx)) {
5882 #if ENABLE_HUSH_CASE
5883 /* "case ... in <newline> word) ..." -
5884 * newlines are ignored (but ';' wouldn't be) */
5885 if (ctx.command->argv == NULL
5886 && ctx.ctx_res_w == RES_MATCH
5891 /* Treat newline as a command separator. */
5892 done_pipe(&ctx, PIPE_SEQ);
5893 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5895 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5900 dest.o_assignment = MAYBE_ASSIGNMENT;
5902 /* note: if (is_ifs) continue;
5903 * will still trigger for us */
5907 /* "cmd}" or "cmd }..." without semicolon or &:
5908 * } is an ordinary char in this case, even inside { cmd; }
5909 * Pathological example: { ""}; } should exec "}" cmd
5912 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5913 || dest.length != 0 /* word} */
5914 || dest.o_quoted /* ""} */
5918 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5919 goto skip_end_trigger;
5920 /* else: } does terminate a group */
5923 if (end_trigger && end_trigger == ch
5924 && (ch != ';' || heredoc_cnt == 0)
5925 #if ENABLE_HUSH_CASE
5927 || ctx.ctx_res_w != RES_MATCH
5928 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5933 /* This is technically valid:
5934 * { cat <<HERE; }; echo Ok
5938 * but we don't support this.
5939 * We require heredoc to be in enclosing {}/(),
5942 syntax_error_unterm_str("here document");
5945 if (done_word(&dest, &ctx)) {
5948 done_pipe(&ctx, PIPE_SEQ);
5949 dest.o_assignment = MAYBE_ASSIGNMENT;
5950 /* Do we sit outside of any if's, loops or case's? */
5952 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5956 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5958 *pstring = ctx.as_string.data;
5960 o_free_unsafe(&ctx.as_string);
5963 debug_printf_parse("parse_stream return %p: "
5964 "end_trigger char found\n",
5966 return ctx.list_head;
5975 next = i_peek(input);
5978 /* Catch <, > before deciding whether this word is
5979 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5982 redir_fd = redirect_opt_num(&dest);
5983 if (done_word(&dest, &ctx)) {
5986 redir_style = REDIRECT_OVERWRITE;
5988 redir_style = REDIRECT_APPEND;
5989 ch = i_getch(input);
5990 nommu_addchr(&ctx.as_string, ch);
5993 else if (next == '(') {
5994 syntax_error(">(process) not supported");
5998 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6000 continue; /* back to top of while (1) */
6002 redir_fd = redirect_opt_num(&dest);
6003 if (done_word(&dest, &ctx)) {
6006 redir_style = REDIRECT_INPUT;
6008 redir_style = REDIRECT_HEREDOC;
6010 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6011 ch = i_getch(input);
6012 nommu_addchr(&ctx.as_string, ch);
6013 } else if (next == '>') {
6014 redir_style = REDIRECT_IO;
6015 ch = i_getch(input);
6016 nommu_addchr(&ctx.as_string, ch);
6019 else if (next == '(') {
6020 syntax_error("<(process) not supported");
6024 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6026 continue; /* back to top of while (1) */
6029 if (dest.o_assignment == MAYBE_ASSIGNMENT
6030 /* check that we are not in word in "a=1 2>word b=1": */
6031 && !ctx.pending_redirect
6033 /* ch is a special char and thus this word
6034 * cannot be an assignment */
6035 dest.o_assignment = NOT_ASSIGNMENT;
6040 if (dest.length == 0) {
6043 if (ch == EOF || ch == '\n')
6046 /* note: we do not add it to &ctx.as_string */
6048 nommu_addchr(&ctx.as_string, '\n');
6050 o_addQchr(&dest, ch);
6055 syntax_error("\\<eof>");
6058 ch = i_getch(input);
6060 o_addchr(&dest, '\\');
6061 nommu_addchr(&ctx.as_string, '\\');
6062 o_addchr(&dest, ch);
6063 nommu_addchr(&ctx.as_string, ch);
6064 /* Example: echo Hello \2>file
6065 * we need to know that word 2 is quoted */
6070 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6071 debug_printf_parse("parse_stream parse error: "
6072 "handle_dollar returned non-0\n");
6079 ch = i_getch(input);
6081 syntax_error_unterm_ch('\'');
6082 /*xfunc_die(); - redundant */
6084 nommu_addchr(&ctx.as_string, ch);
6087 o_addqchr(&dest, ch);
6092 is_in_dquote ^= 1; /* invert */
6093 if (dest.o_assignment == NOT_ASSIGNMENT)
6096 #if ENABLE_HUSH_TICK
6101 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6102 o_addchr(&dest, '`');
6106 add_till_backquote(&dest, input);
6108 o_addstr(&ctx.as_string, dest.data + pos);
6109 o_addchr(&ctx.as_string, '`');
6111 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6112 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6117 #if ENABLE_HUSH_CASE
6120 if (done_word(&dest, &ctx)) {
6123 done_pipe(&ctx, PIPE_SEQ);
6124 #if ENABLE_HUSH_CASE
6125 /* Eat multiple semicolons, detect
6126 * whether it means something special */
6131 ch = i_getch(input);
6132 nommu_addchr(&ctx.as_string, ch);
6133 if (ctx.ctx_res_w == RES_CASE_BODY) {
6134 ctx.ctx_dsemicolon = 1;
6135 ctx.ctx_res_w = RES_MATCH;
6141 /* We just finished a cmd. New one may start
6142 * with an assignment */
6143 dest.o_assignment = MAYBE_ASSIGNMENT;
6146 if (done_word(&dest, &ctx)) {
6150 ch = i_getch(input);
6151 nommu_addchr(&ctx.as_string, ch);
6152 done_pipe(&ctx, PIPE_AND);
6154 done_pipe(&ctx, PIPE_BG);
6158 if (done_word(&dest, &ctx)) {
6161 #if ENABLE_HUSH_CASE
6162 if (ctx.ctx_res_w == RES_MATCH)
6163 break; /* we are in case's "word | word)" */
6165 if (next == '|') { /* || */
6166 ch = i_getch(input);
6167 nommu_addchr(&ctx.as_string, ch);
6168 done_pipe(&ctx, PIPE_OR);
6170 /* we could pick up a file descriptor choice here
6171 * with redirect_opt_num(), but bash doesn't do it.
6172 * "echo foo 2| cat" yields "foo 2". */
6177 #if ENABLE_HUSH_CASE
6178 /* "case... in [(]word)..." - skip '(' */
6179 if (ctx.ctx_res_w == RES_MATCH
6180 && ctx.command->argv == NULL /* not (word|(... */
6181 && dest.length == 0 /* not word(... */
6182 && dest.o_quoted == 0 /* not ""(... */
6188 if (parse_group(&dest, &ctx, input, ch) != 0) {
6193 #if ENABLE_HUSH_CASE
6194 if (ctx.ctx_res_w == RES_MATCH)
6198 /* proper use of this character is caught by end_trigger:
6199 * if we see {, we call parse_group(..., end_trigger='}')
6200 * and it will match } earlier (not here). */
6201 syntax_error_unexpected_ch(ch);
6205 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6211 struct parse_context *pctx;
6212 IF_HAS_KEYWORDS(struct parse_context *p2;)
6214 /* Clean up allocated tree.
6215 * Sample for finding leaks on syntax error recovery path.
6216 * Run it from interactive shell, watch pmap `pidof hush`.
6217 * while if false; then false; fi; do break; fi
6218 * Samples to catch leaks at execution:
6219 * while if (true | {true;}); then echo ok; fi; do break; done
6220 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6224 /* Update pipe/command counts,
6225 * otherwise freeing may miss some */
6226 done_pipe(pctx, PIPE_SEQ);
6227 debug_printf_clean("freeing list %p from ctx %p\n",
6228 pctx->list_head, pctx);
6229 debug_print_tree(pctx->list_head, 0);
6230 free_pipe_list(pctx->list_head);
6231 debug_printf_clean("freed list %p\n", pctx->list_head);
6233 o_free_unsafe(&pctx->as_string);
6235 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6239 IF_HAS_KEYWORDS(pctx = p2;)
6240 } while (HAS_KEYWORDS && pctx);
6241 /* Free text, clear all dest fields */
6243 /* If we are not in top-level parse, we return,
6244 * our caller will propagate error.
6246 if (end_trigger != ';') {
6254 /* Discard cached input, force prompt */
6256 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6261 /* Executing from string: eval, sh -c '...'
6262 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6263 * end_trigger controls how often we stop parsing
6264 * NUL: parse all, execute, return
6265 * ';': parse till ';' or newline, execute, repeat till EOF
6267 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6270 struct pipe *pipe_list;
6272 pipe_list = parse_stream(NULL, inp, end_trigger);
6273 if (!pipe_list) /* EOF */
6275 debug_print_tree(pipe_list, 0);
6276 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6277 run_and_free_list(pipe_list);
6281 static void parse_and_run_string(const char *s)
6283 struct in_str input;
6284 setup_string_in_str(&input, s);
6285 parse_and_run_stream(&input, '\0');
6288 static void parse_and_run_file(FILE *f)
6290 struct in_str input;
6291 setup_file_in_str(&input, f);
6292 parse_and_run_stream(&input, ';');
6295 /* Called a few times only (or even once if "sh -c") */
6296 static void block_signals(int second_time)
6301 mask = (1 << SIGQUIT);
6302 if (G_interactive_fd) {
6303 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6304 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6305 mask |= SPECIAL_JOB_SIGS;
6307 G.non_DFL_mask = mask;
6310 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6314 sigaddset(&G.blocked_set, sig);
6318 sigdelset(&G.blocked_set, SIGCHLD);
6320 sigprocmask(SIG_SETMASK, &G.blocked_set,
6321 second_time ? NULL : &G.inherited_set);
6322 /* POSIX allows shell to re-enable SIGCHLD
6323 * even if it was SIG_IGN on entry */
6324 #if ENABLE_HUSH_FAST
6325 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6327 signal(SIGCHLD, SIGCHLD_handler);
6330 signal(SIGCHLD, SIG_DFL);
6336 static void maybe_set_to_sigexit(int sig)
6338 void (*handler)(int);
6339 /* non_DFL_mask'ed signals are, well, masked,
6340 * no need to set handler for them.
6342 if (!((G.non_DFL_mask >> sig) & 1)) {
6343 handler = signal(sig, sigexit);
6344 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6345 signal(sig, handler);
6348 /* Set handlers to restore tty pgrp and exit */
6349 static void set_fatal_handlers(void)
6351 /* We _must_ restore tty pgrp on fatal signals */
6353 maybe_set_to_sigexit(SIGILL );
6354 maybe_set_to_sigexit(SIGFPE );
6355 maybe_set_to_sigexit(SIGBUS );
6356 maybe_set_to_sigexit(SIGSEGV);
6357 maybe_set_to_sigexit(SIGTRAP);
6358 } /* else: hush is perfect. what SEGV? */
6359 maybe_set_to_sigexit(SIGABRT);
6360 /* bash 3.2 seems to handle these just like 'fatal' ones */
6361 maybe_set_to_sigexit(SIGPIPE);
6362 maybe_set_to_sigexit(SIGALRM);
6363 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6364 * if we aren't interactive... but in this case
6365 * we never want to restore pgrp on exit, and this fn is not called */
6366 /*maybe_set_to_sigexit(SIGHUP );*/
6367 /*maybe_set_to_sigexit(SIGTERM);*/
6368 /*maybe_set_to_sigexit(SIGINT );*/
6372 static int set_mode(const char cstate, const char mode)
6374 int state = (cstate == '-' ? 1 : 0);
6376 case 'n': G.fake_mode = state; break;
6377 case 'x': /*G.debug_mode = state;*/ break;
6378 default: return EXIT_FAILURE;
6380 return EXIT_SUCCESS;
6383 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6384 int hush_main(int argc, char **argv)
6386 static const struct variable const_shell_ver = {
6388 .varstr = (char*)hush_version_str,
6389 .max_len = 1, /* 0 can provoke free(name) */
6393 int signal_mask_is_inited = 0;
6395 unsigned builtin_argc;
6397 struct variable *cur_var;
6400 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6401 G.last_exitcode = EXIT_SUCCESS;
6403 G.argv0_for_re_execing = argv[0];
6405 /* Deal with HUSH_VERSION */
6406 G.shell_ver = const_shell_ver; /* copying struct here */
6407 G.top_var = &G.shell_ver;
6408 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6409 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6410 /* Initialize our shell local variables with the values
6411 * currently living in the environment */
6412 cur_var = G.top_var;
6415 char *value = strchr(*e, '=');
6416 if (value) { /* paranoia */
6417 cur_var->next = xzalloc(sizeof(*cur_var));
6418 cur_var = cur_var->next;
6419 cur_var->varstr = *e;
6420 cur_var->max_len = strlen(*e);
6421 cur_var->flg_export = 1;
6425 debug_printf_env("putenv '%s'\n", hush_version_str);
6426 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6427 #if ENABLE_FEATURE_EDITING
6428 G.line_input_state = new_line_input_t(FOR_SHELL);
6430 G.global_argc = argc;
6431 G.global_argv = argv;
6432 /* Initialize some more globals to non-zero values */
6433 cmdedit_update_prompt();
6435 if (setjmp(die_jmp)) {
6436 /* xfunc has failed! die die die */
6437 /* no EXIT traps, this is an escape hatch! */
6439 hush_exit(xfunc_error_retval);
6442 /* Shell is non-interactive at first. We need to call
6443 * block_signals(0) if we are going to execute "sh <script>",
6444 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6445 * If we later decide that we are interactive, we run block_signals(0)
6446 * (or re-run block_signals(1) if we ran block_signals(0) before)
6447 * in order to intercept (more) signals.
6451 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6454 opt = getopt(argc, argv, "c:xins"
6457 # if ENABLE_HUSH_FUNCTIONS
6467 * sh ... -c 'script'
6468 * sh ... -c 'script' ARG0 [ARG1...]
6469 * On NOMMU, if builtin_argc != 0,
6470 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6471 * "" needs to be replaced with NULL
6472 * and BARGV vector fed to builtin function.
6473 * Note: this form never happens:
6474 * sh ... -c 'builtin' [BARGV...] ""
6477 G.root_pid = getpid();
6478 G.global_argv = argv + optind;
6479 G.global_argc = argc - optind;
6481 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6482 const struct built_in_command *x;
6484 block_signals(0); /* 0: called 1st time */
6485 x = find_builtin(optarg);
6486 if (x) { /* paranoia */
6487 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6488 G.global_argv += builtin_argc;
6489 G.global_argv[-1] = NULL; /* replace "" */
6490 G.last_exitcode = x->function(argv + optind - 1);
6494 if (!G.global_argv[0]) {
6495 /* -c 'script' (no params): prevent empty $0 */
6496 G.global_argv--; /* points to argv[i] of 'script' */
6497 G.global_argv[0] = argv[0];
6499 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6500 block_signals(0); /* 0: called 1st time */
6501 parse_and_run_string(optarg);
6504 /* Well, we cannot just declare interactiveness,
6505 * we have to have some stuff (ctty, etc) */
6506 /* G_interactive_fd++; */
6509 /* "-s" means "read from stdin", but this is how we always
6510 * operate, so simply do nothing here. */
6513 case '<': /* "big heredoc" support */
6514 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6517 G.root_pid = bb_strtou(optarg, &optarg, 16);
6519 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6521 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6523 builtin_argc = bb_strtou(optarg, &optarg, 16);
6524 # if ENABLE_HUSH_LOOPS
6526 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6531 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6533 # if ENABLE_HUSH_FUNCTIONS
6535 struct function *funcp = new_function(optarg);
6536 /* funcp->name is already set to optarg */
6537 /* funcp->body is set to NULL. It's a special case. */
6538 funcp->body_as_string = argv[optind];
6546 if (!set_mode('-', opt))
6550 fprintf(stderr, "Usage: sh [FILE]...\n"
6551 " or: sh -c command [args]...\n\n");
6557 } /* option parsing loop */
6560 G.root_pid = getpid();
6562 /* If we are login shell... */
6563 if (argv[0] && argv[0][0] == '-') {
6565 debug_printf("sourcing /etc/profile\n");
6566 input = fopen_for_read("/etc/profile");
6567 if (input != NULL) {
6568 close_on_exec_on(fileno(input));
6569 block_signals(0); /* 0: called 1st time */
6570 signal_mask_is_inited = 1;
6571 parse_and_run_file(input);
6574 /* bash: after sourcing /etc/profile,
6575 * tries to source (in the given order):
6576 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6577 * stopping on first found. --noprofile turns this off.
6578 * bash also sources ~/.bash_logout on exit.
6579 * If called as sh, skips .bash_XXX files.
6586 * "bash <script>" (which is never interactive (unless -i?))
6587 * sources $BASH_ENV here (without scanning $PATH).
6588 * If called as sh, does the same but with $ENV.
6590 debug_printf("running script '%s'\n", argv[optind]);
6591 G.global_argv = argv + optind;
6592 G.global_argc = argc - optind;
6593 input = xfopen_for_read(argv[optind]);
6594 close_on_exec_on(fileno(input));
6595 if (!signal_mask_is_inited)
6596 block_signals(0); /* 0: called 1st time */
6597 parse_and_run_file(input);
6598 #if ENABLE_FEATURE_CLEAN_UP
6604 /* Up to here, shell was non-interactive. Now it may become one.
6605 * NB: don't forget to (re)run block_signals(0/1) as needed.
6608 /* A shell is interactive if the '-i' flag was given,
6609 * or if all of the following conditions are met:
6611 * no arguments remaining or the -s flag given
6612 * standard input is a terminal
6613 * standard output is a terminal
6614 * Refer to Posix.2, the description of the 'sh' utility.
6617 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6618 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6619 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6620 if (G_saved_tty_pgrp < 0)
6621 G_saved_tty_pgrp = 0;
6623 /* try to dup stdin to high fd#, >= 255 */
6624 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6625 if (G_interactive_fd < 0) {
6626 /* try to dup to any fd */
6627 G_interactive_fd = dup(STDIN_FILENO);
6628 if (G_interactive_fd < 0) {
6630 G_interactive_fd = 0;
6631 G_saved_tty_pgrp = 0;
6634 // TODO: track & disallow any attempts of user
6635 // to (inadvertently) close/redirect G_interactive_fd
6637 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6638 if (G_interactive_fd) {
6639 close_on_exec_on(G_interactive_fd);
6641 if (G_saved_tty_pgrp) {
6642 /* If we were run as 'hush &', sleep until we are
6643 * in the foreground (tty pgrp == our pgrp).
6644 * If we get started under a job aware app (like bash),
6645 * make sure we are now in charge so we don't fight over
6646 * who gets the foreground */
6648 pid_t shell_pgrp = getpgrp();
6649 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6650 if (G_saved_tty_pgrp == shell_pgrp)
6652 /* send TTIN to ourself (should stop us) */
6653 kill(- shell_pgrp, SIGTTIN);
6657 /* Block some signals */
6658 block_signals(signal_mask_is_inited);
6660 if (G_saved_tty_pgrp) {
6661 /* Set other signals to restore saved_tty_pgrp */
6662 set_fatal_handlers();
6663 /* Put ourselves in our own process group
6664 * (bash, too, does this only if ctty is available) */
6665 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6666 /* Grab control of the terminal */
6667 tcsetpgrp(G_interactive_fd, getpid());
6669 /* -1 is special - makes xfuncs longjmp, not exit
6670 * (we reset die_sleep = 0 whereever we [v]fork) */
6671 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6672 } else if (!signal_mask_is_inited) {
6673 block_signals(0); /* 0: called 1st time */
6674 } /* else: block_signals(0) was done before */
6675 #elif ENABLE_HUSH_INTERACTIVE
6676 /* No job control compiled in, only prompt/line editing */
6677 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6678 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6679 if (G_interactive_fd < 0) {
6680 /* try to dup to any fd */
6681 G_interactive_fd = dup(STDIN_FILENO);
6682 if (G_interactive_fd < 0)
6684 G_interactive_fd = 0;
6687 if (G_interactive_fd) {
6688 close_on_exec_on(G_interactive_fd);
6689 block_signals(signal_mask_is_inited);
6690 } else if (!signal_mask_is_inited) {
6694 /* We have interactiveness code disabled */
6695 if (!signal_mask_is_inited) {
6700 * if interactive but not a login shell, sources ~/.bashrc
6701 * (--norc turns this off, --rcfile <file> overrides)
6704 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6705 printf("\n\n%s hush - the humble shell\n", bb_banner);
6706 if (ENABLE_HUSH_HELP)
6707 puts("Enter 'help' for a list of built-in commands.");
6711 parse_and_run_file(stdin);
6714 #if ENABLE_FEATURE_CLEAN_UP
6715 if (G.cwd != bb_msg_unknown)
6717 cur_var = G.top_var->next;
6719 struct variable *tmp = cur_var;
6720 if (!cur_var->max_len)
6721 free(cur_var->varstr);
6722 cur_var = cur_var->next;
6726 hush_exit(G.last_exitcode);
6731 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6732 int lash_main(int argc, char **argv)
6734 //bb_error_msg("lash is deprecated, please use hush instead");
6735 return hush_main(argc, argv);
6743 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6748 static int FAST_FUNC builtin_test(char **argv)
6755 return test_main(argc, argv - argc);
6758 static int FAST_FUNC builtin_echo(char **argv)
6765 return echo_main(argc, argv - argc);
6768 static int FAST_FUNC builtin_eval(char **argv)
6770 int rcode = EXIT_SUCCESS;
6773 char *str = expand_strvec_to_string(argv);
6775 * eval "echo Hi; done" ("done" is syntax error):
6776 * "echo Hi" will not execute too.
6778 parse_and_run_string(str);
6780 rcode = G.last_exitcode;
6785 static int FAST_FUNC builtin_cd(char **argv)
6787 const char *newdir = argv[1];
6788 if (newdir == NULL) {
6789 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6790 * bash says "bash: cd: HOME not set" and does nothing
6793 newdir = get_local_var_value("HOME") ? : "/";
6795 if (chdir(newdir)) {
6796 /* Mimic bash message exactly */
6797 bb_perror_msg("cd: %s", newdir);
6798 return EXIT_FAILURE;
6801 return EXIT_SUCCESS;
6804 static int FAST_FUNC builtin_exec(char **argv)
6806 if (*++argv == NULL)
6807 return EXIT_SUCCESS; /* bash does this */
6812 /* TODO: if exec fails, bash does NOT exit! We do... */
6813 pseudo_exec_argv(&dummy, argv, 0, NULL);
6818 static int FAST_FUNC builtin_exit(char **argv)
6820 debug_printf_exec("%s()\n", __func__);
6822 /* interactive bash:
6823 * # trap "echo EEE" EXIT
6826 * There are stopped jobs.
6827 * (if there are _stopped_ jobs, running ones don't count)
6830 # EEE (then bash exits)
6832 * we can use G.exiting = -1 as indicator "last cmd was exit"
6835 /* note: EXIT trap is run by hush_exit */
6836 if (*++argv == NULL)
6837 hush_exit(G.last_exitcode);
6838 /* mimic bash: exit 123abc == exit 255 + error msg */
6839 xfunc_error_retval = 255;
6840 /* bash: exit -2 == exit 254, no error msg */
6841 hush_exit(xatoi(*argv) & 0xff);
6844 static void print_escaped(const char *s)
6849 const char *p = strchrnul(s, '\'');
6850 /* print 'xxxx', possibly just '' */
6851 printf("'%.*s'", (int)(p - s), s);
6856 /* s points to '; print "'''...'''" */
6858 do putchar('\''); while (*++s == '\'');
6863 #if !ENABLE_HUSH_LOCAL
6864 #define helper_export_local(argv, exp, lvl) \
6865 helper_export_local(argv, exp)
6867 static void helper_export_local(char **argv, int exp, int lvl)
6872 /* So far we do not check that name is valid (TODO?) */
6874 if (strchr(name, '=') == NULL) {
6875 struct variable *var;
6877 var = get_local_var(name);
6878 if (exp == -1) { /* unexporting? */
6879 /* export -n NAME (without =VALUE) */
6881 var->flg_export = 0;
6882 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6884 } /* else: export -n NOT_EXISTING_VAR: no-op */
6887 if (exp == 1) { /* exporting? */
6888 /* export NAME (without =VALUE) */
6890 var->flg_export = 1;
6891 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6892 putenv(var->varstr);
6896 /* Exporting non-existing variable.
6897 * bash does not put it in environment,
6898 * but remembers that it is exported,
6899 * and does put it in env when it is set later.
6900 * We just set it to "" and export. */
6901 /* Or, it's "local NAME" (without =VALUE).
6902 * bash sets the value to "". */
6903 name = xasprintf("%s=", name);
6905 /* (Un)exporting/making local NAME=VALUE */
6906 name = xstrdup(name);
6908 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6912 static int FAST_FUNC builtin_export(char **argv)
6914 unsigned opt_unexport;
6916 #if ENABLE_HUSH_EXPORT_N
6917 /* "!": do not abort on errors */
6918 opt_unexport = getopt32(argv, "!n");
6919 if (opt_unexport == (uint32_t)-1)
6920 return EXIT_FAILURE;
6927 if (argv[0] == NULL) {
6934 /* ash emits: export VAR='VAL'
6935 * bash: declare -x VAR="VAL"
6936 * we follow ash example */
6937 const char *s = *e++;
6938 const char *p = strchr(s, '=');
6940 if (!p) /* wtf? take next variable */
6943 printf("export %.*s", (int)(p - s) + 1, s);
6944 print_escaped(p + 1);
6948 /*fflush(stdout); - done after each builtin anyway */
6950 return EXIT_SUCCESS;
6953 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
6955 return EXIT_SUCCESS;
6958 #if ENABLE_HUSH_LOCAL
6959 static int FAST_FUNC builtin_local(char **argv)
6961 if (G.func_nest_level == 0) {
6962 bb_error_msg("%s: not in a function", argv[0]);
6963 return EXIT_FAILURE; /* bash compat */
6965 helper_export_local(argv, 0, G.func_nest_level);
6966 return EXIT_SUCCESS;
6970 static int FAST_FUNC builtin_trap(char **argv)
6976 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6981 /* No args: print all trapped */
6982 for (i = 0; i < NSIG; ++i) {
6985 print_escaped(G.traps[i]);
6986 printf(" %s\n", get_signame(i));
6989 /*fflush(stdout); - done after each builtin anyway */
6990 return EXIT_SUCCESS;
6994 /* If first arg is a number: reset all specified signals */
6995 sig = bb_strtou(*argv, NULL, 10);
7001 sig = get_signum(*argv++);
7002 if (sig < 0 || sig >= NSIG) {
7004 /* Mimic bash message exactly */
7005 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7010 G.traps[sig] = xstrdup(new_cmd);
7012 debug_printf("trap: setting SIG%s (%i) to '%s'",
7013 get_signame(sig), sig, G.traps[sig]);
7015 /* There is no signal for 0 (EXIT) */
7020 sigaddset(&G.blocked_set, sig);
7022 /* There was a trap handler, we are removing it
7023 * (if sig has non-DFL handling,
7024 * we don't need to do anything) */
7025 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7027 sigdelset(&G.blocked_set, sig);
7030 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7034 if (!argv[1]) { /* no second arg */
7035 bb_error_msg("trap: invalid arguments");
7036 return EXIT_FAILURE;
7039 /* First arg is "-": reset all specified to default */
7040 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7041 /* Everything else: set arg as signal handler
7042 * (includes "" case, which ignores signal) */
7043 if (argv[0][0] == '-') {
7044 if (argv[0][1] == '\0') { /* "-" */
7045 /* new_cmd remains NULL: "reset these sigs" */
7048 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7051 /* else: "-something", no special meaning */
7056 goto process_sig_list;
7059 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7060 static int FAST_FUNC builtin_type(char **argv)
7062 int ret = EXIT_SUCCESS;
7068 if (0) {} /* make conditional compile easier below */
7069 /*else if (find_alias(*argv))
7070 type = "an alias";*/
7071 #if ENABLE_HUSH_FUNCTIONS
7072 else if (find_function(*argv))
7073 type = "a function";
7075 else if (find_builtin(*argv))
7076 type = "a shell builtin";
7077 else if ((path = find_in_path(*argv)) != NULL)
7080 bb_error_msg("type: %s: not found", *argv);
7085 printf("%s is %s\n", *argv, type);
7093 /* built-in 'fg' and 'bg' handler */
7094 static int FAST_FUNC builtin_fg_bg(char **argv)
7099 if (!G_interactive_fd)
7100 return EXIT_FAILURE;
7102 /* If they gave us no args, assume they want the last backgrounded task */
7104 for (pi = G.job_list; pi; pi = pi->next) {
7105 if (pi->jobid == G.last_jobid) {
7109 bb_error_msg("%s: no current job", argv[0]);
7110 return EXIT_FAILURE;
7112 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7113 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7114 return EXIT_FAILURE;
7116 for (pi = G.job_list; pi; pi = pi->next) {
7117 if (pi->jobid == jobnum) {
7121 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7122 return EXIT_FAILURE;
7124 /* TODO: bash prints a string representation
7125 * of job being foregrounded (like "sleep 1 | cat") */
7126 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7127 /* Put the job into the foreground. */
7128 tcsetpgrp(G_interactive_fd, pi->pgrp);
7131 /* Restart the processes in the job */
7132 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7133 for (i = 0; i < pi->num_cmds; i++) {
7134 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7135 pi->cmds[i].is_stopped = 0;
7137 pi->stopped_cmds = 0;
7139 i = kill(- pi->pgrp, SIGCONT);
7141 if (errno == ESRCH) {
7142 delete_finished_bg_job(pi);
7143 return EXIT_SUCCESS;
7145 bb_perror_msg("kill (SIGCONT)");
7148 if (argv[0][0] == 'f') {
7150 return checkjobs_and_fg_shell(pi);
7152 return EXIT_SUCCESS;
7156 #if ENABLE_HUSH_HELP
7157 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7159 const struct built_in_command *x;
7162 "Built-in commands:\n"
7163 "------------------\n");
7164 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7166 printf("%s\t%s\n", x->cmd, x->descr);
7169 return EXIT_SUCCESS;
7174 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7177 const char *status_string;
7179 for (job = G.job_list; job; job = job->next) {
7180 if (job->alive_cmds == job->stopped_cmds)
7181 status_string = "Stopped";
7183 status_string = "Running";
7185 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7187 return EXIT_SUCCESS;
7192 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7197 /* Crude attempt to find where "free memory" starts,
7198 * sans fragmentation. */
7200 l = (unsigned long)p;
7203 if (l < (unsigned long)p) l = (unsigned long)p;
7206 if (!G.memleak_value)
7207 G.memleak_value = l;
7209 l -= G.memleak_value;
7216 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7221 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7224 return EXIT_SUCCESS;
7227 static int FAST_FUNC builtin_read(char **argv)
7230 const char *name = "REPLY";
7234 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7235 * and _after_ that_ it will complain */
7236 if (!is_well_formed_var_name(name, '\0')) {
7237 /* Mimic bash message */
7238 bb_error_msg("read: '%s': not a valid identifier", name);
7243 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7245 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7246 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7249 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7250 * built-in 'set' handler
7252 * set [-abCefhmnuvx] [-o option] [argument...]
7253 * set [+abCefhmnuvx] [+o option] [argument...]
7254 * set -- [argument...]
7257 * Implementations shall support the options in both their hyphen and
7258 * plus-sign forms. These options can also be specified as options to sh.
7260 * Write out all variables and their values: set
7261 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7262 * Turn on the -x and -v options: set -xv
7263 * Unset all positional parameters: set --
7264 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7265 * Set the positional parameters to the expansion of x, even if x expands
7266 * with a leading '-' or '+': set -- $x
7268 * So far, we only support "set -- [argument...]" and some of the short names.
7270 static int FAST_FUNC builtin_set(char **argv)
7273 char **pp, **g_argv;
7274 char *arg = *++argv;
7278 for (e = G.top_var; e; e = e->next)
7280 return EXIT_SUCCESS;
7284 if (!strcmp(arg, "--")) {
7288 if (arg[0] != '+' && arg[0] != '-')
7290 for (n = 1; arg[n]; ++n)
7291 if (set_mode(arg[0], arg[n]))
7293 } while ((arg = *++argv) != NULL);
7294 /* Now argv[0] is 1st argument */
7297 return EXIT_SUCCESS;
7300 /* NB: G.global_argv[0] ($0) is never freed/changed */
7301 g_argv = G.global_argv;
7302 if (G.global_args_malloced) {
7308 G.global_args_malloced = 1;
7309 pp = xzalloc(sizeof(pp[0]) * 2);
7310 pp[0] = g_argv[0]; /* retain $0 */
7313 /* This realloc's G.global_argv */
7314 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7321 return EXIT_SUCCESS;
7323 /* Nothing known, so abort */
7325 bb_error_msg("set: %s: invalid option", arg);
7326 return EXIT_FAILURE;
7329 static int FAST_FUNC builtin_shift(char **argv)
7335 if (n >= 0 && n < G.global_argc) {
7336 if (G.global_args_malloced) {
7339 free(G.global_argv[m++]);
7342 memmove(&G.global_argv[1], &G.global_argv[n+1],
7343 G.global_argc * sizeof(G.global_argv[0]));
7344 return EXIT_SUCCESS;
7346 return EXIT_FAILURE;
7349 static int FAST_FUNC builtin_source(char **argv)
7354 #if ENABLE_HUSH_FUNCTIONS
7358 if (*++argv == NULL)
7359 return EXIT_FAILURE;
7361 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7362 input = fopen_for_read(arg_path);
7365 input = fopen_or_warn(*argv, "r");
7367 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7368 return EXIT_FAILURE;
7370 close_on_exec_on(fileno(input));
7372 #if ENABLE_HUSH_FUNCTIONS
7373 sv_flg = G.flag_return_in_progress;
7374 /* "we are inside sourced file, ok to use return" */
7375 G.flag_return_in_progress = -1;
7377 save_and_replace_G_args(&sv, argv);
7379 parse_and_run_file(input);
7382 restore_G_args(&sv, argv);
7383 #if ENABLE_HUSH_FUNCTIONS
7384 G.flag_return_in_progress = sv_flg;
7387 return G.last_exitcode;
7390 static int FAST_FUNC builtin_umask(char **argv)
7397 mode_t old_mask = mask;
7400 rc = bb_parse_mode(argv[1], &mask);
7405 * bash: umask: 'q': invalid symbolic mode operator
7406 * bash: umask: 999: octal number out of range
7408 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7413 printf("%04o\n", (unsigned) mask);
7414 /* fall through and restore mask which we set to 0 */
7418 return !rc; /* rc != 0 - success */
7421 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7422 static int FAST_FUNC builtin_unset(char **argv)
7427 /* "!": do not abort on errors */
7428 /* "+": stop at 1st non-option */
7429 opts = getopt32(argv, "!+vf");
7430 if (opts == (unsigned)-1)
7431 return EXIT_FAILURE;
7433 bb_error_msg("unset: -v and -f are exclusive");
7434 return EXIT_FAILURE;
7440 if (!(opts & 2)) { /* not -f */
7441 if (unset_local_var(*argv)) {
7442 /* unset <nonexistent_var> doesn't fail.
7443 * Error is when one tries to unset RO var.
7444 * Message was printed by unset_local_var. */
7448 #if ENABLE_HUSH_FUNCTIONS
7458 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7459 static int FAST_FUNC builtin_wait(char **argv)
7461 int ret = EXIT_SUCCESS;
7464 if (*++argv == NULL) {
7465 /* Don't care about wait results */
7466 /* Note 1: must wait until there are no more children */
7467 /* Note 2: must be interruptible */
7469 * $ sleep 3 & sleep 6 & wait
7474 * $ sleep 3 & sleep 6 & wait
7478 * ^C <-- after ~4 sec from keyboard
7481 sigaddset(&G.blocked_set, SIGCHLD);
7482 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7485 if (errno == ECHILD)
7487 /* Wait for SIGCHLD or any other signal of interest */
7488 /* sigtimedwait with infinite timeout: */
7489 sig = sigwaitinfo(&G.blocked_set, NULL);
7491 sig = check_and_run_traps(sig);
7492 if (sig && sig != SIGCHLD) { /* see note 2 */
7498 sigdelset(&G.blocked_set, SIGCHLD);
7499 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7503 /* This is probably buggy wrt interruptible-ness */
7505 pid_t pid = bb_strtou(*argv, NULL, 10);
7507 /* mimic bash message */
7508 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7509 return EXIT_FAILURE;
7511 if (waitpid(pid, &status, 0) == pid) {
7512 if (WIFSIGNALED(status))
7513 ret = 128 + WTERMSIG(status);
7514 else if (WIFEXITED(status))
7515 ret = WEXITSTATUS(status);
7519 bb_perror_msg("wait %s", *argv);
7528 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7529 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7532 def = bb_strtou(argv[1], NULL, 10);
7533 if (errno || def < def_min || argv[2]) {
7534 bb_error_msg("%s: bad arguments", argv[0]);
7542 #if ENABLE_HUSH_LOOPS
7543 static int FAST_FUNC builtin_break(char **argv)
7546 if (G.depth_of_loop == 0) {
7547 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7548 return EXIT_SUCCESS; /* bash compat */
7550 G.flag_break_continue++; /* BC_BREAK = 1 */
7552 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7553 if (depth == UINT_MAX)
7554 G.flag_break_continue = BC_BREAK;
7555 if (G.depth_of_loop < depth)
7556 G.depth_break_continue = G.depth_of_loop;
7558 return EXIT_SUCCESS;
7561 static int FAST_FUNC builtin_continue(char **argv)
7563 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7564 return builtin_break(argv);
7568 #if ENABLE_HUSH_FUNCTIONS
7569 static int FAST_FUNC builtin_return(char **argv)
7573 if (G.flag_return_in_progress != -1) {
7574 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7575 return EXIT_FAILURE; /* bash compat */
7578 G.flag_return_in_progress = 1;
7581 * out of range: wraps around at 256, does not error out
7582 * non-numeric param:
7583 * f() { false; return qwe; }; f; echo $?
7584 * bash: return: qwe: numeric argument required <== we do this
7585 * 255 <== we also do this
7587 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);