1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
45 * Bash stuff (maybe optionally enable?):
46 * &> and >& redirection of stdout+stderr
48 * reserved words: [[ ]] function select
49 * substrings ${var:1:5}
52 * grep for "TODO" and fix (some of them are easy)
54 * follow IFS rules more precisely, including update semantics
55 * export builtin should be special, its arguments are assignments
56 * and therefore expansion of them should be "one-word" expansion:
57 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
59 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
60 * ls: cannot access i=a: No such file or directory
61 * ls: cannot access b: No such file or directory
62 * Note1: same applies to local builtin when we'll have it.
63 * Note2: bash 3.2.33(1) does this only if export word itself
65 * $ export i=`echo 'aaa bbb'`; echo "$i"
67 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
70 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
72 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
74 /* #include <dmalloc.h> */
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
86 #define LEAK_HUNTING 0
87 #define BUILD_AS_NOMMU 0
88 /* Enable/disable sanity checks. Ok to enable in production,
89 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
90 * Keeping 1 for now even in released versions.
93 /* Slightly bigger (+200 bytes), but faster hush.
94 * So far it only enables a trick with counting SIGCHLDs and forks,
95 * which allows us to do fewer waitpid's.
96 * (we can detect a case where neither forks were done nor SIGCHLDs happened
97 * and therefore waitpid will return the same result as last time)
99 #define ENABLE_HUSH_FAST 0
104 # undef USE_FOR_NOMMU
107 # define USE_FOR_NOMMU(...) __VA_ARGS__
108 # define USE_FOR_MMU(...)
111 #if defined SINGLE_APPLET_MAIN
112 /* STANDALONE does not make sense, and won't compile */
113 # undef CONFIG_FEATURE_SH_STANDALONE
114 # undef ENABLE_FEATURE_SH_STANDALONE
115 # undef IF_FEATURE_SH_STANDALONE
116 # define IF_FEATURE_SH_STANDALONE(...)
117 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
118 # define ENABLE_FEATURE_SH_STANDALONE 0
121 #if !ENABLE_HUSH_INTERACTIVE
122 # undef ENABLE_FEATURE_EDITING
123 # define ENABLE_FEATURE_EDITING 0
124 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
125 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
128 /* Do we support ANY keywords? */
129 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
130 # define HAS_KEYWORDS 1
131 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
132 # define IF_HAS_NO_KEYWORDS(...)
134 # define HAS_KEYWORDS 0
135 # define IF_HAS_KEYWORDS(...)
136 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
139 /* If you comment out one of these below, it will be #defined later
140 * to perform debug printfs to stderr: */
141 #define debug_printf(...) do {} while (0)
142 /* Finer-grained debug switches */
143 #define debug_printf_parse(...) do {} while (0)
144 #define debug_print_tree(a, b) do {} while (0)
145 #define debug_printf_exec(...) do {} while (0)
146 #define debug_printf_env(...) do {} while (0)
147 #define debug_printf_jobs(...) do {} while (0)
148 #define debug_printf_expand(...) do {} while (0)
149 #define debug_printf_glob(...) do {} while (0)
150 #define debug_printf_list(...) do {} while (0)
151 #define debug_printf_subst(...) do {} while (0)
152 #define debug_printf_clean(...) do {} while (0)
154 #define ERR_PTR ((void*)(long)1)
156 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
158 #define SPECIAL_VAR_SYMBOL 3
162 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
164 /* This supports saving pointers malloced in vfork child,
165 * to be freed in the parent.
168 typedef struct nommu_save_t {
170 struct variable *old_vars;
172 char **argv_from_re_execing;
176 /* The descrip member of this structure is only used to make
177 * debugging output pretty */
178 static const struct {
180 signed char default_fd;
184 { O_RDONLY, 0, "<" },
185 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
186 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
187 { O_RDONLY, 0, "<<" },
188 { O_CREAT|O_RDWR, 1, "<>" },
189 /* Should not be needed. Bogus default_fd helps in debugging */
190 /* { O_RDONLY, 77, "<<" }, */
193 typedef enum reserved_style {
202 #if ENABLE_HUSH_LOOPS
209 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
214 /* three pseudo-keywords support contrived "case" syntax: */
215 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
216 RES_MATCH , /* "word)" */
217 RES_CASE_BODY, /* "this command is inside CASE" */
224 typedef struct o_string {
226 int length; /* position where data is appended */
228 /* Protect newly added chars against globbing
229 * (by prepending \ to *, ?, [, \) */
232 /* At least some part of the string was inside '' or "",
233 * possibly empty one: word"", wo''rd etc. */
235 smallint has_empty_slot;
236 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
239 MAYBE_ASSIGNMENT = 0,
240 DEFINITELY_ASSIGNMENT = 1,
242 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
244 /* Used for initialization: o_string foo = NULL_O_STRING; */
245 #define NULL_O_STRING { NULL }
247 /* I can almost use ordinary FILE*. Is open_memstream() universally
248 * available? Where is it documented? */
249 typedef struct in_str {
251 /* eof_flag=1: last char in ->p is really an EOF */
252 char eof_flag; /* meaningless if ->p == NULL */
254 #if ENABLE_HUSH_INTERACTIVE
256 smallint promptmode; /* 0: PS1, 1: PS2 */
259 int (*get) (struct in_str *) FAST_FUNC;
260 int (*peek) (struct in_str *) FAST_FUNC;
262 #define i_getch(input) ((input)->get(input))
263 #define i_peek(input) ((input)->peek(input))
265 struct redir_struct {
266 struct redir_struct *next;
267 char *rd_filename; /* filename */
268 int rd_fd; /* fd to redirect */
269 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
271 smallint rd_type; /* (enum redir_type) */
272 /* note: for heredocs, rd_filename contains heredoc delimiter,
273 * and subsequently heredoc itself; and rd_dup is a bitmask:
274 * 1: do we need to trim leading tabs?
275 * 2: is heredoc quoted (<<'delim' syntax) ?
278 typedef enum redir_type {
279 REDIRECT_INVALID = 0,
281 REDIRECT_OVERWRITE = 2,
283 REDIRECT_HEREDOC = 4,
285 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
288 REDIRFD_SYNTAX_ERR = -2,
289 REDIRFD_TO_FILE = -1,
290 /* otherwise, rd_fd is redirected to rd_dup */
292 HEREDOC_SKIPTABS = 1,
298 pid_t pid; /* 0 if exited */
299 int assignment_cnt; /* how many argv[i] are assignments? */
300 smallint is_stopped; /* is the command currently running? */
301 smallint grp_type; /* GRP_xxx */
303 #define GRP_SUBSHELL 1
304 #if ENABLE_HUSH_FUNCTIONS
305 # define GRP_FUNCTION 2
307 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
310 char *group_as_string;
312 #if ENABLE_HUSH_FUNCTIONS
313 struct function *child_func;
314 /* This field is used to prevent a bug here:
315 * while...do f1() {a;}; f1; f1 {b;}; f1; done
316 * When we execute "f1() {a;}" cmd, we create new function and clear
317 * cmd->group, cmd->group_as_string, cmd->argv[0].
318 * when we execute "f1 {b;}", we notice that f1 exists,
319 * and that it's "parent cmd" struct is still "alive",
320 * we put those fields back into cmd->xxx
321 * (struct function has ->parent_cmd ptr to facilitate that).
322 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
323 * Without this trick, loop would execute a;b;b;b;...
324 * instead of correct sequence a;b;a;b;...
325 * When command is freed, it severs the link
326 * (sets ->child_func->parent_cmd to NULL).
329 char **argv; /* command name and arguments */
330 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
331 * and on execution these are substituted with their values.
332 * Substitution can make _several_ words out of one argv[n]!
333 * Example: argv[0]=='.^C*^C.' here: echo .$*.
334 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
336 struct redir_struct *redirects; /* I/O redirections */
338 /* Is there anything in this command at all? */
339 #define IS_NULL_CMD(cmd) \
340 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
345 int num_cmds; /* total number of commands in pipe */
346 int alive_cmds; /* number of commands running (not exited) */
347 int stopped_cmds; /* number of commands alive, but stopped */
349 int jobid; /* job number */
350 pid_t pgrp; /* process group ID for the job */
351 char *cmdtext; /* name of job */
353 struct command *cmds; /* array of commands in pipe */
354 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
355 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
356 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
358 typedef enum pipe_style {
364 /* Is there anything in this pipe at all? */
365 #define IS_NULL_PIPE(pi) \
366 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
368 /* This holds pointers to the various results of parsing */
369 struct parse_context {
370 /* linked list of pipes */
371 struct pipe *list_head;
372 /* last pipe (being constructed right now) */
374 /* last command in pipe (being constructed right now) */
375 struct command *command;
376 /* last redirect in command->redirects list */
377 struct redir_struct *pending_redirect;
383 smallint ctx_inverted; /* "! cmd | cmd" */
385 smallint ctx_dsemicolon; /* ";;" seen */
387 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
389 /* group we are enclosed in:
390 * example: "if pipe1; pipe2; then pipe3; fi"
391 * when we see "if" or "then", we malloc and copy current context,
392 * and make ->stack point to it. then we parse pipeN.
393 * when closing "then" / fi" / whatever is found,
394 * we move list_head into ->stack->command->group,
395 * copy ->stack into current context, and delete ->stack.
396 * (parsing of { list } and ( list ) doesn't use this method)
398 struct parse_context *stack;
402 /* On program start, environ points to initial environment.
403 * putenv adds new pointers into it, unsetenv removes them.
404 * Neither of these (de)allocates the strings.
405 * setenv allocates new strings in malloc space and does putenv,
406 * and thus setenv is unusable (leaky) for shell's purposes */
407 #define setenv(...) setenv_is_leaky_dont_use()
409 struct variable *next;
410 char *varstr; /* points to "name=" portion */
411 #if ENABLE_HUSH_LOCAL
412 unsigned func_nest_level;
414 int max_len; /* if > 0, name is part of initial env; else name is malloced */
415 smallint flg_export; /* putenv should be done on this var */
416 smallint flg_read_only;
424 #if ENABLE_HUSH_FUNCTIONS
426 struct function *next;
428 struct command *parent_cmd;
431 char *body_as_string;
437 /* "Globals" within this file */
438 /* Sorted roughly by size (smaller offsets == smaller code) */
440 /* interactive_fd != 0 means we are an interactive shell.
441 * If we are, then saved_tty_pgrp can also be != 0, meaning
442 * that controlling tty is available. With saved_tty_pgrp == 0,
443 * job control still works, but terminal signals
444 * (^C, ^Z, ^Y, ^\) won't work at all, and background
445 * process groups can only be created with "cmd &".
446 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
447 * to give tty to the foreground process group,
448 * and will take it back when the group is stopped (^Z)
451 #if ENABLE_HUSH_INTERACTIVE
452 /* 'interactive_fd' is a fd# open to ctty, if we have one
453 * _AND_ if we decided to act interactively */
457 # define G_interactive_fd (G.interactive_fd)
459 # define G_interactive_fd 0
461 #if ENABLE_FEATURE_EDITING
462 line_input_t *line_input_state;
469 pid_t saved_tty_pgrp;
470 struct pipe *job_list;
471 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
473 # define G_saved_tty_pgrp 0
475 smallint flag_SIGINT;
476 #if ENABLE_HUSH_LOOPS
477 smallint flag_break_continue;
479 #if ENABLE_HUSH_FUNCTIONS
480 /* 0: outside of a function (or sourced file)
481 * -1: inside of a function, ok to use return builtin
482 * 1: return is invoked, skip all till end of func
484 smallint flag_return_in_progress;
487 smallint exiting; /* used to prevent EXIT trap recursion */
488 /* These four support $?, $#, and $1 */
489 smalluint last_exitcode;
490 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
491 smalluint global_args_malloced;
492 /* how many non-NULL argv's we have. NB: $# + 1 */
496 char *argv0_for_re_execing;
498 #if ENABLE_HUSH_LOOPS
499 unsigned depth_break_continue;
500 unsigned depth_of_loop;
504 struct variable *top_var; /* = &G.shell_ver (set in main()) */
505 struct variable shell_ver;
506 #if ENABLE_HUSH_FUNCTIONS
507 struct function *top_func;
508 # if ENABLE_HUSH_LOCAL
509 struct variable **shadowed_vars_pp;
510 unsigned func_nest_level;
513 /* Signal and trap handling */
515 unsigned count_SIGCHLD;
516 unsigned handled_SIGCHLD;
517 smallint we_have_children;
519 /* which signals have non-DFL handler (even with no traps set)? */
520 unsigned non_DFL_mask;
521 char **traps; /* char *traps[NSIG] */
522 sigset_t blocked_set;
523 sigset_t inherited_set;
525 unsigned long memleak_value;
528 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
530 #define G (*ptr_to_globals)
531 /* Not #defining name to G.name - this quickly gets unwieldy
532 * (too many defines). Also, I actually prefer to see when a variable
533 * is global, thus "G." prefix is a useful hint */
534 #define INIT_G() do { \
535 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
539 /* Function prototypes for builtins */
540 static int builtin_cd(char **argv) FAST_FUNC;
541 static int builtin_echo(char **argv) FAST_FUNC;
542 static int builtin_eval(char **argv) FAST_FUNC;
543 static int builtin_exec(char **argv) FAST_FUNC;
544 static int builtin_exit(char **argv) FAST_FUNC;
545 static int builtin_export(char **argv) FAST_FUNC;
547 static int builtin_fg_bg(char **argv) FAST_FUNC;
548 static int builtin_jobs(char **argv) FAST_FUNC;
551 static int builtin_help(char **argv) FAST_FUNC;
553 #if ENABLE_HUSH_LOCAL
554 static int builtin_local(char **argv) FAST_FUNC;
557 static int builtin_memleak(char **argv) FAST_FUNC;
559 static int builtin_pwd(char **argv) FAST_FUNC;
560 static int builtin_read(char **argv) FAST_FUNC;
561 static int builtin_set(char **argv) FAST_FUNC;
562 static int builtin_shift(char **argv) FAST_FUNC;
563 static int builtin_source(char **argv) FAST_FUNC;
564 static int builtin_test(char **argv) FAST_FUNC;
565 static int builtin_trap(char **argv) FAST_FUNC;
566 static int builtin_type(char **argv) FAST_FUNC;
567 static int builtin_true(char **argv) FAST_FUNC;
568 static int builtin_umask(char **argv) FAST_FUNC;
569 static int builtin_unset(char **argv) FAST_FUNC;
570 static int builtin_wait(char **argv) FAST_FUNC;
571 #if ENABLE_HUSH_LOOPS
572 static int builtin_break(char **argv) FAST_FUNC;
573 static int builtin_continue(char **argv) FAST_FUNC;
575 #if ENABLE_HUSH_FUNCTIONS
576 static int builtin_return(char **argv) FAST_FUNC;
579 /* Table of built-in functions. They can be forked or not, depending on
580 * context: within pipes, they fork. As simple commands, they do not.
581 * When used in non-forking context, they can change global variables
582 * in the parent shell process. If forked, of course they cannot.
583 * For example, 'unset foo | whatever' will parse and run, but foo will
584 * still be set at the end. */
585 struct built_in_command {
587 int (*function)(char **argv) FAST_FUNC;
590 # define BLTIN(cmd, func, help) { cmd, func, help }
592 # define BLTIN(cmd, func, help) { cmd, func }
596 static const struct built_in_command bltins1[] = {
597 BLTIN("." , builtin_source , "Run commands in a file"),
598 BLTIN(":" , builtin_true , NULL),
600 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
602 #if ENABLE_HUSH_LOOPS
603 BLTIN("break" , builtin_break , "Exit from a loop"),
605 BLTIN("cd" , builtin_cd , "Change directory"),
606 #if ENABLE_HUSH_LOOPS
607 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
609 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
610 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
611 BLTIN("exit" , builtin_exit , "Exit"),
612 BLTIN("export" , builtin_export , "Set environment variables"),
614 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
617 BLTIN("help" , builtin_help , NULL),
620 BLTIN("jobs" , builtin_jobs , "List jobs"),
622 #if ENABLE_HUSH_LOCAL
623 BLTIN("local" , builtin_local , "Set local variables"),
626 BLTIN("memleak" , builtin_memleak , NULL),
628 BLTIN("read" , builtin_read , "Input into variable"),
629 #if ENABLE_HUSH_FUNCTIONS
630 BLTIN("return" , builtin_return , "Return from a function"),
632 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
633 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
634 BLTIN("trap" , builtin_trap , "Trap signals"),
635 BLTIN("type" , builtin_type , "Write a description of command type"),
636 // BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
637 BLTIN("umask" , builtin_umask , "Set file creation mask"),
638 BLTIN("unset" , builtin_unset , "Unset variables"),
639 BLTIN("wait" , builtin_wait , "Wait for process"),
641 /* For now, echo and test are unconditionally enabled.
642 * Maybe make it configurable? */
643 static const struct built_in_command bltins2[] = {
644 BLTIN("[" , builtin_test , NULL),
645 BLTIN("echo" , builtin_echo , NULL),
646 BLTIN("pwd" , builtin_pwd , NULL),
647 BLTIN("test" , builtin_test , NULL),
654 /* prevent disasters with G.debug_indent < 0 */
655 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
656 # define debug_enter() (G.debug_indent++)
657 # define debug_leave() (G.debug_indent--)
659 # define indent() ((void)0)
660 # define debug_enter() ((void)0)
661 # define debug_leave() ((void)0)
665 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
668 #ifndef debug_printf_parse
669 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
672 #ifndef debug_printf_exec
673 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
676 #ifndef debug_printf_env
677 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
680 #ifndef debug_printf_jobs
681 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
682 # define DEBUG_JOBS 1
684 # define DEBUG_JOBS 0
687 #ifndef debug_printf_expand
688 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
689 # define DEBUG_EXPAND 1
691 # define DEBUG_EXPAND 0
694 #ifndef debug_printf_glob
695 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
696 # define DEBUG_GLOB 1
698 # define DEBUG_GLOB 0
701 #ifndef debug_printf_list
702 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
705 #ifndef debug_printf_subst
706 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
709 #ifndef debug_printf_clean
710 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
711 # define DEBUG_CLEAN 1
713 # define DEBUG_CLEAN 0
717 static void debug_print_strings(const char *prefix, char **vv)
720 fprintf(stderr, "%s:\n", prefix);
722 fprintf(stderr, " '%s'\n", *vv++);
725 # define debug_print_strings(prefix, vv) ((void)0)
729 /* Leak hunting. Use hush_leaktool.sh for post-processing.
732 static void *xxmalloc(int lineno, size_t size)
734 void *ptr = xmalloc((size + 0xff) & ~0xff);
735 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
738 static void *xxrealloc(int lineno, void *ptr, size_t size)
740 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
741 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
744 static char *xxstrdup(int lineno, const char *str)
746 char *ptr = xstrdup(str);
747 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
750 static void xxfree(void *ptr)
752 fdprintf(2, "free %p\n", ptr);
755 #define xmalloc(s) xxmalloc(__LINE__, s)
756 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
757 #define xstrdup(s) xxstrdup(__LINE__, s)
758 #define free(p) xxfree(p)
762 /* Syntax and runtime errors. They always abort scripts.
763 * In interactive use they usually discard unparsed and/or unexecuted commands
764 * and return to the prompt.
765 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
768 # define die_if_script(lineno, fmt...) die_if_script(fmt)
769 # define syntax_error(lineno, msg) syntax_error(msg)
770 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
771 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
772 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
773 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
776 static void die_if_script(unsigned lineno, const char *fmt, ...)
781 bb_error_msg("hush.c:%u", lineno);
784 bb_verror_msg(fmt, p, NULL);
786 if (!G_interactive_fd)
790 static void syntax_error(unsigned lineno, const char *msg)
793 die_if_script(lineno, "syntax error: %s", msg);
795 die_if_script(lineno, "syntax error", NULL);
798 static void syntax_error_at(unsigned lineno, const char *msg)
800 die_if_script(lineno, "syntax error at '%s'", msg);
803 static void syntax_error_unterm_str(unsigned lineno, const char *s)
805 die_if_script(lineno, "syntax error: unterminated %s", s);
808 /* It so happens that all such cases are totally fatal
809 * even if shell is interactive: EOF while looking for closing
810 * delimiter. There is nowhere to read stuff from after that,
811 * it's EOF! The only choice is to terminate.
813 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
814 static void syntax_error_unterm_ch(unsigned lineno, char ch)
816 char msg[2] = { ch, '\0' };
817 syntax_error_unterm_str(lineno, msg);
821 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
826 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
830 # undef die_if_script
832 # undef syntax_error_at
833 # undef syntax_error_unterm_ch
834 # undef syntax_error_unterm_str
835 # undef syntax_error_unexpected_ch
837 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
838 # define syntax_error(msg) syntax_error(__LINE__, msg)
839 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
840 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
841 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
842 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
846 #if ENABLE_HUSH_INTERACTIVE
847 static void cmdedit_update_prompt(void);
849 # define cmdedit_update_prompt() ((void)0)
855 static int glob_needed(const char *s)
860 if (*s == '*' || *s == '[' || *s == '?')
867 static int is_well_formed_var_name(const char *s, char terminator)
869 if (!s || !(isalpha(*s) || *s == '_'))
872 while (isalnum(*s) || *s == '_')
874 return *s == terminator;
877 /* Replace each \x with x in place, return ptr past NUL. */
878 static char *unbackslash(char *src)
884 if ((*dst++ = *src++) == '\0')
890 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
911 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
912 v[count1 + count2] = NULL;
915 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
919 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
921 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
922 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
925 #define add_strings_to_strings(strings, add, need_to_dup) \
926 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
929 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
930 static char **add_string_to_strings(char **strings, char *add)
935 return add_strings_to_strings(strings, v, /*dup:*/ 0);
938 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
940 char **ptr = add_string_to_strings(strings, add);
941 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
944 #define add_string_to_strings(strings, add) \
945 xx_add_string_to_strings(__LINE__, strings, add)
948 static void free_strings(char **strings)
963 /* Helpers for setting new $n and restoring them back
965 typedef struct save_arg_t {
969 smallint sv_g_malloced;
972 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
976 sv->sv_argv0 = argv[0];
977 sv->sv_g_argv = G.global_argv;
978 sv->sv_g_argc = G.global_argc;
979 sv->sv_g_malloced = G.global_args_malloced;
981 argv[0] = G.global_argv[0]; /* retain $0 */
982 G.global_argv = argv;
983 G.global_args_malloced = 0;
991 static void restore_G_args(save_arg_t *sv, char **argv)
995 if (G.global_args_malloced) {
996 /* someone ran "set -- arg1 arg2 ...", undo */
998 while (*++pp) /* note: does not free $0 */
1000 free(G.global_argv);
1002 argv[0] = sv->sv_argv0;
1003 G.global_argv = sv->sv_g_argv;
1004 G.global_argc = sv->sv_g_argc;
1005 G.global_args_malloced = sv->sv_g_malloced;
1009 /* Basic theory of signal handling in shell
1010 * ========================================
1011 * This does not describe what hush does, rather, it is current understanding
1012 * what it _should_ do. If it doesn't, it's a bug.
1013 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1015 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1016 * is finished or backgrounded. It is the same in interactive and
1017 * non-interactive shells, and is the same regardless of whether
1018 * a user trap handler is installed or a shell special one is in effect.
1019 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1020 * backgrounds (i.e. stops) or kills all members of currently running
1023 * Wait builtin in interruptible by signals for which user trap is set
1024 * or by SIGINT in interactive shell.
1026 * Trap handlers will execute even within trap handlers. (right?)
1028 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1030 * If job control is off, backgrounded commands ("cmd &")
1031 * have SIGINT, SIGQUIT set to SIG_IGN.
1033 * Commands which are run in command substitution ("`cmd`")
1034 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1036 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1037 * by the shell from its parent.
1039 * Signals which differ from SIG_DFL action
1040 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1043 * SIGTERM (interactive): ignore
1044 * SIGHUP (interactive):
1045 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1046 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1047 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1048 * that all pipe members are stopped. Try this in bash:
1049 * while :; do :; done - ^Z does not background it
1050 * (while :; do :; done) - ^Z backgrounds it
1051 * SIGINT (interactive): wait for last pipe, ignore the rest
1052 * of the command line, show prompt. NB: ^C does not send SIGINT
1053 * to interactive shell while shell is waiting for a pipe,
1054 * since shell is bg'ed (is not in foreground process group).
1055 * Example 1: this waits 5 sec, but does not execute ls:
1056 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1057 * Example 2: this does not wait and does not execute ls:
1058 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1059 * Example 3: this does not wait 5 sec, but executes ls:
1060 * "sleep 5; ls -l" + press ^C
1062 * (What happens to signals which are IGN on shell start?)
1063 * (What happens with signal mask on shell start?)
1065 * Implementation in hush
1066 * ======================
1067 * We use in-kernel pending signal mask to determine which signals were sent.
1068 * We block all signals which we don't want to take action immediately,
1069 * i.e. we block all signals which need to have special handling as described
1070 * above, and all signals which have traps set.
1071 * After each pipe execution, we extract any pending signals via sigtimedwait()
1074 * unsigned non_DFL_mask: a mask of such "special" signals
1075 * sigset_t blocked_set: current blocked signal set
1078 * clear bit in blocked_set unless it is also in non_DFL_mask
1079 * "trap 'cmd' SIGxxx":
1080 * set bit in blocked_set (even if 'cmd' is '')
1081 * after [v]fork, if we plan to be a shell:
1082 * unblock signals with special interactive handling
1083 * (child shell is not interactive),
1084 * unset all traps (note: regardless of child shell's type - {}, (), etc)
1085 * after [v]fork, if we plan to exec:
1086 * POSIX says pending signal mask is cleared in child - no need to clear it.
1087 * Restore blocked signal set to one inherited by shell just prior to exec.
1089 * Note: as a result, we do not use signal handlers much. The only uses
1090 * are to count SIGCHLDs
1091 * and to restore tty pgrp on signal-induced exit.
1094 SPECIAL_INTERACTIVE_SIGS = 0
1099 SPECIAL_JOB_SIGS = 0
1107 #if ENABLE_HUSH_FAST
1108 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1111 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1117 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1118 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1119 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1120 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1122 /* Restores tty foreground process group, and exits.
1123 * May be called as signal handler for fatal signal
1124 * (will resend signal to itself, producing correct exit state)
1125 * or called directly with -EXITCODE.
1126 * We also call it if xfunc is exiting. */
1127 static void sigexit(int sig) NORETURN;
1128 static void sigexit(int sig)
1130 /* Disable all signals: job control, SIGPIPE, etc. */
1131 sigprocmask_allsigs(SIG_BLOCK);
1133 /* Careful: we can end up here after [v]fork. Do not restore
1134 * tty pgrp then, only top-level shell process does that */
1135 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1136 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1138 /* Not a signal, just exit */
1142 kill_myself_with_sig(sig); /* does not return */
1146 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1147 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1151 /* Restores tty foreground process group, and exits. */
1152 static void hush_exit(int exitcode) NORETURN;
1153 static void hush_exit(int exitcode)
1155 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1156 /* Prevent recursion:
1157 * trap "echo Hi; exit" EXIT; exit
1159 char *argv[] = { NULL, G.traps[0], NULL };
1167 fflush(NULL); /* flush all streams */
1168 sigexit(- (exitcode & 0xff));
1174 static int check_and_run_traps(int sig)
1176 static const struct timespec zero_timespec = { 0, 0 };
1177 smalluint save_rcode;
1183 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1188 if (G.traps && G.traps[sig]) {
1189 if (G.traps[sig][0]) {
1190 /* We have user-defined handler */
1191 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1192 save_rcode = G.last_exitcode;
1195 G.last_exitcode = save_rcode;
1196 } /* else: "" trap, ignoring signal */
1199 /* not a trap: special action */
1201 #if ENABLE_HUSH_FAST
1204 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1208 /* Builtin was ^C'ed, make it look prettier: */
1215 /* bash is observed to signal whole process groups,
1216 * not individual processes */
1217 for (job = G.job_list; job; job = job->next) {
1220 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1221 if (kill(- job->pgrp, SIGHUP) == 0)
1222 kill(- job->pgrp, SIGCONT);
1227 default: /* ignored: */
1228 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1236 static const char *get_cwd(int force)
1238 if (force || G.cwd == NULL) {
1239 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1240 * we must not try to free(bb_msg_unknown) */
1241 if (G.cwd == bb_msg_unknown)
1243 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1245 G.cwd = bb_msg_unknown;
1252 * Shell and environment variable support
1254 static struct variable **get_ptr_to_local_var(const char *name)
1256 struct variable **pp;
1257 struct variable *cur;
1262 while ((cur = *pp) != NULL) {
1263 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1270 static struct variable *get_local_var(const char *name)
1272 struct variable **pp = get_ptr_to_local_var(name);
1278 static const char *get_local_var_value(const char *name)
1280 struct variable **pp = get_ptr_to_local_var(name);
1282 return strchr((*pp)->varstr, '=') + 1;
1286 /* str holds "NAME=VAL" and is expected to be malloced.
1287 * We take ownership of it.
1289 * 0: do not change export flag
1290 * (if creating new variable, flag will be 0)
1291 * 1: set export flag and putenv the variable
1292 * -1: clear export flag and unsetenv the variable
1293 * flg_read_only is set only when we handle -R var=val
1295 #if !BB_MMU && ENABLE_HUSH_LOCAL
1296 /* all params are used */
1297 #elif BB_MMU && ENABLE_HUSH_LOCAL
1298 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1299 set_local_var(str, flg_export, local_lvl)
1300 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1301 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1302 set_local_var(str, flg_export)
1303 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1304 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1305 set_local_var(str, flg_export, flg_read_only)
1307 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1309 struct variable **var_pp;
1310 struct variable *cur;
1314 eq_sign = strchr(str, '=');
1315 if (!eq_sign) { /* not expected to ever happen? */
1320 name_len = eq_sign - str + 1; /* including '=' */
1321 var_pp = &G.top_var;
1322 while ((cur = *var_pp) != NULL) {
1323 if (strncmp(cur->varstr, str, name_len) != 0) {
1324 var_pp = &cur->next;
1327 /* We found an existing var with this name */
1328 if (cur->flg_read_only) {
1332 bb_error_msg("%s: readonly variable", str);
1336 if (flg_export == -1) { // "&& cur->flg_export" ?
1337 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1342 #if ENABLE_HUSH_LOCAL
1343 if (cur->func_nest_level < local_lvl) {
1344 /* New variable is declared as local,
1345 * and existing one is global, or local
1346 * from enclosing function.
1347 * Remove and save old one: */
1348 *var_pp = cur->next;
1349 cur->next = *G.shadowed_vars_pp;
1350 *G.shadowed_vars_pp = cur;
1351 /* bash 3.2.33(1) and exported vars:
1353 * # f() { local z=a; env | grep ^z; }
1359 if (cur->flg_export)
1364 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1369 if (cur->max_len != 0) {
1370 if (cur->max_len >= strlen(str)) {
1371 /* This one is from startup env, reuse space */
1372 strcpy(cur->varstr, str);
1376 /* max_len == 0 signifies "malloced" var, which we can
1377 * (and has to) free */
1381 goto set_str_and_exp;
1384 /* Not found - create new variable struct */
1385 cur = xzalloc(sizeof(*cur));
1386 #if ENABLE_HUSH_LOCAL
1387 cur->func_nest_level = local_lvl;
1389 cur->next = *var_pp;
1395 cur->flg_read_only = flg_read_only;
1398 if (flg_export == 1)
1399 cur->flg_export = 1;
1400 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1401 cmdedit_update_prompt();
1402 if (cur->flg_export) {
1403 if (flg_export == -1) {
1404 cur->flg_export = 0;
1405 /* unsetenv was already done */
1407 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1408 return putenv(cur->varstr);
1414 static int unset_local_var_len(const char *name, int name_len)
1416 struct variable *cur;
1417 struct variable **var_pp;
1420 return EXIT_SUCCESS;
1421 var_pp = &G.top_var;
1422 while ((cur = *var_pp) != NULL) {
1423 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1424 if (cur->flg_read_only) {
1425 bb_error_msg("%s: readonly variable", name);
1426 return EXIT_FAILURE;
1428 *var_pp = cur->next;
1429 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1430 bb_unsetenv(cur->varstr);
1431 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1432 cmdedit_update_prompt();
1436 return EXIT_SUCCESS;
1438 var_pp = &cur->next;
1440 return EXIT_SUCCESS;
1443 static int unset_local_var(const char *name)
1445 return unset_local_var_len(name, strlen(name));
1448 static void unset_vars(char **strings)
1456 const char *eq = strchrnul(*v, '=');
1457 unset_local_var_len(*v, (int)(eq - *v));
1463 #if ENABLE_SH_MATH_SUPPORT
1464 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1465 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1466 static char *endofname(const char *name)
1474 if (!is_in_name(*p))
1480 static void arith_set_local_var(const char *name, const char *val, int flags)
1482 /* arith code doesnt malloc space, so do it for it */
1483 char *var = xasprintf("%s=%s", name, val);
1484 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1490 * Helpers for "var1=val1 var2=val2 cmd" feature
1492 static void add_vars(struct variable *var)
1494 struct variable *next;
1498 var->next = G.top_var;
1500 if (var->flg_export) {
1501 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1502 putenv(var->varstr);
1504 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1510 static struct variable *set_vars_and_save_old(char **strings)
1513 struct variable *old = NULL;
1519 struct variable *var_p;
1520 struct variable **var_pp;
1523 eq = strchr(*s, '=');
1526 var_pp = get_ptr_to_local_var(*s);
1529 /* Remove variable from global linked list */
1531 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1532 *var_pp = var_p->next;
1533 /* Add it to returned list */
1537 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1548 static int FAST_FUNC static_get(struct in_str *i)
1557 static int FAST_FUNC static_peek(struct in_str *i)
1562 #if ENABLE_HUSH_INTERACTIVE
1564 static void cmdedit_update_prompt(void)
1566 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1567 G.PS1 = get_local_var_value("PS1");
1570 G.PS2 = get_local_var_value("PS2");
1578 static const char* setup_prompt_string(int promptmode)
1580 const char *prompt_str;
1581 debug_printf("setup_prompt_string %d ", promptmode);
1582 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1583 /* Set up the prompt */
1584 if (promptmode == 0) { /* PS1 */
1586 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1591 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1592 debug_printf("result '%s'\n", prompt_str);
1596 static void get_user_input(struct in_str *i)
1599 const char *prompt_str;
1601 prompt_str = setup_prompt_string(i->promptmode);
1602 #if ENABLE_FEATURE_EDITING
1603 /* Enable command line editing only while a command line
1604 * is actually being read */
1607 /* buglet: SIGINT will not make new prompt to appear _at once_,
1608 * only after <Enter>. (^C will work) */
1609 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1610 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1611 check_and_run_traps(0);
1612 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1613 i->eof_flag = (r < 0);
1614 if (i->eof_flag) { /* EOF/error detected */
1615 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1616 G.user_input_buf[1] = '\0';
1621 fputs(prompt_str, stdout);
1623 G.user_input_buf[0] = r = fgetc(i->file);
1624 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1625 //do we need check_and_run_traps(0)? (maybe only if stdin)
1626 } while (G.flag_SIGINT);
1627 i->eof_flag = (r == EOF);
1629 i->p = G.user_input_buf;
1632 #endif /* INTERACTIVE */
1634 /* This is the magic location that prints prompts
1635 * and gets data back from the user */
1636 static int FAST_FUNC file_get(struct in_str *i)
1640 /* If there is data waiting, eat it up */
1641 if (i->p && *i->p) {
1642 #if ENABLE_HUSH_INTERACTIVE
1646 if (i->eof_flag && !*i->p)
1648 /* note: ch is never NUL */
1650 /* need to double check i->file because we might be doing something
1651 * more complicated by now, like sourcing or substituting. */
1652 #if ENABLE_HUSH_INTERACTIVE
1653 if (G_interactive_fd && i->promptme && i->file == stdin) {
1656 } while (!*i->p); /* need non-empty line */
1657 i->promptmode = 1; /* PS2 */
1662 do ch = fgetc(i->file); while (ch == '\0');
1664 debug_printf("file_get: got '%c' %d\n", ch, ch);
1665 #if ENABLE_HUSH_INTERACTIVE
1672 /* All callers guarantee this routine will never
1673 * be used right after a newline, so prompting is not needed.
1675 static int FAST_FUNC file_peek(struct in_str *i)
1678 if (i->p && *i->p) {
1679 if (i->eof_flag && !i->p[1])
1682 /* note: ch is never NUL */
1684 do ch = fgetc(i->file); while (ch == '\0');
1685 i->eof_flag = (ch == EOF);
1686 i->peek_buf[0] = ch;
1687 i->peek_buf[1] = '\0';
1689 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1693 static void setup_file_in_str(struct in_str *i, FILE *f)
1695 i->peek = file_peek;
1697 #if ENABLE_HUSH_INTERACTIVE
1699 i->promptmode = 0; /* PS1 */
1705 static void setup_string_in_str(struct in_str *i, const char *s)
1707 i->peek = static_peek;
1708 i->get = static_get;
1709 #if ENABLE_HUSH_INTERACTIVE
1711 i->promptmode = 0; /* PS1 */
1721 #define B_CHUNK (32 * sizeof(char*))
1723 static void o_reset_to_empty_unquoted(o_string *o)
1731 static void o_free(o_string *o)
1734 memset(o, 0, sizeof(*o));
1737 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1742 static void o_grow_by(o_string *o, int len)
1744 if (o->length + len > o->maxlen) {
1745 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1746 o->data = xrealloc(o->data, 1 + o->maxlen);
1750 static void o_addchr(o_string *o, int ch)
1752 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1754 o->data[o->length] = ch;
1756 o->data[o->length] = '\0';
1759 static void o_addblock(o_string *o, const char *str, int len)
1762 memcpy(&o->data[o->length], str, len);
1764 o->data[o->length] = '\0';
1768 static void o_addstr(o_string *o, const char *str)
1770 o_addblock(o, str, strlen(str));
1772 static void nommu_addchr(o_string *o, int ch)
1778 # define nommu_addchr(o, str) ((void)0)
1781 static void o_addstr_with_NUL(o_string *o, const char *str)
1783 o_addblock(o, str, strlen(str) + 1);
1786 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1791 && (*str != '*' && *str != '?' && *str != '[')
1799 /* My analysis of quoting semantics tells me that state information
1800 * is associated with a destination, not a source.
1802 static void o_addqchr(o_string *o, int ch)
1805 char *found = strchr("*?[\\", ch);
1810 o->data[o->length] = '\\';
1813 o->data[o->length] = ch;
1815 o->data[o->length] = '\0';
1818 static void o_addQchr(o_string *o, int ch)
1821 if (o->o_escape && strchr("*?[\\", ch)) {
1823 o->data[o->length] = '\\';
1827 o->data[o->length] = ch;
1829 o->data[o->length] = '\0';
1832 static void o_addQstr(o_string *o, const char *str, int len)
1835 o_addblock(o, str, len);
1841 int ordinary_cnt = strcspn(str, "*?[\\");
1842 if (ordinary_cnt > len) /* paranoia */
1844 o_addblock(o, str, ordinary_cnt);
1845 if (ordinary_cnt == len)
1847 str += ordinary_cnt;
1848 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1852 if (ch) { /* it is necessarily one of "*?[\\" */
1854 o->data[o->length] = '\\';
1858 o->data[o->length] = ch;
1860 o->data[o->length] = '\0';
1864 /* A special kind of o_string for $VAR and `cmd` expansion.
1865 * It contains char* list[] at the beginning, which is grown in 16 element
1866 * increments. Actual string data starts at the next multiple of 16 * (char*).
1867 * list[i] contains an INDEX (int!) into this string data.
1868 * It means that if list[] needs to grow, data needs to be moved higher up
1869 * but list[i]'s need not be modified.
1870 * NB: remembering how many list[i]'s you have there is crucial.
1871 * o_finalize_list() operation post-processes this structure - calculates
1872 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1874 #if DEBUG_EXPAND || DEBUG_GLOB
1875 static void debug_print_list(const char *prefix, o_string *o, int n)
1877 char **list = (char**)o->data;
1878 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1882 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1883 prefix, list, n, string_start, o->length, o->maxlen);
1886 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1887 o->data + (int)list[i] + string_start,
1888 o->data + (int)list[i] + string_start);
1892 const char *p = o->data + (int)list[n - 1] + string_start;
1894 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1898 # define debug_print_list(prefix, o, n) ((void)0)
1901 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1902 * in list[n] so that it points past last stored byte so far.
1903 * It returns n+1. */
1904 static int o_save_ptr_helper(o_string *o, int n)
1906 char **list = (char**)o->data;
1910 if (!o->has_empty_slot) {
1911 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1912 string_len = o->length - string_start;
1913 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1914 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1915 /* list[n] points to string_start, make space for 16 more pointers */
1916 o->maxlen += 0x10 * sizeof(list[0]);
1917 o->data = xrealloc(o->data, o->maxlen + 1);
1918 list = (char**)o->data;
1919 memmove(list + n + 0x10, list + n, string_len);
1920 o->length += 0x10 * sizeof(list[0]);
1922 debug_printf_list("list[%d]=%d string_start=%d\n",
1923 n, string_len, string_start);
1926 /* We have empty slot at list[n], reuse without growth */
1927 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1928 string_len = o->length - string_start;
1929 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1930 n, string_len, string_start);
1931 o->has_empty_slot = 0;
1933 list[n] = (char*)(ptrdiff_t)string_len;
1937 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1938 static int o_get_last_ptr(o_string *o, int n)
1940 char **list = (char**)o->data;
1941 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1943 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1946 /* o_glob performs globbing on last list[], saving each result
1947 * as a new list[]. */
1948 static int o_glob(o_string *o, int n)
1954 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1956 return o_save_ptr_helper(o, n);
1957 pattern = o->data + o_get_last_ptr(o, n);
1958 debug_printf_glob("glob pattern '%s'\n", pattern);
1959 if (!glob_needed(pattern)) {
1961 o->length = unbackslash(pattern) - o->data;
1962 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1963 return o_save_ptr_helper(o, n);
1966 memset(&globdata, 0, sizeof(globdata));
1967 gr = glob(pattern, 0, NULL, &globdata);
1968 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1969 if (gr == GLOB_NOSPACE)
1970 bb_error_msg_and_die("out of memory during glob");
1971 if (gr == GLOB_NOMATCH) {
1972 globfree(&globdata);
1975 if (gr != 0) { /* GLOB_ABORTED ? */
1976 /* TODO: testcase for bad glob pattern behavior */
1977 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1979 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1980 char **argv = globdata.gl_pathv;
1981 o->length = pattern - o->data; /* "forget" pattern */
1983 o_addstr_with_NUL(o, *argv);
1984 n = o_save_ptr_helper(o, n);
1990 globfree(&globdata);
1992 debug_print_list("o_glob returning", o, n);
1996 /* If o->o_glob == 1, glob the string so far remembered.
1997 * Otherwise, just finish current list[] and start new */
1998 static int o_save_ptr(o_string *o, int n)
2000 if (o->o_glob) { /* if globbing is requested */
2001 /* If o->has_empty_slot, list[n] was already globbed
2002 * (if it was requested back then when it was filled)
2003 * so don't do that again! */
2004 if (!o->has_empty_slot)
2005 return o_glob(o, n); /* o_save_ptr_helper is inside */
2007 return o_save_ptr_helper(o, n);
2010 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2011 static char **o_finalize_list(o_string *o, int n)
2016 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2018 debug_print_list("finalized", o, n);
2019 debug_printf_expand("finalized n:%d\n", n);
2020 list = (char**)o->data;
2021 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2025 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2031 /* Expansion can recurse */
2032 #if ENABLE_HUSH_TICK
2033 static int process_command_subs(o_string *dest, const char *s);
2035 static char *expand_string_to_string(const char *str);
2037 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2038 parse_stream_dquoted(dest, input, dquote_end)
2040 static int parse_stream_dquoted(o_string *as_string,
2042 struct in_str *input,
2045 /* expand_strvec_to_strvec() takes a list of strings, expands
2046 * all variable references within and returns a pointer to
2047 * a list of expanded strings, possibly with larger number
2048 * of strings. (Think VAR="a b"; echo $VAR).
2049 * This new list is allocated as a single malloc block.
2050 * NULL-terminated list of char* pointers is at the beginning of it,
2051 * followed by strings themself.
2052 * Caller can deallocate entire list by single free(list). */
2054 /* Store given string, finalizing the word and starting new one whenever
2055 * we encounter IFS char(s). This is used for expanding variable values.
2056 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2057 static int expand_on_ifs(o_string *output, int n, const char *str)
2060 int word_len = strcspn(str, G.ifs);
2062 if (output->o_escape || !output->o_glob)
2063 o_addQstr(output, str, word_len);
2064 else /* protect backslashes against globbing up :) */
2065 o_addblock_duplicate_backslash(output, str, word_len);
2068 if (!*str) /* EOL - do not finalize word */
2070 o_addchr(output, '\0');
2071 debug_print_list("expand_on_ifs", output, n);
2072 n = o_save_ptr(output, n);
2073 str += strspn(str, G.ifs); /* skip ifs chars */
2075 debug_print_list("expand_on_ifs[1]", output, n);
2079 /* Helper to expand $((...)) and heredoc body. These act as if
2080 * they are in double quotes, with the exception that they are not :).
2081 * Just the rules are similar: "expand only $var and `cmd`"
2083 * Returns malloced string.
2084 * As an optimization, we return NULL if expansion is not needed.
2086 static char *expand_pseudo_dquoted(const char *str)
2089 struct in_str input;
2090 o_string dest = NULL_O_STRING;
2092 if (strchr(str, '$') == NULL
2093 #if ENABLE_HUSH_TICK
2094 && strchr(str, '`') == NULL
2100 /* We need to expand. Example:
2101 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2103 setup_string_in_str(&input, str);
2104 parse_stream_dquoted(NULL, &dest, &input, EOF);
2105 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2106 exp_str = expand_string_to_string(dest.data);
2107 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2108 o_free_unsafe(&dest);
2112 /* Expand all variable references in given string, adding words to list[]
2113 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2114 * to be filled). This routine is extremely tricky: has to deal with
2115 * variables/parameters with whitespace, $* and $@, and constructs like
2116 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2117 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2119 /* or_mask is either 0 (normal case) or 0x80 -
2120 * expansion of right-hand side of assignment == 1-element expand.
2121 * It will also do no globbing, and thus we must not backslash-quote!
2128 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2129 debug_print_list("expand_vars_to_list", output, n);
2130 n = o_save_ptr(output, n);
2131 debug_print_list("expand_vars_to_list[0]", output, n);
2133 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2136 char *dyn_val = NULL;
2137 const char *val = NULL;
2138 #if ENABLE_HUSH_TICK
2139 o_string subst_result = NULL_O_STRING;
2141 #if ENABLE_SH_MATH_SUPPORT
2142 char arith_buf[sizeof(arith_t)*3 + 2];
2144 o_addblock(output, arg, p - arg);
2145 debug_print_list("expand_vars_to_list[1]", output, n);
2147 p = strchr(p, SPECIAL_VAR_SYMBOL);
2149 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2150 /* "$@" is special. Even if quoted, it can still
2151 * expand to nothing (not even an empty string) */
2152 if ((first_ch & 0x7f) != '@')
2153 ored_ch |= first_ch;
2155 switch (first_ch & 0x7f) {
2156 /* Highest bit in first_ch indicates that var is double-quoted */
2158 val = utoa(G.root_pid);
2160 case '!': /* bg pid */
2161 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2163 case '?': /* exitcode */
2164 val = utoa(G.last_exitcode);
2166 case '#': /* argc */
2167 if (arg[1] != SPECIAL_VAR_SYMBOL)
2168 /* actually, it's a ${#var} */
2170 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2175 if (!G.global_argv[i])
2177 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2178 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2179 smallint sv = output->o_escape;
2180 /* unquoted var's contents should be globbed, so don't escape */
2181 output->o_escape = 0;
2182 while (G.global_argv[i]) {
2183 n = expand_on_ifs(output, n, G.global_argv[i]);
2184 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2185 if (G.global_argv[i++][0] && G.global_argv[i]) {
2186 /* this argv[] is not empty and not last:
2187 * put terminating NUL, start new word */
2188 o_addchr(output, '\0');
2189 debug_print_list("expand_vars_to_list[2]", output, n);
2190 n = o_save_ptr(output, n);
2191 debug_print_list("expand_vars_to_list[3]", output, n);
2194 output->o_escape = sv;
2196 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2197 * and in this case should treat it like '$*' - see 'else...' below */
2198 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2200 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2201 if (++i >= G.global_argc)
2203 o_addchr(output, '\0');
2204 debug_print_list("expand_vars_to_list[4]", output, n);
2205 n = o_save_ptr(output, n);
2207 } else { /* quoted $*: add as one word */
2209 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2210 if (!G.global_argv[++i])
2213 o_addchr(output, G.ifs[0]);
2217 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2218 /* "Empty variable", used to make "" etc to not disappear */
2222 #if ENABLE_HUSH_TICK
2223 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2226 /* Can't just stuff it into output o_string,
2227 * expanded result may need to be globbed
2228 * and $IFS-splitted */
2229 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2230 process_command_subs(&subst_result, arg);
2231 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2232 val = subst_result.data;
2235 #if ENABLE_SH_MATH_SUPPORT
2236 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2237 arith_eval_hooks_t hooks;
2242 arg++; /* skip '+' */
2243 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2244 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2246 exp_str = expand_pseudo_dquoted(arg);
2247 hooks.lookupvar = get_local_var_value;
2248 hooks.setvar = arith_set_local_var;
2249 hooks.endofname = endofname;
2250 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2254 const char *msg = "error in arithmetic";
2257 msg = "exponent less than 0";
2260 msg = "divide by 0";
2263 msg = "expression recursion loop detected";
2268 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2269 sprintf(arith_buf, arith_t_fmt, res);
2274 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2276 bool exp_len = false;
2277 bool exp_null = false;
2279 char exp_save = exp_save; /* for compiler */
2280 char exp_op = exp_op; /* for compiler */
2281 char *exp_word = exp_word; /* for compiler */
2285 arg[0] = first_ch & 0x7f;
2287 /* prepare for expansions */
2288 if (var[0] == '#') {
2289 /* handle length expansion ${#var} */
2293 /* maybe handle parameter expansion */
2294 exp_off = strcspn(var, ":-=+?%#");
2298 exp_save = var[exp_off];
2299 exp_null = exp_save == ':';
2300 exp_word = var + exp_off;
2303 exp_op = *exp_word++;
2304 var[exp_off] = '\0';
2308 /* lookup the variable in question */
2309 if (isdigit(var[0])) {
2310 /* handle_dollar() should have vetted var for us */
2312 if (i < G.global_argc)
2313 val = G.global_argv[i];
2314 /* else val remains NULL: $N with too big N */
2316 val = get_local_var_value(var);
2318 /* handle any expansions */
2320 debug_printf_expand("expand: length of '%s' = ", val);
2321 val = utoa(val ? strlen(val) : 0);
2322 debug_printf_expand("%s\n", val);
2323 } else if (exp_off) {
2324 if (exp_op == '%' || exp_op == '#') {
2326 /* we need to do a pattern match */
2329 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2330 if (exp_op == *exp_word) /* ## or %% */
2332 val = dyn_val = xstrdup(val);
2333 loc = scan(dyn_val, exp_word, match_at_left);
2334 if (match_at_left) /* # or ## */
2336 else if (loc) /* % or %% and match was found */
2340 /* we need to do an expansion */
2341 int exp_test = (!val || (exp_null && !val[0]));
2343 exp_test = !exp_test;
2344 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2345 exp_null ? "true" : "false", exp_test);
2347 if (exp_op == '?') {
2348 //TODO: how interactive bash aborts expansion mid-command?
2349 /* ${var?[error_msg_if_unset]} */
2350 /* ${var:?[error_msg_if_unset_or_null]} */
2351 /* mimic bash message */
2352 die_if_script("%s: %s",
2354 exp_word[0] ? exp_word : "parameter null or not set"
2360 if (exp_op == '=') {
2361 /* ${var=[word]} or ${var:=[word]} */
2362 if (isdigit(var[0]) || var[0] == '#') {
2363 /* mimic bash message */
2364 die_if_script("$%s: cannot assign in this way", var);
2367 char *new_var = xasprintf("%s=%s", var, val);
2368 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2374 var[exp_off] = exp_save;
2378 #if ENABLE_HUSH_TICK
2381 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2382 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2384 /* unquoted var's contents should be globbed, so don't escape */
2385 smallint sv = output->o_escape;
2386 output->o_escape = 0;
2387 n = expand_on_ifs(output, n, val);
2389 output->o_escape = sv;
2391 } else { /* quoted $VAR, val will be appended below */
2392 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2395 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2398 o_addQstr(output, val, strlen(val));
2401 /* Do the check to avoid writing to a const string */
2402 if (*p != SPECIAL_VAR_SYMBOL)
2403 *p = SPECIAL_VAR_SYMBOL;
2405 #if ENABLE_HUSH_TICK
2406 o_free(&subst_result);
2409 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2412 debug_print_list("expand_vars_to_list[a]", output, n);
2413 /* this part is literal, and it was already pre-quoted
2414 * if needed (much earlier), do not use o_addQstr here! */
2415 o_addstr_with_NUL(output, arg);
2416 debug_print_list("expand_vars_to_list[b]", output, n);
2417 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2418 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2421 /* allow to reuse list[n] later without re-growth */
2422 output->has_empty_slot = 1;
2424 o_addchr(output, '\0');
2429 static char **expand_variables(char **argv, int or_mask)
2434 o_string output = NULL_O_STRING;
2436 if (or_mask & 0x100) {
2437 output.o_escape = 1; /* protect against globbing for "$var" */
2438 /* (unquoted $var will temporarily switch it off) */
2445 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2448 debug_print_list("expand_variables", &output, n);
2450 /* output.data (malloced in one block) gets returned in "list" */
2451 list = o_finalize_list(&output, n);
2452 debug_print_strings("expand_variables[1]", list);
2456 static char **expand_strvec_to_strvec(char **argv)
2458 return expand_variables(argv, 0x100);
2461 /* Used for expansion of right hand of assignments */
2462 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2464 static char *expand_string_to_string(const char *str)
2466 char *argv[2], **list;
2468 argv[0] = (char*)str;
2470 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2472 if (!list[0] || list[1])
2473 bb_error_msg_and_die("BUG in varexp2");
2474 /* actually, just move string 2*sizeof(char*) bytes back */
2475 overlapping_strcpy((char*)list, list[0]);
2476 unbackslash((char*)list);
2477 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2481 /* Used for "eval" builtin */
2482 static char* expand_strvec_to_string(char **argv)
2486 list = expand_variables(argv, 0x80);
2487 /* Convert all NULs to spaces */
2492 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2493 bb_error_msg_and_die("BUG in varexp3");
2494 /* bash uses ' ' regardless of $IFS contents */
2499 overlapping_strcpy((char*)list, list[0]);
2500 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2504 static char **expand_assignments(char **argv, int count)
2508 /* Expand assignments into one string each */
2509 for (i = 0; i < count; i++) {
2510 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2518 void re_execute_shell(char ***to_free, const char *s,
2519 char *g_argv0, char **g_argv,
2520 char **builtin_argv) NORETURN;
2522 static void reset_traps_to_defaults(void)
2524 /* This function is always called in a child shell
2525 * after fork (not vfork, NOMMU doesn't use this function).
2526 * Child shells are not interactive.
2527 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2528 * Testcase: (while :; do :; done) + ^Z should background.
2529 * Same goes for SIGTERM, SIGHUP, SIGINT.
2534 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2537 /* Stupid. It can be done with *single* &= op, but we can't use
2538 * the fact that G.blocked_set is implemented as a bitmask... */
2539 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2543 sigdelset(&G.blocked_set, sig);
2550 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2551 mask = G.non_DFL_mask;
2552 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2556 G.traps[sig] = NULL;
2557 /* There is no signal for 0 (EXIT) */
2560 /* There was a trap handler, we are removing it.
2561 * But if sig still has non-DFL handling,
2562 * we should not unblock it. */
2565 sigdelset(&G.blocked_set, sig);
2567 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2572 static void re_execute_shell(char ***to_free, const char *s,
2573 char *g_argv0, char **g_argv,
2574 char **builtin_argv) NORETURN;
2575 static void re_execute_shell(char ***to_free, const char *s,
2576 char *g_argv0, char **g_argv,
2577 char **builtin_argv)
2579 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2580 char *heredoc_argv[4];
2581 struct variable *cur;
2582 #if ENABLE_HUSH_FUNCTIONS
2583 struct function *funcp;
2588 if (!g_argv0) { /* heredoc */
2589 argv = heredoc_argv;
2590 argv[0] = (char *) G.argv0_for_re_execing;
2591 argv[1] = (char *) "-<";
2592 argv[2] = (char *) s;
2594 pp = &argv[3]; /* used as pointer to empty environment */
2600 if (pp) while (*pp++)
2603 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2604 , (unsigned) G.root_pid
2605 , (unsigned) G.last_bg_pid
2606 , (unsigned) G.last_exitcode
2608 IF_HUSH_LOOPS(, G.depth_of_loop)
2610 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2611 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2614 for (cur = G.top_var; cur; cur = cur->next) {
2615 if (!cur->flg_export || cur->flg_read_only)
2618 #if ENABLE_HUSH_FUNCTIONS
2619 for (funcp = G.top_func; funcp; funcp = funcp->next)
2625 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2626 *pp++ = (char *) G.argv0_for_re_execing;
2628 for (cur = G.top_var; cur; cur = cur->next) {
2629 if (cur->varstr == hush_version_str)
2631 if (cur->flg_read_only) {
2632 *pp++ = (char *) "-R";
2633 *pp++ = cur->varstr;
2634 } else if (!cur->flg_export) {
2635 *pp++ = (char *) "-V";
2636 *pp++ = cur->varstr;
2639 #if ENABLE_HUSH_FUNCTIONS
2640 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2641 *pp++ = (char *) "-F";
2642 *pp++ = funcp->name;
2643 *pp++ = funcp->body_as_string;
2646 /* We can pass activated traps here. Say, -Tnn:trap_string
2648 * However, POSIX says that subshells reset signals with traps
2650 * I tested bash-3.2 and it not only does that with true subshells
2651 * of the form ( list ), but with any forked children shells.
2652 * I set trap "echo W" WINCH; and then tried:
2654 * { echo 1; sleep 20; echo 2; } &
2655 * while true; do echo 1; sleep 20; echo 2; break; done &
2656 * true | { echo 1; sleep 20; echo 2; } | cat
2658 * In all these cases sending SIGWINCH to the child shell
2659 * did not run the trap. If I add trap "echo V" WINCH;
2660 * _inside_ group (just before echo 1), it works.
2662 * I conclude it means we don't need to pass active traps here.
2663 * exec syscall below resets them to SIG_DFL for us.
2665 *pp++ = (char *) "-c";
2668 while (*++builtin_argv)
2669 *pp++ = *builtin_argv;
2670 *pp++ = (char *) "";
2675 /* *pp = NULL; - is already there */
2679 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2680 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2681 execve(bb_busybox_exec_path, argv, pp);
2682 /* Fallback. Useful for init=/bin/hush usage etc */
2683 if (argv[0][0] == '/')
2684 execve(argv[0], argv, pp);
2685 xfunc_error_retval = 127;
2686 bb_error_msg_and_die("can't re-execute the shell");
2688 #endif /* !BB_MMU */
2691 static void setup_heredoc(struct redir_struct *redir)
2693 struct fd_pair pair;
2696 /* the _body_ of heredoc (misleading field name) */
2697 const char *heredoc = redir->rd_filename;
2704 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2705 expanded = expand_pseudo_dquoted(heredoc);
2709 len = strlen(heredoc);
2711 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2713 xmove_fd(pair.rd, redir->rd_fd);
2715 /* Try writing without forking. Newer kernels have
2716 * dynamically growing pipes. Must use non-blocking write! */
2719 written = write(pair.wr, heredoc, len);
2730 ndelay_off(pair.wr);
2732 /* Okay, pipe buffer was not big enough */
2733 /* Note: we must not create a stray child (bastard? :)
2734 * for the unsuspecting parent process. Child creates a grandchild
2735 * and exits before parent execs the process which consumes heredoc
2736 * (that exec happens after we return from this function) */
2742 bb_perror_msg_and_die("vfork");
2745 disable_restore_tty_pgrp_on_exit();
2746 pid = BB_MMU ? fork() : vfork();
2748 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2752 close(redir->rd_fd); /* read side of the pipe */
2754 full_write(pair.wr, heredoc, len); /* may loop or block */
2757 /* Delegate blocking writes to another process */
2758 xmove_fd(pair.wr, STDOUT_FILENO);
2759 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2763 #if ENABLE_HUSH_FAST
2765 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2767 enable_restore_tty_pgrp_on_exit();
2773 wait(NULL); /* wait till child has died */
2776 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2777 * and stderr if they are redirected. */
2778 static int setup_redirects(struct command *prog, int squirrel[])
2781 struct redir_struct *redir;
2783 for (redir = prog->redirects; redir; redir = redir->next) {
2784 if (redir->rd_type == REDIRECT_HEREDOC2) {
2785 /* rd_fd<<HERE case */
2786 if (squirrel && redir->rd_fd < 3
2787 && squirrel[redir->rd_fd] < 0
2789 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2791 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2793 debug_printf_parse("set heredoc '%s'\n",
2794 redir->rd_filename);
2795 setup_heredoc(redir);
2799 if (redir->rd_dup == REDIRFD_TO_FILE) {
2800 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2802 if (redir->rd_filename == NULL) {
2803 /* Something went wrong in the parse.
2804 * Pretend it didn't happen */
2805 bb_error_msg("bug in redirect parse");
2808 mode = redir_table[redir->rd_type].mode;
2809 p = expand_string_to_string(redir->rd_filename);
2810 openfd = open_or_warn(p, mode);
2813 /* this could get lost if stderr has been redirected, but
2814 * bash and ash both lose it as well (though zsh doesn't!) */
2815 //what the above comment tries to say?
2819 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2820 openfd = redir->rd_dup;
2823 if (openfd != redir->rd_fd) {
2824 if (squirrel && redir->rd_fd < 3
2825 && squirrel[redir->rd_fd] < 0
2827 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2829 if (openfd == REDIRFD_CLOSE) {
2830 /* "n>-" means "close me" */
2831 close(redir->rd_fd);
2833 xdup2(openfd, redir->rd_fd);
2834 if (redir->rd_dup == REDIRFD_TO_FILE)
2842 static void restore_redirects(int squirrel[])
2845 for (i = 0; i < 3; i++) {
2848 /* We simply die on error */
2855 static void free_pipe_list(struct pipe *head);
2857 /* Return code is the exit status of the pipe */
2858 static void free_pipe(struct pipe *pi)
2861 struct command *command;
2862 struct redir_struct *r, *rnext;
2865 if (pi->stopped_cmds > 0) /* why? */
2867 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2868 for (i = 0; i < pi->num_cmds; i++) {
2869 command = &pi->cmds[i];
2870 debug_printf_clean(" command %d:\n", i);
2871 if (command->argv) {
2872 for (a = 0, p = command->argv; *p; a++, p++) {
2873 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2875 free_strings(command->argv);
2876 command->argv = NULL;
2878 /* not "else if": on syntax error, we may have both! */
2879 if (command->group) {
2880 debug_printf_clean(" begin group (grp_type:%d)\n",
2882 free_pipe_list(command->group);
2883 debug_printf_clean(" end group\n");
2884 command->group = NULL;
2886 /* else is crucial here.
2887 * If group != NULL, child_func is meaningless */
2888 #if ENABLE_HUSH_FUNCTIONS
2889 else if (command->child_func) {
2890 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2891 command->child_func->parent_cmd = NULL;
2895 free(command->group_as_string);
2896 command->group_as_string = NULL;
2898 for (r = command->redirects; r; r = rnext) {
2899 debug_printf_clean(" redirect %d%s",
2900 r->rd_fd, redir_table[r->rd_type].descrip);
2901 /* guard against the case >$FOO, where foo is unset or blank */
2902 if (r->rd_filename) {
2903 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2904 free(r->rd_filename);
2905 r->rd_filename = NULL;
2907 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2911 command->redirects = NULL;
2913 free(pi->cmds); /* children are an array, they get freed all at once */
2921 static void free_pipe_list(struct pipe *head)
2923 struct pipe *pi, *next;
2925 for (pi = head; pi; pi = next) {
2927 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2930 debug_printf_clean("pipe followup code %d\n", pi->followup);
2932 /*pi->next = NULL;*/
2938 static int run_list(struct pipe *pi);
2940 #define parse_stream(pstring, input, end_trigger) \
2941 parse_stream(input, end_trigger)
2943 static struct pipe *parse_stream(char **pstring,
2944 struct in_str *input,
2946 static void parse_and_run_string(const char *s);
2949 static char *find_in_path(const char *arg)
2952 const char *PATH = get_local_var_value("PATH");
2958 const char *end = strchrnul(PATH, ':');
2959 int sz = end - PATH; /* must be int! */
2963 ret = xasprintf("%.*s/%s", sz, PATH, arg);
2965 /* We have xxx::yyyy in $PATH,
2966 * it means "use current dir" */
2969 if (access(ret, F_OK) == 0)
2982 static const struct built_in_command* find_builtin_helper(const char *name,
2983 const struct built_in_command *x,
2984 const struct built_in_command *end)
2987 if (strcmp(name, x->cmd) != 0) {
2991 debug_printf_exec("found builtin '%s'\n", name);
2996 static const struct built_in_command* find_builtin1(const char *name)
2998 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3000 static const struct built_in_command* find_builtin(const char *name)
3002 const struct built_in_command *x = find_builtin1(name);
3005 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3008 #if ENABLE_HUSH_FUNCTIONS
3009 static const struct function *find_function(const char *name)
3011 const struct function *funcp = G.top_func;
3013 if (strcmp(name, funcp->name) == 0) {
3016 funcp = funcp->next;
3019 debug_printf_exec("found function '%s'\n", name);
3023 /* Note: takes ownership on name ptr */
3024 static struct function *new_function(char *name)
3026 struct function *funcp;
3027 struct function **funcpp = &G.top_func;
3029 while ((funcp = *funcpp) != NULL) {
3030 struct command *cmd;
3032 if (strcmp(funcp->name, name) != 0) {
3033 funcpp = &funcp->next;
3037 cmd = funcp->parent_cmd;
3038 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3040 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3042 /* Note: if !funcp->body, do not free body_as_string!
3043 * This is a special case of "-F name body" function:
3044 * body_as_string was not malloced! */
3046 free_pipe_list(funcp->body);
3048 free(funcp->body_as_string);
3052 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3053 cmd->argv[0] = funcp->name;
3054 cmd->group = funcp->body;
3056 cmd->group_as_string = funcp->body_as_string;
3061 debug_printf_exec("remembering new function '%s'\n", name);
3062 funcp = *funcpp = xzalloc(sizeof(*funcp));
3063 /*funcp->next = NULL;*/
3069 static void unset_func(const char *name)
3071 struct function *funcp;
3072 struct function **funcpp = &G.top_func;
3074 while ((funcp = *funcpp) != NULL) {
3075 if (strcmp(funcp->name, name) == 0) {
3076 *funcpp = funcp->next;
3077 /* funcp is unlinked now, deleting it.
3078 * Note: if !funcp->body, the function was created by
3079 * "-F name body", do not free ->body_as_string
3080 * and ->name as they were not malloced. */
3082 free_pipe_list(funcp->body);
3085 free(funcp->body_as_string);
3091 funcpp = &funcp->next;
3096 #define exec_function(nommu_save, funcp, argv) \
3097 exec_function(funcp, argv)
3099 static void exec_function(nommu_save_t *nommu_save,
3100 const struct function *funcp,
3101 char **argv) NORETURN;
3102 static void exec_function(nommu_save_t *nommu_save,
3103 const struct function *funcp,
3109 argv[0] = G.global_argv[0];
3110 G.global_argv = argv;
3114 /* On MMU, funcp->body is always non-NULL */
3115 n = run_list(funcp->body);
3119 re_execute_shell(&nommu_save->argv_from_re_execing,
3120 funcp->body_as_string,
3127 static int run_function(const struct function *funcp, char **argv)
3133 save_and_replace_G_args(&sv, argv);
3135 /* "we are in function, ok to use return" */
3136 sv_flg = G.flag_return_in_progress;
3137 G.flag_return_in_progress = -1;
3138 #if ENABLE_HUSH_LOCAL
3139 G.func_nest_level++;
3142 /* On MMU, funcp->body is always non-NULL */
3145 /* Function defined by -F */
3146 parse_and_run_string(funcp->body_as_string);
3147 rc = G.last_exitcode;
3151 rc = run_list(funcp->body);
3154 #if ENABLE_HUSH_LOCAL
3156 struct variable *var;
3157 struct variable **var_pp;
3159 var_pp = &G.top_var;
3160 while ((var = *var_pp) != NULL) {
3161 if (var->func_nest_level < G.func_nest_level) {
3162 var_pp = &var->next;
3166 if (var->flg_export)
3167 bb_unsetenv(var->varstr);
3168 /* Remove from global list */
3169 *var_pp = var->next;
3175 G.func_nest_level--;
3178 G.flag_return_in_progress = sv_flg;
3180 restore_G_args(&sv, argv);
3184 #endif /* ENABLE_HUSH_FUNCTIONS */
3188 #define exec_builtin(nommu_save, x, argv) \
3189 exec_builtin(x, argv)
3191 #define exec_builtin(nommu_save, x, argv) \
3192 exec_builtin(nommu_save, argv)
3194 static void exec_builtin(nommu_save_t *nommu_save,
3195 const struct built_in_command *x,
3196 char **argv) NORETURN;
3197 static void exec_builtin(nommu_save_t *nommu_save,
3198 const struct built_in_command *x,
3202 int rcode = x->function(argv);
3206 /* On NOMMU, we must never block!
3207 * Example: { sleep 99 | read line; } & echo Ok
3209 re_execute_shell(&nommu_save->argv_from_re_execing,
3219 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3220 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3221 #define pseudo_exec(nommu_save, command, argv_expanded) \
3222 pseudo_exec(command, argv_expanded)
3225 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3227 * Don't exit() here. If you don't exec, use _exit instead.
3228 * The at_exit handlers apparently confuse the calling process,
3229 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3230 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3231 char **argv, int assignment_cnt,
3232 char **argv_expanded) NORETURN;
3233 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3234 char **argv, int assignment_cnt,
3235 char **argv_expanded)
3239 /* Case when we are here: ... | var=val | ... */
3240 if (!argv[assignment_cnt])
3241 _exit(EXIT_SUCCESS);
3243 new_env = expand_assignments(argv, assignment_cnt);
3245 set_vars_and_save_old(new_env);
3246 free(new_env); /* optional */
3247 /* we can also destroy set_vars_and_save_old's return value,
3250 nommu_save->new_env = new_env;
3251 nommu_save->old_vars = set_vars_and_save_old(new_env);
3253 if (argv_expanded) {
3254 argv = argv_expanded;
3256 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3258 nommu_save->argv = argv;
3262 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3263 if (strchr(argv[0], '/') != NULL)
3267 /* Check if the command matches any of the builtins.
3268 * Depending on context, this might be redundant. But it's
3269 * easier to waste a few CPU cycles than it is to figure out
3270 * if this is one of those cases.
3273 /* On NOMMU, it is more expensive to re-execute shell
3274 * just in order to run echo or test builtin.
3275 * It's better to skip it here and run corresponding
3276 * non-builtin later. */
3277 const struct built_in_command *x;
3278 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3280 exec_builtin(nommu_save, x, argv);
3283 #if ENABLE_HUSH_FUNCTIONS
3284 /* Check if the command matches any functions */
3286 const struct function *funcp = find_function(argv[0]);
3288 exec_function(nommu_save, funcp, argv);
3293 #if ENABLE_FEATURE_SH_STANDALONE
3294 /* Check if the command matches any busybox applets */
3296 int a = find_applet_by_name(argv[0]);
3298 # if BB_MMU /* see above why on NOMMU it is not allowed */
3299 if (APPLET_IS_NOEXEC(a)) {
3300 debug_printf_exec("running applet '%s'\n", argv[0]);
3301 run_applet_no_and_exit(a, argv);
3304 /* Re-exec ourselves */
3305 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3306 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3307 execv(bb_busybox_exec_path, argv);
3308 /* If they called chroot or otherwise made the binary no longer
3309 * executable, fall through */
3314 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3317 debug_printf_exec("execing '%s'\n", argv[0]);
3318 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3319 execvp(argv[0], argv);
3320 bb_perror_msg("can't execute '%s'", argv[0]);
3321 _exit(EXIT_FAILURE);
3324 /* Called after [v]fork() in run_pipe
3326 static void pseudo_exec(nommu_save_t *nommu_save,
3327 struct command *command,
3328 char **argv_expanded) NORETURN;
3329 static void pseudo_exec(nommu_save_t *nommu_save,
3330 struct command *command,
3331 char **argv_expanded)
3333 if (command->argv) {
3334 pseudo_exec_argv(nommu_save, command->argv,
3335 command->assignment_cnt, argv_expanded);
3338 if (command->group) {
3339 /* Cases when we are here:
3342 * ... | ( list ) | ...
3343 * ... | { list } | ...
3347 debug_printf_exec("pseudo_exec: run_list\n");
3348 reset_traps_to_defaults();
3349 rcode = run_list(command->group);
3350 /* OK to leak memory by not calling free_pipe_list,
3351 * since this process is about to exit */
3354 re_execute_shell(&nommu_save->argv_from_re_execing,
3355 command->group_as_string,
3362 /* Case when we are here: ... | >file */
3363 debug_printf_exec("pseudo_exec'ed null command\n");
3364 _exit(EXIT_SUCCESS);
3368 static const char *get_cmdtext(struct pipe *pi)
3374 /* This is subtle. ->cmdtext is created only on first backgrounding.
3375 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3376 * On subsequent bg argv is trashed, but we won't use it */
3379 argv = pi->cmds[0].argv;
3380 if (!argv || !argv[0]) {
3381 pi->cmdtext = xzalloc(1);
3387 len += strlen(*argv) + 1;
3391 argv = pi->cmds[0].argv;
3393 len = strlen(*argv);
3394 memcpy(p, *argv, len);
3402 static void insert_bg_job(struct pipe *pi)
3404 struct pipe *job, **jobp;
3407 /* Linear search for the ID of the job to use */
3409 for (job = G.job_list; job; job = job->next)
3410 if (job->jobid >= pi->jobid)
3411 pi->jobid = job->jobid + 1;
3413 /* Add job to the list of running jobs */
3415 while ((job = *jobp) != NULL)
3417 job = *jobp = xmalloc(sizeof(*job));
3419 *job = *pi; /* physical copy */
3421 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3422 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3423 for (i = 0; i < pi->num_cmds; i++) {
3424 job->cmds[i].pid = pi->cmds[i].pid;
3425 /* all other fields are not used and stay zero */
3427 job->cmdtext = xstrdup(get_cmdtext(pi));
3429 if (G_interactive_fd)
3430 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3431 /* Last command's pid goes to $! */
3432 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3433 G.last_jobid = job->jobid;
3436 static void remove_bg_job(struct pipe *pi)
3438 struct pipe *prev_pipe;
3440 if (pi == G.job_list) {
3441 G.job_list = pi->next;
3443 prev_pipe = G.job_list;
3444 while (prev_pipe->next != pi)
3445 prev_pipe = prev_pipe->next;
3446 prev_pipe->next = pi->next;
3449 G.last_jobid = G.job_list->jobid;
3454 /* Remove a backgrounded job */
3455 static void delete_finished_bg_job(struct pipe *pi)
3458 pi->stopped_cmds = 0;
3464 /* Check to see if any processes have exited -- if they
3465 * have, figure out why and see if a job has completed */
3466 static int checkjobs(struct pipe* fg_pipe)
3476 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3478 attributes = WUNTRACED;
3479 if (fg_pipe == NULL)
3480 attributes |= WNOHANG;
3483 #if ENABLE_HUSH_FAST
3484 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3485 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3486 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3487 /* There was neither fork nor SIGCHLD since last waitpid */
3488 /* Avoid doing waitpid syscall if possible */
3489 if (!G.we_have_children) {
3493 if (fg_pipe == NULL) { /* is WNOHANG set? */
3494 /* We have children, but they did not exit
3495 * or stop yet (we saw no SIGCHLD) */
3498 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3502 /* Do we do this right?
3503 * bash-3.00# sleep 20 | false
3505 * [3]+ Stopped sleep 20 | false
3506 * bash-3.00# echo $?
3507 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3508 * [hush 1.14.0: yes we do it right]
3515 #if ENABLE_HUSH_FAST
3516 i = G.count_SIGCHLD;
3518 childpid = waitpid(-1, &status, attributes);
3519 if (childpid <= 0) {
3520 if (childpid && errno != ECHILD)
3521 bb_perror_msg("waitpid");
3522 #if ENABLE_HUSH_FAST
3523 else { /* Until next SIGCHLD, waitpid's are useless */
3524 G.we_have_children = (childpid == 0);
3525 G.handled_SIGCHLD = i;
3526 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3531 dead = WIFEXITED(status) || WIFSIGNALED(status);
3534 if (WIFSTOPPED(status))
3535 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3536 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3537 if (WIFSIGNALED(status))
3538 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3539 childpid, WTERMSIG(status), WEXITSTATUS(status));
3540 if (WIFEXITED(status))
3541 debug_printf_jobs("pid %d exited, exitcode %d\n",
3542 childpid, WEXITSTATUS(status));
3544 /* Were we asked to wait for fg pipe? */
3546 for (i = 0; i < fg_pipe->num_cmds; i++) {
3547 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3548 if (fg_pipe->cmds[i].pid != childpid)
3551 fg_pipe->cmds[i].pid = 0;
3552 fg_pipe->alive_cmds--;
3553 if (i == fg_pipe->num_cmds - 1) {
3554 /* last process gives overall exitstatus */
3555 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3556 rcode = WEXITSTATUS(status);
3557 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3558 /* bash prints killing signal's name for *last*
3559 * process in pipe (prints just newline for SIGINT).
3560 * Mimic this. Example: "sleep 5" + ^\
3562 if (WIFSIGNALED(status)) {
3563 int sig = WTERMSIG(status);
3564 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3568 fg_pipe->cmds[i].is_stopped = 1;
3569 fg_pipe->stopped_cmds++;
3571 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3572 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3573 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3574 /* All processes in fg pipe have exited or stopped */
3575 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3576 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3577 * and "killall -STOP cat" */
3578 if (G_interactive_fd) {
3580 if (fg_pipe->alive_cmds)
3581 insert_bg_job(fg_pipe);
3585 if (!fg_pipe->alive_cmds)
3588 /* There are still running processes in the fg pipe */
3589 goto wait_more; /* do waitpid again */
3591 /* it wasnt fg_pipe, look for process in bg pipes */
3595 /* We asked to wait for bg or orphaned children */
3596 /* No need to remember exitcode in this case */
3597 for (pi = G.job_list; pi; pi = pi->next) {
3598 for (i = 0; i < pi->num_cmds; i++) {
3599 if (pi->cmds[i].pid == childpid)
3600 goto found_pi_and_prognum;
3603 /* Happens when shell is used as init process (init=/bin/sh) */
3604 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3605 continue; /* do waitpid again */
3607 found_pi_and_prognum:
3610 pi->cmds[i].pid = 0;
3612 if (!pi->alive_cmds) {
3613 if (G_interactive_fd)
3614 printf(JOB_STATUS_FORMAT, pi->jobid,
3615 "Done", pi->cmdtext);
3616 delete_finished_bg_job(pi);
3620 pi->cmds[i].is_stopped = 1;
3624 } /* while (waitpid succeeds)... */
3630 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3633 int rcode = checkjobs(fg_pipe);
3634 if (G_saved_tty_pgrp) {
3635 /* Job finished, move the shell to the foreground */
3636 p = getpgrp(); /* our process group id */
3637 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3638 tcsetpgrp(G_interactive_fd, p);
3644 /* Start all the jobs, but don't wait for anything to finish.
3647 * Return code is normally -1, when the caller has to wait for children
3648 * to finish to determine the exit status of the pipe. If the pipe
3649 * is a simple builtin command, however, the action is done by the
3650 * time run_pipe returns, and the exit code is provided as the
3653 * Returns -1 only if started some children. IOW: we have to
3654 * mask out retvals of builtins etc with 0xff!
3656 * The only case when we do not need to [v]fork is when the pipe
3657 * is single, non-backgrounded, non-subshell command. Examples:
3658 * cmd ; ... { list } ; ...
3659 * cmd && ... { list } && ...
3660 * cmd || ... { list } || ...
3661 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3662 * or (if SH_STANDALONE) an applet, and we can run the { list }
3663 * with run_list. If it isn't one of these, we fork and exec cmd.
3665 * Cases when we must fork:
3666 * non-single: cmd | cmd
3667 * backgrounded: cmd & { list } &
3668 * subshell: ( list ) [&]
3670 static int run_pipe(struct pipe *pi)
3672 static const char *const null_ptr = NULL;
3675 struct command *command;
3676 char **argv_expanded;
3679 /* it is not always needed, but we aim to smaller code */
3680 int squirrel[] = { -1, -1, -1 };
3683 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3686 IF_HUSH_JOB(pi->pgrp = -1;)
3687 pi->stopped_cmds = 0;
3688 command = &(pi->cmds[0]);
3689 argv_expanded = NULL;
3691 if (pi->num_cmds != 1
3692 || pi->followup == PIPE_BG
3693 || command->grp_type == GRP_SUBSHELL
3700 debug_printf_exec(": group:%p argv:'%s'\n",
3701 command->group, command->argv ? command->argv[0] : "NONE");
3703 if (command->group) {
3704 #if ENABLE_HUSH_FUNCTIONS
3705 if (command->grp_type == GRP_FUNCTION) {
3706 /* "executing" func () { list } */
3707 struct function *funcp;
3709 funcp = new_function(command->argv[0]);
3710 /* funcp->name is already set to argv[0] */
3711 funcp->body = command->group;
3713 funcp->body_as_string = command->group_as_string;
3714 command->group_as_string = NULL;
3716 command->group = NULL;
3717 command->argv[0] = NULL;
3718 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3719 funcp->parent_cmd = command;
3720 command->child_func = funcp;
3722 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3724 return EXIT_SUCCESS;
3728 debug_printf("non-subshell group\n");
3729 rcode = 1; /* exitcode if redir failed */
3730 if (setup_redirects(command, squirrel) == 0) {
3731 debug_printf_exec(": run_list\n");
3732 rcode = run_list(command->group) & 0xff;
3734 restore_redirects(squirrel);
3735 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3737 debug_printf_exec("run_pipe: return %d\n", rcode);
3741 argv = command->argv ? command->argv : (char **) &null_ptr;
3743 const struct built_in_command *x;
3744 #if ENABLE_HUSH_FUNCTIONS
3745 const struct function *funcp;
3749 char **new_env = NULL;
3750 struct variable *old_vars = NULL;
3752 if (argv[command->assignment_cnt] == NULL) {
3753 /* Assignments, but no command */
3754 /* Ensure redirects take effect. Try "a=t >file" */
3755 rcode = setup_redirects(command, squirrel);
3756 restore_redirects(squirrel);
3757 /* Set shell variables */
3759 p = expand_string_to_string(*argv);
3760 debug_printf_exec("set shell var:'%s'->'%s'\n",
3762 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3765 /* Do we need to flag set_local_var() errors?
3766 * "assignment to readonly var" and "putenv error"
3768 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3770 debug_printf_exec("run_pipe: return %d\n", rcode);
3774 /* Expand the rest into (possibly) many strings each */
3775 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3777 x = find_builtin(argv_expanded[0]);
3778 #if ENABLE_HUSH_FUNCTIONS
3781 funcp = find_function(argv_expanded[0]);
3785 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3786 debug_printf("exec with redirects only\n");
3787 rcode = setup_redirects(command, NULL);
3788 goto clean_up_and_ret1;
3791 /* setup_redirects acts on file descriptors, not FILEs.
3792 * This is perfect for work that comes after exec().
3793 * Is it really safe for inline use? Experimentally,
3794 * things seem to work. */
3795 rcode = setup_redirects(command, squirrel);
3797 new_env = expand_assignments(argv, command->assignment_cnt);
3798 old_vars = set_vars_and_save_old(new_env);
3800 debug_printf_exec(": builtin '%s' '%s'...\n",
3801 x->cmd, argv_expanded[1]);
3802 rcode = x->function(argv_expanded) & 0xff;
3805 #if ENABLE_HUSH_FUNCTIONS
3807 # if ENABLE_HUSH_LOCAL
3808 struct variable **sv;
3809 sv = G.shadowed_vars_pp;
3810 G.shadowed_vars_pp = &old_vars;
3812 debug_printf_exec(": function '%s' '%s'...\n",
3813 funcp->name, argv_expanded[1]);
3814 rcode = run_function(funcp, argv_expanded) & 0xff;
3815 # if ENABLE_HUSH_LOCAL
3816 G.shadowed_vars_pp = sv;
3821 #if ENABLE_FEATURE_SH_STANDALONE
3824 restore_redirects(squirrel);
3825 unset_vars(new_env);
3828 free(argv_expanded);
3829 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3831 debug_printf_exec("run_pipe return %d\n", rcode);
3835 #if ENABLE_FEATURE_SH_STANDALONE
3836 i = find_applet_by_name(argv_expanded[0]);
3837 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3838 rcode = setup_redirects(command, squirrel);
3840 new_env = expand_assignments(argv, command->assignment_cnt);
3841 old_vars = set_vars_and_save_old(new_env);
3842 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3843 argv_expanded[0], argv_expanded[1]);
3844 rcode = run_nofork_applet(i, argv_expanded);
3846 goto clean_up_and_ret;
3849 /* It is neither builtin nor applet. We must fork. */
3853 /* NB: argv_expanded may already be created, and that
3854 * might include `cmd` runs! Do not rerun it! We *must*
3855 * use argv_expanded if it's non-NULL */
3857 /* Going to fork a child per each pipe member */
3861 for (i = 0; i < pi->num_cmds; i++) {
3862 struct fd_pair pipefds;
3864 volatile nommu_save_t nommu_save;
3865 nommu_save.new_env = NULL;
3866 nommu_save.old_vars = NULL;
3867 nommu_save.argv = NULL;
3868 nommu_save.argv_from_re_execing = NULL;
3870 command = &(pi->cmds[i]);
3871 if (command->argv) {
3872 debug_printf_exec(": pipe member '%s' '%s'...\n",
3873 command->argv[0], command->argv[1]);
3875 debug_printf_exec(": pipe member with no argv\n");
3878 /* pipes are inserted between pairs of commands */
3881 if ((i + 1) < pi->num_cmds)
3882 xpiped_pair(pipefds);
3884 command->pid = BB_MMU ? fork() : vfork();
3885 if (!command->pid) { /* child */
3887 disable_restore_tty_pgrp_on_exit();
3889 /* Every child adds itself to new process group
3890 * with pgid == pid_of_first_child_in_pipe */
3891 if (G.run_list_level == 1 && G_interactive_fd) {
3894 if (pgrp < 0) /* true for 1st process only */
3896 if (setpgid(0, pgrp) == 0
3897 && pi->followup != PIPE_BG
3898 && G_saved_tty_pgrp /* we have ctty */
3900 /* We do it in *every* child, not just first,
3902 tcsetpgrp(G_interactive_fd, pgrp);
3906 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3907 /* 1st cmd in backgrounded pipe
3908 * should have its stdin /dev/null'ed */
3910 if (open(bb_dev_null, O_RDONLY))
3911 xopen("/", O_RDONLY);
3913 xmove_fd(nextin, 0);
3915 xmove_fd(pipefds.wr, 1);
3918 /* Like bash, explicit redirects override pipes,
3919 * and the pipe fd is available for dup'ing. */
3920 if (setup_redirects(command, NULL))
3923 /* Restore default handlers just prior to exec */
3924 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3926 /* Stores to nommu_save list of env vars putenv'ed
3927 * (NOMMU, on MMU we don't need that) */
3928 /* cast away volatility... */
3929 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3930 /* pseudo_exec() does not return */
3933 /* parent or error */
3934 #if ENABLE_HUSH_FAST
3936 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3938 enable_restore_tty_pgrp_on_exit();
3940 /* Clean up after vforked child */
3941 free(nommu_save.argv);
3942 free(nommu_save.argv_from_re_execing);
3943 unset_vars(nommu_save.new_env);
3944 add_vars(nommu_save.old_vars);
3946 free(argv_expanded);
3947 argv_expanded = NULL;
3948 if (command->pid < 0) { /* [v]fork failed */
3949 /* Clearly indicate, was it fork or vfork */
3950 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3954 /* Second and next children need to know pid of first one */
3956 pi->pgrp = command->pid;
3962 if ((i + 1) < pi->num_cmds)
3964 /* Pass read (output) pipe end to next iteration */
3965 nextin = pipefds.rd;
3968 if (!pi->alive_cmds) {
3970 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3975 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3979 #ifndef debug_print_tree
3980 static void debug_print_tree(struct pipe *pi, int lvl)
3982 static const char *const PIPE[] = {
3988 static const char *RES[] = {
3989 [RES_NONE ] = "NONE" ,
3992 [RES_THEN ] = "THEN" ,
3993 [RES_ELIF ] = "ELIF" ,
3994 [RES_ELSE ] = "ELSE" ,
3997 #if ENABLE_HUSH_LOOPS
3998 [RES_FOR ] = "FOR" ,
3999 [RES_WHILE] = "WHILE",
4000 [RES_UNTIL] = "UNTIL",
4002 [RES_DONE ] = "DONE" ,
4004 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4007 #if ENABLE_HUSH_CASE
4008 [RES_CASE ] = "CASE" ,
4009 [RES_CASE_IN ] = "CASE_IN" ,
4010 [RES_MATCH] = "MATCH",
4011 [RES_CASE_BODY] = "CASE_BODY",
4012 [RES_ESAC ] = "ESAC" ,
4014 [RES_XXXX ] = "XXXX" ,
4015 [RES_SNTX ] = "SNTX" ,
4017 static const char *const GRPTYPE[] = {
4020 #if ENABLE_HUSH_FUNCTIONS
4029 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4030 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4032 while (prn < pi->num_cmds) {
4033 struct command *command = &pi->cmds[prn];
4034 char **argv = command->argv;
4036 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4038 command->assignment_cnt);
4039 if (command->group) {
4040 fprintf(stderr, " group %s: (argv=%p)\n",
4041 GRPTYPE[command->grp_type],
4043 debug_print_tree(command->group, lvl+1);
4047 if (argv) while (*argv) {
4048 fprintf(stderr, " '%s'", *argv);
4051 fprintf(stderr, "\n");
4060 /* NB: called by pseudo_exec, and therefore must not modify any
4061 * global data until exec/_exit (we can be a child after vfork!) */
4062 static int run_list(struct pipe *pi)
4064 #if ENABLE_HUSH_CASE
4065 char *case_word = NULL;
4067 #if ENABLE_HUSH_LOOPS
4068 struct pipe *loop_top = NULL;
4069 char **for_lcur = NULL;
4070 char **for_list = NULL;
4072 smallint last_followup;
4074 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4075 smalluint cond_code = 0;
4077 enum { cond_code = 0 };
4080 smallint rword; /* enum reserved_style */
4081 smallint last_rword; /* ditto */
4084 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4087 #if ENABLE_HUSH_LOOPS
4088 /* Check syntax for "for" */
4089 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4090 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4092 /* current word is FOR or IN (BOLD in comments below) */
4093 if (cpipe->next == NULL) {
4094 syntax_error("malformed for");
4096 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4099 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4100 if (cpipe->next->res_word == RES_DO)
4102 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4103 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4104 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4106 syntax_error("malformed for");
4108 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4114 /* Past this point, all code paths should jump to ret: label
4115 * in order to return, no direct "return" statements please.
4116 * This helps to ensure that no memory is leaked. */
4124 last_rword = RES_XXXX;
4126 last_followup = PIPE_SEQ;
4127 rcode = G.last_exitcode;
4129 /* Go through list of pipes, (maybe) executing them. */
4130 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4134 IF_HAS_KEYWORDS(rword = pi->res_word;)
4135 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4136 rword, cond_code, last_rword);
4137 #if ENABLE_HUSH_LOOPS
4138 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4139 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4141 /* start of a loop: remember where loop starts */
4146 /* Still in the same "if...", "then..." or "do..." branch? */
4147 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4148 if ((rcode == 0 && last_followup == PIPE_OR)
4149 || (rcode != 0 && last_followup == PIPE_AND)
4151 /* It is "<true> || CMD" or "<false> && CMD"
4152 * and we should not execute CMD */
4153 debug_printf_exec("skipped cmd because of || or &&\n");
4154 last_followup = pi->followup;
4158 last_followup = pi->followup;
4159 IF_HAS_KEYWORDS(last_rword = rword;)
4162 if (rword == RES_THEN) {
4163 /* if false; then ... fi has exitcode 0! */
4164 G.last_exitcode = rcode = EXIT_SUCCESS;
4165 /* "if <false> THEN cmd": skip cmd */
4169 if (rword == RES_ELSE || rword == RES_ELIF) {
4170 /* "if <true> then ... ELSE/ELIF cmd":
4171 * skip cmd and all following ones */
4176 #if ENABLE_HUSH_LOOPS
4177 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4179 /* first loop through for */
4181 static const char encoded_dollar_at[] ALIGN1 = {
4182 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4183 }; /* encoded representation of "$@" */
4184 static const char *const encoded_dollar_at_argv[] = {
4185 encoded_dollar_at, NULL
4186 }; /* argv list with one element: "$@" */
4189 vals = (char**)encoded_dollar_at_argv;
4190 if (pi->next->res_word == RES_IN) {
4191 /* if no variable values after "in" we skip "for" */
4192 if (!pi->next->cmds[0].argv) {
4193 G.last_exitcode = rcode = EXIT_SUCCESS;
4194 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4197 vals = pi->next->cmds[0].argv;
4198 } /* else: "for var; do..." -> assume "$@" list */
4199 /* create list of variable values */
4200 debug_print_strings("for_list made from", vals);
4201 for_list = expand_strvec_to_strvec(vals);
4202 for_lcur = for_list;
4203 debug_print_strings("for_list", for_list);
4206 /* "for" loop is over, clean up */
4212 /* Insert next value from for_lcur */
4213 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4214 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4217 if (rword == RES_IN) {
4218 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4220 if (rword == RES_DONE) {
4221 continue; /* "done" has no cmds too */
4224 #if ENABLE_HUSH_CASE
4225 if (rword == RES_CASE) {
4226 case_word = expand_strvec_to_string(pi->cmds->argv);
4229 if (rword == RES_MATCH) {
4232 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4234 /* all prev words didn't match, does this one match? */
4235 argv = pi->cmds->argv;
4237 char *pattern = expand_string_to_string(*argv);
4238 /* TODO: which FNM_xxx flags to use? */
4239 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4241 if (cond_code == 0) { /* match! we will execute this branch */
4242 free(case_word); /* make future "word)" stop */
4250 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4252 continue; /* not matched yet, skip this pipe */
4255 /* Just pressing <enter> in shell should check for jobs.
4256 * OTOH, in non-interactive shell this is useless
4257 * and only leads to extra job checks */
4258 if (pi->num_cmds == 0) {
4259 if (G_interactive_fd)
4260 goto check_jobs_and_continue;
4264 /* After analyzing all keywords and conditions, we decided
4265 * to execute this pipe. NB: have to do checkjobs(NULL)
4266 * after run_pipe to collect any background children,
4267 * even if list execution is to be stopped. */
4268 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4271 #if ENABLE_HUSH_LOOPS
4272 G.flag_break_continue = 0;
4274 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4276 /* We ran a builtin, function, or group.
4277 * rcode is already known
4278 * and we don't need to wait for anything. */
4279 G.last_exitcode = rcode;
4280 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4281 check_and_run_traps(0);
4282 #if ENABLE_HUSH_LOOPS
4283 /* Was it "break" or "continue"? */
4284 if (G.flag_break_continue) {
4285 smallint fbc = G.flag_break_continue;
4286 /* We might fall into outer *loop*,
4287 * don't want to break it too */
4289 G.depth_break_continue--;
4290 if (G.depth_break_continue == 0)
4291 G.flag_break_continue = 0;
4292 /* else: e.g. "continue 2" should *break* once, *then* continue */
4293 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4294 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4295 goto check_jobs_and_break;
4296 /* "continue": simulate end of loop */
4301 #if ENABLE_HUSH_FUNCTIONS
4302 if (G.flag_return_in_progress == 1) {
4303 /* same as "goto check_jobs_and_break" */
4308 } else if (pi->followup == PIPE_BG) {
4309 /* What does bash do with attempts to background builtins? */
4310 /* even bash 3.2 doesn't do that well with nested bg:
4311 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4312 * I'm NOT treating inner &'s as jobs */
4313 check_and_run_traps(0);
4315 if (G.run_list_level == 1)
4318 G.last_exitcode = rcode = EXIT_SUCCESS;
4319 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4322 if (G.run_list_level == 1 && G_interactive_fd) {
4323 /* Waits for completion, then fg's main shell */
4324 rcode = checkjobs_and_fg_shell(pi);
4325 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4326 check_and_run_traps(0);
4329 { /* This one just waits for completion */
4330 rcode = checkjobs(pi);
4331 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4332 check_and_run_traps(0);
4334 G.last_exitcode = rcode;
4338 /* Analyze how result affects subsequent commands */
4340 if (rword == RES_IF || rword == RES_ELIF)
4343 #if ENABLE_HUSH_LOOPS
4344 /* Beware of "while false; true; do ..."! */
4345 if (pi->next && pi->next->res_word == RES_DO) {
4346 if (rword == RES_WHILE) {
4348 /* "while false; do...done" - exitcode 0 */
4349 G.last_exitcode = rcode = EXIT_SUCCESS;
4350 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4351 goto check_jobs_and_break;
4354 if (rword == RES_UNTIL) {
4356 debug_printf_exec(": until expr is true: breaking\n");
4357 check_jobs_and_break:
4365 check_jobs_and_continue:
4372 #if ENABLE_HUSH_LOOPS
4377 #if ENABLE_HUSH_CASE
4381 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4385 /* Select which version we will use */
4386 static int run_and_free_list(struct pipe *pi)
4389 debug_printf_exec("run_and_free_list entered\n");
4391 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4392 rcode = run_list(pi);
4394 /* free_pipe_list has the side effect of clearing memory.
4395 * In the long run that function can be merged with run_list,
4396 * but doing that now would hobble the debugging effort. */
4398 debug_printf_exec("run_and_free_list return %d\n", rcode);
4403 static struct pipe *new_pipe(void)
4406 pi = xzalloc(sizeof(struct pipe));
4407 /*pi->followup = 0; - deliberately invalid value */
4408 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4412 /* Command (member of a pipe) is complete, or we start a new pipe
4413 * if ctx->command is NULL.
4414 * No errors possible here.
4416 static int done_command(struct parse_context *ctx)
4418 /* The command is really already in the pipe structure, so
4419 * advance the pipe counter and make a new, null command. */
4420 struct pipe *pi = ctx->pipe;
4421 struct command *command = ctx->command;
4424 if (IS_NULL_CMD(command)) {
4425 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4429 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4430 //debug_print_tree(ctx->list_head, 20);
4432 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4435 /* Only real trickiness here is that the uncommitted
4436 * command structure is not counted in pi->num_cmds. */
4437 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4438 ctx->command = command = &pi->cmds[pi->num_cmds];
4440 memset(command, 0, sizeof(*command));
4441 return pi->num_cmds; /* used only for 0/nonzero check */
4444 static void done_pipe(struct parse_context *ctx, pipe_style type)
4448 debug_printf_parse("done_pipe entered, followup %d\n", type);
4449 /* Close previous command */
4450 not_null = done_command(ctx);
4451 ctx->pipe->followup = type;
4453 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4454 ctx->ctx_inverted = 0;
4455 ctx->pipe->res_word = ctx->ctx_res_w;
4458 /* Without this check, even just <enter> on command line generates
4459 * tree of three NOPs (!). Which is harmless but annoying.
4460 * IOW: it is safe to do it unconditionally. */
4463 || ctx->ctx_res_w == RES_FI
4465 #if ENABLE_HUSH_LOOPS
4466 || ctx->ctx_res_w == RES_DONE
4467 || ctx->ctx_res_w == RES_FOR
4468 || ctx->ctx_res_w == RES_IN
4470 #if ENABLE_HUSH_CASE
4471 || ctx->ctx_res_w == RES_ESAC
4475 debug_printf_parse("done_pipe: adding new pipe: "
4476 "not_null:%d ctx->ctx_res_w:%d\n",
4477 not_null, ctx->ctx_res_w);
4479 ctx->pipe->next = new_p;
4481 /* RES_THEN, RES_DO etc are "sticky" -
4482 * they remain set for pipes inside if/while.
4483 * This is used to control execution.
4484 * RES_FOR and RES_IN are NOT sticky (needed to support
4485 * cases where variable or value happens to match a keyword):
4487 #if ENABLE_HUSH_LOOPS
4488 if (ctx->ctx_res_w == RES_FOR
4489 || ctx->ctx_res_w == RES_IN)
4490 ctx->ctx_res_w = RES_NONE;
4492 #if ENABLE_HUSH_CASE
4493 if (ctx->ctx_res_w == RES_MATCH)
4494 ctx->ctx_res_w = RES_CASE_BODY;
4495 if (ctx->ctx_res_w == RES_CASE)
4496 ctx->ctx_res_w = RES_CASE_IN;
4498 ctx->command = NULL; /* trick done_command below */
4499 /* Create the memory for command, roughly:
4500 * ctx->pipe->cmds = new struct command;
4501 * ctx->command = &ctx->pipe->cmds[0];
4504 //debug_print_tree(ctx->list_head, 10);
4506 debug_printf_parse("done_pipe return\n");
4509 static void initialize_context(struct parse_context *ctx)
4511 memset(ctx, 0, sizeof(*ctx));
4512 ctx->pipe = ctx->list_head = new_pipe();
4513 /* Create the memory for command, roughly:
4514 * ctx->pipe->cmds = new struct command;
4515 * ctx->command = &ctx->pipe->cmds[0];
4520 /* If a reserved word is found and processed, parse context is modified
4521 * and 1 is returned.
4524 struct reserved_combo {
4527 unsigned char assignment_flag;
4531 FLAG_END = (1 << RES_NONE ),
4533 FLAG_IF = (1 << RES_IF ),
4534 FLAG_THEN = (1 << RES_THEN ),
4535 FLAG_ELIF = (1 << RES_ELIF ),
4536 FLAG_ELSE = (1 << RES_ELSE ),
4537 FLAG_FI = (1 << RES_FI ),
4539 #if ENABLE_HUSH_LOOPS
4540 FLAG_FOR = (1 << RES_FOR ),
4541 FLAG_WHILE = (1 << RES_WHILE),
4542 FLAG_UNTIL = (1 << RES_UNTIL),
4543 FLAG_DO = (1 << RES_DO ),
4544 FLAG_DONE = (1 << RES_DONE ),
4545 FLAG_IN = (1 << RES_IN ),
4547 #if ENABLE_HUSH_CASE
4548 FLAG_MATCH = (1 << RES_MATCH),
4549 FLAG_ESAC = (1 << RES_ESAC ),
4551 FLAG_START = (1 << RES_XXXX ),
4554 static const struct reserved_combo* match_reserved_word(o_string *word)
4556 /* Mostly a list of accepted follow-up reserved words.
4557 * FLAG_END means we are done with the sequence, and are ready
4558 * to turn the compound list into a command.
4559 * FLAG_START means the word must start a new compound list.
4561 static const struct reserved_combo reserved_list[] = {
4563 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4564 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4565 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4566 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4567 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4568 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4570 #if ENABLE_HUSH_LOOPS
4571 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4572 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4573 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4574 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4575 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4576 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4578 #if ENABLE_HUSH_CASE
4579 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4580 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4583 const struct reserved_combo *r;
4585 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4586 if (strcmp(word->data, r->literal) == 0)
4591 /* Return 0: not a keyword, 1: keyword
4593 static int reserved_word(o_string *word, struct parse_context *ctx)
4595 #if ENABLE_HUSH_CASE
4596 static const struct reserved_combo reserved_match = {
4597 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4600 const struct reserved_combo *r;
4604 r = match_reserved_word(word);
4608 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4609 #if ENABLE_HUSH_CASE
4610 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4611 /* "case word IN ..." - IN part starts first MATCH part */
4612 r = &reserved_match;
4615 if (r->flag == 0) { /* '!' */
4616 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4617 syntax_error("! ! command");
4618 ctx->ctx_res_w = RES_SNTX;
4620 ctx->ctx_inverted = 1;
4623 if (r->flag & FLAG_START) {
4624 struct parse_context *old;
4626 old = xmalloc(sizeof(*old));
4627 debug_printf_parse("push stack %p\n", old);
4628 *old = *ctx; /* physical copy */
4629 initialize_context(ctx);
4631 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4632 syntax_error_at(word->data);
4633 ctx->ctx_res_w = RES_SNTX;
4636 /* "{...} fi" is ok. "{...} if" is not
4638 * if { echo foo; } then { echo bar; } fi */
4639 if (ctx->command->group)
4640 done_pipe(ctx, PIPE_SEQ);
4643 ctx->ctx_res_w = r->res;
4644 ctx->old_flag = r->flag;
4645 word->o_assignment = r->assignment_flag;
4647 if (ctx->old_flag & FLAG_END) {
4648 struct parse_context *old;
4650 done_pipe(ctx, PIPE_SEQ);
4651 debug_printf_parse("pop stack %p\n", ctx->stack);
4653 old->command->group = ctx->list_head;
4654 old->command->grp_type = GRP_NORMAL;
4656 o_addstr(&old->as_string, ctx->as_string.data);
4657 o_free_unsafe(&ctx->as_string);
4658 old->command->group_as_string = xstrdup(old->as_string.data);
4659 debug_printf_parse("pop, remembering as:'%s'\n",
4660 old->command->group_as_string);
4662 *ctx = *old; /* physical copy */
4669 /* Word is complete, look at it and update parsing context.
4670 * Normal return is 0. Syntax errors return 1.
4671 * Note: on return, word is reset, but not o_free'd!
4673 static int done_word(o_string *word, struct parse_context *ctx)
4675 struct command *command = ctx->command;
4677 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4678 if (word->length == 0 && word->o_quoted == 0) {
4679 debug_printf_parse("done_word return 0: true null, ignored\n");
4683 if (ctx->pending_redirect) {
4684 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4685 * only if run as "bash", not "sh" */
4686 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4688 * ...the word that follows the redirection operator
4689 * shall be subjected to tilde expansion, parameter expansion,
4690 * command substitution, arithmetic expansion, and quote
4691 * removal. Pathname expansion shall not be performed
4692 * on the word by a non-interactive shell; an interactive
4693 * shell may perform it, but shall do so only when
4694 * the expansion would result in one word."
4696 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4697 /* Cater for >\file case:
4698 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4699 * Same with heredocs:
4700 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4702 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4703 unbackslash(ctx->pending_redirect->rd_filename);
4704 /* Is it <<"HEREDOC"? */
4705 if (word->o_quoted) {
4706 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4709 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4710 ctx->pending_redirect = NULL;
4712 /* If this word wasn't an assignment, next ones definitely
4713 * can't be assignments. Even if they look like ones. */
4714 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4715 && word->o_assignment != WORD_IS_KEYWORD
4717 word->o_assignment = NOT_ASSIGNMENT;
4719 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4720 command->assignment_cnt++;
4721 word->o_assignment = MAYBE_ASSIGNMENT;
4725 # if ENABLE_HUSH_CASE
4726 if (ctx->ctx_dsemicolon
4727 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4729 /* already done when ctx_dsemicolon was set to 1: */
4730 /* ctx->ctx_res_w = RES_MATCH; */
4731 ctx->ctx_dsemicolon = 0;
4734 if (!command->argv /* if it's the first word... */
4735 # if ENABLE_HUSH_LOOPS
4736 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4737 && ctx->ctx_res_w != RES_IN
4739 # if ENABLE_HUSH_CASE
4740 && ctx->ctx_res_w != RES_CASE
4743 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4744 if (reserved_word(word, ctx)) {
4745 o_reset_to_empty_unquoted(word);
4746 debug_printf_parse("done_word return %d\n",
4747 (ctx->ctx_res_w == RES_SNTX));
4748 return (ctx->ctx_res_w == RES_SNTX);
4752 if (command->group) {
4753 /* "{ echo foo; } echo bar" - bad */
4754 syntax_error_at(word->data);
4755 debug_printf_parse("done_word return 1: syntax error, "
4756 "groups and arglists don't mix\n");
4759 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4760 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4761 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4762 /* (otherwise it's known to be not empty and is already safe) */
4764 /* exclude "$@" - it can expand to no word despite "" */
4765 char *p = word->data;
4766 while (p[0] == SPECIAL_VAR_SYMBOL
4767 && (p[1] & 0x7f) == '@'
4768 && p[2] == SPECIAL_VAR_SYMBOL
4772 if (p == word->data || p[0] != '\0') {
4773 /* saw no "$@", or not only "$@" but some
4774 * real text is there too */
4775 /* insert "empty variable" reference, this makes
4776 * e.g. "", $empty"" etc to not disappear */
4777 o_addchr(word, SPECIAL_VAR_SYMBOL);
4778 o_addchr(word, SPECIAL_VAR_SYMBOL);
4781 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4782 debug_print_strings("word appended to argv", command->argv);
4785 #if ENABLE_HUSH_LOOPS
4786 if (ctx->ctx_res_w == RES_FOR) {
4788 || !is_well_formed_var_name(command->argv[0], '\0')
4790 /* bash says just "not a valid identifier" */
4791 syntax_error("not a valid identifier in for");
4794 /* Force FOR to have just one word (variable name) */
4795 /* NB: basically, this makes hush see "for v in ..."
4796 * syntax as if it is "for v; in ...". FOR and IN become
4797 * two pipe structs in parse tree. */
4798 done_pipe(ctx, PIPE_SEQ);
4801 #if ENABLE_HUSH_CASE
4802 /* Force CASE to have just one word */
4803 if (ctx->ctx_res_w == RES_CASE) {
4804 done_pipe(ctx, PIPE_SEQ);
4808 o_reset_to_empty_unquoted(word);
4810 debug_printf_parse("done_word return 0\n");
4815 /* Peek ahead in the input to find out if we have a "&n" construct,
4816 * as in "2>&1", that represents duplicating a file descriptor.
4818 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4819 * REDIRFD_SYNTAX_ERR if syntax error,
4820 * REDIRFD_TO_FILE if no & was seen,
4821 * or the number found.
4824 #define parse_redir_right_fd(as_string, input) \
4825 parse_redir_right_fd(input)
4827 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4833 return REDIRFD_TO_FILE;
4835 ch = i_getch(input); /* get the & */
4836 nommu_addchr(as_string, ch);
4839 ch = i_getch(input);
4840 nommu_addchr(as_string, ch);
4841 return REDIRFD_CLOSE;
4845 while (ch != EOF && isdigit(ch)) {
4846 d = d*10 + (ch-'0');
4848 ch = i_getch(input);
4849 nommu_addchr(as_string, ch);
4854 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4856 bb_error_msg("ambiguous redirect");
4857 return REDIRFD_SYNTAX_ERR;
4860 /* Return code is 0 normal, 1 if a syntax error is detected
4862 static int parse_redirect(struct parse_context *ctx,
4865 struct in_str *input)
4867 struct command *command = ctx->command;
4868 struct redir_struct *redir;
4869 struct redir_struct **redirp;
4872 dup_num = REDIRFD_TO_FILE;
4873 if (style != REDIRECT_HEREDOC) {
4874 /* Check for a '>&1' type redirect */
4875 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4876 if (dup_num == REDIRFD_SYNTAX_ERR)
4879 int ch = i_peek(input);
4880 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4881 if (dup_num) { /* <<-... */
4882 ch = i_getch(input);
4883 nommu_addchr(&ctx->as_string, ch);
4888 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4889 int ch = i_peek(input);
4891 /* >|FILE redirect ("clobbering" >).
4892 * Since we do not support "set -o noclobber" yet,
4893 * >| and > are the same for now. Just eat |.
4895 ch = i_getch(input);
4896 nommu_addchr(&ctx->as_string, ch);
4900 /* Create a new redir_struct and append it to the linked list */
4901 redirp = &command->redirects;
4902 while ((redir = *redirp) != NULL) {
4903 redirp = &(redir->next);
4905 *redirp = redir = xzalloc(sizeof(*redir));
4906 /* redir->next = NULL; */
4907 /* redir->rd_filename = NULL; */
4908 redir->rd_type = style;
4909 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4911 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4912 redir_table[style].descrip);
4914 redir->rd_dup = dup_num;
4915 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4916 /* Erik had a check here that the file descriptor in question
4917 * is legit; I postpone that to "run time"
4918 * A "-" representation of "close me" shows up as a -3 here */
4919 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4920 redir->rd_fd, redir->rd_dup);
4922 /* Set ctx->pending_redirect, so we know what to do at the
4923 * end of the next parsed word. */
4924 ctx->pending_redirect = redir;
4929 /* If a redirect is immediately preceded by a number, that number is
4930 * supposed to tell which file descriptor to redirect. This routine
4931 * looks for such preceding numbers. In an ideal world this routine
4932 * needs to handle all the following classes of redirects...
4933 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4934 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4935 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4936 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4938 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4940 * ... If n is quoted, the number shall not be recognized as part of
4941 * the redirection expression. For example:
4943 * writes the character 2 into file a"
4944 * We are getting it right by setting ->o_quoted on any \<char>
4946 * A -1 return means no valid number was found,
4947 * the caller should use the appropriate default for this redirection.
4949 static int redirect_opt_num(o_string *o)
4953 if (o->data == NULL)
4955 num = bb_strtou(o->data, NULL, 10);
4956 if (errno || num < 0)
4958 o_reset_to_empty_unquoted(o);
4963 #define fetch_till_str(as_string, input, word, skip_tabs) \
4964 fetch_till_str(input, word, skip_tabs)
4966 static char *fetch_till_str(o_string *as_string,
4967 struct in_str *input,
4971 o_string heredoc = NULL_O_STRING;
4977 ch = i_getch(input);
4978 nommu_addchr(as_string, ch);
4980 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4981 heredoc.data[past_EOL] = '\0';
4982 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4983 return heredoc.data;
4986 o_addchr(&heredoc, ch);
4987 past_EOL = heredoc.length;
4990 ch = i_getch(input);
4991 nommu_addchr(as_string, ch);
4992 } while (skip_tabs && ch == '\t');
4993 } while (ch == '\n');
4996 o_free_unsafe(&heredoc);
4999 o_addchr(&heredoc, ch);
5000 nommu_addchr(as_string, ch);
5004 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5005 * and load them all. There should be exactly heredoc_cnt of them.
5007 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5009 struct pipe *pi = ctx->list_head;
5011 while (pi && heredoc_cnt) {
5013 struct command *cmd = pi->cmds;
5015 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5017 cmd->argv ? cmd->argv[0] : "NONE");
5018 for (i = 0; i < pi->num_cmds; i++) {
5019 struct redir_struct *redir = cmd->redirects;
5021 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5022 i, cmd->argv ? cmd->argv[0] : "NONE");
5024 if (redir->rd_type == REDIRECT_HEREDOC) {
5027 redir->rd_type = REDIRECT_HEREDOC2;
5028 /* redir->dup is (ab)used to indicate <<- */
5029 p = fetch_till_str(&ctx->as_string, input,
5030 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5032 syntax_error("unexpected EOF in here document");
5035 free(redir->rd_filename);
5036 redir->rd_filename = p;
5039 redir = redir->next;
5046 /* Should be 0. If it isn't, it's a parse error */
5048 bb_error_msg_and_die("heredoc BUG 2");
5054 #if ENABLE_HUSH_TICK
5055 static FILE *generate_stream_from_string(const char *s)
5058 int pid, channel[2];
5064 pid = BB_MMU ? fork() : vfork();
5066 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5068 if (pid == 0) { /* child */
5069 disable_restore_tty_pgrp_on_exit();
5070 /* Process substitution is not considered to be usual
5071 * 'command execution'.
5072 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5079 close(channel[0]); /* NB: close _first_, then move fd! */
5080 xmove_fd(channel[1], 1);
5081 /* Prevent it from trying to handle ctrl-z etc */
5082 IF_HUSH_JOB(G.run_list_level = 1;)
5084 reset_traps_to_defaults();
5085 parse_and_run_string(s);
5086 _exit(G.last_exitcode);
5088 /* We re-execute after vfork on NOMMU. This makes this script safe:
5089 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5090 * huge=`cat BIG` # was blocking here forever
5093 re_execute_shell(&to_free,
5102 #if ENABLE_HUSH_FAST
5104 //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);
5106 enable_restore_tty_pgrp_on_exit();
5111 pf = fdopen(channel[0], "r");
5115 /* Return code is exit status of the process that is run. */
5116 static int process_command_subs(o_string *dest, const char *s)
5119 struct in_str pipe_str;
5122 pf = generate_stream_from_string(s);
5125 close_on_exec_on(fileno(pf));
5127 /* Now send results of command back into original context */
5128 setup_file_in_str(&pipe_str, pf);
5130 while ((ch = i_getch(&pipe_str)) != EOF) {
5136 o_addchr(dest, '\n');
5139 o_addQchr(dest, ch);
5142 debug_printf("done reading from pipe, pclose()ing\n");
5143 /* Note: we got EOF, and we just close the read end of the pipe.
5144 * We do not wait for the `cmd` child to terminate. bash and ash do.
5146 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5147 * `false`; echo $? - bash outputs "1"
5150 debug_printf("closed FILE from child. return 0\n");
5155 static int parse_group(o_string *dest, struct parse_context *ctx,
5156 struct in_str *input, int ch)
5158 /* dest contains characters seen prior to ( or {.
5159 * Typically it's empty, but for function defs,
5160 * it contains function name (without '()'). */
5161 struct pipe *pipe_list;
5163 struct command *command = ctx->command;
5165 debug_printf_parse("parse_group entered\n");
5166 #if ENABLE_HUSH_FUNCTIONS
5167 if (ch == '(' && !dest->o_quoted) {
5169 if (done_word(dest, ctx))
5172 goto skip; /* (... */
5173 if (command->argv[1]) { /* word word ... (... */
5174 syntax_error_unexpected_ch('(');
5177 /* it is "word(..." or "word (..." */
5179 ch = i_getch(input);
5180 while (ch == ' ' || ch == '\t');
5182 syntax_error_unexpected_ch(ch);
5185 nommu_addchr(&ctx->as_string, ch);
5187 ch = i_getch(input);
5188 while (ch == ' ' || ch == '\t' || ch == '\n');
5190 syntax_error_unexpected_ch(ch);
5193 nommu_addchr(&ctx->as_string, ch);
5194 command->grp_type = GRP_FUNCTION;
5198 if (command->argv /* word [word]{... */
5199 || dest->length /* word{... */
5200 || dest->o_quoted /* ""{... */
5203 debug_printf_parse("parse_group return 1: "
5204 "syntax error, groups and arglists don't mix\n");
5208 #if ENABLE_HUSH_FUNCTIONS
5214 command->grp_type = GRP_SUBSHELL;
5216 /* bash does not allow "{echo...", requires whitespace */
5217 ch = i_getch(input);
5218 if (ch != ' ' && ch != '\t' && ch != '\n') {
5219 syntax_error_unexpected_ch(ch);
5222 nommu_addchr(&ctx->as_string, ch);
5227 char *as_string = NULL;
5229 pipe_list = parse_stream(&as_string, input, endch);
5232 o_addstr(&ctx->as_string, as_string);
5234 /* empty ()/{} or parse error? */
5235 if (!pipe_list || pipe_list == ERR_PTR) {
5236 /* parse_stream already emitted error msg */
5240 debug_printf_parse("parse_group return 1: "
5241 "parse_stream returned %p\n", pipe_list);
5244 command->group = pipe_list;
5246 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5247 command->group_as_string = as_string;
5248 debug_printf_parse("end of group, remembering as:'%s'\n",
5249 command->group_as_string);
5252 debug_printf_parse("parse_group return 0\n");
5254 /* command remains "open", available for possible redirects */
5257 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5258 /* Subroutines for copying $(...) and `...` things */
5259 static void add_till_backquote(o_string *dest, struct in_str *input);
5261 static void add_till_single_quote(o_string *dest, struct in_str *input)
5264 int ch = i_getch(input);
5266 syntax_error_unterm_ch('\'');
5267 /*xfunc_die(); - redundant */
5274 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5275 static void add_till_double_quote(o_string *dest, struct in_str *input)
5278 int ch = i_getch(input);
5280 syntax_error_unterm_ch('"');
5281 /*xfunc_die(); - redundant */
5285 if (ch == '\\') { /* \x. Copy both chars. */
5287 ch = i_getch(input);
5291 add_till_backquote(dest, input);
5295 //if (ch == '$') ...
5298 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5300 * "Within the backquoted style of command substitution, backslash
5301 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5302 * The search for the matching backquote shall be satisfied by the first
5303 * backquote found without a preceding backslash; during this search,
5304 * if a non-escaped backquote is encountered within a shell comment,
5305 * a here-document, an embedded command substitution of the $(command)
5306 * form, or a quoted string, undefined results occur. A single-quoted
5307 * or double-quoted string that begins, but does not end, within the
5308 * "`...`" sequence produces undefined results."
5310 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5312 static void add_till_backquote(o_string *dest, struct in_str *input)
5315 int ch = i_getch(input);
5317 syntax_error_unterm_ch('`');
5318 /*xfunc_die(); - redundant */
5323 /* \x. Copy both chars unless it is \` */
5324 int ch2 = i_getch(input);
5326 syntax_error_unterm_ch('`');
5327 /*xfunc_die(); - redundant */
5329 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5336 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5337 * quoting and nested ()s.
5338 * "With the $(command) style of command substitution, all characters
5339 * following the open parenthesis to the matching closing parenthesis
5340 * constitute the command. Any valid shell script can be used for command,
5341 * except a script consisting solely of redirections which produces
5342 * unspecified results."
5344 * echo $(echo '(TEST)' BEST) (TEST) BEST
5345 * echo $(echo 'TEST)' BEST) TEST) BEST
5346 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5348 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5352 int ch = i_getch(input);
5354 syntax_error_unterm_ch(')');
5355 /*xfunc_die(); - redundant */
5363 if (i_peek(input) == ')') {
5371 add_till_single_quote(dest, input);
5376 add_till_double_quote(dest, input);
5381 /* \x. Copy verbatim. Important for \(, \) */
5382 ch = i_getch(input);
5384 syntax_error_unterm_ch(')');
5385 /*xfunc_die(); - redundant */
5392 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5394 /* Return code: 0 for OK, 1 for syntax error */
5396 #define handle_dollar(as_string, dest, input) \
5397 handle_dollar(dest, input)
5399 static int handle_dollar(o_string *as_string,
5401 struct in_str *input)
5403 int ch = i_peek(input); /* first character after the $ */
5404 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5406 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5408 ch = i_getch(input);
5409 nommu_addchr(as_string, ch);
5411 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5413 debug_printf_parse(": '%c'\n", ch);
5414 o_addchr(dest, ch | quote_mask);
5417 if (!isalnum(ch) && ch != '_')
5419 ch = i_getch(input);
5420 nommu_addchr(as_string, ch);
5422 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5423 } else if (isdigit(ch)) {
5425 ch = i_getch(input);
5426 nommu_addchr(as_string, ch);
5427 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5428 debug_printf_parse(": '%c'\n", ch);
5429 o_addchr(dest, ch | quote_mask);
5430 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5431 } else switch (ch) {
5433 case '!': /* last bg pid */
5434 case '?': /* last exit code */
5435 case '#': /* number of args */
5436 case '*': /* args */
5437 case '@': /* args */
5438 goto make_one_char_var;
5440 bool first_char, all_digits;
5443 ch = i_getch(input);
5444 nommu_addchr(as_string, ch);
5445 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5447 /* TODO: maybe someone will try to escape the '}' */
5452 ch = i_getch(input);
5453 nommu_addchr(as_string, ch);
5460 /* ${#var}: length of var contents */
5467 /* They're being verbose and doing ${?} */
5468 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5473 && ( (all_digits && !isdigit(ch))
5474 || (!all_digits && !isalnum(ch) && ch != '_')
5477 /* handle parameter expansions
5478 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5483 case ':': /* null modifier */
5484 if (expansion == 0) {
5485 debug_printf_parse(": null modifier\n");
5490 case '#': /* remove prefix */
5491 case '%': /* remove suffix */
5492 if (expansion == 0) {
5493 debug_printf_parse(": remove suffix/prefix\n");
5498 case '-': /* default value */
5499 case '=': /* assign default */
5500 case '+': /* alternative */
5501 case '?': /* error indicate */
5502 debug_printf_parse(": parameter expansion\n");
5507 syntax_error_unterm_str("${name}");
5508 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5513 debug_printf_parse(": '%c'\n", ch);
5514 o_addchr(dest, ch | quote_mask);
5518 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5521 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5526 ch = i_getch(input);
5527 nommu_addchr(as_string, ch);
5528 # if ENABLE_SH_MATH_SUPPORT
5529 if (i_peek(input) == '(') {
5530 ch = i_getch(input);
5531 nommu_addchr(as_string, ch);
5532 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5533 o_addchr(dest, /*quote_mask |*/ '+');
5537 add_till_closing_paren(dest, input, true);
5540 o_addstr(as_string, dest->data + pos);
5541 o_addchr(as_string, ')');
5542 o_addchr(as_string, ')');
5545 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5549 # if ENABLE_HUSH_TICK
5550 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5551 o_addchr(dest, quote_mask | '`');
5555 add_till_closing_paren(dest, input, false);
5558 o_addstr(as_string, dest->data + pos);
5559 o_addchr(as_string, '`');
5562 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5568 ch = i_getch(input);
5569 nommu_addchr(as_string, ch);
5571 if (isalnum(ch)) { /* it's $_name or $_123 */
5577 /* $_ Shell or shell script name; or last cmd name */
5578 /* $- Option flags set by set builtin or shell options (-i etc) */
5580 o_addQchr(dest, '$');
5582 debug_printf_parse("handle_dollar return 0\n");
5587 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5588 parse_stream_dquoted(dest, input, dquote_end)
5590 static int parse_stream_dquoted(o_string *as_string,
5592 struct in_str *input,
5599 ch = i_getch(input);
5601 nommu_addchr(as_string, ch);
5602 if (ch == dquote_end) { /* may be only '"' or EOF */
5603 if (dest->o_assignment == NOT_ASSIGNMENT)
5604 dest->o_escape ^= 1;
5605 debug_printf_parse("parse_stream_dquoted return 0\n");
5608 /* note: can't move it above ch == dquote_end check! */
5610 syntax_error_unterm_ch('"');
5611 /*xfunc_die(); - redundant */
5615 next = i_peek(input);
5617 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5618 ch, ch, dest->o_escape);
5621 syntax_error("\\<eof>");
5625 * "The backslash retains its special meaning [in "..."]
5626 * only when followed by one of the following characters:
5627 * $, `, ", \, or <newline>. A double quote may be quoted
5628 * within double quotes by preceding it with a backslash."
5630 if (strchr("$`\"\\\n", next) != NULL) {
5631 ch = i_getch(input);
5633 o_addqchr(dest, ch);
5634 nommu_addchr(as_string, ch);
5637 o_addqchr(dest, '\\');
5638 nommu_addchr(as_string, '\\');
5643 if (handle_dollar(as_string, dest, input) != 0) {
5644 debug_printf_parse("parse_stream_dquoted return 1: "
5645 "handle_dollar returned non-0\n");
5650 #if ENABLE_HUSH_TICK
5652 //int pos = dest->length;
5653 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5654 o_addchr(dest, 0x80 | '`');
5655 add_till_backquote(dest, input);
5656 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5657 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5661 o_addQchr(dest, ch);
5663 && (dest->o_assignment == MAYBE_ASSIGNMENT
5664 || dest->o_assignment == WORD_IS_KEYWORD)
5665 && is_well_formed_var_name(dest->data, '=')
5667 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5673 * Scan input until EOF or end_trigger char.
5674 * Return a list of pipes to execute, or NULL on EOF
5675 * or if end_trigger character is met.
5676 * On syntax error, exit is shell is not interactive,
5677 * reset parsing machinery and start parsing anew,
5678 * or return ERR_PTR.
5680 static struct pipe *parse_stream(char **pstring,
5681 struct in_str *input,
5684 struct parse_context ctx;
5685 o_string dest = NULL_O_STRING;
5689 /* Double-quote state is handled in the state variable is_in_dquote.
5690 * A single-quote triggers a bypass of the main loop until its mate is
5691 * found. When recursing, quote state is passed in via dest->o_escape.
5693 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5694 end_trigger ? : 'X');
5697 G.ifs = get_local_var_value("IFS");
5702 #if ENABLE_HUSH_INTERACTIVE
5703 input->promptmode = 0; /* PS1 */
5705 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5706 initialize_context(&ctx);
5711 const char *is_special;
5715 redir_type redir_style;
5718 /* dest.o_quoted = 1; - already is (see below) */
5719 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5722 /* We reached closing '"' */
5725 ch = i_getch(input);
5726 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5727 ch, ch, dest.o_escape);
5732 syntax_error_unterm_str("here document");
5735 /* end_trigger == '}' case errors out earlier,
5736 * checking only ')' */
5737 if (end_trigger == ')') {
5738 syntax_error_unterm_ch('('); /* exits */
5739 /* goto parse_error; */
5742 if (done_word(&dest, &ctx)) {
5746 done_pipe(&ctx, PIPE_SEQ);
5748 /* If we got nothing... */
5749 /* (this makes bare "&" cmd a no-op.
5750 * bash says: "syntax error near unexpected token '&'") */
5751 if (pi->num_cmds == 0
5752 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5758 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5760 *pstring = ctx.as_string.data;
5762 o_free_unsafe(&ctx.as_string);
5765 debug_printf_parse("parse_stream return %p\n", pi);
5768 nommu_addchr(&ctx.as_string, ch);
5769 is_ifs = strchr(G.ifs, ch);
5770 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5771 "\\$\"" IF_HUSH_TICK("`") /* always special */
5774 if (!is_special && !is_ifs) { /* ordinary char */
5776 o_addQchr(&dest, ch);
5777 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5778 || dest.o_assignment == WORD_IS_KEYWORD)
5780 && is_well_formed_var_name(dest.data, '=')
5782 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5788 if (done_word(&dest, &ctx)) {
5792 #if ENABLE_HUSH_CASE
5793 /* "case ... in <newline> word) ..." -
5794 * newlines are ignored (but ';' wouldn't be) */
5795 if (ctx.command->argv == NULL
5796 && ctx.ctx_res_w == RES_MATCH
5801 /* Treat newline as a command separator. */
5802 done_pipe(&ctx, PIPE_SEQ);
5803 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5805 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5810 dest.o_assignment = MAYBE_ASSIGNMENT;
5812 /* note: if (is_ifs) continue;
5813 * will still trigger for us */
5817 /* "cmd}" or "cmd }..." without semicolon or &:
5818 * } is an ordinary char in this case, even inside { cmd; }
5819 * Pathological example: { ""}; } should exec "}" cmd
5822 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5823 || dest.length != 0 /* word} */
5824 || dest.o_quoted /* ""} */
5828 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5829 goto skip_end_trigger;
5830 /* else: } does terminate a group */
5833 if (end_trigger && end_trigger == ch
5834 && (ch != ';' || heredoc_cnt == 0)
5835 #if ENABLE_HUSH_CASE
5837 || ctx.ctx_res_w != RES_MATCH
5838 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5843 /* This is technically valid:
5844 * { cat <<HERE; }; echo Ok
5848 * but we don't support this.
5849 * We require heredoc to be in enclosing {}/(),
5852 syntax_error_unterm_str("here document");
5855 if (done_word(&dest, &ctx)) {
5858 done_pipe(&ctx, PIPE_SEQ);
5859 dest.o_assignment = MAYBE_ASSIGNMENT;
5860 /* Do we sit outside of any if's, loops or case's? */
5862 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5866 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5868 *pstring = ctx.as_string.data;
5870 o_free_unsafe(&ctx.as_string);
5873 debug_printf_parse("parse_stream return %p: "
5874 "end_trigger char found\n",
5876 return ctx.list_head;
5885 next = i_peek(input);
5888 /* Catch <, > before deciding whether this word is
5889 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5892 redir_fd = redirect_opt_num(&dest);
5893 if (done_word(&dest, &ctx)) {
5896 redir_style = REDIRECT_OVERWRITE;
5898 redir_style = REDIRECT_APPEND;
5899 ch = i_getch(input);
5900 nommu_addchr(&ctx.as_string, ch);
5903 else if (next == '(') {
5904 syntax_error(">(process) not supported");
5908 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5910 continue; /* back to top of while (1) */
5912 redir_fd = redirect_opt_num(&dest);
5913 if (done_word(&dest, &ctx)) {
5916 redir_style = REDIRECT_INPUT;
5918 redir_style = REDIRECT_HEREDOC;
5920 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5921 ch = i_getch(input);
5922 nommu_addchr(&ctx.as_string, ch);
5923 } else if (next == '>') {
5924 redir_style = REDIRECT_IO;
5925 ch = i_getch(input);
5926 nommu_addchr(&ctx.as_string, ch);
5929 else if (next == '(') {
5930 syntax_error("<(process) not supported");
5934 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5936 continue; /* back to top of while (1) */
5939 if (dest.o_assignment == MAYBE_ASSIGNMENT
5940 /* check that we are not in word in "a=1 2>word b=1": */
5941 && !ctx.pending_redirect
5943 /* ch is a special char and thus this word
5944 * cannot be an assignment */
5945 dest.o_assignment = NOT_ASSIGNMENT;
5950 if (dest.length == 0) {
5953 if (ch == EOF || ch == '\n')
5956 /* note: we do not add it to &ctx.as_string */
5958 nommu_addchr(&ctx.as_string, '\n');
5960 o_addQchr(&dest, ch);
5965 syntax_error("\\<eof>");
5968 ch = i_getch(input);
5970 o_addchr(&dest, '\\');
5971 nommu_addchr(&ctx.as_string, '\\');
5972 o_addchr(&dest, ch);
5973 nommu_addchr(&ctx.as_string, ch);
5974 /* Example: echo Hello \2>file
5975 * we need to know that word 2 is quoted */
5980 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5981 debug_printf_parse("parse_stream parse error: "
5982 "handle_dollar returned non-0\n");
5989 ch = i_getch(input);
5991 syntax_error_unterm_ch('\'');
5992 /*xfunc_die(); - redundant */
5994 nommu_addchr(&ctx.as_string, ch);
5997 o_addqchr(&dest, ch);
6002 is_in_dquote ^= 1; /* invert */
6003 if (dest.o_assignment == NOT_ASSIGNMENT)
6006 #if ENABLE_HUSH_TICK
6011 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6012 o_addchr(&dest, '`');
6016 add_till_backquote(&dest, input);
6018 o_addstr(&ctx.as_string, dest.data + pos);
6019 o_addchr(&ctx.as_string, '`');
6021 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6022 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6027 #if ENABLE_HUSH_CASE
6030 if (done_word(&dest, &ctx)) {
6033 done_pipe(&ctx, PIPE_SEQ);
6034 #if ENABLE_HUSH_CASE
6035 /* Eat multiple semicolons, detect
6036 * whether it means something special */
6041 ch = i_getch(input);
6042 nommu_addchr(&ctx.as_string, ch);
6043 if (ctx.ctx_res_w == RES_CASE_BODY) {
6044 ctx.ctx_dsemicolon = 1;
6045 ctx.ctx_res_w = RES_MATCH;
6051 /* We just finished a cmd. New one may start
6052 * with an assignment */
6053 dest.o_assignment = MAYBE_ASSIGNMENT;
6056 if (done_word(&dest, &ctx)) {
6060 ch = i_getch(input);
6061 nommu_addchr(&ctx.as_string, ch);
6062 done_pipe(&ctx, PIPE_AND);
6064 done_pipe(&ctx, PIPE_BG);
6068 if (done_word(&dest, &ctx)) {
6071 #if ENABLE_HUSH_CASE
6072 if (ctx.ctx_res_w == RES_MATCH)
6073 break; /* we are in case's "word | word)" */
6075 if (next == '|') { /* || */
6076 ch = i_getch(input);
6077 nommu_addchr(&ctx.as_string, ch);
6078 done_pipe(&ctx, PIPE_OR);
6080 /* we could pick up a file descriptor choice here
6081 * with redirect_opt_num(), but bash doesn't do it.
6082 * "echo foo 2| cat" yields "foo 2". */
6087 #if ENABLE_HUSH_CASE
6088 /* "case... in [(]word)..." - skip '(' */
6089 if (ctx.ctx_res_w == RES_MATCH
6090 && ctx.command->argv == NULL /* not (word|(... */
6091 && dest.length == 0 /* not word(... */
6092 && dest.o_quoted == 0 /* not ""(... */
6098 if (parse_group(&dest, &ctx, input, ch) != 0) {
6103 #if ENABLE_HUSH_CASE
6104 if (ctx.ctx_res_w == RES_MATCH)
6108 /* proper use of this character is caught by end_trigger:
6109 * if we see {, we call parse_group(..., end_trigger='}')
6110 * and it will match } earlier (not here). */
6111 syntax_error_unexpected_ch(ch);
6115 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6121 struct parse_context *pctx;
6122 IF_HAS_KEYWORDS(struct parse_context *p2;)
6124 /* Clean up allocated tree.
6125 * Samples for finding leaks on syntax error recovery path.
6126 * Run them from interactive shell, watch pmap `pidof hush`.
6127 * while if false; then false; fi do break; done
6129 * while if false; then false; fi; do break; fi
6130 * Samples to catch leaks at execution:
6131 * while if (true | {true;}); then echo ok; fi; do break; done
6132 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6136 /* Update pipe/command counts,
6137 * otherwise freeing may miss some */
6138 done_pipe(pctx, PIPE_SEQ);
6139 debug_printf_clean("freeing list %p from ctx %p\n",
6140 pctx->list_head, pctx);
6141 debug_print_tree(pctx->list_head, 0);
6142 free_pipe_list(pctx->list_head);
6143 debug_printf_clean("freed list %p\n", pctx->list_head);
6145 o_free_unsafe(&pctx->as_string);
6147 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6151 IF_HAS_KEYWORDS(pctx = p2;)
6152 } while (HAS_KEYWORDS && pctx);
6153 /* Free text, clear all dest fields */
6155 /* If we are not in top-level parse, we return,
6156 * our caller will propagate error.
6158 if (end_trigger != ';') {
6166 /* Discard cached input, force prompt */
6168 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6173 /* Executing from string: eval, sh -c '...'
6174 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6175 * end_trigger controls how often we stop parsing
6176 * NUL: parse all, execute, return
6177 * ';': parse till ';' or newline, execute, repeat till EOF
6179 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6182 struct pipe *pipe_list;
6184 pipe_list = parse_stream(NULL, inp, end_trigger);
6185 if (!pipe_list) /* EOF */
6187 debug_print_tree(pipe_list, 0);
6188 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6189 run_and_free_list(pipe_list);
6193 static void parse_and_run_string(const char *s)
6195 struct in_str input;
6196 setup_string_in_str(&input, s);
6197 parse_and_run_stream(&input, '\0');
6200 static void parse_and_run_file(FILE *f)
6202 struct in_str input;
6203 setup_file_in_str(&input, f);
6204 parse_and_run_stream(&input, ';');
6207 /* Called a few times only (or even once if "sh -c") */
6208 static void block_signals(int second_time)
6213 mask = (1 << SIGQUIT);
6214 if (G_interactive_fd) {
6215 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6216 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6217 mask |= SPECIAL_JOB_SIGS;
6219 G.non_DFL_mask = mask;
6222 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6226 sigaddset(&G.blocked_set, sig);
6230 sigdelset(&G.blocked_set, SIGCHLD);
6232 sigprocmask(SIG_SETMASK, &G.blocked_set,
6233 second_time ? NULL : &G.inherited_set);
6234 /* POSIX allows shell to re-enable SIGCHLD
6235 * even if it was SIG_IGN on entry */
6236 #if ENABLE_HUSH_FAST
6237 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6239 signal(SIGCHLD, SIGCHLD_handler);
6242 signal(SIGCHLD, SIG_DFL);
6248 static void maybe_set_to_sigexit(int sig)
6250 void (*handler)(int);
6251 /* non_DFL_mask'ed signals are, well, masked,
6252 * no need to set handler for them.
6254 if (!((G.non_DFL_mask >> sig) & 1)) {
6255 handler = signal(sig, sigexit);
6256 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6257 signal(sig, handler);
6260 /* Set handlers to restore tty pgrp and exit */
6261 static void set_fatal_handlers(void)
6263 /* We _must_ restore tty pgrp on fatal signals */
6265 maybe_set_to_sigexit(SIGILL );
6266 maybe_set_to_sigexit(SIGFPE );
6267 maybe_set_to_sigexit(SIGBUS );
6268 maybe_set_to_sigexit(SIGSEGV);
6269 maybe_set_to_sigexit(SIGTRAP);
6270 } /* else: hush is perfect. what SEGV? */
6271 maybe_set_to_sigexit(SIGABRT);
6272 /* bash 3.2 seems to handle these just like 'fatal' ones */
6273 maybe_set_to_sigexit(SIGPIPE);
6274 maybe_set_to_sigexit(SIGALRM);
6275 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6276 * if we aren't interactive... but in this case
6277 * we never want to restore pgrp on exit, and this fn is not called */
6278 /*maybe_set_to_sigexit(SIGHUP );*/
6279 /*maybe_set_to_sigexit(SIGTERM);*/
6280 /*maybe_set_to_sigexit(SIGINT );*/
6284 static int set_mode(const char cstate, const char mode)
6286 int state = (cstate == '-' ? 1 : 0);
6288 case 'n': G.fake_mode = state; break;
6289 case 'x': /*G.debug_mode = state;*/ break;
6290 default: return EXIT_FAILURE;
6292 return EXIT_SUCCESS;
6295 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6296 int hush_main(int argc, char **argv)
6298 static const struct variable const_shell_ver = {
6300 .varstr = (char*)hush_version_str,
6301 .max_len = 1, /* 0 can provoke free(name) */
6305 int signal_mask_is_inited = 0;
6307 unsigned builtin_argc;
6309 struct variable *cur_var;
6312 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6313 G.last_exitcode = EXIT_SUCCESS;
6315 G.argv0_for_re_execing = argv[0];
6317 /* Deal with HUSH_VERSION */
6318 G.shell_ver = const_shell_ver; /* copying struct here */
6319 G.top_var = &G.shell_ver;
6320 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6321 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6322 /* Initialize our shell local variables with the values
6323 * currently living in the environment */
6324 cur_var = G.top_var;
6327 char *value = strchr(*e, '=');
6328 if (value) { /* paranoia */
6329 cur_var->next = xzalloc(sizeof(*cur_var));
6330 cur_var = cur_var->next;
6331 cur_var->varstr = *e;
6332 cur_var->max_len = strlen(*e);
6333 cur_var->flg_export = 1;
6337 debug_printf_env("putenv '%s'\n", hush_version_str);
6338 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6339 #if ENABLE_FEATURE_EDITING
6340 G.line_input_state = new_line_input_t(FOR_SHELL);
6342 G.global_argc = argc;
6343 G.global_argv = argv;
6344 /* Initialize some more globals to non-zero values */
6345 cmdedit_update_prompt();
6347 if (setjmp(die_jmp)) {
6348 /* xfunc has failed! die die die */
6349 /* no EXIT traps, this is an escape hatch! */
6351 hush_exit(xfunc_error_retval);
6354 /* Shell is non-interactive at first. We need to call
6355 * block_signals(0) if we are going to execute "sh <script>",
6356 * "sh -c <cmds>" or login shell's /etc/profile and friends.
6357 * If we later decide that we are interactive, we run block_signals(0)
6358 * (or re-run block_signals(1) if we ran block_signals(0) before)
6359 * in order to intercept (more) signals.
6363 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6366 opt = getopt(argc, argv, "c:xins"
6369 # if ENABLE_HUSH_FUNCTIONS
6379 * sh ... -c 'script'
6380 * sh ... -c 'script' ARG0 [ARG1...]
6381 * On NOMMU, if builtin_argc != 0,
6382 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6383 * "" needs to be replaced with NULL
6384 * and BARGV vector fed to builtin function.
6385 * Note: this form never happens:
6386 * sh ... -c 'builtin' [BARGV...] ""
6389 G.root_pid = getpid();
6390 G.global_argv = argv + optind;
6391 G.global_argc = argc - optind;
6393 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6394 const struct built_in_command *x;
6396 block_signals(0); /* 0: called 1st time */
6397 x = find_builtin(optarg);
6398 if (x) { /* paranoia */
6399 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6400 G.global_argv += builtin_argc;
6401 G.global_argv[-1] = NULL; /* replace "" */
6402 G.last_exitcode = x->function(argv + optind - 1);
6406 if (!G.global_argv[0]) {
6407 /* -c 'script' (no params): prevent empty $0 */
6408 G.global_argv--; /* points to argv[i] of 'script' */
6409 G.global_argv[0] = argv[0];
6411 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6412 block_signals(0); /* 0: called 1st time */
6413 parse_and_run_string(optarg);
6416 /* Well, we cannot just declare interactiveness,
6417 * we have to have some stuff (ctty, etc) */
6418 /* G_interactive_fd++; */
6421 /* "-s" means "read from stdin", but this is how we always
6422 * operate, so simply do nothing here. */
6425 case '<': /* "big heredoc" support */
6426 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6429 G.root_pid = bb_strtou(optarg, &optarg, 16);
6431 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6433 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6435 builtin_argc = bb_strtou(optarg, &optarg, 16);
6436 # if ENABLE_HUSH_LOOPS
6438 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6443 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6445 # if ENABLE_HUSH_FUNCTIONS
6447 struct function *funcp = new_function(optarg);
6448 /* funcp->name is already set to optarg */
6449 /* funcp->body is set to NULL. It's a special case. */
6450 funcp->body_as_string = argv[optind];
6458 if (!set_mode('-', opt))
6462 fprintf(stderr, "Usage: sh [FILE]...\n"
6463 " or: sh -c command [args]...\n\n");
6469 } /* option parsing loop */
6472 G.root_pid = getpid();
6474 /* If we are login shell... */
6475 if (argv[0] && argv[0][0] == '-') {
6477 debug_printf("sourcing /etc/profile\n");
6478 input = fopen_for_read("/etc/profile");
6479 if (input != NULL) {
6480 close_on_exec_on(fileno(input));
6481 block_signals(0); /* 0: called 1st time */
6482 signal_mask_is_inited = 1;
6483 parse_and_run_file(input);
6486 /* bash: after sourcing /etc/profile,
6487 * tries to source (in the given order):
6488 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6489 * stopping on first found. --noprofile turns this off.
6490 * bash also sources ~/.bash_logout on exit.
6491 * If called as sh, skips .bash_XXX files.
6498 * "bash <script>" (which is never interactive (unless -i?))
6499 * sources $BASH_ENV here (without scanning $PATH).
6500 * If called as sh, does the same but with $ENV.
6502 debug_printf("running script '%s'\n", argv[optind]);
6503 G.global_argv = argv + optind;
6504 G.global_argc = argc - optind;
6505 input = xfopen_for_read(argv[optind]);
6506 close_on_exec_on(fileno(input));
6507 if (!signal_mask_is_inited)
6508 block_signals(0); /* 0: called 1st time */
6509 parse_and_run_file(input);
6510 #if ENABLE_FEATURE_CLEAN_UP
6516 /* Up to here, shell was non-interactive. Now it may become one.
6517 * NB: don't forget to (re)run block_signals(0/1) as needed.
6520 /* A shell is interactive if the '-i' flag was given,
6521 * or if all of the following conditions are met:
6523 * no arguments remaining or the -s flag given
6524 * standard input is a terminal
6525 * standard output is a terminal
6526 * Refer to Posix.2, the description of the 'sh' utility.
6529 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6530 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6531 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6532 if (G_saved_tty_pgrp < 0)
6533 G_saved_tty_pgrp = 0;
6535 /* try to dup stdin to high fd#, >= 255 */
6536 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6537 if (G_interactive_fd < 0) {
6538 /* try to dup to any fd */
6539 G_interactive_fd = dup(STDIN_FILENO);
6540 if (G_interactive_fd < 0) {
6542 G_interactive_fd = 0;
6543 G_saved_tty_pgrp = 0;
6546 // TODO: track & disallow any attempts of user
6547 // to (inadvertently) close/redirect G_interactive_fd
6549 debug_printf("interactive_fd:%d\n", G_interactive_fd);
6550 if (G_interactive_fd) {
6551 close_on_exec_on(G_interactive_fd);
6553 if (G_saved_tty_pgrp) {
6554 /* If we were run as 'hush &', sleep until we are
6555 * in the foreground (tty pgrp == our pgrp).
6556 * If we get started under a job aware app (like bash),
6557 * make sure we are now in charge so we don't fight over
6558 * who gets the foreground */
6560 pid_t shell_pgrp = getpgrp();
6561 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6562 if (G_saved_tty_pgrp == shell_pgrp)
6564 /* send TTIN to ourself (should stop us) */
6565 kill(- shell_pgrp, SIGTTIN);
6569 /* Block some signals */
6570 block_signals(signal_mask_is_inited);
6572 if (G_saved_tty_pgrp) {
6573 /* Set other signals to restore saved_tty_pgrp */
6574 set_fatal_handlers();
6575 /* Put ourselves in our own process group
6576 * (bash, too, does this only if ctty is available) */
6577 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6578 /* Grab control of the terminal */
6579 tcsetpgrp(G_interactive_fd, getpid());
6581 /* -1 is special - makes xfuncs longjmp, not exit
6582 * (we reset die_sleep = 0 whereever we [v]fork) */
6583 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6584 } else if (!signal_mask_is_inited) {
6585 block_signals(0); /* 0: called 1st time */
6586 } /* else: block_signals(0) was done before */
6587 #elif ENABLE_HUSH_INTERACTIVE
6588 /* No job control compiled in, only prompt/line editing */
6589 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6590 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6591 if (G_interactive_fd < 0) {
6592 /* try to dup to any fd */
6593 G_interactive_fd = dup(STDIN_FILENO);
6594 if (G_interactive_fd < 0)
6596 G_interactive_fd = 0;
6599 if (G_interactive_fd) {
6600 close_on_exec_on(G_interactive_fd);
6601 block_signals(signal_mask_is_inited);
6602 } else if (!signal_mask_is_inited) {
6606 /* We have interactiveness code disabled */
6607 if (!signal_mask_is_inited) {
6612 * if interactive but not a login shell, sources ~/.bashrc
6613 * (--norc turns this off, --rcfile <file> overrides)
6616 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6617 printf("\n\n%s hush - the humble shell\n", bb_banner);
6618 if (ENABLE_HUSH_HELP)
6619 puts("Enter 'help' for a list of built-in commands.");
6623 parse_and_run_file(stdin);
6626 #if ENABLE_FEATURE_CLEAN_UP
6627 if (G.cwd != bb_msg_unknown)
6629 cur_var = G.top_var->next;
6631 struct variable *tmp = cur_var;
6632 if (!cur_var->max_len)
6633 free(cur_var->varstr);
6634 cur_var = cur_var->next;
6638 hush_exit(G.last_exitcode);
6643 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6644 int lash_main(int argc, char **argv)
6646 //bb_error_msg("lash is deprecated, please use hush instead");
6647 return hush_main(argc, argv);
6655 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6660 static int FAST_FUNC builtin_test(char **argv)
6667 return test_main(argc, argv - argc);
6670 static int FAST_FUNC builtin_echo(char **argv)
6677 return echo_main(argc, argv - argc);
6680 static int FAST_FUNC builtin_eval(char **argv)
6682 int rcode = EXIT_SUCCESS;
6685 char *str = expand_strvec_to_string(argv);
6687 * eval "echo Hi; done" ("done" is syntax error):
6688 * "echo Hi" will not execute too.
6690 parse_and_run_string(str);
6692 rcode = G.last_exitcode;
6697 static int FAST_FUNC builtin_cd(char **argv)
6699 const char *newdir = argv[1];
6700 if (newdir == NULL) {
6701 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6702 * bash says "bash: cd: HOME not set" and does nothing
6705 newdir = get_local_var_value("HOME") ? : "/";
6707 if (chdir(newdir)) {
6708 /* Mimic bash message exactly */
6709 bb_perror_msg("cd: %s", newdir);
6710 return EXIT_FAILURE;
6713 return EXIT_SUCCESS;
6716 static int FAST_FUNC builtin_exec(char **argv)
6718 if (*++argv == NULL)
6719 return EXIT_SUCCESS; /* bash does this */
6724 /* TODO: if exec fails, bash does NOT exit! We do... */
6725 pseudo_exec_argv(&dummy, argv, 0, NULL);
6730 static int FAST_FUNC builtin_exit(char **argv)
6732 debug_printf_exec("%s()\n", __func__);
6734 /* interactive bash:
6735 * # trap "echo EEE" EXIT
6738 * There are stopped jobs.
6739 * (if there are _stopped_ jobs, running ones don't count)
6742 # EEE (then bash exits)
6744 * we can use G.exiting = -1 as indicator "last cmd was exit"
6747 /* note: EXIT trap is run by hush_exit */
6748 if (*++argv == NULL)
6749 hush_exit(G.last_exitcode);
6750 /* mimic bash: exit 123abc == exit 255 + error msg */
6751 xfunc_error_retval = 255;
6752 /* bash: exit -2 == exit 254, no error msg */
6753 hush_exit(xatoi(*argv) & 0xff);
6756 static void print_escaped(const char *s)
6761 const char *p = strchrnul(s, '\'');
6762 /* print 'xxxx', possibly just '' */
6763 printf("'%.*s'", (int)(p - s), s);
6768 /* s points to '; print "'''...'''" */
6770 do putchar('\''); while (*++s == '\'');
6775 #if !ENABLE_HUSH_LOCAL
6776 #define helper_export_local(argv, exp, lvl) \
6777 helper_export_local(argv, exp)
6779 static void helper_export_local(char **argv, int exp, int lvl)
6784 /* So far we do not check that name is valid (TODO?) */
6786 if (strchr(name, '=') == NULL) {
6787 struct variable *var;
6789 var = get_local_var(name);
6790 if (exp == -1) { /* unexporting? */
6791 /* export -n NAME (without =VALUE) */
6793 var->flg_export = 0;
6794 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6796 } /* else: export -n NOT_EXISTING_VAR: no-op */
6799 if (exp == 1) { /* exporting? */
6800 /* export NAME (without =VALUE) */
6802 var->flg_export = 1;
6803 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6804 putenv(var->varstr);
6808 /* Exporting non-existing variable.
6809 * bash does not put it in environment,
6810 * but remembers that it is exported,
6811 * and does put it in env when it is set later.
6812 * We just set it to "" and export. */
6813 /* Or, it's "local NAME" (without =VALUE).
6814 * bash sets the value to "". */
6815 name = xasprintf("%s=", name);
6817 /* (Un)exporting/making local NAME=VALUE */
6818 name = xstrdup(name);
6820 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6824 static int FAST_FUNC builtin_export(char **argv)
6826 unsigned opt_unexport;
6828 #if ENABLE_HUSH_EXPORT_N
6829 /* "!": do not abort on errors */
6830 opt_unexport = getopt32(argv, "!n");
6831 if (opt_unexport == (uint32_t)-1)
6832 return EXIT_FAILURE;
6839 if (argv[0] == NULL) {
6846 /* ash emits: export VAR='VAL'
6847 * bash: declare -x VAR="VAL"
6848 * we follow ash example */
6849 const char *s = *e++;
6850 const char *p = strchr(s, '=');
6852 if (!p) /* wtf? take next variable */
6855 printf("export %.*s", (int)(p - s) + 1, s);
6856 print_escaped(p + 1);
6860 /*fflush(stdout); - done after each builtin anyway */
6862 return EXIT_SUCCESS;
6865 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
6867 return EXIT_SUCCESS;
6870 #if ENABLE_HUSH_LOCAL
6871 static int FAST_FUNC builtin_local(char **argv)
6873 if (G.func_nest_level == 0) {
6874 bb_error_msg("%s: not in a function", argv[0]);
6875 return EXIT_FAILURE; /* bash compat */
6877 helper_export_local(argv, 0, G.func_nest_level);
6878 return EXIT_SUCCESS;
6882 static int FAST_FUNC builtin_trap(char **argv)
6888 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6893 /* No args: print all trapped */
6894 for (i = 0; i < NSIG; ++i) {
6897 print_escaped(G.traps[i]);
6898 printf(" %s\n", get_signame(i));
6901 /*fflush(stdout); - done after each builtin anyway */
6902 return EXIT_SUCCESS;
6906 /* If first arg is a number: reset all specified signals */
6907 sig = bb_strtou(*argv, NULL, 10);
6913 sig = get_signum(*argv++);
6914 if (sig < 0 || sig >= NSIG) {
6916 /* Mimic bash message exactly */
6917 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
6922 G.traps[sig] = xstrdup(new_cmd);
6924 debug_printf("trap: setting SIG%s (%i) to '%s'",
6925 get_signame(sig), sig, G.traps[sig]);
6927 /* There is no signal for 0 (EXIT) */
6932 sigaddset(&G.blocked_set, sig);
6934 /* There was a trap handler, we are removing it
6935 * (if sig has non-DFL handling,
6936 * we don't need to do anything) */
6937 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6939 sigdelset(&G.blocked_set, sig);
6942 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6946 if (!argv[1]) { /* no second arg */
6947 bb_error_msg("trap: invalid arguments");
6948 return EXIT_FAILURE;
6951 /* First arg is "-": reset all specified to default */
6952 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6953 /* Everything else: set arg as signal handler
6954 * (includes "" case, which ignores signal) */
6955 if (argv[0][0] == '-') {
6956 if (argv[0][1] == '\0') { /* "-" */
6957 /* new_cmd remains NULL: "reset these sigs" */
6960 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6963 /* else: "-something", no special meaning */
6968 goto process_sig_list;
6971 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
6972 static int FAST_FUNC builtin_type(char **argv)
6974 int ret = EXIT_SUCCESS;
6980 if (0) {} /* make conditional compile easier below */
6981 /*else if (find_alias(*argv))
6982 type = "an alias";*/
6983 #if ENABLE_HUSH_FUNCTIONS
6984 else if (find_function(*argv))
6985 type = "a function";
6987 else if (find_builtin(*argv))
6988 type = "a shell builtin";
6989 else if ((path = find_in_path(*argv)) != NULL)
6992 bb_error_msg("type: %s: not found", *argv);
6997 printf("%s is %s\n", *argv, type);
7005 /* built-in 'fg' and 'bg' handler */
7006 static int FAST_FUNC builtin_fg_bg(char **argv)
7011 if (!G_interactive_fd)
7012 return EXIT_FAILURE;
7014 /* If they gave us no args, assume they want the last backgrounded task */
7016 for (pi = G.job_list; pi; pi = pi->next) {
7017 if (pi->jobid == G.last_jobid) {
7021 bb_error_msg("%s: no current job", argv[0]);
7022 return EXIT_FAILURE;
7024 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7025 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7026 return EXIT_FAILURE;
7028 for (pi = G.job_list; pi; pi = pi->next) {
7029 if (pi->jobid == jobnum) {
7033 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7034 return EXIT_FAILURE;
7036 /* TODO: bash prints a string representation
7037 * of job being foregrounded (like "sleep 1 | cat") */
7038 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7039 /* Put the job into the foreground. */
7040 tcsetpgrp(G_interactive_fd, pi->pgrp);
7043 /* Restart the processes in the job */
7044 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7045 for (i = 0; i < pi->num_cmds; i++) {
7046 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7047 pi->cmds[i].is_stopped = 0;
7049 pi->stopped_cmds = 0;
7051 i = kill(- pi->pgrp, SIGCONT);
7053 if (errno == ESRCH) {
7054 delete_finished_bg_job(pi);
7055 return EXIT_SUCCESS;
7057 bb_perror_msg("kill (SIGCONT)");
7060 if (argv[0][0] == 'f') {
7062 return checkjobs_and_fg_shell(pi);
7064 return EXIT_SUCCESS;
7068 #if ENABLE_HUSH_HELP
7069 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7071 const struct built_in_command *x;
7074 "Built-in commands:\n"
7075 "------------------\n");
7076 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7078 printf("%s\t%s\n", x->cmd, x->descr);
7081 return EXIT_SUCCESS;
7086 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7089 const char *status_string;
7091 for (job = G.job_list; job; job = job->next) {
7092 if (job->alive_cmds == job->stopped_cmds)
7093 status_string = "Stopped";
7095 status_string = "Running";
7097 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7099 return EXIT_SUCCESS;
7104 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7109 /* Crude attempt to find where "free memory" starts,
7110 * sans fragmentation. */
7112 l = (unsigned long)p;
7115 if (l < (unsigned long)p) l = (unsigned long)p;
7118 if (!G.memleak_value)
7119 G.memleak_value = l;
7121 l -= G.memleak_value;
7128 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7133 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7136 return EXIT_SUCCESS;
7139 static int FAST_FUNC builtin_read(char **argv)
7142 const char *name = "REPLY";
7146 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7147 * and _after_ that_ it will complain */
7148 if (!is_well_formed_var_name(name, '\0')) {
7149 /* Mimic bash message */
7150 bb_error_msg("read: '%s': not a valid identifier", name);
7155 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7157 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7158 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7161 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7162 * built-in 'set' handler
7164 * set [-abCefhmnuvx] [-o option] [argument...]
7165 * set [+abCefhmnuvx] [+o option] [argument...]
7166 * set -- [argument...]
7169 * Implementations shall support the options in both their hyphen and
7170 * plus-sign forms. These options can also be specified as options to sh.
7172 * Write out all variables and their values: set
7173 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7174 * Turn on the -x and -v options: set -xv
7175 * Unset all positional parameters: set --
7176 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7177 * Set the positional parameters to the expansion of x, even if x expands
7178 * with a leading '-' or '+': set -- $x
7180 * So far, we only support "set -- [argument...]" and some of the short names.
7182 static int FAST_FUNC builtin_set(char **argv)
7185 char **pp, **g_argv;
7186 char *arg = *++argv;
7190 for (e = G.top_var; e; e = e->next)
7192 return EXIT_SUCCESS;
7196 if (!strcmp(arg, "--")) {
7200 if (arg[0] != '+' && arg[0] != '-')
7202 for (n = 1; arg[n]; ++n)
7203 if (set_mode(arg[0], arg[n]))
7205 } while ((arg = *++argv) != NULL);
7206 /* Now argv[0] is 1st argument */
7209 return EXIT_SUCCESS;
7212 /* NB: G.global_argv[0] ($0) is never freed/changed */
7213 g_argv = G.global_argv;
7214 if (G.global_args_malloced) {
7220 G.global_args_malloced = 1;
7221 pp = xzalloc(sizeof(pp[0]) * 2);
7222 pp[0] = g_argv[0]; /* retain $0 */
7225 /* This realloc's G.global_argv */
7226 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7233 return EXIT_SUCCESS;
7235 /* Nothing known, so abort */
7237 bb_error_msg("set: %s: invalid option", arg);
7238 return EXIT_FAILURE;
7241 static int FAST_FUNC builtin_shift(char **argv)
7247 if (n >= 0 && n < G.global_argc) {
7248 if (G.global_args_malloced) {
7251 free(G.global_argv[m++]);
7254 memmove(&G.global_argv[1], &G.global_argv[n+1],
7255 G.global_argc * sizeof(G.global_argv[0]));
7256 return EXIT_SUCCESS;
7258 return EXIT_FAILURE;
7261 static int FAST_FUNC builtin_source(char **argv)
7266 #if ENABLE_HUSH_FUNCTIONS
7270 if (*++argv == NULL)
7271 return EXIT_FAILURE;
7273 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7274 input = fopen_for_read(arg_path);
7277 input = fopen_or_warn(*argv, "r");
7279 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7280 return EXIT_FAILURE;
7282 close_on_exec_on(fileno(input));
7284 #if ENABLE_HUSH_FUNCTIONS
7285 sv_flg = G.flag_return_in_progress;
7286 /* "we are inside sourced file, ok to use return" */
7287 G.flag_return_in_progress = -1;
7289 save_and_replace_G_args(&sv, argv);
7291 parse_and_run_file(input);
7294 restore_G_args(&sv, argv);
7295 #if ENABLE_HUSH_FUNCTIONS
7296 G.flag_return_in_progress = sv_flg;
7299 return G.last_exitcode;
7302 static int FAST_FUNC builtin_umask(char **argv)
7309 mode_t old_mask = mask;
7312 rc = bb_parse_mode(argv[1], &mask);
7317 * bash: umask: 'q': invalid symbolic mode operator
7318 * bash: umask: 999: octal number out of range
7320 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7325 printf("%04o\n", (unsigned) mask);
7326 /* fall through and restore mask which we set to 0 */
7330 return !rc; /* rc != 0 - success */
7333 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7334 static int FAST_FUNC builtin_unset(char **argv)
7339 /* "!": do not abort on errors */
7340 /* "+": stop at 1st non-option */
7341 opts = getopt32(argv, "!+vf");
7342 if (opts == (unsigned)-1)
7343 return EXIT_FAILURE;
7345 bb_error_msg("unset: -v and -f are exclusive");
7346 return EXIT_FAILURE;
7352 if (!(opts & 2)) { /* not -f */
7353 if (unset_local_var(*argv)) {
7354 /* unset <nonexistent_var> doesn't fail.
7355 * Error is when one tries to unset RO var.
7356 * Message was printed by unset_local_var. */
7360 #if ENABLE_HUSH_FUNCTIONS
7370 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7371 static int FAST_FUNC builtin_wait(char **argv)
7373 int ret = EXIT_SUCCESS;
7376 if (*++argv == NULL) {
7377 /* Don't care about wait results */
7378 /* Note 1: must wait until there are no more children */
7379 /* Note 2: must be interruptible */
7381 * $ sleep 3 & sleep 6 & wait
7386 * $ sleep 3 & sleep 6 & wait
7390 * ^C <-- after ~4 sec from keyboard
7393 sigaddset(&G.blocked_set, SIGCHLD);
7394 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7397 if (errno == ECHILD)
7399 /* Wait for SIGCHLD or any other signal of interest */
7400 /* sigtimedwait with infinite timeout: */
7401 sig = sigwaitinfo(&G.blocked_set, NULL);
7403 sig = check_and_run_traps(sig);
7404 if (sig && sig != SIGCHLD) { /* see note 2 */
7410 sigdelset(&G.blocked_set, SIGCHLD);
7411 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7415 /* This is probably buggy wrt interruptible-ness */
7417 pid_t pid = bb_strtou(*argv, NULL, 10);
7419 /* mimic bash message */
7420 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7421 return EXIT_FAILURE;
7423 if (waitpid(pid, &status, 0) == pid) {
7424 if (WIFSIGNALED(status))
7425 ret = 128 + WTERMSIG(status);
7426 else if (WIFEXITED(status))
7427 ret = WEXITSTATUS(status);
7431 bb_perror_msg("wait %s", *argv);
7440 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7441 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7444 def = bb_strtou(argv[1], NULL, 10);
7445 if (errno || def < def_min || argv[2]) {
7446 bb_error_msg("%s: bad arguments", argv[0]);
7454 #if ENABLE_HUSH_LOOPS
7455 static int FAST_FUNC builtin_break(char **argv)
7458 if (G.depth_of_loop == 0) {
7459 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7460 return EXIT_SUCCESS; /* bash compat */
7462 G.flag_break_continue++; /* BC_BREAK = 1 */
7464 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7465 if (depth == UINT_MAX)
7466 G.flag_break_continue = BC_BREAK;
7467 if (G.depth_of_loop < depth)
7468 G.depth_break_continue = G.depth_of_loop;
7470 return EXIT_SUCCESS;
7473 static int FAST_FUNC builtin_continue(char **argv)
7475 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7476 return builtin_break(argv);
7480 #if ENABLE_HUSH_FUNCTIONS
7481 static int FAST_FUNC builtin_return(char **argv)
7485 if (G.flag_return_in_progress != -1) {
7486 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7487 return EXIT_FAILURE; /* bash compat */
7490 G.flag_return_in_progress = 1;
7493 * out of range: wraps around at 256, does not error out
7494 * non-numeric param:
7495 * f() { false; return qwe; }; f; echo $?
7496 * bash: return: qwe: numeric argument required <== we do this
7497 * 255 <== we also do this
7499 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);