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.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
92 #include "builtin_read.h"
93 #include "builtin_ulimit.h"
96 #if ENABLE_HUSH_RANDOM_SUPPORT
99 # define CLEAR_RANDOM_T(rnd) ((void)0)
102 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
107 #define LEAK_HUNTING 0
108 #define BUILD_AS_NOMMU 0
109 /* Enable/disable sanity checks. Ok to enable in production,
110 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
111 * Keeping 1 for now even in released versions.
114 /* Slightly bigger (+200 bytes), but faster hush.
115 * So far it only enables a trick with counting SIGCHLDs and forks,
116 * which allows us to do fewer waitpid's.
117 * (we can detect a case where neither forks were done nor SIGCHLDs happened
118 * and therefore waitpid will return the same result as last time)
120 #define ENABLE_HUSH_FAST 0
125 # undef USE_FOR_NOMMU
128 # define USE_FOR_NOMMU(...) __VA_ARGS__
129 # define USE_FOR_MMU(...)
132 #define SKIP_definitions 1
133 #include "applet_tables.h"
134 #undef SKIP_definitions
136 /* STANDALONE does not make sense, and won't compile */
137 # undef CONFIG_FEATURE_SH_STANDALONE
138 # undef ENABLE_FEATURE_SH_STANDALONE
139 # undef IF_FEATURE_SH_STANDALONE
140 # undef IF_NOT_FEATURE_SH_STANDALONE
141 # define ENABLE_FEATURE_SH_STANDALONE 0
142 # define IF_FEATURE_SH_STANDALONE(...)
143 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
146 #if !ENABLE_HUSH_INTERACTIVE
147 # undef ENABLE_FEATURE_EDITING
148 # define ENABLE_FEATURE_EDITING 0
149 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
150 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
153 /* Do we support ANY keywords? */
154 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
155 # define HAS_KEYWORDS 1
156 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
157 # define IF_HAS_NO_KEYWORDS(...)
159 # define HAS_KEYWORDS 0
160 # define IF_HAS_KEYWORDS(...)
161 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
164 /* If you comment out one of these below, it will be #defined later
165 * to perform debug printfs to stderr: */
166 #define debug_printf(...) do {} while (0)
167 /* Finer-grained debug switches */
168 #define debug_printf_parse(...) do {} while (0)
169 #define debug_print_tree(a, b) do {} while (0)
170 #define debug_printf_exec(...) do {} while (0)
171 #define debug_printf_env(...) do {} while (0)
172 #define debug_printf_jobs(...) do {} while (0)
173 #define debug_printf_expand(...) do {} while (0)
174 #define debug_printf_varexp(...) do {} while (0)
175 #define debug_printf_glob(...) do {} while (0)
176 #define debug_printf_list(...) do {} while (0)
177 #define debug_printf_subst(...) do {} while (0)
178 #define debug_printf_clean(...) do {} while (0)
180 #define ERR_PTR ((void*)(long)1)
182 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
184 #define SPECIAL_VAR_SYMBOL 3
188 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
190 /* This supports saving pointers malloced in vfork child,
191 * to be freed in the parent.
194 typedef struct nommu_save_t {
196 struct variable *old_vars;
198 char **argv_from_re_execing;
202 typedef enum reserved_style {
211 #if ENABLE_HUSH_LOOPS
218 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
223 /* three pseudo-keywords support contrived "case" syntax: */
224 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
225 RES_MATCH , /* "word)" */
226 RES_CASE_BODY, /* "this command is inside CASE" */
233 typedef struct o_string {
235 int length; /* position where data is appended */
237 /* Protect newly added chars against globbing
238 * (by prepending \ to *, ?, [, \) */
241 /* At least some part of the string was inside '' or "",
242 * possibly empty one: word"", wo''rd etc. */
244 smallint has_empty_slot;
245 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
248 MAYBE_ASSIGNMENT = 0,
249 DEFINITELY_ASSIGNMENT = 1,
251 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
253 /* Used for initialization: o_string foo = NULL_O_STRING; */
254 #define NULL_O_STRING { NULL }
256 /* I can almost use ordinary FILE*. Is open_memstream() universally
257 * available? Where is it documented? */
258 typedef struct in_str {
260 /* eof_flag=1: last char in ->p is really an EOF */
261 char eof_flag; /* meaningless if ->p == NULL */
263 #if ENABLE_HUSH_INTERACTIVE
265 smallint promptmode; /* 0: PS1, 1: PS2 */
268 int (*get) (struct in_str *) FAST_FUNC;
269 int (*peek) (struct in_str *) FAST_FUNC;
271 #define i_getch(input) ((input)->get(input))
272 #define i_peek(input) ((input)->peek(input))
274 /* The descrip member of this structure is only used to make
275 * debugging output pretty */
276 static const struct {
278 signed char default_fd;
281 { O_RDONLY, 0, "<" },
282 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
283 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
284 { O_CREAT|O_RDWR, 1, "<>" },
285 { O_RDONLY, 0, "<<" },
286 /* Should not be needed. Bogus default_fd helps in debugging */
287 /* { O_RDONLY, 77, "<<" }, */
290 struct redir_struct {
291 struct redir_struct *next;
292 char *rd_filename; /* filename */
293 int rd_fd; /* fd to redirect */
294 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
296 smallint rd_type; /* (enum redir_type) */
297 /* note: for heredocs, rd_filename contains heredoc delimiter,
298 * and subsequently heredoc itself; and rd_dup is a bitmask:
299 * bit 0: do we need to trim leading tabs?
300 * bit 1: is heredoc quoted (<<'delim' syntax) ?
303 typedef enum redir_type {
305 REDIRECT_OVERWRITE = 1,
308 REDIRECT_HEREDOC = 4,
309 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
312 REDIRFD_SYNTAX_ERR = -2,
313 REDIRFD_TO_FILE = -1,
314 /* otherwise, rd_fd is redirected to rd_dup */
316 HEREDOC_SKIPTABS = 1,
322 pid_t pid; /* 0 if exited */
323 int assignment_cnt; /* how many argv[i] are assignments? */
324 smallint is_stopped; /* is the command currently running? */
325 smallint cmd_type; /* CMD_xxx */
327 #define CMD_SUBSHELL 1
329 /* used for "[[ EXPR ]]" */
330 #if ENABLE_HUSH_BASH_COMPAT
331 # define CMD_SINGLEWORD_NOGLOB 2
334 /* used for "export noglob=* glob* a=`echo a b`" */
335 //#define CMD_SINGLEWORD_NOGLOB_COND 3
336 // It is hard to implement correctly, it adds significant amounts of tricky code,
337 // and all this is only useful for really obscure export statements
338 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
339 // guards the code which implements it, but I have doubts it works
340 // in all cases (especially with mixed globbed/non-globbed arguments)
342 #if ENABLE_HUSH_FUNCTIONS
343 # define CMD_FUNCDEF 3
346 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
349 char *group_as_string;
351 #if ENABLE_HUSH_FUNCTIONS
352 struct function *child_func;
353 /* This field is used to prevent a bug here:
354 * while...do f1() {a;}; f1; f1() {b;}; f1; done
355 * When we execute "f1() {a;}" cmd, we create new function and clear
356 * cmd->group, cmd->group_as_string, cmd->argv[0].
357 * When we execute "f1() {b;}", we notice that f1 exists,
358 * and that its "parent cmd" struct is still "alive",
359 * we put those fields back into cmd->xxx
360 * (struct function has ->parent_cmd ptr to facilitate that).
361 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
362 * Without this trick, loop would execute a;b;b;b;...
363 * instead of correct sequence a;b;a;b;...
364 * When command is freed, it severs the link
365 * (sets ->child_func->parent_cmd to NULL).
368 char **argv; /* command name and arguments */
369 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
370 * and on execution these are substituted with their values.
371 * Substitution can make _several_ words out of one argv[n]!
372 * Example: argv[0]=='.^C*^C.' here: echo .$*.
373 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
375 struct redir_struct *redirects; /* I/O redirections */
377 /* Is there anything in this command at all? */
378 #define IS_NULL_CMD(cmd) \
379 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
384 int num_cmds; /* total number of commands in pipe */
385 int alive_cmds; /* number of commands running (not exited) */
386 int stopped_cmds; /* number of commands alive, but stopped */
388 int jobid; /* job number */
389 pid_t pgrp; /* process group ID for the job */
390 char *cmdtext; /* name of job */
392 struct command *cmds; /* array of commands in pipe */
393 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
394 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
395 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
397 typedef enum pipe_style {
403 /* Is there anything in this pipe at all? */
404 #define IS_NULL_PIPE(pi) \
405 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
407 /* This holds pointers to the various results of parsing */
408 struct parse_context {
409 /* linked list of pipes */
410 struct pipe *list_head;
411 /* last pipe (being constructed right now) */
413 /* last command in pipe (being constructed right now) */
414 struct command *command;
415 /* last redirect in command->redirects list */
416 struct redir_struct *pending_redirect;
422 smallint ctx_inverted; /* "! cmd | cmd" */
424 smallint ctx_dsemicolon; /* ";;" seen */
426 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
428 /* group we are enclosed in:
429 * example: "if pipe1; pipe2; then pipe3; fi"
430 * when we see "if" or "then", we malloc and copy current context,
431 * and make ->stack point to it. then we parse pipeN.
432 * when closing "then" / fi" / whatever is found,
433 * we move list_head into ->stack->command->group,
434 * copy ->stack into current context, and delete ->stack.
435 * (parsing of { list } and ( list ) doesn't use this method)
437 struct parse_context *stack;
441 /* On program start, environ points to initial environment.
442 * putenv adds new pointers into it, unsetenv removes them.
443 * Neither of these (de)allocates the strings.
444 * setenv allocates new strings in malloc space and does putenv,
445 * and thus setenv is unusable (leaky) for shell's purposes */
446 #define setenv(...) setenv_is_leaky_dont_use()
448 struct variable *next;
449 char *varstr; /* points to "name=" portion */
450 #if ENABLE_HUSH_LOCAL
451 unsigned func_nest_level;
453 int max_len; /* if > 0, name is part of initial env; else name is malloced */
454 smallint flg_export; /* putenv should be done on this var */
455 smallint flg_read_only;
463 #if ENABLE_HUSH_FUNCTIONS
465 struct function *next;
467 struct command *parent_cmd;
470 char *body_as_string;
476 /* "Globals" within this file */
477 /* Sorted roughly by size (smaller offsets == smaller code) */
479 /* interactive_fd != 0 means we are an interactive shell.
480 * If we are, then saved_tty_pgrp can also be != 0, meaning
481 * that controlling tty is available. With saved_tty_pgrp == 0,
482 * job control still works, but terminal signals
483 * (^C, ^Z, ^Y, ^\) won't work at all, and background
484 * process groups can only be created with "cmd &".
485 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
486 * to give tty to the foreground process group,
487 * and will take it back when the group is stopped (^Z)
490 #if ENABLE_HUSH_INTERACTIVE
491 /* 'interactive_fd' is a fd# open to ctty, if we have one
492 * _AND_ if we decided to act interactively */
496 # define G_interactive_fd (G.interactive_fd)
498 # define G_interactive_fd 0
500 #if ENABLE_FEATURE_EDITING
501 line_input_t *line_input_state;
506 #if ENABLE_HUSH_RANDOM_SUPPORT
512 pid_t saved_tty_pgrp;
513 struct pipe *job_list;
514 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
516 # define G_saved_tty_pgrp 0
518 smallint flag_SIGINT;
519 #if ENABLE_HUSH_LOOPS
520 smallint flag_break_continue;
522 #if ENABLE_HUSH_FUNCTIONS
523 /* 0: outside of a function (or sourced file)
524 * -1: inside of a function, ok to use return builtin
525 * 1: return is invoked, skip all till end of func
527 smallint flag_return_in_progress;
530 smallint exiting; /* used to prevent EXIT trap recursion */
531 /* These four support $?, $#, and $1 */
532 smalluint last_exitcode;
533 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
534 smalluint global_args_malloced;
535 smalluint inherited_set_is_saved;
536 /* how many non-NULL argv's we have. NB: $# + 1 */
540 char *argv0_for_re_execing;
542 #if ENABLE_HUSH_LOOPS
543 unsigned depth_break_continue;
544 unsigned depth_of_loop;
548 struct variable *top_var; /* = &G.shell_ver (set in main()) */
549 struct variable shell_ver;
550 #if ENABLE_HUSH_FUNCTIONS
551 struct function *top_func;
552 # if ENABLE_HUSH_LOCAL
553 struct variable **shadowed_vars_pp;
554 unsigned func_nest_level;
557 /* Signal and trap handling */
559 unsigned count_SIGCHLD;
560 unsigned handled_SIGCHLD;
561 smallint we_have_children;
563 /* which signals have non-DFL handler (even with no traps set)? */
564 unsigned non_DFL_mask;
565 char **traps; /* char *traps[NSIG] */
566 sigset_t blocked_set;
567 sigset_t inherited_set;
569 unsigned long memleak_value;
572 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
574 #define G (*ptr_to_globals)
575 /* Not #defining name to G.name - this quickly gets unwieldy
576 * (too many defines). Also, I actually prefer to see when a variable
577 * is global, thus "G." prefix is a useful hint */
578 #define INIT_G() do { \
579 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
583 /* Function prototypes for builtins */
584 static int builtin_cd(char **argv) FAST_FUNC;
585 static int builtin_echo(char **argv) FAST_FUNC;
586 static int builtin_eval(char **argv) FAST_FUNC;
587 static int builtin_exec(char **argv) FAST_FUNC;
588 static int builtin_exit(char **argv) FAST_FUNC;
589 static int builtin_export(char **argv) FAST_FUNC;
591 static int builtin_fg_bg(char **argv) FAST_FUNC;
592 static int builtin_jobs(char **argv) FAST_FUNC;
595 static int builtin_help(char **argv) FAST_FUNC;
597 #if ENABLE_HUSH_LOCAL
598 static int builtin_local(char **argv) FAST_FUNC;
601 static int builtin_memleak(char **argv) FAST_FUNC;
604 static int builtin_printf(char **argv) FAST_FUNC;
606 static int builtin_pwd(char **argv) FAST_FUNC;
607 static int builtin_read(char **argv) FAST_FUNC;
608 static int builtin_set(char **argv) FAST_FUNC;
609 static int builtin_shift(char **argv) FAST_FUNC;
610 static int builtin_source(char **argv) FAST_FUNC;
611 static int builtin_test(char **argv) FAST_FUNC;
612 static int builtin_trap(char **argv) FAST_FUNC;
613 static int builtin_type(char **argv) FAST_FUNC;
614 static int builtin_true(char **argv) FAST_FUNC;
615 static int builtin_umask(char **argv) FAST_FUNC;
616 static int builtin_unset(char **argv) FAST_FUNC;
617 static int builtin_wait(char **argv) FAST_FUNC;
618 #if ENABLE_HUSH_LOOPS
619 static int builtin_break(char **argv) FAST_FUNC;
620 static int builtin_continue(char **argv) FAST_FUNC;
622 #if ENABLE_HUSH_FUNCTIONS
623 static int builtin_return(char **argv) FAST_FUNC;
626 /* Table of built-in functions. They can be forked or not, depending on
627 * context: within pipes, they fork. As simple commands, they do not.
628 * When used in non-forking context, they can change global variables
629 * in the parent shell process. If forked, of course they cannot.
630 * For example, 'unset foo | whatever' will parse and run, but foo will
631 * still be set at the end. */
632 struct built_in_command {
634 int (*b_function)(char **argv) FAST_FUNC;
637 # define BLTIN(cmd, func, help) { cmd, func, help }
639 # define BLTIN(cmd, func, help) { cmd, func }
643 static const struct built_in_command bltins1[] = {
644 BLTIN("." , builtin_source , "Run commands in a file"),
645 BLTIN(":" , builtin_true , NULL),
647 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
649 #if ENABLE_HUSH_LOOPS
650 BLTIN("break" , builtin_break , "Exit from a loop"),
652 BLTIN("cd" , builtin_cd , "Change directory"),
653 #if ENABLE_HUSH_LOOPS
654 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
656 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
657 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
658 BLTIN("exit" , builtin_exit , "Exit"),
659 BLTIN("export" , builtin_export , "Set environment variables"),
661 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
664 BLTIN("help" , builtin_help , NULL),
667 BLTIN("jobs" , builtin_jobs , "List jobs"),
669 #if ENABLE_HUSH_LOCAL
670 BLTIN("local" , builtin_local , "Set local variables"),
673 BLTIN("memleak" , builtin_memleak , NULL),
675 BLTIN("read" , builtin_read , "Input into variable"),
676 #if ENABLE_HUSH_FUNCTIONS
677 BLTIN("return" , builtin_return , "Return from a function"),
679 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
680 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
681 #if ENABLE_HUSH_BASH_COMPAT
682 BLTIN("source" , builtin_source , "Run commands in a file"),
684 BLTIN("trap" , builtin_trap , "Trap signals"),
685 BLTIN("type" , builtin_type , "Show command type"),
686 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
687 BLTIN("umask" , builtin_umask , "Set file creation mask"),
688 BLTIN("unset" , builtin_unset , "Unset variables"),
689 BLTIN("wait" , builtin_wait , "Wait for process"),
691 /* For now, echo and test are unconditionally enabled.
692 * Maybe make it configurable? */
693 static const struct built_in_command bltins2[] = {
694 BLTIN("[" , builtin_test , NULL),
695 BLTIN("echo" , builtin_echo , NULL),
697 BLTIN("printf" , builtin_printf , NULL),
699 BLTIN("pwd" , builtin_pwd , NULL),
700 BLTIN("test" , builtin_test , NULL),
707 /* prevent disasters with G.debug_indent < 0 */
708 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
709 # define debug_enter() (G.debug_indent++)
710 # define debug_leave() (G.debug_indent--)
712 # define indent() ((void)0)
713 # define debug_enter() ((void)0)
714 # define debug_leave() ((void)0)
718 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
721 #ifndef debug_printf_parse
722 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
725 #ifndef debug_printf_exec
726 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
729 #ifndef debug_printf_env
730 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
733 #ifndef debug_printf_jobs
734 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
735 # define DEBUG_JOBS 1
737 # define DEBUG_JOBS 0
740 #ifndef debug_printf_expand
741 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
742 # define DEBUG_EXPAND 1
744 # define DEBUG_EXPAND 0
747 #ifndef debug_printf_varexp
748 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
751 #ifndef debug_printf_glob
752 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
753 # define DEBUG_GLOB 1
755 # define DEBUG_GLOB 0
758 #ifndef debug_printf_list
759 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
762 #ifndef debug_printf_subst
763 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
766 #ifndef debug_printf_clean
767 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
768 # define DEBUG_CLEAN 1
770 # define DEBUG_CLEAN 0
774 static void debug_print_strings(const char *prefix, char **vv)
777 fprintf(stderr, "%s:\n", prefix);
779 fprintf(stderr, " '%s'\n", *vv++);
782 # define debug_print_strings(prefix, vv) ((void)0)
786 /* Leak hunting. Use hush_leaktool.sh for post-processing.
789 static void *xxmalloc(int lineno, size_t size)
791 void *ptr = xmalloc((size + 0xff) & ~0xff);
792 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
795 static void *xxrealloc(int lineno, void *ptr, size_t size)
797 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
798 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
801 static char *xxstrdup(int lineno, const char *str)
803 char *ptr = xstrdup(str);
804 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
807 static void xxfree(void *ptr)
809 fdprintf(2, "free %p\n", ptr);
812 #define xmalloc(s) xxmalloc(__LINE__, s)
813 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
814 #define xstrdup(s) xxstrdup(__LINE__, s)
815 #define free(p) xxfree(p)
819 /* Syntax and runtime errors. They always abort scripts.
820 * In interactive use they usually discard unparsed and/or unexecuted commands
821 * and return to the prompt.
822 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
825 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
826 # define syntax_error(lineno, msg) syntax_error(msg)
827 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
828 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
829 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
830 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
833 static void die_if_script(unsigned lineno, const char *fmt, ...)
838 bb_error_msg("hush.c:%u", lineno);
841 bb_verror_msg(fmt, p, NULL);
843 if (!G_interactive_fd)
847 static void syntax_error(unsigned lineno, const char *msg)
850 die_if_script(lineno, "syntax error: %s", msg);
852 die_if_script(lineno, "syntax error", NULL);
855 static void syntax_error_at(unsigned lineno, const char *msg)
857 die_if_script(lineno, "syntax error at '%s'", msg);
860 static void syntax_error_unterm_str(unsigned lineno, const char *s)
862 die_if_script(lineno, "syntax error: unterminated %s", s);
865 /* It so happens that all such cases are totally fatal
866 * even if shell is interactive: EOF while looking for closing
867 * delimiter. There is nowhere to read stuff from after that,
868 * it's EOF! The only choice is to terminate.
870 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
871 static void syntax_error_unterm_ch(unsigned lineno, char ch)
873 char msg[2] = { ch, '\0' };
874 syntax_error_unterm_str(lineno, msg);
878 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
883 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
887 # undef die_if_script
889 # undef syntax_error_at
890 # undef syntax_error_unterm_ch
891 # undef syntax_error_unterm_str
892 # undef syntax_error_unexpected_ch
894 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
895 # define syntax_error(msg) syntax_error(__LINE__, msg)
896 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
897 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
898 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
899 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
903 #if ENABLE_HUSH_INTERACTIVE
904 static void cmdedit_update_prompt(void);
906 # define cmdedit_update_prompt() ((void)0)
912 /* Replace each \x with x in place, return ptr past NUL. */
913 static char *unbackslash(char *src)
915 char *dst = src = strchrnul(src, '\\');
919 if ((*dst++ = *src++) == '\0')
925 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
946 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
947 v[count1 + count2] = NULL;
950 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
954 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
956 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
957 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
960 #define add_strings_to_strings(strings, add, need_to_dup) \
961 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
964 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
965 static char **add_string_to_strings(char **strings, char *add)
970 return add_strings_to_strings(strings, v, /*dup:*/ 0);
973 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
975 char **ptr = add_string_to_strings(strings, add);
976 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
979 #define add_string_to_strings(strings, add) \
980 xx_add_string_to_strings(__LINE__, strings, add)
983 static void free_strings(char **strings)
998 /* Helpers for setting new $n and restoring them back
1000 typedef struct save_arg_t {
1004 smallint sv_g_malloced;
1007 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1011 sv->sv_argv0 = argv[0];
1012 sv->sv_g_argv = G.global_argv;
1013 sv->sv_g_argc = G.global_argc;
1014 sv->sv_g_malloced = G.global_args_malloced;
1016 argv[0] = G.global_argv[0]; /* retain $0 */
1017 G.global_argv = argv;
1018 G.global_args_malloced = 0;
1026 static void restore_G_args(save_arg_t *sv, char **argv)
1030 if (G.global_args_malloced) {
1031 /* someone ran "set -- arg1 arg2 ...", undo */
1033 while (*++pp) /* note: does not free $0 */
1035 free(G.global_argv);
1037 argv[0] = sv->sv_argv0;
1038 G.global_argv = sv->sv_g_argv;
1039 G.global_argc = sv->sv_g_argc;
1040 G.global_args_malloced = sv->sv_g_malloced;
1044 /* Basic theory of signal handling in shell
1045 * ========================================
1046 * This does not describe what hush does, rather, it is current understanding
1047 * what it _should_ do. If it doesn't, it's a bug.
1048 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1050 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1051 * is finished or backgrounded. It is the same in interactive and
1052 * non-interactive shells, and is the same regardless of whether
1053 * a user trap handler is installed or a shell special one is in effect.
1054 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1055 * backgrounds (i.e. stops) or kills all members of currently running
1058 * Wait builtin in interruptible by signals for which user trap is set
1059 * or by SIGINT in interactive shell.
1061 * Trap handlers will execute even within trap handlers. (right?)
1063 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1064 * except for handlers set to '' (empty string).
1066 * If job control is off, backgrounded commands ("cmd &")
1067 * have SIGINT, SIGQUIT set to SIG_IGN.
1069 * Commands which are run in command substitution ("`cmd`")
1070 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1072 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1073 * by the shell from its parent.
1075 * Signals which differ from SIG_DFL action
1076 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1079 * SIGTERM (interactive): ignore
1080 * SIGHUP (interactive):
1081 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1082 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1083 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1084 * that all pipe members are stopped. Try this in bash:
1085 * while :; do :; done - ^Z does not background it
1086 * (while :; do :; done) - ^Z backgrounds it
1087 * SIGINT (interactive): wait for last pipe, ignore the rest
1088 * of the command line, show prompt. NB: ^C does not send SIGINT
1089 * to interactive shell while shell is waiting for a pipe,
1090 * since shell is bg'ed (is not in foreground process group).
1091 * Example 1: this waits 5 sec, but does not execute ls:
1092 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1093 * Example 2: this does not wait and does not execute ls:
1094 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1095 * Example 3: this does not wait 5 sec, but executes ls:
1096 * "sleep 5; ls -l" + press ^C
1098 * (What happens to signals which are IGN on shell start?)
1099 * (What happens with signal mask on shell start?)
1101 * Implementation in hush
1102 * ======================
1103 * We use in-kernel pending signal mask to determine which signals were sent.
1104 * We block all signals which we don't want to take action immediately,
1105 * i.e. we block all signals which need to have special handling as described
1106 * above, and all signals which have traps set.
1107 * After each pipe execution, we extract any pending signals via sigtimedwait()
1110 * unsigned non_DFL_mask: a mask of such "special" signals
1111 * sigset_t blocked_set: current blocked signal set
1114 * clear bit in blocked_set unless it is also in non_DFL_mask
1115 * "trap 'cmd' SIGxxx":
1116 * set bit in blocked_set (even if 'cmd' is '')
1117 * after [v]fork, if we plan to be a shell:
1118 * unblock signals with special interactive handling
1119 * (child shell is not interactive),
1120 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1121 * after [v]fork, if we plan to exec:
1122 * POSIX says fork clears pending signal mask in child - no need to clear it.
1123 * Restore blocked signal set to one inherited by shell just prior to exec.
1125 * Note: as a result, we do not use signal handlers much. The only uses
1126 * are to count SIGCHLDs
1127 * and to restore tty pgrp on signal-induced exit.
1130 * Standard says "When a subshell is entered, traps that are not being ignored
1131 * are set to the default actions". bash interprets it so that traps which
1132 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1135 SPECIAL_INTERACTIVE_SIGS = 0
1140 SPECIAL_JOB_SIGS = 0
1148 #if ENABLE_HUSH_FAST
1149 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1152 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1158 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1159 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1160 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1161 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1163 /* Restores tty foreground process group, and exits.
1164 * May be called as signal handler for fatal signal
1165 * (will resend signal to itself, producing correct exit state)
1166 * or called directly with -EXITCODE.
1167 * We also call it if xfunc is exiting. */
1168 static void sigexit(int sig) NORETURN;
1169 static void sigexit(int sig)
1171 /* Disable all signals: job control, SIGPIPE, etc. */
1172 sigprocmask_allsigs(SIG_BLOCK);
1174 /* Careful: we can end up here after [v]fork. Do not restore
1175 * tty pgrp then, only top-level shell process does that */
1176 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1177 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1179 /* Not a signal, just exit */
1183 kill_myself_with_sig(sig); /* does not return */
1187 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1188 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1192 /* Restores tty foreground process group, and exits. */
1193 static void hush_exit(int exitcode) NORETURN;
1194 static void hush_exit(int exitcode)
1196 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1197 /* Prevent recursion:
1198 * trap "echo Hi; exit" EXIT; exit
1200 char *argv[] = { NULL, G.traps[0], NULL };
1209 sigexit(- (exitcode & 0xff));
1215 static int check_and_run_traps(int sig)
1217 static const struct timespec zero_timespec = { 0, 0 };
1218 smalluint save_rcode;
1224 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1229 if (G.traps && G.traps[sig]) {
1230 if (G.traps[sig][0]) {
1231 /* We have user-defined handler */
1232 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1233 save_rcode = G.last_exitcode;
1236 G.last_exitcode = save_rcode;
1237 } /* else: "" trap, ignoring signal */
1240 /* not a trap: special action */
1242 #if ENABLE_HUSH_FAST
1245 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1249 /* Builtin was ^C'ed, make it look prettier: */
1256 /* bash is observed to signal whole process groups,
1257 * not individual processes */
1258 for (job = G.job_list; job; job = job->next) {
1261 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1262 if (kill(- job->pgrp, SIGHUP) == 0)
1263 kill(- job->pgrp, SIGCONT);
1268 default: /* ignored: */
1269 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1277 static const char *get_cwd(int force)
1279 if (force || G.cwd == NULL) {
1280 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1281 * we must not try to free(bb_msg_unknown) */
1282 if (G.cwd == bb_msg_unknown)
1284 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1286 G.cwd = bb_msg_unknown;
1293 * Shell and environment variable support
1295 static struct variable **get_ptr_to_local_var(const char *name)
1297 struct variable **pp;
1298 struct variable *cur;
1303 while ((cur = *pp) != NULL) {
1304 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1311 static struct variable *get_local_var(const char *name)
1313 struct variable **pp = get_ptr_to_local_var(name);
1319 static const char* FAST_FUNC get_local_var_value(const char *name)
1321 struct variable **pp = get_ptr_to_local_var(name);
1323 return strchr((*pp)->varstr, '=') + 1;
1324 if (strcmp(name, "PPID") == 0)
1325 return utoa(G.root_ppid);
1326 // bash compat: UID? EUID?
1327 #if ENABLE_HUSH_RANDOM_SUPPORT
1328 if (strcmp(name, "RANDOM") == 0) {
1329 return utoa(next_random(&G.random_gen));
1335 /* str holds "NAME=VAL" and is expected to be malloced.
1336 * We take ownership of it.
1338 * 0: do not change export flag
1339 * (if creating new variable, flag will be 0)
1340 * 1: set export flag and putenv the variable
1341 * -1: clear export flag and unsetenv the variable
1342 * flg_read_only is set only when we handle -R var=val
1344 #if !BB_MMU && ENABLE_HUSH_LOCAL
1345 /* all params are used */
1346 #elif BB_MMU && ENABLE_HUSH_LOCAL
1347 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1348 set_local_var(str, flg_export, local_lvl)
1349 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1350 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1351 set_local_var(str, flg_export)
1352 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1353 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1354 set_local_var(str, flg_export, flg_read_only)
1356 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1358 struct variable **var_pp;
1359 struct variable *cur;
1363 eq_sign = strchr(str, '=');
1364 if (!eq_sign) { /* not expected to ever happen? */
1369 name_len = eq_sign - str + 1; /* including '=' */
1370 var_pp = &G.top_var;
1371 while ((cur = *var_pp) != NULL) {
1372 if (strncmp(cur->varstr, str, name_len) != 0) {
1373 var_pp = &cur->next;
1376 /* We found an existing var with this name */
1377 if (cur->flg_read_only) {
1381 bb_error_msg("%s: readonly variable", str);
1385 if (flg_export == -1) { // "&& cur->flg_export" ?
1386 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1391 #if ENABLE_HUSH_LOCAL
1392 if (cur->func_nest_level < local_lvl) {
1393 /* New variable is declared as local,
1394 * and existing one is global, or local
1395 * from enclosing function.
1396 * Remove and save old one: */
1397 *var_pp = cur->next;
1398 cur->next = *G.shadowed_vars_pp;
1399 *G.shadowed_vars_pp = cur;
1400 /* bash 3.2.33(1) and exported vars:
1402 * # f() { local z=a; env | grep ^z; }
1408 if (cur->flg_export)
1413 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1418 if (cur->max_len != 0) {
1419 if (cur->max_len >= strlen(str)) {
1420 /* This one is from startup env, reuse space */
1421 strcpy(cur->varstr, str);
1425 /* max_len == 0 signifies "malloced" var, which we can
1426 * (and has to) free */
1430 goto set_str_and_exp;
1433 /* Not found - create new variable struct */
1434 cur = xzalloc(sizeof(*cur));
1435 #if ENABLE_HUSH_LOCAL
1436 cur->func_nest_level = local_lvl;
1438 cur->next = *var_pp;
1444 cur->flg_read_only = flg_read_only;
1447 if (flg_export == 1)
1448 cur->flg_export = 1;
1449 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1450 cmdedit_update_prompt();
1451 if (cur->flg_export) {
1452 if (flg_export == -1) {
1453 cur->flg_export = 0;
1454 /* unsetenv was already done */
1456 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1457 return putenv(cur->varstr);
1463 /* Used at startup and after each cd */
1464 static void set_pwd_var(int exp)
1466 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1467 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1470 static int unset_local_var_len(const char *name, int name_len)
1472 struct variable *cur;
1473 struct variable **var_pp;
1476 return EXIT_SUCCESS;
1477 var_pp = &G.top_var;
1478 while ((cur = *var_pp) != NULL) {
1479 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1480 if (cur->flg_read_only) {
1481 bb_error_msg("%s: readonly variable", name);
1482 return EXIT_FAILURE;
1484 *var_pp = cur->next;
1485 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1486 bb_unsetenv(cur->varstr);
1487 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1488 cmdedit_update_prompt();
1492 return EXIT_SUCCESS;
1494 var_pp = &cur->next;
1496 return EXIT_SUCCESS;
1499 static int unset_local_var(const char *name)
1501 return unset_local_var_len(name, strlen(name));
1504 static void unset_vars(char **strings)
1512 const char *eq = strchrnul(*v, '=');
1513 unset_local_var_len(*v, (int)(eq - *v));
1519 #if ENABLE_SH_MATH_SUPPORT
1520 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1521 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1522 static char* FAST_FUNC endofname(const char *name)
1530 if (!is_in_name(*p))
1537 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1539 char *var = xasprintf("%s=%s", name, val);
1540 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1545 * Helpers for "var1=val1 var2=val2 cmd" feature
1547 static void add_vars(struct variable *var)
1549 struct variable *next;
1553 var->next = G.top_var;
1555 if (var->flg_export) {
1556 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1557 putenv(var->varstr);
1559 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1565 static struct variable *set_vars_and_save_old(char **strings)
1568 struct variable *old = NULL;
1574 struct variable *var_p;
1575 struct variable **var_pp;
1578 eq = strchr(*s, '=');
1581 var_pp = get_ptr_to_local_var(*s);
1584 /* Remove variable from global linked list */
1586 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1587 *var_pp = var_p->next;
1588 /* Add it to returned list */
1592 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1603 static int FAST_FUNC static_get(struct in_str *i)
1612 static int FAST_FUNC static_peek(struct in_str *i)
1617 #if ENABLE_HUSH_INTERACTIVE
1619 static void cmdedit_update_prompt(void)
1621 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1622 G.PS1 = get_local_var_value("PS1");
1625 G.PS2 = get_local_var_value("PS2");
1633 static const char* setup_prompt_string(int promptmode)
1635 const char *prompt_str;
1636 debug_printf("setup_prompt_string %d ", promptmode);
1637 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1638 /* Set up the prompt */
1639 if (promptmode == 0) { /* PS1 */
1641 /* bash uses $PWD value, even if it is set by user.
1642 * It uses current dir only if PWD is unset.
1643 * We always use current dir. */
1644 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1649 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1650 debug_printf("result '%s'\n", prompt_str);
1654 static void get_user_input(struct in_str *i)
1657 const char *prompt_str;
1659 prompt_str = setup_prompt_string(i->promptmode);
1660 #if ENABLE_FEATURE_EDITING
1661 /* Enable command line editing only while a command line
1662 * is actually being read */
1665 /* buglet: SIGINT will not make new prompt to appear _at once_,
1666 * only after <Enter>. (^C will work) */
1667 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1668 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1669 check_and_run_traps(0);
1670 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1671 i->eof_flag = (r < 0);
1672 if (i->eof_flag) { /* EOF/error detected */
1673 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1674 G.user_input_buf[1] = '\0';
1679 fputs(prompt_str, stdout);
1681 G.user_input_buf[0] = r = fgetc(i->file);
1682 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1683 //do we need check_and_run_traps(0)? (maybe only if stdin)
1684 } while (G.flag_SIGINT);
1685 i->eof_flag = (r == EOF);
1687 i->p = G.user_input_buf;
1690 #endif /* INTERACTIVE */
1692 /* This is the magic location that prints prompts
1693 * and gets data back from the user */
1694 static int FAST_FUNC file_get(struct in_str *i)
1698 /* If there is data waiting, eat it up */
1699 if (i->p && *i->p) {
1700 #if ENABLE_HUSH_INTERACTIVE
1704 if (i->eof_flag && !*i->p)
1706 /* note: ch is never NUL */
1708 /* need to double check i->file because we might be doing something
1709 * more complicated by now, like sourcing or substituting. */
1710 #if ENABLE_HUSH_INTERACTIVE
1711 if (G_interactive_fd && i->promptme && i->file == stdin) {
1714 } while (!*i->p); /* need non-empty line */
1715 i->promptmode = 1; /* PS2 */
1720 do ch = fgetc(i->file); while (ch == '\0');
1722 debug_printf("file_get: got '%c' %d\n", ch, ch);
1723 #if ENABLE_HUSH_INTERACTIVE
1730 /* All callers guarantee this routine will never
1731 * be used right after a newline, so prompting is not needed.
1733 static int FAST_FUNC file_peek(struct in_str *i)
1736 if (i->p && *i->p) {
1737 if (i->eof_flag && !i->p[1])
1740 /* note: ch is never NUL */
1742 do ch = fgetc(i->file); while (ch == '\0');
1743 i->eof_flag = (ch == EOF);
1744 i->peek_buf[0] = ch;
1745 i->peek_buf[1] = '\0';
1747 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1751 static void setup_file_in_str(struct in_str *i, FILE *f)
1753 i->peek = file_peek;
1755 #if ENABLE_HUSH_INTERACTIVE
1757 i->promptmode = 0; /* PS1 */
1763 static void setup_string_in_str(struct in_str *i, const char *s)
1765 i->peek = static_peek;
1766 i->get = static_get;
1767 #if ENABLE_HUSH_INTERACTIVE
1769 i->promptmode = 0; /* PS1 */
1779 #define B_CHUNK (32 * sizeof(char*))
1781 static void o_reset_to_empty_unquoted(o_string *o)
1789 static void o_free(o_string *o)
1792 memset(o, 0, sizeof(*o));
1795 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1800 static void o_grow_by(o_string *o, int len)
1802 if (o->length + len > o->maxlen) {
1803 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1804 o->data = xrealloc(o->data, 1 + o->maxlen);
1808 static void o_addchr(o_string *o, int ch)
1810 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1812 o->data[o->length] = ch;
1814 o->data[o->length] = '\0';
1817 static void o_addblock(o_string *o, const char *str, int len)
1820 memcpy(&o->data[o->length], str, len);
1822 o->data[o->length] = '\0';
1825 static void o_addstr(o_string *o, const char *str)
1827 o_addblock(o, str, strlen(str));
1830 static void nommu_addchr(o_string *o, int ch)
1836 # define nommu_addchr(o, str) ((void)0)
1839 static void o_addstr_with_NUL(o_string *o, const char *str)
1841 o_addblock(o, str, strlen(str) + 1);
1844 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1849 && (*str != '*' && *str != '?' && *str != '[')
1857 #undef HUSH_BRACE_EXP
1859 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
1860 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
1861 * Apparently, on unquoted $v bash still does globbing
1862 * ("v='*.txt'; echo $v" prints all .txt files),
1863 * but NOT brace expansion! Thus, there should be TWO independent
1864 * quoting mechanisms on $v expansion side: one protects
1865 * $v from brace expansion, and other additionally protects "$v" against globbing.
1866 * We have only second one.
1869 #ifdef HUSH_BRACE_EXP
1870 # define MAYBE_BRACES "{}"
1872 # define MAYBE_BRACES ""
1875 /* My analysis of quoting semantics tells me that state information
1876 * is associated with a destination, not a source.
1878 static void o_addqchr(o_string *o, int ch)
1881 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
1886 o->data[o->length] = '\\';
1889 o->data[o->length] = ch;
1891 o->data[o->length] = '\0';
1894 static void o_addQchr(o_string *o, int ch)
1897 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
1899 o->data[o->length] = '\\';
1903 o->data[o->length] = ch;
1905 o->data[o->length] = '\0';
1908 static void o_addQstr(o_string *o, const char *str, int len)
1911 o_addblock(o, str, len);
1917 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
1918 if (ordinary_cnt > len) /* paranoia */
1920 o_addblock(o, str, ordinary_cnt);
1921 if (ordinary_cnt == len)
1923 str += ordinary_cnt;
1924 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1928 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
1930 o->data[o->length] = '\\';
1934 o->data[o->length] = ch;
1936 o->data[o->length] = '\0';
1940 /* A special kind of o_string for $VAR and `cmd` expansion.
1941 * It contains char* list[] at the beginning, which is grown in 16 element
1942 * increments. Actual string data starts at the next multiple of 16 * (char*).
1943 * list[i] contains an INDEX (int!) into this string data.
1944 * It means that if list[] needs to grow, data needs to be moved higher up
1945 * but list[i]'s need not be modified.
1946 * NB: remembering how many list[i]'s you have there is crucial.
1947 * o_finalize_list() operation post-processes this structure - calculates
1948 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1950 #if DEBUG_EXPAND || DEBUG_GLOB
1951 static void debug_print_list(const char *prefix, o_string *o, int n)
1953 char **list = (char**)o->data;
1954 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1958 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1959 prefix, list, n, string_start, o->length, o->maxlen);
1962 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1963 o->data + (int)list[i] + string_start,
1964 o->data + (int)list[i] + string_start);
1968 const char *p = o->data + (int)list[n - 1] + string_start;
1970 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1974 # define debug_print_list(prefix, o, n) ((void)0)
1977 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1978 * in list[n] so that it points past last stored byte so far.
1979 * It returns n+1. */
1980 static int o_save_ptr_helper(o_string *o, int n)
1982 char **list = (char**)o->data;
1986 if (!o->has_empty_slot) {
1987 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1988 string_len = o->length - string_start;
1989 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1990 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1991 /* list[n] points to string_start, make space for 16 more pointers */
1992 o->maxlen += 0x10 * sizeof(list[0]);
1993 o->data = xrealloc(o->data, o->maxlen + 1);
1994 list = (char**)o->data;
1995 memmove(list + n + 0x10, list + n, string_len);
1996 o->length += 0x10 * sizeof(list[0]);
1998 debug_printf_list("list[%d]=%d string_start=%d\n",
1999 n, string_len, string_start);
2002 /* We have empty slot at list[n], reuse without growth */
2003 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2004 string_len = o->length - string_start;
2005 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2006 n, string_len, string_start);
2007 o->has_empty_slot = 0;
2009 list[n] = (char*)(ptrdiff_t)string_len;
2013 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2014 static int o_get_last_ptr(o_string *o, int n)
2016 char **list = (char**)o->data;
2017 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2019 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2022 #ifdef HUSH_BRACE_EXP
2023 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2024 * first, it processes even {a} (no commas), second,
2025 * I didn't manage to make it return strings when they don't match
2026 * existing files. Need to re-implement it.
2030 static int glob_needed(const char *s)
2039 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2045 /* Return pointer to next closing brace or to comma */
2046 static const char *next_brace_sub(const char *cp)
2050 while (*cp != '\0') {
2057 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2059 if (*cp++ == '{') /*}*/
2063 return *cp != '\0' ? cp : NULL;
2065 /* Recursive brace globber. Note: may garble pattern[]. */
2066 static int glob_brace(char *pattern, o_string *o, int n)
2068 char *new_pattern_buf;
2075 debug_printf_glob("glob_brace('%s')\n", pattern);
2081 if (*begin == '{') /*}*/ {
2082 /* Find the first sub-pattern and at the same time
2083 * find the rest after the closing brace */
2084 next = next_brace_sub(begin);
2086 /* An illegal expression */
2089 /*{*/ if (*next == '}') {
2090 /* "{abc}" with no commas - illegal
2091 * brace expr, disregard and skip it */
2097 if (*begin == '\\' && begin[1] != '\0')
2101 debug_printf_glob("begin:%s\n", begin);
2102 debug_printf_glob("next:%s\n", next);
2104 /* Now find the end of the whole brace expression */
2106 /*{*/ while (*rest != '}') {
2107 rest = next_brace_sub(rest);
2109 /* An illegal expression */
2112 debug_printf_glob("rest:%s\n", rest);
2114 rest_len = strlen(++rest) + 1;
2116 /* We are sure the brace expression is well-formed */
2118 /* Allocate working buffer large enough for our work */
2119 new_pattern_buf = xmalloc(strlen(pattern));
2121 /* We have a brace expression. BEGIN points to the opening {,
2122 * NEXT points past the terminator of the first element, and REST
2123 * points past the final }. We will accumulate result names from
2124 * recursive runs for each brace alternative in the buffer using
2129 /* Construct the new glob expression */
2132 mempcpy(new_pattern_buf,
2133 /* We know the prefix for all sub-patterns */
2134 pattern, begin - pattern),
2138 /* Note: glob_brace() may garble new_pattern_buf[].
2139 * That's why we re-copy prefix every time (1st memcpy above).
2141 n = glob_brace(new_pattern_buf, o, n);
2142 /*{*/ if (*next == '}') {
2143 /* We saw the last entry */
2147 next = next_brace_sub(next);
2149 free(new_pattern_buf);
2157 memset(&globdata, 0, sizeof(globdata));
2158 gr = glob(pattern, 0, NULL, &globdata);
2159 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2161 if (gr == GLOB_NOMATCH) {
2162 globfree(&globdata);
2163 /* NB: garbles parameter */
2164 unbackslash(pattern);
2165 o_addstr_with_NUL(o, pattern);
2166 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2167 return o_save_ptr_helper(o, n);
2169 if (gr == GLOB_NOSPACE)
2170 bb_error_msg_and_die(bb_msg_memory_exhausted);
2171 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2172 * but we didn't specify it. Paranoia again. */
2173 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2175 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2176 char **argv = globdata.gl_pathv;
2178 o_addstr_with_NUL(o, *argv);
2179 n = o_save_ptr_helper(o, n);
2185 globfree(&globdata);
2189 /* Performs globbing on last list[],
2190 * saving each result as a new list[].
2192 static int o_glob(o_string *o, int n)
2194 char *pattern, *copy;
2196 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2198 return o_save_ptr_helper(o, n);
2199 pattern = o->data + o_get_last_ptr(o, n);
2200 debug_printf_glob("glob pattern '%s'\n", pattern);
2201 if (!glob_needed(pattern)) {
2202 /* unbackslash last string in o in place, fix length */
2203 o->length = unbackslash(pattern) - o->data;
2204 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2205 return o_save_ptr_helper(o, n);
2208 copy = xstrdup(pattern);
2209 /* "forget" pattern in o */
2210 o->length = pattern - o->data;
2211 n = glob_brace(copy, o, n);
2214 debug_print_list("o_glob returning", o, n);
2221 static int glob_needed(const char *s)
2230 if (*s == '*' || *s == '[' || *s == '?')
2236 /* Performs globbing on last list[],
2237 * saving each result as a new list[].
2239 static int o_glob(o_string *o, int n)
2245 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2247 return o_save_ptr_helper(o, n);
2248 pattern = o->data + o_get_last_ptr(o, n);
2249 debug_printf_glob("glob pattern '%s'\n", pattern);
2250 if (!glob_needed(pattern)) {
2252 /* unbackslash last string in o in place, fix length */
2253 o->length = unbackslash(pattern) - o->data;
2254 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2255 return o_save_ptr_helper(o, n);
2258 memset(&globdata, 0, sizeof(globdata));
2259 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2260 * If we glob "*.\*" and don't find anything, we need
2261 * to fall back to using literal "*.*", but GLOB_NOCHECK
2262 * will return "*.\*"!
2264 gr = glob(pattern, 0, NULL, &globdata);
2265 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2267 if (gr == GLOB_NOMATCH) {
2268 globfree(&globdata);
2271 if (gr == GLOB_NOSPACE)
2272 bb_error_msg_and_die(bb_msg_memory_exhausted);
2273 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2274 * but we didn't specify it. Paranoia again. */
2275 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2277 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2278 char **argv = globdata.gl_pathv;
2279 /* "forget" pattern in o */
2280 o->length = pattern - o->data;
2282 o_addstr_with_NUL(o, *argv);
2283 n = o_save_ptr_helper(o, n);
2289 globfree(&globdata);
2291 debug_print_list("o_glob returning", o, n);
2297 /* If o->o_glob == 1, glob the string so far remembered.
2298 * Otherwise, just finish current list[] and start new */
2299 static int o_save_ptr(o_string *o, int n)
2301 if (o->o_glob) { /* if globbing is requested */
2302 /* If o->has_empty_slot, list[n] was already globbed
2303 * (if it was requested back then when it was filled)
2304 * so don't do that again! */
2305 if (!o->has_empty_slot)
2306 return o_glob(o, n); /* o_save_ptr_helper is inside */
2308 return o_save_ptr_helper(o, n);
2311 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2312 static char **o_finalize_list(o_string *o, int n)
2317 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2319 debug_print_list("finalized", o, n);
2320 debug_printf_expand("finalized n:%d\n", n);
2321 list = (char**)o->data;
2322 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2326 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2332 /* Expansion can recurse */
2333 #if ENABLE_HUSH_TICK
2334 static int process_command_subs(o_string *dest, const char *s);
2336 static char *expand_string_to_string(const char *str);
2338 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2339 parse_stream_dquoted(dest, input, dquote_end)
2341 static int parse_stream_dquoted(o_string *as_string,
2343 struct in_str *input,
2346 /* expand_strvec_to_strvec() takes a list of strings, expands
2347 * all variable references within and returns a pointer to
2348 * a list of expanded strings, possibly with larger number
2349 * of strings. (Think VAR="a b"; echo $VAR).
2350 * This new list is allocated as a single malloc block.
2351 * NULL-terminated list of char* pointers is at the beginning of it,
2352 * followed by strings themself.
2353 * Caller can deallocate entire list by single free(list). */
2355 /* Store given string, finalizing the word and starting new one whenever
2356 * we encounter IFS char(s). This is used for expanding variable values.
2357 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2358 static int expand_on_ifs(o_string *output, int n, const char *str)
2361 int word_len = strcspn(str, G.ifs);
2363 if (output->o_escape || !output->o_glob)
2364 o_addQstr(output, str, word_len);
2365 else /* protect backslashes against globbing up :) */
2366 o_addblock_duplicate_backslash(output, str, word_len);
2369 if (!*str) /* EOL - do not finalize word */
2371 o_addchr(output, '\0');
2372 debug_print_list("expand_on_ifs", output, n);
2373 n = o_save_ptr(output, n);
2374 str += strspn(str, G.ifs); /* skip ifs chars */
2376 debug_print_list("expand_on_ifs[1]", output, n);
2380 /* Helper to expand $((...)) and heredoc body. These act as if
2381 * they are in double quotes, with the exception that they are not :).
2382 * Just the rules are similar: "expand only $var and `cmd`"
2384 * Returns malloced string.
2385 * As an optimization, we return NULL if expansion is not needed.
2387 static char *expand_pseudo_dquoted(const char *str)
2390 struct in_str input;
2391 o_string dest = NULL_O_STRING;
2393 if (strchr(str, '$') == NULL
2394 #if ENABLE_HUSH_TICK
2395 && strchr(str, '`') == NULL
2401 /* We need to expand. Example:
2402 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2404 setup_string_in_str(&input, str);
2405 parse_stream_dquoted(NULL, &dest, &input, EOF);
2406 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2407 exp_str = expand_string_to_string(dest.data);
2408 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2409 o_free_unsafe(&dest);
2413 #if ENABLE_SH_MATH_SUPPORT
2414 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2416 arith_eval_hooks_t hooks;
2420 hooks.lookupvar = get_local_var_value;
2421 hooks.setvar = set_local_var_from_halves;
2422 hooks.endofname = endofname;
2423 exp_str = expand_pseudo_dquoted(arg);
2424 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2430 /* Expand all variable references in given string, adding words to list[]
2431 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2432 * to be filled). This routine is extremely tricky: has to deal with
2433 * variables/parameters with whitespace, $* and $@, and constructs like
2434 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2435 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2437 /* or_mask is either 0 (normal case) or 0x80 -
2438 * expansion of right-hand side of assignment == 1-element expand.
2439 * It will also do no globbing, and thus we must not backslash-quote!
2446 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2447 debug_print_list("expand_vars_to_list", output, n);
2448 n = o_save_ptr(output, n);
2449 debug_print_list("expand_vars_to_list[0]", output, n);
2451 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2454 char *to_be_freed = NULL;
2455 const char *val = NULL;
2456 #if ENABLE_HUSH_TICK
2457 o_string subst_result = NULL_O_STRING;
2459 #if ENABLE_SH_MATH_SUPPORT
2460 char arith_buf[sizeof(arith_t)*3 + 2];
2462 o_addblock(output, arg, p - arg);
2463 debug_print_list("expand_vars_to_list[1]", output, n);
2465 p = strchr(p, SPECIAL_VAR_SYMBOL);
2467 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2468 /* "$@" is special. Even if quoted, it can still
2469 * expand to nothing (not even an empty string) */
2470 if ((first_ch & 0x7f) != '@')
2471 ored_ch |= first_ch;
2473 switch (first_ch & 0x7f) {
2474 /* Highest bit in first_ch indicates that var is double-quoted */
2476 val = utoa(G.root_pid);
2478 case '!': /* bg pid */
2479 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2481 case '?': /* exitcode */
2482 val = utoa(G.last_exitcode);
2484 case '#': /* argc */
2485 if (arg[1] != SPECIAL_VAR_SYMBOL)
2486 /* actually, it's a ${#var} */
2488 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2493 if (!G.global_argv[i])
2495 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2496 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2497 smallint sv = output->o_escape;
2498 /* unquoted var's contents should be globbed, so don't escape */
2499 output->o_escape = 0;
2500 while (G.global_argv[i]) {
2501 n = expand_on_ifs(output, n, G.global_argv[i]);
2502 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2503 if (G.global_argv[i++][0] && G.global_argv[i]) {
2504 /* this argv[] is not empty and not last:
2505 * put terminating NUL, start new word */
2506 o_addchr(output, '\0');
2507 debug_print_list("expand_vars_to_list[2]", output, n);
2508 n = o_save_ptr(output, n);
2509 debug_print_list("expand_vars_to_list[3]", output, n);
2512 output->o_escape = sv;
2514 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2515 * and in this case should treat it like '$*' - see 'else...' below */
2516 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2518 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2519 if (++i >= G.global_argc)
2521 o_addchr(output, '\0');
2522 debug_print_list("expand_vars_to_list[4]", output, n);
2523 n = o_save_ptr(output, n);
2525 } else { /* quoted $*: add as one word */
2527 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2528 if (!G.global_argv[++i])
2531 o_addchr(output, G.ifs[0]);
2535 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2536 /* "Empty variable", used to make "" etc to not disappear */
2540 #if ENABLE_HUSH_TICK
2541 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2544 /* Can't just stuff it into output o_string,
2545 * expanded result may need to be globbed
2546 * and $IFS-splitted */
2547 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2548 G.last_exitcode = process_command_subs(&subst_result, arg);
2549 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
2550 val = subst_result.data;
2553 #if ENABLE_SH_MATH_SUPPORT
2554 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2558 arg++; /* skip '+' */
2559 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2560 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2561 res = expand_and_evaluate_arith(arg, &errcode);
2564 const char *msg = "error in arithmetic";
2567 msg = "exponent less than 0";
2570 msg = "divide by 0";
2573 msg = "expression recursion loop detected";
2578 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2579 sprintf(arith_buf, arith_t_fmt, res);
2584 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2587 char exp_len; /* '#' if it's ${#var} */
2589 char exp_save = exp_save; /* for compiler */
2590 char *exp_saveptr = exp_saveptr; /* points to expansion operator */
2591 char *exp_word = exp_word; /* for compiler */
2594 arg[0] = first_ch & 0x7f;
2596 /* prepare for expansions */
2599 if (exp_len == '#') {
2600 /* handle length expansion ${#var} */
2603 /* maybe handle parameter expansion */
2604 exp_saveptr = var + strcspn(var, "%#:-=+?");
2605 exp_op = exp_save = *exp_saveptr;
2607 exp_word = exp_saveptr + 1;
2608 if (exp_op == ':') {
2609 exp_op = *exp_word++;
2610 if (ENABLE_HUSH_BASH_COMPAT
2611 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2613 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2618 *exp_saveptr = '\0';
2622 /* lookup the variable in question */
2623 if (isdigit(var[0])) {
2624 /* handle_dollar() should have vetted var for us */
2626 if (i < G.global_argc)
2627 val = G.global_argv[i];
2628 /* else val remains NULL: $N with too big N */
2630 val = get_local_var_value(var);
2632 /* handle any expansions */
2633 if (exp_len == '#') {
2634 debug_printf_expand("expand: length(%s)=", val);
2635 val = utoa(val ? strlen(val) : 0);
2636 debug_printf_expand("%s\n", val);
2637 } else if (exp_op) {
2638 if (exp_op == '%' || exp_op == '#') {
2639 /* Standard-mandated substring removal ops:
2640 * ${parameter%word} - remove smallest suffix pattern
2641 * ${parameter%%word} - remove largest suffix pattern
2642 * ${parameter#word} - remove smallest prefix pattern
2643 * ${parameter##word} - remove largest prefix pattern
2645 * Word is expanded to produce a glob pattern.
2646 * Then var's value is matched to it and matching part removed.
2651 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2652 if (exp_op == *exp_word) /* ## or %% */
2654 val = to_be_freed = xstrdup(val);
2656 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2658 exp_word = exp_exp_word;
2659 loc = scan(to_be_freed, exp_word, match_at_left);
2660 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2661 // exp_op, to_be_freed, exp_word, loc);
2664 if (loc) { /* match was found */
2665 if (match_at_left) /* # or ## */
2671 } else if (exp_op == ':') {
2672 #if ENABLE_HUSH_BASH_COMPAT
2673 /* It's ${var:N[:M]} bashism.
2674 * Note that in encoded form it has TWO parts:
2675 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2680 beg = expand_and_evaluate_arith(exp_word, &errcode);
2681 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2682 *p++ = SPECIAL_VAR_SYMBOL;
2684 p = strchr(p, SPECIAL_VAR_SYMBOL);
2686 len = expand_and_evaluate_arith(exp_word, &errcode);
2687 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2689 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2690 if (beg < 0) /* bash compat */
2692 debug_printf_varexp("from val:'%s'\n", val);
2693 if (len == 0 || !val || beg >= strlen(val))
2696 /* Paranoia. What if user entered 9999999999999
2697 * which fits in arith_t but not int? */
2700 val = to_be_freed = xstrndup(val + beg, len);
2702 debug_printf_varexp("val:'%s'\n", val);
2706 die_if_script("malformed ${%s:...}", var);
2709 } else { /* one of "-=+?" */
2710 /* Standard-mandated substitution ops:
2711 * ${var?word} - indicate error if unset
2712 * If var is unset, word (or a message indicating it is unset
2713 * if word is null) is written to standard error
2714 * and the shell exits with a non-zero exit status.
2715 * Otherwise, the value of var is substituted.
2716 * ${var-word} - use default value
2717 * If var is unset, word is substituted.
2718 * ${var=word} - assign and use default value
2719 * If var is unset, word is assigned to var.
2720 * In all cases, final value of var is substituted.
2721 * ${var+word} - use alternative value
2722 * If var is unset, null is substituted.
2723 * Otherwise, word is substituted.
2725 * Word is subjected to tilde expansion, parameter expansion,
2726 * command substitution, and arithmetic expansion.
2727 * If word is not needed, it is not expanded.
2729 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2730 * but also treat null var as if it is unset.
2732 int use_word = (!val || ((exp_save == ':') && !val[0]));
2734 use_word = !use_word;
2735 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2736 (exp_save == ':') ? "true" : "false", use_word);
2738 to_be_freed = expand_pseudo_dquoted(exp_word);
2740 exp_word = to_be_freed;
2741 if (exp_op == '?') {
2742 /* mimic bash message */
2743 die_if_script("%s: %s",
2745 exp_word[0] ? exp_word : "parameter null or not set"
2747 //TODO: how interactive bash aborts expansion mid-command?
2752 if (exp_op == '=') {
2753 /* ${var=[word]} or ${var:=[word]} */
2754 if (isdigit(var[0]) || var[0] == '#') {
2755 /* mimic bash message */
2756 die_if_script("$%s: cannot assign in this way", var);
2759 char *new_var = xasprintf("%s=%s", var, val);
2760 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2766 *exp_saveptr = exp_save;
2770 #if ENABLE_HUSH_TICK
2773 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2774 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2776 /* unquoted var's contents should be globbed, so don't escape */
2777 smallint sv = output->o_escape;
2778 output->o_escape = 0;
2779 n = expand_on_ifs(output, n, val);
2781 output->o_escape = sv;
2783 } else { /* quoted $VAR, val will be appended below */
2784 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2787 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2790 o_addQstr(output, val, strlen(val));
2793 /* Do the check to avoid writing to a const string */
2794 if (*p != SPECIAL_VAR_SYMBOL)
2795 *p = SPECIAL_VAR_SYMBOL;
2797 #if ENABLE_HUSH_TICK
2798 o_free(&subst_result);
2801 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2804 debug_print_list("expand_vars_to_list[a]", output, n);
2805 /* this part is literal, and it was already pre-quoted
2806 * if needed (much earlier), do not use o_addQstr here! */
2807 o_addstr_with_NUL(output, arg);
2808 debug_print_list("expand_vars_to_list[b]", output, n);
2809 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2810 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2813 /* allow to reuse list[n] later without re-growth */
2814 output->has_empty_slot = 1;
2816 o_addchr(output, '\0');
2821 static char **expand_variables(char **argv, int or_mask)
2826 o_string output = NULL_O_STRING;
2828 if (or_mask & 0x100) {
2829 output.o_escape = 1; /* protect against globbing for "$var" */
2830 /* (unquoted $var will temporarily switch it off) */
2837 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2840 debug_print_list("expand_variables", &output, n);
2842 /* output.data (malloced in one block) gets returned in "list" */
2843 list = o_finalize_list(&output, n);
2844 debug_print_strings("expand_variables[1]", list);
2848 static char **expand_strvec_to_strvec(char **argv)
2850 return expand_variables(argv, 0x100);
2853 #if ENABLE_HUSH_BASH_COMPAT
2854 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2856 return expand_variables(argv, 0x80);
2860 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2861 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2866 o_string output = NULL_O_STRING;
2871 int is_var = is_well_formed_var_name(*v, '=');
2872 /* is_var * 0x80: singleword expansion for vars */
2873 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2875 /* Subtle! expand_vars_to_list did not glob last word yet.
2876 * It does this only when fed with further data.
2877 * Therefore we set globbing flags AFTER it, not before:
2880 /* if it is not recognizably abc=...; then: */
2881 output.o_escape = !is_var; /* protect against globbing for "$var" */
2882 /* (unquoted $var will temporarily switch it off) */
2883 output.o_glob = !is_var; /* and indeed do globbing */
2886 debug_print_list("expand_cond", &output, n);
2888 /* output.data (malloced in one block) gets returned in "list" */
2889 list = o_finalize_list(&output, n);
2890 debug_print_strings("expand_cond[1]", list);
2895 /* Used for expansion of right hand of assignments */
2896 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2898 static char *expand_string_to_string(const char *str)
2900 char *argv[2], **list;
2902 argv[0] = (char*)str;
2904 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2906 if (!list[0] || list[1])
2907 bb_error_msg_and_die("BUG in varexp2");
2908 /* actually, just move string 2*sizeof(char*) bytes back */
2909 overlapping_strcpy((char*)list, list[0]);
2910 unbackslash((char*)list);
2911 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2915 /* Used for "eval" builtin */
2916 static char* expand_strvec_to_string(char **argv)
2920 list = expand_variables(argv, 0x80);
2921 /* Convert all NULs to spaces */
2926 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2927 bb_error_msg_and_die("BUG in varexp3");
2928 /* bash uses ' ' regardless of $IFS contents */
2933 overlapping_strcpy((char*)list, list[0]);
2934 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2938 static char **expand_assignments(char **argv, int count)
2942 /* Expand assignments into one string each */
2943 for (i = 0; i < count; i++) {
2944 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2952 void re_execute_shell(char ***to_free, const char *s,
2953 char *g_argv0, char **g_argv,
2954 char **builtin_argv) NORETURN;
2956 static void reset_traps_to_defaults(void)
2958 /* This function is always called in a child shell
2959 * after fork (not vfork, NOMMU doesn't use this function).
2964 /* Child shells are not interactive.
2965 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2966 * Testcase: (while :; do :; done) + ^Z should background.
2967 * Same goes for SIGTERM, SIGHUP, SIGINT.
2969 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2970 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
2972 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2973 * Stupid. It can be done with *single* &= op, but we can't use
2974 * the fact that G.blocked_set is implemented as a bitmask
2976 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2980 /* Careful. Only if no trap or trap is not "" */
2981 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2982 sigdelset(&G.blocked_set, sig);
2989 /* Our homegrown sig mask is saner to work with :) */
2990 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2992 /* Resetting all traps to default except empty ones */
2993 mask = G.non_DFL_mask;
2994 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2995 if (!G.traps[sig] || !G.traps[sig][0])
2998 G.traps[sig] = NULL;
2999 /* There is no signal for 0 (EXIT) */
3002 /* There was a trap handler, we just removed it.
3003 * But if sig still has non-DFL handling,
3004 * we should not unblock the sig. */
3007 sigdelset(&G.blocked_set, sig);
3009 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3014 static void re_execute_shell(char ***to_free, const char *s,
3015 char *g_argv0, char **g_argv,
3016 char **builtin_argv) NORETURN;
3017 static void re_execute_shell(char ***to_free, const char *s,
3018 char *g_argv0, char **g_argv,
3019 char **builtin_argv)
3021 #define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3022 /* delims + 2 * (number of bytes in printed hex numbers) */
3023 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3024 char *heredoc_argv[4];
3025 struct variable *cur;
3026 # if ENABLE_HUSH_FUNCTIONS
3027 struct function *funcp;
3031 unsigned long long empty_trap_mask;
3033 if (!g_argv0) { /* heredoc */
3034 argv = heredoc_argv;
3035 argv[0] = (char *) G.argv0_for_re_execing;
3036 argv[1] = (char *) "-<";
3037 argv[2] = (char *) s;
3039 pp = &argv[3]; /* used as pointer to empty environment */
3045 if (pp) while (*pp++)
3048 empty_trap_mask = 0;
3051 for (sig = 1; sig < NSIG; sig++) {
3052 if (G.traps[sig] && !G.traps[sig][0])
3053 empty_trap_mask |= 1LL << sig;
3057 sprintf(param_buf, NOMMU_HACK_FMT
3058 , (unsigned) G.root_pid
3059 , (unsigned) G.root_ppid
3060 , (unsigned) G.last_bg_pid
3061 , (unsigned) G.last_exitcode
3064 IF_HUSH_LOOPS(, G.depth_of_loop)
3066 #undef NOMMU_HACK_FMT
3067 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3068 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3071 for (cur = G.top_var; cur; cur = cur->next) {
3072 if (!cur->flg_export || cur->flg_read_only)
3075 # if ENABLE_HUSH_FUNCTIONS
3076 for (funcp = G.top_func; funcp; funcp = funcp->next)
3082 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3083 *pp++ = (char *) G.argv0_for_re_execing;
3085 for (cur = G.top_var; cur; cur = cur->next) {
3086 if (cur->varstr == hush_version_str)
3088 if (cur->flg_read_only) {
3089 *pp++ = (char *) "-R";
3090 *pp++ = cur->varstr;
3091 } else if (!cur->flg_export) {
3092 *pp++ = (char *) "-V";
3093 *pp++ = cur->varstr;
3096 # if ENABLE_HUSH_FUNCTIONS
3097 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3098 *pp++ = (char *) "-F";
3099 *pp++ = funcp->name;
3100 *pp++ = funcp->body_as_string;
3103 /* We can pass activated traps here. Say, -Tnn:trap_string
3105 * However, POSIX says that subshells reset signals with traps
3107 * I tested bash-3.2 and it not only does that with true subshells
3108 * of the form ( list ), but with any forked children shells.
3109 * I set trap "echo W" WINCH; and then tried:
3111 * { echo 1; sleep 20; echo 2; } &
3112 * while true; do echo 1; sleep 20; echo 2; break; done &
3113 * true | { echo 1; sleep 20; echo 2; } | cat
3115 * In all these cases sending SIGWINCH to the child shell
3116 * did not run the trap. If I add trap "echo V" WINCH;
3117 * _inside_ group (just before echo 1), it works.
3119 * I conclude it means we don't need to pass active traps here.
3120 * Even if we would use signal handlers instead of signal masking
3121 * in order to implement trap handling,
3122 * exec syscall below resets signals to SIG_DFL for us.
3124 *pp++ = (char *) "-c";
3127 while (*++builtin_argv)
3128 *pp++ = *builtin_argv;
3129 *pp++ = (char *) "";
3134 /* *pp = NULL; - is already there */
3138 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3139 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3140 execve(bb_busybox_exec_path, argv, pp);
3141 /* Fallback. Useful for init=/bin/hush usage etc */
3142 if (argv[0][0] == '/')
3143 execve(argv[0], argv, pp);
3144 xfunc_error_retval = 127;
3145 bb_error_msg_and_die("can't re-execute the shell");
3147 #endif /* !BB_MMU */
3150 static void setup_heredoc(struct redir_struct *redir)
3152 struct fd_pair pair;
3155 /* the _body_ of heredoc (misleading field name) */
3156 const char *heredoc = redir->rd_filename;
3163 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3164 expanded = expand_pseudo_dquoted(heredoc);
3168 len = strlen(heredoc);
3170 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3172 xmove_fd(pair.rd, redir->rd_fd);
3174 /* Try writing without forking. Newer kernels have
3175 * dynamically growing pipes. Must use non-blocking write! */
3178 written = write(pair.wr, heredoc, len);
3189 ndelay_off(pair.wr);
3191 /* Okay, pipe buffer was not big enough */
3192 /* Note: we must not create a stray child (bastard? :)
3193 * for the unsuspecting parent process. Child creates a grandchild
3194 * and exits before parent execs the process which consumes heredoc
3195 * (that exec happens after we return from this function) */
3201 bb_perror_msg_and_die("vfork");
3204 disable_restore_tty_pgrp_on_exit();
3205 pid = BB_MMU ? fork() : vfork();
3207 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3211 close(redir->rd_fd); /* read side of the pipe */
3213 full_write(pair.wr, heredoc, len); /* may loop or block */
3216 /* Delegate blocking writes to another process */
3217 xmove_fd(pair.wr, STDOUT_FILENO);
3218 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3222 #if ENABLE_HUSH_FAST
3224 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3226 enable_restore_tty_pgrp_on_exit();
3232 wait(NULL); /* wait till child has died */
3235 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3236 * and stderr if they are redirected. */
3237 static int setup_redirects(struct command *prog, int squirrel[])
3240 struct redir_struct *redir;
3242 for (redir = prog->redirects; redir; redir = redir->next) {
3243 if (redir->rd_type == REDIRECT_HEREDOC2) {
3244 /* rd_fd<<HERE case */
3245 if (squirrel && redir->rd_fd < 3
3246 && squirrel[redir->rd_fd] < 0
3248 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3250 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3252 debug_printf_parse("set heredoc '%s'\n",
3253 redir->rd_filename);
3254 setup_heredoc(redir);
3258 if (redir->rd_dup == REDIRFD_TO_FILE) {
3259 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3261 if (redir->rd_filename == NULL) {
3262 /* Something went wrong in the parse.
3263 * Pretend it didn't happen */
3264 bb_error_msg("bug in redirect parse");
3267 mode = redir_table[redir->rd_type].mode;
3268 p = expand_string_to_string(redir->rd_filename);
3269 openfd = open_or_warn(p, mode);
3272 /* this could get lost if stderr has been redirected, but
3273 * bash and ash both lose it as well (though zsh doesn't!) */
3274 //what the above comment tries to say?
3278 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3279 openfd = redir->rd_dup;
3282 if (openfd != redir->rd_fd) {
3283 if (squirrel && redir->rd_fd < 3
3284 && squirrel[redir->rd_fd] < 0
3286 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3288 if (openfd == REDIRFD_CLOSE) {
3289 /* "n>-" means "close me" */
3290 close(redir->rd_fd);
3292 xdup2(openfd, redir->rd_fd);
3293 if (redir->rd_dup == REDIRFD_TO_FILE)
3301 static void restore_redirects(int squirrel[])
3304 for (i = 0; i < 3; i++) {
3307 /* We simply die on error */
3314 static void free_pipe_list(struct pipe *head);
3316 /* Return code is the exit status of the pipe */
3317 static void free_pipe(struct pipe *pi)
3320 struct command *command;
3321 struct redir_struct *r, *rnext;
3324 if (pi->stopped_cmds > 0) /* why? */
3326 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3327 for (i = 0; i < pi->num_cmds; i++) {
3328 command = &pi->cmds[i];
3329 debug_printf_clean(" command %d:\n", i);
3330 if (command->argv) {
3331 for (a = 0, p = command->argv; *p; a++, p++) {
3332 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3334 free_strings(command->argv);
3335 command->argv = NULL;
3337 /* not "else if": on syntax error, we may have both! */
3338 if (command->group) {
3339 debug_printf_clean(" begin group (cmd_type:%d)\n",
3341 free_pipe_list(command->group);
3342 debug_printf_clean(" end group\n");
3343 command->group = NULL;
3345 /* else is crucial here.
3346 * If group != NULL, child_func is meaningless */
3347 #if ENABLE_HUSH_FUNCTIONS
3348 else if (command->child_func) {
3349 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3350 command->child_func->parent_cmd = NULL;
3354 free(command->group_as_string);
3355 command->group_as_string = NULL;
3357 for (r = command->redirects; r; r = rnext) {
3358 debug_printf_clean(" redirect %d%s",
3359 r->rd_fd, redir_table[r->rd_type].descrip);
3360 /* guard against the case >$FOO, where foo is unset or blank */
3361 if (r->rd_filename) {
3362 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3363 free(r->rd_filename);
3364 r->rd_filename = NULL;
3366 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3370 command->redirects = NULL;
3372 free(pi->cmds); /* children are an array, they get freed all at once */
3380 static void free_pipe_list(struct pipe *head)
3382 struct pipe *pi, *next;
3384 for (pi = head; pi; pi = next) {
3386 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3389 debug_printf_clean("pipe followup code %d\n", pi->followup);
3391 /*pi->next = NULL;*/
3397 static int run_list(struct pipe *pi);
3399 #define parse_stream(pstring, input, end_trigger) \
3400 parse_stream(input, end_trigger)
3402 static struct pipe *parse_stream(char **pstring,
3403 struct in_str *input,
3405 static void parse_and_run_string(const char *s);
3408 static char *find_in_path(const char *arg)
3411 const char *PATH = get_local_var_value("PATH");
3417 const char *end = strchrnul(PATH, ':');
3418 int sz = end - PATH; /* must be int! */
3422 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3424 /* We have xxx::yyyy in $PATH,
3425 * it means "use current dir" */
3428 if (access(ret, F_OK) == 0)
3441 static const struct built_in_command* find_builtin_helper(const char *name,
3442 const struct built_in_command *x,
3443 const struct built_in_command *end)
3446 if (strcmp(name, x->b_cmd) != 0) {
3450 debug_printf_exec("found builtin '%s'\n", name);
3455 static const struct built_in_command* find_builtin1(const char *name)
3457 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3459 static const struct built_in_command* find_builtin(const char *name)
3461 const struct built_in_command *x = find_builtin1(name);
3464 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3467 #if ENABLE_HUSH_FUNCTIONS
3468 static struct function **find_function_slot(const char *name)
3470 struct function **funcpp = &G.top_func;
3472 if (strcmp(name, (*funcpp)->name) == 0) {
3475 funcpp = &(*funcpp)->next;
3480 static const struct function *find_function(const char *name)
3482 const struct function *funcp = *find_function_slot(name);
3484 debug_printf_exec("found function '%s'\n", name);
3488 /* Note: takes ownership on name ptr */
3489 static struct function *new_function(char *name)
3491 struct function **funcpp = find_function_slot(name);
3492 struct function *funcp = *funcpp;
3494 if (funcp != NULL) {
3495 struct command *cmd = funcp->parent_cmd;
3496 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3498 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3500 /* Note: if !funcp->body, do not free body_as_string!
3501 * This is a special case of "-F name body" function:
3502 * body_as_string was not malloced! */
3504 free_pipe_list(funcp->body);
3506 free(funcp->body_as_string);
3510 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3511 cmd->argv[0] = funcp->name;
3512 cmd->group = funcp->body;
3514 cmd->group_as_string = funcp->body_as_string;
3518 debug_printf_exec("remembering new function '%s'\n", name);
3519 funcp = *funcpp = xzalloc(sizeof(*funcp));
3520 /*funcp->next = NULL;*/
3527 static void unset_func(const char *name)
3529 struct function **funcpp = find_function_slot(name);
3530 struct function *funcp = *funcpp;
3532 if (funcp != NULL) {
3533 debug_printf_exec("freeing function '%s'\n", funcp->name);
3534 *funcpp = funcp->next;
3535 /* funcp is unlinked now, deleting it.
3536 * Note: if !funcp->body, the function was created by
3537 * "-F name body", do not free ->body_as_string
3538 * and ->name as they were not malloced. */
3540 free_pipe_list(funcp->body);
3543 free(funcp->body_as_string);
3551 #define exec_function(to_free, funcp, argv) \
3552 exec_function(funcp, argv)
3554 static void exec_function(char ***to_free,
3555 const struct function *funcp,
3556 char **argv) NORETURN;
3557 static void exec_function(char ***to_free,
3558 const struct function *funcp,
3564 argv[0] = G.global_argv[0];
3565 G.global_argv = argv;
3569 /* On MMU, funcp->body is always non-NULL */
3570 n = run_list(funcp->body);
3574 re_execute_shell(to_free,
3575 funcp->body_as_string,
3582 static int run_function(const struct function *funcp, char **argv)
3588 save_and_replace_G_args(&sv, argv);
3590 /* "we are in function, ok to use return" */
3591 sv_flg = G.flag_return_in_progress;
3592 G.flag_return_in_progress = -1;
3593 # if ENABLE_HUSH_LOCAL
3594 G.func_nest_level++;
3597 /* On MMU, funcp->body is always non-NULL */
3600 /* Function defined by -F */
3601 parse_and_run_string(funcp->body_as_string);
3602 rc = G.last_exitcode;
3606 rc = run_list(funcp->body);
3609 # if ENABLE_HUSH_LOCAL
3611 struct variable *var;
3612 struct variable **var_pp;
3614 var_pp = &G.top_var;
3615 while ((var = *var_pp) != NULL) {
3616 if (var->func_nest_level < G.func_nest_level) {
3617 var_pp = &var->next;
3621 if (var->flg_export)
3622 bb_unsetenv(var->varstr);
3623 /* Remove from global list */
3624 *var_pp = var->next;
3630 G.func_nest_level--;
3633 G.flag_return_in_progress = sv_flg;
3635 restore_G_args(&sv, argv);
3639 #endif /* ENABLE_HUSH_FUNCTIONS */
3643 #define exec_builtin(to_free, x, argv) \
3644 exec_builtin(x, argv)
3646 #define exec_builtin(to_free, x, argv) \
3647 exec_builtin(to_free, argv)
3649 static void exec_builtin(char ***to_free,
3650 const struct built_in_command *x,
3651 char **argv) NORETURN;
3652 static void exec_builtin(char ***to_free,
3653 const struct built_in_command *x,
3657 int rcode = x->b_function(argv);
3661 /* On NOMMU, we must never block!
3662 * Example: { sleep 99 | read line; } & echo Ok
3664 re_execute_shell(to_free,
3673 static void execvp_or_die(char **argv) NORETURN;
3674 static void execvp_or_die(char **argv)
3676 debug_printf_exec("execing '%s'\n", argv[0]);
3677 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3678 execvp(argv[0], argv);
3679 bb_perror_msg("can't execute '%s'", argv[0]);
3680 _exit(127); /* bash compat */
3684 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3685 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3686 #define pseudo_exec(nommu_save, command, argv_expanded) \
3687 pseudo_exec(command, argv_expanded)
3690 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3692 * Don't exit() here. If you don't exec, use _exit instead.
3693 * The at_exit handlers apparently confuse the calling process,
3694 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3695 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3696 char **argv, int assignment_cnt,
3697 char **argv_expanded) NORETURN;
3698 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3699 char **argv, int assignment_cnt,
3700 char **argv_expanded)
3704 /* Case when we are here: ... | var=val | ... */
3705 if (!argv[assignment_cnt])
3706 _exit(EXIT_SUCCESS);
3708 new_env = expand_assignments(argv, assignment_cnt);
3710 set_vars_and_save_old(new_env);
3711 free(new_env); /* optional */
3712 /* we can also destroy set_vars_and_save_old's return value,
3715 nommu_save->new_env = new_env;
3716 nommu_save->old_vars = set_vars_and_save_old(new_env);
3718 if (argv_expanded) {
3719 argv = argv_expanded;
3721 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3723 nommu_save->argv = argv;
3727 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3728 if (strchr(argv[0], '/') != NULL)
3732 /* Check if the command matches any of the builtins.
3733 * Depending on context, this might be redundant. But it's
3734 * easier to waste a few CPU cycles than it is to figure out
3735 * if this is one of those cases.
3738 /* On NOMMU, it is more expensive to re-execute shell
3739 * just in order to run echo or test builtin.
3740 * It's better to skip it here and run corresponding
3741 * non-builtin later. */
3742 const struct built_in_command *x;
3743 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3745 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3748 #if ENABLE_HUSH_FUNCTIONS
3749 /* Check if the command matches any functions */
3751 const struct function *funcp = find_function(argv[0]);
3753 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3758 #if ENABLE_FEATURE_SH_STANDALONE
3759 /* Check if the command matches any busybox applets */
3761 int a = find_applet_by_name(argv[0]);
3763 # if BB_MMU /* see above why on NOMMU it is not allowed */
3764 if (APPLET_IS_NOEXEC(a)) {
3765 debug_printf_exec("running applet '%s'\n", argv[0]);
3766 run_applet_no_and_exit(a, argv);
3769 /* Re-exec ourselves */
3770 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3771 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3772 execv(bb_busybox_exec_path, argv);
3773 /* If they called chroot or otherwise made the binary no longer
3774 * executable, fall through */
3779 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3782 execvp_or_die(argv);
3785 /* Called after [v]fork() in run_pipe
3787 static void pseudo_exec(nommu_save_t *nommu_save,
3788 struct command *command,
3789 char **argv_expanded) NORETURN;
3790 static void pseudo_exec(nommu_save_t *nommu_save,
3791 struct command *command,
3792 char **argv_expanded)
3794 if (command->argv) {
3795 pseudo_exec_argv(nommu_save, command->argv,
3796 command->assignment_cnt, argv_expanded);
3799 if (command->group) {
3800 /* Cases when we are here:
3803 * ... | ( list ) | ...
3804 * ... | { list } | ...
3808 debug_printf_exec("pseudo_exec: run_list\n");
3809 reset_traps_to_defaults();
3810 rcode = run_list(command->group);
3811 /* OK to leak memory by not calling free_pipe_list,
3812 * since this process is about to exit */
3815 re_execute_shell(&nommu_save->argv_from_re_execing,
3816 command->group_as_string,
3823 /* Case when we are here: ... | >file */
3824 debug_printf_exec("pseudo_exec'ed null command\n");
3825 _exit(EXIT_SUCCESS);
3829 static const char *get_cmdtext(struct pipe *pi)
3835 /* This is subtle. ->cmdtext is created only on first backgrounding.
3836 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3837 * On subsequent bg argv is trashed, but we won't use it */
3840 argv = pi->cmds[0].argv;
3841 if (!argv || !argv[0]) {
3842 pi->cmdtext = xzalloc(1);
3848 len += strlen(*argv) + 1;
3852 argv = pi->cmds[0].argv;
3854 len = strlen(*argv);
3855 memcpy(p, *argv, len);
3863 static void insert_bg_job(struct pipe *pi)
3865 struct pipe *job, **jobp;
3868 /* Linear search for the ID of the job to use */
3870 for (job = G.job_list; job; job = job->next)
3871 if (job->jobid >= pi->jobid)
3872 pi->jobid = job->jobid + 1;
3874 /* Add job to the list of running jobs */
3876 while ((job = *jobp) != NULL)
3878 job = *jobp = xmalloc(sizeof(*job));
3880 *job = *pi; /* physical copy */
3882 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3883 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3884 for (i = 0; i < pi->num_cmds; i++) {
3885 job->cmds[i].pid = pi->cmds[i].pid;
3886 /* all other fields are not used and stay zero */
3888 job->cmdtext = xstrdup(get_cmdtext(pi));
3890 if (G_interactive_fd)
3891 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3892 /* Last command's pid goes to $! */
3893 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3894 G.last_jobid = job->jobid;
3897 static void remove_bg_job(struct pipe *pi)
3899 struct pipe *prev_pipe;
3901 if (pi == G.job_list) {
3902 G.job_list = pi->next;
3904 prev_pipe = G.job_list;
3905 while (prev_pipe->next != pi)
3906 prev_pipe = prev_pipe->next;
3907 prev_pipe->next = pi->next;
3910 G.last_jobid = G.job_list->jobid;
3915 /* Remove a backgrounded job */
3916 static void delete_finished_bg_job(struct pipe *pi)
3919 pi->stopped_cmds = 0;
3925 /* Check to see if any processes have exited -- if they
3926 * have, figure out why and see if a job has completed */
3927 static int checkjobs(struct pipe* fg_pipe)
3937 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3939 attributes = WUNTRACED;
3940 if (fg_pipe == NULL)
3941 attributes |= WNOHANG;
3944 #if ENABLE_HUSH_FAST
3945 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3946 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3947 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3948 /* There was neither fork nor SIGCHLD since last waitpid */
3949 /* Avoid doing waitpid syscall if possible */
3950 if (!G.we_have_children) {
3954 if (fg_pipe == NULL) { /* is WNOHANG set? */
3955 /* We have children, but they did not exit
3956 * or stop yet (we saw no SIGCHLD) */
3959 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3963 /* Do we do this right?
3964 * bash-3.00# sleep 20 | false
3966 * [3]+ Stopped sleep 20 | false
3967 * bash-3.00# echo $?
3968 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3969 * [hush 1.14.0: yes we do it right]
3976 #if ENABLE_HUSH_FAST
3977 i = G.count_SIGCHLD;
3979 childpid = waitpid(-1, &status, attributes);
3980 if (childpid <= 0) {
3981 if (childpid && errno != ECHILD)
3982 bb_perror_msg("waitpid");
3983 #if ENABLE_HUSH_FAST
3984 else { /* Until next SIGCHLD, waitpid's are useless */
3985 G.we_have_children = (childpid == 0);
3986 G.handled_SIGCHLD = i;
3987 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3992 dead = WIFEXITED(status) || WIFSIGNALED(status);
3995 if (WIFSTOPPED(status))
3996 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3997 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3998 if (WIFSIGNALED(status))
3999 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4000 childpid, WTERMSIG(status), WEXITSTATUS(status));
4001 if (WIFEXITED(status))
4002 debug_printf_jobs("pid %d exited, exitcode %d\n",
4003 childpid, WEXITSTATUS(status));
4005 /* Were we asked to wait for fg pipe? */
4007 for (i = 0; i < fg_pipe->num_cmds; i++) {
4008 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4009 if (fg_pipe->cmds[i].pid != childpid)
4012 fg_pipe->cmds[i].pid = 0;
4013 fg_pipe->alive_cmds--;
4014 if (i == fg_pipe->num_cmds - 1) {
4015 /* last process gives overall exitstatus */
4016 rcode = WEXITSTATUS(status);
4017 /* bash prints killer signal's name for *last*
4018 * process in pipe (prints just newline for SIGINT).
4019 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4021 if (WIFSIGNALED(status)) {
4022 int sig = WTERMSIG(status);
4023 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4024 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4025 * Maybe we need to use sig | 128? */
4028 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4031 fg_pipe->cmds[i].is_stopped = 1;
4032 fg_pipe->stopped_cmds++;
4034 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4035 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4036 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4037 /* All processes in fg pipe have exited or stopped */
4038 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4039 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4040 * and "killall -STOP cat" */
4041 if (G_interactive_fd) {
4043 if (fg_pipe->alive_cmds)
4044 insert_bg_job(fg_pipe);
4048 if (!fg_pipe->alive_cmds)
4051 /* There are still running processes in the fg pipe */
4052 goto wait_more; /* do waitpid again */
4054 /* it wasnt fg_pipe, look for process in bg pipes */
4058 /* We asked to wait for bg or orphaned children */
4059 /* No need to remember exitcode in this case */
4060 for (pi = G.job_list; pi; pi = pi->next) {
4061 for (i = 0; i < pi->num_cmds; i++) {
4062 if (pi->cmds[i].pid == childpid)
4063 goto found_pi_and_prognum;
4066 /* Happens when shell is used as init process (init=/bin/sh) */
4067 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4068 continue; /* do waitpid again */
4070 found_pi_and_prognum:
4073 pi->cmds[i].pid = 0;
4075 if (!pi->alive_cmds) {
4076 if (G_interactive_fd)
4077 printf(JOB_STATUS_FORMAT, pi->jobid,
4078 "Done", pi->cmdtext);
4079 delete_finished_bg_job(pi);
4083 pi->cmds[i].is_stopped = 1;
4087 } /* while (waitpid succeeds)... */
4093 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4096 int rcode = checkjobs(fg_pipe);
4097 if (G_saved_tty_pgrp) {
4098 /* Job finished, move the shell to the foreground */
4099 p = getpgrp(); /* our process group id */
4100 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4101 tcsetpgrp(G_interactive_fd, p);
4107 /* Start all the jobs, but don't wait for anything to finish.
4110 * Return code is normally -1, when the caller has to wait for children
4111 * to finish to determine the exit status of the pipe. If the pipe
4112 * is a simple builtin command, however, the action is done by the
4113 * time run_pipe returns, and the exit code is provided as the
4116 * Returns -1 only if started some children. IOW: we have to
4117 * mask out retvals of builtins etc with 0xff!
4119 * The only case when we do not need to [v]fork is when the pipe
4120 * is single, non-backgrounded, non-subshell command. Examples:
4121 * cmd ; ... { list } ; ...
4122 * cmd && ... { list } && ...
4123 * cmd || ... { list } || ...
4124 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4125 * or (if SH_STANDALONE) an applet, and we can run the { list }
4126 * with run_list. If it isn't one of these, we fork and exec cmd.
4128 * Cases when we must fork:
4129 * non-single: cmd | cmd
4130 * backgrounded: cmd & { list } &
4131 * subshell: ( list ) [&]
4133 static NOINLINE int run_pipe(struct pipe *pi)
4135 static const char *const null_ptr = NULL;
4138 struct command *command;
4139 char **argv_expanded;
4142 /* it is not always needed, but we aim to smaller code */
4143 int squirrel[] = { -1, -1, -1 };
4146 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4149 IF_HUSH_JOB(pi->pgrp = -1;)
4150 pi->stopped_cmds = 0;
4151 command = &(pi->cmds[0]);
4152 argv_expanded = NULL;
4154 if (pi->num_cmds != 1
4155 || pi->followup == PIPE_BG
4156 || command->cmd_type == CMD_SUBSHELL
4163 debug_printf_exec(": group:%p argv:'%s'\n",
4164 command->group, command->argv ? command->argv[0] : "NONE");
4166 if (command->group) {
4167 #if ENABLE_HUSH_FUNCTIONS
4168 if (command->cmd_type == CMD_FUNCDEF) {
4169 /* "executing" func () { list } */
4170 struct function *funcp;
4172 funcp = new_function(command->argv[0]);
4173 /* funcp->name is already set to argv[0] */
4174 funcp->body = command->group;
4176 funcp->body_as_string = command->group_as_string;
4177 command->group_as_string = NULL;
4179 command->group = NULL;
4180 command->argv[0] = NULL;
4181 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4182 funcp->parent_cmd = command;
4183 command->child_func = funcp;
4185 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4187 return EXIT_SUCCESS;
4191 debug_printf("non-subshell group\n");
4192 rcode = 1; /* exitcode if redir failed */
4193 if (setup_redirects(command, squirrel) == 0) {
4194 debug_printf_exec(": run_list\n");
4195 rcode = run_list(command->group) & 0xff;
4197 restore_redirects(squirrel);
4198 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4200 debug_printf_exec("run_pipe: return %d\n", rcode);
4204 argv = command->argv ? command->argv : (char **) &null_ptr;
4206 const struct built_in_command *x;
4207 #if ENABLE_HUSH_FUNCTIONS
4208 const struct function *funcp;
4212 char **new_env = NULL;
4213 struct variable *old_vars = NULL;
4215 if (argv[command->assignment_cnt] == NULL) {
4216 /* Assignments, but no command */
4217 /* Ensure redirects take effect (that is, create files).
4218 * Try "a=t >file": */
4219 rcode = setup_redirects(command, squirrel);
4220 restore_redirects(squirrel);
4221 /* Set shell variables */
4223 p = expand_string_to_string(*argv);
4224 debug_printf_exec("set shell var:'%s'->'%s'\n",
4226 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4229 /* Redirect error sets $? to 1. Othervise,
4230 * if evaluating assignment value set $?, retain it.
4231 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4233 rcode = G.last_exitcode;
4234 /* Do we need to flag set_local_var() errors?
4235 * "assignment to readonly var" and "putenv error"
4237 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4239 debug_printf_exec("run_pipe: return %d\n", rcode);
4243 /* Expand the rest into (possibly) many strings each */
4245 #if ENABLE_HUSH_BASH_COMPAT
4246 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4247 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4250 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4251 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4252 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4257 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4260 /* if someone gives us an empty string: `cmd with empty output` */
4261 if (!argv_expanded[0]) {
4262 free(argv_expanded);
4264 return G.last_exitcode;
4267 x = find_builtin(argv_expanded[0]);
4268 #if ENABLE_HUSH_FUNCTIONS
4271 funcp = find_function(argv_expanded[0]);
4275 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4276 debug_printf("exec with redirects only\n");
4277 rcode = setup_redirects(command, NULL);
4278 goto clean_up_and_ret1;
4281 /* setup_redirects acts on file descriptors, not FILEs.
4282 * This is perfect for work that comes after exec().
4283 * Is it really safe for inline use? Experimentally,
4284 * things seem to work. */
4285 rcode = setup_redirects(command, squirrel);
4287 new_env = expand_assignments(argv, command->assignment_cnt);
4288 old_vars = set_vars_and_save_old(new_env);
4290 debug_printf_exec(": builtin '%s' '%s'...\n",
4291 x->b_cmd, argv_expanded[1]);
4292 rcode = x->b_function(argv_expanded) & 0xff;
4295 #if ENABLE_HUSH_FUNCTIONS
4297 # if ENABLE_HUSH_LOCAL
4298 struct variable **sv;
4299 sv = G.shadowed_vars_pp;
4300 G.shadowed_vars_pp = &old_vars;
4302 debug_printf_exec(": function '%s' '%s'...\n",
4303 funcp->name, argv_expanded[1]);
4304 rcode = run_function(funcp, argv_expanded) & 0xff;
4305 # if ENABLE_HUSH_LOCAL
4306 G.shadowed_vars_pp = sv;
4311 #if ENABLE_FEATURE_SH_STANDALONE
4314 restore_redirects(squirrel);
4315 unset_vars(new_env);
4318 free(argv_expanded);
4319 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4321 debug_printf_exec("run_pipe return %d\n", rcode);
4325 #if ENABLE_FEATURE_SH_STANDALONE
4326 i = find_applet_by_name(argv_expanded[0]);
4327 if (i >= 0 && APPLET_IS_NOFORK(i)) {
4328 rcode = setup_redirects(command, squirrel);
4330 new_env = expand_assignments(argv, command->assignment_cnt);
4331 old_vars = set_vars_and_save_old(new_env);
4332 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4333 argv_expanded[0], argv_expanded[1]);
4334 rcode = run_nofork_applet(i, argv_expanded);
4336 goto clean_up_and_ret;
4339 /* It is neither builtin nor applet. We must fork. */
4343 /* NB: argv_expanded may already be created, and that
4344 * might include `cmd` runs! Do not rerun it! We *must*
4345 * use argv_expanded if it's non-NULL */
4347 /* Going to fork a child per each pipe member */
4351 for (i = 0; i < pi->num_cmds; i++) {
4352 struct fd_pair pipefds;
4354 volatile nommu_save_t nommu_save;
4355 nommu_save.new_env = NULL;
4356 nommu_save.old_vars = NULL;
4357 nommu_save.argv = NULL;
4358 nommu_save.argv_from_re_execing = NULL;
4360 command = &(pi->cmds[i]);
4361 if (command->argv) {
4362 debug_printf_exec(": pipe member '%s' '%s'...\n",
4363 command->argv[0], command->argv[1]);
4365 debug_printf_exec(": pipe member with no argv\n");
4368 /* pipes are inserted between pairs of commands */
4371 if ((i + 1) < pi->num_cmds)
4372 xpiped_pair(pipefds);
4374 command->pid = BB_MMU ? fork() : vfork();
4375 if (!command->pid) { /* child */
4377 disable_restore_tty_pgrp_on_exit();
4378 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4380 /* Every child adds itself to new process group
4381 * with pgid == pid_of_first_child_in_pipe */
4382 if (G.run_list_level == 1 && G_interactive_fd) {
4385 if (pgrp < 0) /* true for 1st process only */
4387 if (setpgid(0, pgrp) == 0
4388 && pi->followup != PIPE_BG
4389 && G_saved_tty_pgrp /* we have ctty */
4391 /* We do it in *every* child, not just first,
4393 tcsetpgrp(G_interactive_fd, pgrp);
4397 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4398 /* 1st cmd in backgrounded pipe
4399 * should have its stdin /dev/null'ed */
4401 if (open(bb_dev_null, O_RDONLY))
4402 xopen("/", O_RDONLY);
4404 xmove_fd(nextin, 0);
4406 xmove_fd(pipefds.wr, 1);
4409 /* Like bash, explicit redirects override pipes,
4410 * and the pipe fd is available for dup'ing. */
4411 if (setup_redirects(command, NULL))
4414 /* Restore default handlers just prior to exec */
4415 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4417 /* Stores to nommu_save list of env vars putenv'ed
4418 * (NOMMU, on MMU we don't need that) */
4419 /* cast away volatility... */
4420 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4421 /* pseudo_exec() does not return */
4424 /* parent or error */
4425 #if ENABLE_HUSH_FAST
4427 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4429 enable_restore_tty_pgrp_on_exit();
4431 /* Clean up after vforked child */
4432 free(nommu_save.argv);
4433 free(nommu_save.argv_from_re_execing);
4434 unset_vars(nommu_save.new_env);
4435 add_vars(nommu_save.old_vars);
4437 free(argv_expanded);
4438 argv_expanded = NULL;
4439 if (command->pid < 0) { /* [v]fork failed */
4440 /* Clearly indicate, was it fork or vfork */
4441 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4445 /* Second and next children need to know pid of first one */
4447 pi->pgrp = command->pid;
4453 if ((i + 1) < pi->num_cmds)
4455 /* Pass read (output) pipe end to next iteration */
4456 nextin = pipefds.rd;
4459 if (!pi->alive_cmds) {
4461 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4466 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4470 #ifndef debug_print_tree
4471 static void debug_print_tree(struct pipe *pi, int lvl)
4473 static const char *const PIPE[] = {
4479 static const char *RES[] = {
4480 [RES_NONE ] = "NONE" ,
4483 [RES_THEN ] = "THEN" ,
4484 [RES_ELIF ] = "ELIF" ,
4485 [RES_ELSE ] = "ELSE" ,
4488 # if ENABLE_HUSH_LOOPS
4489 [RES_FOR ] = "FOR" ,
4490 [RES_WHILE] = "WHILE",
4491 [RES_UNTIL] = "UNTIL",
4493 [RES_DONE ] = "DONE" ,
4495 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4498 # if ENABLE_HUSH_CASE
4499 [RES_CASE ] = "CASE" ,
4500 [RES_CASE_IN ] = "CASE_IN" ,
4501 [RES_MATCH] = "MATCH",
4502 [RES_CASE_BODY] = "CASE_BODY",
4503 [RES_ESAC ] = "ESAC" ,
4505 [RES_XXXX ] = "XXXX" ,
4506 [RES_SNTX ] = "SNTX" ,
4508 static const char *const CMDTYPE[] = {
4512 # if ENABLE_HUSH_FUNCTIONS
4521 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4522 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4524 while (prn < pi->num_cmds) {
4525 struct command *command = &pi->cmds[prn];
4526 char **argv = command->argv;
4528 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4530 command->assignment_cnt);
4531 if (command->group) {
4532 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4533 CMDTYPE[command->cmd_type],
4536 , " group_as_string:", command->group_as_string
4541 debug_print_tree(command->group, lvl+1);
4545 if (argv) while (*argv) {
4546 fprintf(stderr, " '%s'", *argv);
4549 fprintf(stderr, "\n");
4556 #endif /* debug_print_tree */
4558 /* NB: called by pseudo_exec, and therefore must not modify any
4559 * global data until exec/_exit (we can be a child after vfork!) */
4560 static int run_list(struct pipe *pi)
4562 #if ENABLE_HUSH_CASE
4563 char *case_word = NULL;
4565 #if ENABLE_HUSH_LOOPS
4566 struct pipe *loop_top = NULL;
4567 char **for_lcur = NULL;
4568 char **for_list = NULL;
4570 smallint last_followup;
4572 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4573 smalluint cond_code = 0;
4575 enum { cond_code = 0 };
4578 smallint rword; /* enum reserved_style */
4579 smallint last_rword; /* ditto */
4582 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4585 #if ENABLE_HUSH_LOOPS
4586 /* Check syntax for "for" */
4587 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4588 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4590 /* current word is FOR or IN (BOLD in comments below) */
4591 if (cpipe->next == NULL) {
4592 syntax_error("malformed for");
4594 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4597 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4598 if (cpipe->next->res_word == RES_DO)
4600 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4601 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4602 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4604 syntax_error("malformed for");
4606 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4612 /* Past this point, all code paths should jump to ret: label
4613 * in order to return, no direct "return" statements please.
4614 * This helps to ensure that no memory is leaked. */
4622 last_rword = RES_XXXX;
4624 last_followup = PIPE_SEQ;
4625 rcode = G.last_exitcode;
4627 /* Go through list of pipes, (maybe) executing them. */
4628 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4632 IF_HAS_KEYWORDS(rword = pi->res_word;)
4633 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4634 rword, cond_code, last_rword);
4635 #if ENABLE_HUSH_LOOPS
4636 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4637 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4639 /* start of a loop: remember where loop starts */
4644 /* Still in the same "if...", "then..." or "do..." branch? */
4645 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4646 if ((rcode == 0 && last_followup == PIPE_OR)
4647 || (rcode != 0 && last_followup == PIPE_AND)
4649 /* It is "<true> || CMD" or "<false> && CMD"
4650 * and we should not execute CMD */
4651 debug_printf_exec("skipped cmd because of || or &&\n");
4652 last_followup = pi->followup;
4656 last_followup = pi->followup;
4657 IF_HAS_KEYWORDS(last_rword = rword;)
4660 if (rword == RES_THEN) {
4661 /* if false; then ... fi has exitcode 0! */
4662 G.last_exitcode = rcode = EXIT_SUCCESS;
4663 /* "if <false> THEN cmd": skip cmd */
4667 if (rword == RES_ELSE || rword == RES_ELIF) {
4668 /* "if <true> then ... ELSE/ELIF cmd":
4669 * skip cmd and all following ones */
4674 #if ENABLE_HUSH_LOOPS
4675 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4677 /* first loop through for */
4679 static const char encoded_dollar_at[] ALIGN1 = {
4680 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4681 }; /* encoded representation of "$@" */
4682 static const char *const encoded_dollar_at_argv[] = {
4683 encoded_dollar_at, NULL
4684 }; /* argv list with one element: "$@" */
4687 vals = (char**)encoded_dollar_at_argv;
4688 if (pi->next->res_word == RES_IN) {
4689 /* if no variable values after "in" we skip "for" */
4690 if (!pi->next->cmds[0].argv) {
4691 G.last_exitcode = rcode = EXIT_SUCCESS;
4692 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4695 vals = pi->next->cmds[0].argv;
4696 } /* else: "for var; do..." -> assume "$@" list */
4697 /* create list of variable values */
4698 debug_print_strings("for_list made from", vals);
4699 for_list = expand_strvec_to_strvec(vals);
4700 for_lcur = for_list;
4701 debug_print_strings("for_list", for_list);
4704 /* "for" loop is over, clean up */
4710 /* Insert next value from for_lcur */
4711 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4712 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4715 if (rword == RES_IN) {
4716 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4718 if (rword == RES_DONE) {
4719 continue; /* "done" has no cmds too */
4722 #if ENABLE_HUSH_CASE
4723 if (rword == RES_CASE) {
4724 case_word = expand_strvec_to_string(pi->cmds->argv);
4727 if (rword == RES_MATCH) {
4730 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4732 /* all prev words didn't match, does this one match? */
4733 argv = pi->cmds->argv;
4735 char *pattern = expand_string_to_string(*argv);
4736 /* TODO: which FNM_xxx flags to use? */
4737 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4739 if (cond_code == 0) { /* match! we will execute this branch */
4740 free(case_word); /* make future "word)" stop */
4748 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4750 continue; /* not matched yet, skip this pipe */
4753 /* Just pressing <enter> in shell should check for jobs.
4754 * OTOH, in non-interactive shell this is useless
4755 * and only leads to extra job checks */
4756 if (pi->num_cmds == 0) {
4757 if (G_interactive_fd)
4758 goto check_jobs_and_continue;
4762 /* After analyzing all keywords and conditions, we decided
4763 * to execute this pipe. NB: have to do checkjobs(NULL)
4764 * after run_pipe to collect any background children,
4765 * even if list execution is to be stopped. */
4766 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4769 #if ENABLE_HUSH_LOOPS
4770 G.flag_break_continue = 0;
4772 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4774 /* We ran a builtin, function, or group.
4775 * rcode is already known
4776 * and we don't need to wait for anything. */
4777 G.last_exitcode = rcode;
4778 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4779 check_and_run_traps(0);
4780 #if ENABLE_HUSH_LOOPS
4781 /* Was it "break" or "continue"? */
4782 if (G.flag_break_continue) {
4783 smallint fbc = G.flag_break_continue;
4784 /* We might fall into outer *loop*,
4785 * don't want to break it too */
4787 G.depth_break_continue--;
4788 if (G.depth_break_continue == 0)
4789 G.flag_break_continue = 0;
4790 /* else: e.g. "continue 2" should *break* once, *then* continue */
4791 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4792 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4793 goto check_jobs_and_break;
4794 /* "continue": simulate end of loop */
4799 #if ENABLE_HUSH_FUNCTIONS
4800 if (G.flag_return_in_progress == 1) {
4801 /* same as "goto check_jobs_and_break" */
4806 } else if (pi->followup == PIPE_BG) {
4807 /* What does bash do with attempts to background builtins? */
4808 /* even bash 3.2 doesn't do that well with nested bg:
4809 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4810 * I'm NOT treating inner &'s as jobs */
4811 check_and_run_traps(0);
4813 if (G.run_list_level == 1)
4816 G.last_exitcode = rcode = EXIT_SUCCESS;
4817 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4820 if (G.run_list_level == 1 && G_interactive_fd) {
4821 /* Waits for completion, then fg's main shell */
4822 rcode = checkjobs_and_fg_shell(pi);
4823 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4824 check_and_run_traps(0);
4827 { /* This one just waits for completion */
4828 rcode = checkjobs(pi);
4829 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4830 check_and_run_traps(0);
4832 G.last_exitcode = rcode;
4836 /* Analyze how result affects subsequent commands */
4838 if (rword == RES_IF || rword == RES_ELIF)
4841 #if ENABLE_HUSH_LOOPS
4842 /* Beware of "while false; true; do ..."! */
4843 if (pi->next && pi->next->res_word == RES_DO) {
4844 if (rword == RES_WHILE) {
4846 /* "while false; do...done" - exitcode 0 */
4847 G.last_exitcode = rcode = EXIT_SUCCESS;
4848 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4849 goto check_jobs_and_break;
4852 if (rword == RES_UNTIL) {
4854 debug_printf_exec(": until expr is true: breaking\n");
4855 check_jobs_and_break:
4863 check_jobs_and_continue:
4870 #if ENABLE_HUSH_LOOPS
4875 #if ENABLE_HUSH_CASE
4879 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4883 /* Select which version we will use */
4884 static int run_and_free_list(struct pipe *pi)
4887 debug_printf_exec("run_and_free_list entered\n");
4889 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4890 rcode = run_list(pi);
4892 /* free_pipe_list has the side effect of clearing memory.
4893 * In the long run that function can be merged with run_list,
4894 * but doing that now would hobble the debugging effort. */
4896 debug_printf_exec("run_and_free_list return %d\n", rcode);
4901 static struct pipe *new_pipe(void)
4904 pi = xzalloc(sizeof(struct pipe));
4905 /*pi->followup = 0; - deliberately invalid value */
4906 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4910 /* Command (member of a pipe) is complete, or we start a new pipe
4911 * if ctx->command is NULL.
4912 * No errors possible here.
4914 static int done_command(struct parse_context *ctx)
4916 /* The command is really already in the pipe structure, so
4917 * advance the pipe counter and make a new, null command. */
4918 struct pipe *pi = ctx->pipe;
4919 struct command *command = ctx->command;
4922 if (IS_NULL_CMD(command)) {
4923 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4927 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4928 //debug_print_tree(ctx->list_head, 20);
4930 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4933 /* Only real trickiness here is that the uncommitted
4934 * command structure is not counted in pi->num_cmds. */
4935 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4936 ctx->command = command = &pi->cmds[pi->num_cmds];
4938 memset(command, 0, sizeof(*command));
4939 return pi->num_cmds; /* used only for 0/nonzero check */
4942 static void done_pipe(struct parse_context *ctx, pipe_style type)
4946 debug_printf_parse("done_pipe entered, followup %d\n", type);
4947 /* Close previous command */
4948 not_null = done_command(ctx);
4949 ctx->pipe->followup = type;
4951 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4952 ctx->ctx_inverted = 0;
4953 ctx->pipe->res_word = ctx->ctx_res_w;
4956 /* Without this check, even just <enter> on command line generates
4957 * tree of three NOPs (!). Which is harmless but annoying.
4958 * IOW: it is safe to do it unconditionally. */
4961 || ctx->ctx_res_w == RES_FI
4963 #if ENABLE_HUSH_LOOPS
4964 || ctx->ctx_res_w == RES_DONE
4965 || ctx->ctx_res_w == RES_FOR
4966 || ctx->ctx_res_w == RES_IN
4968 #if ENABLE_HUSH_CASE
4969 || ctx->ctx_res_w == RES_ESAC
4973 debug_printf_parse("done_pipe: adding new pipe: "
4974 "not_null:%d ctx->ctx_res_w:%d\n",
4975 not_null, ctx->ctx_res_w);
4977 ctx->pipe->next = new_p;
4979 /* RES_THEN, RES_DO etc are "sticky" -
4980 * they remain set for pipes inside if/while.
4981 * This is used to control execution.
4982 * RES_FOR and RES_IN are NOT sticky (needed to support
4983 * cases where variable or value happens to match a keyword):
4985 #if ENABLE_HUSH_LOOPS
4986 if (ctx->ctx_res_w == RES_FOR
4987 || ctx->ctx_res_w == RES_IN)
4988 ctx->ctx_res_w = RES_NONE;
4990 #if ENABLE_HUSH_CASE
4991 if (ctx->ctx_res_w == RES_MATCH)
4992 ctx->ctx_res_w = RES_CASE_BODY;
4993 if (ctx->ctx_res_w == RES_CASE)
4994 ctx->ctx_res_w = RES_CASE_IN;
4996 ctx->command = NULL; /* trick done_command below */
4997 /* Create the memory for command, roughly:
4998 * ctx->pipe->cmds = new struct command;
4999 * ctx->command = &ctx->pipe->cmds[0];
5002 //debug_print_tree(ctx->list_head, 10);
5004 debug_printf_parse("done_pipe return\n");
5007 static void initialize_context(struct parse_context *ctx)
5009 memset(ctx, 0, sizeof(*ctx));
5010 ctx->pipe = ctx->list_head = new_pipe();
5011 /* Create the memory for command, roughly:
5012 * ctx->pipe->cmds = new struct command;
5013 * ctx->command = &ctx->pipe->cmds[0];
5018 /* If a reserved word is found and processed, parse context is modified
5019 * and 1 is returned.
5022 struct reserved_combo {
5025 unsigned char assignment_flag;
5029 FLAG_END = (1 << RES_NONE ),
5031 FLAG_IF = (1 << RES_IF ),
5032 FLAG_THEN = (1 << RES_THEN ),
5033 FLAG_ELIF = (1 << RES_ELIF ),
5034 FLAG_ELSE = (1 << RES_ELSE ),
5035 FLAG_FI = (1 << RES_FI ),
5037 # if ENABLE_HUSH_LOOPS
5038 FLAG_FOR = (1 << RES_FOR ),
5039 FLAG_WHILE = (1 << RES_WHILE),
5040 FLAG_UNTIL = (1 << RES_UNTIL),
5041 FLAG_DO = (1 << RES_DO ),
5042 FLAG_DONE = (1 << RES_DONE ),
5043 FLAG_IN = (1 << RES_IN ),
5045 # if ENABLE_HUSH_CASE
5046 FLAG_MATCH = (1 << RES_MATCH),
5047 FLAG_ESAC = (1 << RES_ESAC ),
5049 FLAG_START = (1 << RES_XXXX ),
5052 static const struct reserved_combo* match_reserved_word(o_string *word)
5054 /* Mostly a list of accepted follow-up reserved words.
5055 * FLAG_END means we are done with the sequence, and are ready
5056 * to turn the compound list into a command.
5057 * FLAG_START means the word must start a new compound list.
5059 static const struct reserved_combo reserved_list[] = {
5061 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5062 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5063 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5064 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5065 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5066 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5068 # if ENABLE_HUSH_LOOPS
5069 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5070 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5071 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5072 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5073 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5074 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5076 # if ENABLE_HUSH_CASE
5077 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5078 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5081 const struct reserved_combo *r;
5083 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5084 if (strcmp(word->data, r->literal) == 0)
5089 /* Return 0: not a keyword, 1: keyword
5091 static int reserved_word(o_string *word, struct parse_context *ctx)
5093 # if ENABLE_HUSH_CASE
5094 static const struct reserved_combo reserved_match = {
5095 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5098 const struct reserved_combo *r;
5102 r = match_reserved_word(word);
5106 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5107 # if ENABLE_HUSH_CASE
5108 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5109 /* "case word IN ..." - IN part starts first MATCH part */
5110 r = &reserved_match;
5113 if (r->flag == 0) { /* '!' */
5114 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5115 syntax_error("! ! command");
5116 ctx->ctx_res_w = RES_SNTX;
5118 ctx->ctx_inverted = 1;
5121 if (r->flag & FLAG_START) {
5122 struct parse_context *old;
5124 old = xmalloc(sizeof(*old));
5125 debug_printf_parse("push stack %p\n", old);
5126 *old = *ctx; /* physical copy */
5127 initialize_context(ctx);
5129 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5130 syntax_error_at(word->data);
5131 ctx->ctx_res_w = RES_SNTX;
5134 /* "{...} fi" is ok. "{...} if" is not
5136 * if { echo foo; } then { echo bar; } fi */
5137 if (ctx->command->group)
5138 done_pipe(ctx, PIPE_SEQ);
5141 ctx->ctx_res_w = r->res;
5142 ctx->old_flag = r->flag;
5143 word->o_assignment = r->assignment_flag;
5145 if (ctx->old_flag & FLAG_END) {
5146 struct parse_context *old;
5148 done_pipe(ctx, PIPE_SEQ);
5149 debug_printf_parse("pop stack %p\n", ctx->stack);
5151 old->command->group = ctx->list_head;
5152 old->command->cmd_type = CMD_NORMAL;
5154 o_addstr(&old->as_string, ctx->as_string.data);
5155 o_free_unsafe(&ctx->as_string);
5156 old->command->group_as_string = xstrdup(old->as_string.data);
5157 debug_printf_parse("pop, remembering as:'%s'\n",
5158 old->command->group_as_string);
5160 *ctx = *old; /* physical copy */
5165 #endif /* HAS_KEYWORDS */
5167 /* Word is complete, look at it and update parsing context.
5168 * Normal return is 0. Syntax errors return 1.
5169 * Note: on return, word is reset, but not o_free'd!
5171 static int done_word(o_string *word, struct parse_context *ctx)
5173 struct command *command = ctx->command;
5175 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5176 if (word->length == 0 && word->o_quoted == 0) {
5177 debug_printf_parse("done_word return 0: true null, ignored\n");
5181 if (ctx->pending_redirect) {
5182 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5183 * only if run as "bash", not "sh" */
5184 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5186 * ...the word that follows the redirection operator
5187 * shall be subjected to tilde expansion, parameter expansion,
5188 * command substitution, arithmetic expansion, and quote
5189 * removal. Pathname expansion shall not be performed
5190 * on the word by a non-interactive shell; an interactive
5191 * shell may perform it, but shall do so only when
5192 * the expansion would result in one word."
5194 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5195 /* Cater for >\file case:
5196 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5197 * Same with heredocs:
5198 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5200 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5201 unbackslash(ctx->pending_redirect->rd_filename);
5202 /* Is it <<"HEREDOC"? */
5203 if (word->o_quoted) {
5204 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5207 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5208 ctx->pending_redirect = NULL;
5210 /* If this word wasn't an assignment, next ones definitely
5211 * can't be assignments. Even if they look like ones. */
5212 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5213 && word->o_assignment != WORD_IS_KEYWORD
5215 word->o_assignment = NOT_ASSIGNMENT;
5217 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5218 command->assignment_cnt++;
5219 word->o_assignment = MAYBE_ASSIGNMENT;
5223 # if ENABLE_HUSH_CASE
5224 if (ctx->ctx_dsemicolon
5225 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5227 /* already done when ctx_dsemicolon was set to 1: */
5228 /* ctx->ctx_res_w = RES_MATCH; */
5229 ctx->ctx_dsemicolon = 0;
5232 if (!command->argv /* if it's the first word... */
5233 # if ENABLE_HUSH_LOOPS
5234 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5235 && ctx->ctx_res_w != RES_IN
5237 # if ENABLE_HUSH_CASE
5238 && ctx->ctx_res_w != RES_CASE
5241 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5242 if (reserved_word(word, ctx)) {
5243 o_reset_to_empty_unquoted(word);
5244 debug_printf_parse("done_word return %d\n",
5245 (ctx->ctx_res_w == RES_SNTX));
5246 return (ctx->ctx_res_w == RES_SNTX);
5248 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5249 if (strcmp(word->data, "export") == 0
5250 # if ENABLE_HUSH_LOCAL
5251 || strcmp(word->data, "local") == 0
5254 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5257 # if ENABLE_HUSH_BASH_COMPAT
5258 if (strcmp(word->data, "[[") == 0) {
5259 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5265 if (command->group) {
5266 /* "{ echo foo; } echo bar" - bad */
5267 syntax_error_at(word->data);
5268 debug_printf_parse("done_word return 1: syntax error, "
5269 "groups and arglists don't mix\n");
5272 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5273 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5274 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5275 /* (otherwise it's known to be not empty and is already safe) */
5277 /* exclude "$@" - it can expand to no word despite "" */
5278 char *p = word->data;
5279 while (p[0] == SPECIAL_VAR_SYMBOL
5280 && (p[1] & 0x7f) == '@'
5281 && p[2] == SPECIAL_VAR_SYMBOL
5285 if (p == word->data || p[0] != '\0') {
5286 /* saw no "$@", or not only "$@" but some
5287 * real text is there too */
5288 /* insert "empty variable" reference, this makes
5289 * e.g. "", $empty"" etc to not disappear */
5290 o_addchr(word, SPECIAL_VAR_SYMBOL);
5291 o_addchr(word, SPECIAL_VAR_SYMBOL);
5294 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5295 debug_print_strings("word appended to argv", command->argv);
5298 #if ENABLE_HUSH_LOOPS
5299 if (ctx->ctx_res_w == RES_FOR) {
5301 || !is_well_formed_var_name(command->argv[0], '\0')
5303 /* bash says just "not a valid identifier" */
5304 syntax_error("not a valid identifier in for");
5307 /* Force FOR to have just one word (variable name) */
5308 /* NB: basically, this makes hush see "for v in ..."
5309 * syntax as if it is "for v; in ...". FOR and IN become
5310 * two pipe structs in parse tree. */
5311 done_pipe(ctx, PIPE_SEQ);
5314 #if ENABLE_HUSH_CASE
5315 /* Force CASE to have just one word */
5316 if (ctx->ctx_res_w == RES_CASE) {
5317 done_pipe(ctx, PIPE_SEQ);
5321 o_reset_to_empty_unquoted(word);
5323 debug_printf_parse("done_word return 0\n");
5328 /* Peek ahead in the input to find out if we have a "&n" construct,
5329 * as in "2>&1", that represents duplicating a file descriptor.
5331 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5332 * REDIRFD_SYNTAX_ERR if syntax error,
5333 * REDIRFD_TO_FILE if no & was seen,
5334 * or the number found.
5337 #define parse_redir_right_fd(as_string, input) \
5338 parse_redir_right_fd(input)
5340 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5346 return REDIRFD_TO_FILE;
5348 ch = i_getch(input); /* get the & */
5349 nommu_addchr(as_string, ch);
5352 ch = i_getch(input);
5353 nommu_addchr(as_string, ch);
5354 return REDIRFD_CLOSE;
5358 while (ch != EOF && isdigit(ch)) {
5359 d = d*10 + (ch-'0');
5361 ch = i_getch(input);
5362 nommu_addchr(as_string, ch);
5367 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5369 bb_error_msg("ambiguous redirect");
5370 return REDIRFD_SYNTAX_ERR;
5373 /* Return code is 0 normal, 1 if a syntax error is detected
5375 static int parse_redirect(struct parse_context *ctx,
5378 struct in_str *input)
5380 struct command *command = ctx->command;
5381 struct redir_struct *redir;
5382 struct redir_struct **redirp;
5385 dup_num = REDIRFD_TO_FILE;
5386 if (style != REDIRECT_HEREDOC) {
5387 /* Check for a '>&1' type redirect */
5388 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5389 if (dup_num == REDIRFD_SYNTAX_ERR)
5392 int ch = i_peek(input);
5393 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5394 if (dup_num) { /* <<-... */
5395 ch = i_getch(input);
5396 nommu_addchr(&ctx->as_string, ch);
5401 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5402 int ch = i_peek(input);
5404 /* >|FILE redirect ("clobbering" >).
5405 * Since we do not support "set -o noclobber" yet,
5406 * >| and > are the same for now. Just eat |.
5408 ch = i_getch(input);
5409 nommu_addchr(&ctx->as_string, ch);
5413 /* Create a new redir_struct and append it to the linked list */
5414 redirp = &command->redirects;
5415 while ((redir = *redirp) != NULL) {
5416 redirp = &(redir->next);
5418 *redirp = redir = xzalloc(sizeof(*redir));
5419 /* redir->next = NULL; */
5420 /* redir->rd_filename = NULL; */
5421 redir->rd_type = style;
5422 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5424 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5425 redir_table[style].descrip);
5427 redir->rd_dup = dup_num;
5428 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5429 /* Erik had a check here that the file descriptor in question
5430 * is legit; I postpone that to "run time"
5431 * A "-" representation of "close me" shows up as a -3 here */
5432 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5433 redir->rd_fd, redir->rd_dup);
5435 /* Set ctx->pending_redirect, so we know what to do at the
5436 * end of the next parsed word. */
5437 ctx->pending_redirect = redir;
5442 /* If a redirect is immediately preceded by a number, that number is
5443 * supposed to tell which file descriptor to redirect. This routine
5444 * looks for such preceding numbers. In an ideal world this routine
5445 * needs to handle all the following classes of redirects...
5446 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5447 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5448 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5449 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5451 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5453 * ... If n is quoted, the number shall not be recognized as part of
5454 * the redirection expression. For example:
5456 * writes the character 2 into file a"
5457 * We are getting it right by setting ->o_quoted on any \<char>
5459 * A -1 return means no valid number was found,
5460 * the caller should use the appropriate default for this redirection.
5462 static int redirect_opt_num(o_string *o)
5466 if (o->data == NULL)
5468 num = bb_strtou(o->data, NULL, 10);
5469 if (errno || num < 0)
5471 o_reset_to_empty_unquoted(o);
5476 #define fetch_till_str(as_string, input, word, skip_tabs) \
5477 fetch_till_str(input, word, skip_tabs)
5479 static char *fetch_till_str(o_string *as_string,
5480 struct in_str *input,
5484 o_string heredoc = NULL_O_STRING;
5490 ch = i_getch(input);
5491 nommu_addchr(as_string, ch);
5493 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5494 heredoc.data[past_EOL] = '\0';
5495 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5496 return heredoc.data;
5499 o_addchr(&heredoc, ch);
5500 past_EOL = heredoc.length;
5503 ch = i_getch(input);
5504 nommu_addchr(as_string, ch);
5505 } while (skip_tabs && ch == '\t');
5506 } while (ch == '\n');
5509 o_free_unsafe(&heredoc);
5512 o_addchr(&heredoc, ch);
5513 nommu_addchr(as_string, ch);
5517 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5518 * and load them all. There should be exactly heredoc_cnt of them.
5520 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5522 struct pipe *pi = ctx->list_head;
5524 while (pi && heredoc_cnt) {
5526 struct command *cmd = pi->cmds;
5528 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5530 cmd->argv ? cmd->argv[0] : "NONE");
5531 for (i = 0; i < pi->num_cmds; i++) {
5532 struct redir_struct *redir = cmd->redirects;
5534 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5535 i, cmd->argv ? cmd->argv[0] : "NONE");
5537 if (redir->rd_type == REDIRECT_HEREDOC) {
5540 redir->rd_type = REDIRECT_HEREDOC2;
5541 /* redir->rd_dup is (ab)used to indicate <<- */
5542 p = fetch_till_str(&ctx->as_string, input,
5543 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5545 syntax_error("unexpected EOF in here document");
5548 free(redir->rd_filename);
5549 redir->rd_filename = p;
5552 redir = redir->next;
5559 /* Should be 0. If it isn't, it's a parse error */
5561 bb_error_msg_and_die("heredoc BUG 2");
5567 #if ENABLE_HUSH_TICK
5568 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5573 char **to_free = NULL;
5577 pid = BB_MMU ? fork() : vfork();
5579 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5581 if (pid == 0) { /* child */
5582 disable_restore_tty_pgrp_on_exit();
5583 /* Process substitution is not considered to be usual
5584 * 'command execution'.
5585 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5592 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5593 close(channel[0]); /* NB: close _first_, then move fd! */
5594 xmove_fd(channel[1], 1);
5595 /* Prevent it from trying to handle ctrl-z etc */
5596 IF_HUSH_JOB(G.run_list_level = 1;)
5597 /* Awful hack for `trap` or $(trap).
5599 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5600 * contains an example where "trap" is executed in a subshell:
5602 * save_traps=$(trap)
5604 * eval "$save_traps"
5606 * Standard does not say that "trap" in subshell shall print
5607 * parent shell's traps. It only says that its output
5608 * must have suitable form, but then, in the above example
5609 * (which is not supposed to be normative), it implies that.
5611 * bash (and probably other shell) does implement it
5612 * (traps are reset to defaults, but "trap" still shows them),
5613 * but as a result, "trap" logic is hopelessly messed up:
5616 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5617 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5618 * # true | trap <--- trap is in subshell - no output (ditto)
5619 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5620 * trap -- 'echo Ho' SIGWINCH
5621 * # echo `(trap)` <--- in subshell in subshell - output
5622 * trap -- 'echo Ho' SIGWINCH
5623 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5624 * trap -- 'echo Ho' SIGWINCH
5626 * The rules when to forget and when to not forget traps
5627 * get really complex and nonsensical.
5629 * Our solution: ONLY bare $(trap) or `trap` is special.
5631 s = skip_whitespace(s);
5632 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5634 static const char *const argv[] = { NULL, NULL };
5635 builtin_trap((char**)argv);
5636 exit(0); /* not _exit() - we need to fflush */
5639 reset_traps_to_defaults();
5640 parse_and_run_string(s);
5641 _exit(G.last_exitcode);
5643 /* We re-execute after vfork on NOMMU. This makes this script safe:
5644 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5645 * huge=`cat BIG` # was blocking here forever
5648 re_execute_shell(&to_free,
5658 # if ENABLE_HUSH_FAST
5660 //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);
5662 enable_restore_tty_pgrp_on_exit();
5667 close_on_exec_on(channel[0]);
5668 return xfdopen_for_read(channel[0]);
5671 /* Return code is exit status of the process that is run. */
5672 static int process_command_subs(o_string *dest, const char *s)
5675 struct in_str pipe_str;
5677 int status, ch, eol_cnt;
5679 fp = generate_stream_from_string(s, &pid);
5681 /* Now send results of command back into original context */
5682 setup_file_in_str(&pipe_str, fp);
5684 while ((ch = i_getch(&pipe_str)) != EOF) {
5690 o_addchr(dest, '\n');
5693 o_addQchr(dest, ch);
5696 debug_printf("done reading from `cmd` pipe, closing it\n");
5698 /* We need to extract exitcode. Test case
5699 * "true; echo `sleep 1; false` $?"
5701 safe_waitpid(pid, &status, 0);
5702 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5703 return WEXITSTATUS(status);
5705 #endif /* ENABLE_HUSH_TICK */
5707 #if !ENABLE_HUSH_FUNCTIONS
5708 #define parse_group(dest, ctx, input, ch) \
5709 parse_group(ctx, input, ch)
5711 static int parse_group(o_string *dest, struct parse_context *ctx,
5712 struct in_str *input, int ch)
5714 /* dest contains characters seen prior to ( or {.
5715 * Typically it's empty, but for function defs,
5716 * it contains function name (without '()'). */
5717 struct pipe *pipe_list;
5719 struct command *command = ctx->command;
5721 debug_printf_parse("parse_group entered\n");
5722 #if ENABLE_HUSH_FUNCTIONS
5723 if (ch == '(' && !dest->o_quoted) {
5725 if (done_word(dest, ctx))
5728 goto skip; /* (... */
5729 if (command->argv[1]) { /* word word ... (... */
5730 syntax_error_unexpected_ch('(');
5733 /* it is "word(..." or "word (..." */
5735 ch = i_getch(input);
5736 while (ch == ' ' || ch == '\t');
5738 syntax_error_unexpected_ch(ch);
5741 nommu_addchr(&ctx->as_string, ch);
5743 ch = i_getch(input);
5744 while (ch == ' ' || ch == '\t' || ch == '\n');
5746 syntax_error_unexpected_ch(ch);
5749 nommu_addchr(&ctx->as_string, ch);
5750 command->cmd_type = CMD_FUNCDEF;
5755 #if 0 /* Prevented by caller */
5756 if (command->argv /* word [word]{... */
5757 || dest->length /* word{... */
5758 || dest->o_quoted /* ""{... */
5761 debug_printf_parse("parse_group return 1: "
5762 "syntax error, groups and arglists don't mix\n");
5767 #if ENABLE_HUSH_FUNCTIONS
5773 command->cmd_type = CMD_SUBSHELL;
5775 /* bash does not allow "{echo...", requires whitespace */
5776 ch = i_getch(input);
5777 if (ch != ' ' && ch != '\t' && ch != '\n') {
5778 syntax_error_unexpected_ch(ch);
5781 nommu_addchr(&ctx->as_string, ch);
5786 # define as_string NULL
5788 char *as_string = NULL;
5790 pipe_list = parse_stream(&as_string, input, endch);
5793 o_addstr(&ctx->as_string, as_string);
5795 /* empty ()/{} or parse error? */
5796 if (!pipe_list || pipe_list == ERR_PTR) {
5797 /* parse_stream already emitted error msg */
5800 debug_printf_parse("parse_group return 1: "
5801 "parse_stream returned %p\n", pipe_list);
5804 command->group = pipe_list;
5806 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5807 command->group_as_string = as_string;
5808 debug_printf_parse("end of group, remembering as:'%s'\n",
5809 command->group_as_string);
5813 debug_printf_parse("parse_group return 0\n");
5815 /* command remains "open", available for possible redirects */
5818 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5819 /* Subroutines for copying $(...) and `...` things */
5820 static void add_till_backquote(o_string *dest, struct in_str *input);
5822 static void add_till_single_quote(o_string *dest, struct in_str *input)
5825 int ch = i_getch(input);
5827 syntax_error_unterm_ch('\'');
5828 /*xfunc_die(); - redundant */
5835 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5836 static void add_till_double_quote(o_string *dest, struct in_str *input)
5839 int ch = i_getch(input);
5841 syntax_error_unterm_ch('"');
5842 /*xfunc_die(); - redundant */
5846 if (ch == '\\') { /* \x. Copy both chars. */
5848 ch = i_getch(input);
5852 add_till_backquote(dest, input);
5856 //if (ch == '$') ...
5859 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5861 * "Within the backquoted style of command substitution, backslash
5862 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5863 * The search for the matching backquote shall be satisfied by the first
5864 * backquote found without a preceding backslash; during this search,
5865 * if a non-escaped backquote is encountered within a shell comment,
5866 * a here-document, an embedded command substitution of the $(command)
5867 * form, or a quoted string, undefined results occur. A single-quoted
5868 * or double-quoted string that begins, but does not end, within the
5869 * "`...`" sequence produces undefined results."
5871 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5873 static void add_till_backquote(o_string *dest, struct in_str *input)
5876 int ch = i_getch(input);
5878 syntax_error_unterm_ch('`');
5879 /*xfunc_die(); - redundant */
5884 /* \x. Copy both chars unless it is \` */
5885 int ch2 = i_getch(input);
5887 syntax_error_unterm_ch('`');
5888 /*xfunc_die(); - redundant */
5890 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5897 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5898 * quoting and nested ()s.
5899 * "With the $(command) style of command substitution, all characters
5900 * following the open parenthesis to the matching closing parenthesis
5901 * constitute the command. Any valid shell script can be used for command,
5902 * except a script consisting solely of redirections which produces
5903 * unspecified results."
5905 * echo $(echo '(TEST)' BEST) (TEST) BEST
5906 * echo $(echo 'TEST)' BEST) TEST) BEST
5907 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5909 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
5910 * can contain arbitrary constructs, just like $(cmd).
5911 * In bash compat mode, it needs to also be able to stop on '}' or ':'
5912 * for ${var:N[:M]} parsing.
5914 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
5915 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
5918 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
5919 #if ENABLE_HUSH_BASH_COMPAT
5920 char end_char2 = end_ch >> 8;
5922 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
5925 ch = i_getch(input);
5927 syntax_error_unterm_ch(end_ch);
5928 /*xfunc_die(); - redundant */
5930 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
5933 /* we look for closing )) of $((EXPR)) */
5934 if (i_peek(input) == end_ch) {
5935 i_getch(input); /* eat second ')' */
5940 if (ch == '(' || ch == '{') {
5941 ch = (ch == '(' ? ')' : '}');
5942 add_till_closing_bracket(dest, input, ch);
5947 add_till_single_quote(dest, input);
5952 add_till_double_quote(dest, input);
5957 add_till_backquote(dest, input);
5962 /* \x. Copy verbatim. Important for \(, \) */
5963 ch = i_getch(input);
5965 syntax_error_unterm_ch(')');
5966 /*xfunc_die(); - redundant */
5974 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5976 /* Return code: 0 for OK, 1 for syntax error */
5978 #define handle_dollar(as_string, dest, input) \
5979 handle_dollar(dest, input)
5980 #define as_string NULL
5982 static int handle_dollar(o_string *as_string,
5984 struct in_str *input)
5986 int ch = i_peek(input); /* first character after the $ */
5987 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5989 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5991 ch = i_getch(input);
5992 nommu_addchr(as_string, ch);
5994 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5996 debug_printf_parse(": '%c'\n", ch);
5997 o_addchr(dest, ch | quote_mask);
6000 if (!isalnum(ch) && ch != '_')
6002 ch = i_getch(input);
6003 nommu_addchr(as_string, ch);
6005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6006 } else if (isdigit(ch)) {
6008 ch = i_getch(input);
6009 nommu_addchr(as_string, ch);
6010 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6011 debug_printf_parse(": '%c'\n", ch);
6012 o_addchr(dest, ch | quote_mask);
6013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6014 } else switch (ch) {
6016 case '!': /* last bg pid */
6017 case '?': /* last exit code */
6018 case '#': /* number of args */
6019 case '*': /* args */
6020 case '@': /* args */
6021 goto make_one_char_var;
6023 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6025 ch = i_getch(input); /* eat '{' */
6026 nommu_addchr(as_string, ch);
6028 ch = i_getch(input); /* first char after '{' */
6029 nommu_addchr(as_string, ch);
6030 /* It should be ${?}, or ${#var},
6031 * or even ${?+subst} - operator acting on a special variable,
6032 * or the beginning of variable name.
6034 if (!strchr("$!?#*@_", ch) && !isalnum(ch)) { /* not one of those */
6036 syntax_error_unterm_str("${name}");
6037 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
6042 /* It's possible to just call add_till_closing_bracket() at this point.
6043 * However, this regresses some of our testsuite cases
6044 * which check invalid constructs like ${%}.
6045 * Oh well... let's check that the var name part is fine... */
6051 debug_printf_parse(": '%c'\n", ch);
6053 ch = i_getch(input);
6054 nommu_addchr(as_string, ch);
6058 if (!isalnum(ch) && ch != '_') {
6060 unsigned char last_ch;
6061 /* handle parameter expansions
6062 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6064 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6065 goto bad_dollar_syntax;
6068 /* Eat everything until closing '}' (or ':') */
6070 if (ENABLE_HUSH_BASH_COMPAT
6072 && !strchr("%#:-=+?"+3, i_peek(input))
6074 /* It's ${var:N[:M]} thing */
6075 end_ch = '}' * 0x100 + ':';
6080 last_ch = add_till_closing_bracket(dest, input, end_ch);
6082 o_addstr(as_string, dest->data + pos);
6083 o_addchr(as_string, last_ch);
6086 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6087 /* close the first block: */
6088 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6089 /* while parsing N from ${var:N[:M]}... */
6090 if ((end_ch & 0xff) == last_ch) {
6091 /* ...got ':' - parse the rest */
6095 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6096 o_addstr(dest, "999999999");
6101 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6104 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6108 ch = i_getch(input);
6109 nommu_addchr(as_string, ch);
6110 # if ENABLE_SH_MATH_SUPPORT
6111 if (i_peek(input) == '(') {
6112 ch = i_getch(input);
6113 nommu_addchr(as_string, ch);
6114 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6115 o_addchr(dest, /*quote_mask |*/ '+');
6118 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6121 o_addstr(as_string, dest->data + pos);
6122 o_addchr(as_string, ')');
6123 o_addchr(as_string, ')');
6126 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6130 # if ENABLE_HUSH_TICK
6131 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6132 o_addchr(dest, quote_mask | '`');
6135 add_till_closing_bracket(dest, input, ')');
6138 o_addstr(as_string, dest->data + pos);
6139 o_addchr(as_string, ')');
6142 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6148 ch = i_getch(input);
6149 nommu_addchr(as_string, ch);
6151 if (isalnum(ch)) { /* it's $_name or $_123 */
6156 /* TODO: $_ and $-: */
6157 /* $_ Shell or shell script name; or last argument of last command
6158 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6159 * but in command's env, set to full pathname used to invoke it */
6160 /* $- Option flags set by set builtin or shell options (-i etc) */
6162 o_addQchr(dest, '$');
6164 debug_printf_parse("handle_dollar return 0\n");
6170 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6171 parse_stream_dquoted(dest, input, dquote_end)
6172 #define as_string NULL
6174 static int parse_stream_dquoted(o_string *as_string,
6176 struct in_str *input,
6183 ch = i_getch(input);
6185 nommu_addchr(as_string, ch);
6186 if (ch == dquote_end) { /* may be only '"' or EOF */
6187 if (dest->o_assignment == NOT_ASSIGNMENT)
6188 dest->o_escape ^= 1;
6189 debug_printf_parse("parse_stream_dquoted return 0\n");
6192 /* note: can't move it above ch == dquote_end check! */
6194 syntax_error_unterm_ch('"');
6195 /*xfunc_die(); - redundant */
6199 next = i_peek(input);
6201 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6202 ch, ch, dest->o_escape);
6205 syntax_error("\\<eof>");
6209 * "The backslash retains its special meaning [in "..."]
6210 * only when followed by one of the following characters:
6211 * $, `, ", \, or <newline>. A double quote may be quoted
6212 * within double quotes by preceding it with a backslash."
6214 if (strchr("$`\"\\\n", next) != NULL) {
6215 ch = i_getch(input);
6217 o_addqchr(dest, ch);
6218 nommu_addchr(as_string, ch);
6221 o_addqchr(dest, '\\');
6222 nommu_addchr(as_string, '\\');
6227 if (handle_dollar(as_string, dest, input) != 0) {
6228 debug_printf_parse("parse_stream_dquoted return 1: "
6229 "handle_dollar returned non-0\n");
6234 #if ENABLE_HUSH_TICK
6236 //unsigned pos = dest->length;
6237 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6238 o_addchr(dest, 0x80 | '`');
6239 add_till_backquote(dest, input);
6240 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6241 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6245 o_addQchr(dest, ch);
6247 && (dest->o_assignment == MAYBE_ASSIGNMENT
6248 || dest->o_assignment == WORD_IS_KEYWORD)
6249 && is_well_formed_var_name(dest->data, '=')
6251 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6258 * Scan input until EOF or end_trigger char.
6259 * Return a list of pipes to execute, or NULL on EOF
6260 * or if end_trigger character is met.
6261 * On syntax error, exit is shell is not interactive,
6262 * reset parsing machinery and start parsing anew,
6263 * or return ERR_PTR.
6265 static struct pipe *parse_stream(char **pstring,
6266 struct in_str *input,
6269 struct parse_context ctx;
6270 o_string dest = NULL_O_STRING;
6274 /* Double-quote state is handled in the state variable is_in_dquote.
6275 * A single-quote triggers a bypass of the main loop until its mate is
6276 * found. When recursing, quote state is passed in via dest->o_escape.
6278 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6279 end_trigger ? end_trigger : 'X');
6282 /* If very first arg is "" or '', dest.data may end up NULL.
6283 * Preventing this: */
6284 o_addchr(&dest, '\0');
6287 G.ifs = get_local_var_value("IFS");
6292 #if ENABLE_HUSH_INTERACTIVE
6293 input->promptmode = 0; /* PS1 */
6295 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6296 initialize_context(&ctx);
6301 const char *is_special;
6305 redir_type redir_style;
6308 /* dest.o_quoted = 1; - already is (see below) */
6309 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6312 /* We reached closing '"' */
6315 ch = i_getch(input);
6316 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6317 ch, ch, dest.o_escape);
6322 syntax_error_unterm_str("here document");
6325 /* end_trigger == '}' case errors out earlier,
6326 * checking only ')' */
6327 if (end_trigger == ')') {
6328 syntax_error_unterm_ch('('); /* exits */
6329 /* goto parse_error; */
6332 if (done_word(&dest, &ctx)) {
6336 done_pipe(&ctx, PIPE_SEQ);
6338 /* If we got nothing... */
6339 /* (this makes bare "&" cmd a no-op.
6340 * bash says: "syntax error near unexpected token '&'") */
6341 if (pi->num_cmds == 0
6342 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6348 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6350 *pstring = ctx.as_string.data;
6352 o_free_unsafe(&ctx.as_string);
6355 debug_printf_parse("parse_stream return %p\n", pi);
6358 nommu_addchr(&ctx.as_string, ch);
6362 next = i_peek(input);
6364 is_special = "{}<>;&|()#'" /* special outside of "str" */
6365 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6366 /* Are { and } special here? */
6367 if (ctx.command->argv /* word [word]{... - non-special */
6368 || dest.length /* word{... - non-special */
6369 || dest.o_quoted /* ""{... - non-special */
6370 || (next != ';' /* }; - special */
6371 && next != ')' /* }) - special */
6372 && next != '&' /* }& and }&& ... - special */
6373 && next != '|' /* }|| ... - special */
6374 && !strchr(G.ifs, next) /* {word - non-special */
6377 /* They are not special, skip "{}" */
6380 is_special = strchr(is_special, ch);
6381 is_ifs = strchr(G.ifs, ch);
6383 if (!is_special && !is_ifs) { /* ordinary char */
6385 o_addQchr(&dest, ch);
6386 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6387 || dest.o_assignment == WORD_IS_KEYWORD)
6389 && is_well_formed_var_name(dest.data, '=')
6391 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6397 if (done_word(&dest, &ctx)) {
6401 #if ENABLE_HUSH_CASE
6402 /* "case ... in <newline> word) ..." -
6403 * newlines are ignored (but ';' wouldn't be) */
6404 if (ctx.command->argv == NULL
6405 && ctx.ctx_res_w == RES_MATCH
6410 /* Treat newline as a command separator. */
6411 done_pipe(&ctx, PIPE_SEQ);
6412 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6414 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6419 dest.o_assignment = MAYBE_ASSIGNMENT;
6421 /* note: if (is_ifs) continue;
6422 * will still trigger for us */
6426 /* "cmd}" or "cmd }..." without semicolon or &:
6427 * } is an ordinary char in this case, even inside { cmd; }
6428 * Pathological example: { ""}; } should exec "}" cmd
6431 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6432 || dest.length != 0 /* word} */
6433 || dest.o_quoted /* ""} */
6437 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6438 goto skip_end_trigger;
6439 /* else: } does terminate a group */
6442 if (end_trigger && end_trigger == ch
6443 && (ch != ';' || heredoc_cnt == 0)
6444 #if ENABLE_HUSH_CASE
6446 || ctx.ctx_res_w != RES_MATCH
6447 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6452 /* This is technically valid:
6453 * { cat <<HERE; }; echo Ok
6457 * but we don't support this.
6458 * We require heredoc to be in enclosing {}/(),
6461 syntax_error_unterm_str("here document");
6464 if (done_word(&dest, &ctx)) {
6467 done_pipe(&ctx, PIPE_SEQ);
6468 dest.o_assignment = MAYBE_ASSIGNMENT;
6469 /* Do we sit outside of any if's, loops or case's? */
6471 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6475 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6477 *pstring = ctx.as_string.data;
6479 o_free_unsafe(&ctx.as_string);
6482 debug_printf_parse("parse_stream return %p: "
6483 "end_trigger char found\n",
6485 return ctx.list_head;
6492 /* Catch <, > before deciding whether this word is
6493 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6496 redir_fd = redirect_opt_num(&dest);
6497 if (done_word(&dest, &ctx)) {
6500 redir_style = REDIRECT_OVERWRITE;
6502 redir_style = REDIRECT_APPEND;
6503 ch = i_getch(input);
6504 nommu_addchr(&ctx.as_string, ch);
6507 else if (next == '(') {
6508 syntax_error(">(process) not supported");
6512 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6514 continue; /* back to top of while (1) */
6516 redir_fd = redirect_opt_num(&dest);
6517 if (done_word(&dest, &ctx)) {
6520 redir_style = REDIRECT_INPUT;
6522 redir_style = REDIRECT_HEREDOC;
6524 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6525 ch = i_getch(input);
6526 nommu_addchr(&ctx.as_string, ch);
6527 } else if (next == '>') {
6528 redir_style = REDIRECT_IO;
6529 ch = i_getch(input);
6530 nommu_addchr(&ctx.as_string, ch);
6533 else if (next == '(') {
6534 syntax_error("<(process) not supported");
6538 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6540 continue; /* back to top of while (1) */
6543 if (dest.o_assignment == MAYBE_ASSIGNMENT
6544 /* check that we are not in word in "a=1 2>word b=1": */
6545 && !ctx.pending_redirect
6547 /* ch is a special char and thus this word
6548 * cannot be an assignment */
6549 dest.o_assignment = NOT_ASSIGNMENT;
6552 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6556 if (dest.length == 0) {
6559 if (ch == EOF || ch == '\n')
6562 /* note: we do not add it to &ctx.as_string */
6564 nommu_addchr(&ctx.as_string, '\n');
6566 o_addQchr(&dest, ch);
6571 syntax_error("\\<eof>");
6574 ch = i_getch(input);
6576 o_addchr(&dest, '\\');
6577 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6578 o_addchr(&dest, ch);
6579 nommu_addchr(&ctx.as_string, ch);
6580 /* Example: echo Hello \2>file
6581 * we need to know that word 2 is quoted */
6586 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6587 ctx.as_string.data[--ctx.as_string.length] = '\0';
6592 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6593 debug_printf_parse("parse_stream parse error: "
6594 "handle_dollar returned non-0\n");
6601 ch = i_getch(input);
6603 syntax_error_unterm_ch('\'');
6604 /*xfunc_die(); - redundant */
6606 nommu_addchr(&ctx.as_string, ch);
6609 o_addqchr(&dest, ch);
6614 is_in_dquote ^= 1; /* invert */
6615 if (dest.o_assignment == NOT_ASSIGNMENT)
6618 #if ENABLE_HUSH_TICK
6623 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6624 o_addchr(&dest, '`');
6628 add_till_backquote(&dest, input);
6630 o_addstr(&ctx.as_string, dest.data + pos);
6631 o_addchr(&ctx.as_string, '`');
6633 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6634 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6639 #if ENABLE_HUSH_CASE
6642 if (done_word(&dest, &ctx)) {
6645 done_pipe(&ctx, PIPE_SEQ);
6646 #if ENABLE_HUSH_CASE
6647 /* Eat multiple semicolons, detect
6648 * whether it means something special */
6653 ch = i_getch(input);
6654 nommu_addchr(&ctx.as_string, ch);
6655 if (ctx.ctx_res_w == RES_CASE_BODY) {
6656 ctx.ctx_dsemicolon = 1;
6657 ctx.ctx_res_w = RES_MATCH;
6663 /* We just finished a cmd. New one may start
6664 * with an assignment */
6665 dest.o_assignment = MAYBE_ASSIGNMENT;
6668 if (done_word(&dest, &ctx)) {
6672 ch = i_getch(input);
6673 nommu_addchr(&ctx.as_string, ch);
6674 done_pipe(&ctx, PIPE_AND);
6676 done_pipe(&ctx, PIPE_BG);
6680 if (done_word(&dest, &ctx)) {
6683 #if ENABLE_HUSH_CASE
6684 if (ctx.ctx_res_w == RES_MATCH)
6685 break; /* we are in case's "word | word)" */
6687 if (next == '|') { /* || */
6688 ch = i_getch(input);
6689 nommu_addchr(&ctx.as_string, ch);
6690 done_pipe(&ctx, PIPE_OR);
6692 /* we could pick up a file descriptor choice here
6693 * with redirect_opt_num(), but bash doesn't do it.
6694 * "echo foo 2| cat" yields "foo 2". */
6697 o_reset_to_empty_unquoted(&ctx.as_string);
6702 #if ENABLE_HUSH_CASE
6703 /* "case... in [(]word)..." - skip '(' */
6704 if (ctx.ctx_res_w == RES_MATCH
6705 && ctx.command->argv == NULL /* not (word|(... */
6706 && dest.length == 0 /* not word(... */
6707 && dest.o_quoted == 0 /* not ""(... */
6713 if (parse_group(&dest, &ctx, input, ch) != 0) {
6718 #if ENABLE_HUSH_CASE
6719 if (ctx.ctx_res_w == RES_MATCH)
6723 /* proper use of this character is caught by end_trigger:
6724 * if we see {, we call parse_group(..., end_trigger='}')
6725 * and it will match } earlier (not here). */
6726 syntax_error_unexpected_ch(ch);
6730 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6736 struct parse_context *pctx;
6737 IF_HAS_KEYWORDS(struct parse_context *p2;)
6739 /* Clean up allocated tree.
6740 * Sample for finding leaks on syntax error recovery path.
6741 * Run it from interactive shell, watch pmap `pidof hush`.
6742 * while if false; then false; fi; do break; fi
6743 * Samples to catch leaks at execution:
6744 * while if (true | {true;}); then echo ok; fi; do break; done
6745 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6749 /* Update pipe/command counts,
6750 * otherwise freeing may miss some */
6751 done_pipe(pctx, PIPE_SEQ);
6752 debug_printf_clean("freeing list %p from ctx %p\n",
6753 pctx->list_head, pctx);
6754 debug_print_tree(pctx->list_head, 0);
6755 free_pipe_list(pctx->list_head);
6756 debug_printf_clean("freed list %p\n", pctx->list_head);
6758 o_free_unsafe(&pctx->as_string);
6760 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6764 IF_HAS_KEYWORDS(pctx = p2;)
6765 } while (HAS_KEYWORDS && pctx);
6766 /* Free text, clear all dest fields */
6768 /* If we are not in top-level parse, we return,
6769 * our caller will propagate error.
6771 if (end_trigger != ';') {
6779 /* Discard cached input, force prompt */
6781 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6786 /* Executing from string: eval, sh -c '...'
6787 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6788 * end_trigger controls how often we stop parsing
6789 * NUL: parse all, execute, return
6790 * ';': parse till ';' or newline, execute, repeat till EOF
6792 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6794 /* Why we need empty flag?
6795 * An obscure corner case "false; ``; echo $?":
6796 * empty command in `` should still set $? to 0.
6797 * But we can't just set $? to 0 at the start,
6798 * this breaks "false; echo `echo $?`" case.
6802 struct pipe *pipe_list;
6804 pipe_list = parse_stream(NULL, inp, end_trigger);
6805 if (!pipe_list) { /* EOF */
6807 G.last_exitcode = 0;
6810 debug_print_tree(pipe_list, 0);
6811 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6812 run_and_free_list(pipe_list);
6817 static void parse_and_run_string(const char *s)
6819 struct in_str input;
6820 setup_string_in_str(&input, s);
6821 parse_and_run_stream(&input, '\0');
6824 static void parse_and_run_file(FILE *f)
6826 struct in_str input;
6827 setup_file_in_str(&input, f);
6828 parse_and_run_stream(&input, ';');
6831 /* Called a few times only (or even once if "sh -c") */
6832 static void init_sigmasks(void)
6836 sigset_t old_blocked_set;
6838 if (!G.inherited_set_is_saved) {
6839 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6840 G.inherited_set = G.blocked_set;
6842 old_blocked_set = G.blocked_set;
6844 mask = (1 << SIGQUIT);
6845 if (G_interactive_fd) {
6846 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6847 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6848 mask |= SPECIAL_JOB_SIGS;
6850 G.non_DFL_mask = mask;
6855 sigaddset(&G.blocked_set, sig);
6859 sigdelset(&G.blocked_set, SIGCHLD);
6861 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
6862 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6864 /* POSIX allows shell to re-enable SIGCHLD
6865 * even if it was SIG_IGN on entry */
6866 #if ENABLE_HUSH_FAST
6867 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6868 if (!G.inherited_set_is_saved)
6869 signal(SIGCHLD, SIGCHLD_handler);
6871 if (!G.inherited_set_is_saved)
6872 signal(SIGCHLD, SIG_DFL);
6875 G.inherited_set_is_saved = 1;
6880 static void maybe_set_to_sigexit(int sig)
6882 void (*handler)(int);
6883 /* non_DFL_mask'ed signals are, well, masked,
6884 * no need to set handler for them.
6886 if (!((G.non_DFL_mask >> sig) & 1)) {
6887 handler = signal(sig, sigexit);
6888 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6889 signal(sig, handler);
6892 /* Set handlers to restore tty pgrp and exit */
6893 static void set_fatal_handlers(void)
6895 /* We _must_ restore tty pgrp on fatal signals */
6897 maybe_set_to_sigexit(SIGILL );
6898 maybe_set_to_sigexit(SIGFPE );
6899 maybe_set_to_sigexit(SIGBUS );
6900 maybe_set_to_sigexit(SIGSEGV);
6901 maybe_set_to_sigexit(SIGTRAP);
6902 } /* else: hush is perfect. what SEGV? */
6903 maybe_set_to_sigexit(SIGABRT);
6904 /* bash 3.2 seems to handle these just like 'fatal' ones */
6905 maybe_set_to_sigexit(SIGPIPE);
6906 maybe_set_to_sigexit(SIGALRM);
6907 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6908 * if we aren't interactive... but in this case
6909 * we never want to restore pgrp on exit, and this fn is not called */
6910 /*maybe_set_to_sigexit(SIGHUP );*/
6911 /*maybe_set_to_sigexit(SIGTERM);*/
6912 /*maybe_set_to_sigexit(SIGINT );*/
6916 static int set_mode(const char cstate, const char mode)
6918 int state = (cstate == '-' ? 1 : 0);
6920 case 'n': G.fake_mode = state; break;
6921 case 'x': /*G.debug_mode = state;*/ break;
6922 default: return EXIT_FAILURE;
6924 return EXIT_SUCCESS;
6927 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6928 int hush_main(int argc, char **argv)
6930 static const struct variable const_shell_ver = {
6932 .varstr = (char*)hush_version_str,
6933 .max_len = 1, /* 0 can provoke free(name) */
6938 unsigned builtin_argc;
6940 struct variable *cur_var;
6943 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
6944 G.last_exitcode = EXIT_SUCCESS;
6946 G.argv0_for_re_execing = argv[0];
6948 /* Deal with HUSH_VERSION */
6949 G.shell_ver = const_shell_ver; /* copying struct here */
6950 G.top_var = &G.shell_ver;
6951 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6952 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6953 /* Initialize our shell local variables with the values
6954 * currently living in the environment */
6955 cur_var = G.top_var;
6958 char *value = strchr(*e, '=');
6959 if (value) { /* paranoia */
6960 cur_var->next = xzalloc(sizeof(*cur_var));
6961 cur_var = cur_var->next;
6962 cur_var->varstr = *e;
6963 cur_var->max_len = strlen(*e);
6964 cur_var->flg_export = 1;
6968 /* reinstate HUSH_VERSION */
6969 debug_printf_env("putenv '%s'\n", hush_version_str);
6970 putenv((char *)hush_version_str);
6973 set_pwd_var(/*exp:*/ 1);
6974 /* bash also exports SHLVL and _,
6975 * and sets (but doesn't export) the following variables:
6977 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6978 * BASH_VERSION='3.2.0(1)-release'
6980 * MACHTYPE=i386-pc-linux-gnu
6982 * HOSTNAME=<xxxxxxxxxx>
6983 * PPID=<NNNNN> - we also do it elsewhere
6994 * PIPESTATUS=([0]="0")
6995 * HISTFILE=/<xxx>/.bash_history
6999 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7001 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7011 #if ENABLE_FEATURE_EDITING
7012 G.line_input_state = new_line_input_t(FOR_SHELL);
7014 G.global_argc = argc;
7015 G.global_argv = argv;
7016 /* Initialize some more globals to non-zero values */
7017 cmdedit_update_prompt();
7019 if (setjmp(die_jmp)) {
7020 /* xfunc has failed! die die die */
7021 /* no EXIT traps, this is an escape hatch! */
7023 hush_exit(xfunc_error_retval);
7026 /* Shell is non-interactive at first. We need to call
7027 * init_sigmasks() if we are going to execute "sh <script>",
7028 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7029 * If we later decide that we are interactive, we run init_sigmasks()
7030 * in order to intercept (more) signals.
7034 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7037 opt = getopt(argc, argv, "+c:xins"
7040 # if ENABLE_HUSH_FUNCTIONS
7050 * sh ... -c 'script'
7051 * sh ... -c 'script' ARG0 [ARG1...]
7052 * On NOMMU, if builtin_argc != 0,
7053 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7054 * "" needs to be replaced with NULL
7055 * and BARGV vector fed to builtin function.
7056 * Note: the form without ARG0 never happens:
7057 * sh ... -c 'builtin' BARGV... ""
7060 G.root_pid = getpid();
7061 G.root_ppid = getppid();
7063 G.global_argv = argv + optind;
7064 G.global_argc = argc - optind;
7066 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7067 const struct built_in_command *x;
7070 x = find_builtin(optarg);
7071 if (x) { /* paranoia */
7072 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7073 G.global_argv += builtin_argc;
7074 G.global_argv[-1] = NULL; /* replace "" */
7075 G.last_exitcode = x->b_function(argv + optind - 1);
7079 if (!G.global_argv[0]) {
7080 /* -c 'script' (no params): prevent empty $0 */
7081 G.global_argv--; /* points to argv[i] of 'script' */
7082 G.global_argv[0] = argv[0];
7083 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7085 parse_and_run_string(optarg);
7088 /* Well, we cannot just declare interactiveness,
7089 * we have to have some stuff (ctty, etc) */
7090 /* G_interactive_fd++; */
7093 /* "-s" means "read from stdin", but this is how we always
7094 * operate, so simply do nothing here. */
7097 case '<': /* "big heredoc" support */
7098 full_write(STDOUT_FILENO, optarg, strlen(optarg));
7101 unsigned long long empty_trap_mask;
7103 G.root_pid = bb_strtou(optarg, &optarg, 16);
7105 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7107 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7109 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7111 builtin_argc = bb_strtou(optarg, &optarg, 16);
7113 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7114 if (empty_trap_mask != 0) {
7117 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7118 for (sig = 1; sig < NSIG; sig++) {
7119 if (empty_trap_mask & (1LL << sig)) {
7120 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7121 sigaddset(&G.blocked_set, sig);
7124 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7126 # if ENABLE_HUSH_LOOPS
7128 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7134 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7136 # if ENABLE_HUSH_FUNCTIONS
7138 struct function *funcp = new_function(optarg);
7139 /* funcp->name is already set to optarg */
7140 /* funcp->body is set to NULL. It's a special case. */
7141 funcp->body_as_string = argv[optind];
7149 if (!set_mode('-', opt))
7153 fprintf(stderr, "Usage: sh [FILE]...\n"
7154 " or: sh -c command [args]...\n\n");
7160 } /* option parsing loop */
7163 G.root_pid = getpid();
7164 G.root_ppid = getppid();
7167 /* If we are login shell... */
7168 if (argv[0] && argv[0][0] == '-') {
7170 debug_printf("sourcing /etc/profile\n");
7171 input = fopen_for_read("/etc/profile");
7172 if (input != NULL) {
7173 close_on_exec_on(fileno(input));
7175 parse_and_run_file(input);
7178 /* bash: after sourcing /etc/profile,
7179 * tries to source (in the given order):
7180 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7181 * stopping on first found. --noprofile turns this off.
7182 * bash also sources ~/.bash_logout on exit.
7183 * If called as sh, skips .bash_XXX files.
7190 * "bash <script>" (which is never interactive (unless -i?))
7191 * sources $BASH_ENV here (without scanning $PATH).
7192 * If called as sh, does the same but with $ENV.
7194 debug_printf("running script '%s'\n", argv[optind]);
7195 G.global_argv = argv + optind;
7196 G.global_argc = argc - optind;
7197 input = xfopen_for_read(argv[optind]);
7198 close_on_exec_on(fileno(input));
7200 parse_and_run_file(input);
7201 #if ENABLE_FEATURE_CLEAN_UP
7207 /* Up to here, shell was non-interactive. Now it may become one.
7208 * NB: don't forget to (re)run init_sigmasks() as needed.
7211 /* A shell is interactive if the '-i' flag was given,
7212 * or if all of the following conditions are met:
7214 * no arguments remaining or the -s flag given
7215 * standard input is a terminal
7216 * standard output is a terminal
7217 * Refer to Posix.2, the description of the 'sh' utility.
7220 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7221 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7222 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7223 if (G_saved_tty_pgrp < 0)
7224 G_saved_tty_pgrp = 0;
7226 /* try to dup stdin to high fd#, >= 255 */
7227 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7228 if (G_interactive_fd < 0) {
7229 /* try to dup to any fd */
7230 G_interactive_fd = dup(STDIN_FILENO);
7231 if (G_interactive_fd < 0) {
7233 G_interactive_fd = 0;
7234 G_saved_tty_pgrp = 0;
7237 // TODO: track & disallow any attempts of user
7238 // to (inadvertently) close/redirect G_interactive_fd
7240 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7241 if (G_interactive_fd) {
7242 close_on_exec_on(G_interactive_fd);
7244 if (G_saved_tty_pgrp) {
7245 /* If we were run as 'hush &', sleep until we are
7246 * in the foreground (tty pgrp == our pgrp).
7247 * If we get started under a job aware app (like bash),
7248 * make sure we are now in charge so we don't fight over
7249 * who gets the foreground */
7251 pid_t shell_pgrp = getpgrp();
7252 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7253 if (G_saved_tty_pgrp == shell_pgrp)
7255 /* send TTIN to ourself (should stop us) */
7256 kill(- shell_pgrp, SIGTTIN);
7260 /* Block some signals */
7263 if (G_saved_tty_pgrp) {
7264 /* Set other signals to restore saved_tty_pgrp */
7265 set_fatal_handlers();
7266 /* Put ourselves in our own process group
7267 * (bash, too, does this only if ctty is available) */
7268 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7269 /* Grab control of the terminal */
7270 tcsetpgrp(G_interactive_fd, getpid());
7272 /* -1 is special - makes xfuncs longjmp, not exit
7273 * (we reset die_sleep = 0 whereever we [v]fork) */
7274 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7278 #elif ENABLE_HUSH_INTERACTIVE
7279 /* No job control compiled in, only prompt/line editing */
7280 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7281 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7282 if (G_interactive_fd < 0) {
7283 /* try to dup to any fd */
7284 G_interactive_fd = dup(STDIN_FILENO);
7285 if (G_interactive_fd < 0)
7287 G_interactive_fd = 0;
7290 if (G_interactive_fd) {
7291 close_on_exec_on(G_interactive_fd);
7295 /* We have interactiveness code disabled */
7299 * if interactive but not a login shell, sources ~/.bashrc
7300 * (--norc turns this off, --rcfile <file> overrides)
7303 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7304 /* note: ash and hush share this string */
7305 printf("\n\n%s %s\n"
7306 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7309 "hush - the humble shell"
7313 parse_and_run_file(stdin);
7316 #if ENABLE_FEATURE_CLEAN_UP
7317 if (G.cwd != bb_msg_unknown)
7319 cur_var = G.top_var->next;
7321 struct variable *tmp = cur_var;
7322 if (!cur_var->max_len)
7323 free(cur_var->varstr);
7324 cur_var = cur_var->next;
7328 hush_exit(G.last_exitcode);
7333 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7334 int lash_main(int argc, char **argv)
7336 bb_error_msg("lash is deprecated, please use hush instead");
7337 return hush_main(argc, argv);
7342 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7343 int msh_main(int argc, char **argv)
7345 //bb_error_msg("msh is deprecated, please use hush instead");
7346 return hush_main(argc, argv);
7354 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7359 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7366 return applet_main_func(argc, argv - argc);
7369 static int FAST_FUNC builtin_test(char **argv)
7371 return run_applet_main(argv, test_main);
7374 static int FAST_FUNC builtin_echo(char **argv)
7376 return run_applet_main(argv, echo_main);
7380 static int FAST_FUNC builtin_printf(char **argv)
7382 return run_applet_main(argv, printf_main);
7386 static char **skip_dash_dash(char **argv)
7389 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7394 static int FAST_FUNC builtin_eval(char **argv)
7396 int rcode = EXIT_SUCCESS;
7398 argv = skip_dash_dash(argv);
7400 char *str = expand_strvec_to_string(argv);
7402 * eval "echo Hi; done" ("done" is syntax error):
7403 * "echo Hi" will not execute too.
7405 parse_and_run_string(str);
7407 rcode = G.last_exitcode;
7412 static int FAST_FUNC builtin_cd(char **argv)
7416 argv = skip_dash_dash(argv);
7418 if (newdir == NULL) {
7419 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7420 * bash says "bash: cd: HOME not set" and does nothing
7423 const char *home = get_local_var_value("HOME");
7424 newdir = home ? home : "/";
7426 if (chdir(newdir)) {
7427 /* Mimic bash message exactly */
7428 bb_perror_msg("cd: %s", newdir);
7429 return EXIT_FAILURE;
7431 /* Read current dir (get_cwd(1) is inside) and set PWD.
7432 * Note: do not enforce exporting. If PWD was unset or unexported,
7433 * set it again, but do not export. bash does the same.
7435 set_pwd_var(/*exp:*/ 0);
7436 return EXIT_SUCCESS;
7439 static int FAST_FUNC builtin_exec(char **argv)
7441 argv = skip_dash_dash(argv);
7442 if (argv[0] == NULL)
7443 return EXIT_SUCCESS; /* bash does this */
7445 /* Careful: we can end up here after [v]fork. Do not restore
7446 * tty pgrp then, only top-level shell process does that */
7447 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7448 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7450 /* TODO: if exec fails, bash does NOT exit! We do.
7451 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7452 * and tcsetpgrp, and this is inherently racy.
7454 execvp_or_die(argv);
7457 static int FAST_FUNC builtin_exit(char **argv)
7459 debug_printf_exec("%s()\n", __func__);
7461 /* interactive bash:
7462 * # trap "echo EEE" EXIT
7465 * There are stopped jobs.
7466 * (if there are _stopped_ jobs, running ones don't count)
7469 # EEE (then bash exits)
7471 * we can use G.exiting = -1 as indicator "last cmd was exit"
7474 /* note: EXIT trap is run by hush_exit */
7475 argv = skip_dash_dash(argv);
7476 if (argv[0] == NULL)
7477 hush_exit(G.last_exitcode);
7478 /* mimic bash: exit 123abc == exit 255 + error msg */
7479 xfunc_error_retval = 255;
7480 /* bash: exit -2 == exit 254, no error msg */
7481 hush_exit(xatoi(argv[0]) & 0xff);
7484 static void print_escaped(const char *s)
7489 const char *p = strchrnul(s, '\'');
7490 /* print 'xxxx', possibly just '' */
7491 printf("'%.*s'", (int)(p - s), s);
7496 /* s points to '; print "'''...'''" */
7498 do putchar('\''); while (*++s == '\'');
7503 #if !ENABLE_HUSH_LOCAL
7504 #define helper_export_local(argv, exp, lvl) \
7505 helper_export_local(argv, exp)
7507 static void helper_export_local(char **argv, int exp, int lvl)
7512 /* So far we do not check that name is valid (TODO?) */
7514 if (strchr(name, '=') == NULL) {
7515 struct variable *var;
7517 var = get_local_var(name);
7518 if (exp == -1) { /* unexporting? */
7519 /* export -n NAME (without =VALUE) */
7521 var->flg_export = 0;
7522 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7524 } /* else: export -n NOT_EXISTING_VAR: no-op */
7527 if (exp == 1) { /* exporting? */
7528 /* export NAME (without =VALUE) */
7530 var->flg_export = 1;
7531 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7532 putenv(var->varstr);
7536 /* Exporting non-existing variable.
7537 * bash does not put it in environment,
7538 * but remembers that it is exported,
7539 * and does put it in env when it is set later.
7540 * We just set it to "" and export. */
7541 /* Or, it's "local NAME" (without =VALUE).
7542 * bash sets the value to "". */
7543 name = xasprintf("%s=", name);
7545 /* (Un)exporting/making local NAME=VALUE */
7546 name = xstrdup(name);
7548 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7552 static int FAST_FUNC builtin_export(char **argv)
7554 unsigned opt_unexport;
7556 #if ENABLE_HUSH_EXPORT_N
7557 /* "!": do not abort on errors */
7558 opt_unexport = getopt32(argv, "!n");
7559 if (opt_unexport == (uint32_t)-1)
7560 return EXIT_FAILURE;
7567 if (argv[0] == NULL) {
7574 /* ash emits: export VAR='VAL'
7575 * bash: declare -x VAR="VAL"
7576 * we follow ash example */
7577 const char *s = *e++;
7578 const char *p = strchr(s, '=');
7580 if (!p) /* wtf? take next variable */
7583 printf("export %.*s", (int)(p - s) + 1, s);
7584 print_escaped(p + 1);
7588 /*fflush_all(); - done after each builtin anyway */
7590 return EXIT_SUCCESS;
7593 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7595 return EXIT_SUCCESS;
7598 #if ENABLE_HUSH_LOCAL
7599 static int FAST_FUNC builtin_local(char **argv)
7601 if (G.func_nest_level == 0) {
7602 bb_error_msg("%s: not in a function", argv[0]);
7603 return EXIT_FAILURE; /* bash compat */
7605 helper_export_local(argv, 0, G.func_nest_level);
7606 return EXIT_SUCCESS;
7610 static int FAST_FUNC builtin_trap(char **argv)
7616 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7621 /* No args: print all trapped */
7622 for (i = 0; i < NSIG; ++i) {
7625 print_escaped(G.traps[i]);
7626 /* note: bash adds "SIG", but only if invoked
7627 * as "bash". If called as "sh", or if set -o posix,
7628 * then it prints short signal names.
7629 * We are printing short names: */
7630 printf(" %s\n", get_signame(i));
7633 /*fflush_all(); - done after each builtin anyway */
7634 return EXIT_SUCCESS;
7638 /* If first arg is a number: reset all specified signals */
7639 sig = bb_strtou(*argv, NULL, 10);
7645 sig = get_signum(*argv++);
7646 if (sig < 0 || sig >= NSIG) {
7648 /* Mimic bash message exactly */
7649 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7654 G.traps[sig] = xstrdup(new_cmd);
7656 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
7657 get_signame(sig), sig, G.traps[sig]);
7659 /* There is no signal for 0 (EXIT) */
7664 sigaddset(&G.blocked_set, sig);
7666 /* There was a trap handler, we are removing it
7667 * (if sig has non-DFL handling,
7668 * we don't need to do anything) */
7669 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7671 sigdelset(&G.blocked_set, sig);
7674 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7678 if (!argv[1]) { /* no second arg */
7679 bb_error_msg("trap: invalid arguments");
7680 return EXIT_FAILURE;
7683 /* First arg is "-": reset all specified to default */
7684 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7685 /* Everything else: set arg as signal handler
7686 * (includes "" case, which ignores signal) */
7687 if (argv[0][0] == '-') {
7688 if (argv[0][1] == '\0') { /* "-" */
7689 /* new_cmd remains NULL: "reset these sigs" */
7692 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7695 /* else: "-something", no special meaning */
7700 goto process_sig_list;
7703 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7704 static int FAST_FUNC builtin_type(char **argv)
7706 int ret = EXIT_SUCCESS;
7712 if (0) {} /* make conditional compile easier below */
7713 /*else if (find_alias(*argv))
7714 type = "an alias";*/
7715 #if ENABLE_HUSH_FUNCTIONS
7716 else if (find_function(*argv))
7717 type = "a function";
7719 else if (find_builtin(*argv))
7720 type = "a shell builtin";
7721 else if ((path = find_in_path(*argv)) != NULL)
7724 bb_error_msg("type: %s: not found", *argv);
7729 printf("%s is %s\n", *argv, type);
7737 /* built-in 'fg' and 'bg' handler */
7738 static int FAST_FUNC builtin_fg_bg(char **argv)
7743 if (!G_interactive_fd)
7744 return EXIT_FAILURE;
7746 /* If they gave us no args, assume they want the last backgrounded task */
7748 for (pi = G.job_list; pi; pi = pi->next) {
7749 if (pi->jobid == G.last_jobid) {
7753 bb_error_msg("%s: no current job", argv[0]);
7754 return EXIT_FAILURE;
7756 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7757 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7758 return EXIT_FAILURE;
7760 for (pi = G.job_list; pi; pi = pi->next) {
7761 if (pi->jobid == jobnum) {
7765 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7766 return EXIT_FAILURE;
7768 /* TODO: bash prints a string representation
7769 * of job being foregrounded (like "sleep 1 | cat") */
7770 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7771 /* Put the job into the foreground. */
7772 tcsetpgrp(G_interactive_fd, pi->pgrp);
7775 /* Restart the processes in the job */
7776 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7777 for (i = 0; i < pi->num_cmds; i++) {
7778 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7779 pi->cmds[i].is_stopped = 0;
7781 pi->stopped_cmds = 0;
7783 i = kill(- pi->pgrp, SIGCONT);
7785 if (errno == ESRCH) {
7786 delete_finished_bg_job(pi);
7787 return EXIT_SUCCESS;
7789 bb_perror_msg("kill (SIGCONT)");
7792 if (argv[0][0] == 'f') {
7794 return checkjobs_and_fg_shell(pi);
7796 return EXIT_SUCCESS;
7800 #if ENABLE_HUSH_HELP
7801 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7803 const struct built_in_command *x;
7806 "Built-in commands:\n"
7807 "------------------\n");
7808 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7810 printf("%-10s%s\n", x->b_cmd, x->b_descr);
7813 return EXIT_SUCCESS;
7818 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7821 const char *status_string;
7823 for (job = G.job_list; job; job = job->next) {
7824 if (job->alive_cmds == job->stopped_cmds)
7825 status_string = "Stopped";
7827 status_string = "Running";
7829 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7831 return EXIT_SUCCESS;
7836 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7841 # ifdef M_TRIM_THRESHOLD
7842 /* Optional. Reduces probability of false positives */
7845 /* Crude attempt to find where "free memory" starts,
7846 * sans fragmentation. */
7848 l = (unsigned long)p;
7851 if (l < (unsigned long)p) l = (unsigned long)p;
7854 if (!G.memleak_value)
7855 G.memleak_value = l;
7857 l -= G.memleak_value;
7864 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7869 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7872 return EXIT_SUCCESS;
7875 static int FAST_FUNC builtin_read(char **argv)
7884 /* "!": do not abort on errors.
7885 * Option string must start with "sr" to match BUILTIN_READ_xxx
7887 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
7888 if (read_flags == (uint32_t)-1)
7889 return EXIT_FAILURE;
7892 r = shell_builtin_read(set_local_var_from_halves,
7894 get_local_var_value("IFS"), /* can be NULL */
7902 if ((uintptr_t)r > 1) {
7903 bb_error_msg("%s", r);
7904 r = (char*)(uintptr_t)1;
7907 return (uintptr_t)r;
7910 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7911 * built-in 'set' handler
7913 * set [-abCefhmnuvx] [-o option] [argument...]
7914 * set [+abCefhmnuvx] [+o option] [argument...]
7915 * set -- [argument...]
7918 * Implementations shall support the options in both their hyphen and
7919 * plus-sign forms. These options can also be specified as options to sh.
7921 * Write out all variables and their values: set
7922 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7923 * Turn on the -x and -v options: set -xv
7924 * Unset all positional parameters: set --
7925 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7926 * Set the positional parameters to the expansion of x, even if x expands
7927 * with a leading '-' or '+': set -- $x
7929 * So far, we only support "set -- [argument...]" and some of the short names.
7931 static int FAST_FUNC builtin_set(char **argv)
7934 char **pp, **g_argv;
7935 char *arg = *++argv;
7939 for (e = G.top_var; e; e = e->next)
7941 return EXIT_SUCCESS;
7945 if (!strcmp(arg, "--")) {
7949 if (arg[0] != '+' && arg[0] != '-')
7951 for (n = 1; arg[n]; ++n)
7952 if (set_mode(arg[0], arg[n]))
7954 } while ((arg = *++argv) != NULL);
7955 /* Now argv[0] is 1st argument */
7958 return EXIT_SUCCESS;
7961 /* NB: G.global_argv[0] ($0) is never freed/changed */
7962 g_argv = G.global_argv;
7963 if (G.global_args_malloced) {
7969 G.global_args_malloced = 1;
7970 pp = xzalloc(sizeof(pp[0]) * 2);
7971 pp[0] = g_argv[0]; /* retain $0 */
7974 /* This realloc's G.global_argv */
7975 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7982 return EXIT_SUCCESS;
7984 /* Nothing known, so abort */
7986 bb_error_msg("set: %s: invalid option", arg);
7987 return EXIT_FAILURE;
7990 static int FAST_FUNC builtin_shift(char **argv)
7993 argv = skip_dash_dash(argv);
7997 if (n >= 0 && n < G.global_argc) {
7998 if (G.global_args_malloced) {
8001 free(G.global_argv[m++]);
8004 memmove(&G.global_argv[1], &G.global_argv[n+1],
8005 G.global_argc * sizeof(G.global_argv[0]));
8006 return EXIT_SUCCESS;
8008 return EXIT_FAILURE;
8011 static int FAST_FUNC builtin_source(char **argv)
8013 char *arg_path, *filename;
8016 #if ENABLE_HUSH_FUNCTIONS
8020 argv = skip_dash_dash(argv);
8023 /* bash says: "bash: .: filename argument required" */
8024 return 2; /* bash compat */
8027 if (!strchr(filename, '/')) {
8028 arg_path = find_in_path(filename);
8030 filename = arg_path;
8032 input = fopen_or_warn(filename, "r");
8035 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8036 return EXIT_FAILURE;
8038 close_on_exec_on(fileno(input));
8040 #if ENABLE_HUSH_FUNCTIONS
8041 sv_flg = G.flag_return_in_progress;
8042 /* "we are inside sourced file, ok to use return" */
8043 G.flag_return_in_progress = -1;
8045 save_and_replace_G_args(&sv, argv);
8047 parse_and_run_file(input);
8050 restore_G_args(&sv, argv);
8051 #if ENABLE_HUSH_FUNCTIONS
8052 G.flag_return_in_progress = sv_flg;
8055 return G.last_exitcode;
8058 static int FAST_FUNC builtin_umask(char **argv)
8064 argv = skip_dash_dash(argv);
8066 mode_t old_mask = mask;
8069 rc = bb_parse_mode(argv[0], &mask);
8074 * bash: umask: 'q': invalid symbolic mode operator
8075 * bash: umask: 999: octal number out of range
8077 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8082 printf("%04o\n", (unsigned) mask);
8083 /* fall through and restore mask which we set to 0 */
8087 return !rc; /* rc != 0 - success */
8090 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8091 static int FAST_FUNC builtin_unset(char **argv)
8096 /* "!": do not abort on errors */
8097 /* "+": stop at 1st non-option */
8098 opts = getopt32(argv, "!+vf");
8099 if (opts == (unsigned)-1)
8100 return EXIT_FAILURE;
8102 bb_error_msg("unset: -v and -f are exclusive");
8103 return EXIT_FAILURE;
8109 if (!(opts & 2)) { /* not -f */
8110 if (unset_local_var(*argv)) {
8111 /* unset <nonexistent_var> doesn't fail.
8112 * Error is when one tries to unset RO var.
8113 * Message was printed by unset_local_var. */
8117 #if ENABLE_HUSH_FUNCTIONS
8127 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8128 static int FAST_FUNC builtin_wait(char **argv)
8130 int ret = EXIT_SUCCESS;
8133 argv = skip_dash_dash(argv);
8134 if (argv[0] == NULL) {
8135 /* Don't care about wait results */
8136 /* Note 1: must wait until there are no more children */
8137 /* Note 2: must be interruptible */
8139 * $ sleep 3 & sleep 6 & wait
8144 * $ sleep 3 & sleep 6 & wait
8148 * ^C <-- after ~4 sec from keyboard
8151 sigaddset(&G.blocked_set, SIGCHLD);
8152 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8155 if (errno == ECHILD)
8157 /* Wait for SIGCHLD or any other signal of interest */
8158 /* sigtimedwait with infinite timeout: */
8159 sig = sigwaitinfo(&G.blocked_set, NULL);
8161 sig = check_and_run_traps(sig);
8162 if (sig && sig != SIGCHLD) { /* see note 2 */
8168 sigdelset(&G.blocked_set, SIGCHLD);
8169 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8173 /* This is probably buggy wrt interruptible-ness */
8175 pid_t pid = bb_strtou(*argv, NULL, 10);
8177 /* mimic bash message */
8178 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8179 return EXIT_FAILURE;
8181 if (waitpid(pid, &status, 0) == pid) {
8182 if (WIFSIGNALED(status))
8183 ret = 128 + WTERMSIG(status);
8184 else if (WIFEXITED(status))
8185 ret = WEXITSTATUS(status);
8189 bb_perror_msg("wait %s", *argv);
8198 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8199 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8202 def = bb_strtou(argv[1], NULL, 10);
8203 if (errno || def < def_min || argv[2]) {
8204 bb_error_msg("%s: bad arguments", argv[0]);
8212 #if ENABLE_HUSH_LOOPS
8213 static int FAST_FUNC builtin_break(char **argv)
8216 if (G.depth_of_loop == 0) {
8217 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8218 return EXIT_SUCCESS; /* bash compat */
8220 G.flag_break_continue++; /* BC_BREAK = 1 */
8222 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8223 if (depth == UINT_MAX)
8224 G.flag_break_continue = BC_BREAK;
8225 if (G.depth_of_loop < depth)
8226 G.depth_break_continue = G.depth_of_loop;
8228 return EXIT_SUCCESS;
8231 static int FAST_FUNC builtin_continue(char **argv)
8233 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8234 return builtin_break(argv);
8238 #if ENABLE_HUSH_FUNCTIONS
8239 static int FAST_FUNC builtin_return(char **argv)
8243 if (G.flag_return_in_progress != -1) {
8244 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8245 return EXIT_FAILURE; /* bash compat */
8248 G.flag_return_in_progress = 1;
8251 * out of range: wraps around at 256, does not error out
8252 * non-numeric param:
8253 * f() { false; return qwe; }; f; echo $?
8254 * bash: return: qwe: numeric argument required <== we do this
8255 * 255 <== we also do this
8257 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);