1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
45 * Bash stuff (optionally enabled):
46 * &> and >& redirection of stdout+stderr
48 * reserved words: [[ ]] function select
49 * substrings ${var:1:5}
51 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
52 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
53 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
55 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
56 * This is exactly equivalent to let "expression".
59 * grep for "TODO" and fix (some of them are easy)
61 * special variables (done: PWD)
62 * follow IFS rules more precisely, including update semantics
63 * export builtin should be special, its arguments are assignments
64 * and therefore expansion of them should be "one-word" expansion:
65 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
67 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
68 * ls: cannot access i=a: No such file or directory
69 * ls: cannot access b: No such file or directory
70 * Note1: same applies to local builtin.
71 * Note2: bash 3.2.33(1) does this only if export word itself
73 * $ export i=`echo 'aaa bbb'`; echo "$i"
75 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
78 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
80 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
81 #include <malloc.h> /* for malloc_trim */
83 /* #include <dmalloc.h> */
89 #if ENABLE_HUSH_RANDOM_SUPPORT
92 # define CLEAR_RANDOM_T(rnd) ((void)0)
95 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
100 #define LEAK_HUNTING 0
101 #define BUILD_AS_NOMMU 0
102 /* Enable/disable sanity checks. Ok to enable in production,
103 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
104 * Keeping 1 for now even in released versions.
107 /* Slightly bigger (+200 bytes), but faster hush.
108 * So far it only enables a trick with counting SIGCHLDs and forks,
109 * which allows us to do fewer waitpid's.
110 * (we can detect a case where neither forks were done nor SIGCHLDs happened
111 * and therefore waitpid will return the same result as last time)
113 #define ENABLE_HUSH_FAST 0
118 # undef USE_FOR_NOMMU
121 # define USE_FOR_NOMMU(...) __VA_ARGS__
122 # define USE_FOR_MMU(...)
125 #if defined SINGLE_APPLET_MAIN
126 /* STANDALONE does not make sense, and won't compile */
127 # undef CONFIG_FEATURE_SH_STANDALONE
128 # undef ENABLE_FEATURE_SH_STANDALONE
129 # undef IF_FEATURE_SH_STANDALONE
130 # define IF_FEATURE_SH_STANDALONE(...)
131 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
132 # define ENABLE_FEATURE_SH_STANDALONE 0
135 #if !ENABLE_HUSH_INTERACTIVE
136 # undef ENABLE_FEATURE_EDITING
137 # define ENABLE_FEATURE_EDITING 0
138 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
139 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
142 /* Do we support ANY keywords? */
143 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
144 # define HAS_KEYWORDS 1
145 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
146 # define IF_HAS_NO_KEYWORDS(...)
148 # define HAS_KEYWORDS 0
149 # define IF_HAS_KEYWORDS(...)
150 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
153 /* If you comment out one of these below, it will be #defined later
154 * to perform debug printfs to stderr: */
155 #define debug_printf(...) do {} while (0)
156 /* Finer-grained debug switches */
157 #define debug_printf_parse(...) do {} while (0)
158 #define debug_print_tree(a, b) do {} while (0)
159 #define debug_printf_exec(...) do {} while (0)
160 #define debug_printf_env(...) do {} while (0)
161 #define debug_printf_jobs(...) do {} while (0)
162 #define debug_printf_expand(...) do {} while (0)
163 #define debug_printf_glob(...) do {} while (0)
164 #define debug_printf_list(...) do {} while (0)
165 #define debug_printf_subst(...) do {} while (0)
166 #define debug_printf_clean(...) do {} while (0)
168 #define ERR_PTR ((void*)(long)1)
170 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
172 #define SPECIAL_VAR_SYMBOL 3
176 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
178 /* This supports saving pointers malloced in vfork child,
179 * to be freed in the parent.
182 typedef struct nommu_save_t {
184 struct variable *old_vars;
186 char **argv_from_re_execing;
190 typedef enum reserved_style {
199 #if ENABLE_HUSH_LOOPS
206 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
211 /* three pseudo-keywords support contrived "case" syntax: */
212 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
213 RES_MATCH , /* "word)" */
214 RES_CASE_BODY, /* "this command is inside CASE" */
221 typedef struct o_string {
223 int length; /* position where data is appended */
225 /* Protect newly added chars against globbing
226 * (by prepending \ to *, ?, [, \) */
229 /* At least some part of the string was inside '' or "",
230 * possibly empty one: word"", wo''rd etc. */
232 smallint has_empty_slot;
233 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
236 MAYBE_ASSIGNMENT = 0,
237 DEFINITELY_ASSIGNMENT = 1,
239 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
241 /* Used for initialization: o_string foo = NULL_O_STRING; */
242 #define NULL_O_STRING { NULL }
244 /* I can almost use ordinary FILE*. Is open_memstream() universally
245 * available? Where is it documented? */
246 typedef struct in_str {
248 /* eof_flag=1: last char in ->p is really an EOF */
249 char eof_flag; /* meaningless if ->p == NULL */
251 #if ENABLE_HUSH_INTERACTIVE
253 smallint promptmode; /* 0: PS1, 1: PS2 */
256 int (*get) (struct in_str *) FAST_FUNC;
257 int (*peek) (struct in_str *) FAST_FUNC;
259 #define i_getch(input) ((input)->get(input))
260 #define i_peek(input) ((input)->peek(input))
262 /* The descrip member of this structure is only used to make
263 * debugging output pretty */
264 static const struct {
266 signed char default_fd;
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_CREAT|O_RDWR, 1, "<>" },
273 { O_RDONLY, 0, "<<" },
274 /* Should not be needed. Bogus default_fd helps in debugging */
275 /* { O_RDONLY, 77, "<<" }, */
278 struct redir_struct {
279 struct redir_struct *next;
280 char *rd_filename; /* filename */
281 int rd_fd; /* fd to redirect */
282 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
284 smallint rd_type; /* (enum redir_type) */
285 /* note: for heredocs, rd_filename contains heredoc delimiter,
286 * and subsequently heredoc itself; and rd_dup is a bitmask:
287 * bit 0: do we need to trim leading tabs?
288 * bit 1: is heredoc quoted (<<'delim' syntax) ?
291 typedef enum redir_type {
293 REDIRECT_OVERWRITE = 1,
296 REDIRECT_HEREDOC = 4,
297 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
300 REDIRFD_SYNTAX_ERR = -2,
301 REDIRFD_TO_FILE = -1,
302 /* otherwise, rd_fd is redirected to rd_dup */
304 HEREDOC_SKIPTABS = 1,
310 pid_t pid; /* 0 if exited */
311 int assignment_cnt; /* how many argv[i] are assignments? */
312 smallint is_stopped; /* is the command currently running? */
313 smallint cmd_type; /* CMD_xxx */
315 #define CMD_SUBSHELL 1
317 /* used for "[[ EXPR ]]" */
318 #if ENABLE_HUSH_BASH_COMPAT
319 # define CMD_SINGLEWORD_NOGLOB 2
322 /* used for "export noglob=* glob* a=`echo a b`" */
323 //#define CMD_SINGLEWORD_NOGLOB_COND 3
324 // It is hard to implement correctly, it adds significant amounts of tricky code,
325 // and all this is only useful for really obscure export statements
326 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
327 // guards the code which implements it, but I have doubts it works
328 // in all cases (especially with mixed globbed/non-globbed arguments)
330 #if ENABLE_HUSH_FUNCTIONS
331 # define CMD_FUNCDEF 3
334 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
337 char *group_as_string;
339 #if ENABLE_HUSH_FUNCTIONS
340 struct function *child_func;
341 /* This field is used to prevent a bug here:
342 * while...do f1() {a;}; f1; f1() {b;}; f1; done
343 * When we execute "f1() {a;}" cmd, we create new function and clear
344 * cmd->group, cmd->group_as_string, cmd->argv[0].
345 * When we execute "f1() {b;}", we notice that f1 exists,
346 * and that its "parent cmd" struct is still "alive",
347 * we put those fields back into cmd->xxx
348 * (struct function has ->parent_cmd ptr to facilitate that).
349 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
350 * Without this trick, loop would execute a;b;b;b;...
351 * instead of correct sequence a;b;a;b;...
352 * When command is freed, it severs the link
353 * (sets ->child_func->parent_cmd to NULL).
356 char **argv; /* command name and arguments */
357 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
358 * and on execution these are substituted with their values.
359 * Substitution can make _several_ words out of one argv[n]!
360 * Example: argv[0]=='.^C*^C.' here: echo .$*.
361 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
363 struct redir_struct *redirects; /* I/O redirections */
365 /* Is there anything in this command at all? */
366 #define IS_NULL_CMD(cmd) \
367 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
372 int num_cmds; /* total number of commands in pipe */
373 int alive_cmds; /* number of commands running (not exited) */
374 int stopped_cmds; /* number of commands alive, but stopped */
376 int jobid; /* job number */
377 pid_t pgrp; /* process group ID for the job */
378 char *cmdtext; /* name of job */
380 struct command *cmds; /* array of commands in pipe */
381 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
382 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
383 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
385 typedef enum pipe_style {
391 /* Is there anything in this pipe at all? */
392 #define IS_NULL_PIPE(pi) \
393 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
395 /* This holds pointers to the various results of parsing */
396 struct parse_context {
397 /* linked list of pipes */
398 struct pipe *list_head;
399 /* last pipe (being constructed right now) */
401 /* last command in pipe (being constructed right now) */
402 struct command *command;
403 /* last redirect in command->redirects list */
404 struct redir_struct *pending_redirect;
410 smallint ctx_inverted; /* "! cmd | cmd" */
412 smallint ctx_dsemicolon; /* ";;" seen */
414 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
416 /* group we are enclosed in:
417 * example: "if pipe1; pipe2; then pipe3; fi"
418 * when we see "if" or "then", we malloc and copy current context,
419 * and make ->stack point to it. then we parse pipeN.
420 * when closing "then" / fi" / whatever is found,
421 * we move list_head into ->stack->command->group,
422 * copy ->stack into current context, and delete ->stack.
423 * (parsing of { list } and ( list ) doesn't use this method)
425 struct parse_context *stack;
429 /* On program start, environ points to initial environment.
430 * putenv adds new pointers into it, unsetenv removes them.
431 * Neither of these (de)allocates the strings.
432 * setenv allocates new strings in malloc space and does putenv,
433 * and thus setenv is unusable (leaky) for shell's purposes */
434 #define setenv(...) setenv_is_leaky_dont_use()
436 struct variable *next;
437 char *varstr; /* points to "name=" portion */
438 #if ENABLE_HUSH_LOCAL
439 unsigned func_nest_level;
441 int max_len; /* if > 0, name is part of initial env; else name is malloced */
442 smallint flg_export; /* putenv should be done on this var */
443 smallint flg_read_only;
451 #if ENABLE_HUSH_FUNCTIONS
453 struct function *next;
455 struct command *parent_cmd;
458 char *body_as_string;
464 /* "Globals" within this file */
465 /* Sorted roughly by size (smaller offsets == smaller code) */
467 /* interactive_fd != 0 means we are an interactive shell.
468 * If we are, then saved_tty_pgrp can also be != 0, meaning
469 * that controlling tty is available. With saved_tty_pgrp == 0,
470 * job control still works, but terminal signals
471 * (^C, ^Z, ^Y, ^\) won't work at all, and background
472 * process groups can only be created with "cmd &".
473 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
474 * to give tty to the foreground process group,
475 * and will take it back when the group is stopped (^Z)
478 #if ENABLE_HUSH_INTERACTIVE
479 /* 'interactive_fd' is a fd# open to ctty, if we have one
480 * _AND_ if we decided to act interactively */
484 # define G_interactive_fd (G.interactive_fd)
486 # define G_interactive_fd 0
488 #if ENABLE_FEATURE_EDITING
489 line_input_t *line_input_state;
494 #if ENABLE_HUSH_RANDOM_SUPPORT
500 pid_t saved_tty_pgrp;
501 struct pipe *job_list;
502 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
504 # define G_saved_tty_pgrp 0
506 smallint flag_SIGINT;
507 #if ENABLE_HUSH_LOOPS
508 smallint flag_break_continue;
510 #if ENABLE_HUSH_FUNCTIONS
511 /* 0: outside of a function (or sourced file)
512 * -1: inside of a function, ok to use return builtin
513 * 1: return is invoked, skip all till end of func
515 smallint flag_return_in_progress;
518 smallint exiting; /* used to prevent EXIT trap recursion */
519 /* These four support $?, $#, and $1 */
520 smalluint last_exitcode;
521 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
522 smalluint global_args_malloced;
523 /* how many non-NULL argv's we have. NB: $# + 1 */
527 char *argv0_for_re_execing;
529 #if ENABLE_HUSH_LOOPS
530 unsigned depth_break_continue;
531 unsigned depth_of_loop;
535 struct variable *top_var; /* = &G.shell_ver (set in main()) */
536 struct variable shell_ver;
537 #if ENABLE_HUSH_FUNCTIONS
538 struct function *top_func;
539 # if ENABLE_HUSH_LOCAL
540 struct variable **shadowed_vars_pp;
541 unsigned func_nest_level;
544 /* Signal and trap handling */
546 unsigned count_SIGCHLD;
547 unsigned handled_SIGCHLD;
548 smallint we_have_children;
550 /* which signals have non-DFL handler (even with no traps set)? */
551 unsigned non_DFL_mask;
552 char **traps; /* char *traps[NSIG] */
553 sigset_t blocked_set;
554 sigset_t inherited_set;
556 unsigned long memleak_value;
559 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
561 #define G (*ptr_to_globals)
562 /* Not #defining name to G.name - this quickly gets unwieldy
563 * (too many defines). Also, I actually prefer to see when a variable
564 * is global, thus "G." prefix is a useful hint */
565 #define INIT_G() do { \
566 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
570 /* Function prototypes for builtins */
571 static int builtin_cd(char **argv) FAST_FUNC;
572 static int builtin_echo(char **argv) FAST_FUNC;
573 static int builtin_eval(char **argv) FAST_FUNC;
574 static int builtin_exec(char **argv) FAST_FUNC;
575 static int builtin_exit(char **argv) FAST_FUNC;
576 static int builtin_export(char **argv) FAST_FUNC;
578 static int builtin_fg_bg(char **argv) FAST_FUNC;
579 static int builtin_jobs(char **argv) FAST_FUNC;
582 static int builtin_help(char **argv) FAST_FUNC;
584 #if ENABLE_HUSH_LOCAL
585 static int builtin_local(char **argv) FAST_FUNC;
588 static int builtin_memleak(char **argv) FAST_FUNC;
591 static int builtin_printf(char **argv) FAST_FUNC;
593 static int builtin_pwd(char **argv) FAST_FUNC;
594 static int builtin_read(char **argv) FAST_FUNC;
595 static int builtin_set(char **argv) FAST_FUNC;
596 static int builtin_shift(char **argv) FAST_FUNC;
597 static int builtin_source(char **argv) FAST_FUNC;
598 static int builtin_test(char **argv) FAST_FUNC;
599 static int builtin_trap(char **argv) FAST_FUNC;
600 static int builtin_type(char **argv) FAST_FUNC;
601 static int builtin_true(char **argv) FAST_FUNC;
602 static int builtin_umask(char **argv) FAST_FUNC;
603 static int builtin_unset(char **argv) FAST_FUNC;
604 static int builtin_wait(char **argv) FAST_FUNC;
605 #if ENABLE_HUSH_LOOPS
606 static int builtin_break(char **argv) FAST_FUNC;
607 static int builtin_continue(char **argv) FAST_FUNC;
609 #if ENABLE_HUSH_FUNCTIONS
610 static int builtin_return(char **argv) FAST_FUNC;
613 /* Table of built-in functions. They can be forked or not, depending on
614 * context: within pipes, they fork. As simple commands, they do not.
615 * When used in non-forking context, they can change global variables
616 * in the parent shell process. If forked, of course they cannot.
617 * For example, 'unset foo | whatever' will parse and run, but foo will
618 * still be set at the end. */
619 struct built_in_command {
621 int (*function)(char **argv) FAST_FUNC;
624 # define BLTIN(cmd, func, help) { cmd, func, help }
626 # define BLTIN(cmd, func, help) { cmd, func }
630 static const struct built_in_command bltins1[] = {
631 BLTIN("." , builtin_source , "Run commands in a file"),
632 BLTIN(":" , builtin_true , NULL),
634 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
636 #if ENABLE_HUSH_LOOPS
637 BLTIN("break" , builtin_break , "Exit from a loop"),
639 BLTIN("cd" , builtin_cd , "Change directory"),
640 #if ENABLE_HUSH_LOOPS
641 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
643 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
644 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
645 BLTIN("exit" , builtin_exit , "Exit"),
646 BLTIN("export" , builtin_export , "Set environment variables"),
648 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
651 BLTIN("help" , builtin_help , NULL),
654 BLTIN("jobs" , builtin_jobs , "List jobs"),
656 #if ENABLE_HUSH_LOCAL
657 BLTIN("local" , builtin_local , "Set local variables"),
660 BLTIN("memleak" , builtin_memleak , NULL),
662 BLTIN("read" , builtin_read , "Input into variable"),
663 #if ENABLE_HUSH_FUNCTIONS
664 BLTIN("return" , builtin_return , "Return from a function"),
666 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
667 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
668 BLTIN("trap" , builtin_trap , "Trap signals"),
669 BLTIN("type" , builtin_type , "Write a description of command type"),
670 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
671 BLTIN("umask" , builtin_umask , "Set file creation mask"),
672 BLTIN("unset" , builtin_unset , "Unset variables"),
673 BLTIN("wait" , builtin_wait , "Wait for process"),
675 /* For now, echo and test are unconditionally enabled.
676 * Maybe make it configurable? */
677 static const struct built_in_command bltins2[] = {
678 BLTIN("[" , builtin_test , NULL),
679 BLTIN("echo" , builtin_echo , NULL),
681 BLTIN("printf" , builtin_printf , NULL),
683 BLTIN("pwd" , builtin_pwd , NULL),
684 BLTIN("test" , builtin_test , NULL),
691 /* prevent disasters with G.debug_indent < 0 */
692 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
693 # define debug_enter() (G.debug_indent++)
694 # define debug_leave() (G.debug_indent--)
696 # define indent() ((void)0)
697 # define debug_enter() ((void)0)
698 # define debug_leave() ((void)0)
702 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
705 #ifndef debug_printf_parse
706 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
709 #ifndef debug_printf_exec
710 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
713 #ifndef debug_printf_env
714 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
717 #ifndef debug_printf_jobs
718 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
719 # define DEBUG_JOBS 1
721 # define DEBUG_JOBS 0
724 #ifndef debug_printf_expand
725 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
726 # define DEBUG_EXPAND 1
728 # define DEBUG_EXPAND 0
731 #ifndef debug_printf_glob
732 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
733 # define DEBUG_GLOB 1
735 # define DEBUG_GLOB 0
738 #ifndef debug_printf_list
739 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
742 #ifndef debug_printf_subst
743 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
746 #ifndef debug_printf_clean
747 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
748 # define DEBUG_CLEAN 1
750 # define DEBUG_CLEAN 0
754 static void debug_print_strings(const char *prefix, char **vv)
757 fprintf(stderr, "%s:\n", prefix);
759 fprintf(stderr, " '%s'\n", *vv++);
762 # define debug_print_strings(prefix, vv) ((void)0)
766 /* Leak hunting. Use hush_leaktool.sh for post-processing.
769 static void *xxmalloc(int lineno, size_t size)
771 void *ptr = xmalloc((size + 0xff) & ~0xff);
772 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
775 static void *xxrealloc(int lineno, void *ptr, size_t size)
777 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
778 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
781 static char *xxstrdup(int lineno, const char *str)
783 char *ptr = xstrdup(str);
784 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
787 static void xxfree(void *ptr)
789 fdprintf(2, "free %p\n", ptr);
792 #define xmalloc(s) xxmalloc(__LINE__, s)
793 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
794 #define xstrdup(s) xxstrdup(__LINE__, s)
795 #define free(p) xxfree(p)
799 /* Syntax and runtime errors. They always abort scripts.
800 * In interactive use they usually discard unparsed and/or unexecuted commands
801 * and return to the prompt.
802 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
805 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
806 # define syntax_error(lineno, msg) syntax_error(msg)
807 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
808 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
809 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
810 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
813 static void die_if_script(unsigned lineno, const char *fmt, ...)
818 bb_error_msg("hush.c:%u", lineno);
821 bb_verror_msg(fmt, p, NULL);
823 if (!G_interactive_fd)
827 static void syntax_error(unsigned lineno, const char *msg)
830 die_if_script(lineno, "syntax error: %s", msg);
832 die_if_script(lineno, "syntax error", NULL);
835 static void syntax_error_at(unsigned lineno, const char *msg)
837 die_if_script(lineno, "syntax error at '%s'", msg);
840 static void syntax_error_unterm_str(unsigned lineno, const char *s)
842 die_if_script(lineno, "syntax error: unterminated %s", s);
845 /* It so happens that all such cases are totally fatal
846 * even if shell is interactive: EOF while looking for closing
847 * delimiter. There is nowhere to read stuff from after that,
848 * it's EOF! The only choice is to terminate.
850 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
851 static void syntax_error_unterm_ch(unsigned lineno, char ch)
853 char msg[2] = { ch, '\0' };
854 syntax_error_unterm_str(lineno, msg);
858 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
863 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
867 # undef die_if_script
869 # undef syntax_error_at
870 # undef syntax_error_unterm_ch
871 # undef syntax_error_unterm_str
872 # undef syntax_error_unexpected_ch
874 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
875 # define syntax_error(msg) syntax_error(__LINE__, msg)
876 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
877 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
878 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
879 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
883 #if ENABLE_HUSH_INTERACTIVE
884 static void cmdedit_update_prompt(void);
886 # define cmdedit_update_prompt() ((void)0)
892 static int glob_needed(const char *s)
897 if (*s == '*' || *s == '[' || *s == '?')
904 static int is_well_formed_var_name(const char *s, char terminator)
906 if (!s || !(isalpha(*s) || *s == '_'))
909 while (isalnum(*s) || *s == '_')
911 return *s == terminator;
914 /* Replace each \x with x in place, return ptr past NUL. */
915 static char *unbackslash(char *src)
917 char *dst = src = strchrnul(src, '\\');
921 if ((*dst++ = *src++) == '\0')
927 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
948 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
949 v[count1 + count2] = NULL;
952 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
956 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
958 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
959 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
962 #define add_strings_to_strings(strings, add, need_to_dup) \
963 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
966 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
967 static char **add_string_to_strings(char **strings, char *add)
972 return add_strings_to_strings(strings, v, /*dup:*/ 0);
975 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
977 char **ptr = add_string_to_strings(strings, add);
978 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
981 #define add_string_to_strings(strings, add) \
982 xx_add_string_to_strings(__LINE__, strings, add)
985 static void free_strings(char **strings)
1000 /* Helpers for setting new $n and restoring them back
1002 typedef struct save_arg_t {
1006 smallint sv_g_malloced;
1009 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1013 sv->sv_argv0 = argv[0];
1014 sv->sv_g_argv = G.global_argv;
1015 sv->sv_g_argc = G.global_argc;
1016 sv->sv_g_malloced = G.global_args_malloced;
1018 argv[0] = G.global_argv[0]; /* retain $0 */
1019 G.global_argv = argv;
1020 G.global_args_malloced = 0;
1028 static void restore_G_args(save_arg_t *sv, char **argv)
1032 if (G.global_args_malloced) {
1033 /* someone ran "set -- arg1 arg2 ...", undo */
1035 while (*++pp) /* note: does not free $0 */
1037 free(G.global_argv);
1039 argv[0] = sv->sv_argv0;
1040 G.global_argv = sv->sv_g_argv;
1041 G.global_argc = sv->sv_g_argc;
1042 G.global_args_malloced = sv->sv_g_malloced;
1046 /* Basic theory of signal handling in shell
1047 * ========================================
1048 * This does not describe what hush does, rather, it is current understanding
1049 * what it _should_ do. If it doesn't, it's a bug.
1050 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1052 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1053 * is finished or backgrounded. It is the same in interactive and
1054 * non-interactive shells, and is the same regardless of whether
1055 * a user trap handler is installed or a shell special one is in effect.
1056 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1057 * backgrounds (i.e. stops) or kills all members of currently running
1060 * Wait builtin in interruptible by signals for which user trap is set
1061 * or by SIGINT in interactive shell.
1063 * Trap handlers will execute even within trap handlers. (right?)
1065 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1067 * If job control is off, backgrounded commands ("cmd &")
1068 * have SIGINT, SIGQUIT set to SIG_IGN.
1070 * Commands which are run in command substitution ("`cmd`")
1071 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1073 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1074 * by the shell from its parent.
1076 * Signals which differ from SIG_DFL action
1077 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1080 * SIGTERM (interactive): ignore
1081 * SIGHUP (interactive):
1082 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1083 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1084 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1085 * that all pipe members are stopped. Try this in bash:
1086 * while :; do :; done - ^Z does not background it
1087 * (while :; do :; done) - ^Z backgrounds it
1088 * SIGINT (interactive): wait for last pipe, ignore the rest
1089 * of the command line, show prompt. NB: ^C does not send SIGINT
1090 * to interactive shell while shell is waiting for a pipe,
1091 * since shell is bg'ed (is not in foreground process group).
1092 * Example 1: this waits 5 sec, but does not execute ls:
1093 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1094 * Example 2: this does not wait and does not execute ls:
1095 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1096 * Example 3: this does not wait 5 sec, but executes ls:
1097 * "sleep 5; ls -l" + press ^C
1099 * (What happens to signals which are IGN on shell start?)
1100 * (What happens with signal mask on shell start?)
1102 * Implementation in hush
1103 * ======================
1104 * We use in-kernel pending signal mask to determine which signals were sent.
1105 * We block all signals which we don't want to take action immediately,
1106 * i.e. we block all signals which need to have special handling as described
1107 * above, and all signals which have traps set.
1108 * After each pipe execution, we extract any pending signals via sigtimedwait()
1111 * unsigned non_DFL_mask: a mask of such "special" signals
1112 * sigset_t blocked_set: current blocked signal set
1115 * clear bit in blocked_set unless it is also in non_DFL_mask
1116 * "trap 'cmd' SIGxxx":
1117 * set bit in blocked_set (even if 'cmd' is '')
1118 * after [v]fork, if we plan to be a shell:
1119 * unblock signals with special interactive handling
1120 * (child shell is not interactive),
1121 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1122 * after [v]fork, if we plan to exec:
1123 * POSIX says fork clears pending signal mask in child - no need to clear it.
1124 * Restore blocked signal set to one inherited by shell just prior to exec.
1126 * Note: as a result, we do not use signal handlers much. The only uses
1127 * are to count SIGCHLDs
1128 * and to restore tty pgrp on signal-induced exit.
1131 * Standard says "When a subshell is entered, traps that are not being ignored
1132 * are set to the default actions". bash interprets it so that traps which
1133 * are set to "" (ignore) are NOT reset to defaults. We do the same.
1136 SPECIAL_INTERACTIVE_SIGS = 0
1141 SPECIAL_JOB_SIGS = 0
1149 #if ENABLE_HUSH_FAST
1150 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1153 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1159 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1160 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1161 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1162 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1164 /* Restores tty foreground process group, and exits.
1165 * May be called as signal handler for fatal signal
1166 * (will resend signal to itself, producing correct exit state)
1167 * or called directly with -EXITCODE.
1168 * We also call it if xfunc is exiting. */
1169 static void sigexit(int sig) NORETURN;
1170 static void sigexit(int sig)
1172 /* Disable all signals: job control, SIGPIPE, etc. */
1173 sigprocmask_allsigs(SIG_BLOCK);
1175 /* Careful: we can end up here after [v]fork. Do not restore
1176 * tty pgrp then, only top-level shell process does that */
1177 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1178 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1180 /* Not a signal, just exit */
1184 kill_myself_with_sig(sig); /* does not return */
1188 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1189 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1193 /* Restores tty foreground process group, and exits. */
1194 static void hush_exit(int exitcode) NORETURN;
1195 static void hush_exit(int exitcode)
1197 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1198 /* Prevent recursion:
1199 * trap "echo Hi; exit" EXIT; exit
1201 char *argv[] = { NULL, G.traps[0], NULL };
1209 fflush(NULL); /* flush all streams */
1210 sigexit(- (exitcode & 0xff));
1216 static int check_and_run_traps(int sig)
1218 static const struct timespec zero_timespec = { 0, 0 };
1219 smalluint save_rcode;
1225 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1230 if (G.traps && G.traps[sig]) {
1231 if (G.traps[sig][0]) {
1232 /* We have user-defined handler */
1233 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1234 save_rcode = G.last_exitcode;
1237 G.last_exitcode = save_rcode;
1238 } /* else: "" trap, ignoring signal */
1241 /* not a trap: special action */
1243 #if ENABLE_HUSH_FAST
1246 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1250 /* Builtin was ^C'ed, make it look prettier: */
1257 /* bash is observed to signal whole process groups,
1258 * not individual processes */
1259 for (job = G.job_list; job; job = job->next) {
1262 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1263 if (kill(- job->pgrp, SIGHUP) == 0)
1264 kill(- job->pgrp, SIGCONT);
1269 default: /* ignored: */
1270 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1278 static const char *get_cwd(int force)
1280 if (force || G.cwd == NULL) {
1281 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1282 * we must not try to free(bb_msg_unknown) */
1283 if (G.cwd == bb_msg_unknown)
1285 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1287 G.cwd = bb_msg_unknown;
1294 * Shell and environment variable support
1296 static struct variable **get_ptr_to_local_var(const char *name)
1298 struct variable **pp;
1299 struct variable *cur;
1304 while ((cur = *pp) != NULL) {
1305 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1312 static struct variable *get_local_var(const char *name)
1314 struct variable **pp = get_ptr_to_local_var(name);
1320 static const char *get_local_var_value(const char *name)
1322 struct variable **pp = get_ptr_to_local_var(name);
1324 return strchr((*pp)->varstr, '=') + 1;
1325 if (strcmp(name, "PPID") == 0)
1326 return utoa(G.root_ppid);
1327 // bash compat: UID? EUID?
1328 #if ENABLE_HUSH_RANDOM_SUPPORT
1329 if (strcmp(name, "RANDOM") == 0) {
1330 return utoa(next_random(&G.random_gen));
1336 /* str holds "NAME=VAL" and is expected to be malloced.
1337 * We take ownership of it.
1339 * 0: do not change export flag
1340 * (if creating new variable, flag will be 0)
1341 * 1: set export flag and putenv the variable
1342 * -1: clear export flag and unsetenv the variable
1343 * flg_read_only is set only when we handle -R var=val
1345 #if !BB_MMU && ENABLE_HUSH_LOCAL
1346 /* all params are used */
1347 #elif BB_MMU && ENABLE_HUSH_LOCAL
1348 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1349 set_local_var(str, flg_export, local_lvl)
1350 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1351 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1352 set_local_var(str, flg_export)
1353 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1354 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1355 set_local_var(str, flg_export, flg_read_only)
1357 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1359 struct variable **var_pp;
1360 struct variable *cur;
1364 eq_sign = strchr(str, '=');
1365 if (!eq_sign) { /* not expected to ever happen? */
1370 name_len = eq_sign - str + 1; /* including '=' */
1371 var_pp = &G.top_var;
1372 while ((cur = *var_pp) != NULL) {
1373 if (strncmp(cur->varstr, str, name_len) != 0) {
1374 var_pp = &cur->next;
1377 /* We found an existing var with this name */
1378 if (cur->flg_read_only) {
1382 bb_error_msg("%s: readonly variable", str);
1386 if (flg_export == -1) { // "&& cur->flg_export" ?
1387 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1392 #if ENABLE_HUSH_LOCAL
1393 if (cur->func_nest_level < local_lvl) {
1394 /* New variable is declared as local,
1395 * and existing one is global, or local
1396 * from enclosing function.
1397 * Remove and save old one: */
1398 *var_pp = cur->next;
1399 cur->next = *G.shadowed_vars_pp;
1400 *G.shadowed_vars_pp = cur;
1401 /* bash 3.2.33(1) and exported vars:
1403 * # f() { local z=a; env | grep ^z; }
1409 if (cur->flg_export)
1414 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1419 if (cur->max_len != 0) {
1420 if (cur->max_len >= strlen(str)) {
1421 /* This one is from startup env, reuse space */
1422 strcpy(cur->varstr, str);
1426 /* max_len == 0 signifies "malloced" var, which we can
1427 * (and has to) free */
1431 goto set_str_and_exp;
1434 /* Not found - create new variable struct */
1435 cur = xzalloc(sizeof(*cur));
1436 #if ENABLE_HUSH_LOCAL
1437 cur->func_nest_level = local_lvl;
1439 cur->next = *var_pp;
1445 cur->flg_read_only = flg_read_only;
1448 if (flg_export == 1)
1449 cur->flg_export = 1;
1450 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1451 cmdedit_update_prompt();
1452 if (cur->flg_export) {
1453 if (flg_export == -1) {
1454 cur->flg_export = 0;
1455 /* unsetenv was already done */
1457 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1458 return putenv(cur->varstr);
1464 /* Used at startup and after each cd */
1465 static void set_pwd_var(int exp)
1467 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1468 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1471 static int unset_local_var_len(const char *name, int name_len)
1473 struct variable *cur;
1474 struct variable **var_pp;
1477 return EXIT_SUCCESS;
1478 var_pp = &G.top_var;
1479 while ((cur = *var_pp) != NULL) {
1480 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1481 if (cur->flg_read_only) {
1482 bb_error_msg("%s: readonly variable", name);
1483 return EXIT_FAILURE;
1485 *var_pp = cur->next;
1486 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1487 bb_unsetenv(cur->varstr);
1488 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1489 cmdedit_update_prompt();
1493 return EXIT_SUCCESS;
1495 var_pp = &cur->next;
1497 return EXIT_SUCCESS;
1500 static int unset_local_var(const char *name)
1502 return unset_local_var_len(name, strlen(name));
1505 static void unset_vars(char **strings)
1513 const char *eq = strchrnul(*v, '=');
1514 unset_local_var_len(*v, (int)(eq - *v));
1520 #if ENABLE_SH_MATH_SUPPORT
1521 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1522 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1523 static char *endofname(const char *name)
1531 if (!is_in_name(*p))
1537 static void arith_set_local_var(const char *name, const char *val, int flags)
1539 /* arith code doesnt malloc space, so do it for it */
1540 char *var = xasprintf("%s=%s", name, val);
1541 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1547 * Helpers for "var1=val1 var2=val2 cmd" feature
1549 static void add_vars(struct variable *var)
1551 struct variable *next;
1555 var->next = G.top_var;
1557 if (var->flg_export) {
1558 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1559 putenv(var->varstr);
1561 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1567 static struct variable *set_vars_and_save_old(char **strings)
1570 struct variable *old = NULL;
1576 struct variable *var_p;
1577 struct variable **var_pp;
1580 eq = strchr(*s, '=');
1583 var_pp = get_ptr_to_local_var(*s);
1586 /* Remove variable from global linked list */
1588 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1589 *var_pp = var_p->next;
1590 /* Add it to returned list */
1594 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1605 static int FAST_FUNC static_get(struct in_str *i)
1614 static int FAST_FUNC static_peek(struct in_str *i)
1619 #if ENABLE_HUSH_INTERACTIVE
1621 static void cmdedit_update_prompt(void)
1623 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1624 G.PS1 = get_local_var_value("PS1");
1627 G.PS2 = get_local_var_value("PS2");
1635 static const char* setup_prompt_string(int promptmode)
1637 const char *prompt_str;
1638 debug_printf("setup_prompt_string %d ", promptmode);
1639 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1640 /* Set up the prompt */
1641 if (promptmode == 0) { /* PS1 */
1643 /* bash uses $PWD value, even if it is set by user.
1644 * It uses current dir only if PWD is unset.
1645 * We always use current dir. */
1646 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1651 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1652 debug_printf("result '%s'\n", prompt_str);
1656 static void get_user_input(struct in_str *i)
1659 const char *prompt_str;
1661 prompt_str = setup_prompt_string(i->promptmode);
1662 #if ENABLE_FEATURE_EDITING
1663 /* Enable command line editing only while a command line
1664 * is actually being read */
1667 /* buglet: SIGINT will not make new prompt to appear _at once_,
1668 * only after <Enter>. (^C will work) */
1669 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1670 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1671 check_and_run_traps(0);
1672 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1673 i->eof_flag = (r < 0);
1674 if (i->eof_flag) { /* EOF/error detected */
1675 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1676 G.user_input_buf[1] = '\0';
1681 fputs(prompt_str, stdout);
1683 G.user_input_buf[0] = r = fgetc(i->file);
1684 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1685 //do we need check_and_run_traps(0)? (maybe only if stdin)
1686 } while (G.flag_SIGINT);
1687 i->eof_flag = (r == EOF);
1689 i->p = G.user_input_buf;
1692 #endif /* INTERACTIVE */
1694 /* This is the magic location that prints prompts
1695 * and gets data back from the user */
1696 static int FAST_FUNC file_get(struct in_str *i)
1700 /* If there is data waiting, eat it up */
1701 if (i->p && *i->p) {
1702 #if ENABLE_HUSH_INTERACTIVE
1706 if (i->eof_flag && !*i->p)
1708 /* note: ch is never NUL */
1710 /* need to double check i->file because we might be doing something
1711 * more complicated by now, like sourcing or substituting. */
1712 #if ENABLE_HUSH_INTERACTIVE
1713 if (G_interactive_fd && i->promptme && i->file == stdin) {
1716 } while (!*i->p); /* need non-empty line */
1717 i->promptmode = 1; /* PS2 */
1722 do ch = fgetc(i->file); while (ch == '\0');
1724 debug_printf("file_get: got '%c' %d\n", ch, ch);
1725 #if ENABLE_HUSH_INTERACTIVE
1732 /* All callers guarantee this routine will never
1733 * be used right after a newline, so prompting is not needed.
1735 static int FAST_FUNC file_peek(struct in_str *i)
1738 if (i->p && *i->p) {
1739 if (i->eof_flag && !i->p[1])
1742 /* note: ch is never NUL */
1744 do ch = fgetc(i->file); while (ch == '\0');
1745 i->eof_flag = (ch == EOF);
1746 i->peek_buf[0] = ch;
1747 i->peek_buf[1] = '\0';
1749 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1753 static void setup_file_in_str(struct in_str *i, FILE *f)
1755 i->peek = file_peek;
1757 #if ENABLE_HUSH_INTERACTIVE
1759 i->promptmode = 0; /* PS1 */
1765 static void setup_string_in_str(struct in_str *i, const char *s)
1767 i->peek = static_peek;
1768 i->get = static_get;
1769 #if ENABLE_HUSH_INTERACTIVE
1771 i->promptmode = 0; /* PS1 */
1781 #define B_CHUNK (32 * sizeof(char*))
1783 static void o_reset_to_empty_unquoted(o_string *o)
1791 static void o_free(o_string *o)
1794 memset(o, 0, sizeof(*o));
1797 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1802 static void o_grow_by(o_string *o, int len)
1804 if (o->length + len > o->maxlen) {
1805 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1806 o->data = xrealloc(o->data, 1 + o->maxlen);
1810 static void o_addchr(o_string *o, int ch)
1812 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1814 o->data[o->length] = ch;
1816 o->data[o->length] = '\0';
1819 static void o_addblock(o_string *o, const char *str, int len)
1822 memcpy(&o->data[o->length], str, len);
1824 o->data[o->length] = '\0';
1828 static void o_addstr(o_string *o, const char *str)
1830 o_addblock(o, str, strlen(str));
1832 static void nommu_addchr(o_string *o, int ch)
1838 # define nommu_addchr(o, str) ((void)0)
1841 static void o_addstr_with_NUL(o_string *o, const char *str)
1843 o_addblock(o, str, strlen(str) + 1);
1846 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1851 && (*str != '*' && *str != '?' && *str != '[')
1859 /* My analysis of quoting semantics tells me that state information
1860 * is associated with a destination, not a source.
1862 static void o_addqchr(o_string *o, int ch)
1865 char *found = strchr("*?[\\", ch);
1870 o->data[o->length] = '\\';
1873 o->data[o->length] = ch;
1875 o->data[o->length] = '\0';
1878 static void o_addQchr(o_string *o, int ch)
1881 if (o->o_escape && strchr("*?[\\", ch)) {
1883 o->data[o->length] = '\\';
1887 o->data[o->length] = ch;
1889 o->data[o->length] = '\0';
1892 static void o_addQstr(o_string *o, const char *str, int len)
1895 o_addblock(o, str, len);
1901 int ordinary_cnt = strcspn(str, "*?[\\");
1902 if (ordinary_cnt > len) /* paranoia */
1904 o_addblock(o, str, ordinary_cnt);
1905 if (ordinary_cnt == len)
1907 str += ordinary_cnt;
1908 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1912 if (ch) { /* it is necessarily one of "*?[\\" */
1914 o->data[o->length] = '\\';
1918 o->data[o->length] = ch;
1920 o->data[o->length] = '\0';
1924 /* A special kind of o_string for $VAR and `cmd` expansion.
1925 * It contains char* list[] at the beginning, which is grown in 16 element
1926 * increments. Actual string data starts at the next multiple of 16 * (char*).
1927 * list[i] contains an INDEX (int!) into this string data.
1928 * It means that if list[] needs to grow, data needs to be moved higher up
1929 * but list[i]'s need not be modified.
1930 * NB: remembering how many list[i]'s you have there is crucial.
1931 * o_finalize_list() operation post-processes this structure - calculates
1932 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1934 #if DEBUG_EXPAND || DEBUG_GLOB
1935 static void debug_print_list(const char *prefix, o_string *o, int n)
1937 char **list = (char**)o->data;
1938 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1942 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1943 prefix, list, n, string_start, o->length, o->maxlen);
1946 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1947 o->data + (int)list[i] + string_start,
1948 o->data + (int)list[i] + string_start);
1952 const char *p = o->data + (int)list[n - 1] + string_start;
1954 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1958 # define debug_print_list(prefix, o, n) ((void)0)
1961 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1962 * in list[n] so that it points past last stored byte so far.
1963 * It returns n+1. */
1964 static int o_save_ptr_helper(o_string *o, int n)
1966 char **list = (char**)o->data;
1970 if (!o->has_empty_slot) {
1971 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1972 string_len = o->length - string_start;
1973 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1974 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1975 /* list[n] points to string_start, make space for 16 more pointers */
1976 o->maxlen += 0x10 * sizeof(list[0]);
1977 o->data = xrealloc(o->data, o->maxlen + 1);
1978 list = (char**)o->data;
1979 memmove(list + n + 0x10, list + n, string_len);
1980 o->length += 0x10 * sizeof(list[0]);
1982 debug_printf_list("list[%d]=%d string_start=%d\n",
1983 n, string_len, string_start);
1986 /* We have empty slot at list[n], reuse without growth */
1987 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1988 string_len = o->length - string_start;
1989 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1990 n, string_len, string_start);
1991 o->has_empty_slot = 0;
1993 list[n] = (char*)(ptrdiff_t)string_len;
1997 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1998 static int o_get_last_ptr(o_string *o, int n)
2000 char **list = (char**)o->data;
2001 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2003 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2006 /* o_glob performs globbing on last list[], saving each result
2007 * as a new list[]. */
2008 static int o_glob(o_string *o, int n)
2014 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2016 return o_save_ptr_helper(o, n);
2017 pattern = o->data + o_get_last_ptr(o, n);
2018 debug_printf_glob("glob pattern '%s'\n", pattern);
2019 if (!glob_needed(pattern)) {
2021 o->length = unbackslash(pattern) - o->data;
2022 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2023 return o_save_ptr_helper(o, n);
2026 memset(&globdata, 0, sizeof(globdata));
2027 gr = glob(pattern, 0, NULL, &globdata);
2028 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2029 if (gr == GLOB_NOSPACE)
2030 bb_error_msg_and_die("out of memory during glob");
2031 if (gr == GLOB_NOMATCH) {
2032 globfree(&globdata);
2035 if (gr != 0) { /* GLOB_ABORTED ? */
2036 /* TODO: testcase for bad glob pattern behavior */
2037 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2039 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2040 char **argv = globdata.gl_pathv;
2041 o->length = pattern - o->data; /* "forget" pattern */
2043 o_addstr_with_NUL(o, *argv);
2044 n = o_save_ptr_helper(o, n);
2050 globfree(&globdata);
2052 debug_print_list("o_glob returning", o, n);
2056 /* If o->o_glob == 1, glob the string so far remembered.
2057 * Otherwise, just finish current list[] and start new */
2058 static int o_save_ptr(o_string *o, int n)
2060 if (o->o_glob) { /* if globbing is requested */
2061 /* If o->has_empty_slot, list[n] was already globbed
2062 * (if it was requested back then when it was filled)
2063 * so don't do that again! */
2064 if (!o->has_empty_slot)
2065 return o_glob(o, n); /* o_save_ptr_helper is inside */
2067 return o_save_ptr_helper(o, n);
2070 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2071 static char **o_finalize_list(o_string *o, int n)
2076 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2078 debug_print_list("finalized", o, n);
2079 debug_printf_expand("finalized n:%d\n", n);
2080 list = (char**)o->data;
2081 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2085 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2091 /* Expansion can recurse */
2092 #if ENABLE_HUSH_TICK
2093 static int process_command_subs(o_string *dest, const char *s);
2095 static char *expand_string_to_string(const char *str);
2097 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2098 parse_stream_dquoted(dest, input, dquote_end)
2100 static int parse_stream_dquoted(o_string *as_string,
2102 struct in_str *input,
2105 /* expand_strvec_to_strvec() takes a list of strings, expands
2106 * all variable references within and returns a pointer to
2107 * a list of expanded strings, possibly with larger number
2108 * of strings. (Think VAR="a b"; echo $VAR).
2109 * This new list is allocated as a single malloc block.
2110 * NULL-terminated list of char* pointers is at the beginning of it,
2111 * followed by strings themself.
2112 * Caller can deallocate entire list by single free(list). */
2114 /* Store given string, finalizing the word and starting new one whenever
2115 * we encounter IFS char(s). This is used for expanding variable values.
2116 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2117 static int expand_on_ifs(o_string *output, int n, const char *str)
2120 int word_len = strcspn(str, G.ifs);
2122 if (output->o_escape || !output->o_glob)
2123 o_addQstr(output, str, word_len);
2124 else /* protect backslashes against globbing up :) */
2125 o_addblock_duplicate_backslash(output, str, word_len);
2128 if (!*str) /* EOL - do not finalize word */
2130 o_addchr(output, '\0');
2131 debug_print_list("expand_on_ifs", output, n);
2132 n = o_save_ptr(output, n);
2133 str += strspn(str, G.ifs); /* skip ifs chars */
2135 debug_print_list("expand_on_ifs[1]", output, n);
2139 /* Helper to expand $((...)) and heredoc body. These act as if
2140 * they are in double quotes, with the exception that they are not :).
2141 * Just the rules are similar: "expand only $var and `cmd`"
2143 * Returns malloced string.
2144 * As an optimization, we return NULL if expansion is not needed.
2146 static char *expand_pseudo_dquoted(const char *str)
2149 struct in_str input;
2150 o_string dest = NULL_O_STRING;
2152 if (strchr(str, '$') == NULL
2153 #if ENABLE_HUSH_TICK
2154 && strchr(str, '`') == NULL
2160 /* We need to expand. Example:
2161 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2163 setup_string_in_str(&input, str);
2164 parse_stream_dquoted(NULL, &dest, &input, EOF);
2165 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2166 exp_str = expand_string_to_string(dest.data);
2167 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2168 o_free_unsafe(&dest);
2172 /* Expand all variable references in given string, adding words to list[]
2173 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2174 * to be filled). This routine is extremely tricky: has to deal with
2175 * variables/parameters with whitespace, $* and $@, and constructs like
2176 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2177 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2179 /* or_mask is either 0 (normal case) or 0x80 -
2180 * expansion of right-hand side of assignment == 1-element expand.
2181 * It will also do no globbing, and thus we must not backslash-quote!
2188 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2189 debug_print_list("expand_vars_to_list", output, n);
2190 n = o_save_ptr(output, n);
2191 debug_print_list("expand_vars_to_list[0]", output, n);
2193 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2196 char *dyn_val = NULL;
2197 const char *val = NULL;
2198 #if ENABLE_HUSH_TICK
2199 o_string subst_result = NULL_O_STRING;
2201 #if ENABLE_SH_MATH_SUPPORT
2202 char arith_buf[sizeof(arith_t)*3 + 2];
2204 o_addblock(output, arg, p - arg);
2205 debug_print_list("expand_vars_to_list[1]", output, n);
2207 p = strchr(p, SPECIAL_VAR_SYMBOL);
2209 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2210 /* "$@" is special. Even if quoted, it can still
2211 * expand to nothing (not even an empty string) */
2212 if ((first_ch & 0x7f) != '@')
2213 ored_ch |= first_ch;
2215 switch (first_ch & 0x7f) {
2216 /* Highest bit in first_ch indicates that var is double-quoted */
2218 val = utoa(G.root_pid);
2220 case '!': /* bg pid */
2221 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2223 case '?': /* exitcode */
2224 val = utoa(G.last_exitcode);
2226 case '#': /* argc */
2227 if (arg[1] != SPECIAL_VAR_SYMBOL)
2228 /* actually, it's a ${#var} */
2230 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2235 if (!G.global_argv[i])
2237 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2238 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2239 smallint sv = output->o_escape;
2240 /* unquoted var's contents should be globbed, so don't escape */
2241 output->o_escape = 0;
2242 while (G.global_argv[i]) {
2243 n = expand_on_ifs(output, n, G.global_argv[i]);
2244 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2245 if (G.global_argv[i++][0] && G.global_argv[i]) {
2246 /* this argv[] is not empty and not last:
2247 * put terminating NUL, start new word */
2248 o_addchr(output, '\0');
2249 debug_print_list("expand_vars_to_list[2]", output, n);
2250 n = o_save_ptr(output, n);
2251 debug_print_list("expand_vars_to_list[3]", output, n);
2254 output->o_escape = sv;
2256 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2257 * and in this case should treat it like '$*' - see 'else...' below */
2258 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2260 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2261 if (++i >= G.global_argc)
2263 o_addchr(output, '\0');
2264 debug_print_list("expand_vars_to_list[4]", output, n);
2265 n = o_save_ptr(output, n);
2267 } else { /* quoted $*: add as one word */
2269 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2270 if (!G.global_argv[++i])
2273 o_addchr(output, G.ifs[0]);
2277 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2278 /* "Empty variable", used to make "" etc to not disappear */
2282 #if ENABLE_HUSH_TICK
2283 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2286 /* Can't just stuff it into output o_string,
2287 * expanded result may need to be globbed
2288 * and $IFS-splitted */
2289 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2290 process_command_subs(&subst_result, arg);
2291 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2292 val = subst_result.data;
2295 #if ENABLE_SH_MATH_SUPPORT
2296 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2297 arith_eval_hooks_t hooks;
2302 arg++; /* skip '+' */
2303 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2304 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2306 exp_str = expand_pseudo_dquoted(arg);
2307 hooks.lookupvar = get_local_var_value;
2308 hooks.setvar = arith_set_local_var;
2309 hooks.endofname = endofname;
2310 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2314 const char *msg = "error in arithmetic";
2317 msg = "exponent less than 0";
2320 msg = "divide by 0";
2323 msg = "expression recursion loop detected";
2328 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2329 sprintf(arith_buf, arith_t_fmt, res);
2334 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2336 bool exp_len = false;
2337 bool exp_null = false;
2339 char exp_save = exp_save; /* for compiler */
2340 char exp_op = exp_op; /* for compiler */
2341 char *exp_word = exp_word; /* for compiler */
2345 arg[0] = first_ch & 0x7f;
2347 /* prepare for expansions */
2348 if (var[0] == '#') {
2349 /* handle length expansion ${#var} */
2353 /* maybe handle parameter expansion */
2354 exp_off = strcspn(var, ":-=+?%#");
2358 exp_save = var[exp_off];
2359 exp_null = exp_save == ':';
2360 exp_word = var + exp_off;
2363 exp_op = *exp_word++;
2364 var[exp_off] = '\0';
2368 /* lookup the variable in question */
2369 if (isdigit(var[0])) {
2370 /* handle_dollar() should have vetted var for us */
2372 if (i < G.global_argc)
2373 val = G.global_argv[i];
2374 /* else val remains NULL: $N with too big N */
2376 val = get_local_var_value(var);
2378 /* handle any expansions */
2380 debug_printf_expand("expand: length of '%s' = ", val);
2381 val = utoa(val ? strlen(val) : 0);
2382 debug_printf_expand("%s\n", val);
2383 } else if (exp_off) {
2384 if (exp_op == '%' || exp_op == '#') {
2386 /* we need to do a pattern match */
2389 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2390 if (exp_op == *exp_word) /* ## or %% */
2392 val = dyn_val = xstrdup(val);
2393 loc = scan(dyn_val, exp_word, match_at_left);
2394 if (match_at_left) /* # or ## */
2396 else if (loc) /* % or %% and match was found */
2400 /* we need to do an expansion */
2401 int exp_test = (!val || (exp_null && !val[0]));
2403 exp_test = !exp_test;
2404 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2405 exp_null ? "true" : "false", exp_test);
2407 if (exp_op == '?') {
2408 //TODO: how interactive bash aborts expansion mid-command?
2409 /* ${var?[error_msg_if_unset]} */
2410 /* ${var:?[error_msg_if_unset_or_null]} */
2411 /* mimic bash message */
2412 die_if_script("%s: %s",
2414 exp_word[0] ? exp_word : "parameter null or not set"
2420 if (exp_op == '=') {
2421 /* ${var=[word]} or ${var:=[word]} */
2422 if (isdigit(var[0]) || var[0] == '#') {
2423 /* mimic bash message */
2424 die_if_script("$%s: cannot assign in this way", var);
2427 char *new_var = xasprintf("%s=%s", var, val);
2428 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2434 var[exp_off] = exp_save;
2438 #if ENABLE_HUSH_TICK
2441 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2442 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2444 /* unquoted var's contents should be globbed, so don't escape */
2445 smallint sv = output->o_escape;
2446 output->o_escape = 0;
2447 n = expand_on_ifs(output, n, val);
2449 output->o_escape = sv;
2451 } else { /* quoted $VAR, val will be appended below */
2452 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2455 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2458 o_addQstr(output, val, strlen(val));
2461 /* Do the check to avoid writing to a const string */
2462 if (*p != SPECIAL_VAR_SYMBOL)
2463 *p = SPECIAL_VAR_SYMBOL;
2465 #if ENABLE_HUSH_TICK
2466 o_free(&subst_result);
2469 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2472 debug_print_list("expand_vars_to_list[a]", output, n);
2473 /* this part is literal, and it was already pre-quoted
2474 * if needed (much earlier), do not use o_addQstr here! */
2475 o_addstr_with_NUL(output, arg);
2476 debug_print_list("expand_vars_to_list[b]", output, n);
2477 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2478 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2481 /* allow to reuse list[n] later without re-growth */
2482 output->has_empty_slot = 1;
2484 o_addchr(output, '\0');
2489 static char **expand_variables(char **argv, int or_mask)
2494 o_string output = NULL_O_STRING;
2496 if (or_mask & 0x100) {
2497 output.o_escape = 1; /* protect against globbing for "$var" */
2498 /* (unquoted $var will temporarily switch it off) */
2505 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2508 debug_print_list("expand_variables", &output, n);
2510 /* output.data (malloced in one block) gets returned in "list" */
2511 list = o_finalize_list(&output, n);
2512 debug_print_strings("expand_variables[1]", list);
2516 static char **expand_strvec_to_strvec(char **argv)
2518 return expand_variables(argv, 0x100);
2521 #if ENABLE_HUSH_BASH_COMPAT
2522 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2524 return expand_variables(argv, 0x80);
2528 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2529 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2534 o_string output = NULL_O_STRING;
2539 int is_var = is_well_formed_var_name(*v, '=');
2540 /* is_var * 0x80: singleword expansion for vars */
2541 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2543 /* Subtle! expand_vars_to_list did not glob last word yet.
2544 * It does this only when fed with further data.
2545 * Therefore we set globbing flags AFTER it, not before:
2548 /* if it is not recognizably abc=...; then: */
2549 output.o_escape = !is_var; /* protect against globbing for "$var" */
2550 /* (unquoted $var will temporarily switch it off) */
2551 output.o_glob = !is_var; /* and indeed do globbing */
2554 debug_print_list("expand_cond", &output, n);
2556 /* output.data (malloced in one block) gets returned in "list" */
2557 list = o_finalize_list(&output, n);
2558 debug_print_strings("expand_cond[1]", list);
2563 /* Used for expansion of right hand of assignments */
2564 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2566 static char *expand_string_to_string(const char *str)
2568 char *argv[2], **list;
2570 argv[0] = (char*)str;
2572 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2574 if (!list[0] || list[1])
2575 bb_error_msg_and_die("BUG in varexp2");
2576 /* actually, just move string 2*sizeof(char*) bytes back */
2577 overlapping_strcpy((char*)list, list[0]);
2578 unbackslash((char*)list);
2579 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2583 /* Used for "eval" builtin */
2584 static char* expand_strvec_to_string(char **argv)
2588 list = expand_variables(argv, 0x80);
2589 /* Convert all NULs to spaces */
2594 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2595 bb_error_msg_and_die("BUG in varexp3");
2596 /* bash uses ' ' regardless of $IFS contents */
2601 overlapping_strcpy((char*)list, list[0]);
2602 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2606 static char **expand_assignments(char **argv, int count)
2610 /* Expand assignments into one string each */
2611 for (i = 0; i < count; i++) {
2612 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2620 void re_execute_shell(char ***to_free, const char *s,
2621 char *g_argv0, char **g_argv,
2622 char **builtin_argv) NORETURN;
2624 static void reset_traps_to_defaults(void)
2626 /* This function is always called in a child shell
2627 * after fork (not vfork, NOMMU doesn't use this function).
2632 /* Child shells are not interactive.
2633 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2634 * Testcase: (while :; do :; done) + ^Z should background.
2635 * Same goes for SIGTERM, SIGHUP, SIGINT.
2637 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2638 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
2640 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2641 * Stupid. It can be done with *single* &= op, but we can't use
2642 * the fact that G.blocked_set is implemented as a bitmask
2644 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2648 /* Careful. Only if no trap or trap is not "" */
2649 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2650 sigdelset(&G.blocked_set, sig);
2657 /* Our homegrown sig mask is saner to work with :) */
2658 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2660 /* Resetting all traps to default except empty ones */
2661 mask = G.non_DFL_mask;
2662 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2663 if (!G.traps[sig] || !G.traps[sig][0])
2666 G.traps[sig] = NULL;
2667 /* There is no signal for 0 (EXIT) */
2670 /* There was a trap handler, we just removed it.
2671 * But if sig still has non-DFL handling,
2672 * we should not unblock the sig. */
2675 sigdelset(&G.blocked_set, sig);
2677 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2682 static void re_execute_shell(char ***to_free, const char *s,
2683 char *g_argv0, char **g_argv,
2684 char **builtin_argv) NORETURN;
2685 static void re_execute_shell(char ***to_free, const char *s,
2686 char *g_argv0, char **g_argv,
2687 char **builtin_argv)
2689 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2690 char *heredoc_argv[4];
2691 struct variable *cur;
2692 # if ENABLE_HUSH_FUNCTIONS
2693 struct function *funcp;
2698 if (!g_argv0) { /* heredoc */
2699 argv = heredoc_argv;
2700 argv[0] = (char *) G.argv0_for_re_execing;
2701 argv[1] = (char *) "-<";
2702 argv[2] = (char *) s;
2704 pp = &argv[3]; /* used as pointer to empty environment */
2710 if (pp) while (*pp++)
2713 sprintf(param_buf, "-$%x:%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2714 , (unsigned) G.root_pid
2715 , (unsigned) G.root_ppid
2716 , (unsigned) G.last_bg_pid
2717 , (unsigned) G.last_exitcode
2719 IF_HUSH_LOOPS(, G.depth_of_loop)
2721 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2722 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2725 for (cur = G.top_var; cur; cur = cur->next) {
2726 if (!cur->flg_export || cur->flg_read_only)
2729 # if ENABLE_HUSH_FUNCTIONS
2730 for (funcp = G.top_func; funcp; funcp = funcp->next)
2736 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2737 *pp++ = (char *) G.argv0_for_re_execing;
2739 for (cur = G.top_var; cur; cur = cur->next) {
2740 if (cur->varstr == hush_version_str)
2742 if (cur->flg_read_only) {
2743 *pp++ = (char *) "-R";
2744 *pp++ = cur->varstr;
2745 } else if (!cur->flg_export) {
2746 *pp++ = (char *) "-V";
2747 *pp++ = cur->varstr;
2750 # if ENABLE_HUSH_FUNCTIONS
2751 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2752 *pp++ = (char *) "-F";
2753 *pp++ = funcp->name;
2754 *pp++ = funcp->body_as_string;
2757 /* We can pass activated traps here. Say, -Tnn:trap_string
2759 * However, POSIX says that subshells reset signals with traps
2761 * I tested bash-3.2 and it not only does that with true subshells
2762 * of the form ( list ), but with any forked children shells.
2763 * I set trap "echo W" WINCH; and then tried:
2765 * { echo 1; sleep 20; echo 2; } &
2766 * while true; do echo 1; sleep 20; echo 2; break; done &
2767 * true | { echo 1; sleep 20; echo 2; } | cat
2769 * In all these cases sending SIGWINCH to the child shell
2770 * did not run the trap. If I add trap "echo V" WINCH;
2771 * _inside_ group (just before echo 1), it works.
2773 * I conclude it means we don't need to pass active traps here.
2774 * exec syscall below resets them to SIG_DFL for us.
2776 *pp++ = (char *) "-c";
2779 while (*++builtin_argv)
2780 *pp++ = *builtin_argv;
2781 *pp++ = (char *) "";
2786 /* *pp = NULL; - is already there */
2790 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2791 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2792 execve(bb_busybox_exec_path, argv, pp);
2793 /* Fallback. Useful for init=/bin/hush usage etc */
2794 if (argv[0][0] == '/')
2795 execve(argv[0], argv, pp);
2796 xfunc_error_retval = 127;
2797 bb_error_msg_and_die("can't re-execute the shell");
2799 #endif /* !BB_MMU */
2802 static void setup_heredoc(struct redir_struct *redir)
2804 struct fd_pair pair;
2807 /* the _body_ of heredoc (misleading field name) */
2808 const char *heredoc = redir->rd_filename;
2815 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2816 expanded = expand_pseudo_dquoted(heredoc);
2820 len = strlen(heredoc);
2822 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2824 xmove_fd(pair.rd, redir->rd_fd);
2826 /* Try writing without forking. Newer kernels have
2827 * dynamically growing pipes. Must use non-blocking write! */
2830 written = write(pair.wr, heredoc, len);
2841 ndelay_off(pair.wr);
2843 /* Okay, pipe buffer was not big enough */
2844 /* Note: we must not create a stray child (bastard? :)
2845 * for the unsuspecting parent process. Child creates a grandchild
2846 * and exits before parent execs the process which consumes heredoc
2847 * (that exec happens after we return from this function) */
2853 bb_perror_msg_and_die("vfork");
2856 disable_restore_tty_pgrp_on_exit();
2857 pid = BB_MMU ? fork() : vfork();
2859 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2863 close(redir->rd_fd); /* read side of the pipe */
2865 full_write(pair.wr, heredoc, len); /* may loop or block */
2868 /* Delegate blocking writes to another process */
2869 xmove_fd(pair.wr, STDOUT_FILENO);
2870 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2874 #if ENABLE_HUSH_FAST
2876 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2878 enable_restore_tty_pgrp_on_exit();
2884 wait(NULL); /* wait till child has died */
2887 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2888 * and stderr if they are redirected. */
2889 static int setup_redirects(struct command *prog, int squirrel[])
2892 struct redir_struct *redir;
2894 for (redir = prog->redirects; redir; redir = redir->next) {
2895 if (redir->rd_type == REDIRECT_HEREDOC2) {
2896 /* rd_fd<<HERE case */
2897 if (squirrel && redir->rd_fd < 3
2898 && squirrel[redir->rd_fd] < 0
2900 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2902 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2904 debug_printf_parse("set heredoc '%s'\n",
2905 redir->rd_filename);
2906 setup_heredoc(redir);
2910 if (redir->rd_dup == REDIRFD_TO_FILE) {
2911 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2913 if (redir->rd_filename == NULL) {
2914 /* Something went wrong in the parse.
2915 * Pretend it didn't happen */
2916 bb_error_msg("bug in redirect parse");
2919 mode = redir_table[redir->rd_type].mode;
2920 p = expand_string_to_string(redir->rd_filename);
2921 openfd = open_or_warn(p, mode);
2924 /* this could get lost if stderr has been redirected, but
2925 * bash and ash both lose it as well (though zsh doesn't!) */
2926 //what the above comment tries to say?
2930 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2931 openfd = redir->rd_dup;
2934 if (openfd != redir->rd_fd) {
2935 if (squirrel && redir->rd_fd < 3
2936 && squirrel[redir->rd_fd] < 0
2938 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2940 if (openfd == REDIRFD_CLOSE) {
2941 /* "n>-" means "close me" */
2942 close(redir->rd_fd);
2944 xdup2(openfd, redir->rd_fd);
2945 if (redir->rd_dup == REDIRFD_TO_FILE)
2953 static void restore_redirects(int squirrel[])
2956 for (i = 0; i < 3; i++) {
2959 /* We simply die on error */
2966 static void free_pipe_list(struct pipe *head);
2968 /* Return code is the exit status of the pipe */
2969 static void free_pipe(struct pipe *pi)
2972 struct command *command;
2973 struct redir_struct *r, *rnext;
2976 if (pi->stopped_cmds > 0) /* why? */
2978 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2979 for (i = 0; i < pi->num_cmds; i++) {
2980 command = &pi->cmds[i];
2981 debug_printf_clean(" command %d:\n", i);
2982 if (command->argv) {
2983 for (a = 0, p = command->argv; *p; a++, p++) {
2984 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2986 free_strings(command->argv);
2987 command->argv = NULL;
2989 /* not "else if": on syntax error, we may have both! */
2990 if (command->group) {
2991 debug_printf_clean(" begin group (cmd_type:%d)\n",
2993 free_pipe_list(command->group);
2994 debug_printf_clean(" end group\n");
2995 command->group = NULL;
2997 /* else is crucial here.
2998 * If group != NULL, child_func is meaningless */
2999 #if ENABLE_HUSH_FUNCTIONS
3000 else if (command->child_func) {
3001 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3002 command->child_func->parent_cmd = NULL;
3006 free(command->group_as_string);
3007 command->group_as_string = NULL;
3009 for (r = command->redirects; r; r = rnext) {
3010 debug_printf_clean(" redirect %d%s",
3011 r->rd_fd, redir_table[r->rd_type].descrip);
3012 /* guard against the case >$FOO, where foo is unset or blank */
3013 if (r->rd_filename) {
3014 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3015 free(r->rd_filename);
3016 r->rd_filename = NULL;
3018 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3022 command->redirects = NULL;
3024 free(pi->cmds); /* children are an array, they get freed all at once */
3032 static void free_pipe_list(struct pipe *head)
3034 struct pipe *pi, *next;
3036 for (pi = head; pi; pi = next) {
3038 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3041 debug_printf_clean("pipe followup code %d\n", pi->followup);
3043 /*pi->next = NULL;*/
3049 static int run_list(struct pipe *pi);
3051 #define parse_stream(pstring, input, end_trigger) \
3052 parse_stream(input, end_trigger)
3054 static struct pipe *parse_stream(char **pstring,
3055 struct in_str *input,
3057 static void parse_and_run_string(const char *s);
3060 static char *find_in_path(const char *arg)
3063 const char *PATH = get_local_var_value("PATH");
3069 const char *end = strchrnul(PATH, ':');
3070 int sz = end - PATH; /* must be int! */
3074 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3076 /* We have xxx::yyyy in $PATH,
3077 * it means "use current dir" */
3080 if (access(ret, F_OK) == 0)
3093 static const struct built_in_command* find_builtin_helper(const char *name,
3094 const struct built_in_command *x,
3095 const struct built_in_command *end)
3098 if (strcmp(name, x->cmd) != 0) {
3102 debug_printf_exec("found builtin '%s'\n", name);
3107 static const struct built_in_command* find_builtin1(const char *name)
3109 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3111 static const struct built_in_command* find_builtin(const char *name)
3113 const struct built_in_command *x = find_builtin1(name);
3116 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3119 #if ENABLE_HUSH_FUNCTIONS
3120 static struct function **find_function_slot(const char *name)
3122 struct function **funcpp = &G.top_func;
3124 if (strcmp(name, (*funcpp)->name) == 0) {
3127 funcpp = &(*funcpp)->next;
3132 static const struct function *find_function(const char *name)
3134 const struct function *funcp = *find_function_slot(name);
3136 debug_printf_exec("found function '%s'\n", name);
3140 /* Note: takes ownership on name ptr */
3141 static struct function *new_function(char *name)
3143 struct function **funcpp = find_function_slot(name);
3144 struct function *funcp = *funcpp;
3146 if (funcp != NULL) {
3147 struct command *cmd = funcp->parent_cmd;
3148 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3150 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3152 /* Note: if !funcp->body, do not free body_as_string!
3153 * This is a special case of "-F name body" function:
3154 * body_as_string was not malloced! */
3156 free_pipe_list(funcp->body);
3158 free(funcp->body_as_string);
3162 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3163 cmd->argv[0] = funcp->name;
3164 cmd->group = funcp->body;
3166 cmd->group_as_string = funcp->body_as_string;
3170 debug_printf_exec("remembering new function '%s'\n", name);
3171 funcp = *funcpp = xzalloc(sizeof(*funcp));
3172 /*funcp->next = NULL;*/
3179 static void unset_func(const char *name)
3181 struct function **funcpp = find_function_slot(name);
3182 struct function *funcp = *funcpp;
3184 if (funcp != NULL) {
3185 debug_printf_exec("freeing function '%s'\n", funcp->name);
3186 *funcpp = funcp->next;
3187 /* funcp is unlinked now, deleting it.
3188 * Note: if !funcp->body, the function was created by
3189 * "-F name body", do not free ->body_as_string
3190 * and ->name as they were not malloced. */
3192 free_pipe_list(funcp->body);
3195 free(funcp->body_as_string);
3203 #define exec_function(to_free, funcp, argv) \
3204 exec_function(funcp, argv)
3206 static void exec_function(char ***to_free,
3207 const struct function *funcp,
3208 char **argv) NORETURN;
3209 static void exec_function(char ***to_free,
3210 const struct function *funcp,
3216 argv[0] = G.global_argv[0];
3217 G.global_argv = argv;
3221 /* On MMU, funcp->body is always non-NULL */
3222 n = run_list(funcp->body);
3226 re_execute_shell(to_free,
3227 funcp->body_as_string,
3234 static int run_function(const struct function *funcp, char **argv)
3240 save_and_replace_G_args(&sv, argv);
3242 /* "we are in function, ok to use return" */
3243 sv_flg = G.flag_return_in_progress;
3244 G.flag_return_in_progress = -1;
3245 # if ENABLE_HUSH_LOCAL
3246 G.func_nest_level++;
3249 /* On MMU, funcp->body is always non-NULL */
3252 /* Function defined by -F */
3253 parse_and_run_string(funcp->body_as_string);
3254 rc = G.last_exitcode;
3258 rc = run_list(funcp->body);
3261 # if ENABLE_HUSH_LOCAL
3263 struct variable *var;
3264 struct variable **var_pp;
3266 var_pp = &G.top_var;
3267 while ((var = *var_pp) != NULL) {
3268 if (var->func_nest_level < G.func_nest_level) {
3269 var_pp = &var->next;
3273 if (var->flg_export)
3274 bb_unsetenv(var->varstr);
3275 /* Remove from global list */
3276 *var_pp = var->next;
3282 G.func_nest_level--;
3285 G.flag_return_in_progress = sv_flg;
3287 restore_G_args(&sv, argv);
3291 #endif /* ENABLE_HUSH_FUNCTIONS */
3295 #define exec_builtin(to_free, x, argv) \
3296 exec_builtin(x, argv)
3298 #define exec_builtin(to_free, x, argv) \
3299 exec_builtin(to_free, argv)
3301 static void exec_builtin(char ***to_free,
3302 const struct built_in_command *x,
3303 char **argv) NORETURN;
3304 static void exec_builtin(char ***to_free,
3305 const struct built_in_command *x,
3309 int rcode = x->function(argv);
3313 /* On NOMMU, we must never block!
3314 * Example: { sleep 99 | read line; } & echo Ok
3316 re_execute_shell(to_free,
3325 static void execvp_or_die(char **argv) NORETURN;
3326 static void execvp_or_die(char **argv)
3328 debug_printf_exec("execing '%s'\n", argv[0]);
3329 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3330 execvp(argv[0], argv);
3331 bb_perror_msg("can't execute '%s'", argv[0]);
3332 _exit(127); /* bash compat */
3336 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3337 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3338 #define pseudo_exec(nommu_save, command, argv_expanded) \
3339 pseudo_exec(command, argv_expanded)
3342 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3344 * Don't exit() here. If you don't exec, use _exit instead.
3345 * The at_exit handlers apparently confuse the calling process,
3346 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3347 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3348 char **argv, int assignment_cnt,
3349 char **argv_expanded) NORETURN;
3350 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3351 char **argv, int assignment_cnt,
3352 char **argv_expanded)
3356 /* Case when we are here: ... | var=val | ... */
3357 if (!argv[assignment_cnt])
3358 _exit(EXIT_SUCCESS);
3360 new_env = expand_assignments(argv, assignment_cnt);
3362 set_vars_and_save_old(new_env);
3363 free(new_env); /* optional */
3364 /* we can also destroy set_vars_and_save_old's return value,
3367 nommu_save->new_env = new_env;
3368 nommu_save->old_vars = set_vars_and_save_old(new_env);
3370 if (argv_expanded) {
3371 argv = argv_expanded;
3373 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3375 nommu_save->argv = argv;
3379 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3380 if (strchr(argv[0], '/') != NULL)
3384 /* Check if the command matches any of the builtins.
3385 * Depending on context, this might be redundant. But it's
3386 * easier to waste a few CPU cycles than it is to figure out
3387 * if this is one of those cases.
3390 /* On NOMMU, it is more expensive to re-execute shell
3391 * just in order to run echo or test builtin.
3392 * It's better to skip it here and run corresponding
3393 * non-builtin later. */
3394 const struct built_in_command *x;
3395 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3397 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3400 #if ENABLE_HUSH_FUNCTIONS
3401 /* Check if the command matches any functions */
3403 const struct function *funcp = find_function(argv[0]);
3405 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3410 #if ENABLE_FEATURE_SH_STANDALONE
3411 /* Check if the command matches any busybox applets */
3413 int a = find_applet_by_name(argv[0]);
3415 # if BB_MMU /* see above why on NOMMU it is not allowed */
3416 if (APPLET_IS_NOEXEC(a)) {
3417 debug_printf_exec("running applet '%s'\n", argv[0]);
3418 run_applet_no_and_exit(a, argv);
3421 /* Re-exec ourselves */
3422 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3423 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3424 execv(bb_busybox_exec_path, argv);
3425 /* If they called chroot or otherwise made the binary no longer
3426 * executable, fall through */
3431 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3434 execvp_or_die(argv);
3437 /* Called after [v]fork() in run_pipe
3439 static void pseudo_exec(nommu_save_t *nommu_save,
3440 struct command *command,
3441 char **argv_expanded) NORETURN;
3442 static void pseudo_exec(nommu_save_t *nommu_save,
3443 struct command *command,
3444 char **argv_expanded)
3446 if (command->argv) {
3447 pseudo_exec_argv(nommu_save, command->argv,
3448 command->assignment_cnt, argv_expanded);
3451 if (command->group) {
3452 /* Cases when we are here:
3455 * ... | ( list ) | ...
3456 * ... | { list } | ...
3460 debug_printf_exec("pseudo_exec: run_list\n");
3461 reset_traps_to_defaults();
3462 rcode = run_list(command->group);
3463 /* OK to leak memory by not calling free_pipe_list,
3464 * since this process is about to exit */
3467 re_execute_shell(&nommu_save->argv_from_re_execing,
3468 command->group_as_string,
3475 /* Case when we are here: ... | >file */
3476 debug_printf_exec("pseudo_exec'ed null command\n");
3477 _exit(EXIT_SUCCESS);
3481 static const char *get_cmdtext(struct pipe *pi)
3487 /* This is subtle. ->cmdtext is created only on first backgrounding.
3488 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3489 * On subsequent bg argv is trashed, but we won't use it */
3492 argv = pi->cmds[0].argv;
3493 if (!argv || !argv[0]) {
3494 pi->cmdtext = xzalloc(1);
3500 len += strlen(*argv) + 1;
3504 argv = pi->cmds[0].argv;
3506 len = strlen(*argv);
3507 memcpy(p, *argv, len);
3515 static void insert_bg_job(struct pipe *pi)
3517 struct pipe *job, **jobp;
3520 /* Linear search for the ID of the job to use */
3522 for (job = G.job_list; job; job = job->next)
3523 if (job->jobid >= pi->jobid)
3524 pi->jobid = job->jobid + 1;
3526 /* Add job to the list of running jobs */
3528 while ((job = *jobp) != NULL)
3530 job = *jobp = xmalloc(sizeof(*job));
3532 *job = *pi; /* physical copy */
3534 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3535 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3536 for (i = 0; i < pi->num_cmds; i++) {
3537 job->cmds[i].pid = pi->cmds[i].pid;
3538 /* all other fields are not used and stay zero */
3540 job->cmdtext = xstrdup(get_cmdtext(pi));
3542 if (G_interactive_fd)
3543 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3544 /* Last command's pid goes to $! */
3545 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3546 G.last_jobid = job->jobid;
3549 static void remove_bg_job(struct pipe *pi)
3551 struct pipe *prev_pipe;
3553 if (pi == G.job_list) {
3554 G.job_list = pi->next;
3556 prev_pipe = G.job_list;
3557 while (prev_pipe->next != pi)
3558 prev_pipe = prev_pipe->next;
3559 prev_pipe->next = pi->next;
3562 G.last_jobid = G.job_list->jobid;
3567 /* Remove a backgrounded job */
3568 static void delete_finished_bg_job(struct pipe *pi)
3571 pi->stopped_cmds = 0;
3577 /* Check to see if any processes have exited -- if they
3578 * have, figure out why and see if a job has completed */
3579 static int checkjobs(struct pipe* fg_pipe)
3589 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3591 attributes = WUNTRACED;
3592 if (fg_pipe == NULL)
3593 attributes |= WNOHANG;
3596 #if ENABLE_HUSH_FAST
3597 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3598 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3599 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3600 /* There was neither fork nor SIGCHLD since last waitpid */
3601 /* Avoid doing waitpid syscall if possible */
3602 if (!G.we_have_children) {
3606 if (fg_pipe == NULL) { /* is WNOHANG set? */
3607 /* We have children, but they did not exit
3608 * or stop yet (we saw no SIGCHLD) */
3611 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3615 /* Do we do this right?
3616 * bash-3.00# sleep 20 | false
3618 * [3]+ Stopped sleep 20 | false
3619 * bash-3.00# echo $?
3620 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3621 * [hush 1.14.0: yes we do it right]
3628 #if ENABLE_HUSH_FAST
3629 i = G.count_SIGCHLD;
3631 childpid = waitpid(-1, &status, attributes);
3632 if (childpid <= 0) {
3633 if (childpid && errno != ECHILD)
3634 bb_perror_msg("waitpid");
3635 #if ENABLE_HUSH_FAST
3636 else { /* Until next SIGCHLD, waitpid's are useless */
3637 G.we_have_children = (childpid == 0);
3638 G.handled_SIGCHLD = i;
3639 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3644 dead = WIFEXITED(status) || WIFSIGNALED(status);
3647 if (WIFSTOPPED(status))
3648 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3649 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3650 if (WIFSIGNALED(status))
3651 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3652 childpid, WTERMSIG(status), WEXITSTATUS(status));
3653 if (WIFEXITED(status))
3654 debug_printf_jobs("pid %d exited, exitcode %d\n",
3655 childpid, WEXITSTATUS(status));
3657 /* Were we asked to wait for fg pipe? */
3659 for (i = 0; i < fg_pipe->num_cmds; i++) {
3660 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3661 if (fg_pipe->cmds[i].pid != childpid)
3664 fg_pipe->cmds[i].pid = 0;
3665 fg_pipe->alive_cmds--;
3666 if (i == fg_pipe->num_cmds - 1) {
3667 /* last process gives overall exitstatus */
3668 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3669 rcode = WEXITSTATUS(status);
3670 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3671 /* bash prints killer signal's name for *last*
3672 * process in pipe (prints just newline for SIGINT).
3673 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
3675 if (WIFSIGNALED(status)) {
3676 int sig = WTERMSIG(status);
3677 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3681 fg_pipe->cmds[i].is_stopped = 1;
3682 fg_pipe->stopped_cmds++;
3684 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3685 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3686 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3687 /* All processes in fg pipe have exited or stopped */
3688 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3689 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3690 * and "killall -STOP cat" */
3691 if (G_interactive_fd) {
3693 if (fg_pipe->alive_cmds)
3694 insert_bg_job(fg_pipe);
3698 if (!fg_pipe->alive_cmds)
3701 /* There are still running processes in the fg pipe */
3702 goto wait_more; /* do waitpid again */
3704 /* it wasnt fg_pipe, look for process in bg pipes */
3708 /* We asked to wait for bg or orphaned children */
3709 /* No need to remember exitcode in this case */
3710 for (pi = G.job_list; pi; pi = pi->next) {
3711 for (i = 0; i < pi->num_cmds; i++) {
3712 if (pi->cmds[i].pid == childpid)
3713 goto found_pi_and_prognum;
3716 /* Happens when shell is used as init process (init=/bin/sh) */
3717 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3718 continue; /* do waitpid again */
3720 found_pi_and_prognum:
3723 pi->cmds[i].pid = 0;
3725 if (!pi->alive_cmds) {
3726 if (G_interactive_fd)
3727 printf(JOB_STATUS_FORMAT, pi->jobid,
3728 "Done", pi->cmdtext);
3729 delete_finished_bg_job(pi);
3733 pi->cmds[i].is_stopped = 1;
3737 } /* while (waitpid succeeds)... */
3743 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3746 int rcode = checkjobs(fg_pipe);
3747 if (G_saved_tty_pgrp) {
3748 /* Job finished, move the shell to the foreground */
3749 p = getpgrp(); /* our process group id */
3750 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3751 tcsetpgrp(G_interactive_fd, p);
3757 /* Start all the jobs, but don't wait for anything to finish.
3760 * Return code is normally -1, when the caller has to wait for children
3761 * to finish to determine the exit status of the pipe. If the pipe
3762 * is a simple builtin command, however, the action is done by the
3763 * time run_pipe returns, and the exit code is provided as the
3766 * Returns -1 only if started some children. IOW: we have to
3767 * mask out retvals of builtins etc with 0xff!
3769 * The only case when we do not need to [v]fork is when the pipe
3770 * is single, non-backgrounded, non-subshell command. Examples:
3771 * cmd ; ... { list } ; ...
3772 * cmd && ... { list } && ...
3773 * cmd || ... { list } || ...
3774 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3775 * or (if SH_STANDALONE) an applet, and we can run the { list }
3776 * with run_list. If it isn't one of these, we fork and exec cmd.
3778 * Cases when we must fork:
3779 * non-single: cmd | cmd
3780 * backgrounded: cmd & { list } &
3781 * subshell: ( list ) [&]
3783 static NOINLINE int run_pipe(struct pipe *pi)
3785 static const char *const null_ptr = NULL;
3788 struct command *command;
3789 char **argv_expanded;
3792 /* it is not always needed, but we aim to smaller code */
3793 int squirrel[] = { -1, -1, -1 };
3796 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3799 IF_HUSH_JOB(pi->pgrp = -1;)
3800 pi->stopped_cmds = 0;
3801 command = &(pi->cmds[0]);
3802 argv_expanded = NULL;
3804 if (pi->num_cmds != 1
3805 || pi->followup == PIPE_BG
3806 || command->cmd_type == CMD_SUBSHELL
3813 debug_printf_exec(": group:%p argv:'%s'\n",
3814 command->group, command->argv ? command->argv[0] : "NONE");
3816 if (command->group) {
3817 #if ENABLE_HUSH_FUNCTIONS
3818 if (command->cmd_type == CMD_FUNCDEF) {
3819 /* "executing" func () { list } */
3820 struct function *funcp;
3822 funcp = new_function(command->argv[0]);
3823 /* funcp->name is already set to argv[0] */
3824 funcp->body = command->group;
3826 funcp->body_as_string = command->group_as_string;
3827 command->group_as_string = NULL;
3829 command->group = NULL;
3830 command->argv[0] = NULL;
3831 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3832 funcp->parent_cmd = command;
3833 command->child_func = funcp;
3835 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3837 return EXIT_SUCCESS;
3841 debug_printf("non-subshell group\n");
3842 rcode = 1; /* exitcode if redir failed */
3843 if (setup_redirects(command, squirrel) == 0) {
3844 debug_printf_exec(": run_list\n");
3845 rcode = run_list(command->group) & 0xff;
3847 restore_redirects(squirrel);
3848 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3850 debug_printf_exec("run_pipe: return %d\n", rcode);
3854 argv = command->argv ? command->argv : (char **) &null_ptr;
3856 const struct built_in_command *x;
3857 #if ENABLE_HUSH_FUNCTIONS
3858 const struct function *funcp;
3862 char **new_env = NULL;
3863 struct variable *old_vars = NULL;
3865 if (argv[command->assignment_cnt] == NULL) {
3866 /* Assignments, but no command */
3867 /* Ensure redirects take effect. Try "a=t >file" */
3868 rcode = setup_redirects(command, squirrel);
3869 restore_redirects(squirrel);
3870 /* Set shell variables */
3872 p = expand_string_to_string(*argv);
3873 debug_printf_exec("set shell var:'%s'->'%s'\n",
3875 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3878 /* Do we need to flag set_local_var() errors?
3879 * "assignment to readonly var" and "putenv error"
3881 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3883 debug_printf_exec("run_pipe: return %d\n", rcode);
3887 /* Expand the rest into (possibly) many strings each */
3889 #if ENABLE_HUSH_BASH_COMPAT
3890 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3891 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3894 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3895 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3896 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3901 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3904 /* if someone gives us an empty string: `cmd with empty output` */
3905 if (!argv_expanded[0]) {
3910 x = find_builtin(argv_expanded[0]);
3911 #if ENABLE_HUSH_FUNCTIONS
3914 funcp = find_function(argv_expanded[0]);
3918 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3919 debug_printf("exec with redirects only\n");
3920 rcode = setup_redirects(command, NULL);
3921 goto clean_up_and_ret1;
3924 /* setup_redirects acts on file descriptors, not FILEs.
3925 * This is perfect for work that comes after exec().
3926 * Is it really safe for inline use? Experimentally,
3927 * things seem to work. */
3928 rcode = setup_redirects(command, squirrel);
3930 new_env = expand_assignments(argv, command->assignment_cnt);
3931 old_vars = set_vars_and_save_old(new_env);
3933 debug_printf_exec(": builtin '%s' '%s'...\n",
3934 x->cmd, argv_expanded[1]);
3935 rcode = x->function(argv_expanded) & 0xff;
3938 #if ENABLE_HUSH_FUNCTIONS
3940 # if ENABLE_HUSH_LOCAL
3941 struct variable **sv;
3942 sv = G.shadowed_vars_pp;
3943 G.shadowed_vars_pp = &old_vars;
3945 debug_printf_exec(": function '%s' '%s'...\n",
3946 funcp->name, argv_expanded[1]);
3947 rcode = run_function(funcp, argv_expanded) & 0xff;
3948 # if ENABLE_HUSH_LOCAL
3949 G.shadowed_vars_pp = sv;
3954 #if ENABLE_FEATURE_SH_STANDALONE
3957 restore_redirects(squirrel);
3958 unset_vars(new_env);
3961 free(argv_expanded);
3962 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3964 debug_printf_exec("run_pipe return %d\n", rcode);
3968 #if ENABLE_FEATURE_SH_STANDALONE
3969 i = find_applet_by_name(argv_expanded[0]);
3970 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3971 rcode = setup_redirects(command, squirrel);
3973 new_env = expand_assignments(argv, command->assignment_cnt);
3974 old_vars = set_vars_and_save_old(new_env);
3975 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3976 argv_expanded[0], argv_expanded[1]);
3977 rcode = run_nofork_applet(i, argv_expanded);
3979 goto clean_up_and_ret;
3982 /* It is neither builtin nor applet. We must fork. */
3986 /* NB: argv_expanded may already be created, and that
3987 * might include `cmd` runs! Do not rerun it! We *must*
3988 * use argv_expanded if it's non-NULL */
3990 /* Going to fork a child per each pipe member */
3994 for (i = 0; i < pi->num_cmds; i++) {
3995 struct fd_pair pipefds;
3997 volatile nommu_save_t nommu_save;
3998 nommu_save.new_env = NULL;
3999 nommu_save.old_vars = NULL;
4000 nommu_save.argv = NULL;
4001 nommu_save.argv_from_re_execing = NULL;
4003 command = &(pi->cmds[i]);
4004 if (command->argv) {
4005 debug_printf_exec(": pipe member '%s' '%s'...\n",
4006 command->argv[0], command->argv[1]);
4008 debug_printf_exec(": pipe member with no argv\n");
4011 /* pipes are inserted between pairs of commands */
4014 if ((i + 1) < pi->num_cmds)
4015 xpiped_pair(pipefds);
4017 command->pid = BB_MMU ? fork() : vfork();
4018 if (!command->pid) { /* child */
4020 disable_restore_tty_pgrp_on_exit();
4021 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4023 /* Every child adds itself to new process group
4024 * with pgid == pid_of_first_child_in_pipe */
4025 if (G.run_list_level == 1 && G_interactive_fd) {
4028 if (pgrp < 0) /* true for 1st process only */
4030 if (setpgid(0, pgrp) == 0
4031 && pi->followup != PIPE_BG
4032 && G_saved_tty_pgrp /* we have ctty */
4034 /* We do it in *every* child, not just first,
4036 tcsetpgrp(G_interactive_fd, pgrp);
4040 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4041 /* 1st cmd in backgrounded pipe
4042 * should have its stdin /dev/null'ed */
4044 if (open(bb_dev_null, O_RDONLY))
4045 xopen("/", O_RDONLY);
4047 xmove_fd(nextin, 0);
4049 xmove_fd(pipefds.wr, 1);
4052 /* Like bash, explicit redirects override pipes,
4053 * and the pipe fd is available for dup'ing. */
4054 if (setup_redirects(command, NULL))
4057 /* Restore default handlers just prior to exec */
4058 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4060 /* Stores to nommu_save list of env vars putenv'ed
4061 * (NOMMU, on MMU we don't need that) */
4062 /* cast away volatility... */
4063 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4064 /* pseudo_exec() does not return */
4067 /* parent or error */
4068 #if ENABLE_HUSH_FAST
4070 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4072 enable_restore_tty_pgrp_on_exit();
4074 /* Clean up after vforked child */
4075 free(nommu_save.argv);
4076 free(nommu_save.argv_from_re_execing);
4077 unset_vars(nommu_save.new_env);
4078 add_vars(nommu_save.old_vars);
4080 free(argv_expanded);
4081 argv_expanded = NULL;
4082 if (command->pid < 0) { /* [v]fork failed */
4083 /* Clearly indicate, was it fork or vfork */
4084 bb_perror_msg(BB_MMU ? "fork" : "vfork");
4088 /* Second and next children need to know pid of first one */
4090 pi->pgrp = command->pid;
4096 if ((i + 1) < pi->num_cmds)
4098 /* Pass read (output) pipe end to next iteration */
4099 nextin = pipefds.rd;
4102 if (!pi->alive_cmds) {
4104 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4109 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4113 #ifndef debug_print_tree
4114 static void debug_print_tree(struct pipe *pi, int lvl)
4116 static const char *const PIPE[] = {
4122 static const char *RES[] = {
4123 [RES_NONE ] = "NONE" ,
4126 [RES_THEN ] = "THEN" ,
4127 [RES_ELIF ] = "ELIF" ,
4128 [RES_ELSE ] = "ELSE" ,
4131 # if ENABLE_HUSH_LOOPS
4132 [RES_FOR ] = "FOR" ,
4133 [RES_WHILE] = "WHILE",
4134 [RES_UNTIL] = "UNTIL",
4136 [RES_DONE ] = "DONE" ,
4138 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4141 # if ENABLE_HUSH_CASE
4142 [RES_CASE ] = "CASE" ,
4143 [RES_CASE_IN ] = "CASE_IN" ,
4144 [RES_MATCH] = "MATCH",
4145 [RES_CASE_BODY] = "CASE_BODY",
4146 [RES_ESAC ] = "ESAC" ,
4148 [RES_XXXX ] = "XXXX" ,
4149 [RES_SNTX ] = "SNTX" ,
4151 static const char *const CMDTYPE[] = {
4155 # if ENABLE_HUSH_FUNCTIONS
4164 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4165 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4167 while (prn < pi->num_cmds) {
4168 struct command *command = &pi->cmds[prn];
4169 char **argv = command->argv;
4171 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4173 command->assignment_cnt);
4174 if (command->group) {
4175 fprintf(stderr, " group %s: (argv=%p)\n",
4176 CMDTYPE[command->cmd_type],
4178 debug_print_tree(command->group, lvl+1);
4182 if (argv) while (*argv) {
4183 fprintf(stderr, " '%s'", *argv);
4186 fprintf(stderr, "\n");
4193 #endif /* debug_print_tree */
4195 /* NB: called by pseudo_exec, and therefore must not modify any
4196 * global data until exec/_exit (we can be a child after vfork!) */
4197 static int run_list(struct pipe *pi)
4199 #if ENABLE_HUSH_CASE
4200 char *case_word = NULL;
4202 #if ENABLE_HUSH_LOOPS
4203 struct pipe *loop_top = NULL;
4204 char **for_lcur = NULL;
4205 char **for_list = NULL;
4207 smallint last_followup;
4209 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4210 smalluint cond_code = 0;
4212 enum { cond_code = 0 };
4215 smallint rword; /* enum reserved_style */
4216 smallint last_rword; /* ditto */
4219 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4222 #if ENABLE_HUSH_LOOPS
4223 /* Check syntax for "for" */
4224 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4225 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4227 /* current word is FOR or IN (BOLD in comments below) */
4228 if (cpipe->next == NULL) {
4229 syntax_error("malformed for");
4231 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4234 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4235 if (cpipe->next->res_word == RES_DO)
4237 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4238 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4239 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4241 syntax_error("malformed for");
4243 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4249 /* Past this point, all code paths should jump to ret: label
4250 * in order to return, no direct "return" statements please.
4251 * This helps to ensure that no memory is leaked. */
4259 last_rword = RES_XXXX;
4261 last_followup = PIPE_SEQ;
4262 rcode = G.last_exitcode;
4264 /* Go through list of pipes, (maybe) executing them. */
4265 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4269 IF_HAS_KEYWORDS(rword = pi->res_word;)
4270 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4271 rword, cond_code, last_rword);
4272 #if ENABLE_HUSH_LOOPS
4273 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4274 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4276 /* start of a loop: remember where loop starts */
4281 /* Still in the same "if...", "then..." or "do..." branch? */
4282 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4283 if ((rcode == 0 && last_followup == PIPE_OR)
4284 || (rcode != 0 && last_followup == PIPE_AND)
4286 /* It is "<true> || CMD" or "<false> && CMD"
4287 * and we should not execute CMD */
4288 debug_printf_exec("skipped cmd because of || or &&\n");
4289 last_followup = pi->followup;
4293 last_followup = pi->followup;
4294 IF_HAS_KEYWORDS(last_rword = rword;)
4297 if (rword == RES_THEN) {
4298 /* if false; then ... fi has exitcode 0! */
4299 G.last_exitcode = rcode = EXIT_SUCCESS;
4300 /* "if <false> THEN cmd": skip cmd */
4304 if (rword == RES_ELSE || rword == RES_ELIF) {
4305 /* "if <true> then ... ELSE/ELIF cmd":
4306 * skip cmd and all following ones */
4311 #if ENABLE_HUSH_LOOPS
4312 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4314 /* first loop through for */
4316 static const char encoded_dollar_at[] ALIGN1 = {
4317 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4318 }; /* encoded representation of "$@" */
4319 static const char *const encoded_dollar_at_argv[] = {
4320 encoded_dollar_at, NULL
4321 }; /* argv list with one element: "$@" */
4324 vals = (char**)encoded_dollar_at_argv;
4325 if (pi->next->res_word == RES_IN) {
4326 /* if no variable values after "in" we skip "for" */
4327 if (!pi->next->cmds[0].argv) {
4328 G.last_exitcode = rcode = EXIT_SUCCESS;
4329 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4332 vals = pi->next->cmds[0].argv;
4333 } /* else: "for var; do..." -> assume "$@" list */
4334 /* create list of variable values */
4335 debug_print_strings("for_list made from", vals);
4336 for_list = expand_strvec_to_strvec(vals);
4337 for_lcur = for_list;
4338 debug_print_strings("for_list", for_list);
4341 /* "for" loop is over, clean up */
4347 /* Insert next value from for_lcur */
4348 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4349 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4352 if (rword == RES_IN) {
4353 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4355 if (rword == RES_DONE) {
4356 continue; /* "done" has no cmds too */
4359 #if ENABLE_HUSH_CASE
4360 if (rword == RES_CASE) {
4361 case_word = expand_strvec_to_string(pi->cmds->argv);
4364 if (rword == RES_MATCH) {
4367 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4369 /* all prev words didn't match, does this one match? */
4370 argv = pi->cmds->argv;
4372 char *pattern = expand_string_to_string(*argv);
4373 /* TODO: which FNM_xxx flags to use? */
4374 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4376 if (cond_code == 0) { /* match! we will execute this branch */
4377 free(case_word); /* make future "word)" stop */
4385 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4387 continue; /* not matched yet, skip this pipe */
4390 /* Just pressing <enter> in shell should check for jobs.
4391 * OTOH, in non-interactive shell this is useless
4392 * and only leads to extra job checks */
4393 if (pi->num_cmds == 0) {
4394 if (G_interactive_fd)
4395 goto check_jobs_and_continue;
4399 /* After analyzing all keywords and conditions, we decided
4400 * to execute this pipe. NB: have to do checkjobs(NULL)
4401 * after run_pipe to collect any background children,
4402 * even if list execution is to be stopped. */
4403 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4406 #if ENABLE_HUSH_LOOPS
4407 G.flag_break_continue = 0;
4409 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4411 /* We ran a builtin, function, or group.
4412 * rcode is already known
4413 * and we don't need to wait for anything. */
4414 G.last_exitcode = rcode;
4415 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4416 check_and_run_traps(0);
4417 #if ENABLE_HUSH_LOOPS
4418 /* Was it "break" or "continue"? */
4419 if (G.flag_break_continue) {
4420 smallint fbc = G.flag_break_continue;
4421 /* We might fall into outer *loop*,
4422 * don't want to break it too */
4424 G.depth_break_continue--;
4425 if (G.depth_break_continue == 0)
4426 G.flag_break_continue = 0;
4427 /* else: e.g. "continue 2" should *break* once, *then* continue */
4428 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4429 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4430 goto check_jobs_and_break;
4431 /* "continue": simulate end of loop */
4436 #if ENABLE_HUSH_FUNCTIONS
4437 if (G.flag_return_in_progress == 1) {
4438 /* same as "goto check_jobs_and_break" */
4443 } else if (pi->followup == PIPE_BG) {
4444 /* What does bash do with attempts to background builtins? */
4445 /* even bash 3.2 doesn't do that well with nested bg:
4446 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4447 * I'm NOT treating inner &'s as jobs */
4448 check_and_run_traps(0);
4450 if (G.run_list_level == 1)
4453 G.last_exitcode = rcode = EXIT_SUCCESS;
4454 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4457 if (G.run_list_level == 1 && G_interactive_fd) {
4458 /* Waits for completion, then fg's main shell */
4459 rcode = checkjobs_and_fg_shell(pi);
4460 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4461 check_and_run_traps(0);
4464 { /* This one just waits for completion */
4465 rcode = checkjobs(pi);
4466 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4467 check_and_run_traps(0);
4469 G.last_exitcode = rcode;
4473 /* Analyze how result affects subsequent commands */
4475 if (rword == RES_IF || rword == RES_ELIF)
4478 #if ENABLE_HUSH_LOOPS
4479 /* Beware of "while false; true; do ..."! */
4480 if (pi->next && pi->next->res_word == RES_DO) {
4481 if (rword == RES_WHILE) {
4483 /* "while false; do...done" - exitcode 0 */
4484 G.last_exitcode = rcode = EXIT_SUCCESS;
4485 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4486 goto check_jobs_and_break;
4489 if (rword == RES_UNTIL) {
4491 debug_printf_exec(": until expr is true: breaking\n");
4492 check_jobs_and_break:
4500 check_jobs_and_continue:
4507 #if ENABLE_HUSH_LOOPS
4512 #if ENABLE_HUSH_CASE
4516 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4520 /* Select which version we will use */
4521 static int run_and_free_list(struct pipe *pi)
4524 debug_printf_exec("run_and_free_list entered\n");
4526 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4527 rcode = run_list(pi);
4529 /* free_pipe_list has the side effect of clearing memory.
4530 * In the long run that function can be merged with run_list,
4531 * but doing that now would hobble the debugging effort. */
4533 debug_printf_exec("run_and_free_list return %d\n", rcode);
4538 static struct pipe *new_pipe(void)
4541 pi = xzalloc(sizeof(struct pipe));
4542 /*pi->followup = 0; - deliberately invalid value */
4543 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4547 /* Command (member of a pipe) is complete, or we start a new pipe
4548 * if ctx->command is NULL.
4549 * No errors possible here.
4551 static int done_command(struct parse_context *ctx)
4553 /* The command is really already in the pipe structure, so
4554 * advance the pipe counter and make a new, null command. */
4555 struct pipe *pi = ctx->pipe;
4556 struct command *command = ctx->command;
4559 if (IS_NULL_CMD(command)) {
4560 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4564 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4565 //debug_print_tree(ctx->list_head, 20);
4567 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4570 /* Only real trickiness here is that the uncommitted
4571 * command structure is not counted in pi->num_cmds. */
4572 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4573 ctx->command = command = &pi->cmds[pi->num_cmds];
4575 memset(command, 0, sizeof(*command));
4576 return pi->num_cmds; /* used only for 0/nonzero check */
4579 static void done_pipe(struct parse_context *ctx, pipe_style type)
4583 debug_printf_parse("done_pipe entered, followup %d\n", type);
4584 /* Close previous command */
4585 not_null = done_command(ctx);
4586 ctx->pipe->followup = type;
4588 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4589 ctx->ctx_inverted = 0;
4590 ctx->pipe->res_word = ctx->ctx_res_w;
4593 /* Without this check, even just <enter> on command line generates
4594 * tree of three NOPs (!). Which is harmless but annoying.
4595 * IOW: it is safe to do it unconditionally. */
4598 || ctx->ctx_res_w == RES_FI
4600 #if ENABLE_HUSH_LOOPS
4601 || ctx->ctx_res_w == RES_DONE
4602 || ctx->ctx_res_w == RES_FOR
4603 || ctx->ctx_res_w == RES_IN
4605 #if ENABLE_HUSH_CASE
4606 || ctx->ctx_res_w == RES_ESAC
4610 debug_printf_parse("done_pipe: adding new pipe: "
4611 "not_null:%d ctx->ctx_res_w:%d\n",
4612 not_null, ctx->ctx_res_w);
4614 ctx->pipe->next = new_p;
4616 /* RES_THEN, RES_DO etc are "sticky" -
4617 * they remain set for pipes inside if/while.
4618 * This is used to control execution.
4619 * RES_FOR and RES_IN are NOT sticky (needed to support
4620 * cases where variable or value happens to match a keyword):
4622 #if ENABLE_HUSH_LOOPS
4623 if (ctx->ctx_res_w == RES_FOR
4624 || ctx->ctx_res_w == RES_IN)
4625 ctx->ctx_res_w = RES_NONE;
4627 #if ENABLE_HUSH_CASE
4628 if (ctx->ctx_res_w == RES_MATCH)
4629 ctx->ctx_res_w = RES_CASE_BODY;
4630 if (ctx->ctx_res_w == RES_CASE)
4631 ctx->ctx_res_w = RES_CASE_IN;
4633 ctx->command = NULL; /* trick done_command below */
4634 /* Create the memory for command, roughly:
4635 * ctx->pipe->cmds = new struct command;
4636 * ctx->command = &ctx->pipe->cmds[0];
4639 //debug_print_tree(ctx->list_head, 10);
4641 debug_printf_parse("done_pipe return\n");
4644 static void initialize_context(struct parse_context *ctx)
4646 memset(ctx, 0, sizeof(*ctx));
4647 ctx->pipe = ctx->list_head = new_pipe();
4648 /* Create the memory for command, roughly:
4649 * ctx->pipe->cmds = new struct command;
4650 * ctx->command = &ctx->pipe->cmds[0];
4655 /* If a reserved word is found and processed, parse context is modified
4656 * and 1 is returned.
4659 struct reserved_combo {
4662 unsigned char assignment_flag;
4666 FLAG_END = (1 << RES_NONE ),
4668 FLAG_IF = (1 << RES_IF ),
4669 FLAG_THEN = (1 << RES_THEN ),
4670 FLAG_ELIF = (1 << RES_ELIF ),
4671 FLAG_ELSE = (1 << RES_ELSE ),
4672 FLAG_FI = (1 << RES_FI ),
4674 # if ENABLE_HUSH_LOOPS
4675 FLAG_FOR = (1 << RES_FOR ),
4676 FLAG_WHILE = (1 << RES_WHILE),
4677 FLAG_UNTIL = (1 << RES_UNTIL),
4678 FLAG_DO = (1 << RES_DO ),
4679 FLAG_DONE = (1 << RES_DONE ),
4680 FLAG_IN = (1 << RES_IN ),
4682 # if ENABLE_HUSH_CASE
4683 FLAG_MATCH = (1 << RES_MATCH),
4684 FLAG_ESAC = (1 << RES_ESAC ),
4686 FLAG_START = (1 << RES_XXXX ),
4689 static const struct reserved_combo* match_reserved_word(o_string *word)
4691 /* Mostly a list of accepted follow-up reserved words.
4692 * FLAG_END means we are done with the sequence, and are ready
4693 * to turn the compound list into a command.
4694 * FLAG_START means the word must start a new compound list.
4696 static const struct reserved_combo reserved_list[] = {
4698 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4699 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4700 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4701 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4702 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4703 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4705 # if ENABLE_HUSH_LOOPS
4706 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4707 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4708 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4709 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4710 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4711 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4713 # if ENABLE_HUSH_CASE
4714 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4715 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4718 const struct reserved_combo *r;
4720 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4721 if (strcmp(word->data, r->literal) == 0)
4726 /* Return 0: not a keyword, 1: keyword
4728 static int reserved_word(o_string *word, struct parse_context *ctx)
4730 # if ENABLE_HUSH_CASE
4731 static const struct reserved_combo reserved_match = {
4732 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4735 const struct reserved_combo *r;
4739 r = match_reserved_word(word);
4743 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4744 # if ENABLE_HUSH_CASE
4745 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4746 /* "case word IN ..." - IN part starts first MATCH part */
4747 r = &reserved_match;
4750 if (r->flag == 0) { /* '!' */
4751 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4752 syntax_error("! ! command");
4753 ctx->ctx_res_w = RES_SNTX;
4755 ctx->ctx_inverted = 1;
4758 if (r->flag & FLAG_START) {
4759 struct parse_context *old;
4761 old = xmalloc(sizeof(*old));
4762 debug_printf_parse("push stack %p\n", old);
4763 *old = *ctx; /* physical copy */
4764 initialize_context(ctx);
4766 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4767 syntax_error_at(word->data);
4768 ctx->ctx_res_w = RES_SNTX;
4771 /* "{...} fi" is ok. "{...} if" is not
4773 * if { echo foo; } then { echo bar; } fi */
4774 if (ctx->command->group)
4775 done_pipe(ctx, PIPE_SEQ);
4778 ctx->ctx_res_w = r->res;
4779 ctx->old_flag = r->flag;
4780 word->o_assignment = r->assignment_flag;
4782 if (ctx->old_flag & FLAG_END) {
4783 struct parse_context *old;
4785 done_pipe(ctx, PIPE_SEQ);
4786 debug_printf_parse("pop stack %p\n", ctx->stack);
4788 old->command->group = ctx->list_head;
4789 old->command->cmd_type = CMD_NORMAL;
4791 o_addstr(&old->as_string, ctx->as_string.data);
4792 o_free_unsafe(&ctx->as_string);
4793 old->command->group_as_string = xstrdup(old->as_string.data);
4794 debug_printf_parse("pop, remembering as:'%s'\n",
4795 old->command->group_as_string);
4797 *ctx = *old; /* physical copy */
4802 #endif /* HAS_KEYWORDS */
4804 /* Word is complete, look at it and update parsing context.
4805 * Normal return is 0. Syntax errors return 1.
4806 * Note: on return, word is reset, but not o_free'd!
4808 static int done_word(o_string *word, struct parse_context *ctx)
4810 struct command *command = ctx->command;
4812 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4813 if (word->length == 0 && word->o_quoted == 0) {
4814 debug_printf_parse("done_word return 0: true null, ignored\n");
4818 if (ctx->pending_redirect) {
4819 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4820 * only if run as "bash", not "sh" */
4821 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4823 * ...the word that follows the redirection operator
4824 * shall be subjected to tilde expansion, parameter expansion,
4825 * command substitution, arithmetic expansion, and quote
4826 * removal. Pathname expansion shall not be performed
4827 * on the word by a non-interactive shell; an interactive
4828 * shell may perform it, but shall do so only when
4829 * the expansion would result in one word."
4831 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4832 /* Cater for >\file case:
4833 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4834 * Same with heredocs:
4835 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4837 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4838 unbackslash(ctx->pending_redirect->rd_filename);
4839 /* Is it <<"HEREDOC"? */
4840 if (word->o_quoted) {
4841 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4844 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4845 ctx->pending_redirect = NULL;
4847 /* If this word wasn't an assignment, next ones definitely
4848 * can't be assignments. Even if they look like ones. */
4849 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4850 && word->o_assignment != WORD_IS_KEYWORD
4852 word->o_assignment = NOT_ASSIGNMENT;
4854 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4855 command->assignment_cnt++;
4856 word->o_assignment = MAYBE_ASSIGNMENT;
4860 # if ENABLE_HUSH_CASE
4861 if (ctx->ctx_dsemicolon
4862 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4864 /* already done when ctx_dsemicolon was set to 1: */
4865 /* ctx->ctx_res_w = RES_MATCH; */
4866 ctx->ctx_dsemicolon = 0;
4869 if (!command->argv /* if it's the first word... */
4870 # if ENABLE_HUSH_LOOPS
4871 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4872 && ctx->ctx_res_w != RES_IN
4874 # if ENABLE_HUSH_CASE
4875 && ctx->ctx_res_w != RES_CASE
4878 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4879 if (reserved_word(word, ctx)) {
4880 o_reset_to_empty_unquoted(word);
4881 debug_printf_parse("done_word return %d\n",
4882 (ctx->ctx_res_w == RES_SNTX));
4883 return (ctx->ctx_res_w == RES_SNTX);
4885 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4886 if (strcmp(word->data, "export") == 0
4887 # if ENABLE_HUSH_LOCAL
4888 || strcmp(word->data, "local") == 0
4891 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4894 # if ENABLE_HUSH_BASH_COMPAT
4895 if (strcmp(word->data, "[[") == 0) {
4896 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4902 if (command->group) {
4903 /* "{ echo foo; } echo bar" - bad */
4904 syntax_error_at(word->data);
4905 debug_printf_parse("done_word return 1: syntax error, "
4906 "groups and arglists don't mix\n");
4909 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4910 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4911 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4912 /* (otherwise it's known to be not empty and is already safe) */
4914 /* exclude "$@" - it can expand to no word despite "" */
4915 char *p = word->data;
4916 while (p[0] == SPECIAL_VAR_SYMBOL
4917 && (p[1] & 0x7f) == '@'
4918 && p[2] == SPECIAL_VAR_SYMBOL
4922 if (p == word->data || p[0] != '\0') {
4923 /* saw no "$@", or not only "$@" but some
4924 * real text is there too */
4925 /* insert "empty variable" reference, this makes
4926 * e.g. "", $empty"" etc to not disappear */
4927 o_addchr(word, SPECIAL_VAR_SYMBOL);
4928 o_addchr(word, SPECIAL_VAR_SYMBOL);
4931 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4932 debug_print_strings("word appended to argv", command->argv);
4935 #if ENABLE_HUSH_LOOPS
4936 if (ctx->ctx_res_w == RES_FOR) {
4938 || !is_well_formed_var_name(command->argv[0], '\0')
4940 /* bash says just "not a valid identifier" */
4941 syntax_error("not a valid identifier in for");
4944 /* Force FOR to have just one word (variable name) */
4945 /* NB: basically, this makes hush see "for v in ..."
4946 * syntax as if it is "for v; in ...". FOR and IN become
4947 * two pipe structs in parse tree. */
4948 done_pipe(ctx, PIPE_SEQ);
4951 #if ENABLE_HUSH_CASE
4952 /* Force CASE to have just one word */
4953 if (ctx->ctx_res_w == RES_CASE) {
4954 done_pipe(ctx, PIPE_SEQ);
4958 o_reset_to_empty_unquoted(word);
4960 debug_printf_parse("done_word return 0\n");
4965 /* Peek ahead in the input to find out if we have a "&n" construct,
4966 * as in "2>&1", that represents duplicating a file descriptor.
4968 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4969 * REDIRFD_SYNTAX_ERR if syntax error,
4970 * REDIRFD_TO_FILE if no & was seen,
4971 * or the number found.
4974 #define parse_redir_right_fd(as_string, input) \
4975 parse_redir_right_fd(input)
4977 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4983 return REDIRFD_TO_FILE;
4985 ch = i_getch(input); /* get the & */
4986 nommu_addchr(as_string, ch);
4989 ch = i_getch(input);
4990 nommu_addchr(as_string, ch);
4991 return REDIRFD_CLOSE;
4995 while (ch != EOF && isdigit(ch)) {
4996 d = d*10 + (ch-'0');
4998 ch = i_getch(input);
4999 nommu_addchr(as_string, ch);
5004 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5006 bb_error_msg("ambiguous redirect");
5007 return REDIRFD_SYNTAX_ERR;
5010 /* Return code is 0 normal, 1 if a syntax error is detected
5012 static int parse_redirect(struct parse_context *ctx,
5015 struct in_str *input)
5017 struct command *command = ctx->command;
5018 struct redir_struct *redir;
5019 struct redir_struct **redirp;
5022 dup_num = REDIRFD_TO_FILE;
5023 if (style != REDIRECT_HEREDOC) {
5024 /* Check for a '>&1' type redirect */
5025 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5026 if (dup_num == REDIRFD_SYNTAX_ERR)
5029 int ch = i_peek(input);
5030 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5031 if (dup_num) { /* <<-... */
5032 ch = i_getch(input);
5033 nommu_addchr(&ctx->as_string, ch);
5038 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5039 int ch = i_peek(input);
5041 /* >|FILE redirect ("clobbering" >).
5042 * Since we do not support "set -o noclobber" yet,
5043 * >| and > are the same for now. Just eat |.
5045 ch = i_getch(input);
5046 nommu_addchr(&ctx->as_string, ch);
5050 /* Create a new redir_struct and append it to the linked list */
5051 redirp = &command->redirects;
5052 while ((redir = *redirp) != NULL) {
5053 redirp = &(redir->next);
5055 *redirp = redir = xzalloc(sizeof(*redir));
5056 /* redir->next = NULL; */
5057 /* redir->rd_filename = NULL; */
5058 redir->rd_type = style;
5059 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5061 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5062 redir_table[style].descrip);
5064 redir->rd_dup = dup_num;
5065 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5066 /* Erik had a check here that the file descriptor in question
5067 * is legit; I postpone that to "run time"
5068 * A "-" representation of "close me" shows up as a -3 here */
5069 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5070 redir->rd_fd, redir->rd_dup);
5072 /* Set ctx->pending_redirect, so we know what to do at the
5073 * end of the next parsed word. */
5074 ctx->pending_redirect = redir;
5079 /* If a redirect is immediately preceded by a number, that number is
5080 * supposed to tell which file descriptor to redirect. This routine
5081 * looks for such preceding numbers. In an ideal world this routine
5082 * needs to handle all the following classes of redirects...
5083 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5084 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5085 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5086 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5088 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5090 * ... If n is quoted, the number shall not be recognized as part of
5091 * the redirection expression. For example:
5093 * writes the character 2 into file a"
5094 * We are getting it right by setting ->o_quoted on any \<char>
5096 * A -1 return means no valid number was found,
5097 * the caller should use the appropriate default for this redirection.
5099 static int redirect_opt_num(o_string *o)
5103 if (o->data == NULL)
5105 num = bb_strtou(o->data, NULL, 10);
5106 if (errno || num < 0)
5108 o_reset_to_empty_unquoted(o);
5113 #define fetch_till_str(as_string, input, word, skip_tabs) \
5114 fetch_till_str(input, word, skip_tabs)
5116 static char *fetch_till_str(o_string *as_string,
5117 struct in_str *input,
5121 o_string heredoc = NULL_O_STRING;
5127 ch = i_getch(input);
5128 nommu_addchr(as_string, ch);
5130 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5131 heredoc.data[past_EOL] = '\0';
5132 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5133 return heredoc.data;
5136 o_addchr(&heredoc, ch);
5137 past_EOL = heredoc.length;
5140 ch = i_getch(input);
5141 nommu_addchr(as_string, ch);
5142 } while (skip_tabs && ch == '\t');
5143 } while (ch == '\n');
5146 o_free_unsafe(&heredoc);
5149 o_addchr(&heredoc, ch);
5150 nommu_addchr(as_string, ch);
5154 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5155 * and load them all. There should be exactly heredoc_cnt of them.
5157 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5159 struct pipe *pi = ctx->list_head;
5161 while (pi && heredoc_cnt) {
5163 struct command *cmd = pi->cmds;
5165 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5167 cmd->argv ? cmd->argv[0] : "NONE");
5168 for (i = 0; i < pi->num_cmds; i++) {
5169 struct redir_struct *redir = cmd->redirects;
5171 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5172 i, cmd->argv ? cmd->argv[0] : "NONE");
5174 if (redir->rd_type == REDIRECT_HEREDOC) {
5177 redir->rd_type = REDIRECT_HEREDOC2;
5178 /* redir->rd_dup is (ab)used to indicate <<- */
5179 p = fetch_till_str(&ctx->as_string, input,
5180 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5182 syntax_error("unexpected EOF in here document");
5185 free(redir->rd_filename);
5186 redir->rd_filename = p;
5189 redir = redir->next;
5196 /* Should be 0. If it isn't, it's a parse error */
5198 bb_error_msg_and_die("heredoc BUG 2");
5204 #if ENABLE_HUSH_TICK
5205 static FILE *generate_stream_from_string(const char *s)
5208 int pid, channel[2];
5214 pid = BB_MMU ? fork() : vfork();
5216 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5218 if (pid == 0) { /* child */
5219 disable_restore_tty_pgrp_on_exit();
5220 /* Process substitution is not considered to be usual
5221 * 'command execution'.
5222 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5229 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5230 close(channel[0]); /* NB: close _first_, then move fd! */
5231 xmove_fd(channel[1], 1);
5232 /* Prevent it from trying to handle ctrl-z etc */
5233 IF_HUSH_JOB(G.run_list_level = 1;)
5234 /* Awful hack for `trap` or $(trap).
5236 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5237 * contains an example where "trap" is executed in a subshell:
5239 * save_traps=$(trap)
5241 * eval "$save_traps"
5243 * Standard does not say that "trap" in subshell shall print
5244 * parent shell's traps. It only says that its output
5245 * must have suitable form, but then, in the above example
5246 * (which is not supposed to be normative), it implies that.
5248 * bash (and probably other shell) does implement it
5249 * (traps are reset to defaults, but "trap" still shows them),
5250 * but as a result, "trap" logic is hopelessly messed up:
5253 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5254 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5255 * # true | trap <--- trap is in subshell - no output (ditto)
5256 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5257 * trap -- 'echo Ho' SIGWINCH
5258 * # echo `(trap)` <--- in subshell in subshell - output
5259 * trap -- 'echo Ho' SIGWINCH
5260 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5261 * trap -- 'echo Ho' SIGWINCH
5263 * The rules when to forget and when to not forget traps
5264 * get really complex and nonsensical.
5266 * Our solution: ONLY bare $(trap) or `trap` is special.
5268 s = skip_whitespace(s);
5269 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5271 static const char *const argv[] = { NULL, NULL };
5272 builtin_trap((char**)argv);
5273 exit(0); /* not _exit() - we need to fflush */
5276 reset_traps_to_defaults();
5277 parse_and_run_string(s);
5278 _exit(G.last_exitcode);
5280 /* We re-execute after vfork on NOMMU. This makes this script safe:
5281 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5282 * huge=`cat BIG` # was blocking here forever
5285 re_execute_shell(&to_free,
5294 # if ENABLE_HUSH_FAST
5296 //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);
5298 enable_restore_tty_pgrp_on_exit();
5303 pf = fdopen(channel[0], "r");
5307 /* Return code is exit status of the process that is run. */
5308 static int process_command_subs(o_string *dest, const char *s)
5311 struct in_str pipe_str;
5314 pf = generate_stream_from_string(s);
5317 close_on_exec_on(fileno(pf));
5319 /* Now send results of command back into original context */
5320 setup_file_in_str(&pipe_str, pf);
5322 while ((ch = i_getch(&pipe_str)) != EOF) {
5328 o_addchr(dest, '\n');
5331 o_addQchr(dest, ch);
5334 debug_printf("done reading from pipe, pclose()ing\n");
5335 /* Note: we got EOF, and we just close the read end of the pipe.
5336 * We do not wait for the `cmd` child to terminate. bash and ash do.
5338 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5339 * `false`; echo $? - bash outputs "1"
5342 debug_printf("closed FILE from child. return 0\n");
5345 #endif /* ENABLE_HUSH_TICK */
5347 static int parse_group(o_string *dest, struct parse_context *ctx,
5348 struct in_str *input, int ch)
5350 /* dest contains characters seen prior to ( or {.
5351 * Typically it's empty, but for function defs,
5352 * it contains function name (without '()'). */
5353 struct pipe *pipe_list;
5355 struct command *command = ctx->command;
5357 debug_printf_parse("parse_group entered\n");
5358 #if ENABLE_HUSH_FUNCTIONS
5359 if (ch == '(' && !dest->o_quoted) {
5361 if (done_word(dest, ctx))
5364 goto skip; /* (... */
5365 if (command->argv[1]) { /* word word ... (... */
5366 syntax_error_unexpected_ch('(');
5369 /* it is "word(..." or "word (..." */
5371 ch = i_getch(input);
5372 while (ch == ' ' || ch == '\t');
5374 syntax_error_unexpected_ch(ch);
5377 nommu_addchr(&ctx->as_string, ch);
5379 ch = i_getch(input);
5380 while (ch == ' ' || ch == '\t' || ch == '\n');
5382 syntax_error_unexpected_ch(ch);
5385 nommu_addchr(&ctx->as_string, ch);
5386 command->cmd_type = CMD_FUNCDEF;
5390 if (command->argv /* word [word]{... */
5391 || dest->length /* word{... */
5392 || dest->o_quoted /* ""{... */
5395 debug_printf_parse("parse_group return 1: "
5396 "syntax error, groups and arglists don't mix\n");
5400 #if ENABLE_HUSH_FUNCTIONS
5406 command->cmd_type = CMD_SUBSHELL;
5408 /* bash does not allow "{echo...", requires whitespace */
5409 ch = i_getch(input);
5410 if (ch != ' ' && ch != '\t' && ch != '\n') {
5411 syntax_error_unexpected_ch(ch);
5414 nommu_addchr(&ctx->as_string, ch);
5419 char *as_string = NULL;
5421 pipe_list = parse_stream(&as_string, input, endch);
5424 o_addstr(&ctx->as_string, as_string);
5426 /* empty ()/{} or parse error? */
5427 if (!pipe_list || pipe_list == ERR_PTR) {
5428 /* parse_stream already emitted error msg */
5432 debug_printf_parse("parse_group return 1: "
5433 "parse_stream returned %p\n", pipe_list);
5436 command->group = pipe_list;
5438 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5439 command->group_as_string = as_string;
5440 debug_printf_parse("end of group, remembering as:'%s'\n",
5441 command->group_as_string);
5444 debug_printf_parse("parse_group return 0\n");
5446 /* command remains "open", available for possible redirects */
5449 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5450 /* Subroutines for copying $(...) and `...` things */
5451 static void add_till_backquote(o_string *dest, struct in_str *input);
5453 static void add_till_single_quote(o_string *dest, struct in_str *input)
5456 int ch = i_getch(input);
5458 syntax_error_unterm_ch('\'');
5459 /*xfunc_die(); - redundant */
5466 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5467 static void add_till_double_quote(o_string *dest, struct in_str *input)
5470 int ch = i_getch(input);
5472 syntax_error_unterm_ch('"');
5473 /*xfunc_die(); - redundant */
5477 if (ch == '\\') { /* \x. Copy both chars. */
5479 ch = i_getch(input);
5483 add_till_backquote(dest, input);
5487 //if (ch == '$') ...
5490 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5492 * "Within the backquoted style of command substitution, backslash
5493 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5494 * The search for the matching backquote shall be satisfied by the first
5495 * backquote found without a preceding backslash; during this search,
5496 * if a non-escaped backquote is encountered within a shell comment,
5497 * a here-document, an embedded command substitution of the $(command)
5498 * form, or a quoted string, undefined results occur. A single-quoted
5499 * or double-quoted string that begins, but does not end, within the
5500 * "`...`" sequence produces undefined results."
5502 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5504 static void add_till_backquote(o_string *dest, struct in_str *input)
5507 int ch = i_getch(input);
5509 syntax_error_unterm_ch('`');
5510 /*xfunc_die(); - redundant */
5515 /* \x. Copy both chars unless it is \` */
5516 int ch2 = i_getch(input);
5518 syntax_error_unterm_ch('`');
5519 /*xfunc_die(); - redundant */
5521 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5528 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5529 * quoting and nested ()s.
5530 * "With the $(command) style of command substitution, all characters
5531 * following the open parenthesis to the matching closing parenthesis
5532 * constitute the command. Any valid shell script can be used for command,
5533 * except a script consisting solely of redirections which produces
5534 * unspecified results."
5536 * echo $(echo '(TEST)' BEST) (TEST) BEST
5537 * echo $(echo 'TEST)' BEST) TEST) BEST
5538 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5540 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5544 int ch = i_getch(input);
5546 syntax_error_unterm_ch(')');
5547 /*xfunc_die(); - redundant */
5555 if (i_peek(input) == ')') {
5563 add_till_single_quote(dest, input);
5568 add_till_double_quote(dest, input);
5573 /* \x. Copy verbatim. Important for \(, \) */
5574 ch = i_getch(input);
5576 syntax_error_unterm_ch(')');
5577 /*xfunc_die(); - redundant */
5584 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5586 /* Return code: 0 for OK, 1 for syntax error */
5588 #define handle_dollar(as_string, dest, input) \
5589 handle_dollar(dest, input)
5591 static int handle_dollar(o_string *as_string,
5593 struct in_str *input)
5595 int ch = i_peek(input); /* first character after the $ */
5596 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5598 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5600 ch = i_getch(input);
5601 nommu_addchr(as_string, ch);
5603 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5605 debug_printf_parse(": '%c'\n", ch);
5606 o_addchr(dest, ch | quote_mask);
5609 if (!isalnum(ch) && ch != '_')
5611 ch = i_getch(input);
5612 nommu_addchr(as_string, ch);
5614 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5615 } else if (isdigit(ch)) {
5617 ch = i_getch(input);
5618 nommu_addchr(as_string, ch);
5619 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5620 debug_printf_parse(": '%c'\n", ch);
5621 o_addchr(dest, ch | quote_mask);
5622 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5623 } else switch (ch) {
5625 case '!': /* last bg pid */
5626 case '?': /* last exit code */
5627 case '#': /* number of args */
5628 case '*': /* args */
5629 case '@': /* args */
5630 goto make_one_char_var;
5632 bool first_char, all_digits;
5635 ch = i_getch(input);
5636 nommu_addchr(as_string, ch);
5637 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5639 /* TODO: maybe someone will try to escape the '}' */
5644 ch = i_getch(input);
5645 nommu_addchr(as_string, ch);
5652 /* ${#var}: length of var contents */
5659 /* They're being verbose and doing ${?} */
5660 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5665 && ( (all_digits && !isdigit(ch))
5666 || (!all_digits && !isalnum(ch) && ch != '_')
5669 /* handle parameter expansions
5670 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5675 case ':': /* null modifier */
5676 if (expansion == 0) {
5677 debug_printf_parse(": null modifier\n");
5682 case '#': /* remove prefix */
5683 case '%': /* remove suffix */
5684 if (expansion == 0) {
5685 debug_printf_parse(": remove suffix/prefix\n");
5690 case '-': /* default value */
5691 case '=': /* assign default */
5692 case '+': /* alternative */
5693 case '?': /* error indicate */
5694 debug_printf_parse(": parameter expansion\n");
5699 syntax_error_unterm_str("${name}");
5700 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5705 debug_printf_parse(": '%c'\n", ch);
5706 o_addchr(dest, ch | quote_mask);
5710 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5713 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
5718 ch = i_getch(input);
5719 nommu_addchr(as_string, ch);
5720 # if ENABLE_SH_MATH_SUPPORT
5721 if (i_peek(input) == '(') {
5722 ch = i_getch(input);
5723 nommu_addchr(as_string, ch);
5724 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5725 o_addchr(dest, /*quote_mask |*/ '+');
5729 add_till_closing_paren(dest, input, true);
5732 o_addstr(as_string, dest->data + pos);
5733 o_addchr(as_string, ')');
5734 o_addchr(as_string, ')');
5737 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5741 # if ENABLE_HUSH_TICK
5742 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5743 o_addchr(dest, quote_mask | '`');
5747 add_till_closing_paren(dest, input, false);
5750 o_addstr(as_string, dest->data + pos);
5751 o_addchr(as_string, '`');
5754 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5760 ch = i_getch(input);
5761 nommu_addchr(as_string, ch);
5763 if (isalnum(ch)) { /* it's $_name or $_123 */
5768 /* TODO: $_ and $-: */
5769 /* $_ Shell or shell script name; or last argument of last command
5770 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5771 * but in command's env, set to full pathname used to invoke it */
5772 /* $- Option flags set by set builtin or shell options (-i etc) */
5774 o_addQchr(dest, '$');
5776 debug_printf_parse("handle_dollar return 0\n");
5781 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5782 parse_stream_dquoted(dest, input, dquote_end)
5784 static int parse_stream_dquoted(o_string *as_string,
5786 struct in_str *input,
5793 ch = i_getch(input);
5795 nommu_addchr(as_string, ch);
5796 if (ch == dquote_end) { /* may be only '"' or EOF */
5797 if (dest->o_assignment == NOT_ASSIGNMENT)
5798 dest->o_escape ^= 1;
5799 debug_printf_parse("parse_stream_dquoted return 0\n");
5802 /* note: can't move it above ch == dquote_end check! */
5804 syntax_error_unterm_ch('"');
5805 /*xfunc_die(); - redundant */
5809 next = i_peek(input);
5811 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
5812 ch, ch, dest->o_escape);
5815 syntax_error("\\<eof>");
5819 * "The backslash retains its special meaning [in "..."]
5820 * only when followed by one of the following characters:
5821 * $, `, ", \, or <newline>. A double quote may be quoted
5822 * within double quotes by preceding it with a backslash."
5824 if (strchr("$`\"\\\n", next) != NULL) {
5825 ch = i_getch(input);
5827 o_addqchr(dest, ch);
5828 nommu_addchr(as_string, ch);
5831 o_addqchr(dest, '\\');
5832 nommu_addchr(as_string, '\\');
5837 if (handle_dollar(as_string, dest, input) != 0) {
5838 debug_printf_parse("parse_stream_dquoted return 1: "
5839 "handle_dollar returned non-0\n");
5844 #if ENABLE_HUSH_TICK
5846 //int pos = dest->length;
5847 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5848 o_addchr(dest, 0x80 | '`');
5849 add_till_backquote(dest, input);
5850 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5851 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5855 o_addQchr(dest, ch);
5857 && (dest->o_assignment == MAYBE_ASSIGNMENT
5858 || dest->o_assignment == WORD_IS_KEYWORD)
5859 && is_well_formed_var_name(dest->data, '=')
5861 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5867 * Scan input until EOF or end_trigger char.
5868 * Return a list of pipes to execute, or NULL on EOF
5869 * or if end_trigger character is met.
5870 * On syntax error, exit is shell is not interactive,
5871 * reset parsing machinery and start parsing anew,
5872 * or return ERR_PTR.
5874 static struct pipe *parse_stream(char **pstring,
5875 struct in_str *input,
5878 struct parse_context ctx;
5879 o_string dest = NULL_O_STRING;
5883 /* Double-quote state is handled in the state variable is_in_dquote.
5884 * A single-quote triggers a bypass of the main loop until its mate is
5885 * found. When recursing, quote state is passed in via dest->o_escape.
5887 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5888 end_trigger ? end_trigger : 'X');
5891 /* If very first arg is "" or '', dest.data may end up NULL.
5892 * Preventing this: */
5893 o_addchr(&dest, '\0');
5896 G.ifs = get_local_var_value("IFS");
5901 #if ENABLE_HUSH_INTERACTIVE
5902 input->promptmode = 0; /* PS1 */
5904 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5905 initialize_context(&ctx);
5910 const char *is_special;
5914 redir_type redir_style;
5917 /* dest.o_quoted = 1; - already is (see below) */
5918 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5921 /* We reached closing '"' */
5924 ch = i_getch(input);
5925 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5926 ch, ch, dest.o_escape);
5931 syntax_error_unterm_str("here document");
5934 /* end_trigger == '}' case errors out earlier,
5935 * checking only ')' */
5936 if (end_trigger == ')') {
5937 syntax_error_unterm_ch('('); /* exits */
5938 /* goto parse_error; */
5941 if (done_word(&dest, &ctx)) {
5945 done_pipe(&ctx, PIPE_SEQ);
5947 /* If we got nothing... */
5948 /* (this makes bare "&" cmd a no-op.
5949 * bash says: "syntax error near unexpected token '&'") */
5950 if (pi->num_cmds == 0
5951 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5957 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5959 *pstring = ctx.as_string.data;
5961 o_free_unsafe(&ctx.as_string);
5964 debug_printf_parse("parse_stream return %p\n", pi);
5967 nommu_addchr(&ctx.as_string, ch);
5968 is_ifs = strchr(G.ifs, ch);
5969 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5970 "\\$\"" IF_HUSH_TICK("`") /* always special */
5973 if (!is_special && !is_ifs) { /* ordinary char */
5975 o_addQchr(&dest, ch);
5976 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5977 || dest.o_assignment == WORD_IS_KEYWORD)
5979 && is_well_formed_var_name(dest.data, '=')
5981 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5987 if (done_word(&dest, &ctx)) {
5991 #if ENABLE_HUSH_CASE
5992 /* "case ... in <newline> word) ..." -
5993 * newlines are ignored (but ';' wouldn't be) */
5994 if (ctx.command->argv == NULL
5995 && ctx.ctx_res_w == RES_MATCH
6000 /* Treat newline as a command separator. */
6001 done_pipe(&ctx, PIPE_SEQ);
6002 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6004 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6009 dest.o_assignment = MAYBE_ASSIGNMENT;
6011 /* note: if (is_ifs) continue;
6012 * will still trigger for us */
6016 /* "cmd}" or "cmd }..." without semicolon or &:
6017 * } is an ordinary char in this case, even inside { cmd; }
6018 * Pathological example: { ""}; } should exec "}" cmd
6021 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6022 || dest.length != 0 /* word} */
6023 || dest.o_quoted /* ""} */
6027 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6028 goto skip_end_trigger;
6029 /* else: } does terminate a group */
6032 if (end_trigger && end_trigger == ch
6033 && (ch != ';' || heredoc_cnt == 0)
6034 #if ENABLE_HUSH_CASE
6036 || ctx.ctx_res_w != RES_MATCH
6037 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6042 /* This is technically valid:
6043 * { cat <<HERE; }; echo Ok
6047 * but we don't support this.
6048 * We require heredoc to be in enclosing {}/(),
6051 syntax_error_unterm_str("here document");
6054 if (done_word(&dest, &ctx)) {
6057 done_pipe(&ctx, PIPE_SEQ);
6058 dest.o_assignment = MAYBE_ASSIGNMENT;
6059 /* Do we sit outside of any if's, loops or case's? */
6061 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6065 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6067 *pstring = ctx.as_string.data;
6069 o_free_unsafe(&ctx.as_string);
6072 debug_printf_parse("parse_stream return %p: "
6073 "end_trigger char found\n",
6075 return ctx.list_head;
6084 next = i_peek(input);
6087 /* Catch <, > before deciding whether this word is
6088 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6091 redir_fd = redirect_opt_num(&dest);
6092 if (done_word(&dest, &ctx)) {
6095 redir_style = REDIRECT_OVERWRITE;
6097 redir_style = REDIRECT_APPEND;
6098 ch = i_getch(input);
6099 nommu_addchr(&ctx.as_string, ch);
6102 else if (next == '(') {
6103 syntax_error(">(process) not supported");
6107 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6109 continue; /* back to top of while (1) */
6111 redir_fd = redirect_opt_num(&dest);
6112 if (done_word(&dest, &ctx)) {
6115 redir_style = REDIRECT_INPUT;
6117 redir_style = REDIRECT_HEREDOC;
6119 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6120 ch = i_getch(input);
6121 nommu_addchr(&ctx.as_string, ch);
6122 } else if (next == '>') {
6123 redir_style = REDIRECT_IO;
6124 ch = i_getch(input);
6125 nommu_addchr(&ctx.as_string, ch);
6128 else if (next == '(') {
6129 syntax_error("<(process) not supported");
6133 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6135 continue; /* back to top of while (1) */
6138 if (dest.o_assignment == MAYBE_ASSIGNMENT
6139 /* check that we are not in word in "a=1 2>word b=1": */
6140 && !ctx.pending_redirect
6142 /* ch is a special char and thus this word
6143 * cannot be an assignment */
6144 dest.o_assignment = NOT_ASSIGNMENT;
6147 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6151 if (dest.length == 0) {
6154 if (ch == EOF || ch == '\n')
6157 /* note: we do not add it to &ctx.as_string */
6159 nommu_addchr(&ctx.as_string, '\n');
6161 o_addQchr(&dest, ch);
6166 syntax_error("\\<eof>");
6169 ch = i_getch(input);
6171 o_addchr(&dest, '\\');
6172 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6173 o_addchr(&dest, ch);
6174 nommu_addchr(&ctx.as_string, ch);
6175 /* Example: echo Hello \2>file
6176 * we need to know that word 2 is quoted */
6181 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6182 ctx.as_string.data[--ctx.as_string.length] = '\0';
6187 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6188 debug_printf_parse("parse_stream parse error: "
6189 "handle_dollar returned non-0\n");
6196 ch = i_getch(input);
6198 syntax_error_unterm_ch('\'');
6199 /*xfunc_die(); - redundant */
6201 nommu_addchr(&ctx.as_string, ch);
6204 o_addqchr(&dest, ch);
6209 is_in_dquote ^= 1; /* invert */
6210 if (dest.o_assignment == NOT_ASSIGNMENT)
6213 #if ENABLE_HUSH_TICK
6218 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6219 o_addchr(&dest, '`');
6223 add_till_backquote(&dest, input);
6225 o_addstr(&ctx.as_string, dest.data + pos);
6226 o_addchr(&ctx.as_string, '`');
6228 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6229 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6234 #if ENABLE_HUSH_CASE
6237 if (done_word(&dest, &ctx)) {
6240 done_pipe(&ctx, PIPE_SEQ);
6241 #if ENABLE_HUSH_CASE
6242 /* Eat multiple semicolons, detect
6243 * whether it means something special */
6248 ch = i_getch(input);
6249 nommu_addchr(&ctx.as_string, ch);
6250 if (ctx.ctx_res_w == RES_CASE_BODY) {
6251 ctx.ctx_dsemicolon = 1;
6252 ctx.ctx_res_w = RES_MATCH;
6258 /* We just finished a cmd. New one may start
6259 * with an assignment */
6260 dest.o_assignment = MAYBE_ASSIGNMENT;
6263 if (done_word(&dest, &ctx)) {
6267 ch = i_getch(input);
6268 nommu_addchr(&ctx.as_string, ch);
6269 done_pipe(&ctx, PIPE_AND);
6271 done_pipe(&ctx, PIPE_BG);
6275 if (done_word(&dest, &ctx)) {
6278 #if ENABLE_HUSH_CASE
6279 if (ctx.ctx_res_w == RES_MATCH)
6280 break; /* we are in case's "word | word)" */
6282 if (next == '|') { /* || */
6283 ch = i_getch(input);
6284 nommu_addchr(&ctx.as_string, ch);
6285 done_pipe(&ctx, PIPE_OR);
6287 /* we could pick up a file descriptor choice here
6288 * with redirect_opt_num(), but bash doesn't do it.
6289 * "echo foo 2| cat" yields "foo 2". */
6294 #if ENABLE_HUSH_CASE
6295 /* "case... in [(]word)..." - skip '(' */
6296 if (ctx.ctx_res_w == RES_MATCH
6297 && ctx.command->argv == NULL /* not (word|(... */
6298 && dest.length == 0 /* not word(... */
6299 && dest.o_quoted == 0 /* not ""(... */
6305 if (parse_group(&dest, &ctx, input, ch) != 0) {
6310 #if ENABLE_HUSH_CASE
6311 if (ctx.ctx_res_w == RES_MATCH)
6315 /* proper use of this character is caught by end_trigger:
6316 * if we see {, we call parse_group(..., end_trigger='}')
6317 * and it will match } earlier (not here). */
6318 syntax_error_unexpected_ch(ch);
6322 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6328 struct parse_context *pctx;
6329 IF_HAS_KEYWORDS(struct parse_context *p2;)
6331 /* Clean up allocated tree.
6332 * Sample for finding leaks on syntax error recovery path.
6333 * Run it from interactive shell, watch pmap `pidof hush`.
6334 * while if false; then false; fi; do break; fi
6335 * Samples to catch leaks at execution:
6336 * while if (true | {true;}); then echo ok; fi; do break; done
6337 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6341 /* Update pipe/command counts,
6342 * otherwise freeing may miss some */
6343 done_pipe(pctx, PIPE_SEQ);
6344 debug_printf_clean("freeing list %p from ctx %p\n",
6345 pctx->list_head, pctx);
6346 debug_print_tree(pctx->list_head, 0);
6347 free_pipe_list(pctx->list_head);
6348 debug_printf_clean("freed list %p\n", pctx->list_head);
6350 o_free_unsafe(&pctx->as_string);
6352 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6356 IF_HAS_KEYWORDS(pctx = p2;)
6357 } while (HAS_KEYWORDS && pctx);
6358 /* Free text, clear all dest fields */
6360 /* If we are not in top-level parse, we return,
6361 * our caller will propagate error.
6363 if (end_trigger != ';') {
6371 /* Discard cached input, force prompt */
6373 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6378 /* Executing from string: eval, sh -c '...'
6379 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6380 * end_trigger controls how often we stop parsing
6381 * NUL: parse all, execute, return
6382 * ';': parse till ';' or newline, execute, repeat till EOF
6384 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6387 struct pipe *pipe_list;
6389 pipe_list = parse_stream(NULL, inp, end_trigger);
6390 if (!pipe_list) /* EOF */
6392 debug_print_tree(pipe_list, 0);
6393 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6394 run_and_free_list(pipe_list);
6398 static void parse_and_run_string(const char *s)
6400 struct in_str input;
6401 setup_string_in_str(&input, s);
6402 parse_and_run_stream(&input, '\0');
6405 static void parse_and_run_file(FILE *f)
6407 struct in_str input;
6408 setup_file_in_str(&input, f);
6409 parse_and_run_stream(&input, ';');
6412 /* Called a few times only (or even once if "sh -c") */
6413 static void block_signals(int second_time)
6418 mask = (1 << SIGQUIT);
6419 if (G_interactive_fd) {
6420 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6421 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6422 mask |= SPECIAL_JOB_SIGS;
6424 G.non_DFL_mask = mask;
6427 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6431 sigaddset(&G.blocked_set, sig);
6435 sigdelset(&G.blocked_set, SIGCHLD);
6437 sigprocmask(SIG_SETMASK, &G.blocked_set,
6438 second_time ? NULL : &G.inherited_set);
6439 /* POSIX allows shell to re-enable SIGCHLD
6440 * even if it was SIG_IGN on entry */
6441 #if ENABLE_HUSH_FAST
6442 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6444 signal(SIGCHLD, SIGCHLD_handler);
6447 signal(SIGCHLD, SIG_DFL);
6453 static void maybe_set_to_sigexit(int sig)
6455 void (*handler)(int);
6456 /* non_DFL_mask'ed signals are, well, masked,
6457 * no need to set handler for them.
6459 if (!((G.non_DFL_mask >> sig) & 1)) {
6460 handler = signal(sig, sigexit);
6461 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6462 signal(sig, handler);
6465 /* Set handlers to restore tty pgrp and exit */
6466 static void set_fatal_handlers(void)
6468 /* We _must_ restore tty pgrp on fatal signals */
6470 maybe_set_to_sigexit(SIGILL );
6471 maybe_set_to_sigexit(SIGFPE );
6472 maybe_set_to_sigexit(SIGBUS );
6473 maybe_set_to_sigexit(SIGSEGV);
6474 maybe_set_to_sigexit(SIGTRAP);
6475 } /* else: hush is perfect. what SEGV? */
6476 maybe_set_to_sigexit(SIGABRT);
6477 /* bash 3.2 seems to handle these just like 'fatal' ones */
6478 maybe_set_to_sigexit(SIGPIPE);
6479 maybe_set_to_sigexit(SIGALRM);
6480 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6481 * if we aren't interactive... but in this case
6482 * we never want to restore pgrp on exit, and this fn is not called */
6483 /*maybe_set_to_sigexit(SIGHUP );*/
6484 /*maybe_set_to_sigexit(SIGTERM);*/
6485 /*maybe_set_to_sigexit(SIGINT );*/
6489 static int set_mode(const char cstate, const char mode)
6491 int state = (cstate == '-' ? 1 : 0);
6493 case 'n': G.fake_mode = state; break;
6494 case 'x': /*G.debug_mode = state;*/ break;
6495 default: return EXIT_FAILURE;
6497 return EXIT_SUCCESS;
6500 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6501 int hush_main(int argc, char **argv)
6503 static const struct variable const_shell_ver = {
6505 .varstr = (char*)hush_version_str,
6506 .max_len = 1, /* 0 can provoke free(name) */
6510 int signal_mask_is_inited = 0;
6512 unsigned builtin_argc;
6514 struct variable *cur_var;
6517 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6518 G.last_exitcode = EXIT_SUCCESS;
6520 G.argv0_for_re_execing = argv[0];
6522 /* Deal with HUSH_VERSION */
6523 G.shell_ver = const_shell_ver; /* copying struct here */
6524 G.top_var = &G.shell_ver;
6525 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6526 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6527 /* Initialize our shell local variables with the values
6528 * currently living in the environment */
6529 cur_var = G.top_var;
6532 char *value = strchr(*e, '=');
6533 if (value) { /* paranoia */
6534 cur_var->next = xzalloc(sizeof(*cur_var));
6535 cur_var = cur_var->next;
6536 cur_var->varstr = *e;
6537 cur_var->max_len = strlen(*e);
6538 cur_var->flg_export = 1;
6542 /* reinstate HUSH_VERSION */
6543 debug_printf_env("putenv '%s'\n", hush_version_str);
6544 putenv((char *)hush_version_str);
6547 set_pwd_var(/*exp:*/ 1);
6548 /* bash also exports SHLVL and _,
6549 * and sets (but doesn't export) the following variables:
6551 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6552 * BASH_VERSION='3.2.0(1)-release'
6554 * MACHTYPE=i386-pc-linux-gnu
6556 * HOSTNAME=<xxxxxxxxxx>
6557 * PPID=<NNNNN> - we also do it elsewhere
6568 * PIPESTATUS=([0]="0")
6569 * HISTFILE=/<xxx>/.bash_history
6573 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6575 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6585 #if ENABLE_FEATURE_EDITING
6586 G.line_input_state = new_line_input_t(FOR_SHELL);
6588 G.global_argc = argc;
6589 G.global_argv = argv;
6590 /* Initialize some more globals to non-zero values */
6591 cmdedit_update_prompt();
6593 if (setjmp(die_jmp)) {
6594 /* xfunc has failed! die die die */
6595 /* no EXIT traps, this is an escape hatch! */
6597 hush_exit(xfunc_error_retval);
6600 /* Shell is non-interactive at first. We need to call
6601 * block_signals(0) if we are going to execute "sh <script>",
6602 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6603 * If we later decide that we are interactive, we run block_signals(0)
6604 * (or re-run block_signals(1) if we ran block_signals(0) before)
6605 * in order to intercept (more) signals.
6609 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6612 opt = getopt(argc, argv, "+c:xins"
6615 # if ENABLE_HUSH_FUNCTIONS
6625 * sh ... -c 'script'
6626 * sh ... -c 'script' ARG0 [ARG1...]
6627 * On NOMMU, if builtin_argc != 0,
6628 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6629 * "" needs to be replaced with NULL
6630 * and BARGV vector fed to builtin function.
6631 * Note: this form never happens:
6632 * sh ... -c 'builtin' [BARGV...] ""
6635 G.root_pid = getpid();
6636 G.root_ppid = getppid();
6638 G.global_argv = argv + optind;
6639 G.global_argc = argc - optind;
6641 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6642 const struct built_in_command *x;
6644 block_signals(0); /* 0: called 1st time */
6645 x = find_builtin(optarg);
6646 if (x) { /* paranoia */
6647 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6648 G.global_argv += builtin_argc;
6649 G.global_argv[-1] = NULL; /* replace "" */
6650 G.last_exitcode = x->function(argv + optind - 1);
6654 if (!G.global_argv[0]) {
6655 /* -c 'script' (no params): prevent empty $0 */
6656 G.global_argv--; /* points to argv[i] of 'script' */
6657 G.global_argv[0] = argv[0];
6659 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6660 block_signals(0); /* 0: called 1st time */
6661 parse_and_run_string(optarg);
6664 /* Well, we cannot just declare interactiveness,
6665 * we have to have some stuff (ctty, etc) */
6666 /* G_interactive_fd++; */
6669 /* "-s" means "read from stdin", but this is how we always
6670 * operate, so simply do nothing here. */
6673 case '<': /* "big heredoc" support */
6674 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6677 G.root_pid = bb_strtou(optarg, &optarg, 16);
6679 G.root_ppid = bb_strtou(optarg, &optarg, 16);
6681 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6683 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6685 builtin_argc = bb_strtou(optarg, &optarg, 16);
6686 # if ENABLE_HUSH_LOOPS
6688 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6693 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6695 # if ENABLE_HUSH_FUNCTIONS
6697 struct function *funcp = new_function(optarg);
6698 /* funcp->name is already set to optarg */
6699 /* funcp->body is set to NULL. It's a special case. */
6700 funcp->body_as_string = argv[optind];
6708 if (!set_mode('-', opt))
6712 fprintf(stderr, "Usage: sh [FILE]...\n"
6713 " or: sh -c command [args]...\n\n");
6719 } /* option parsing loop */
6722 G.root_pid = getpid();
6723 G.root_ppid = getppid();
6726 /* If we are login shell... */
6727 if (argv[0] && argv[0][0] == '-') {
6729 debug_printf("sourcing /etc/profile\n");
6730 input = fopen_for_read("/etc/profile");
6731 if (input != NULL) {
6732 close_on_exec_on(fileno(input));
6733 block_signals(0); /* 0: called 1st time */
6734 signal_mask_is_inited = 1;
6735 parse_and_run_file(input);
6738 /* bash: after sourcing /etc/profile,
6739 * tries to source (in the given order):
6740 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6741 * stopping on first found. --noprofile turns this off.
6742 * bash also sources ~/.bash_logout on exit.
6743 * If called as sh, skips .bash_XXX files.
6750 * "bash <script>" (which is never interactive (unless -i?))
6751 * sources $BASH_ENV here (without scanning $PATH).
6752 * If called as sh, does the same but with $ENV.
6754 debug_printf("running script '%s'\n", argv[optind]);
6755 G.global_argv = argv + optind;
6756 G.global_argc = argc - optind;
6757 input = xfopen_for_read(argv[optind]);
6758 close_on_exec_on(fileno(input));
6759 if (!signal_mask_is_inited)
6760 block_signals(0); /* 0: called 1st time */
6761 parse_and_run_file(input);
6762 #if ENABLE_FEATURE_CLEAN_UP
6768 /* Up to here, shell was non-interactive. Now it may become one.
6769 * NB: don't forget to (re)run block_signals(0/1) as needed.
6772 /* A shell is interactive if the '-i' flag was given,
6773 * or if all of the following conditions are met:
6775 * no arguments remaining or the -s flag given
6776 * standard input is a terminal
6777 * standard output is a terminal
6778 * Refer to Posix.2, the description of the 'sh' utility.
6781 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6782 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6783 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6784 if (G_saved_tty_pgrp < 0)
6785 G_saved_tty_pgrp = 0;
6787 /* try to dup stdin to high fd#, >= 255 */
6788 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6789 if (G_interactive_fd < 0) {
6790 /* try to dup to any fd */
6791 G_interactive_fd = dup(STDIN_FILENO);
6792 if (G_interactive_fd < 0) {
6794 G_interactive_fd = 0;
6795 G_saved_tty_pgrp = 0;
6798 // TODO: track & disallow any attempts of user
6799 // to (inadvertently) close/redirect G_interactive_fd
6801 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6802 if (G_interactive_fd) {
6803 close_on_exec_on(G_interactive_fd);
6805 if (G_saved_tty_pgrp) {
6806 /* If we were run as 'hush &', sleep until we are
6807 * in the foreground (tty pgrp == our pgrp).
6808 * If we get started under a job aware app (like bash),
6809 * make sure we are now in charge so we don't fight over
6810 * who gets the foreground */
6812 pid_t shell_pgrp = getpgrp();
6813 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6814 if (G_saved_tty_pgrp == shell_pgrp)
6816 /* send TTIN to ourself (should stop us) */
6817 kill(- shell_pgrp, SIGTTIN);
6821 /* Block some signals */
6822 block_signals(signal_mask_is_inited);
6824 if (G_saved_tty_pgrp) {
6825 /* Set other signals to restore saved_tty_pgrp */
6826 set_fatal_handlers();
6827 /* Put ourselves in our own process group
6828 * (bash, too, does this only if ctty is available) */
6829 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6830 /* Grab control of the terminal */
6831 tcsetpgrp(G_interactive_fd, getpid());
6833 /* -1 is special - makes xfuncs longjmp, not exit
6834 * (we reset die_sleep = 0 whereever we [v]fork) */
6835 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6836 } else if (!signal_mask_is_inited) {
6837 block_signals(0); /* 0: called 1st time */
6838 } /* else: block_signals(0) was done before */
6839 #elif ENABLE_HUSH_INTERACTIVE
6840 /* No job control compiled in, only prompt/line editing */
6841 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6842 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6843 if (G_interactive_fd < 0) {
6844 /* try to dup to any fd */
6845 G_interactive_fd = dup(STDIN_FILENO);
6846 if (G_interactive_fd < 0)
6848 G_interactive_fd = 0;
6851 if (G_interactive_fd) {
6852 close_on_exec_on(G_interactive_fd);
6853 block_signals(signal_mask_is_inited);
6854 } else if (!signal_mask_is_inited) {
6858 /* We have interactiveness code disabled */
6859 if (!signal_mask_is_inited) {
6864 * if interactive but not a login shell, sources ~/.bashrc
6865 * (--norc turns this off, --rcfile <file> overrides)
6868 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6869 /* note: ash and hush share this string */
6870 printf("\n\n%s %s\n"
6871 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
6874 "hush - the humble shell"
6878 parse_and_run_file(stdin);
6881 #if ENABLE_FEATURE_CLEAN_UP
6882 if (G.cwd != bb_msg_unknown)
6884 cur_var = G.top_var->next;
6886 struct variable *tmp = cur_var;
6887 if (!cur_var->max_len)
6888 free(cur_var->varstr);
6889 cur_var = cur_var->next;
6893 hush_exit(G.last_exitcode);
6898 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6899 int lash_main(int argc, char **argv)
6901 bb_error_msg("lash is deprecated, please use hush instead");
6902 return hush_main(argc, argv);
6907 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6908 int msh_main(int argc, char **argv)
6910 //bb_error_msg("msh is deprecated, please use hush instead");
6911 return hush_main(argc, argv);
6919 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6924 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
6931 return applet_main_func(argc, argv - argc);
6934 static int FAST_FUNC builtin_test(char **argv)
6936 return run_applet_main(argv, test_main);
6939 static int FAST_FUNC builtin_echo(char **argv)
6941 return run_applet_main(argv, echo_main);
6945 static int FAST_FUNC builtin_printf(char **argv)
6947 return run_applet_main(argv, printf_main);
6951 static int FAST_FUNC builtin_eval(char **argv)
6953 int rcode = EXIT_SUCCESS;
6956 char *str = expand_strvec_to_string(argv);
6958 * eval "echo Hi; done" ("done" is syntax error):
6959 * "echo Hi" will not execute too.
6961 parse_and_run_string(str);
6963 rcode = G.last_exitcode;
6968 static int FAST_FUNC builtin_cd(char **argv)
6970 const char *newdir = argv[1];
6971 if (newdir == NULL) {
6972 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6973 * bash says "bash: cd: HOME not set" and does nothing
6976 const char *home = get_local_var_value("HOME");
6977 newdir = home ? home : "/";
6979 if (chdir(newdir)) {
6980 /* Mimic bash message exactly */
6981 bb_perror_msg("cd: %s", newdir);
6982 return EXIT_FAILURE;
6984 /* Read current dir (get_cwd(1) is inside) and set PWD.
6985 * Note: do not enforce exporting. If PWD was unset or unexported,
6986 * set it again, but do not export. bash does the same.
6988 set_pwd_var(/*exp:*/ 0);
6989 return EXIT_SUCCESS;
6992 static int FAST_FUNC builtin_exec(char **argv)
6994 if (*++argv == NULL)
6995 return EXIT_SUCCESS; /* bash does this */
6997 /* Careful: we can end up here after [v]fork. Do not restore
6998 * tty pgrp then, only top-level shell process does that */
6999 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7000 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7002 /* TODO: if exec fails, bash does NOT exit! We do.
7003 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7004 * and tcsetpgrp, and this is inherently racy.
7006 execvp_or_die(argv);
7009 static int FAST_FUNC builtin_exit(char **argv)
7011 debug_printf_exec("%s()\n", __func__);
7013 /* interactive bash:
7014 * # trap "echo EEE" EXIT
7017 * There are stopped jobs.
7018 * (if there are _stopped_ jobs, running ones don't count)
7021 # EEE (then bash exits)
7023 * we can use G.exiting = -1 as indicator "last cmd was exit"
7026 /* note: EXIT trap is run by hush_exit */
7027 if (*++argv == NULL)
7028 hush_exit(G.last_exitcode);
7029 /* mimic bash: exit 123abc == exit 255 + error msg */
7030 xfunc_error_retval = 255;
7031 /* bash: exit -2 == exit 254, no error msg */
7032 hush_exit(xatoi(*argv) & 0xff);
7035 static void print_escaped(const char *s)
7040 const char *p = strchrnul(s, '\'');
7041 /* print 'xxxx', possibly just '' */
7042 printf("'%.*s'", (int)(p - s), s);
7047 /* s points to '; print "'''...'''" */
7049 do putchar('\''); while (*++s == '\'');
7054 #if !ENABLE_HUSH_LOCAL
7055 #define helper_export_local(argv, exp, lvl) \
7056 helper_export_local(argv, exp)
7058 static void helper_export_local(char **argv, int exp, int lvl)
7063 /* So far we do not check that name is valid (TODO?) */
7065 if (strchr(name, '=') == NULL) {
7066 struct variable *var;
7068 var = get_local_var(name);
7069 if (exp == -1) { /* unexporting? */
7070 /* export -n NAME (without =VALUE) */
7072 var->flg_export = 0;
7073 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7075 } /* else: export -n NOT_EXISTING_VAR: no-op */
7078 if (exp == 1) { /* exporting? */
7079 /* export NAME (without =VALUE) */
7081 var->flg_export = 1;
7082 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7083 putenv(var->varstr);
7087 /* Exporting non-existing variable.
7088 * bash does not put it in environment,
7089 * but remembers that it is exported,
7090 * and does put it in env when it is set later.
7091 * We just set it to "" and export. */
7092 /* Or, it's "local NAME" (without =VALUE).
7093 * bash sets the value to "". */
7094 name = xasprintf("%s=", name);
7096 /* (Un)exporting/making local NAME=VALUE */
7097 name = xstrdup(name);
7099 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7103 static int FAST_FUNC builtin_export(char **argv)
7105 unsigned opt_unexport;
7107 #if ENABLE_HUSH_EXPORT_N
7108 /* "!": do not abort on errors */
7109 opt_unexport = getopt32(argv, "!n");
7110 if (opt_unexport == (uint32_t)-1)
7111 return EXIT_FAILURE;
7118 if (argv[0] == NULL) {
7125 /* ash emits: export VAR='VAL'
7126 * bash: declare -x VAR="VAL"
7127 * we follow ash example */
7128 const char *s = *e++;
7129 const char *p = strchr(s, '=');
7131 if (!p) /* wtf? take next variable */
7134 printf("export %.*s", (int)(p - s) + 1, s);
7135 print_escaped(p + 1);
7139 /*fflush(stdout); - done after each builtin anyway */
7141 return EXIT_SUCCESS;
7144 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7146 return EXIT_SUCCESS;
7149 #if ENABLE_HUSH_LOCAL
7150 static int FAST_FUNC builtin_local(char **argv)
7152 if (G.func_nest_level == 0) {
7153 bb_error_msg("%s: not in a function", argv[0]);
7154 return EXIT_FAILURE; /* bash compat */
7156 helper_export_local(argv, 0, G.func_nest_level);
7157 return EXIT_SUCCESS;
7161 static int FAST_FUNC builtin_trap(char **argv)
7167 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7172 /* No args: print all trapped */
7173 for (i = 0; i < NSIG; ++i) {
7176 print_escaped(G.traps[i]);
7177 /* note: bash adds "SIG", but only if invoked
7178 * as "bash". If called as "sh", or if set -o posix,
7179 * then it prints short signal names.
7180 * We are printing short names: */
7181 printf(" %s\n", get_signame(i));
7184 /*fflush(stdout); - done after each builtin anyway */
7185 return EXIT_SUCCESS;
7189 /* If first arg is a number: reset all specified signals */
7190 sig = bb_strtou(*argv, NULL, 10);
7196 sig = get_signum(*argv++);
7197 if (sig < 0 || sig >= NSIG) {
7199 /* Mimic bash message exactly */
7200 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7205 G.traps[sig] = xstrdup(new_cmd);
7207 debug_printf("trap: setting SIG%s (%i) to '%s'",
7208 get_signame(sig), sig, G.traps[sig]);
7210 /* There is no signal for 0 (EXIT) */
7215 sigaddset(&G.blocked_set, sig);
7217 /* There was a trap handler, we are removing it
7218 * (if sig has non-DFL handling,
7219 * we don't need to do anything) */
7220 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7222 sigdelset(&G.blocked_set, sig);
7225 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7229 if (!argv[1]) { /* no second arg */
7230 bb_error_msg("trap: invalid arguments");
7231 return EXIT_FAILURE;
7234 /* First arg is "-": reset all specified to default */
7235 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7236 /* Everything else: set arg as signal handler
7237 * (includes "" case, which ignores signal) */
7238 if (argv[0][0] == '-') {
7239 if (argv[0][1] == '\0') { /* "-" */
7240 /* new_cmd remains NULL: "reset these sigs" */
7243 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7246 /* else: "-something", no special meaning */
7251 goto process_sig_list;
7254 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7255 static int FAST_FUNC builtin_type(char **argv)
7257 int ret = EXIT_SUCCESS;
7263 if (0) {} /* make conditional compile easier below */
7264 /*else if (find_alias(*argv))
7265 type = "an alias";*/
7266 #if ENABLE_HUSH_FUNCTIONS
7267 else if (find_function(*argv))
7268 type = "a function";
7270 else if (find_builtin(*argv))
7271 type = "a shell builtin";
7272 else if ((path = find_in_path(*argv)) != NULL)
7275 bb_error_msg("type: %s: not found", *argv);
7280 printf("%s is %s\n", *argv, type);
7288 /* built-in 'fg' and 'bg' handler */
7289 static int FAST_FUNC builtin_fg_bg(char **argv)
7294 if (!G_interactive_fd)
7295 return EXIT_FAILURE;
7297 /* If they gave us no args, assume they want the last backgrounded task */
7299 for (pi = G.job_list; pi; pi = pi->next) {
7300 if (pi->jobid == G.last_jobid) {
7304 bb_error_msg("%s: no current job", argv[0]);
7305 return EXIT_FAILURE;
7307 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7308 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7309 return EXIT_FAILURE;
7311 for (pi = G.job_list; pi; pi = pi->next) {
7312 if (pi->jobid == jobnum) {
7316 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7317 return EXIT_FAILURE;
7319 /* TODO: bash prints a string representation
7320 * of job being foregrounded (like "sleep 1 | cat") */
7321 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7322 /* Put the job into the foreground. */
7323 tcsetpgrp(G_interactive_fd, pi->pgrp);
7326 /* Restart the processes in the job */
7327 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7328 for (i = 0; i < pi->num_cmds; i++) {
7329 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7330 pi->cmds[i].is_stopped = 0;
7332 pi->stopped_cmds = 0;
7334 i = kill(- pi->pgrp, SIGCONT);
7336 if (errno == ESRCH) {
7337 delete_finished_bg_job(pi);
7338 return EXIT_SUCCESS;
7340 bb_perror_msg("kill (SIGCONT)");
7343 if (argv[0][0] == 'f') {
7345 return checkjobs_and_fg_shell(pi);
7347 return EXIT_SUCCESS;
7351 #if ENABLE_HUSH_HELP
7352 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7354 const struct built_in_command *x;
7357 "Built-in commands:\n"
7358 "------------------\n");
7359 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7361 printf("%s\t%s\n", x->cmd, x->descr);
7364 return EXIT_SUCCESS;
7369 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7372 const char *status_string;
7374 for (job = G.job_list; job; job = job->next) {
7375 if (job->alive_cmds == job->stopped_cmds)
7376 status_string = "Stopped";
7378 status_string = "Running";
7380 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7382 return EXIT_SUCCESS;
7387 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7392 # ifdef M_TRIM_THRESHOLD
7393 /* Optional. Reduces probability of false positives */
7396 /* Crude attempt to find where "free memory" starts,
7397 * sans fragmentation. */
7399 l = (unsigned long)p;
7402 if (l < (unsigned long)p) l = (unsigned long)p;
7405 if (!G.memleak_value)
7406 G.memleak_value = l;
7408 l -= G.memleak_value;
7415 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7420 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7423 return EXIT_SUCCESS;
7426 static int FAST_FUNC builtin_read(char **argv)
7429 const char *name = "REPLY";
7433 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7434 * and _after_ that_ it will complain */
7435 if (!is_well_formed_var_name(name, '\0')) {
7436 /* Mimic bash message */
7437 bb_error_msg("read: '%s': not a valid identifier", name);
7442 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7444 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7445 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7448 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7449 * built-in 'set' handler
7451 * set [-abCefhmnuvx] [-o option] [argument...]
7452 * set [+abCefhmnuvx] [+o option] [argument...]
7453 * set -- [argument...]
7456 * Implementations shall support the options in both their hyphen and
7457 * plus-sign forms. These options can also be specified as options to sh.
7459 * Write out all variables and their values: set
7460 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7461 * Turn on the -x and -v options: set -xv
7462 * Unset all positional parameters: set --
7463 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7464 * Set the positional parameters to the expansion of x, even if x expands
7465 * with a leading '-' or '+': set -- $x
7467 * So far, we only support "set -- [argument...]" and some of the short names.
7469 static int FAST_FUNC builtin_set(char **argv)
7472 char **pp, **g_argv;
7473 char *arg = *++argv;
7477 for (e = G.top_var; e; e = e->next)
7479 return EXIT_SUCCESS;
7483 if (!strcmp(arg, "--")) {
7487 if (arg[0] != '+' && arg[0] != '-')
7489 for (n = 1; arg[n]; ++n)
7490 if (set_mode(arg[0], arg[n]))
7492 } while ((arg = *++argv) != NULL);
7493 /* Now argv[0] is 1st argument */
7496 return EXIT_SUCCESS;
7499 /* NB: G.global_argv[0] ($0) is never freed/changed */
7500 g_argv = G.global_argv;
7501 if (G.global_args_malloced) {
7507 G.global_args_malloced = 1;
7508 pp = xzalloc(sizeof(pp[0]) * 2);
7509 pp[0] = g_argv[0]; /* retain $0 */
7512 /* This realloc's G.global_argv */
7513 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7520 return EXIT_SUCCESS;
7522 /* Nothing known, so abort */
7524 bb_error_msg("set: %s: invalid option", arg);
7525 return EXIT_FAILURE;
7528 static int FAST_FUNC builtin_shift(char **argv)
7534 if (n >= 0 && n < G.global_argc) {
7535 if (G.global_args_malloced) {
7538 free(G.global_argv[m++]);
7541 memmove(&G.global_argv[1], &G.global_argv[n+1],
7542 G.global_argc * sizeof(G.global_argv[0]));
7543 return EXIT_SUCCESS;
7545 return EXIT_FAILURE;
7548 static int FAST_FUNC builtin_source(char **argv)
7553 #if ENABLE_HUSH_FUNCTIONS
7557 if (*++argv == NULL)
7558 return EXIT_FAILURE;
7560 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7561 input = fopen_for_read(arg_path);
7564 input = fopen_or_warn(*argv, "r");
7566 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7567 return EXIT_FAILURE;
7569 close_on_exec_on(fileno(input));
7571 #if ENABLE_HUSH_FUNCTIONS
7572 sv_flg = G.flag_return_in_progress;
7573 /* "we are inside sourced file, ok to use return" */
7574 G.flag_return_in_progress = -1;
7576 save_and_replace_G_args(&sv, argv);
7578 parse_and_run_file(input);
7581 restore_G_args(&sv, argv);
7582 #if ENABLE_HUSH_FUNCTIONS
7583 G.flag_return_in_progress = sv_flg;
7586 return G.last_exitcode;
7589 static int FAST_FUNC builtin_umask(char **argv)
7596 mode_t old_mask = mask;
7599 rc = bb_parse_mode(argv[1], &mask);
7604 * bash: umask: 'q': invalid symbolic mode operator
7605 * bash: umask: 999: octal number out of range
7607 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7612 printf("%04o\n", (unsigned) mask);
7613 /* fall through and restore mask which we set to 0 */
7617 return !rc; /* rc != 0 - success */
7620 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7621 static int FAST_FUNC builtin_unset(char **argv)
7626 /* "!": do not abort on errors */
7627 /* "+": stop at 1st non-option */
7628 opts = getopt32(argv, "!+vf");
7629 if (opts == (unsigned)-1)
7630 return EXIT_FAILURE;
7632 bb_error_msg("unset: -v and -f are exclusive");
7633 return EXIT_FAILURE;
7639 if (!(opts & 2)) { /* not -f */
7640 if (unset_local_var(*argv)) {
7641 /* unset <nonexistent_var> doesn't fail.
7642 * Error is when one tries to unset RO var.
7643 * Message was printed by unset_local_var. */
7647 #if ENABLE_HUSH_FUNCTIONS
7657 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7658 static int FAST_FUNC builtin_wait(char **argv)
7660 int ret = EXIT_SUCCESS;
7663 if (*++argv == NULL) {
7664 /* Don't care about wait results */
7665 /* Note 1: must wait until there are no more children */
7666 /* Note 2: must be interruptible */
7668 * $ sleep 3 & sleep 6 & wait
7673 * $ sleep 3 & sleep 6 & wait
7677 * ^C <-- after ~4 sec from keyboard
7680 sigaddset(&G.blocked_set, SIGCHLD);
7681 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7684 if (errno == ECHILD)
7686 /* Wait for SIGCHLD or any other signal of interest */
7687 /* sigtimedwait with infinite timeout: */
7688 sig = sigwaitinfo(&G.blocked_set, NULL);
7690 sig = check_and_run_traps(sig);
7691 if (sig && sig != SIGCHLD) { /* see note 2 */
7697 sigdelset(&G.blocked_set, SIGCHLD);
7698 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7702 /* This is probably buggy wrt interruptible-ness */
7704 pid_t pid = bb_strtou(*argv, NULL, 10);
7706 /* mimic bash message */
7707 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7708 return EXIT_FAILURE;
7710 if (waitpid(pid, &status, 0) == pid) {
7711 if (WIFSIGNALED(status))
7712 ret = 128 + WTERMSIG(status);
7713 else if (WIFEXITED(status))
7714 ret = WEXITSTATUS(status);
7718 bb_perror_msg("wait %s", *argv);
7727 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7728 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7731 def = bb_strtou(argv[1], NULL, 10);
7732 if (errno || def < def_min || argv[2]) {
7733 bb_error_msg("%s: bad arguments", argv[0]);
7741 #if ENABLE_HUSH_LOOPS
7742 static int FAST_FUNC builtin_break(char **argv)
7745 if (G.depth_of_loop == 0) {
7746 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7747 return EXIT_SUCCESS; /* bash compat */
7749 G.flag_break_continue++; /* BC_BREAK = 1 */
7751 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7752 if (depth == UINT_MAX)
7753 G.flag_break_continue = BC_BREAK;
7754 if (G.depth_of_loop < depth)
7755 G.depth_break_continue = G.depth_of_loop;
7757 return EXIT_SUCCESS;
7760 static int FAST_FUNC builtin_continue(char **argv)
7762 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7763 return builtin_break(argv);
7767 #if ENABLE_HUSH_FUNCTIONS
7768 static int FAST_FUNC builtin_return(char **argv)
7772 if (G.flag_return_in_progress != -1) {
7773 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7774 return EXIT_FAILURE; /* bash compat */
7777 G.flag_return_in_progress = 1;
7780 * out of range: wraps around at 256, does not error out
7781 * non-numeric param:
7782 * f() { false; return qwe; }; f; echo $?
7783 * bash: return: qwe: numeric argument required <== we do this
7784 * 255 <== we also do this
7786 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);