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 * subst operator: ${var/[/]expr/expr}
54 * brace expansion: one/{two,three,four}
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
67 * export builtin should be special, its arguments are assignments
68 * and therefore expansion of them should be "one-word" expansion:
69 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
71 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
72 * ls: cannot access i=a: No such file or directory
73 * ls: cannot access b: No such file or directory
74 * Note1: same applies to local builtin.
75 * Note2: bash 3.2.33(1) does this only if export word itself
77 * $ export i=`echo 'aaa bbb'`; echo "$i"
79 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #include <malloc.h> /* for malloc_trim */
87 /* #include <dmalloc.h> */
92 #include "shell_common.h"
95 #if ENABLE_HUSH_RANDOM_SUPPORT
98 # define CLEAR_RANDOM_T(rnd) ((void)0)
101 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
106 #define LEAK_HUNTING 0
107 #define BUILD_AS_NOMMU 0
108 /* Enable/disable sanity checks. Ok to enable in production,
109 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
110 * Keeping 1 for now even in released versions.
113 /* Slightly bigger (+200 bytes), but faster hush.
114 * So far it only enables a trick with counting SIGCHLDs and forks,
115 * which allows us to do fewer waitpid's.
116 * (we can detect a case where neither forks were done nor SIGCHLDs happened
117 * and therefore waitpid will return the same result as last time)
119 #define ENABLE_HUSH_FAST 0
120 /* TODO: implement simplified code for users which do not need ${var%...} ops
121 * So far ${var%...} ops are always enabled:
123 #define ENABLE_HUSH_DOLLAR_OPS 1
128 # undef USE_FOR_NOMMU
131 # define USE_FOR_NOMMU(...) __VA_ARGS__
132 # define USE_FOR_MMU(...)
135 #include "NUM_APPLETS.h"
137 /* STANDALONE does not make sense, and won't compile */
138 # undef CONFIG_FEATURE_SH_STANDALONE
139 # undef ENABLE_FEATURE_SH_STANDALONE
140 # undef IF_FEATURE_SH_STANDALONE
141 # undef IF_NOT_FEATURE_SH_STANDALONE
142 # define ENABLE_FEATURE_SH_STANDALONE 0
143 # define IF_FEATURE_SH_STANDALONE(...)
144 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
147 #if !ENABLE_HUSH_INTERACTIVE
148 # undef ENABLE_FEATURE_EDITING
149 # define ENABLE_FEATURE_EDITING 0
150 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
151 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
154 /* Do we support ANY keywords? */
155 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
156 # define HAS_KEYWORDS 1
157 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
158 # define IF_HAS_NO_KEYWORDS(...)
160 # define HAS_KEYWORDS 0
161 # define IF_HAS_KEYWORDS(...)
162 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
165 /* If you comment out one of these below, it will be #defined later
166 * to perform debug printfs to stderr: */
167 #define debug_printf(...) do {} while (0)
168 /* Finer-grained debug switches */
169 #define debug_printf_parse(...) do {} while (0)
170 #define debug_print_tree(a, b) do {} while (0)
171 #define debug_printf_exec(...) do {} while (0)
172 #define debug_printf_env(...) do {} while (0)
173 #define debug_printf_jobs(...) do {} while (0)
174 #define debug_printf_expand(...) do {} while (0)
175 #define debug_printf_varexp(...) do {} while (0)
176 #define debug_printf_glob(...) do {} while (0)
177 #define debug_printf_list(...) do {} while (0)
178 #define debug_printf_subst(...) do {} while (0)
179 #define debug_printf_clean(...) do {} while (0)
181 #define ERR_PTR ((void*)(long)1)
183 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
185 #define _SPECIAL_VARS_STR "_*@$!?#"
186 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
187 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
189 #define SPECIAL_VAR_SYMBOL 3
193 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
195 /* This supports saving pointers malloced in vfork child,
196 * to be freed in the parent.
199 typedef struct nommu_save_t {
201 struct variable *old_vars;
203 char **argv_from_re_execing;
207 typedef enum reserved_style {
216 #if ENABLE_HUSH_LOOPS
223 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
228 /* three pseudo-keywords support contrived "case" syntax: */
229 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
230 RES_MATCH , /* "word)" */
231 RES_CASE_BODY, /* "this command is inside CASE" */
238 typedef struct o_string {
240 int length; /* position where data is appended */
242 /* Protect newly added chars against globbing
243 * (by prepending \ to *, ?, [, \) */
246 /* At least some part of the string was inside '' or "",
247 * possibly empty one: word"", wo''rd etc. */
249 smallint has_empty_slot;
250 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
253 MAYBE_ASSIGNMENT = 0,
254 DEFINITELY_ASSIGNMENT = 1,
256 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
258 /* Used for initialization: o_string foo = NULL_O_STRING; */
259 #define NULL_O_STRING { NULL }
261 /* I can almost use ordinary FILE*. Is open_memstream() universally
262 * available? Where is it documented? */
263 typedef struct in_str {
265 /* eof_flag=1: last char in ->p is really an EOF */
266 char eof_flag; /* meaningless if ->p == NULL */
268 #if ENABLE_HUSH_INTERACTIVE
270 smallint promptmode; /* 0: PS1, 1: PS2 */
273 int (*get) (struct in_str *) FAST_FUNC;
274 int (*peek) (struct in_str *) FAST_FUNC;
276 #define i_getch(input) ((input)->get(input))
277 #define i_peek(input) ((input)->peek(input))
279 /* The descrip member of this structure is only used to make
280 * debugging output pretty */
281 static const struct {
283 signed char default_fd;
286 { O_RDONLY, 0, "<" },
287 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
288 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
289 { O_CREAT|O_RDWR, 1, "<>" },
290 { O_RDONLY, 0, "<<" },
291 /* Should not be needed. Bogus default_fd helps in debugging */
292 /* { O_RDONLY, 77, "<<" }, */
295 struct redir_struct {
296 struct redir_struct *next;
297 char *rd_filename; /* filename */
298 int rd_fd; /* fd to redirect */
299 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
301 smallint rd_type; /* (enum redir_type) */
302 /* note: for heredocs, rd_filename contains heredoc delimiter,
303 * and subsequently heredoc itself; and rd_dup is a bitmask:
304 * bit 0: do we need to trim leading tabs?
305 * bit 1: is heredoc quoted (<<'delim' syntax) ?
308 typedef enum redir_type {
310 REDIRECT_OVERWRITE = 1,
313 REDIRECT_HEREDOC = 4,
314 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
317 REDIRFD_SYNTAX_ERR = -2,
318 REDIRFD_TO_FILE = -1,
319 /* otherwise, rd_fd is redirected to rd_dup */
321 HEREDOC_SKIPTABS = 1,
327 pid_t pid; /* 0 if exited */
328 int assignment_cnt; /* how many argv[i] are assignments? */
329 smallint is_stopped; /* is the command currently running? */
330 smallint cmd_type; /* CMD_xxx */
332 #define CMD_SUBSHELL 1
334 /* used for "[[ EXPR ]]" */
335 #if ENABLE_HUSH_BASH_COMPAT
336 # define CMD_SINGLEWORD_NOGLOB 2
339 /* used for "export noglob=* glob* a=`echo a b`" */
340 //#define CMD_SINGLEWORD_NOGLOB_COND 3
341 // It is hard to implement correctly, it adds significant amounts of tricky code,
342 // and all this is only useful for really obscure export statements
343 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
344 // guards the code which implements it, but I have doubts it works
345 // in all cases (especially with mixed globbed/non-globbed arguments)
347 #if ENABLE_HUSH_FUNCTIONS
348 # define CMD_FUNCDEF 3
351 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
354 char *group_as_string;
356 #if ENABLE_HUSH_FUNCTIONS
357 struct function *child_func;
358 /* This field is used to prevent a bug here:
359 * while...do f1() {a;}; f1; f1() {b;}; f1; done
360 * When we execute "f1() {a;}" cmd, we create new function and clear
361 * cmd->group, cmd->group_as_string, cmd->argv[0].
362 * When we execute "f1() {b;}", we notice that f1 exists,
363 * and that its "parent cmd" struct is still "alive",
364 * we put those fields back into cmd->xxx
365 * (struct function has ->parent_cmd ptr to facilitate that).
366 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
367 * Without this trick, loop would execute a;b;b;b;...
368 * instead of correct sequence a;b;a;b;...
369 * When command is freed, it severs the link
370 * (sets ->child_func->parent_cmd to NULL).
373 char **argv; /* command name and arguments */
374 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
375 * and on execution these are substituted with their values.
376 * Substitution can make _several_ words out of one argv[n]!
377 * Example: argv[0]=='.^C*^C.' here: echo .$*.
378 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
380 struct redir_struct *redirects; /* I/O redirections */
382 /* Is there anything in this command at all? */
383 #define IS_NULL_CMD(cmd) \
384 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
389 int num_cmds; /* total number of commands in pipe */
390 int alive_cmds; /* number of commands running (not exited) */
391 int stopped_cmds; /* number of commands alive, but stopped */
393 int jobid; /* job number */
394 pid_t pgrp; /* process group ID for the job */
395 char *cmdtext; /* name of job */
397 struct command *cmds; /* array of commands in pipe */
398 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
399 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
400 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
402 typedef enum pipe_style {
408 /* Is there anything in this pipe at all? */
409 #define IS_NULL_PIPE(pi) \
410 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
412 /* This holds pointers to the various results of parsing */
413 struct parse_context {
414 /* linked list of pipes */
415 struct pipe *list_head;
416 /* last pipe (being constructed right now) */
418 /* last command in pipe (being constructed right now) */
419 struct command *command;
420 /* last redirect in command->redirects list */
421 struct redir_struct *pending_redirect;
427 smallint ctx_inverted; /* "! cmd | cmd" */
429 smallint ctx_dsemicolon; /* ";;" seen */
431 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
433 /* group we are enclosed in:
434 * example: "if pipe1; pipe2; then pipe3; fi"
435 * when we see "if" or "then", we malloc and copy current context,
436 * and make ->stack point to it. then we parse pipeN.
437 * when closing "then" / fi" / whatever is found,
438 * we move list_head into ->stack->command->group,
439 * copy ->stack into current context, and delete ->stack.
440 * (parsing of { list } and ( list ) doesn't use this method)
442 struct parse_context *stack;
446 /* On program start, environ points to initial environment.
447 * putenv adds new pointers into it, unsetenv removes them.
448 * Neither of these (de)allocates the strings.
449 * setenv allocates new strings in malloc space and does putenv,
450 * and thus setenv is unusable (leaky) for shell's purposes */
451 #define setenv(...) setenv_is_leaky_dont_use()
453 struct variable *next;
454 char *varstr; /* points to "name=" portion */
455 #if ENABLE_HUSH_LOCAL
456 unsigned func_nest_level;
458 int max_len; /* if > 0, name is part of initial env; else name is malloced */
459 smallint flg_export; /* putenv should be done on this var */
460 smallint flg_read_only;
468 #if ENABLE_HUSH_FUNCTIONS
470 struct function *next;
472 struct command *parent_cmd;
475 char *body_as_string;
481 /* "Globals" within this file */
482 /* Sorted roughly by size (smaller offsets == smaller code) */
484 /* interactive_fd != 0 means we are an interactive shell.
485 * If we are, then saved_tty_pgrp can also be != 0, meaning
486 * that controlling tty is available. With saved_tty_pgrp == 0,
487 * job control still works, but terminal signals
488 * (^C, ^Z, ^Y, ^\) won't work at all, and background
489 * process groups can only be created with "cmd &".
490 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
491 * to give tty to the foreground process group,
492 * and will take it back when the group is stopped (^Z)
495 #if ENABLE_HUSH_INTERACTIVE
496 /* 'interactive_fd' is a fd# open to ctty, if we have one
497 * _AND_ if we decided to act interactively */
501 # define G_interactive_fd (G.interactive_fd)
503 # define G_interactive_fd 0
505 #if ENABLE_FEATURE_EDITING
506 line_input_t *line_input_state;
511 #if ENABLE_HUSH_RANDOM_SUPPORT
517 pid_t saved_tty_pgrp;
518 struct pipe *job_list;
519 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
521 # define G_saved_tty_pgrp 0
523 smallint flag_SIGINT;
524 #if ENABLE_HUSH_LOOPS
525 smallint flag_break_continue;
527 #if ENABLE_HUSH_FUNCTIONS
528 /* 0: outside of a function (or sourced file)
529 * -1: inside of a function, ok to use return builtin
530 * 1: return is invoked, skip all till end of func
532 smallint flag_return_in_progress;
536 smallint exiting; /* used to prevent EXIT trap recursion */
537 /* These four support $?, $#, and $1 */
538 smalluint last_exitcode;
539 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
540 smalluint global_args_malloced;
541 smalluint inherited_set_is_saved;
542 /* how many non-NULL argv's we have. NB: $# + 1 */
546 char *argv0_for_re_execing;
548 #if ENABLE_HUSH_LOOPS
549 unsigned depth_break_continue;
550 unsigned depth_of_loop;
554 struct variable *top_var; /* = &G.shell_ver (set in main()) */
555 struct variable shell_ver;
556 #if ENABLE_HUSH_FUNCTIONS
557 struct function *top_func;
558 # if ENABLE_HUSH_LOCAL
559 struct variable **shadowed_vars_pp;
560 unsigned func_nest_level;
563 /* Signal and trap handling */
565 unsigned count_SIGCHLD;
566 unsigned handled_SIGCHLD;
567 smallint we_have_children;
569 /* which signals have non-DFL handler (even with no traps set)? */
570 unsigned non_DFL_mask;
571 char **traps; /* char *traps[NSIG] */
572 sigset_t blocked_set;
573 sigset_t inherited_set;
575 unsigned long memleak_value;
578 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
580 #define G (*ptr_to_globals)
581 /* Not #defining name to G.name - this quickly gets unwieldy
582 * (too many defines). Also, I actually prefer to see when a variable
583 * is global, thus "G." prefix is a useful hint */
584 #define INIT_G() do { \
585 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
589 /* Function prototypes for builtins */
590 static int builtin_cd(char **argv) FAST_FUNC;
591 static int builtin_echo(char **argv) FAST_FUNC;
592 static int builtin_eval(char **argv) FAST_FUNC;
593 static int builtin_exec(char **argv) FAST_FUNC;
594 static int builtin_exit(char **argv) FAST_FUNC;
595 static int builtin_export(char **argv) FAST_FUNC;
597 static int builtin_fg_bg(char **argv) FAST_FUNC;
598 static int builtin_jobs(char **argv) FAST_FUNC;
601 static int builtin_help(char **argv) FAST_FUNC;
603 #if ENABLE_HUSH_LOCAL
604 static int builtin_local(char **argv) FAST_FUNC;
607 static int builtin_memleak(char **argv) FAST_FUNC;
610 static int builtin_printf(char **argv) FAST_FUNC;
612 static int builtin_pwd(char **argv) FAST_FUNC;
613 static int builtin_read(char **argv) FAST_FUNC;
614 static int builtin_set(char **argv) FAST_FUNC;
615 static int builtin_shift(char **argv) FAST_FUNC;
616 static int builtin_source(char **argv) FAST_FUNC;
617 static int builtin_test(char **argv) FAST_FUNC;
618 static int builtin_trap(char **argv) FAST_FUNC;
619 static int builtin_type(char **argv) FAST_FUNC;
620 static int builtin_true(char **argv) FAST_FUNC;
621 static int builtin_umask(char **argv) FAST_FUNC;
622 static int builtin_unset(char **argv) FAST_FUNC;
623 static int builtin_wait(char **argv) FAST_FUNC;
624 #if ENABLE_HUSH_LOOPS
625 static int builtin_break(char **argv) FAST_FUNC;
626 static int builtin_continue(char **argv) FAST_FUNC;
628 #if ENABLE_HUSH_FUNCTIONS
629 static int builtin_return(char **argv) FAST_FUNC;
632 /* Table of built-in functions. They can be forked or not, depending on
633 * context: within pipes, they fork. As simple commands, they do not.
634 * When used in non-forking context, they can change global variables
635 * in the parent shell process. If forked, of course they cannot.
636 * For example, 'unset foo | whatever' will parse and run, but foo will
637 * still be set at the end. */
638 struct built_in_command {
640 int (*b_function)(char **argv) FAST_FUNC;
643 # define BLTIN(cmd, func, help) { cmd, func, help }
645 # define BLTIN(cmd, func, help) { cmd, func }
649 static const struct built_in_command bltins1[] = {
650 BLTIN("." , builtin_source , "Run commands in a file"),
651 BLTIN(":" , builtin_true , NULL),
653 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
655 #if ENABLE_HUSH_LOOPS
656 BLTIN("break" , builtin_break , "Exit from a loop"),
658 BLTIN("cd" , builtin_cd , "Change directory"),
659 #if ENABLE_HUSH_LOOPS
660 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
662 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
663 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
664 BLTIN("exit" , builtin_exit , "Exit"),
665 BLTIN("export" , builtin_export , "Set environment variables"),
667 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
670 BLTIN("help" , builtin_help , NULL),
673 BLTIN("jobs" , builtin_jobs , "List jobs"),
675 #if ENABLE_HUSH_LOCAL
676 BLTIN("local" , builtin_local , "Set local variables"),
679 BLTIN("memleak" , builtin_memleak , NULL),
681 BLTIN("read" , builtin_read , "Input into variable"),
682 #if ENABLE_HUSH_FUNCTIONS
683 BLTIN("return" , builtin_return , "Return from a function"),
685 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
686 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
687 #if ENABLE_HUSH_BASH_COMPAT
688 BLTIN("source" , builtin_source , "Run commands in a file"),
690 BLTIN("trap" , builtin_trap , "Trap signals"),
691 BLTIN("type" , builtin_type , "Show command type"),
692 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
693 BLTIN("umask" , builtin_umask , "Set file creation mask"),
694 BLTIN("unset" , builtin_unset , "Unset variables"),
695 BLTIN("wait" , builtin_wait , "Wait for process"),
697 /* For now, echo and test are unconditionally enabled.
698 * Maybe make it configurable? */
699 static const struct built_in_command bltins2[] = {
700 BLTIN("[" , builtin_test , NULL),
701 BLTIN("echo" , builtin_echo , NULL),
703 BLTIN("printf" , builtin_printf , NULL),
705 BLTIN("pwd" , builtin_pwd , NULL),
706 BLTIN("test" , builtin_test , NULL),
713 /* prevent disasters with G.debug_indent < 0 */
714 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
715 # define debug_enter() (G.debug_indent++)
716 # define debug_leave() (G.debug_indent--)
718 # define indent() ((void)0)
719 # define debug_enter() ((void)0)
720 # define debug_leave() ((void)0)
724 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
727 #ifndef debug_printf_parse
728 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
731 #ifndef debug_printf_exec
732 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
735 #ifndef debug_printf_env
736 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
739 #ifndef debug_printf_jobs
740 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
741 # define DEBUG_JOBS 1
743 # define DEBUG_JOBS 0
746 #ifndef debug_printf_expand
747 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
748 # define DEBUG_EXPAND 1
750 # define DEBUG_EXPAND 0
753 #ifndef debug_printf_varexp
754 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
757 #ifndef debug_printf_glob
758 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
759 # define DEBUG_GLOB 1
761 # define DEBUG_GLOB 0
764 #ifndef debug_printf_list
765 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
768 #ifndef debug_printf_subst
769 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
772 #ifndef debug_printf_clean
773 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
774 # define DEBUG_CLEAN 1
776 # define DEBUG_CLEAN 0
780 static void debug_print_strings(const char *prefix, char **vv)
783 fprintf(stderr, "%s:\n", prefix);
785 fprintf(stderr, " '%s'\n", *vv++);
788 # define debug_print_strings(prefix, vv) ((void)0)
792 /* Leak hunting. Use hush_leaktool.sh for post-processing.
795 static void *xxmalloc(int lineno, size_t size)
797 void *ptr = xmalloc((size + 0xff) & ~0xff);
798 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
801 static void *xxrealloc(int lineno, void *ptr, size_t size)
803 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
804 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
807 static char *xxstrdup(int lineno, const char *str)
809 char *ptr = xstrdup(str);
810 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
813 static void xxfree(void *ptr)
815 fdprintf(2, "free %p\n", ptr);
818 # define xmalloc(s) xxmalloc(__LINE__, s)
819 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
820 # define xstrdup(s) xxstrdup(__LINE__, s)
821 # define free(p) xxfree(p)
825 /* Syntax and runtime errors. They always abort scripts.
826 * In interactive use they usually discard unparsed and/or unexecuted commands
827 * and return to the prompt.
828 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
831 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
832 # define syntax_error(lineno, msg) syntax_error(msg)
833 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
834 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
835 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
836 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
839 static void die_if_script(unsigned lineno, const char *fmt, ...)
844 bb_error_msg("hush.c:%u", lineno);
847 bb_verror_msg(fmt, p, NULL);
849 if (!G_interactive_fd)
853 static void syntax_error(unsigned lineno, const char *msg)
856 die_if_script(lineno, "syntax error: %s", msg);
858 die_if_script(lineno, "syntax error", NULL);
861 static void syntax_error_at(unsigned lineno, const char *msg)
863 die_if_script(lineno, "syntax error at '%s'", msg);
866 static void syntax_error_unterm_str(unsigned lineno, const char *s)
868 die_if_script(lineno, "syntax error: unterminated %s", s);
871 /* It so happens that all such cases are totally fatal
872 * even if shell is interactive: EOF while looking for closing
873 * delimiter. There is nowhere to read stuff from after that,
874 * it's EOF! The only choice is to terminate.
876 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
877 static void syntax_error_unterm_ch(unsigned lineno, char ch)
879 char msg[2] = { ch, '\0' };
880 syntax_error_unterm_str(lineno, msg);
884 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
889 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
893 # undef die_if_script
895 # undef syntax_error_at
896 # undef syntax_error_unterm_ch
897 # undef syntax_error_unterm_str
898 # undef syntax_error_unexpected_ch
900 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
901 # define syntax_error(msg) syntax_error(__LINE__, msg)
902 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
903 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
904 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
905 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
909 #if ENABLE_HUSH_INTERACTIVE
910 static void cmdedit_update_prompt(void);
912 # define cmdedit_update_prompt() ((void)0)
918 /* Replace each \x with x in place, return ptr past NUL. */
919 static char *unbackslash(char *src)
921 char *dst = src = strchrnul(src, '\\');
925 if ((*dst++ = *src++) == '\0')
931 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
952 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
953 v[count1 + count2] = NULL;
956 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
960 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
962 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
963 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
966 #define add_strings_to_strings(strings, add, need_to_dup) \
967 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
970 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
971 static char **add_string_to_strings(char **strings, char *add)
976 return add_strings_to_strings(strings, v, /*dup:*/ 0);
979 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
981 char **ptr = add_string_to_strings(strings, add);
982 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
985 #define add_string_to_strings(strings, add) \
986 xx_add_string_to_strings(__LINE__, strings, add)
989 static void free_strings(char **strings)
1004 /* Helpers for setting new $n and restoring them back
1006 typedef struct save_arg_t {
1010 smallint sv_g_malloced;
1013 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1017 sv->sv_argv0 = argv[0];
1018 sv->sv_g_argv = G.global_argv;
1019 sv->sv_g_argc = G.global_argc;
1020 sv->sv_g_malloced = G.global_args_malloced;
1022 argv[0] = G.global_argv[0]; /* retain $0 */
1023 G.global_argv = argv;
1024 G.global_args_malloced = 0;
1032 static void restore_G_args(save_arg_t *sv, char **argv)
1036 if (G.global_args_malloced) {
1037 /* someone ran "set -- arg1 arg2 ...", undo */
1039 while (*++pp) /* note: does not free $0 */
1041 free(G.global_argv);
1043 argv[0] = sv->sv_argv0;
1044 G.global_argv = sv->sv_g_argv;
1045 G.global_argc = sv->sv_g_argc;
1046 G.global_args_malloced = sv->sv_g_malloced;
1050 /* Basic theory of signal handling in shell
1051 * ========================================
1052 * This does not describe what hush does, rather, it is current understanding
1053 * what it _should_ do. If it doesn't, it's a bug.
1054 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1056 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1057 * is finished or backgrounded. It is the same in interactive and
1058 * non-interactive shells, and is the same regardless of whether
1059 * a user trap handler is installed or a shell special one is in effect.
1060 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1061 * backgrounds (i.e. stops) or kills all members of currently running
1064 * Wait builtin in interruptible by signals for which user trap is set
1065 * or by SIGINT in interactive shell.
1067 * Trap handlers will execute even within trap handlers. (right?)
1069 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1070 * except for handlers set to '' (empty string).
1072 * If job control is off, backgrounded commands ("cmd &")
1073 * have SIGINT, SIGQUIT set to SIG_IGN.
1075 * Commands which are run in command substitution ("`cmd`")
1076 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1078 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1079 * by the shell from its parent.
1081 * Signals which differ from SIG_DFL action
1082 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1085 * SIGTERM (interactive): ignore
1086 * SIGHUP (interactive):
1087 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1088 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1089 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1090 * that all pipe members are stopped. Try this in bash:
1091 * while :; do :; done - ^Z does not background it
1092 * (while :; do :; done) - ^Z backgrounds it
1093 * SIGINT (interactive): wait for last pipe, ignore the rest
1094 * of the command line, show prompt. NB: ^C does not send SIGINT
1095 * to interactive shell while shell is waiting for a pipe,
1096 * since shell is bg'ed (is not in foreground process group).
1097 * Example 1: this waits 5 sec, but does not execute ls:
1098 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1099 * Example 2: this does not wait and does not execute ls:
1100 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1101 * Example 3: this does not wait 5 sec, but executes ls:
1102 * "sleep 5; ls -l" + press ^C
1104 * (What happens to signals which are IGN on shell start?)
1105 * (What happens with signal mask on shell start?)
1107 * Implementation in hush
1108 * ======================
1109 * We use in-kernel pending signal mask to determine which signals were sent.
1110 * We block all signals which we don't want to take action immediately,
1111 * i.e. we block all signals which need to have special handling as described
1112 * above, and all signals which have traps set.
1113 * After each pipe execution, we extract any pending signals via sigtimedwait()
1116 * unsigned non_DFL_mask: a mask of such "special" signals
1117 * sigset_t blocked_set: current blocked signal set
1120 * clear bit in blocked_set unless it is also in non_DFL_mask
1121 * "trap 'cmd' SIGxxx":
1122 * set bit in blocked_set (even if 'cmd' is '')
1123 * after [v]fork, if we plan to be a shell:
1124 * unblock signals with special interactive handling
1125 * (child shell is not interactive),
1126 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1127 * after [v]fork, if we plan to exec:
1128 * POSIX says fork clears pending signal mask in child - no need to clear it.
1129 * Restore blocked signal set to one inherited by shell just prior to exec.
1131 * Note: as a result, we do not use signal handlers much. The only uses
1132 * are to count SIGCHLDs
1133 * and to restore tty pgrp on signal-induced exit.
1136 * Standard says "When a subshell is entered, traps that are not being ignored
1137 * are set to the default actions". bash interprets it so that traps which
1138 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1141 SPECIAL_INTERACTIVE_SIGS = 0
1146 SPECIAL_JOB_SIGS = 0
1154 #if ENABLE_HUSH_FAST
1155 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1158 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1164 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1165 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1166 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1167 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1169 /* Restores tty foreground process group, and exits.
1170 * May be called as signal handler for fatal signal
1171 * (will resend signal to itself, producing correct exit state)
1172 * or called directly with -EXITCODE.
1173 * We also call it if xfunc is exiting. */
1174 static void sigexit(int sig) NORETURN;
1175 static void sigexit(int sig)
1177 /* Disable all signals: job control, SIGPIPE, etc. */
1178 sigprocmask_allsigs(SIG_BLOCK);
1180 /* Careful: we can end up here after [v]fork. Do not restore
1181 * tty pgrp then, only top-level shell process does that */
1182 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1183 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1185 /* Not a signal, just exit */
1189 kill_myself_with_sig(sig); /* does not return */
1193 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1194 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1198 /* Restores tty foreground process group, and exits. */
1199 static void hush_exit(int exitcode) NORETURN;
1200 static void hush_exit(int exitcode)
1202 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1203 /* Prevent recursion:
1204 * trap "echo Hi; exit" EXIT; exit
1206 char *argv[] = { NULL, G.traps[0], NULL };
1215 sigexit(- (exitcode & 0xff));
1221 static int check_and_run_traps(int sig)
1223 static const struct timespec zero_timespec;
1224 smalluint save_rcode;
1230 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1235 if (G.traps && G.traps[sig]) {
1236 if (G.traps[sig][0]) {
1237 /* We have user-defined handler */
1238 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1239 save_rcode = G.last_exitcode;
1242 G.last_exitcode = save_rcode;
1243 } /* else: "" trap, ignoring signal */
1246 /* not a trap: special action */
1248 #if ENABLE_HUSH_FAST
1251 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1255 /* Builtin was ^C'ed, make it look prettier: */
1262 /* bash is observed to signal whole process groups,
1263 * not individual processes */
1264 for (job = G.job_list; job; job = job->next) {
1267 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1268 if (kill(- job->pgrp, SIGHUP) == 0)
1269 kill(- job->pgrp, SIGCONT);
1274 default: /* ignored: */
1275 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1283 static const char *get_cwd(int force)
1285 if (force || G.cwd == NULL) {
1286 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1287 * we must not try to free(bb_msg_unknown) */
1288 if (G.cwd == bb_msg_unknown)
1290 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1292 G.cwd = bb_msg_unknown;
1299 * Shell and environment variable support
1301 static struct variable **get_ptr_to_local_var(const char *name)
1303 struct variable **pp;
1304 struct variable *cur;
1309 while ((cur = *pp) != NULL) {
1310 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1317 static struct variable *get_local_var(const char *name)
1319 struct variable **pp = get_ptr_to_local_var(name);
1325 static const char* FAST_FUNC get_local_var_value(const char *name)
1327 struct variable **pp = get_ptr_to_local_var(name);
1329 return strchr((*pp)->varstr, '=') + 1;
1330 if (strcmp(name, "PPID") == 0)
1331 return utoa(G.root_ppid);
1332 // bash compat: UID? EUID?
1333 #if ENABLE_HUSH_RANDOM_SUPPORT
1334 if (strcmp(name, "RANDOM") == 0) {
1335 return utoa(next_random(&G.random_gen));
1341 /* str holds "NAME=VAL" and is expected to be malloced.
1342 * We take ownership of it.
1344 * 0: do not change export flag
1345 * (if creating new variable, flag will be 0)
1346 * 1: set export flag and putenv the variable
1347 * -1: clear export flag and unsetenv the variable
1348 * flg_read_only is set only when we handle -R var=val
1350 #if !BB_MMU && ENABLE_HUSH_LOCAL
1351 /* all params are used */
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, local_lvl)
1355 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1356 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1357 set_local_var(str, flg_export)
1358 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1359 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1360 set_local_var(str, flg_export, flg_read_only)
1362 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1364 struct variable **var_pp;
1365 struct variable *cur;
1369 eq_sign = strchr(str, '=');
1370 if (!eq_sign) { /* not expected to ever happen? */
1375 name_len = eq_sign - str + 1; /* including '=' */
1376 var_pp = &G.top_var;
1377 while ((cur = *var_pp) != NULL) {
1378 if (strncmp(cur->varstr, str, name_len) != 0) {
1379 var_pp = &cur->next;
1382 /* We found an existing var with this name */
1383 if (cur->flg_read_only) {
1387 bb_error_msg("%s: readonly variable", str);
1391 if (flg_export == -1) { // "&& cur->flg_export" ?
1392 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1397 #if ENABLE_HUSH_LOCAL
1398 if (cur->func_nest_level < local_lvl) {
1399 /* New variable is declared as local,
1400 * and existing one is global, or local
1401 * from enclosing function.
1402 * Remove and save old one: */
1403 *var_pp = cur->next;
1404 cur->next = *G.shadowed_vars_pp;
1405 *G.shadowed_vars_pp = cur;
1406 /* bash 3.2.33(1) and exported vars:
1408 * # f() { local z=a; env | grep ^z; }
1414 if (cur->flg_export)
1419 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1424 if (cur->max_len != 0) {
1425 if (cur->max_len >= strlen(str)) {
1426 /* This one is from startup env, reuse space */
1427 strcpy(cur->varstr, str);
1431 /* max_len == 0 signifies "malloced" var, which we can
1432 * (and has to) free */
1436 goto set_str_and_exp;
1439 /* Not found - create new variable struct */
1440 cur = xzalloc(sizeof(*cur));
1441 #if ENABLE_HUSH_LOCAL
1442 cur->func_nest_level = local_lvl;
1444 cur->next = *var_pp;
1450 cur->flg_read_only = flg_read_only;
1453 if (flg_export == 1)
1454 cur->flg_export = 1;
1455 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1456 cmdedit_update_prompt();
1457 if (cur->flg_export) {
1458 if (flg_export == -1) {
1459 cur->flg_export = 0;
1460 /* unsetenv was already done */
1462 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1463 return putenv(cur->varstr);
1469 /* Used at startup and after each cd */
1470 static void set_pwd_var(int exp)
1472 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1473 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1476 static int unset_local_var_len(const char *name, int name_len)
1478 struct variable *cur;
1479 struct variable **var_pp;
1482 return EXIT_SUCCESS;
1483 var_pp = &G.top_var;
1484 while ((cur = *var_pp) != NULL) {
1485 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1486 if (cur->flg_read_only) {
1487 bb_error_msg("%s: readonly variable", name);
1488 return EXIT_FAILURE;
1490 *var_pp = cur->next;
1491 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1492 bb_unsetenv(cur->varstr);
1493 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1494 cmdedit_update_prompt();
1498 return EXIT_SUCCESS;
1500 var_pp = &cur->next;
1502 return EXIT_SUCCESS;
1505 static int unset_local_var(const char *name)
1507 return unset_local_var_len(name, strlen(name));
1510 static void unset_vars(char **strings)
1518 const char *eq = strchrnul(*v, '=');
1519 unset_local_var_len(*v, (int)(eq - *v));
1525 #if ENABLE_SH_MATH_SUPPORT
1526 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1527 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1528 static char* FAST_FUNC endofname(const char *name)
1536 if (!is_in_name(*p))
1543 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1545 char *var = xasprintf("%s=%s", name, val);
1546 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1551 * Helpers for "var1=val1 var2=val2 cmd" feature
1553 static void add_vars(struct variable *var)
1555 struct variable *next;
1559 var->next = G.top_var;
1561 if (var->flg_export) {
1562 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1563 putenv(var->varstr);
1565 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1571 static struct variable *set_vars_and_save_old(char **strings)
1574 struct variable *old = NULL;
1580 struct variable *var_p;
1581 struct variable **var_pp;
1584 eq = strchr(*s, '=');
1587 var_pp = get_ptr_to_local_var(*s);
1590 /* Remove variable from global linked list */
1592 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1593 *var_pp = var_p->next;
1594 /* Add it to returned list */
1598 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1609 static int FAST_FUNC static_get(struct in_str *i)
1619 static int FAST_FUNC static_peek(struct in_str *i)
1624 #if ENABLE_HUSH_INTERACTIVE
1626 static void cmdedit_update_prompt(void)
1628 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1629 G.PS1 = get_local_var_value("PS1");
1632 G.PS2 = get_local_var_value("PS2");
1640 static const char* setup_prompt_string(int promptmode)
1642 const char *prompt_str;
1643 debug_printf("setup_prompt_string %d ", promptmode);
1644 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1645 /* Set up the prompt */
1646 if (promptmode == 0) { /* PS1 */
1648 /* bash uses $PWD value, even if it is set by user.
1649 * It uses current dir only if PWD is unset.
1650 * We always use current dir. */
1651 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1656 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1657 debug_printf("result '%s'\n", prompt_str);
1661 static void get_user_input(struct in_str *i)
1664 const char *prompt_str;
1666 prompt_str = setup_prompt_string(i->promptmode);
1667 # if ENABLE_FEATURE_EDITING
1668 /* Enable command line editing only while a command line
1669 * is actually being read */
1672 /* buglet: SIGINT will not make new prompt to appear _at once_,
1673 * only after <Enter>. (^C will work) */
1674 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1675 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1676 check_and_run_traps(0);
1677 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1678 i->eof_flag = (r < 0);
1679 if (i->eof_flag) { /* EOF/error detected */
1680 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1681 G.user_input_buf[1] = '\0';
1686 fputs(prompt_str, stdout);
1688 G.user_input_buf[0] = r = fgetc(i->file);
1689 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1690 //do we need check_and_run_traps(0)? (maybe only if stdin)
1691 } while (G.flag_SIGINT);
1692 i->eof_flag = (r == EOF);
1694 i->p = G.user_input_buf;
1697 #endif /* INTERACTIVE */
1699 /* This is the magic location that prints prompts
1700 * and gets data back from the user */
1701 static int FAST_FUNC file_get(struct in_str *i)
1705 /* If there is data waiting, eat it up */
1706 if (i->p && *i->p) {
1707 #if ENABLE_HUSH_INTERACTIVE
1711 if (i->eof_flag && !*i->p)
1713 /* note: ch is never NUL */
1715 /* need to double check i->file because we might be doing something
1716 * more complicated by now, like sourcing or substituting. */
1717 #if ENABLE_HUSH_INTERACTIVE
1718 if (G_interactive_fd && i->promptme && i->file == stdin) {
1721 } while (!*i->p); /* need non-empty line */
1722 i->promptmode = 1; /* PS2 */
1727 do ch = fgetc(i->file); while (ch == '\0');
1729 debug_printf("file_get: got '%c' %d\n", ch, ch);
1730 #if ENABLE_HUSH_INTERACTIVE
1737 /* All callers guarantee this routine will never
1738 * be used right after a newline, so prompting is not needed.
1740 static int FAST_FUNC file_peek(struct in_str *i)
1743 if (i->p && *i->p) {
1744 if (i->eof_flag && !i->p[1])
1747 /* note: ch is never NUL */
1749 do ch = fgetc(i->file); while (ch == '\0');
1750 i->eof_flag = (ch == EOF);
1751 i->peek_buf[0] = ch;
1752 i->peek_buf[1] = '\0';
1754 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1758 static void setup_file_in_str(struct in_str *i, FILE *f)
1760 i->peek = file_peek;
1762 #if ENABLE_HUSH_INTERACTIVE
1764 i->promptmode = 0; /* PS1 */
1770 static void setup_string_in_str(struct in_str *i, const char *s)
1772 i->peek = static_peek;
1773 i->get = static_get;
1774 #if ENABLE_HUSH_INTERACTIVE
1776 i->promptmode = 0; /* PS1 */
1786 #define B_CHUNK (32 * sizeof(char*))
1788 static void o_reset_to_empty_unquoted(o_string *o)
1796 static void o_free(o_string *o)
1799 memset(o, 0, sizeof(*o));
1802 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1807 static void o_grow_by(o_string *o, int len)
1809 if (o->length + len > o->maxlen) {
1810 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1811 o->data = xrealloc(o->data, 1 + o->maxlen);
1815 static void o_addchr(o_string *o, int ch)
1817 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1819 o->data[o->length] = ch;
1821 o->data[o->length] = '\0';
1824 static void o_addblock(o_string *o, const char *str, int len)
1827 memcpy(&o->data[o->length], str, len);
1829 o->data[o->length] = '\0';
1832 static void o_addstr(o_string *o, const char *str)
1834 o_addblock(o, str, strlen(str));
1838 static void nommu_addchr(o_string *o, int ch)
1844 # define nommu_addchr(o, str) ((void)0)
1847 static void o_addstr_with_NUL(o_string *o, const char *str)
1849 o_addblock(o, str, strlen(str) + 1);
1852 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1857 && (*str != '*' && *str != '?' && *str != '[')
1865 #undef HUSH_BRACE_EXP
1867 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
1868 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
1869 * Apparently, on unquoted $v bash still does globbing
1870 * ("v='*.txt'; echo $v" prints all .txt files),
1871 * but NOT brace expansion! Thus, there should be TWO independent
1872 * quoting mechanisms on $v expansion side: one protects
1873 * $v from brace expansion, and other additionally protects "$v" against globbing.
1874 * We have only second one.
1877 #ifdef HUSH_BRACE_EXP
1878 # define MAYBE_BRACES "{}"
1880 # define MAYBE_BRACES ""
1883 /* My analysis of quoting semantics tells me that state information
1884 * is associated with a destination, not a source.
1886 static void o_addqchr(o_string *o, int ch)
1889 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
1894 o->data[o->length] = '\\';
1897 o->data[o->length] = ch;
1899 o->data[o->length] = '\0';
1902 static void o_addQchr(o_string *o, int ch)
1905 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
1907 o->data[o->length] = '\\';
1911 o->data[o->length] = ch;
1913 o->data[o->length] = '\0';
1916 static void o_addQstr(o_string *o, const char *str, int len)
1919 o_addblock(o, str, len);
1925 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
1926 if (ordinary_cnt > len) /* paranoia */
1928 o_addblock(o, str, ordinary_cnt);
1929 if (ordinary_cnt == len)
1931 str += ordinary_cnt;
1932 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1936 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
1938 o->data[o->length] = '\\';
1942 o->data[o->length] = ch;
1944 o->data[o->length] = '\0';
1948 /* A special kind of o_string for $VAR and `cmd` expansion.
1949 * It contains char* list[] at the beginning, which is grown in 16 element
1950 * increments. Actual string data starts at the next multiple of 16 * (char*).
1951 * list[i] contains an INDEX (int!) into this string data.
1952 * It means that if list[] needs to grow, data needs to be moved higher up
1953 * but list[i]'s need not be modified.
1954 * NB: remembering how many list[i]'s you have there is crucial.
1955 * o_finalize_list() operation post-processes this structure - calculates
1956 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1958 #if DEBUG_EXPAND || DEBUG_GLOB
1959 static void debug_print_list(const char *prefix, o_string *o, int n)
1961 char **list = (char**)o->data;
1962 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1966 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1967 prefix, list, n, string_start, o->length, o->maxlen);
1970 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1971 o->data + (int)list[i] + string_start,
1972 o->data + (int)list[i] + string_start);
1976 const char *p = o->data + (int)list[n - 1] + string_start;
1978 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1982 # define debug_print_list(prefix, o, n) ((void)0)
1985 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1986 * in list[n] so that it points past last stored byte so far.
1987 * It returns n+1. */
1988 static int o_save_ptr_helper(o_string *o, int n)
1990 char **list = (char**)o->data;
1994 if (!o->has_empty_slot) {
1995 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1996 string_len = o->length - string_start;
1997 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1998 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1999 /* list[n] points to string_start, make space for 16 more pointers */
2000 o->maxlen += 0x10 * sizeof(list[0]);
2001 o->data = xrealloc(o->data, o->maxlen + 1);
2002 list = (char**)o->data;
2003 memmove(list + n + 0x10, list + n, string_len);
2004 o->length += 0x10 * sizeof(list[0]);
2006 debug_printf_list("list[%d]=%d string_start=%d\n",
2007 n, string_len, string_start);
2010 /* We have empty slot at list[n], reuse without growth */
2011 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2012 string_len = o->length - string_start;
2013 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2014 n, string_len, string_start);
2015 o->has_empty_slot = 0;
2017 list[n] = (char*)(ptrdiff_t)string_len;
2021 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2022 static int o_get_last_ptr(o_string *o, int n)
2024 char **list = (char**)o->data;
2025 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2027 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2030 #ifdef HUSH_BRACE_EXP
2031 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2032 * first, it processes even {a} (no commas), second,
2033 * I didn't manage to make it return strings when they don't match
2034 * existing files. Need to re-implement it.
2038 static int glob_needed(const char *s)
2047 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2053 /* Return pointer to next closing brace or to comma */
2054 static const char *next_brace_sub(const char *cp)
2058 while (*cp != '\0') {
2065 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2067 if (*cp++ == '{') /*}*/
2071 return *cp != '\0' ? cp : NULL;
2073 /* Recursive brace globber. Note: may garble pattern[]. */
2074 static int glob_brace(char *pattern, o_string *o, int n)
2076 char *new_pattern_buf;
2083 debug_printf_glob("glob_brace('%s')\n", pattern);
2089 if (*begin == '{') /*}*/ {
2090 /* Find the first sub-pattern and at the same time
2091 * find the rest after the closing brace */
2092 next = next_brace_sub(begin);
2094 /* An illegal expression */
2097 /*{*/ if (*next == '}') {
2098 /* "{abc}" with no commas - illegal
2099 * brace expr, disregard and skip it */
2105 if (*begin == '\\' && begin[1] != '\0')
2109 debug_printf_glob("begin:%s\n", begin);
2110 debug_printf_glob("next:%s\n", next);
2112 /* Now find the end of the whole brace expression */
2114 /*{*/ while (*rest != '}') {
2115 rest = next_brace_sub(rest);
2117 /* An illegal expression */
2120 debug_printf_glob("rest:%s\n", rest);
2122 rest_len = strlen(++rest) + 1;
2124 /* We are sure the brace expression is well-formed */
2126 /* Allocate working buffer large enough for our work */
2127 new_pattern_buf = xmalloc(strlen(pattern));
2129 /* We have a brace expression. BEGIN points to the opening {,
2130 * NEXT points past the terminator of the first element, and REST
2131 * points past the final }. We will accumulate result names from
2132 * recursive runs for each brace alternative in the buffer using
2137 /* Construct the new glob expression */
2140 mempcpy(new_pattern_buf,
2141 /* We know the prefix for all sub-patterns */
2142 pattern, begin - pattern),
2146 /* Note: glob_brace() may garble new_pattern_buf[].
2147 * That's why we re-copy prefix every time (1st memcpy above).
2149 n = glob_brace(new_pattern_buf, o, n);
2150 /*{*/ if (*next == '}') {
2151 /* We saw the last entry */
2155 next = next_brace_sub(next);
2157 free(new_pattern_buf);
2165 memset(&globdata, 0, sizeof(globdata));
2166 gr = glob(pattern, 0, NULL, &globdata);
2167 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2169 if (gr == GLOB_NOMATCH) {
2170 globfree(&globdata);
2171 /* NB: garbles parameter */
2172 unbackslash(pattern);
2173 o_addstr_with_NUL(o, pattern);
2174 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2175 return o_save_ptr_helper(o, n);
2177 if (gr == GLOB_NOSPACE)
2178 bb_error_msg_and_die(bb_msg_memory_exhausted);
2179 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2180 * but we didn't specify it. Paranoia again. */
2181 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2183 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2184 char **argv = globdata.gl_pathv;
2186 o_addstr_with_NUL(o, *argv);
2187 n = o_save_ptr_helper(o, n);
2193 globfree(&globdata);
2197 /* Performs globbing on last list[],
2198 * saving each result as a new list[].
2200 static int o_glob(o_string *o, int n)
2202 char *pattern, *copy;
2204 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2206 return o_save_ptr_helper(o, n);
2207 pattern = o->data + o_get_last_ptr(o, n);
2208 debug_printf_glob("glob pattern '%s'\n", pattern);
2209 if (!glob_needed(pattern)) {
2210 /* unbackslash last string in o in place, fix length */
2211 o->length = unbackslash(pattern) - o->data;
2212 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2213 return o_save_ptr_helper(o, n);
2216 copy = xstrdup(pattern);
2217 /* "forget" pattern in o */
2218 o->length = pattern - o->data;
2219 n = glob_brace(copy, o, n);
2222 debug_print_list("o_glob returning", o, n);
2226 #else /* !HUSH_BRACE_EXP */
2229 static int glob_needed(const char *s)
2238 if (*s == '*' || *s == '[' || *s == '?')
2244 /* Performs globbing on last list[],
2245 * saving each result as a new list[].
2247 static int o_glob(o_string *o, int n)
2253 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2255 return o_save_ptr_helper(o, n);
2256 pattern = o->data + o_get_last_ptr(o, n);
2257 debug_printf_glob("glob pattern '%s'\n", pattern);
2258 if (!glob_needed(pattern)) {
2260 /* unbackslash last string in o in place, fix length */
2261 o->length = unbackslash(pattern) - o->data;
2262 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2263 return o_save_ptr_helper(o, n);
2266 memset(&globdata, 0, sizeof(globdata));
2267 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2268 * If we glob "*.\*" and don't find anything, we need
2269 * to fall back to using literal "*.*", but GLOB_NOCHECK
2270 * will return "*.\*"!
2272 gr = glob(pattern, 0, NULL, &globdata);
2273 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2275 if (gr == GLOB_NOMATCH) {
2276 globfree(&globdata);
2279 if (gr == GLOB_NOSPACE)
2280 bb_error_msg_and_die(bb_msg_memory_exhausted);
2281 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2282 * but we didn't specify it. Paranoia again. */
2283 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2285 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2286 char **argv = globdata.gl_pathv;
2287 /* "forget" pattern in o */
2288 o->length = pattern - o->data;
2290 o_addstr_with_NUL(o, *argv);
2291 n = o_save_ptr_helper(o, n);
2297 globfree(&globdata);
2299 debug_print_list("o_glob returning", o, n);
2303 #endif /* !HUSH_BRACE_EXP */
2305 /* If o->o_glob == 1, glob the string so far remembered.
2306 * Otherwise, just finish current list[] and start new */
2307 static int o_save_ptr(o_string *o, int n)
2309 if (o->o_glob) { /* if globbing is requested */
2310 /* If o->has_empty_slot, list[n] was already globbed
2311 * (if it was requested back then when it was filled)
2312 * so don't do that again! */
2313 if (!o->has_empty_slot)
2314 return o_glob(o, n); /* o_save_ptr_helper is inside */
2316 return o_save_ptr_helper(o, n);
2319 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2320 static char **o_finalize_list(o_string *o, int n)
2325 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2327 debug_print_list("finalized", o, n);
2328 debug_printf_expand("finalized n:%d\n", n);
2329 list = (char**)o->data;
2330 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2334 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2340 /* Expansion can recurse */
2341 #if ENABLE_HUSH_TICK
2342 static int process_command_subs(o_string *dest, const char *s);
2344 static char *expand_string_to_string(const char *str);
2346 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2347 parse_stream_dquoted(dest, input, dquote_end)
2349 static int parse_stream_dquoted(o_string *as_string,
2351 struct in_str *input,
2354 /* expand_strvec_to_strvec() takes a list of strings, expands
2355 * all variable references within and returns a pointer to
2356 * a list of expanded strings, possibly with larger number
2357 * of strings. (Think VAR="a b"; echo $VAR).
2358 * This new list is allocated as a single malloc block.
2359 * NULL-terminated list of char* pointers is at the beginning of it,
2360 * followed by strings themself.
2361 * Caller can deallocate entire list by single free(list). */
2363 /* Store given string, finalizing the word and starting new one whenever
2364 * we encounter IFS char(s). This is used for expanding variable values.
2365 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2366 static int expand_on_ifs(o_string *output, int n, const char *str)
2369 int word_len = strcspn(str, G.ifs);
2371 if (output->o_escape || !output->o_glob)
2372 o_addQstr(output, str, word_len);
2373 else /* protect backslashes against globbing up :) */
2374 o_addblock_duplicate_backslash(output, str, word_len);
2377 if (!*str) /* EOL - do not finalize word */
2379 o_addchr(output, '\0');
2380 debug_print_list("expand_on_ifs", output, n);
2381 n = o_save_ptr(output, n);
2382 str += strspn(str, G.ifs); /* skip ifs chars */
2384 debug_print_list("expand_on_ifs[1]", output, n);
2388 /* Helper to expand $((...)) and heredoc body. These act as if
2389 * they are in double quotes, with the exception that they are not :).
2390 * Just the rules are similar: "expand only $var and `cmd`"
2392 * Returns malloced string.
2393 * As an optimization, we return NULL if expansion is not needed.
2395 static char *expand_pseudo_dquoted(const char *str)
2398 struct in_str input;
2399 o_string dest = NULL_O_STRING;
2401 if (strchr(str, '$') == NULL
2402 #if ENABLE_HUSH_TICK
2403 && strchr(str, '`') == NULL
2409 /* We need to expand. Example:
2410 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2412 setup_string_in_str(&input, str);
2413 parse_stream_dquoted(NULL, &dest, &input, EOF);
2414 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2415 exp_str = expand_string_to_string(dest.data);
2416 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2417 o_free_unsafe(&dest);
2421 #if ENABLE_SH_MATH_SUPPORT
2422 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2424 arith_eval_hooks_t hooks;
2428 hooks.lookupvar = get_local_var_value;
2429 hooks.setvar = set_local_var_from_halves;
2430 hooks.endofname = endofname;
2431 exp_str = expand_pseudo_dquoted(arg);
2432 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2438 /* Expand all variable references in given string, adding words to list[]
2439 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2440 * to be filled). This routine is extremely tricky: has to deal with
2441 * variables/parameters with whitespace, $* and $@, and constructs like
2442 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2443 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2445 /* or_mask is either 0 (normal case) or 0x80 -
2446 * expansion of right-hand side of assignment == 1-element expand.
2447 * It will also do no globbing, and thus we must not backslash-quote!
2454 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2455 debug_print_list("expand_vars_to_list", output, n);
2456 n = o_save_ptr(output, n);
2457 debug_print_list("expand_vars_to_list[0]", output, n);
2459 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2462 char *to_be_freed = NULL;
2463 const char *val = NULL;
2464 #if ENABLE_HUSH_TICK
2465 o_string subst_result = NULL_O_STRING;
2467 #if ENABLE_SH_MATH_SUPPORT
2468 char arith_buf[sizeof(arith_t)*3 + 2];
2470 o_addblock(output, arg, p - arg);
2471 debug_print_list("expand_vars_to_list[1]", output, n);
2473 p = strchr(p, SPECIAL_VAR_SYMBOL);
2475 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2476 /* "$@" is special. Even if quoted, it can still
2477 * expand to nothing (not even an empty string) */
2478 if ((first_ch & 0x7f) != '@')
2479 ored_ch |= first_ch;
2481 switch (first_ch & 0x7f) {
2482 /* Highest bit in first_ch indicates that var is double-quoted */
2486 if (!G.global_argv[i])
2488 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2489 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2490 smallint sv = output->o_escape;
2491 /* unquoted var's contents should be globbed, so don't escape */
2492 output->o_escape = 0;
2493 while (G.global_argv[i]) {
2494 n = expand_on_ifs(output, n, G.global_argv[i]);
2495 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2496 if (G.global_argv[i++][0] && G.global_argv[i]) {
2497 /* this argv[] is not empty and not last:
2498 * put terminating NUL, start new word */
2499 o_addchr(output, '\0');
2500 debug_print_list("expand_vars_to_list[2]", output, n);
2501 n = o_save_ptr(output, n);
2502 debug_print_list("expand_vars_to_list[3]", output, n);
2505 output->o_escape = sv;
2507 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2508 * and in this case should treat it like '$*' - see 'else...' below */
2509 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2511 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2512 if (++i >= G.global_argc)
2514 o_addchr(output, '\0');
2515 debug_print_list("expand_vars_to_list[4]", output, n);
2516 n = o_save_ptr(output, n);
2518 } else { /* quoted $*: add as one word */
2520 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2521 if (!G.global_argv[++i])
2524 o_addchr(output, G.ifs[0]);
2528 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2529 /* "Empty variable", used to make "" etc to not disappear */
2533 #if ENABLE_HUSH_TICK
2534 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2537 /* Can't just stuff it into output o_string,
2538 * expanded result may need to be globbed
2539 * and $IFS-splitted */
2540 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2541 G.last_exitcode = process_command_subs(&subst_result, arg);
2542 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
2543 val = subst_result.data;
2546 #if ENABLE_SH_MATH_SUPPORT
2547 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2551 arg++; /* skip '+' */
2552 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2553 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2554 res = expand_and_evaluate_arith(arg, &errcode);
2557 const char *msg = "error in arithmetic";
2560 msg = "exponent less than 0";
2563 msg = "divide by 0";
2566 msg = "expression recursion loop detected";
2571 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2572 sprintf(arith_buf, arith_t_fmt, res);
2577 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2581 char exp_save = exp_save; /* for compiler */
2582 char *exp_saveptr; /* points to expansion operator */
2583 char *exp_word = exp_word; /* for compiler */
2587 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2588 first_char = arg[0] = first_ch & 0x7f;
2591 if (first_char == '#' && arg[1] && !exp_saveptr) {
2592 /* handle length expansion ${#var} */
2596 /* maybe handle parameter expansion */
2597 if (exp_saveptr /* if 2nd char is one of expansion operators */
2598 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2600 /* ${?:0}, ${#[:]%0} etc */
2601 exp_saveptr = var + 1;
2603 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2604 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2606 exp_op = exp_save = *exp_saveptr;
2608 exp_word = exp_saveptr + 1;
2609 if (exp_op == ':') {
2610 exp_op = *exp_word++;
2611 if (ENABLE_HUSH_BASH_COMPAT
2612 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2614 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2619 *exp_saveptr = '\0';
2620 } /* else: it's not an expansion op, but bare ${var} */
2623 /* lookup the variable in question */
2624 if (isdigit(var[0])) {
2625 /* parse_dollar() should have vetted var for us */
2627 if (i < G.global_argc)
2628 val = G.global_argv[i];
2629 /* else val remains NULL: $N with too big N */
2633 val = utoa(G.root_pid);
2635 case '!': /* bg pid */
2636 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2638 case '?': /* exitcode */
2639 val = utoa(G.last_exitcode);
2641 case '#': /* argc */
2642 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2645 val = get_local_var_value(var);
2649 /* handle any expansions */
2650 if (exp_op == 'L') {
2651 debug_printf_expand("expand: length(%s)=", val);
2652 val = utoa(val ? strlen(val) : 0);
2653 debug_printf_expand("%s\n", val);
2654 } else if (exp_op) {
2655 if (exp_op == '%' || exp_op == '#') {
2656 /* Standard-mandated substring removal ops:
2657 * ${parameter%word} - remove smallest suffix pattern
2658 * ${parameter%%word} - remove largest suffix pattern
2659 * ${parameter#word} - remove smallest prefix pattern
2660 * ${parameter##word} - remove largest prefix pattern
2662 * Word is expanded to produce a glob pattern.
2663 * Then var's value is matched to it and matching part removed.
2668 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2669 if (exp_op == *exp_word) /* ## or %% */
2671 val = to_be_freed = xstrdup(val);
2673 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2675 exp_word = exp_exp_word;
2676 loc = scan(to_be_freed, exp_word, match_at_left);
2677 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2678 // exp_op, to_be_freed, exp_word, loc);
2681 if (loc) { /* match was found */
2682 if (match_at_left) /* # or ## */
2688 } else if (exp_op == ':') {
2689 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2690 /* It's ${var:N[:M]} bashism.
2691 * Note that in encoded form it has TWO parts:
2692 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2697 beg = expand_and_evaluate_arith(exp_word, &errcode);
2698 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2699 *p++ = SPECIAL_VAR_SYMBOL;
2701 p = strchr(p, SPECIAL_VAR_SYMBOL);
2703 len = expand_and_evaluate_arith(exp_word, &errcode);
2704 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2706 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2707 if (beg < 0) /* bash compat */
2709 debug_printf_varexp("from val:'%s'\n", val);
2710 if (len == 0 || !val || beg >= strlen(val))
2713 /* Paranoia. What if user entered 9999999999999
2714 * which fits in arith_t but not int? */
2717 val = to_be_freed = xstrndup(val + beg, len);
2719 debug_printf_varexp("val:'%s'\n", val);
2723 die_if_script("malformed ${%s:...}", var);
2726 } else { /* one of "-=+?" */
2727 /* Standard-mandated substitution ops:
2728 * ${var?word} - indicate error if unset
2729 * If var is unset, word (or a message indicating it is unset
2730 * if word is null) is written to standard error
2731 * and the shell exits with a non-zero exit status.
2732 * Otherwise, the value of var is substituted.
2733 * ${var-word} - use default value
2734 * If var is unset, word is substituted.
2735 * ${var=word} - assign and use default value
2736 * If var is unset, word is assigned to var.
2737 * In all cases, final value of var is substituted.
2738 * ${var+word} - use alternative value
2739 * If var is unset, null is substituted.
2740 * Otherwise, word is substituted.
2742 * Word is subjected to tilde expansion, parameter expansion,
2743 * command substitution, and arithmetic expansion.
2744 * If word is not needed, it is not expanded.
2746 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2747 * but also treat null var as if it is unset.
2749 int use_word = (!val || ((exp_save == ':') && !val[0]));
2751 use_word = !use_word;
2752 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2753 (exp_save == ':') ? "true" : "false", use_word);
2755 to_be_freed = expand_pseudo_dquoted(exp_word);
2757 exp_word = to_be_freed;
2758 if (exp_op == '?') {
2759 /* mimic bash message */
2760 die_if_script("%s: %s",
2762 exp_word[0] ? exp_word : "parameter null or not set"
2764 //TODO: how interactive bash aborts expansion mid-command?
2769 if (exp_op == '=') {
2770 /* ${var=[word]} or ${var:=[word]} */
2771 if (isdigit(var[0]) || var[0] == '#') {
2772 /* mimic bash message */
2773 die_if_script("$%s: cannot assign in this way", var);
2776 char *new_var = xasprintf("%s=%s", var, val);
2777 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2781 } /* one of "-=+?" */
2783 *exp_saveptr = exp_save;
2787 #if ENABLE_HUSH_TICK
2790 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2791 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2793 /* unquoted var's contents should be globbed, so don't escape */
2794 smallint sv = output->o_escape;
2795 output->o_escape = 0;
2796 n = expand_on_ifs(output, n, val);
2798 output->o_escape = sv;
2800 } else { /* quoted $VAR, val will be appended below */
2801 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2804 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2807 o_addQstr(output, val, strlen(val));
2810 /* Do the check to avoid writing to a const string */
2811 if (*p != SPECIAL_VAR_SYMBOL)
2812 *p = SPECIAL_VAR_SYMBOL;
2814 #if ENABLE_HUSH_TICK
2815 o_free(&subst_result);
2818 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2821 debug_print_list("expand_vars_to_list[a]", output, n);
2822 /* this part is literal, and it was already pre-quoted
2823 * if needed (much earlier), do not use o_addQstr here! */
2824 o_addstr_with_NUL(output, arg);
2825 debug_print_list("expand_vars_to_list[b]", output, n);
2826 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2827 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2830 /* allow to reuse list[n] later without re-growth */
2831 output->has_empty_slot = 1;
2833 o_addchr(output, '\0');
2838 static char **expand_variables(char **argv, int or_mask)
2843 o_string output = NULL_O_STRING;
2845 if (or_mask & 0x100) {
2846 output.o_escape = 1; /* protect against globbing for "$var" */
2847 /* (unquoted $var will temporarily switch it off) */
2854 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2857 debug_print_list("expand_variables", &output, n);
2859 /* output.data (malloced in one block) gets returned in "list" */
2860 list = o_finalize_list(&output, n);
2861 debug_print_strings("expand_variables[1]", list);
2865 static char **expand_strvec_to_strvec(char **argv)
2867 return expand_variables(argv, 0x100);
2870 #if ENABLE_HUSH_BASH_COMPAT
2871 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2873 return expand_variables(argv, 0x80);
2877 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2878 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2883 o_string output = NULL_O_STRING;
2888 int is_var = is_well_formed_var_name(*v, '=');
2889 /* is_var * 0x80: singleword expansion for vars */
2890 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2892 /* Subtle! expand_vars_to_list did not glob last word yet.
2893 * It does this only when fed with further data.
2894 * Therefore we set globbing flags AFTER it, not before:
2897 /* if it is not recognizably abc=...; then: */
2898 output.o_escape = !is_var; /* protect against globbing for "$var" */
2899 /* (unquoted $var will temporarily switch it off) */
2900 output.o_glob = !is_var; /* and indeed do globbing */
2903 debug_print_list("expand_cond", &output, n);
2905 /* output.data (malloced in one block) gets returned in "list" */
2906 list = o_finalize_list(&output, n);
2907 debug_print_strings("expand_cond[1]", list);
2912 /* Used for expansion of right hand of assignments */
2913 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2915 static char *expand_string_to_string(const char *str)
2917 char *argv[2], **list;
2919 argv[0] = (char*)str;
2921 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2923 if (!list[0] || list[1])
2924 bb_error_msg_and_die("BUG in varexp2");
2925 /* actually, just move string 2*sizeof(char*) bytes back */
2926 overlapping_strcpy((char*)list, list[0]);
2927 unbackslash((char*)list);
2928 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2932 /* Used for "eval" builtin */
2933 static char* expand_strvec_to_string(char **argv)
2937 list = expand_variables(argv, 0x80);
2938 /* Convert all NULs to spaces */
2943 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2944 bb_error_msg_and_die("BUG in varexp3");
2945 /* bash uses ' ' regardless of $IFS contents */
2950 overlapping_strcpy((char*)list, list[0]);
2951 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2955 static char **expand_assignments(char **argv, int count)
2959 /* Expand assignments into one string each */
2960 for (i = 0; i < count; i++) {
2961 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2969 void re_execute_shell(char ***to_free, const char *s,
2970 char *g_argv0, char **g_argv,
2971 char **builtin_argv) NORETURN;
2973 static void reset_traps_to_defaults(void)
2975 /* This function is always called in a child shell
2976 * after fork (not vfork, NOMMU doesn't use this function).
2981 /* Child shells are not interactive.
2982 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2983 * Testcase: (while :; do :; done) + ^Z should background.
2984 * Same goes for SIGTERM, SIGHUP, SIGINT.
2986 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2987 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
2989 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2990 * Stupid. It can be done with *single* &= op, but we can't use
2991 * the fact that G.blocked_set is implemented as a bitmask
2993 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2997 /* Careful. Only if no trap or trap is not "" */
2998 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2999 sigdelset(&G.blocked_set, sig);
3006 /* Our homegrown sig mask is saner to work with :) */
3007 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3009 /* Resetting all traps to default except empty ones */
3010 mask = G.non_DFL_mask;
3011 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3012 if (!G.traps[sig] || !G.traps[sig][0])
3015 G.traps[sig] = NULL;
3016 /* There is no signal for 0 (EXIT) */
3019 /* There was a trap handler, we just removed it.
3020 * But if sig still has non-DFL handling,
3021 * we should not unblock the sig. */
3024 sigdelset(&G.blocked_set, sig);
3026 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3031 static void re_execute_shell(char ***to_free, const char *s,
3032 char *g_argv0, char **g_argv,
3033 char **builtin_argv) NORETURN;
3034 static void re_execute_shell(char ***to_free, const char *s,
3035 char *g_argv0, char **g_argv,
3036 char **builtin_argv)
3038 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3039 /* delims + 2 * (number of bytes in printed hex numbers) */
3040 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3041 char *heredoc_argv[4];
3042 struct variable *cur;
3043 # if ENABLE_HUSH_FUNCTIONS
3044 struct function *funcp;
3048 unsigned long long empty_trap_mask;
3050 if (!g_argv0) { /* heredoc */
3051 argv = heredoc_argv;
3052 argv[0] = (char *) G.argv0_for_re_execing;
3053 argv[1] = (char *) "-<";
3054 argv[2] = (char *) s;
3056 pp = &argv[3]; /* used as pointer to empty environment */
3062 if (pp) while (*pp++)
3065 empty_trap_mask = 0;
3068 for (sig = 1; sig < NSIG; sig++) {
3069 if (G.traps[sig] && !G.traps[sig][0])
3070 empty_trap_mask |= 1LL << sig;
3074 sprintf(param_buf, NOMMU_HACK_FMT
3075 , (unsigned) G.root_pid
3076 , (unsigned) G.root_ppid
3077 , (unsigned) G.last_bg_pid
3078 , (unsigned) G.last_exitcode
3081 IF_HUSH_LOOPS(, G.depth_of_loop)
3083 # undef NOMMU_HACK_FMT
3084 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3085 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3088 for (cur = G.top_var; cur; cur = cur->next) {
3089 if (!cur->flg_export || cur->flg_read_only)
3092 # if ENABLE_HUSH_FUNCTIONS
3093 for (funcp = G.top_func; funcp; funcp = funcp->next)
3099 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3100 *pp++ = (char *) G.argv0_for_re_execing;
3102 for (cur = G.top_var; cur; cur = cur->next) {
3103 if (cur->varstr == hush_version_str)
3105 if (cur->flg_read_only) {
3106 *pp++ = (char *) "-R";
3107 *pp++ = cur->varstr;
3108 } else if (!cur->flg_export) {
3109 *pp++ = (char *) "-V";
3110 *pp++ = cur->varstr;
3113 # if ENABLE_HUSH_FUNCTIONS
3114 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3115 *pp++ = (char *) "-F";
3116 *pp++ = funcp->name;
3117 *pp++ = funcp->body_as_string;
3120 /* We can pass activated traps here. Say, -Tnn:trap_string
3122 * However, POSIX says that subshells reset signals with traps
3124 * I tested bash-3.2 and it not only does that with true subshells
3125 * of the form ( list ), but with any forked children shells.
3126 * I set trap "echo W" WINCH; and then tried:
3128 * { echo 1; sleep 20; echo 2; } &
3129 * while true; do echo 1; sleep 20; echo 2; break; done &
3130 * true | { echo 1; sleep 20; echo 2; } | cat
3132 * In all these cases sending SIGWINCH to the child shell
3133 * did not run the trap. If I add trap "echo V" WINCH;
3134 * _inside_ group (just before echo 1), it works.
3136 * I conclude it means we don't need to pass active traps here.
3137 * Even if we would use signal handlers instead of signal masking
3138 * in order to implement trap handling,
3139 * exec syscall below resets signals to SIG_DFL for us.
3141 *pp++ = (char *) "-c";
3144 while (*++builtin_argv)
3145 *pp++ = *builtin_argv;
3146 *pp++ = (char *) "";
3151 /* *pp = NULL; - is already there */
3155 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3156 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3157 execve(bb_busybox_exec_path, argv, pp);
3158 /* Fallback. Useful for init=/bin/hush usage etc */
3159 if (argv[0][0] == '/')
3160 execve(argv[0], argv, pp);
3161 xfunc_error_retval = 127;
3162 bb_error_msg_and_die("can't re-execute the shell");
3164 #endif /* !BB_MMU */
3167 static void setup_heredoc(struct redir_struct *redir)
3169 struct fd_pair pair;
3172 /* the _body_ of heredoc (misleading field name) */
3173 const char *heredoc = redir->rd_filename;
3180 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3181 expanded = expand_pseudo_dquoted(heredoc);
3185 len = strlen(heredoc);
3187 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3189 xmove_fd(pair.rd, redir->rd_fd);
3191 /* Try writing without forking. Newer kernels have
3192 * dynamically growing pipes. Must use non-blocking write! */
3195 written = write(pair.wr, heredoc, len);
3206 ndelay_off(pair.wr);
3208 /* Okay, pipe buffer was not big enough */
3209 /* Note: we must not create a stray child (bastard? :)
3210 * for the unsuspecting parent process. Child creates a grandchild
3211 * and exits before parent execs the process which consumes heredoc
3212 * (that exec happens after we return from this function) */
3219 disable_restore_tty_pgrp_on_exit();
3220 pid = BB_MMU ? xfork() : xvfork();
3224 close(redir->rd_fd); /* read side of the pipe */
3226 full_write(pair.wr, heredoc, len); /* may loop or block */
3229 /* Delegate blocking writes to another process */
3230 xmove_fd(pair.wr, STDOUT_FILENO);
3231 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3235 #if ENABLE_HUSH_FAST
3237 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3239 enable_restore_tty_pgrp_on_exit();
3245 wait(NULL); /* wait till child has died */
3248 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3249 * and stderr if they are redirected. */
3250 static int setup_redirects(struct command *prog, int squirrel[])
3253 struct redir_struct *redir;
3255 for (redir = prog->redirects; redir; redir = redir->next) {
3256 if (redir->rd_type == REDIRECT_HEREDOC2) {
3257 /* rd_fd<<HERE case */
3258 if (squirrel && redir->rd_fd < 3
3259 && squirrel[redir->rd_fd] < 0
3261 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3263 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3265 debug_printf_parse("set heredoc '%s'\n",
3266 redir->rd_filename);
3267 setup_heredoc(redir);
3271 if (redir->rd_dup == REDIRFD_TO_FILE) {
3272 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3274 if (redir->rd_filename == NULL) {
3275 /* Something went wrong in the parse.
3276 * Pretend it didn't happen */
3277 bb_error_msg("bug in redirect parse");
3280 mode = redir_table[redir->rd_type].mode;
3281 p = expand_string_to_string(redir->rd_filename);
3282 openfd = open_or_warn(p, mode);
3285 /* this could get lost if stderr has been redirected, but
3286 * bash and ash both lose it as well (though zsh doesn't!) */
3287 //what the above comment tries to say?
3291 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3292 openfd = redir->rd_dup;
3295 if (openfd != redir->rd_fd) {
3296 if (squirrel && redir->rd_fd < 3
3297 && squirrel[redir->rd_fd] < 0
3299 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3301 if (openfd == REDIRFD_CLOSE) {
3302 /* "n>-" means "close me" */
3303 close(redir->rd_fd);
3305 xdup2(openfd, redir->rd_fd);
3306 if (redir->rd_dup == REDIRFD_TO_FILE)
3314 static void restore_redirects(int squirrel[])
3317 for (i = 0; i < 3; i++) {
3320 /* We simply die on error */
3327 static void free_pipe_list(struct pipe *head);
3329 /* Return code is the exit status of the pipe */
3330 static void free_pipe(struct pipe *pi)
3333 struct command *command;
3334 struct redir_struct *r, *rnext;
3337 if (pi->stopped_cmds > 0) /* why? */
3339 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3340 for (i = 0; i < pi->num_cmds; i++) {
3341 command = &pi->cmds[i];
3342 debug_printf_clean(" command %d:\n", i);
3343 if (command->argv) {
3344 for (a = 0, p = command->argv; *p; a++, p++) {
3345 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3347 free_strings(command->argv);
3348 command->argv = NULL;
3350 /* not "else if": on syntax error, we may have both! */
3351 if (command->group) {
3352 debug_printf_clean(" begin group (cmd_type:%d)\n",
3354 free_pipe_list(command->group);
3355 debug_printf_clean(" end group\n");
3356 command->group = NULL;
3358 /* else is crucial here.
3359 * If group != NULL, child_func is meaningless */
3360 #if ENABLE_HUSH_FUNCTIONS
3361 else if (command->child_func) {
3362 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3363 command->child_func->parent_cmd = NULL;
3367 free(command->group_as_string);
3368 command->group_as_string = NULL;
3370 for (r = command->redirects; r; r = rnext) {
3371 debug_printf_clean(" redirect %d%s",
3372 r->rd_fd, redir_table[r->rd_type].descrip);
3373 /* guard against the case >$FOO, where foo is unset or blank */
3374 if (r->rd_filename) {
3375 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3376 free(r->rd_filename);
3377 r->rd_filename = NULL;
3379 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3383 command->redirects = NULL;
3385 free(pi->cmds); /* children are an array, they get freed all at once */
3393 static void free_pipe_list(struct pipe *head)
3395 struct pipe *pi, *next;
3397 for (pi = head; pi; pi = next) {
3399 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3402 debug_printf_clean("pipe followup code %d\n", pi->followup);
3404 /*pi->next = NULL;*/
3410 static int run_list(struct pipe *pi);
3412 #define parse_stream(pstring, input, end_trigger) \
3413 parse_stream(input, end_trigger)
3415 static struct pipe *parse_stream(char **pstring,
3416 struct in_str *input,
3418 static void parse_and_run_string(const char *s);
3421 static char *find_in_path(const char *arg)
3424 const char *PATH = get_local_var_value("PATH");
3430 const char *end = strchrnul(PATH, ':');
3431 int sz = end - PATH; /* must be int! */
3435 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3437 /* We have xxx::yyyy in $PATH,
3438 * it means "use current dir" */
3441 if (access(ret, F_OK) == 0)
3454 static const struct built_in_command* find_builtin_helper(const char *name,
3455 const struct built_in_command *x,
3456 const struct built_in_command *end)
3459 if (strcmp(name, x->b_cmd) != 0) {
3463 debug_printf_exec("found builtin '%s'\n", name);
3468 static const struct built_in_command* find_builtin1(const char *name)
3470 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3472 static const struct built_in_command* find_builtin(const char *name)
3474 const struct built_in_command *x = find_builtin1(name);
3477 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3480 #if ENABLE_HUSH_FUNCTIONS
3481 static struct function **find_function_slot(const char *name)
3483 struct function **funcpp = &G.top_func;
3485 if (strcmp(name, (*funcpp)->name) == 0) {
3488 funcpp = &(*funcpp)->next;
3493 static const struct function *find_function(const char *name)
3495 const struct function *funcp = *find_function_slot(name);
3497 debug_printf_exec("found function '%s'\n", name);
3501 /* Note: takes ownership on name ptr */
3502 static struct function *new_function(char *name)
3504 struct function **funcpp = find_function_slot(name);
3505 struct function *funcp = *funcpp;
3507 if (funcp != NULL) {
3508 struct command *cmd = funcp->parent_cmd;
3509 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3511 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3513 /* Note: if !funcp->body, do not free body_as_string!
3514 * This is a special case of "-F name body" function:
3515 * body_as_string was not malloced! */
3517 free_pipe_list(funcp->body);
3519 free(funcp->body_as_string);
3523 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3524 cmd->argv[0] = funcp->name;
3525 cmd->group = funcp->body;
3527 cmd->group_as_string = funcp->body_as_string;
3531 debug_printf_exec("remembering new function '%s'\n", name);
3532 funcp = *funcpp = xzalloc(sizeof(*funcp));
3533 /*funcp->next = NULL;*/
3540 static void unset_func(const char *name)
3542 struct function **funcpp = find_function_slot(name);
3543 struct function *funcp = *funcpp;
3545 if (funcp != NULL) {
3546 debug_printf_exec("freeing function '%s'\n", funcp->name);
3547 *funcpp = funcp->next;
3548 /* funcp is unlinked now, deleting it.
3549 * Note: if !funcp->body, the function was created by
3550 * "-F name body", do not free ->body_as_string
3551 * and ->name as they were not malloced. */
3553 free_pipe_list(funcp->body);
3556 free(funcp->body_as_string);
3564 #define exec_function(to_free, funcp, argv) \
3565 exec_function(funcp, argv)
3567 static void exec_function(char ***to_free,
3568 const struct function *funcp,
3569 char **argv) NORETURN;
3570 static void exec_function(char ***to_free,
3571 const struct function *funcp,
3577 argv[0] = G.global_argv[0];
3578 G.global_argv = argv;
3582 /* On MMU, funcp->body is always non-NULL */
3583 n = run_list(funcp->body);
3587 re_execute_shell(to_free,
3588 funcp->body_as_string,
3595 static int run_function(const struct function *funcp, char **argv)
3601 save_and_replace_G_args(&sv, argv);
3603 /* "we are in function, ok to use return" */
3604 sv_flg = G.flag_return_in_progress;
3605 G.flag_return_in_progress = -1;
3606 # if ENABLE_HUSH_LOCAL
3607 G.func_nest_level++;
3610 /* On MMU, funcp->body is always non-NULL */
3613 /* Function defined by -F */
3614 parse_and_run_string(funcp->body_as_string);
3615 rc = G.last_exitcode;
3619 rc = run_list(funcp->body);
3622 # if ENABLE_HUSH_LOCAL
3624 struct variable *var;
3625 struct variable **var_pp;
3627 var_pp = &G.top_var;
3628 while ((var = *var_pp) != NULL) {
3629 if (var->func_nest_level < G.func_nest_level) {
3630 var_pp = &var->next;
3634 if (var->flg_export)
3635 bb_unsetenv(var->varstr);
3636 /* Remove from global list */
3637 *var_pp = var->next;
3643 G.func_nest_level--;
3646 G.flag_return_in_progress = sv_flg;
3648 restore_G_args(&sv, argv);
3652 #endif /* ENABLE_HUSH_FUNCTIONS */
3656 #define exec_builtin(to_free, x, argv) \
3657 exec_builtin(x, argv)
3659 #define exec_builtin(to_free, x, argv) \
3660 exec_builtin(to_free, argv)
3662 static void exec_builtin(char ***to_free,
3663 const struct built_in_command *x,
3664 char **argv) NORETURN;
3665 static void exec_builtin(char ***to_free,
3666 const struct built_in_command *x,
3670 int rcode = x->b_function(argv);
3674 /* On NOMMU, we must never block!
3675 * Example: { sleep 99 | read line; } & echo Ok
3677 re_execute_shell(to_free,
3686 static void execvp_or_die(char **argv) NORETURN;
3687 static void execvp_or_die(char **argv)
3689 debug_printf_exec("execing '%s'\n", argv[0]);
3690 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3691 execvp(argv[0], argv);
3692 bb_perror_msg("can't execute '%s'", argv[0]);
3693 _exit(127); /* bash compat */
3696 static void dump_cmd_in_x_mode(char **argv)
3698 if (G.x_mode && argv) {
3699 /* We want to output the line in one write op */
3707 len += strlen(argv[n++]) + 1;
3713 p += sprintf(p, " %s", argv[n++]);
3722 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3723 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3724 #define pseudo_exec(nommu_save, command, argv_expanded) \
3725 pseudo_exec(command, argv_expanded)
3728 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3730 * Don't exit() here. If you don't exec, use _exit instead.
3731 * The at_exit handlers apparently confuse the calling process,
3732 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3733 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3734 char **argv, int assignment_cnt,
3735 char **argv_expanded) NORETURN;
3736 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3737 char **argv, int assignment_cnt,
3738 char **argv_expanded)
3742 new_env = expand_assignments(argv, assignment_cnt);
3743 dump_cmd_in_x_mode(new_env);
3745 if (!argv[assignment_cnt]) {
3746 /* Case when we are here: ... | var=val | ...
3747 * (note that we do not exit early, i.e., do not optimize out
3748 * expand_assignments(): think about ... | var=`sleep 1` | ...
3750 free_strings(new_env);
3751 _exit(EXIT_SUCCESS);
3755 set_vars_and_save_old(new_env);
3756 free(new_env); /* optional */
3757 /* we can also destroy set_vars_and_save_old's return value,
3760 nommu_save->new_env = new_env;
3761 nommu_save->old_vars = set_vars_and_save_old(new_env);
3764 if (argv_expanded) {
3765 argv = argv_expanded;
3767 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3769 nommu_save->argv = argv;
3772 dump_cmd_in_x_mode(argv);
3774 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3775 if (strchr(argv[0], '/') != NULL)
3779 /* Check if the command matches any of the builtins.
3780 * Depending on context, this might be redundant. But it's
3781 * easier to waste a few CPU cycles than it is to figure out
3782 * if this is one of those cases.
3785 /* On NOMMU, it is more expensive to re-execute shell
3786 * just in order to run echo or test builtin.
3787 * It's better to skip it here and run corresponding
3788 * non-builtin later. */
3789 const struct built_in_command *x;
3790 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3792 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3795 #if ENABLE_HUSH_FUNCTIONS
3796 /* Check if the command matches any functions */
3798 const struct function *funcp = find_function(argv[0]);
3800 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3805 #if ENABLE_FEATURE_SH_STANDALONE
3806 /* Check if the command matches any busybox applets */
3808 int a = find_applet_by_name(argv[0]);
3810 # if BB_MMU /* see above why on NOMMU it is not allowed */
3811 if (APPLET_IS_NOEXEC(a)) {
3812 debug_printf_exec("running applet '%s'\n", argv[0]);
3813 run_applet_no_and_exit(a, argv);
3816 /* Re-exec ourselves */
3817 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3818 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3819 execv(bb_busybox_exec_path, argv);
3820 /* If they called chroot or otherwise made the binary no longer
3821 * executable, fall through */
3826 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3829 execvp_or_die(argv);
3832 /* Called after [v]fork() in run_pipe
3834 static void pseudo_exec(nommu_save_t *nommu_save,
3835 struct command *command,
3836 char **argv_expanded) NORETURN;
3837 static void pseudo_exec(nommu_save_t *nommu_save,
3838 struct command *command,
3839 char **argv_expanded)
3841 if (command->argv) {
3842 pseudo_exec_argv(nommu_save, command->argv,
3843 command->assignment_cnt, argv_expanded);
3846 if (command->group) {
3847 /* Cases when we are here:
3850 * ... | ( list ) | ...
3851 * ... | { list } | ...
3855 debug_printf_exec("pseudo_exec: run_list\n");
3856 reset_traps_to_defaults();
3857 rcode = run_list(command->group);
3858 /* OK to leak memory by not calling free_pipe_list,
3859 * since this process is about to exit */
3862 re_execute_shell(&nommu_save->argv_from_re_execing,
3863 command->group_as_string,
3870 /* Case when we are here: ... | >file */
3871 debug_printf_exec("pseudo_exec'ed null command\n");
3872 _exit(EXIT_SUCCESS);
3876 static const char *get_cmdtext(struct pipe *pi)
3882 /* This is subtle. ->cmdtext is created only on first backgrounding.
3883 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3884 * On subsequent bg argv is trashed, but we won't use it */
3887 argv = pi->cmds[0].argv;
3888 if (!argv || !argv[0]) {
3889 pi->cmdtext = xzalloc(1);
3895 len += strlen(*argv) + 1;
3899 argv = pi->cmds[0].argv;
3901 len = strlen(*argv);
3902 memcpy(p, *argv, len);
3910 static void insert_bg_job(struct pipe *pi)
3912 struct pipe *job, **jobp;
3915 /* Linear search for the ID of the job to use */
3917 for (job = G.job_list; job; job = job->next)
3918 if (job->jobid >= pi->jobid)
3919 pi->jobid = job->jobid + 1;
3921 /* Add job to the list of running jobs */
3923 while ((job = *jobp) != NULL)
3925 job = *jobp = xmalloc(sizeof(*job));
3927 *job = *pi; /* physical copy */
3929 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3930 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3931 for (i = 0; i < pi->num_cmds; i++) {
3932 job->cmds[i].pid = pi->cmds[i].pid;
3933 /* all other fields are not used and stay zero */
3935 job->cmdtext = xstrdup(get_cmdtext(pi));
3937 if (G_interactive_fd)
3938 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3939 /* Last command's pid goes to $! */
3940 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3941 G.last_jobid = job->jobid;
3944 static void remove_bg_job(struct pipe *pi)
3946 struct pipe *prev_pipe;
3948 if (pi == G.job_list) {
3949 G.job_list = pi->next;
3951 prev_pipe = G.job_list;
3952 while (prev_pipe->next != pi)
3953 prev_pipe = prev_pipe->next;
3954 prev_pipe->next = pi->next;
3957 G.last_jobid = G.job_list->jobid;
3962 /* Remove a backgrounded job */
3963 static void delete_finished_bg_job(struct pipe *pi)
3966 pi->stopped_cmds = 0;
3972 /* Check to see if any processes have exited -- if they
3973 * have, figure out why and see if a job has completed */
3974 static int checkjobs(struct pipe* fg_pipe)
3984 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3986 attributes = WUNTRACED;
3987 if (fg_pipe == NULL)
3988 attributes |= WNOHANG;
3991 #if ENABLE_HUSH_FAST
3992 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3993 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3994 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3995 /* There was neither fork nor SIGCHLD since last waitpid */
3996 /* Avoid doing waitpid syscall if possible */
3997 if (!G.we_have_children) {
4001 if (fg_pipe == NULL) { /* is WNOHANG set? */
4002 /* We have children, but they did not exit
4003 * or stop yet (we saw no SIGCHLD) */
4006 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4010 /* Do we do this right?
4011 * bash-3.00# sleep 20 | false
4013 * [3]+ Stopped sleep 20 | false
4014 * bash-3.00# echo $?
4015 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4016 * [hush 1.14.0: yes we do it right]
4023 #if ENABLE_HUSH_FAST
4024 i = G.count_SIGCHLD;
4026 childpid = waitpid(-1, &status, attributes);
4027 if (childpid <= 0) {
4028 if (childpid && errno != ECHILD)
4029 bb_perror_msg("waitpid");
4030 #if ENABLE_HUSH_FAST
4031 else { /* Until next SIGCHLD, waitpid's are useless */
4032 G.we_have_children = (childpid == 0);
4033 G.handled_SIGCHLD = i;
4034 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4039 dead = WIFEXITED(status) || WIFSIGNALED(status);
4042 if (WIFSTOPPED(status))
4043 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4044 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4045 if (WIFSIGNALED(status))
4046 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4047 childpid, WTERMSIG(status), WEXITSTATUS(status));
4048 if (WIFEXITED(status))
4049 debug_printf_jobs("pid %d exited, exitcode %d\n",
4050 childpid, WEXITSTATUS(status));
4052 /* Were we asked to wait for fg pipe? */
4054 for (i = 0; i < fg_pipe->num_cmds; i++) {
4055 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4056 if (fg_pipe->cmds[i].pid != childpid)
4059 fg_pipe->cmds[i].pid = 0;
4060 fg_pipe->alive_cmds--;
4061 if (i == fg_pipe->num_cmds - 1) {
4062 /* last process gives overall exitstatus */
4063 rcode = WEXITSTATUS(status);
4064 /* bash prints killer signal's name for *last*
4065 * process in pipe (prints just newline for SIGINT).
4066 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4068 if (WIFSIGNALED(status)) {
4069 int sig = WTERMSIG(status);
4070 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4071 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4072 * Maybe we need to use sig | 128? */
4075 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4078 fg_pipe->cmds[i].is_stopped = 1;
4079 fg_pipe->stopped_cmds++;
4081 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4082 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4083 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4084 /* All processes in fg pipe have exited or stopped */
4085 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4086 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4087 * and "killall -STOP cat" */
4088 if (G_interactive_fd) {
4090 if (fg_pipe->alive_cmds)
4091 insert_bg_job(fg_pipe);
4095 if (!fg_pipe->alive_cmds)
4098 /* There are still running processes in the fg pipe */
4099 goto wait_more; /* do waitpid again */
4101 /* it wasnt fg_pipe, look for process in bg pipes */
4105 /* We asked to wait for bg or orphaned children */
4106 /* No need to remember exitcode in this case */
4107 for (pi = G.job_list; pi; pi = pi->next) {
4108 for (i = 0; i < pi->num_cmds; i++) {
4109 if (pi->cmds[i].pid == childpid)
4110 goto found_pi_and_prognum;
4113 /* Happens when shell is used as init process (init=/bin/sh) */
4114 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4115 continue; /* do waitpid again */
4117 found_pi_and_prognum:
4120 pi->cmds[i].pid = 0;
4122 if (!pi->alive_cmds) {
4123 if (G_interactive_fd)
4124 printf(JOB_STATUS_FORMAT, pi->jobid,
4125 "Done", pi->cmdtext);
4126 delete_finished_bg_job(pi);
4130 pi->cmds[i].is_stopped = 1;
4134 } /* while (waitpid succeeds)... */
4140 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4143 int rcode = checkjobs(fg_pipe);
4144 if (G_saved_tty_pgrp) {
4145 /* Job finished, move the shell to the foreground */
4146 p = getpgrp(); /* our process group id */
4147 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4148 tcsetpgrp(G_interactive_fd, p);
4154 /* Start all the jobs, but don't wait for anything to finish.
4157 * Return code is normally -1, when the caller has to wait for children
4158 * to finish to determine the exit status of the pipe. If the pipe
4159 * is a simple builtin command, however, the action is done by the
4160 * time run_pipe returns, and the exit code is provided as the
4163 * Returns -1 only if started some children. IOW: we have to
4164 * mask out retvals of builtins etc with 0xff!
4166 * The only case when we do not need to [v]fork is when the pipe
4167 * is single, non-backgrounded, non-subshell command. Examples:
4168 * cmd ; ... { list } ; ...
4169 * cmd && ... { list } && ...
4170 * cmd || ... { list } || ...
4171 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4172 * or (if SH_STANDALONE) an applet, and we can run the { list }
4173 * with run_list. If it isn't one of these, we fork and exec cmd.
4175 * Cases when we must fork:
4176 * non-single: cmd | cmd
4177 * backgrounded: cmd & { list } &
4178 * subshell: ( list ) [&]
4180 static NOINLINE int run_pipe(struct pipe *pi)
4182 static const char *const null_ptr = NULL;
4186 struct command *command;
4187 char **argv_expanded;
4190 /* it is not always needed, but we aim to smaller code */
4191 int squirrel[] = { -1, -1, -1 };
4194 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4197 IF_HUSH_JOB(pi->pgrp = -1;)
4198 pi->stopped_cmds = 0;
4199 command = &pi->cmds[0];
4200 argv_expanded = NULL;
4202 if (pi->num_cmds != 1
4203 || pi->followup == PIPE_BG
4204 || command->cmd_type == CMD_SUBSHELL
4211 debug_printf_exec(": group:%p argv:'%s'\n",
4212 command->group, command->argv ? command->argv[0] : "NONE");
4214 if (command->group) {
4215 #if ENABLE_HUSH_FUNCTIONS
4216 if (command->cmd_type == CMD_FUNCDEF) {
4217 /* "executing" func () { list } */
4218 struct function *funcp;
4220 funcp = new_function(command->argv[0]);
4221 /* funcp->name is already set to argv[0] */
4222 funcp->body = command->group;
4224 funcp->body_as_string = command->group_as_string;
4225 command->group_as_string = NULL;
4227 command->group = NULL;
4228 command->argv[0] = NULL;
4229 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4230 funcp->parent_cmd = command;
4231 command->child_func = funcp;
4233 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4235 return EXIT_SUCCESS;
4239 debug_printf("non-subshell group\n");
4240 rcode = 1; /* exitcode if redir failed */
4241 if (setup_redirects(command, squirrel) == 0) {
4242 debug_printf_exec(": run_list\n");
4243 rcode = run_list(command->group) & 0xff;
4245 restore_redirects(squirrel);
4246 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4248 debug_printf_exec("run_pipe: return %d\n", rcode);
4252 argv = command->argv ? command->argv : (char **) &null_ptr;
4254 const struct built_in_command *x;
4255 #if ENABLE_HUSH_FUNCTIONS
4256 const struct function *funcp;
4260 char **new_env = NULL;
4261 struct variable *old_vars = NULL;
4263 if (argv[command->assignment_cnt] == NULL) {
4264 /* Assignments, but no command */
4265 /* Ensure redirects take effect (that is, create files).
4266 * Try "a=t >file": */
4267 rcode = setup_redirects(command, squirrel);
4268 restore_redirects(squirrel);
4269 /* Set shell variables */
4271 bb_putchar_stderr('+');
4273 p = expand_string_to_string(*argv);
4275 fprintf(stderr, " %s", p);
4276 debug_printf_exec("set shell var:'%s'->'%s'\n",
4278 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4282 bb_putchar_stderr('\n');
4283 /* Redirect error sets $? to 1. Otherwise,
4284 * if evaluating assignment value set $?, retain it.
4285 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4287 rcode = G.last_exitcode;
4288 /* Do we need to flag set_local_var() errors?
4289 * "assignment to readonly var" and "putenv error"
4291 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4293 debug_printf_exec("run_pipe: return %d\n", rcode);
4297 /* Expand the rest into (possibly) many strings each */
4299 #if ENABLE_HUSH_BASH_COMPAT
4300 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4301 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4304 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4305 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4306 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4311 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4314 /* if someone gives us an empty string: `cmd with empty output` */
4315 if (!argv_expanded[0]) {
4316 free(argv_expanded);
4318 return G.last_exitcode;
4321 x = find_builtin(argv_expanded[0]);
4322 #if ENABLE_HUSH_FUNCTIONS
4325 funcp = find_function(argv_expanded[0]);
4329 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4330 debug_printf("exec with redirects only\n");
4331 rcode = setup_redirects(command, NULL);
4332 goto clean_up_and_ret1;
4335 /* setup_redirects acts on file descriptors, not FILEs.
4336 * This is perfect for work that comes after exec().
4337 * Is it really safe for inline use? Experimentally,
4338 * things seem to work. */
4339 rcode = setup_redirects(command, squirrel);
4341 new_env = expand_assignments(argv, command->assignment_cnt);
4342 dump_cmd_in_x_mode(new_env);
4343 dump_cmd_in_x_mode(argv_expanded);
4344 old_vars = set_vars_and_save_old(new_env);
4346 debug_printf_exec(": builtin '%s' '%s'...\n",
4347 x->b_cmd, argv_expanded[1]);
4348 rcode = x->b_function(argv_expanded) & 0xff;
4351 #if ENABLE_HUSH_FUNCTIONS
4353 # if ENABLE_HUSH_LOCAL
4354 struct variable **sv;
4355 sv = G.shadowed_vars_pp;
4356 G.shadowed_vars_pp = &old_vars;
4358 debug_printf_exec(": function '%s' '%s'...\n",
4359 funcp->name, argv_expanded[1]);
4360 rcode = run_function(funcp, argv_expanded) & 0xff;
4361 # if ENABLE_HUSH_LOCAL
4362 G.shadowed_vars_pp = sv;
4368 restore_redirects(squirrel);
4369 unset_vars(new_env);
4372 free(argv_expanded);
4373 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4375 debug_printf_exec("run_pipe return %d\n", rcode);
4379 if (ENABLE_FEATURE_SH_STANDALONE) {
4380 int n = find_applet_by_name(argv_expanded[0]);
4381 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4382 rcode = setup_redirects(command, squirrel);
4384 new_env = expand_assignments(argv, command->assignment_cnt);
4385 dump_cmd_in_x_mode(new_env);
4386 dump_cmd_in_x_mode(argv_expanded);
4387 old_vars = set_vars_and_save_old(new_env);
4388 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4389 argv_expanded[0], argv_expanded[1]);
4390 rcode = run_nofork_applet(n, argv_expanded);
4392 goto clean_up_and_ret;
4395 /* It is neither builtin nor applet. We must fork. */
4399 /* NB: argv_expanded may already be created, and that
4400 * might include `cmd` runs! Do not rerun it! We *must*
4401 * use argv_expanded if it's non-NULL */
4403 /* Going to fork a child per each pipe member */
4408 while (cmd_no < pi->num_cmds) {
4409 struct fd_pair pipefds;
4411 volatile nommu_save_t nommu_save;
4412 nommu_save.new_env = NULL;
4413 nommu_save.old_vars = NULL;
4414 nommu_save.argv = NULL;
4415 nommu_save.argv_from_re_execing = NULL;
4417 command = &pi->cmds[cmd_no];
4419 if (command->argv) {
4420 debug_printf_exec(": pipe member '%s' '%s'...\n",
4421 command->argv[0], command->argv[1]);
4423 debug_printf_exec(": pipe member with no argv\n");
4426 /* pipes are inserted between pairs of commands */
4429 if (cmd_no < pi->num_cmds)
4430 xpiped_pair(pipefds);
4432 command->pid = BB_MMU ? fork() : vfork();
4433 if (!command->pid) { /* child */
4435 disable_restore_tty_pgrp_on_exit();
4436 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4438 /* Every child adds itself to new process group
4439 * with pgid == pid_of_first_child_in_pipe */
4440 if (G.run_list_level == 1 && G_interactive_fd) {
4443 if (pgrp < 0) /* true for 1st process only */
4445 if (setpgid(0, pgrp) == 0
4446 && pi->followup != PIPE_BG
4447 && G_saved_tty_pgrp /* we have ctty */
4449 /* We do it in *every* child, not just first,
4451 tcsetpgrp(G_interactive_fd, pgrp);
4455 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4456 /* 1st cmd in backgrounded pipe
4457 * should have its stdin /dev/null'ed */
4459 if (open(bb_dev_null, O_RDONLY))
4460 xopen("/", O_RDONLY);
4462 xmove_fd(next_infd, 0);
4464 xmove_fd(pipefds.wr, 1);
4467 /* Like bash, explicit redirects override pipes,
4468 * and the pipe fd is available for dup'ing. */
4469 if (setup_redirects(command, NULL))
4472 /* Restore default handlers just prior to exec */
4473 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4475 /* Stores to nommu_save list of env vars putenv'ed
4476 * (NOMMU, on MMU we don't need that) */
4477 /* cast away volatility... */
4478 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4479 /* pseudo_exec() does not return */
4482 /* parent or error */
4483 #if ENABLE_HUSH_FAST
4485 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4487 enable_restore_tty_pgrp_on_exit();
4489 /* Clean up after vforked child */
4490 free(nommu_save.argv);
4491 free(nommu_save.argv_from_re_execing);
4492 unset_vars(nommu_save.new_env);
4493 add_vars(nommu_save.old_vars);
4495 free(argv_expanded);
4496 argv_expanded = NULL;
4497 if (command->pid < 0) { /* [v]fork failed */
4498 /* Clearly indicate, was it fork or vfork */
4499 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4503 /* Second and next children need to know pid of first one */
4505 pi->pgrp = command->pid;
4511 if (cmd_no < pi->num_cmds)
4513 /* Pass read (output) pipe end to next iteration */
4514 next_infd = pipefds.rd;
4517 if (!pi->alive_cmds) {
4519 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4524 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4528 #ifndef debug_print_tree
4529 static void debug_print_tree(struct pipe *pi, int lvl)
4531 static const char *const PIPE[] = {
4537 static const char *RES[] = {
4538 [RES_NONE ] = "NONE" ,
4541 [RES_THEN ] = "THEN" ,
4542 [RES_ELIF ] = "ELIF" ,
4543 [RES_ELSE ] = "ELSE" ,
4546 # if ENABLE_HUSH_LOOPS
4547 [RES_FOR ] = "FOR" ,
4548 [RES_WHILE] = "WHILE",
4549 [RES_UNTIL] = "UNTIL",
4551 [RES_DONE ] = "DONE" ,
4553 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4556 # if ENABLE_HUSH_CASE
4557 [RES_CASE ] = "CASE" ,
4558 [RES_CASE_IN ] = "CASE_IN" ,
4559 [RES_MATCH] = "MATCH",
4560 [RES_CASE_BODY] = "CASE_BODY",
4561 [RES_ESAC ] = "ESAC" ,
4563 [RES_XXXX ] = "XXXX" ,
4564 [RES_SNTX ] = "SNTX" ,
4566 static const char *const CMDTYPE[] = {
4570 # if ENABLE_HUSH_FUNCTIONS
4579 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4580 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4582 while (prn < pi->num_cmds) {
4583 struct command *command = &pi->cmds[prn];
4584 char **argv = command->argv;
4586 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4588 command->assignment_cnt);
4589 if (command->group) {
4590 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4591 CMDTYPE[command->cmd_type],
4594 , " group_as_string:", command->group_as_string
4599 debug_print_tree(command->group, lvl+1);
4603 if (argv) while (*argv) {
4604 fprintf(stderr, " '%s'", *argv);
4607 fprintf(stderr, "\n");
4614 #endif /* debug_print_tree */
4616 /* NB: called by pseudo_exec, and therefore must not modify any
4617 * global data until exec/_exit (we can be a child after vfork!) */
4618 static int run_list(struct pipe *pi)
4620 #if ENABLE_HUSH_CASE
4621 char *case_word = NULL;
4623 #if ENABLE_HUSH_LOOPS
4624 struct pipe *loop_top = NULL;
4625 char **for_lcur = NULL;
4626 char **for_list = NULL;
4628 smallint last_followup;
4630 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4631 smalluint cond_code = 0;
4633 enum { cond_code = 0 };
4636 smallint rword; /* enum reserved_style */
4637 smallint last_rword; /* ditto */
4640 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4643 #if ENABLE_HUSH_LOOPS
4644 /* Check syntax for "for" */
4645 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4646 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4648 /* current word is FOR or IN (BOLD in comments below) */
4649 if (cpipe->next == NULL) {
4650 syntax_error("malformed for");
4652 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4655 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4656 if (cpipe->next->res_word == RES_DO)
4658 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4659 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4660 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4662 syntax_error("malformed for");
4664 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4670 /* Past this point, all code paths should jump to ret: label
4671 * in order to return, no direct "return" statements please.
4672 * This helps to ensure that no memory is leaked. */
4680 last_rword = RES_XXXX;
4682 last_followup = PIPE_SEQ;
4683 rcode = G.last_exitcode;
4685 /* Go through list of pipes, (maybe) executing them. */
4686 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4690 IF_HAS_KEYWORDS(rword = pi->res_word;)
4691 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4692 rword, cond_code, last_rword);
4693 #if ENABLE_HUSH_LOOPS
4694 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4695 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4697 /* start of a loop: remember where loop starts */
4702 /* Still in the same "if...", "then..." or "do..." branch? */
4703 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4704 if ((rcode == 0 && last_followup == PIPE_OR)
4705 || (rcode != 0 && last_followup == PIPE_AND)
4707 /* It is "<true> || CMD" or "<false> && CMD"
4708 * and we should not execute CMD */
4709 debug_printf_exec("skipped cmd because of || or &&\n");
4710 last_followup = pi->followup;
4714 last_followup = pi->followup;
4715 IF_HAS_KEYWORDS(last_rword = rword;)
4718 if (rword == RES_THEN) {
4719 /* if false; then ... fi has exitcode 0! */
4720 G.last_exitcode = rcode = EXIT_SUCCESS;
4721 /* "if <false> THEN cmd": skip cmd */
4725 if (rword == RES_ELSE || rword == RES_ELIF) {
4726 /* "if <true> then ... ELSE/ELIF cmd":
4727 * skip cmd and all following ones */
4732 #if ENABLE_HUSH_LOOPS
4733 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4735 /* first loop through for */
4737 static const char encoded_dollar_at[] ALIGN1 = {
4738 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4739 }; /* encoded representation of "$@" */
4740 static const char *const encoded_dollar_at_argv[] = {
4741 encoded_dollar_at, NULL
4742 }; /* argv list with one element: "$@" */
4745 vals = (char**)encoded_dollar_at_argv;
4746 if (pi->next->res_word == RES_IN) {
4747 /* if no variable values after "in" we skip "for" */
4748 if (!pi->next->cmds[0].argv) {
4749 G.last_exitcode = rcode = EXIT_SUCCESS;
4750 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4753 vals = pi->next->cmds[0].argv;
4754 } /* else: "for var; do..." -> assume "$@" list */
4755 /* create list of variable values */
4756 debug_print_strings("for_list made from", vals);
4757 for_list = expand_strvec_to_strvec(vals);
4758 for_lcur = for_list;
4759 debug_print_strings("for_list", for_list);
4762 /* "for" loop is over, clean up */
4768 /* Insert next value from for_lcur */
4769 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4770 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4773 if (rword == RES_IN) {
4774 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4776 if (rword == RES_DONE) {
4777 continue; /* "done" has no cmds too */
4780 #if ENABLE_HUSH_CASE
4781 if (rword == RES_CASE) {
4782 case_word = expand_strvec_to_string(pi->cmds->argv);
4785 if (rword == RES_MATCH) {
4788 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4790 /* all prev words didn't match, does this one match? */
4791 argv = pi->cmds->argv;
4793 char *pattern = expand_string_to_string(*argv);
4794 /* TODO: which FNM_xxx flags to use? */
4795 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4797 if (cond_code == 0) { /* match! we will execute this branch */
4798 free(case_word); /* make future "word)" stop */
4806 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4808 continue; /* not matched yet, skip this pipe */
4811 /* Just pressing <enter> in shell should check for jobs.
4812 * OTOH, in non-interactive shell this is useless
4813 * and only leads to extra job checks */
4814 if (pi->num_cmds == 0) {
4815 if (G_interactive_fd)
4816 goto check_jobs_and_continue;
4820 /* After analyzing all keywords and conditions, we decided
4821 * to execute this pipe. NB: have to do checkjobs(NULL)
4822 * after run_pipe to collect any background children,
4823 * even if list execution is to be stopped. */
4824 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4827 #if ENABLE_HUSH_LOOPS
4828 G.flag_break_continue = 0;
4830 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4832 /* We ran a builtin, function, or group.
4833 * rcode is already known
4834 * and we don't need to wait for anything. */
4835 G.last_exitcode = rcode;
4836 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4837 check_and_run_traps(0);
4838 #if ENABLE_HUSH_LOOPS
4839 /* Was it "break" or "continue"? */
4840 if (G.flag_break_continue) {
4841 smallint fbc = G.flag_break_continue;
4842 /* We might fall into outer *loop*,
4843 * don't want to break it too */
4845 G.depth_break_continue--;
4846 if (G.depth_break_continue == 0)
4847 G.flag_break_continue = 0;
4848 /* else: e.g. "continue 2" should *break* once, *then* continue */
4849 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4850 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4851 goto check_jobs_and_break;
4852 /* "continue": simulate end of loop */
4857 #if ENABLE_HUSH_FUNCTIONS
4858 if (G.flag_return_in_progress == 1) {
4859 /* same as "goto check_jobs_and_break" */
4864 } else if (pi->followup == PIPE_BG) {
4865 /* What does bash do with attempts to background builtins? */
4866 /* even bash 3.2 doesn't do that well with nested bg:
4867 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4868 * I'm NOT treating inner &'s as jobs */
4869 check_and_run_traps(0);
4871 if (G.run_list_level == 1)
4874 G.last_exitcode = rcode = EXIT_SUCCESS;
4875 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4878 if (G.run_list_level == 1 && G_interactive_fd) {
4879 /* Waits for completion, then fg's main shell */
4880 rcode = checkjobs_and_fg_shell(pi);
4881 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4882 check_and_run_traps(0);
4885 { /* This one just waits for completion */
4886 rcode = checkjobs(pi);
4887 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4888 check_and_run_traps(0);
4890 G.last_exitcode = rcode;
4894 /* Analyze how result affects subsequent commands */
4896 if (rword == RES_IF || rword == RES_ELIF)
4899 #if ENABLE_HUSH_LOOPS
4900 /* Beware of "while false; true; do ..."! */
4901 if (pi->next && pi->next->res_word == RES_DO) {
4902 if (rword == RES_WHILE) {
4904 /* "while false; do...done" - exitcode 0 */
4905 G.last_exitcode = rcode = EXIT_SUCCESS;
4906 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4907 goto check_jobs_and_break;
4910 if (rword == RES_UNTIL) {
4912 debug_printf_exec(": until expr is true: breaking\n");
4913 check_jobs_and_break:
4921 check_jobs_and_continue:
4928 #if ENABLE_HUSH_LOOPS
4933 #if ENABLE_HUSH_CASE
4937 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4941 /* Select which version we will use */
4942 static int run_and_free_list(struct pipe *pi)
4945 debug_printf_exec("run_and_free_list entered\n");
4947 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4948 rcode = run_list(pi);
4950 /* free_pipe_list has the side effect of clearing memory.
4951 * In the long run that function can be merged with run_list,
4952 * but doing that now would hobble the debugging effort. */
4954 debug_printf_exec("run_and_free_list return %d\n", rcode);
4959 static struct pipe *new_pipe(void)
4962 pi = xzalloc(sizeof(struct pipe));
4963 /*pi->followup = 0; - deliberately invalid value */
4964 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4968 /* Command (member of a pipe) is complete, or we start a new pipe
4969 * if ctx->command is NULL.
4970 * No errors possible here.
4972 static int done_command(struct parse_context *ctx)
4974 /* The command is really already in the pipe structure, so
4975 * advance the pipe counter and make a new, null command. */
4976 struct pipe *pi = ctx->pipe;
4977 struct command *command = ctx->command;
4980 if (IS_NULL_CMD(command)) {
4981 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4985 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4986 //debug_print_tree(ctx->list_head, 20);
4988 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4991 /* Only real trickiness here is that the uncommitted
4992 * command structure is not counted in pi->num_cmds. */
4993 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4994 ctx->command = command = &pi->cmds[pi->num_cmds];
4996 memset(command, 0, sizeof(*command));
4997 return pi->num_cmds; /* used only for 0/nonzero check */
5000 static void done_pipe(struct parse_context *ctx, pipe_style type)
5004 debug_printf_parse("done_pipe entered, followup %d\n", type);
5005 /* Close previous command */
5006 not_null = done_command(ctx);
5007 ctx->pipe->followup = type;
5009 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5010 ctx->ctx_inverted = 0;
5011 ctx->pipe->res_word = ctx->ctx_res_w;
5014 /* Without this check, even just <enter> on command line generates
5015 * tree of three NOPs (!). Which is harmless but annoying.
5016 * IOW: it is safe to do it unconditionally. */
5019 || ctx->ctx_res_w == RES_FI
5021 #if ENABLE_HUSH_LOOPS
5022 || ctx->ctx_res_w == RES_DONE
5023 || ctx->ctx_res_w == RES_FOR
5024 || ctx->ctx_res_w == RES_IN
5026 #if ENABLE_HUSH_CASE
5027 || ctx->ctx_res_w == RES_ESAC
5031 debug_printf_parse("done_pipe: adding new pipe: "
5032 "not_null:%d ctx->ctx_res_w:%d\n",
5033 not_null, ctx->ctx_res_w);
5035 ctx->pipe->next = new_p;
5037 /* RES_THEN, RES_DO etc are "sticky" -
5038 * they remain set for pipes inside if/while.
5039 * This is used to control execution.
5040 * RES_FOR and RES_IN are NOT sticky (needed to support
5041 * cases where variable or value happens to match a keyword):
5043 #if ENABLE_HUSH_LOOPS
5044 if (ctx->ctx_res_w == RES_FOR
5045 || ctx->ctx_res_w == RES_IN)
5046 ctx->ctx_res_w = RES_NONE;
5048 #if ENABLE_HUSH_CASE
5049 if (ctx->ctx_res_w == RES_MATCH)
5050 ctx->ctx_res_w = RES_CASE_BODY;
5051 if (ctx->ctx_res_w == RES_CASE)
5052 ctx->ctx_res_w = RES_CASE_IN;
5054 ctx->command = NULL; /* trick done_command below */
5055 /* Create the memory for command, roughly:
5056 * ctx->pipe->cmds = new struct command;
5057 * ctx->command = &ctx->pipe->cmds[0];
5060 //debug_print_tree(ctx->list_head, 10);
5062 debug_printf_parse("done_pipe return\n");
5065 static void initialize_context(struct parse_context *ctx)
5067 memset(ctx, 0, sizeof(*ctx));
5068 ctx->pipe = ctx->list_head = new_pipe();
5069 /* Create the memory for command, roughly:
5070 * ctx->pipe->cmds = new struct command;
5071 * ctx->command = &ctx->pipe->cmds[0];
5076 /* If a reserved word is found and processed, parse context is modified
5077 * and 1 is returned.
5080 struct reserved_combo {
5083 unsigned char assignment_flag;
5087 FLAG_END = (1 << RES_NONE ),
5089 FLAG_IF = (1 << RES_IF ),
5090 FLAG_THEN = (1 << RES_THEN ),
5091 FLAG_ELIF = (1 << RES_ELIF ),
5092 FLAG_ELSE = (1 << RES_ELSE ),
5093 FLAG_FI = (1 << RES_FI ),
5095 # if ENABLE_HUSH_LOOPS
5096 FLAG_FOR = (1 << RES_FOR ),
5097 FLAG_WHILE = (1 << RES_WHILE),
5098 FLAG_UNTIL = (1 << RES_UNTIL),
5099 FLAG_DO = (1 << RES_DO ),
5100 FLAG_DONE = (1 << RES_DONE ),
5101 FLAG_IN = (1 << RES_IN ),
5103 # if ENABLE_HUSH_CASE
5104 FLAG_MATCH = (1 << RES_MATCH),
5105 FLAG_ESAC = (1 << RES_ESAC ),
5107 FLAG_START = (1 << RES_XXXX ),
5110 static const struct reserved_combo* match_reserved_word(o_string *word)
5112 /* Mostly a list of accepted follow-up reserved words.
5113 * FLAG_END means we are done with the sequence, and are ready
5114 * to turn the compound list into a command.
5115 * FLAG_START means the word must start a new compound list.
5117 static const struct reserved_combo reserved_list[] = {
5119 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5120 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5121 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5122 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5123 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5124 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5126 # if ENABLE_HUSH_LOOPS
5127 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5128 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5129 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5130 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5131 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5132 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5134 # if ENABLE_HUSH_CASE
5135 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5136 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5139 const struct reserved_combo *r;
5141 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5142 if (strcmp(word->data, r->literal) == 0)
5147 /* Return 0: not a keyword, 1: keyword
5149 static int reserved_word(o_string *word, struct parse_context *ctx)
5151 # if ENABLE_HUSH_CASE
5152 static const struct reserved_combo reserved_match = {
5153 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5156 const struct reserved_combo *r;
5160 r = match_reserved_word(word);
5164 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5165 # if ENABLE_HUSH_CASE
5166 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5167 /* "case word IN ..." - IN part starts first MATCH part */
5168 r = &reserved_match;
5171 if (r->flag == 0) { /* '!' */
5172 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5173 syntax_error("! ! command");
5174 ctx->ctx_res_w = RES_SNTX;
5176 ctx->ctx_inverted = 1;
5179 if (r->flag & FLAG_START) {
5180 struct parse_context *old;
5182 old = xmalloc(sizeof(*old));
5183 debug_printf_parse("push stack %p\n", old);
5184 *old = *ctx; /* physical copy */
5185 initialize_context(ctx);
5187 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5188 syntax_error_at(word->data);
5189 ctx->ctx_res_w = RES_SNTX;
5192 /* "{...} fi" is ok. "{...} if" is not
5194 * if { echo foo; } then { echo bar; } fi */
5195 if (ctx->command->group)
5196 done_pipe(ctx, PIPE_SEQ);
5199 ctx->ctx_res_w = r->res;
5200 ctx->old_flag = r->flag;
5201 word->o_assignment = r->assignment_flag;
5203 if (ctx->old_flag & FLAG_END) {
5204 struct parse_context *old;
5206 done_pipe(ctx, PIPE_SEQ);
5207 debug_printf_parse("pop stack %p\n", ctx->stack);
5209 old->command->group = ctx->list_head;
5210 old->command->cmd_type = CMD_NORMAL;
5212 o_addstr(&old->as_string, ctx->as_string.data);
5213 o_free_unsafe(&ctx->as_string);
5214 old->command->group_as_string = xstrdup(old->as_string.data);
5215 debug_printf_parse("pop, remembering as:'%s'\n",
5216 old->command->group_as_string);
5218 *ctx = *old; /* physical copy */
5223 #endif /* HAS_KEYWORDS */
5225 /* Word is complete, look at it and update parsing context.
5226 * Normal return is 0. Syntax errors return 1.
5227 * Note: on return, word is reset, but not o_free'd!
5229 static int done_word(o_string *word, struct parse_context *ctx)
5231 struct command *command = ctx->command;
5233 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5234 if (word->length == 0 && word->o_quoted == 0) {
5235 debug_printf_parse("done_word return 0: true null, ignored\n");
5239 if (ctx->pending_redirect) {
5240 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5241 * only if run as "bash", not "sh" */
5242 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5244 * ...the word that follows the redirection operator
5245 * shall be subjected to tilde expansion, parameter expansion,
5246 * command substitution, arithmetic expansion, and quote
5247 * removal. Pathname expansion shall not be performed
5248 * on the word by a non-interactive shell; an interactive
5249 * shell may perform it, but shall do so only when
5250 * the expansion would result in one word."
5252 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5253 /* Cater for >\file case:
5254 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5255 * Same with heredocs:
5256 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5258 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5259 unbackslash(ctx->pending_redirect->rd_filename);
5260 /* Is it <<"HEREDOC"? */
5261 if (word->o_quoted) {
5262 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5265 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5266 ctx->pending_redirect = NULL;
5268 /* If this word wasn't an assignment, next ones definitely
5269 * can't be assignments. Even if they look like ones. */
5270 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5271 && word->o_assignment != WORD_IS_KEYWORD
5273 word->o_assignment = NOT_ASSIGNMENT;
5275 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5276 command->assignment_cnt++;
5277 word->o_assignment = MAYBE_ASSIGNMENT;
5281 # if ENABLE_HUSH_CASE
5282 if (ctx->ctx_dsemicolon
5283 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5285 /* already done when ctx_dsemicolon was set to 1: */
5286 /* ctx->ctx_res_w = RES_MATCH; */
5287 ctx->ctx_dsemicolon = 0;
5290 if (!command->argv /* if it's the first word... */
5291 # if ENABLE_HUSH_LOOPS
5292 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5293 && ctx->ctx_res_w != RES_IN
5295 # if ENABLE_HUSH_CASE
5296 && ctx->ctx_res_w != RES_CASE
5299 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5300 if (reserved_word(word, ctx)) {
5301 o_reset_to_empty_unquoted(word);
5302 debug_printf_parse("done_word return %d\n",
5303 (ctx->ctx_res_w == RES_SNTX));
5304 return (ctx->ctx_res_w == RES_SNTX);
5306 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5307 if (strcmp(word->data, "export") == 0
5308 # if ENABLE_HUSH_LOCAL
5309 || strcmp(word->data, "local") == 0
5312 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5315 # if ENABLE_HUSH_BASH_COMPAT
5316 if (strcmp(word->data, "[[") == 0) {
5317 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5323 if (command->group) {
5324 /* "{ echo foo; } echo bar" - bad */
5325 syntax_error_at(word->data);
5326 debug_printf_parse("done_word return 1: syntax error, "
5327 "groups and arglists don't mix\n");
5330 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5331 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5332 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5333 /* (otherwise it's known to be not empty and is already safe) */
5335 /* exclude "$@" - it can expand to no word despite "" */
5336 char *p = word->data;
5337 while (p[0] == SPECIAL_VAR_SYMBOL
5338 && (p[1] & 0x7f) == '@'
5339 && p[2] == SPECIAL_VAR_SYMBOL
5343 if (p == word->data || p[0] != '\0') {
5344 /* saw no "$@", or not only "$@" but some
5345 * real text is there too */
5346 /* insert "empty variable" reference, this makes
5347 * e.g. "", $empty"" etc to not disappear */
5348 o_addchr(word, SPECIAL_VAR_SYMBOL);
5349 o_addchr(word, SPECIAL_VAR_SYMBOL);
5352 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5353 debug_print_strings("word appended to argv", command->argv);
5356 #if ENABLE_HUSH_LOOPS
5357 if (ctx->ctx_res_w == RES_FOR) {
5359 || !is_well_formed_var_name(command->argv[0], '\0')
5361 /* bash says just "not a valid identifier" */
5362 syntax_error("not a valid identifier in for");
5365 /* Force FOR to have just one word (variable name) */
5366 /* NB: basically, this makes hush see "for v in ..."
5367 * syntax as if it is "for v; in ...". FOR and IN become
5368 * two pipe structs in parse tree. */
5369 done_pipe(ctx, PIPE_SEQ);
5372 #if ENABLE_HUSH_CASE
5373 /* Force CASE to have just one word */
5374 if (ctx->ctx_res_w == RES_CASE) {
5375 done_pipe(ctx, PIPE_SEQ);
5379 o_reset_to_empty_unquoted(word);
5381 debug_printf_parse("done_word return 0\n");
5386 /* Peek ahead in the input to find out if we have a "&n" construct,
5387 * as in "2>&1", that represents duplicating a file descriptor.
5389 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5390 * REDIRFD_SYNTAX_ERR if syntax error,
5391 * REDIRFD_TO_FILE if no & was seen,
5392 * or the number found.
5395 #define parse_redir_right_fd(as_string, input) \
5396 parse_redir_right_fd(input)
5398 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5404 return REDIRFD_TO_FILE;
5406 ch = i_getch(input); /* get the & */
5407 nommu_addchr(as_string, ch);
5410 ch = i_getch(input);
5411 nommu_addchr(as_string, ch);
5412 return REDIRFD_CLOSE;
5416 while (ch != EOF && isdigit(ch)) {
5417 d = d*10 + (ch-'0');
5419 ch = i_getch(input);
5420 nommu_addchr(as_string, ch);
5425 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5427 bb_error_msg("ambiguous redirect");
5428 return REDIRFD_SYNTAX_ERR;
5431 /* Return code is 0 normal, 1 if a syntax error is detected
5433 static int parse_redirect(struct parse_context *ctx,
5436 struct in_str *input)
5438 struct command *command = ctx->command;
5439 struct redir_struct *redir;
5440 struct redir_struct **redirp;
5443 dup_num = REDIRFD_TO_FILE;
5444 if (style != REDIRECT_HEREDOC) {
5445 /* Check for a '>&1' type redirect */
5446 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5447 if (dup_num == REDIRFD_SYNTAX_ERR)
5450 int ch = i_peek(input);
5451 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5452 if (dup_num) { /* <<-... */
5453 ch = i_getch(input);
5454 nommu_addchr(&ctx->as_string, ch);
5459 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5460 int ch = i_peek(input);
5462 /* >|FILE redirect ("clobbering" >).
5463 * Since we do not support "set -o noclobber" yet,
5464 * >| and > are the same for now. Just eat |.
5466 ch = i_getch(input);
5467 nommu_addchr(&ctx->as_string, ch);
5471 /* Create a new redir_struct and append it to the linked list */
5472 redirp = &command->redirects;
5473 while ((redir = *redirp) != NULL) {
5474 redirp = &(redir->next);
5476 *redirp = redir = xzalloc(sizeof(*redir));
5477 /* redir->next = NULL; */
5478 /* redir->rd_filename = NULL; */
5479 redir->rd_type = style;
5480 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5482 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5483 redir_table[style].descrip);
5485 redir->rd_dup = dup_num;
5486 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5487 /* Erik had a check here that the file descriptor in question
5488 * is legit; I postpone that to "run time"
5489 * A "-" representation of "close me" shows up as a -3 here */
5490 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5491 redir->rd_fd, redir->rd_dup);
5493 /* Set ctx->pending_redirect, so we know what to do at the
5494 * end of the next parsed word. */
5495 ctx->pending_redirect = redir;
5500 /* If a redirect is immediately preceded by a number, that number is
5501 * supposed to tell which file descriptor to redirect. This routine
5502 * looks for such preceding numbers. In an ideal world this routine
5503 * needs to handle all the following classes of redirects...
5504 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5505 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5506 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5507 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5509 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5511 * ... If n is quoted, the number shall not be recognized as part of
5512 * the redirection expression. For example:
5514 * writes the character 2 into file a"
5515 * We are getting it right by setting ->o_quoted on any \<char>
5517 * A -1 return means no valid number was found,
5518 * the caller should use the appropriate default for this redirection.
5520 static int redirect_opt_num(o_string *o)
5524 if (o->data == NULL)
5526 num = bb_strtou(o->data, NULL, 10);
5527 if (errno || num < 0)
5529 o_reset_to_empty_unquoted(o);
5534 #define fetch_till_str(as_string, input, word, skip_tabs) \
5535 fetch_till_str(input, word, skip_tabs)
5537 static char *fetch_till_str(o_string *as_string,
5538 struct in_str *input,
5542 o_string heredoc = NULL_O_STRING;
5548 ch = i_getch(input);
5549 nommu_addchr(as_string, ch);
5551 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5552 heredoc.data[past_EOL] = '\0';
5553 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5554 return heredoc.data;
5557 o_addchr(&heredoc, ch);
5558 past_EOL = heredoc.length;
5561 ch = i_getch(input);
5562 nommu_addchr(as_string, ch);
5563 } while (skip_tabs && ch == '\t');
5564 } while (ch == '\n');
5567 o_free_unsafe(&heredoc);
5570 o_addchr(&heredoc, ch);
5571 nommu_addchr(as_string, ch);
5575 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5576 * and load them all. There should be exactly heredoc_cnt of them.
5578 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5580 struct pipe *pi = ctx->list_head;
5582 while (pi && heredoc_cnt) {
5584 struct command *cmd = pi->cmds;
5586 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5588 cmd->argv ? cmd->argv[0] : "NONE");
5589 for (i = 0; i < pi->num_cmds; i++) {
5590 struct redir_struct *redir = cmd->redirects;
5592 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5593 i, cmd->argv ? cmd->argv[0] : "NONE");
5595 if (redir->rd_type == REDIRECT_HEREDOC) {
5598 redir->rd_type = REDIRECT_HEREDOC2;
5599 /* redir->rd_dup is (ab)used to indicate <<- */
5600 p = fetch_till_str(&ctx->as_string, input,
5601 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5603 syntax_error("unexpected EOF in here document");
5606 free(redir->rd_filename);
5607 redir->rd_filename = p;
5610 redir = redir->next;
5617 /* Should be 0. If it isn't, it's a parse error */
5619 bb_error_msg_and_die("heredoc BUG 2");
5625 #if ENABLE_HUSH_TICK
5626 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5631 char **to_free = NULL;
5635 pid = BB_MMU ? xfork() : xvfork();
5636 if (pid == 0) { /* child */
5637 disable_restore_tty_pgrp_on_exit();
5638 /* Process substitution is not considered to be usual
5639 * 'command execution'.
5640 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5647 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5648 close(channel[0]); /* NB: close _first_, then move fd! */
5649 xmove_fd(channel[1], 1);
5650 /* Prevent it from trying to handle ctrl-z etc */
5651 IF_HUSH_JOB(G.run_list_level = 1;)
5652 /* Awful hack for `trap` or $(trap).
5654 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5655 * contains an example where "trap" is executed in a subshell:
5657 * save_traps=$(trap)
5659 * eval "$save_traps"
5661 * Standard does not say that "trap" in subshell shall print
5662 * parent shell's traps. It only says that its output
5663 * must have suitable form, but then, in the above example
5664 * (which is not supposed to be normative), it implies that.
5666 * bash (and probably other shell) does implement it
5667 * (traps are reset to defaults, but "trap" still shows them),
5668 * but as a result, "trap" logic is hopelessly messed up:
5671 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5672 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5673 * # true | trap <--- trap is in subshell - no output (ditto)
5674 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5675 * trap -- 'echo Ho' SIGWINCH
5676 * # echo `(trap)` <--- in subshell in subshell - output
5677 * trap -- 'echo Ho' SIGWINCH
5678 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5679 * trap -- 'echo Ho' SIGWINCH
5681 * The rules when to forget and when to not forget traps
5682 * get really complex and nonsensical.
5684 * Our solution: ONLY bare $(trap) or `trap` is special.
5686 s = skip_whitespace(s);
5687 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5689 static const char *const argv[] = { NULL, NULL };
5690 builtin_trap((char**)argv);
5691 exit(0); /* not _exit() - we need to fflush */
5694 reset_traps_to_defaults();
5695 parse_and_run_string(s);
5696 _exit(G.last_exitcode);
5698 /* We re-execute after vfork on NOMMU. This makes this script safe:
5699 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5700 * huge=`cat BIG` # was blocking here forever
5703 re_execute_shell(&to_free,
5713 # if ENABLE_HUSH_FAST
5715 //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);
5717 enable_restore_tty_pgrp_on_exit();
5722 close_on_exec_on(channel[0]);
5723 return xfdopen_for_read(channel[0]);
5726 /* Return code is exit status of the process that is run. */
5727 static int process_command_subs(o_string *dest, const char *s)
5730 struct in_str pipe_str;
5732 int status, ch, eol_cnt;
5734 fp = generate_stream_from_string(s, &pid);
5736 /* Now send results of command back into original context */
5737 setup_file_in_str(&pipe_str, fp);
5739 while ((ch = i_getch(&pipe_str)) != EOF) {
5745 o_addchr(dest, '\n');
5748 o_addQchr(dest, ch);
5751 debug_printf("done reading from `cmd` pipe, closing it\n");
5753 /* We need to extract exitcode. Test case
5754 * "true; echo `sleep 1; false` $?"
5756 safe_waitpid(pid, &status, 0);
5757 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5758 return WEXITSTATUS(status);
5760 #endif /* ENABLE_HUSH_TICK */
5762 #if !ENABLE_HUSH_FUNCTIONS
5763 #define parse_group(dest, ctx, input, ch) \
5764 parse_group(ctx, input, ch)
5766 static int parse_group(o_string *dest, struct parse_context *ctx,
5767 struct in_str *input, int ch)
5769 /* dest contains characters seen prior to ( or {.
5770 * Typically it's empty, but for function defs,
5771 * it contains function name (without '()'). */
5772 struct pipe *pipe_list;
5774 struct command *command = ctx->command;
5776 debug_printf_parse("parse_group entered\n");
5777 #if ENABLE_HUSH_FUNCTIONS
5778 if (ch == '(' && !dest->o_quoted) {
5780 if (done_word(dest, ctx))
5783 goto skip; /* (... */
5784 if (command->argv[1]) { /* word word ... (... */
5785 syntax_error_unexpected_ch('(');
5788 /* it is "word(..." or "word (..." */
5790 ch = i_getch(input);
5791 while (ch == ' ' || ch == '\t');
5793 syntax_error_unexpected_ch(ch);
5796 nommu_addchr(&ctx->as_string, ch);
5798 ch = i_getch(input);
5799 while (ch == ' ' || ch == '\t' || ch == '\n');
5801 syntax_error_unexpected_ch(ch);
5804 nommu_addchr(&ctx->as_string, ch);
5805 command->cmd_type = CMD_FUNCDEF;
5810 #if 0 /* Prevented by caller */
5811 if (command->argv /* word [word]{... */
5812 || dest->length /* word{... */
5813 || dest->o_quoted /* ""{... */
5816 debug_printf_parse("parse_group return 1: "
5817 "syntax error, groups and arglists don't mix\n");
5822 #if ENABLE_HUSH_FUNCTIONS
5828 command->cmd_type = CMD_SUBSHELL;
5830 /* bash does not allow "{echo...", requires whitespace */
5831 ch = i_getch(input);
5832 if (ch != ' ' && ch != '\t' && ch != '\n') {
5833 syntax_error_unexpected_ch(ch);
5836 nommu_addchr(&ctx->as_string, ch);
5841 # define as_string NULL
5843 char *as_string = NULL;
5845 pipe_list = parse_stream(&as_string, input, endch);
5848 o_addstr(&ctx->as_string, as_string);
5850 /* empty ()/{} or parse error? */
5851 if (!pipe_list || pipe_list == ERR_PTR) {
5852 /* parse_stream already emitted error msg */
5855 debug_printf_parse("parse_group return 1: "
5856 "parse_stream returned %p\n", pipe_list);
5859 command->group = pipe_list;
5861 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5862 command->group_as_string = as_string;
5863 debug_printf_parse("end of group, remembering as:'%s'\n",
5864 command->group_as_string);
5868 debug_printf_parse("parse_group return 0\n");
5870 /* command remains "open", available for possible redirects */
5873 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
5874 /* Subroutines for copying $(...) and `...` things */
5875 static void add_till_backquote(o_string *dest, struct in_str *input);
5877 static void add_till_single_quote(o_string *dest, struct in_str *input)
5880 int ch = i_getch(input);
5882 syntax_error_unterm_ch('\'');
5883 /*xfunc_die(); - redundant */
5890 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5891 static void add_till_double_quote(o_string *dest, struct in_str *input)
5894 int ch = i_getch(input);
5896 syntax_error_unterm_ch('"');
5897 /*xfunc_die(); - redundant */
5901 if (ch == '\\') { /* \x. Copy both chars. */
5903 ch = i_getch(input);
5907 add_till_backquote(dest, input);
5911 //if (ch == '$') ...
5914 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5916 * "Within the backquoted style of command substitution, backslash
5917 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5918 * The search for the matching backquote shall be satisfied by the first
5919 * backquote found without a preceding backslash; during this search,
5920 * if a non-escaped backquote is encountered within a shell comment,
5921 * a here-document, an embedded command substitution of the $(command)
5922 * form, or a quoted string, undefined results occur. A single-quoted
5923 * or double-quoted string that begins, but does not end, within the
5924 * "`...`" sequence produces undefined results."
5926 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5928 static void add_till_backquote(o_string *dest, struct in_str *input)
5931 int ch = i_getch(input);
5933 syntax_error_unterm_ch('`');
5934 /*xfunc_die(); - redundant */
5939 /* \x. Copy both chars unless it is \` */
5940 int ch2 = i_getch(input);
5942 syntax_error_unterm_ch('`');
5943 /*xfunc_die(); - redundant */
5945 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5952 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5953 * quoting and nested ()s.
5954 * "With the $(command) style of command substitution, all characters
5955 * following the open parenthesis to the matching closing parenthesis
5956 * constitute the command. Any valid shell script can be used for command,
5957 * except a script consisting solely of redirections which produces
5958 * unspecified results."
5960 * echo $(echo '(TEST)' BEST) (TEST) BEST
5961 * echo $(echo 'TEST)' BEST) TEST) BEST
5962 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5964 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
5965 * can contain arbitrary constructs, just like $(cmd).
5966 * In bash compat mode, it needs to also be able to stop on '}' or ':'
5967 * for ${var:N[:M]} parsing.
5969 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
5970 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
5973 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
5974 # if ENABLE_HUSH_BASH_COMPAT
5975 char end_char2 = end_ch >> 8;
5977 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
5980 ch = i_getch(input);
5982 syntax_error_unterm_ch(end_ch);
5983 /*xfunc_die(); - redundant */
5985 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
5988 /* we look for closing )) of $((EXPR)) */
5989 if (i_peek(input) == end_ch) {
5990 i_getch(input); /* eat second ')' */
5995 if (ch == '(' || ch == '{') {
5996 ch = (ch == '(' ? ')' : '}');
5997 add_till_closing_bracket(dest, input, ch);
6002 add_till_single_quote(dest, input);
6007 add_till_double_quote(dest, input);
6012 add_till_backquote(dest, input);
6017 /* \x. Copy verbatim. Important for \(, \) */
6018 ch = i_getch(input);
6020 syntax_error_unterm_ch(')');
6021 /*xfunc_die(); - redundant */
6029 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6031 /* Return code: 0 for OK, 1 for syntax error */
6033 #define parse_dollar(as_string, dest, input) \
6034 parse_dollar(dest, input)
6035 #define as_string NULL
6037 static int parse_dollar(o_string *as_string,
6039 struct in_str *input)
6041 int ch = i_peek(input); /* first character after the $ */
6042 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6044 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6046 ch = i_getch(input);
6047 nommu_addchr(as_string, ch);
6049 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6051 debug_printf_parse(": '%c'\n", ch);
6052 o_addchr(dest, ch | quote_mask);
6055 if (!isalnum(ch) && ch != '_')
6057 ch = i_getch(input);
6058 nommu_addchr(as_string, ch);
6060 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6061 } else if (isdigit(ch)) {
6063 ch = i_getch(input);
6064 nommu_addchr(as_string, ch);
6065 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6066 debug_printf_parse(": '%c'\n", ch);
6067 o_addchr(dest, ch | quote_mask);
6068 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6069 } else switch (ch) {
6071 case '!': /* last bg pid */
6072 case '?': /* last exit code */
6073 case '#': /* number of args */
6074 case '*': /* args */
6075 case '@': /* args */
6076 goto make_one_char_var;
6078 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6080 ch = i_getch(input); /* eat '{' */
6081 nommu_addchr(as_string, ch);
6083 ch = i_getch(input); /* first char after '{' */
6084 nommu_addchr(as_string, ch);
6085 /* It should be ${?}, or ${#var},
6086 * or even ${?+subst} - operator acting on a special variable,
6087 * or the beginning of variable name.
6089 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6091 syntax_error_unterm_str("${name}");
6092 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6097 /* It's possible to just call add_till_closing_bracket() at this point.
6098 * However, this regresses some of our testsuite cases
6099 * which check invalid constructs like ${%}.
6100 * Oh well... let's check that the var name part is fine... */
6106 debug_printf_parse(": '%c'\n", ch);
6108 ch = i_getch(input);
6109 nommu_addchr(as_string, ch);
6113 if (!isalnum(ch) && ch != '_') {
6115 unsigned char last_ch;
6116 /* handle parameter expansions
6117 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6119 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6120 goto bad_dollar_syntax;
6123 /* Eat everything until closing '}' (or ':') */
6125 if (ENABLE_HUSH_BASH_COMPAT
6127 && !strchr("%#:-=+?"+3, i_peek(input))
6129 /* It's ${var:N[:M]} thing */
6130 end_ch = '}' * 0x100 + ':';
6135 #if ENABLE_HUSH_DOLLAR_OPS
6136 last_ch = add_till_closing_bracket(dest, input, end_ch);
6138 #error Simple code to only allow ${var} is not implemented
6141 o_addstr(as_string, dest->data + pos);
6142 o_addchr(as_string, last_ch);
6145 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6146 /* close the first block: */
6147 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6148 /* while parsing N from ${var:N[:M]}... */
6149 if ((end_ch & 0xff) == last_ch) {
6150 /* ...got ':' - parse the rest */
6154 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6155 o_addstr(dest, "999999999");
6160 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6163 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6167 ch = i_getch(input);
6168 nommu_addchr(as_string, ch);
6169 # if ENABLE_SH_MATH_SUPPORT
6170 if (i_peek(input) == '(') {
6171 ch = i_getch(input);
6172 nommu_addchr(as_string, ch);
6173 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6174 o_addchr(dest, /*quote_mask |*/ '+');
6177 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6179 o_addstr(as_string, dest->data + pos);
6180 o_addchr(as_string, ')');
6181 o_addchr(as_string, ')');
6183 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6187 # if ENABLE_HUSH_TICK
6188 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6189 o_addchr(dest, quote_mask | '`');
6192 add_till_closing_bracket(dest, input, ')');
6194 o_addstr(as_string, dest->data + pos);
6195 o_addchr(as_string, ')');
6197 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6203 ch = i_getch(input);
6204 nommu_addchr(as_string, ch);
6206 if (isalnum(ch)) { /* it's $_name or $_123 */
6211 /* TODO: $_ and $-: */
6212 /* $_ Shell or shell script name; or last argument of last command
6213 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6214 * but in command's env, set to full pathname used to invoke it */
6215 /* $- Option flags set by set builtin or shell options (-i etc) */
6217 o_addQchr(dest, '$');
6219 debug_printf_parse("parse_dollar return 0\n");
6225 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6226 parse_stream_dquoted(dest, input, dquote_end)
6227 #define as_string NULL
6229 static int parse_stream_dquoted(o_string *as_string,
6231 struct in_str *input,
6238 ch = i_getch(input);
6240 nommu_addchr(as_string, ch);
6241 if (ch == dquote_end) { /* may be only '"' or EOF */
6242 if (dest->o_assignment == NOT_ASSIGNMENT)
6243 dest->o_escape ^= 1;
6244 debug_printf_parse("parse_stream_dquoted return 0\n");
6247 /* note: can't move it above ch == dquote_end check! */
6249 syntax_error_unterm_ch('"');
6250 /*xfunc_die(); - redundant */
6254 next = i_peek(input);
6256 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6257 ch, ch, dest->o_escape);
6260 syntax_error("\\<eof>");
6264 * "The backslash retains its special meaning [in "..."]
6265 * only when followed by one of the following characters:
6266 * $, `, ", \, or <newline>. A double quote may be quoted
6267 * within double quotes by preceding it with a backslash."
6269 if (strchr("$`\"\\\n", next) != NULL) {
6270 ch = i_getch(input);
6272 o_addqchr(dest, ch);
6273 nommu_addchr(as_string, ch);
6276 o_addqchr(dest, '\\');
6277 nommu_addchr(as_string, '\\');
6282 if (parse_dollar(as_string, dest, input) != 0) {
6283 debug_printf_parse("parse_stream_dquoted return 1: "
6284 "parse_dollar returned non-0\n");
6289 #if ENABLE_HUSH_TICK
6291 //unsigned pos = dest->length;
6292 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6293 o_addchr(dest, 0x80 | '`');
6294 add_till_backquote(dest, input);
6295 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6296 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6300 o_addQchr(dest, ch);
6302 && (dest->o_assignment == MAYBE_ASSIGNMENT
6303 || dest->o_assignment == WORD_IS_KEYWORD)
6304 && is_well_formed_var_name(dest->data, '=')
6306 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6313 * Scan input until EOF or end_trigger char.
6314 * Return a list of pipes to execute, or NULL on EOF
6315 * or if end_trigger character is met.
6316 * On syntax error, exit is shell is not interactive,
6317 * reset parsing machinery and start parsing anew,
6318 * or return ERR_PTR.
6320 static struct pipe *parse_stream(char **pstring,
6321 struct in_str *input,
6324 struct parse_context ctx;
6325 o_string dest = NULL_O_STRING;
6329 /* Double-quote state is handled in the state variable is_in_dquote.
6330 * A single-quote triggers a bypass of the main loop until its mate is
6331 * found. When recursing, quote state is passed in via dest->o_escape.
6333 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6334 end_trigger ? end_trigger : 'X');
6337 /* If very first arg is "" or '', dest.data may end up NULL.
6338 * Preventing this: */
6339 o_addchr(&dest, '\0');
6342 G.ifs = get_local_var_value("IFS");
6347 #if ENABLE_HUSH_INTERACTIVE
6348 input->promptmode = 0; /* PS1 */
6350 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6351 initialize_context(&ctx);
6356 const char *is_special;
6360 redir_type redir_style;
6363 /* dest.o_quoted = 1; - already is (see below) */
6364 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6367 /* We reached closing '"' */
6370 ch = i_getch(input);
6371 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6372 ch, ch, dest.o_escape);
6377 syntax_error_unterm_str("here document");
6380 /* end_trigger == '}' case errors out earlier,
6381 * checking only ')' */
6382 if (end_trigger == ')') {
6383 syntax_error_unterm_ch('('); /* exits */
6384 /* goto parse_error; */
6387 if (done_word(&dest, &ctx)) {
6391 done_pipe(&ctx, PIPE_SEQ);
6393 /* If we got nothing... */
6394 /* (this makes bare "&" cmd a no-op.
6395 * bash says: "syntax error near unexpected token '&'") */
6396 if (pi->num_cmds == 0
6397 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6403 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6405 *pstring = ctx.as_string.data;
6407 o_free_unsafe(&ctx.as_string);
6410 debug_printf_parse("parse_stream return %p\n", pi);
6413 nommu_addchr(&ctx.as_string, ch);
6417 next = i_peek(input);
6419 is_special = "{}<>;&|()#'" /* special outside of "str" */
6420 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6421 /* Are { and } special here? */
6422 if (ctx.command->argv /* word [word]{... - non-special */
6423 || dest.length /* word{... - non-special */
6424 || dest.o_quoted /* ""{... - non-special */
6425 || (next != ';' /* }; - special */
6426 && next != ')' /* }) - special */
6427 && next != '&' /* }& and }&& ... - special */
6428 && next != '|' /* }|| ... - special */
6429 && !strchr(G.ifs, next) /* {word - non-special */
6432 /* They are not special, skip "{}" */
6435 is_special = strchr(is_special, ch);
6436 is_ifs = strchr(G.ifs, ch);
6438 if (!is_special && !is_ifs) { /* ordinary char */
6440 o_addQchr(&dest, ch);
6441 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6442 || dest.o_assignment == WORD_IS_KEYWORD)
6444 && is_well_formed_var_name(dest.data, '=')
6446 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6452 if (done_word(&dest, &ctx)) {
6456 #if ENABLE_HUSH_CASE
6457 /* "case ... in <newline> word) ..." -
6458 * newlines are ignored (but ';' wouldn't be) */
6459 if (ctx.command->argv == NULL
6460 && ctx.ctx_res_w == RES_MATCH
6465 /* Treat newline as a command separator. */
6466 done_pipe(&ctx, PIPE_SEQ);
6467 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6469 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6474 dest.o_assignment = MAYBE_ASSIGNMENT;
6476 /* note: if (is_ifs) continue;
6477 * will still trigger for us */
6481 /* "cmd}" or "cmd }..." without semicolon or &:
6482 * } is an ordinary char in this case, even inside { cmd; }
6483 * Pathological example: { ""}; } should exec "}" cmd
6486 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6487 || dest.length != 0 /* word} */
6488 || dest.o_quoted /* ""} */
6492 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6493 goto skip_end_trigger;
6494 /* else: } does terminate a group */
6497 if (end_trigger && end_trigger == ch
6498 && (ch != ';' || heredoc_cnt == 0)
6499 #if ENABLE_HUSH_CASE
6501 || ctx.ctx_res_w != RES_MATCH
6502 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6507 /* This is technically valid:
6508 * { cat <<HERE; }; echo Ok
6512 * but we don't support this.
6513 * We require heredoc to be in enclosing {}/(),
6516 syntax_error_unterm_str("here document");
6519 if (done_word(&dest, &ctx)) {
6522 done_pipe(&ctx, PIPE_SEQ);
6523 dest.o_assignment = MAYBE_ASSIGNMENT;
6524 /* Do we sit outside of any if's, loops or case's? */
6526 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6530 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6532 *pstring = ctx.as_string.data;
6534 o_free_unsafe(&ctx.as_string);
6537 debug_printf_parse("parse_stream return %p: "
6538 "end_trigger char found\n",
6540 return ctx.list_head;
6547 /* Catch <, > before deciding whether this word is
6548 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6551 redir_fd = redirect_opt_num(&dest);
6552 if (done_word(&dest, &ctx)) {
6555 redir_style = REDIRECT_OVERWRITE;
6557 redir_style = REDIRECT_APPEND;
6558 ch = i_getch(input);
6559 nommu_addchr(&ctx.as_string, ch);
6562 else if (next == '(') {
6563 syntax_error(">(process) not supported");
6567 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6569 continue; /* back to top of while (1) */
6571 redir_fd = redirect_opt_num(&dest);
6572 if (done_word(&dest, &ctx)) {
6575 redir_style = REDIRECT_INPUT;
6577 redir_style = REDIRECT_HEREDOC;
6579 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6580 ch = i_getch(input);
6581 nommu_addchr(&ctx.as_string, ch);
6582 } else if (next == '>') {
6583 redir_style = REDIRECT_IO;
6584 ch = i_getch(input);
6585 nommu_addchr(&ctx.as_string, ch);
6588 else if (next == '(') {
6589 syntax_error("<(process) not supported");
6593 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6595 continue; /* back to top of while (1) */
6598 if (dest.o_assignment == MAYBE_ASSIGNMENT
6599 /* check that we are not in word in "a=1 2>word b=1": */
6600 && !ctx.pending_redirect
6602 /* ch is a special char and thus this word
6603 * cannot be an assignment */
6604 dest.o_assignment = NOT_ASSIGNMENT;
6607 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6611 if (dest.length == 0) {
6614 if (ch == EOF || ch == '\n')
6617 /* note: we do not add it to &ctx.as_string */
6619 nommu_addchr(&ctx.as_string, '\n');
6621 o_addQchr(&dest, ch);
6626 syntax_error("\\<eof>");
6629 ch = i_getch(input);
6631 o_addchr(&dest, '\\');
6632 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6633 o_addchr(&dest, ch);
6634 nommu_addchr(&ctx.as_string, ch);
6635 /* Example: echo Hello \2>file
6636 * we need to know that word 2 is quoted */
6641 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6642 ctx.as_string.data[--ctx.as_string.length] = '\0';
6647 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
6648 debug_printf_parse("parse_stream parse error: "
6649 "parse_dollar returned non-0\n");
6656 ch = i_getch(input);
6658 syntax_error_unterm_ch('\'');
6659 /*xfunc_die(); - redundant */
6661 nommu_addchr(&ctx.as_string, ch);
6664 o_addqchr(&dest, ch);
6669 is_in_dquote ^= 1; /* invert */
6670 if (dest.o_assignment == NOT_ASSIGNMENT)
6673 #if ENABLE_HUSH_TICK
6677 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6678 o_addchr(&dest, '`');
6680 add_till_backquote(&dest, input);
6682 o_addstr(&ctx.as_string, dest.data + pos);
6683 o_addchr(&ctx.as_string, '`');
6685 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6686 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6691 #if ENABLE_HUSH_CASE
6694 if (done_word(&dest, &ctx)) {
6697 done_pipe(&ctx, PIPE_SEQ);
6698 #if ENABLE_HUSH_CASE
6699 /* Eat multiple semicolons, detect
6700 * whether it means something special */
6705 ch = i_getch(input);
6706 nommu_addchr(&ctx.as_string, ch);
6707 if (ctx.ctx_res_w == RES_CASE_BODY) {
6708 ctx.ctx_dsemicolon = 1;
6709 ctx.ctx_res_w = RES_MATCH;
6715 /* We just finished a cmd. New one may start
6716 * with an assignment */
6717 dest.o_assignment = MAYBE_ASSIGNMENT;
6720 if (done_word(&dest, &ctx)) {
6724 ch = i_getch(input);
6725 nommu_addchr(&ctx.as_string, ch);
6726 done_pipe(&ctx, PIPE_AND);
6728 done_pipe(&ctx, PIPE_BG);
6732 if (done_word(&dest, &ctx)) {
6735 #if ENABLE_HUSH_CASE
6736 if (ctx.ctx_res_w == RES_MATCH)
6737 break; /* we are in case's "word | word)" */
6739 if (next == '|') { /* || */
6740 ch = i_getch(input);
6741 nommu_addchr(&ctx.as_string, ch);
6742 done_pipe(&ctx, PIPE_OR);
6744 /* we could pick up a file descriptor choice here
6745 * with redirect_opt_num(), but bash doesn't do it.
6746 * "echo foo 2| cat" yields "foo 2". */
6749 o_reset_to_empty_unquoted(&ctx.as_string);
6754 #if ENABLE_HUSH_CASE
6755 /* "case... in [(]word)..." - skip '(' */
6756 if (ctx.ctx_res_w == RES_MATCH
6757 && ctx.command->argv == NULL /* not (word|(... */
6758 && dest.length == 0 /* not word(... */
6759 && dest.o_quoted == 0 /* not ""(... */
6765 if (parse_group(&dest, &ctx, input, ch) != 0) {
6770 #if ENABLE_HUSH_CASE
6771 if (ctx.ctx_res_w == RES_MATCH)
6775 /* proper use of this character is caught by end_trigger:
6776 * if we see {, we call parse_group(..., end_trigger='}')
6777 * and it will match } earlier (not here). */
6778 syntax_error_unexpected_ch(ch);
6782 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6788 struct parse_context *pctx;
6789 IF_HAS_KEYWORDS(struct parse_context *p2;)
6791 /* Clean up allocated tree.
6792 * Sample for finding leaks on syntax error recovery path.
6793 * Run it from interactive shell, watch pmap `pidof hush`.
6794 * while if false; then false; fi; do break; fi
6795 * Samples to catch leaks at execution:
6796 * while if (true | {true;}); then echo ok; fi; do break; done
6797 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6801 /* Update pipe/command counts,
6802 * otherwise freeing may miss some */
6803 done_pipe(pctx, PIPE_SEQ);
6804 debug_printf_clean("freeing list %p from ctx %p\n",
6805 pctx->list_head, pctx);
6806 debug_print_tree(pctx->list_head, 0);
6807 free_pipe_list(pctx->list_head);
6808 debug_printf_clean("freed list %p\n", pctx->list_head);
6810 o_free_unsafe(&pctx->as_string);
6812 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6816 IF_HAS_KEYWORDS(pctx = p2;)
6817 } while (HAS_KEYWORDS && pctx);
6818 /* Free text, clear all dest fields */
6820 /* If we are not in top-level parse, we return,
6821 * our caller will propagate error.
6823 if (end_trigger != ';') {
6831 /* Discard cached input, force prompt */
6833 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6838 /* Executing from string: eval, sh -c '...'
6839 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6840 * end_trigger controls how often we stop parsing
6841 * NUL: parse all, execute, return
6842 * ';': parse till ';' or newline, execute, repeat till EOF
6844 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6846 /* Why we need empty flag?
6847 * An obscure corner case "false; ``; echo $?":
6848 * empty command in `` should still set $? to 0.
6849 * But we can't just set $? to 0 at the start,
6850 * this breaks "false; echo `echo $?`" case.
6854 struct pipe *pipe_list;
6856 pipe_list = parse_stream(NULL, inp, end_trigger);
6857 if (!pipe_list) { /* EOF */
6859 G.last_exitcode = 0;
6862 debug_print_tree(pipe_list, 0);
6863 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6864 run_and_free_list(pipe_list);
6869 static void parse_and_run_string(const char *s)
6871 struct in_str input;
6872 setup_string_in_str(&input, s);
6873 parse_and_run_stream(&input, '\0');
6876 static void parse_and_run_file(FILE *f)
6878 struct in_str input;
6879 setup_file_in_str(&input, f);
6880 parse_and_run_stream(&input, ';');
6883 /* Called a few times only (or even once if "sh -c") */
6884 static void init_sigmasks(void)
6888 sigset_t old_blocked_set;
6890 if (!G.inherited_set_is_saved) {
6891 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6892 G.inherited_set = G.blocked_set;
6894 old_blocked_set = G.blocked_set;
6896 mask = (1 << SIGQUIT);
6897 if (G_interactive_fd) {
6898 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6899 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6900 mask |= SPECIAL_JOB_SIGS;
6902 G.non_DFL_mask = mask;
6907 sigaddset(&G.blocked_set, sig);
6911 sigdelset(&G.blocked_set, SIGCHLD);
6913 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
6914 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6916 /* POSIX allows shell to re-enable SIGCHLD
6917 * even if it was SIG_IGN on entry */
6918 #if ENABLE_HUSH_FAST
6919 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6920 if (!G.inherited_set_is_saved)
6921 signal(SIGCHLD, SIGCHLD_handler);
6923 if (!G.inherited_set_is_saved)
6924 signal(SIGCHLD, SIG_DFL);
6927 G.inherited_set_is_saved = 1;
6932 static void maybe_set_to_sigexit(int sig)
6934 void (*handler)(int);
6935 /* non_DFL_mask'ed signals are, well, masked,
6936 * no need to set handler for them.
6938 if (!((G.non_DFL_mask >> sig) & 1)) {
6939 handler = signal(sig, sigexit);
6940 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6941 signal(sig, handler);
6944 /* Set handlers to restore tty pgrp and exit */
6945 static void set_fatal_handlers(void)
6947 /* We _must_ restore tty pgrp on fatal signals */
6949 maybe_set_to_sigexit(SIGILL );
6950 maybe_set_to_sigexit(SIGFPE );
6951 maybe_set_to_sigexit(SIGBUS );
6952 maybe_set_to_sigexit(SIGSEGV);
6953 maybe_set_to_sigexit(SIGTRAP);
6954 } /* else: hush is perfect. what SEGV? */
6955 maybe_set_to_sigexit(SIGABRT);
6956 /* bash 3.2 seems to handle these just like 'fatal' ones */
6957 maybe_set_to_sigexit(SIGPIPE);
6958 maybe_set_to_sigexit(SIGALRM);
6959 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6960 * if we aren't interactive... but in this case
6961 * we never want to restore pgrp on exit, and this fn is not called */
6962 /*maybe_set_to_sigexit(SIGHUP );*/
6963 /*maybe_set_to_sigexit(SIGTERM);*/
6964 /*maybe_set_to_sigexit(SIGINT );*/
6968 static int set_mode(const char cstate, const char mode)
6970 int state = (cstate == '-' ? 1 : 0);
6972 case 'n': G.fake_mode = state; break;
6973 case 'x': G.x_mode = state; break;
6974 default: return EXIT_FAILURE;
6976 return EXIT_SUCCESS;
6979 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6980 int hush_main(int argc, char **argv)
6982 static const struct variable const_shell_ver = {
6984 .varstr = (char*)hush_version_str,
6985 .max_len = 1, /* 0 can provoke free(name) */
6990 unsigned builtin_argc;
6992 struct variable *cur_var;
6995 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
6996 G.last_exitcode = EXIT_SUCCESS;
6998 G.argv0_for_re_execing = argv[0];
7000 /* Deal with HUSH_VERSION */
7001 G.shell_ver = const_shell_ver; /* copying struct here */
7002 G.top_var = &G.shell_ver;
7003 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7004 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7005 /* Initialize our shell local variables with the values
7006 * currently living in the environment */
7007 cur_var = G.top_var;
7010 char *value = strchr(*e, '=');
7011 if (value) { /* paranoia */
7012 cur_var->next = xzalloc(sizeof(*cur_var));
7013 cur_var = cur_var->next;
7014 cur_var->varstr = *e;
7015 cur_var->max_len = strlen(*e);
7016 cur_var->flg_export = 1;
7020 /* reinstate HUSH_VERSION */
7021 debug_printf_env("putenv '%s'\n", hush_version_str);
7022 putenv((char *)hush_version_str);
7025 set_pwd_var(/*exp:*/ 1);
7026 /* bash also exports SHLVL and _,
7027 * and sets (but doesn't export) the following variables:
7029 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7030 * BASH_VERSION='3.2.0(1)-release'
7032 * MACHTYPE=i386-pc-linux-gnu
7034 * HOSTNAME=<xxxxxxxxxx>
7035 * PPID=<NNNNN> - we also do it elsewhere
7046 * PIPESTATUS=([0]="0")
7047 * HISTFILE=/<xxx>/.bash_history
7051 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7053 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7063 #if ENABLE_FEATURE_EDITING
7064 G.line_input_state = new_line_input_t(FOR_SHELL);
7066 G.global_argc = argc;
7067 G.global_argv = argv;
7068 /* Initialize some more globals to non-zero values */
7069 cmdedit_update_prompt();
7071 if (setjmp(die_jmp)) {
7072 /* xfunc has failed! die die die */
7073 /* no EXIT traps, this is an escape hatch! */
7075 hush_exit(xfunc_error_retval);
7078 /* Shell is non-interactive at first. We need to call
7079 * init_sigmasks() if we are going to execute "sh <script>",
7080 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7081 * If we later decide that we are interactive, we run init_sigmasks()
7082 * in order to intercept (more) signals.
7086 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7089 opt = getopt(argc, argv, "+c:xins"
7092 # if ENABLE_HUSH_FUNCTIONS
7102 * sh ... -c 'script'
7103 * sh ... -c 'script' ARG0 [ARG1...]
7104 * On NOMMU, if builtin_argc != 0,
7105 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7106 * "" needs to be replaced with NULL
7107 * and BARGV vector fed to builtin function.
7108 * Note: the form without ARG0 never happens:
7109 * sh ... -c 'builtin' BARGV... ""
7112 G.root_pid = getpid();
7113 G.root_ppid = getppid();
7115 G.global_argv = argv + optind;
7116 G.global_argc = argc - optind;
7118 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7119 const struct built_in_command *x;
7122 x = find_builtin(optarg);
7123 if (x) { /* paranoia */
7124 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7125 G.global_argv += builtin_argc;
7126 G.global_argv[-1] = NULL; /* replace "" */
7127 G.last_exitcode = x->b_function(argv + optind - 1);
7131 if (!G.global_argv[0]) {
7132 /* -c 'script' (no params): prevent empty $0 */
7133 G.global_argv--; /* points to argv[i] of 'script' */
7134 G.global_argv[0] = argv[0];
7136 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7138 parse_and_run_string(optarg);
7141 /* Well, we cannot just declare interactiveness,
7142 * we have to have some stuff (ctty, etc) */
7143 /* G_interactive_fd++; */
7146 /* "-s" means "read from stdin", but this is how we always
7147 * operate, so simply do nothing here. */
7150 case '<': /* "big heredoc" support */
7151 full_write1_str(optarg);
7154 unsigned long long empty_trap_mask;
7156 G.root_pid = bb_strtou(optarg, &optarg, 16);
7158 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7160 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7162 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7164 builtin_argc = bb_strtou(optarg, &optarg, 16);
7166 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7167 if (empty_trap_mask != 0) {
7170 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7171 for (sig = 1; sig < NSIG; sig++) {
7172 if (empty_trap_mask & (1LL << sig)) {
7173 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7174 sigaddset(&G.blocked_set, sig);
7177 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7179 # if ENABLE_HUSH_LOOPS
7181 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7187 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7189 # if ENABLE_HUSH_FUNCTIONS
7191 struct function *funcp = new_function(optarg);
7192 /* funcp->name is already set to optarg */
7193 /* funcp->body is set to NULL. It's a special case. */
7194 funcp->body_as_string = argv[optind];
7202 if (set_mode('-', opt) == 0) /* no error */
7206 fprintf(stderr, "Usage: sh [FILE]...\n"
7207 " or: sh -c command [args]...\n\n");
7213 } /* option parsing loop */
7216 G.root_pid = getpid();
7217 G.root_ppid = getppid();
7220 /* If we are login shell... */
7221 if (argv[0] && argv[0][0] == '-') {
7223 debug_printf("sourcing /etc/profile\n");
7224 input = fopen_for_read("/etc/profile");
7225 if (input != NULL) {
7226 close_on_exec_on(fileno(input));
7228 parse_and_run_file(input);
7231 /* bash: after sourcing /etc/profile,
7232 * tries to source (in the given order):
7233 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7234 * stopping on first found. --noprofile turns this off.
7235 * bash also sources ~/.bash_logout on exit.
7236 * If called as sh, skips .bash_XXX files.
7243 * "bash <script>" (which is never interactive (unless -i?))
7244 * sources $BASH_ENV here (without scanning $PATH).
7245 * If called as sh, does the same but with $ENV.
7247 debug_printf("running script '%s'\n", argv[optind]);
7248 G.global_argv = argv + optind;
7249 G.global_argc = argc - optind;
7250 input = xfopen_for_read(argv[optind]);
7251 close_on_exec_on(fileno(input));
7253 parse_and_run_file(input);
7254 #if ENABLE_FEATURE_CLEAN_UP
7260 /* Up to here, shell was non-interactive. Now it may become one.
7261 * NB: don't forget to (re)run init_sigmasks() as needed.
7264 /* A shell is interactive if the '-i' flag was given,
7265 * or if all of the following conditions are met:
7267 * no arguments remaining or the -s flag given
7268 * standard input is a terminal
7269 * standard output is a terminal
7270 * Refer to Posix.2, the description of the 'sh' utility.
7273 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7274 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7275 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7276 if (G_saved_tty_pgrp < 0)
7277 G_saved_tty_pgrp = 0;
7279 /* try to dup stdin to high fd#, >= 255 */
7280 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7281 if (G_interactive_fd < 0) {
7282 /* try to dup to any fd */
7283 G_interactive_fd = dup(STDIN_FILENO);
7284 if (G_interactive_fd < 0) {
7286 G_interactive_fd = 0;
7287 G_saved_tty_pgrp = 0;
7290 // TODO: track & disallow any attempts of user
7291 // to (inadvertently) close/redirect G_interactive_fd
7293 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7294 if (G_interactive_fd) {
7295 close_on_exec_on(G_interactive_fd);
7297 if (G_saved_tty_pgrp) {
7298 /* If we were run as 'hush &', sleep until we are
7299 * in the foreground (tty pgrp == our pgrp).
7300 * If we get started under a job aware app (like bash),
7301 * make sure we are now in charge so we don't fight over
7302 * who gets the foreground */
7304 pid_t shell_pgrp = getpgrp();
7305 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7306 if (G_saved_tty_pgrp == shell_pgrp)
7308 /* send TTIN to ourself (should stop us) */
7309 kill(- shell_pgrp, SIGTTIN);
7313 /* Block some signals */
7316 if (G_saved_tty_pgrp) {
7317 /* Set other signals to restore saved_tty_pgrp */
7318 set_fatal_handlers();
7319 /* Put ourselves in our own process group
7320 * (bash, too, does this only if ctty is available) */
7321 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7322 /* Grab control of the terminal */
7323 tcsetpgrp(G_interactive_fd, getpid());
7325 /* -1 is special - makes xfuncs longjmp, not exit
7326 * (we reset die_sleep = 0 whereever we [v]fork) */
7327 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7331 #elif ENABLE_HUSH_INTERACTIVE
7332 /* No job control compiled in, only prompt/line editing */
7333 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7334 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7335 if (G_interactive_fd < 0) {
7336 /* try to dup to any fd */
7337 G_interactive_fd = dup(STDIN_FILENO);
7338 if (G_interactive_fd < 0)
7340 G_interactive_fd = 0;
7343 if (G_interactive_fd) {
7344 close_on_exec_on(G_interactive_fd);
7348 /* We have interactiveness code disabled */
7352 * if interactive but not a login shell, sources ~/.bashrc
7353 * (--norc turns this off, --rcfile <file> overrides)
7356 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7357 /* note: ash and hush share this string */
7358 printf("\n\n%s %s\n"
7359 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7362 "hush - the humble shell"
7366 parse_and_run_file(stdin);
7369 #if ENABLE_FEATURE_CLEAN_UP
7370 if (G.cwd != bb_msg_unknown)
7372 cur_var = G.top_var->next;
7374 struct variable *tmp = cur_var;
7375 if (!cur_var->max_len)
7376 free(cur_var->varstr);
7377 cur_var = cur_var->next;
7381 hush_exit(G.last_exitcode);
7386 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7387 int lash_main(int argc, char **argv)
7389 bb_error_msg("lash is deprecated, please use hush instead");
7390 return hush_main(argc, argv);
7395 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7396 int msh_main(int argc, char **argv)
7398 //bb_error_msg("msh is deprecated, please use hush instead");
7399 return hush_main(argc, argv);
7407 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7412 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7419 return applet_main_func(argc, argv - argc);
7422 static int FAST_FUNC builtin_test(char **argv)
7424 return run_applet_main(argv, test_main);
7427 static int FAST_FUNC builtin_echo(char **argv)
7429 return run_applet_main(argv, echo_main);
7433 static int FAST_FUNC builtin_printf(char **argv)
7435 return run_applet_main(argv, printf_main);
7439 static char **skip_dash_dash(char **argv)
7442 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7447 static int FAST_FUNC builtin_eval(char **argv)
7449 int rcode = EXIT_SUCCESS;
7451 argv = skip_dash_dash(argv);
7453 char *str = expand_strvec_to_string(argv);
7455 * eval "echo Hi; done" ("done" is syntax error):
7456 * "echo Hi" will not execute too.
7458 parse_and_run_string(str);
7460 rcode = G.last_exitcode;
7465 static int FAST_FUNC builtin_cd(char **argv)
7469 argv = skip_dash_dash(argv);
7471 if (newdir == NULL) {
7472 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7473 * bash says "bash: cd: HOME not set" and does nothing
7476 const char *home = get_local_var_value("HOME");
7477 newdir = home ? home : "/";
7479 if (chdir(newdir)) {
7480 /* Mimic bash message exactly */
7481 bb_perror_msg("cd: %s", newdir);
7482 return EXIT_FAILURE;
7484 /* Read current dir (get_cwd(1) is inside) and set PWD.
7485 * Note: do not enforce exporting. If PWD was unset or unexported,
7486 * set it again, but do not export. bash does the same.
7488 set_pwd_var(/*exp:*/ 0);
7489 return EXIT_SUCCESS;
7492 static int FAST_FUNC builtin_exec(char **argv)
7494 argv = skip_dash_dash(argv);
7495 if (argv[0] == NULL)
7496 return EXIT_SUCCESS; /* bash does this */
7498 /* Careful: we can end up here after [v]fork. Do not restore
7499 * tty pgrp then, only top-level shell process does that */
7500 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7501 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7503 /* TODO: if exec fails, bash does NOT exit! We do.
7504 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7505 * and tcsetpgrp, and this is inherently racy.
7507 execvp_or_die(argv);
7510 static int FAST_FUNC builtin_exit(char **argv)
7512 debug_printf_exec("%s()\n", __func__);
7514 /* interactive bash:
7515 * # trap "echo EEE" EXIT
7518 * There are stopped jobs.
7519 * (if there are _stopped_ jobs, running ones don't count)
7522 # EEE (then bash exits)
7524 * we can use G.exiting = -1 as indicator "last cmd was exit"
7527 /* note: EXIT trap is run by hush_exit */
7528 argv = skip_dash_dash(argv);
7529 if (argv[0] == NULL)
7530 hush_exit(G.last_exitcode);
7531 /* mimic bash: exit 123abc == exit 255 + error msg */
7532 xfunc_error_retval = 255;
7533 /* bash: exit -2 == exit 254, no error msg */
7534 hush_exit(xatoi(argv[0]) & 0xff);
7537 static void print_escaped(const char *s)
7542 const char *p = strchrnul(s, '\'');
7543 /* print 'xxxx', possibly just '' */
7544 printf("'%.*s'", (int)(p - s), s);
7549 /* s points to '; print "'''...'''" */
7551 do putchar('\''); while (*++s == '\'');
7556 #if !ENABLE_HUSH_LOCAL
7557 #define helper_export_local(argv, exp, lvl) \
7558 helper_export_local(argv, exp)
7560 static void helper_export_local(char **argv, int exp, int lvl)
7565 /* So far we do not check that name is valid (TODO?) */
7567 if (strchr(name, '=') == NULL) {
7568 struct variable *var;
7570 var = get_local_var(name);
7571 if (exp == -1) { /* unexporting? */
7572 /* export -n NAME (without =VALUE) */
7574 var->flg_export = 0;
7575 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7577 } /* else: export -n NOT_EXISTING_VAR: no-op */
7580 if (exp == 1) { /* exporting? */
7581 /* export NAME (without =VALUE) */
7583 var->flg_export = 1;
7584 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7585 putenv(var->varstr);
7589 /* Exporting non-existing variable.
7590 * bash does not put it in environment,
7591 * but remembers that it is exported,
7592 * and does put it in env when it is set later.
7593 * We just set it to "" and export. */
7594 /* Or, it's "local NAME" (without =VALUE).
7595 * bash sets the value to "". */
7596 name = xasprintf("%s=", name);
7598 /* (Un)exporting/making local NAME=VALUE */
7599 name = xstrdup(name);
7601 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7605 static int FAST_FUNC builtin_export(char **argv)
7607 unsigned opt_unexport;
7609 #if ENABLE_HUSH_EXPORT_N
7610 /* "!": do not abort on errors */
7611 opt_unexport = getopt32(argv, "!n");
7612 if (opt_unexport == (uint32_t)-1)
7613 return EXIT_FAILURE;
7620 if (argv[0] == NULL) {
7627 /* ash emits: export VAR='VAL'
7628 * bash: declare -x VAR="VAL"
7629 * we follow ash example */
7630 const char *s = *e++;
7631 const char *p = strchr(s, '=');
7633 if (!p) /* wtf? take next variable */
7636 printf("export %.*s", (int)(p - s) + 1, s);
7637 print_escaped(p + 1);
7641 /*fflush_all(); - done after each builtin anyway */
7643 return EXIT_SUCCESS;
7646 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7648 return EXIT_SUCCESS;
7651 #if ENABLE_HUSH_LOCAL
7652 static int FAST_FUNC builtin_local(char **argv)
7654 if (G.func_nest_level == 0) {
7655 bb_error_msg("%s: not in a function", argv[0]);
7656 return EXIT_FAILURE; /* bash compat */
7658 helper_export_local(argv, 0, G.func_nest_level);
7659 return EXIT_SUCCESS;
7663 static int FAST_FUNC builtin_trap(char **argv)
7669 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7674 /* No args: print all trapped */
7675 for (i = 0; i < NSIG; ++i) {
7678 print_escaped(G.traps[i]);
7679 /* note: bash adds "SIG", but only if invoked
7680 * as "bash". If called as "sh", or if set -o posix,
7681 * then it prints short signal names.
7682 * We are printing short names: */
7683 printf(" %s\n", get_signame(i));
7686 /*fflush_all(); - done after each builtin anyway */
7687 return EXIT_SUCCESS;
7691 /* If first arg is a number: reset all specified signals */
7692 sig = bb_strtou(*argv, NULL, 10);
7698 sig = get_signum(*argv++);
7699 if (sig < 0 || sig >= NSIG) {
7701 /* Mimic bash message exactly */
7702 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7707 G.traps[sig] = xstrdup(new_cmd);
7709 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
7710 get_signame(sig), sig, G.traps[sig]);
7712 /* There is no signal for 0 (EXIT) */
7717 sigaddset(&G.blocked_set, sig);
7719 /* There was a trap handler, we are removing it
7720 * (if sig has non-DFL handling,
7721 * we don't need to do anything) */
7722 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7724 sigdelset(&G.blocked_set, sig);
7727 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7731 if (!argv[1]) { /* no second arg */
7732 bb_error_msg("trap: invalid arguments");
7733 return EXIT_FAILURE;
7736 /* First arg is "-": reset all specified to default */
7737 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7738 /* Everything else: set arg as signal handler
7739 * (includes "" case, which ignores signal) */
7740 if (argv[0][0] == '-') {
7741 if (argv[0][1] == '\0') { /* "-" */
7742 /* new_cmd remains NULL: "reset these sigs" */
7745 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7748 /* else: "-something", no special meaning */
7753 goto process_sig_list;
7756 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7757 static int FAST_FUNC builtin_type(char **argv)
7759 int ret = EXIT_SUCCESS;
7765 if (0) {} /* make conditional compile easier below */
7766 /*else if (find_alias(*argv))
7767 type = "an alias";*/
7768 #if ENABLE_HUSH_FUNCTIONS
7769 else if (find_function(*argv))
7770 type = "a function";
7772 else if (find_builtin(*argv))
7773 type = "a shell builtin";
7774 else if ((path = find_in_path(*argv)) != NULL)
7777 bb_error_msg("type: %s: not found", *argv);
7782 printf("%s is %s\n", *argv, type);
7790 /* built-in 'fg' and 'bg' handler */
7791 static int FAST_FUNC builtin_fg_bg(char **argv)
7796 if (!G_interactive_fd)
7797 return EXIT_FAILURE;
7799 /* If they gave us no args, assume they want the last backgrounded task */
7801 for (pi = G.job_list; pi; pi = pi->next) {
7802 if (pi->jobid == G.last_jobid) {
7806 bb_error_msg("%s: no current job", argv[0]);
7807 return EXIT_FAILURE;
7809 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7810 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7811 return EXIT_FAILURE;
7813 for (pi = G.job_list; pi; pi = pi->next) {
7814 if (pi->jobid == jobnum) {
7818 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7819 return EXIT_FAILURE;
7821 /* TODO: bash prints a string representation
7822 * of job being foregrounded (like "sleep 1 | cat") */
7823 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7824 /* Put the job into the foreground. */
7825 tcsetpgrp(G_interactive_fd, pi->pgrp);
7828 /* Restart the processes in the job */
7829 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7830 for (i = 0; i < pi->num_cmds; i++) {
7831 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7832 pi->cmds[i].is_stopped = 0;
7834 pi->stopped_cmds = 0;
7836 i = kill(- pi->pgrp, SIGCONT);
7838 if (errno == ESRCH) {
7839 delete_finished_bg_job(pi);
7840 return EXIT_SUCCESS;
7842 bb_perror_msg("kill (SIGCONT)");
7845 if (argv[0][0] == 'f') {
7847 return checkjobs_and_fg_shell(pi);
7849 return EXIT_SUCCESS;
7853 #if ENABLE_HUSH_HELP
7854 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7856 const struct built_in_command *x;
7859 "Built-in commands:\n"
7860 "------------------\n");
7861 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7863 printf("%-10s%s\n", x->b_cmd, x->b_descr);
7866 return EXIT_SUCCESS;
7871 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7874 const char *status_string;
7876 for (job = G.job_list; job; job = job->next) {
7877 if (job->alive_cmds == job->stopped_cmds)
7878 status_string = "Stopped";
7880 status_string = "Running";
7882 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7884 return EXIT_SUCCESS;
7889 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7894 # ifdef M_TRIM_THRESHOLD
7895 /* Optional. Reduces probability of false positives */
7898 /* Crude attempt to find where "free memory" starts,
7899 * sans fragmentation. */
7901 l = (unsigned long)p;
7904 if (l < (unsigned long)p) l = (unsigned long)p;
7907 if (!G.memleak_value)
7908 G.memleak_value = l;
7910 l -= G.memleak_value;
7917 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7922 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7925 return EXIT_SUCCESS;
7928 static int FAST_FUNC builtin_read(char **argv)
7937 /* "!": do not abort on errors.
7938 * Option string must start with "sr" to match BUILTIN_READ_xxx
7940 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
7941 if (read_flags == (uint32_t)-1)
7942 return EXIT_FAILURE;
7945 r = shell_builtin_read(set_local_var_from_halves,
7947 get_local_var_value("IFS"), /* can be NULL */
7955 if ((uintptr_t)r > 1) {
7956 bb_error_msg("%s", r);
7957 r = (char*)(uintptr_t)1;
7960 return (uintptr_t)r;
7963 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7964 * built-in 'set' handler
7966 * set [-abCefhmnuvx] [-o option] [argument...]
7967 * set [+abCefhmnuvx] [+o option] [argument...]
7968 * set -- [argument...]
7971 * Implementations shall support the options in both their hyphen and
7972 * plus-sign forms. These options can also be specified as options to sh.
7974 * Write out all variables and their values: set
7975 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7976 * Turn on the -x and -v options: set -xv
7977 * Unset all positional parameters: set --
7978 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7979 * Set the positional parameters to the expansion of x, even if x expands
7980 * with a leading '-' or '+': set -- $x
7982 * So far, we only support "set -- [argument...]" and some of the short names.
7984 static int FAST_FUNC builtin_set(char **argv)
7987 char **pp, **g_argv;
7988 char *arg = *++argv;
7992 for (e = G.top_var; e; e = e->next)
7994 return EXIT_SUCCESS;
7998 if (!strcmp(arg, "--")) {
8002 if (arg[0] != '+' && arg[0] != '-')
8004 for (n = 1; arg[n]; ++n)
8005 if (set_mode(arg[0], arg[n]))
8007 } while ((arg = *++argv) != NULL);
8008 /* Now argv[0] is 1st argument */
8011 return EXIT_SUCCESS;
8014 /* NB: G.global_argv[0] ($0) is never freed/changed */
8015 g_argv = G.global_argv;
8016 if (G.global_args_malloced) {
8022 G.global_args_malloced = 1;
8023 pp = xzalloc(sizeof(pp[0]) * 2);
8024 pp[0] = g_argv[0]; /* retain $0 */
8027 /* This realloc's G.global_argv */
8028 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8035 return EXIT_SUCCESS;
8037 /* Nothing known, so abort */
8039 bb_error_msg("set: %s: invalid option", arg);
8040 return EXIT_FAILURE;
8043 static int FAST_FUNC builtin_shift(char **argv)
8046 argv = skip_dash_dash(argv);
8050 if (n >= 0 && n < G.global_argc) {
8051 if (G.global_args_malloced) {
8054 free(G.global_argv[m++]);
8057 memmove(&G.global_argv[1], &G.global_argv[n+1],
8058 G.global_argc * sizeof(G.global_argv[0]));
8059 return EXIT_SUCCESS;
8061 return EXIT_FAILURE;
8064 static int FAST_FUNC builtin_source(char **argv)
8066 char *arg_path, *filename;
8069 #if ENABLE_HUSH_FUNCTIONS
8073 argv = skip_dash_dash(argv);
8076 /* bash says: "bash: .: filename argument required" */
8077 return 2; /* bash compat */
8080 if (!strchr(filename, '/')) {
8081 arg_path = find_in_path(filename);
8083 filename = arg_path;
8085 input = fopen_or_warn(filename, "r");
8088 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8089 return EXIT_FAILURE;
8091 close_on_exec_on(fileno(input));
8093 #if ENABLE_HUSH_FUNCTIONS
8094 sv_flg = G.flag_return_in_progress;
8095 /* "we are inside sourced file, ok to use return" */
8096 G.flag_return_in_progress = -1;
8098 save_and_replace_G_args(&sv, argv);
8100 parse_and_run_file(input);
8103 restore_G_args(&sv, argv);
8104 #if ENABLE_HUSH_FUNCTIONS
8105 G.flag_return_in_progress = sv_flg;
8108 return G.last_exitcode;
8111 static int FAST_FUNC builtin_umask(char **argv)
8117 argv = skip_dash_dash(argv);
8119 mode_t old_mask = mask;
8122 rc = bb_parse_mode(argv[0], &mask);
8127 * bash: umask: 'q': invalid symbolic mode operator
8128 * bash: umask: 999: octal number out of range
8130 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8135 printf("%04o\n", (unsigned) mask);
8136 /* fall through and restore mask which we set to 0 */
8140 return !rc; /* rc != 0 - success */
8143 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8144 static int FAST_FUNC builtin_unset(char **argv)
8149 /* "!": do not abort on errors */
8150 /* "+": stop at 1st non-option */
8151 opts = getopt32(argv, "!+vf");
8152 if (opts == (unsigned)-1)
8153 return EXIT_FAILURE;
8155 bb_error_msg("unset: -v and -f are exclusive");
8156 return EXIT_FAILURE;
8162 if (!(opts & 2)) { /* not -f */
8163 if (unset_local_var(*argv)) {
8164 /* unset <nonexistent_var> doesn't fail.
8165 * Error is when one tries to unset RO var.
8166 * Message was printed by unset_local_var. */
8170 #if ENABLE_HUSH_FUNCTIONS
8180 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8181 static int FAST_FUNC builtin_wait(char **argv)
8183 int ret = EXIT_SUCCESS;
8186 argv = skip_dash_dash(argv);
8187 if (argv[0] == NULL) {
8188 /* Don't care about wait results */
8189 /* Note 1: must wait until there are no more children */
8190 /* Note 2: must be interruptible */
8192 * $ sleep 3 & sleep 6 & wait
8197 * $ sleep 3 & sleep 6 & wait
8201 * ^C <-- after ~4 sec from keyboard
8204 sigaddset(&G.blocked_set, SIGCHLD);
8205 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8208 if (errno == ECHILD)
8210 /* Wait for SIGCHLD or any other signal of interest */
8211 /* sigtimedwait with infinite timeout: */
8212 sig = sigwaitinfo(&G.blocked_set, NULL);
8214 sig = check_and_run_traps(sig);
8215 if (sig && sig != SIGCHLD) { /* see note 2 */
8221 sigdelset(&G.blocked_set, SIGCHLD);
8222 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8226 /* This is probably buggy wrt interruptible-ness */
8228 pid_t pid = bb_strtou(*argv, NULL, 10);
8230 /* mimic bash message */
8231 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8232 return EXIT_FAILURE;
8234 if (waitpid(pid, &status, 0) == pid) {
8235 if (WIFSIGNALED(status))
8236 ret = 128 + WTERMSIG(status);
8237 else if (WIFEXITED(status))
8238 ret = WEXITSTATUS(status);
8242 bb_perror_msg("wait %s", *argv);
8251 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8252 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8255 def = bb_strtou(argv[1], NULL, 10);
8256 if (errno || def < def_min || argv[2]) {
8257 bb_error_msg("%s: bad arguments", argv[0]);
8265 #if ENABLE_HUSH_LOOPS
8266 static int FAST_FUNC builtin_break(char **argv)
8269 if (G.depth_of_loop == 0) {
8270 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8271 return EXIT_SUCCESS; /* bash compat */
8273 G.flag_break_continue++; /* BC_BREAK = 1 */
8275 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8276 if (depth == UINT_MAX)
8277 G.flag_break_continue = BC_BREAK;
8278 if (G.depth_of_loop < depth)
8279 G.depth_break_continue = G.depth_of_loop;
8281 return EXIT_SUCCESS;
8284 static int FAST_FUNC builtin_continue(char **argv)
8286 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8287 return builtin_break(argv);
8291 #if ENABLE_HUSH_FUNCTIONS
8292 static int FAST_FUNC builtin_return(char **argv)
8296 if (G.flag_return_in_progress != -1) {
8297 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8298 return EXIT_FAILURE; /* bash compat */
8301 G.flag_return_in_progress = 1;
8304 * out of range: wraps around at 256, does not error out
8305 * non-numeric param:
8306 * f() { false; return qwe; }; f; echo $?
8307 * bash: return: qwe: numeric argument required <== we do this
8308 * 255 <== we also do this
8310 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);