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>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
87 # include <malloc.h> /* for malloc_trim */
90 /* #include <dmalloc.h> */
94 #include <sys/utsname.h> /* for setting $HOSTNAME */
96 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
98 #include "shell_common.h"
101 #if ENABLE_HUSH_RANDOM_SUPPORT
104 # define CLEAR_RANDOM_T(rnd) ((void)0)
106 #ifndef F_DUPFD_CLOEXEC
107 # define F_DUPFD_CLOEXEC F_DUPFD
110 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
114 //config: bool "hush"
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
122 //config: It will compile and work on no-mmu systems.
124 //config: It does not handle select, aliases, tilde expansion,
125 //config: &>file and >&file redirection of stdout+stderr.
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
130 //config: depends on HUSH
132 //config: Enable bash-compatible extensions.
134 //config:config HUSH_BRACE_EXPANSION
135 //config: bool "Brace expansion"
137 //config: depends on HUSH_BASH_COMPAT
139 //config: Enable {abc,def} extension.
141 //config:config HUSH_HELP
142 //config: bool "help builtin"
144 //config: depends on HUSH
146 //config: Enable help builtin in hush. Code size + ~1 kbyte.
148 //config:config HUSH_INTERACTIVE
149 //config: bool "Interactive mode"
151 //config: depends on HUSH
153 //config: Enable interactive mode (prompt and command editing).
154 //config: Without this, hush simply reads and executes commands
155 //config: from stdin just like a shell script from a file.
156 //config: No prompt, no PS1/PS2 magic shell variables.
158 //config:config HUSH_SAVEHISTORY
159 //config: bool "Save command history to .hush_history"
161 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
163 //config: Enable history saving in hush.
165 //config:config HUSH_JOB
166 //config: bool "Job control"
168 //config: depends on HUSH_INTERACTIVE
170 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171 //config: command (not entire shell), fg/bg builtins work. Without this option,
172 //config: "cmd &" still works by simply spawning a process and immediately
173 //config: prompting for next command (or executing next command in a script),
174 //config: but no separate process group is formed.
176 //config:config HUSH_TICK
177 //config: bool "Process substitution"
179 //config: depends on HUSH
181 //config: Enable process substitution `command` and $(command) in hush.
183 //config:config HUSH_IF
184 //config: bool "Support if/then/elif/else/fi"
186 //config: depends on HUSH
188 //config: Enable if/then/elif/else/fi in hush.
190 //config:config HUSH_LOOPS
191 //config: bool "Support for, while and until loops"
193 //config: depends on HUSH
195 //config: Enable for, while and until loops in hush.
197 //config:config HUSH_CASE
198 //config: bool "Support case ... esac statement"
200 //config: depends on HUSH
202 //config: Enable case ... esac statement in hush. +400 bytes.
204 //config:config HUSH_FUNCTIONS
205 //config: bool "Support funcname() { commands; } syntax"
207 //config: depends on HUSH
209 //config: Enable support for shell functions in hush. +800 bytes.
211 //config:config HUSH_LOCAL
212 //config: bool "Support local builtin"
214 //config: depends on HUSH_FUNCTIONS
216 //config: Enable support for local variables in functions.
218 //config:config HUSH_RANDOM_SUPPORT
219 //config: bool "Pseudorandom generator and $RANDOM variable"
221 //config: depends on HUSH
223 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
226 //config:config HUSH_EXPORT_N
227 //config: bool "Support 'export -n' option"
229 //config: depends on HUSH
231 //config: export -n unexports variables. It is a bash extension.
233 //config:config HUSH_MODE_X
234 //config: bool "Support 'hush -x' option and 'set -x' command"
236 //config: depends on HUSH
238 //config: This instructs hush to print commands before execution.
239 //config: Adds ~300 bytes.
242 //config: bool "msh (deprecated: aliased to hush)"
244 //config: select HUSH
246 //config: msh is deprecated and will be removed, please migrate to hush.
249 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257 /* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
262 //usage:#define hush_trivial_usage
263 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
264 //usage:#define hush_full_usage "\n\n"
265 //usage: "Unix shell interpreter"
267 //usage:#define msh_trivial_usage hush_trivial_usage
268 //usage:#define msh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
271 //usage:# define sh_trivial_usage hush_trivial_usage
272 //usage:# define sh_full_usage hush_full_usage
274 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275 //usage:# define bash_trivial_usage hush_trivial_usage
276 //usage:# define bash_full_usage hush_full_usage
281 #define LEAK_HUNTING 0
282 #define BUILD_AS_NOMMU 0
283 /* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
288 /* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
294 #define ENABLE_HUSH_FAST 0
295 /* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
298 #define ENABLE_HUSH_DOLLAR_OPS 1
303 # undef USE_FOR_NOMMU
306 # define USE_FOR_NOMMU(...) __VA_ARGS__
307 # define USE_FOR_MMU(...)
310 #include "NUM_APPLETS.h"
312 /* STANDALONE does not make sense, and won't compile */
313 # undef CONFIG_FEATURE_SH_STANDALONE
314 # undef ENABLE_FEATURE_SH_STANDALONE
315 # undef IF_FEATURE_SH_STANDALONE
316 # undef IF_NOT_FEATURE_SH_STANDALONE
317 # define ENABLE_FEATURE_SH_STANDALONE 0
318 # define IF_FEATURE_SH_STANDALONE(...)
319 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
322 #if !ENABLE_HUSH_INTERACTIVE
323 # undef ENABLE_FEATURE_EDITING
324 # define ENABLE_FEATURE_EDITING 0
325 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
327 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
328 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
331 /* Do we support ANY keywords? */
332 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
333 # define HAS_KEYWORDS 1
334 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
335 # define IF_HAS_NO_KEYWORDS(...)
337 # define HAS_KEYWORDS 0
338 # define IF_HAS_KEYWORDS(...)
339 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
342 /* If you comment out one of these below, it will be #defined later
343 * to perform debug printfs to stderr: */
344 #define debug_printf(...) do {} while (0)
345 /* Finer-grained debug switches */
346 #define debug_printf_parse(...) do {} while (0)
347 #define debug_print_tree(a, b) do {} while (0)
348 #define debug_printf_exec(...) do {} while (0)
349 #define debug_printf_env(...) do {} while (0)
350 #define debug_printf_jobs(...) do {} while (0)
351 #define debug_printf_expand(...) do {} while (0)
352 #define debug_printf_varexp(...) do {} while (0)
353 #define debug_printf_glob(...) do {} while (0)
354 #define debug_printf_list(...) do {} while (0)
355 #define debug_printf_subst(...) do {} while (0)
356 #define debug_printf_clean(...) do {} while (0)
358 #define ERR_PTR ((void*)(long)1)
360 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
362 #define _SPECIAL_VARS_STR "_*@$!?#"
363 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
364 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
365 #if ENABLE_HUSH_BASH_COMPAT
366 /* Support / and // replace ops */
367 /* Note that // is stored as \ in "encoded" string representation */
368 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
369 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
370 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
372 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
373 # define VAR_SUBST_OPS "%#:-=+?"
374 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
377 #define SPECIAL_VAR_SYMBOL 3
381 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
383 /* This supports saving pointers malloced in vfork child,
384 * to be freed in the parent.
387 typedef struct nommu_save_t {
389 struct variable *old_vars;
391 char **argv_from_re_execing;
404 #if ENABLE_HUSH_LOOPS
411 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
416 /* three pseudo-keywords support contrived "case" syntax: */
417 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
418 RES_MATCH , /* "word)" */
419 RES_CASE_BODY, /* "this command is inside CASE" */
426 typedef struct o_string {
428 int length; /* position where data is appended */
431 /* At least some part of the string was inside '' or "",
432 * possibly empty one: word"", wo''rd etc. */
433 smallint has_quoted_part;
434 smallint has_empty_slot;
435 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
438 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
440 /* Protect newly added chars against globbing
441 * by prepending \ to *, ?, [, \ */
442 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
445 MAYBE_ASSIGNMENT = 0,
446 DEFINITELY_ASSIGNMENT = 1,
448 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
451 /* Used for initialization: o_string foo = NULL_O_STRING; */
452 #define NULL_O_STRING { NULL }
454 #ifndef debug_printf_parse
455 static const char *const assignment_flag[] = {
457 "DEFINITELY_ASSIGNMENT",
463 typedef struct in_str {
465 #if ENABLE_HUSH_INTERACTIVE
466 smallint promptmode; /* 0: PS1, 1: PS2 */
471 int (*get) (struct in_str *) FAST_FUNC;
472 int (*peek) (struct in_str *) FAST_FUNC;
474 #define i_getch(input) ((input)->get(input))
475 #define i_peek(input) ((input)->peek(input))
477 /* The descrip member of this structure is only used to make
478 * debugging output pretty */
479 static const struct {
481 signed char default_fd;
484 { O_RDONLY, 0, "<" },
485 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
486 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
487 { O_CREAT|O_RDWR, 1, "<>" },
488 { O_RDONLY, 0, "<<" },
489 /* Should not be needed. Bogus default_fd helps in debugging */
490 /* { O_RDONLY, 77, "<<" }, */
493 struct redir_struct {
494 struct redir_struct *next;
495 char *rd_filename; /* filename */
496 int rd_fd; /* fd to redirect */
497 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
499 smallint rd_type; /* (enum redir_type) */
500 /* note: for heredocs, rd_filename contains heredoc delimiter,
501 * and subsequently heredoc itself; and rd_dup is a bitmask:
502 * bit 0: do we need to trim leading tabs?
503 * bit 1: is heredoc quoted (<<'delim' syntax) ?
506 typedef enum redir_type {
508 REDIRECT_OVERWRITE = 1,
511 REDIRECT_HEREDOC = 4,
512 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
515 REDIRFD_SYNTAX_ERR = -2,
516 REDIRFD_TO_FILE = -1,
517 /* otherwise, rd_fd is redirected to rd_dup */
519 HEREDOC_SKIPTABS = 1,
525 pid_t pid; /* 0 if exited */
526 int assignment_cnt; /* how many argv[i] are assignments? */
527 smallint cmd_type; /* CMD_xxx */
529 #define CMD_SUBSHELL 1
530 #if ENABLE_HUSH_BASH_COMPAT
531 /* used for "[[ EXPR ]]" */
532 # define CMD_SINGLEWORD_NOGLOB 2
534 #if ENABLE_HUSH_FUNCTIONS
535 # define CMD_FUNCDEF 3
538 smalluint cmd_exitcode;
539 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
542 char *group_as_string;
544 #if ENABLE_HUSH_FUNCTIONS
545 struct function *child_func;
546 /* This field is used to prevent a bug here:
547 * while...do f1() {a;}; f1; f1() {b;}; f1; done
548 * When we execute "f1() {a;}" cmd, we create new function and clear
549 * cmd->group, cmd->group_as_string, cmd->argv[0].
550 * When we execute "f1() {b;}", we notice that f1 exists,
551 * and that its "parent cmd" struct is still "alive",
552 * we put those fields back into cmd->xxx
553 * (struct function has ->parent_cmd ptr to facilitate that).
554 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
555 * Without this trick, loop would execute a;b;b;b;...
556 * instead of correct sequence a;b;a;b;...
557 * When command is freed, it severs the link
558 * (sets ->child_func->parent_cmd to NULL).
561 char **argv; /* command name and arguments */
562 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
563 * and on execution these are substituted with their values.
564 * Substitution can make _several_ words out of one argv[n]!
565 * Example: argv[0]=='.^C*^C.' here: echo .$*.
566 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
568 struct redir_struct *redirects; /* I/O redirections */
570 /* Is there anything in this command at all? */
571 #define IS_NULL_CMD(cmd) \
572 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
576 int num_cmds; /* total number of commands in pipe */
577 int alive_cmds; /* number of commands running (not exited) */
578 int stopped_cmds; /* number of commands alive, but stopped */
580 int jobid; /* job number */
581 pid_t pgrp; /* process group ID for the job */
582 char *cmdtext; /* name of job */
584 struct command *cmds; /* array of commands in pipe */
585 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
586 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
587 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
589 typedef enum pipe_style {
595 /* Is there anything in this pipe at all? */
596 #define IS_NULL_PIPE(pi) \
597 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
599 /* This holds pointers to the various results of parsing */
600 struct parse_context {
601 /* linked list of pipes */
602 struct pipe *list_head;
603 /* last pipe (being constructed right now) */
605 /* last command in pipe (being constructed right now) */
606 struct command *command;
607 /* last redirect in command->redirects list */
608 struct redir_struct *pending_redirect;
614 smallint ctx_inverted; /* "! cmd | cmd" */
616 smallint ctx_dsemicolon; /* ";;" seen */
618 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
620 /* group we are enclosed in:
621 * example: "if pipe1; pipe2; then pipe3; fi"
622 * when we see "if" or "then", we malloc and copy current context,
623 * and make ->stack point to it. then we parse pipeN.
624 * when closing "then" / fi" / whatever is found,
625 * we move list_head into ->stack->command->group,
626 * copy ->stack into current context, and delete ->stack.
627 * (parsing of { list } and ( list ) doesn't use this method)
629 struct parse_context *stack;
633 /* On program start, environ points to initial environment.
634 * putenv adds new pointers into it, unsetenv removes them.
635 * Neither of these (de)allocates the strings.
636 * setenv allocates new strings in malloc space and does putenv,
637 * and thus setenv is unusable (leaky) for shell's purposes */
638 #define setenv(...) setenv_is_leaky_dont_use()
640 struct variable *next;
641 char *varstr; /* points to "name=" portion */
642 #if ENABLE_HUSH_LOCAL
643 unsigned func_nest_level;
645 int max_len; /* if > 0, name is part of initial env; else name is malloced */
646 smallint flg_export; /* putenv should be done on this var */
647 smallint flg_read_only;
655 #if ENABLE_HUSH_FUNCTIONS
657 struct function *next;
659 struct command *parent_cmd;
662 char *body_as_string;
668 /* set -/+o OPT support. (TODO: make it optional)
669 * bash supports the following opts:
680 * interactive-comments on
698 static const char o_opt_strings[] ALIGN1 =
701 #if ENABLE_HUSH_MODE_X
708 #if ENABLE_HUSH_MODE_X
716 struct FILE_list *next;
722 /* "Globals" within this file */
723 /* Sorted roughly by size (smaller offsets == smaller code) */
725 /* interactive_fd != 0 means we are an interactive shell.
726 * If we are, then saved_tty_pgrp can also be != 0, meaning
727 * that controlling tty is available. With saved_tty_pgrp == 0,
728 * job control still works, but terminal signals
729 * (^C, ^Z, ^Y, ^\) won't work at all, and background
730 * process groups can only be created with "cmd &".
731 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
732 * to give tty to the foreground process group,
733 * and will take it back when the group is stopped (^Z)
736 #if ENABLE_HUSH_INTERACTIVE
737 /* 'interactive_fd' is a fd# open to ctty, if we have one
738 * _AND_ if we decided to act interactively */
742 # define G_interactive_fd (G.interactive_fd)
744 # define G_interactive_fd 0
746 #if ENABLE_FEATURE_EDITING
747 line_input_t *line_input_state;
752 #if ENABLE_HUSH_RANDOM_SUPPORT
758 pid_t saved_tty_pgrp;
759 struct pipe *job_list;
760 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
762 # define G_saved_tty_pgrp 0
764 char o_opt[NUM_OPT_O];
765 #if ENABLE_HUSH_MODE_X
766 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
770 smallint flag_SIGINT;
771 #if ENABLE_HUSH_LOOPS
772 smallint flag_break_continue;
774 #if ENABLE_HUSH_FUNCTIONS
775 /* 0: outside of a function (or sourced file)
776 * -1: inside of a function, ok to use return builtin
777 * 1: return is invoked, skip all till end of func
779 smallint flag_return_in_progress;
780 # define G_flag_return_in_progress (G.flag_return_in_progress)
782 # define G_flag_return_in_progress 0
784 smallint exiting; /* used to prevent EXIT trap recursion */
785 /* These four support $?, $#, and $1 */
786 smalluint last_exitcode;
787 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
788 smalluint global_args_malloced;
789 /* how many non-NULL argv's we have. NB: $# + 1 */
793 char *argv0_for_re_execing;
795 #if ENABLE_HUSH_LOOPS
796 unsigned depth_break_continue;
797 unsigned depth_of_loop;
801 struct variable *top_var;
802 char **expanded_assignments;
803 #if ENABLE_HUSH_FUNCTIONS
804 struct function *top_func;
805 # if ENABLE_HUSH_LOCAL
806 struct variable **shadowed_vars_pp;
807 unsigned func_nest_level;
810 /* Signal and trap handling */
812 unsigned count_SIGCHLD;
813 unsigned handled_SIGCHLD;
814 smallint we_have_children;
816 struct FILE_list *FILE_list;
817 /* Which signals have non-DFL handler (even with no traps set)?
818 * Set at the start to:
819 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
820 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
821 * The rest is cleared right before execv syscalls.
822 * Other than these two times, never modified.
824 unsigned special_sig_mask;
826 unsigned fatal_sig_mask;
827 # define G_fatal_sig_mask G.fatal_sig_mask
829 # define G_fatal_sig_mask 0
831 char **traps; /* char *traps[NSIG] */
832 sigset_t pending_set;
834 unsigned long memleak_value;
838 #if ENABLE_FEATURE_EDITING
839 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
842 #define G (*ptr_to_globals)
843 /* Not #defining name to G.name - this quickly gets unwieldy
844 * (too many defines). Also, I actually prefer to see when a variable
845 * is global, thus "G." prefix is a useful hint */
846 #define INIT_G() do { \
847 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
848 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
849 sigfillset(&G.sa.sa_mask); \
850 G.sa.sa_flags = SA_RESTART; \
854 /* Function prototypes for builtins */
855 static int builtin_cd(char **argv) FAST_FUNC;
856 static int builtin_echo(char **argv) FAST_FUNC;
857 static int builtin_eval(char **argv) FAST_FUNC;
858 static int builtin_exec(char **argv) FAST_FUNC;
859 static int builtin_exit(char **argv) FAST_FUNC;
860 static int builtin_export(char **argv) FAST_FUNC;
862 static int builtin_fg_bg(char **argv) FAST_FUNC;
863 static int builtin_jobs(char **argv) FAST_FUNC;
866 static int builtin_help(char **argv) FAST_FUNC;
868 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
869 static int builtin_history(char **argv) FAST_FUNC;
871 #if ENABLE_HUSH_LOCAL
872 static int builtin_local(char **argv) FAST_FUNC;
875 static int builtin_memleak(char **argv) FAST_FUNC;
878 static int builtin_printf(char **argv) FAST_FUNC;
880 static int builtin_pwd(char **argv) FAST_FUNC;
881 static int builtin_read(char **argv) FAST_FUNC;
882 static int builtin_set(char **argv) FAST_FUNC;
883 static int builtin_shift(char **argv) FAST_FUNC;
884 static int builtin_source(char **argv) FAST_FUNC;
885 static int builtin_test(char **argv) FAST_FUNC;
886 static int builtin_trap(char **argv) FAST_FUNC;
887 static int builtin_type(char **argv) FAST_FUNC;
888 static int builtin_true(char **argv) FAST_FUNC;
889 static int builtin_umask(char **argv) FAST_FUNC;
890 static int builtin_unset(char **argv) FAST_FUNC;
891 static int builtin_wait(char **argv) FAST_FUNC;
892 #if ENABLE_HUSH_LOOPS
893 static int builtin_break(char **argv) FAST_FUNC;
894 static int builtin_continue(char **argv) FAST_FUNC;
896 #if ENABLE_HUSH_FUNCTIONS
897 static int builtin_return(char **argv) FAST_FUNC;
900 /* Table of built-in functions. They can be forked or not, depending on
901 * context: within pipes, they fork. As simple commands, they do not.
902 * When used in non-forking context, they can change global variables
903 * in the parent shell process. If forked, of course they cannot.
904 * For example, 'unset foo | whatever' will parse and run, but foo will
905 * still be set at the end. */
906 struct built_in_command {
908 int (*b_function)(char **argv) FAST_FUNC;
911 # define BLTIN(cmd, func, help) { cmd, func, help }
913 # define BLTIN(cmd, func, help) { cmd, func }
917 static const struct built_in_command bltins1[] = {
918 BLTIN("." , builtin_source , "Run commands in a file"),
919 BLTIN(":" , builtin_true , NULL),
921 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
923 #if ENABLE_HUSH_LOOPS
924 BLTIN("break" , builtin_break , "Exit from a loop"),
926 BLTIN("cd" , builtin_cd , "Change directory"),
927 #if ENABLE_HUSH_LOOPS
928 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
930 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
931 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
932 BLTIN("exit" , builtin_exit , "Exit"),
933 BLTIN("export" , builtin_export , "Set environment variables"),
935 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
938 BLTIN("help" , builtin_help , NULL),
940 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
941 BLTIN("history" , builtin_history , "Show command history"),
944 BLTIN("jobs" , builtin_jobs , "List jobs"),
946 #if ENABLE_HUSH_LOCAL
947 BLTIN("local" , builtin_local , "Set local variables"),
950 BLTIN("memleak" , builtin_memleak , NULL),
952 BLTIN("read" , builtin_read , "Input into variable"),
953 #if ENABLE_HUSH_FUNCTIONS
954 BLTIN("return" , builtin_return , "Return from a function"),
956 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
957 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
958 #if ENABLE_HUSH_BASH_COMPAT
959 BLTIN("source" , builtin_source , "Run commands in a file"),
961 BLTIN("trap" , builtin_trap , "Trap signals"),
962 BLTIN("true" , builtin_true , NULL),
963 BLTIN("type" , builtin_type , "Show command type"),
964 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
965 BLTIN("umask" , builtin_umask , "Set file creation mask"),
966 BLTIN("unset" , builtin_unset , "Unset variables"),
967 BLTIN("wait" , builtin_wait , "Wait for process"),
969 /* For now, echo and test are unconditionally enabled.
970 * Maybe make it configurable? */
971 static const struct built_in_command bltins2[] = {
972 BLTIN("[" , builtin_test , NULL),
973 BLTIN("echo" , builtin_echo , NULL),
975 BLTIN("printf" , builtin_printf , NULL),
977 BLTIN("pwd" , builtin_pwd , NULL),
978 BLTIN("test" , builtin_test , NULL),
985 /* prevent disasters with G.debug_indent < 0 */
986 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
987 # define debug_enter() (G.debug_indent++)
988 # define debug_leave() (G.debug_indent--)
990 # define indent() ((void)0)
991 # define debug_enter() ((void)0)
992 # define debug_leave() ((void)0)
996 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
999 #ifndef debug_printf_parse
1000 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1003 #ifndef debug_printf_exec
1004 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1007 #ifndef debug_printf_env
1008 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1011 #ifndef debug_printf_jobs
1012 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1013 # define DEBUG_JOBS 1
1015 # define DEBUG_JOBS 0
1018 #ifndef debug_printf_expand
1019 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1020 # define DEBUG_EXPAND 1
1022 # define DEBUG_EXPAND 0
1025 #ifndef debug_printf_varexp
1026 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1029 #ifndef debug_printf_glob
1030 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1031 # define DEBUG_GLOB 1
1033 # define DEBUG_GLOB 0
1036 #ifndef debug_printf_list
1037 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1040 #ifndef debug_printf_subst
1041 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1044 #ifndef debug_printf_clean
1045 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1046 # define DEBUG_CLEAN 1
1048 # define DEBUG_CLEAN 0
1052 static void debug_print_strings(const char *prefix, char **vv)
1055 fdprintf(2, "%s:\n", prefix);
1057 fdprintf(2, " '%s'\n", *vv++);
1060 # define debug_print_strings(prefix, vv) ((void)0)
1064 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1067 static void *xxmalloc(int lineno, size_t size)
1069 void *ptr = xmalloc((size + 0xff) & ~0xff);
1070 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1073 static void *xxrealloc(int lineno, void *ptr, size_t size)
1075 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1076 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1079 static char *xxstrdup(int lineno, const char *str)
1081 char *ptr = xstrdup(str);
1082 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1085 static void xxfree(void *ptr)
1087 fdprintf(2, "free %p\n", ptr);
1090 # define xmalloc(s) xxmalloc(__LINE__, s)
1091 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1092 # define xstrdup(s) xxstrdup(__LINE__, s)
1093 # define free(p) xxfree(p)
1097 /* Syntax and runtime errors. They always abort scripts.
1098 * In interactive use they usually discard unparsed and/or unexecuted commands
1099 * and return to the prompt.
1100 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1103 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1104 # define syntax_error(lineno, msg) syntax_error(msg)
1105 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1106 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1107 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1108 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1111 static void die_if_script(unsigned lineno, const char *fmt, ...)
1116 bb_error_msg("hush.c:%u", lineno);
1119 bb_verror_msg(fmt, p, NULL);
1121 if (!G_interactive_fd)
1125 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1128 bb_error_msg("syntax error: %s", msg);
1130 bb_error_msg("syntax error");
1133 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1135 bb_error_msg("syntax error at '%s'", msg);
1138 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1140 bb_error_msg("syntax error: unterminated %s", s);
1143 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1145 char msg[2] = { ch, '\0' };
1146 syntax_error_unterm_str(lineno, msg);
1149 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1154 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1158 # undef die_if_script
1159 # undef syntax_error
1160 # undef syntax_error_at
1161 # undef syntax_error_unterm_ch
1162 # undef syntax_error_unterm_str
1163 # undef syntax_error_unexpected_ch
1165 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1166 # define syntax_error(msg) syntax_error(__LINE__, msg)
1167 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1168 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1169 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1170 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1174 #if ENABLE_HUSH_INTERACTIVE
1175 static void cmdedit_update_prompt(void);
1177 # define cmdedit_update_prompt() ((void)0)
1181 /* Utility functions
1183 /* Replace each \x with x in place, return ptr past NUL. */
1184 static char *unbackslash(char *src)
1186 char *dst = src = strchrnul(src, '\\');
1190 if ((*dst++ = *src++) == '\0')
1196 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1217 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1218 v[count1 + count2] = NULL;
1221 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1225 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1227 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1228 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1231 #define add_strings_to_strings(strings, add, need_to_dup) \
1232 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1235 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1236 static char **add_string_to_strings(char **strings, char *add)
1241 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1244 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1246 char **ptr = add_string_to_strings(strings, add);
1247 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1250 #define add_string_to_strings(strings, add) \
1251 xx_add_string_to_strings(__LINE__, strings, add)
1254 static void free_strings(char **strings)
1269 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1271 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1272 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1274 /* fd was not open? */
1284 /* Manipulating the list of open FILEs */
1285 static FILE *remember_FILE(FILE *fp)
1288 struct FILE_list *n = xmalloc(sizeof(*n));
1289 n->next = G.FILE_list;
1293 close_on_exec_on(n->fd);
1297 static void fclose_and_forget(FILE *fp)
1299 struct FILE_list **pp = &G.FILE_list;
1301 struct FILE_list *cur = *pp;
1302 if (cur->fp == fp) {
1311 static int save_FILEs_on_redirect(int fd)
1313 struct FILE_list *fl = G.FILE_list;
1316 /* We use it only on script files, they are all CLOEXEC */
1317 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1324 static void restore_redirected_FILEs(void)
1326 struct FILE_list *fl = G.FILE_list;
1328 int should_be = fileno(fl->fp);
1329 if (fl->fd != should_be) {
1330 xmove_fd(fl->fd, should_be);
1336 #if ENABLE_FEATURE_SH_STANDALONE
1337 static void close_all_FILE_list(void)
1339 struct FILE_list *fl = G.FILE_list;
1341 /* fclose would also free FILE object.
1342 * It is disastrous if we share memory with a vforked parent.
1343 * I'm not sure we never come here after vfork.
1344 * Therefore just close fd, nothing more.
1346 /*fclose(fl->fp); - unsafe */
1354 /* Helpers for setting new $n and restoring them back
1356 typedef struct save_arg_t {
1360 smallint sv_g_malloced;
1363 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1367 sv->sv_argv0 = argv[0];
1368 sv->sv_g_argv = G.global_argv;
1369 sv->sv_g_argc = G.global_argc;
1370 sv->sv_g_malloced = G.global_args_malloced;
1372 argv[0] = G.global_argv[0]; /* retain $0 */
1373 G.global_argv = argv;
1374 G.global_args_malloced = 0;
1382 static void restore_G_args(save_arg_t *sv, char **argv)
1386 if (G.global_args_malloced) {
1387 /* someone ran "set -- arg1 arg2 ...", undo */
1389 while (*++pp) /* note: does not free $0 */
1391 free(G.global_argv);
1393 argv[0] = sv->sv_argv0;
1394 G.global_argv = sv->sv_g_argv;
1395 G.global_argc = sv->sv_g_argc;
1396 G.global_args_malloced = sv->sv_g_malloced;
1400 /* Basic theory of signal handling in shell
1401 * ========================================
1402 * This does not describe what hush does, rather, it is current understanding
1403 * what it _should_ do. If it doesn't, it's a bug.
1404 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1406 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1407 * is finished or backgrounded. It is the same in interactive and
1408 * non-interactive shells, and is the same regardless of whether
1409 * a user trap handler is installed or a shell special one is in effect.
1410 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1411 * backgrounds (i.e. stops) or kills all members of currently running
1414 * Wait builtin is interruptible by signals for which user trap is set
1415 * or by SIGINT in interactive shell.
1417 * Trap handlers will execute even within trap handlers. (right?)
1419 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1420 * except for handlers set to '' (empty string).
1422 * If job control is off, backgrounded commands ("cmd &")
1423 * have SIGINT, SIGQUIT set to SIG_IGN.
1425 * Commands which are run in command substitution ("`cmd`")
1426 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1428 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1429 * by the shell from its parent.
1431 * Signals which differ from SIG_DFL action
1432 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1435 * SIGTERM (interactive): ignore
1436 * SIGHUP (interactive):
1437 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1438 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1439 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1440 * that all pipe members are stopped. Try this in bash:
1441 * while :; do :; done - ^Z does not background it
1442 * (while :; do :; done) - ^Z backgrounds it
1443 * SIGINT (interactive): wait for last pipe, ignore the rest
1444 * of the command line, show prompt. NB: ^C does not send SIGINT
1445 * to interactive shell while shell is waiting for a pipe,
1446 * since shell is bg'ed (is not in foreground process group).
1447 * Example 1: this waits 5 sec, but does not execute ls:
1448 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1449 * Example 2: this does not wait and does not execute ls:
1450 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1451 * Example 3: this does not wait 5 sec, but executes ls:
1452 * "sleep 5; ls -l" + press ^C
1453 * Example 4: this does not wait and does not execute ls:
1454 * "sleep 5 & wait; ls -l" + press ^C
1456 * (What happens to signals which are IGN on shell start?)
1457 * (What happens with signal mask on shell start?)
1459 * Old implementation
1460 * ==================
1461 * We use in-kernel pending signal mask to determine which signals were sent.
1462 * We block all signals which we don't want to take action immediately,
1463 * i.e. we block all signals which need to have special handling as described
1464 * above, and all signals which have traps set.
1465 * After each pipe execution, we extract any pending signals via sigtimedwait()
1468 * unsigned special_sig_mask: a mask of such "special" signals
1469 * sigset_t blocked_set: current blocked signal set
1472 * clear bit in blocked_set unless it is also in special_sig_mask
1473 * "trap 'cmd' SIGxxx":
1474 * set bit in blocked_set (even if 'cmd' is '')
1475 * after [v]fork, if we plan to be a shell:
1476 * unblock signals with special interactive handling
1477 * (child shell is not interactive),
1478 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1479 * after [v]fork, if we plan to exec:
1480 * POSIX says fork clears pending signal mask in child - no need to clear it.
1481 * Restore blocked signal set to one inherited by shell just prior to exec.
1483 * Note: as a result, we do not use signal handlers much. The only uses
1484 * are to count SIGCHLDs
1485 * and to restore tty pgrp on signal-induced exit.
1488 * Standard says "When a subshell is entered, traps that are not being ignored
1489 * are set to the default actions". bash interprets it so that traps which
1490 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1492 * Problem: the above approach makes it unwieldy to catch signals while
1493 * we are in read builtin, or while we read commands from stdin:
1494 * masked signals are not visible!
1496 * New implementation
1497 * ==================
1498 * We record each signal we are interested in by installing signal handler
1499 * for them - a bit like emulating kernel pending signal mask in userspace.
1500 * We are interested in: signals which need to have special handling
1501 * as described above, and all signals which have traps set.
1502 * Signals are recorded in pending_set.
1503 * After each pipe execution, we extract any pending signals
1506 * unsigned special_sig_mask: a mask of shell-special signals.
1507 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1508 * char *traps[sig] if trap for sig is set (even if it's '').
1509 * sigset_t pending_set: set of sigs we received.
1512 * if sig is in special_sig_mask, set handler back to:
1513 * record_pending_signo, or to IGN if it's a tty stop signal
1514 * if sig is in fatal_sig_mask, set handler back to sigexit.
1515 * else: set handler back to SIG_DFL
1516 * "trap 'cmd' SIGxxx":
1517 * set handler to record_pending_signo.
1519 * set handler to SIG_IGN.
1520 * after [v]fork, if we plan to be a shell:
1521 * set signals with special interactive handling to SIG_DFL
1522 * (because child shell is not interactive),
1523 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1524 * after [v]fork, if we plan to exec:
1525 * POSIX says fork clears pending signal mask in child - no need to clear it.
1527 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1528 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1531 * Standard says "When a subshell is entered, traps that are not being ignored
1532 * are set to the default actions". bash interprets it so that traps which
1533 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1536 SPECIAL_INTERACTIVE_SIGS = 0
1541 SPECIAL_JOBSTOP_SIGS = 0
1550 static void record_pending_signo(int sig)
1552 sigaddset(&G.pending_set, sig);
1553 #if ENABLE_HUSH_FAST
1554 if (sig == SIGCHLD) {
1556 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1561 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1563 struct sigaction old_sa;
1565 /* We could use signal() to install handlers... almost:
1566 * except that we need to mask ALL signals while handlers run.
1567 * I saw signal nesting in strace, race window isn't small.
1568 * SA_RESTART is also needed, but in Linux, signal()
1569 * sets SA_RESTART too.
1571 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1572 /* sigfillset(&G.sa.sa_mask); - already done */
1573 /* G.sa.sa_flags = SA_RESTART; - already done */
1574 G.sa.sa_handler = handler;
1575 sigaction(sig, &G.sa, &old_sa);
1576 return old_sa.sa_handler;
1579 static void hush_exit(int exitcode) NORETURN;
1580 static void fflush_and__exit(void) NORETURN;
1581 static void restore_ttypgrp_and__exit(void) NORETURN;
1583 static void restore_ttypgrp_and__exit(void)
1585 /* xfunc has failed! die die die */
1586 /* no EXIT traps, this is an escape hatch! */
1588 hush_exit(xfunc_error_retval);
1591 /* Needed only on some libc:
1592 * It was observed that on exit(), fgetc'ed buffered data
1593 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1594 * With the net effect that even after fork(), not vfork(),
1595 * exit() in NOEXECed applet in "sh SCRIPT":
1596 * noexec_applet_here
1597 * echo END_OF_SCRIPT
1598 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1599 * This makes "echo END_OF_SCRIPT" executed twice.
1600 * Similar problems can be seen with die_if_script() -> xfunc_die()
1601 * and in `cmd` handling.
1602 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1604 static void fflush_and__exit(void)
1607 _exit(xfunc_error_retval);
1612 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1613 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1614 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1615 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1617 /* Restores tty foreground process group, and exits.
1618 * May be called as signal handler for fatal signal
1619 * (will resend signal to itself, producing correct exit state)
1620 * or called directly with -EXITCODE.
1621 * We also call it if xfunc is exiting.
1623 static void sigexit(int sig) NORETURN;
1624 static void sigexit(int sig)
1626 /* Careful: we can end up here after [v]fork. Do not restore
1627 * tty pgrp then, only top-level shell process does that */
1628 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1629 /* Disable all signals: job control, SIGPIPE, etc.
1630 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1632 sigprocmask_allsigs(SIG_BLOCK);
1633 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1636 /* Not a signal, just exit */
1640 kill_myself_with_sig(sig); /* does not return */
1644 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1645 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1649 static sighandler_t pick_sighandler(unsigned sig)
1651 sighandler_t handler = SIG_DFL;
1652 if (sig < sizeof(unsigned)*8) {
1653 unsigned sigmask = (1 << sig);
1657 if (G_fatal_sig_mask & sigmask)
1661 /* sig has special handling? */
1662 if (G.special_sig_mask & sigmask) {
1663 handler = record_pending_signo;
1664 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1665 * in order to ignore them: they will be raised
1666 * in an endless loop when we try to do some
1667 * terminal ioctls! We do have to _ignore_ these.
1669 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1676 /* Restores tty foreground process group, and exits. */
1677 static void hush_exit(int exitcode)
1679 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1680 save_history(G.line_input_state);
1684 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1686 /* argv[0] is unused */
1687 argv[1] = G.traps[0];
1689 G.exiting = 1; /* prevent EXIT trap recursion */
1690 /* Note: G.traps[0] is not cleared!
1691 * "trap" will still show it, if executed
1696 #if ENABLE_FEATURE_CLEAN_UP
1698 struct variable *cur_var;
1699 if (G.cwd != bb_msg_unknown)
1701 cur_var = G.top_var;
1703 struct variable *tmp = cur_var;
1704 if (!cur_var->max_len)
1705 free(cur_var->varstr);
1706 cur_var = cur_var->next;
1714 sigexit(- (exitcode & 0xff));
1721 //TODO: return a mask of ALL handled sigs?
1722 static int check_and_run_traps(void)
1729 if (sigisemptyset(&G.pending_set))
1734 if (sigismember(&G.pending_set, sig)) {
1735 sigdelset(&G.pending_set, sig);
1738 } while (sig < NSIG);
1741 if (G.traps && G.traps[sig]) {
1742 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1743 if (G.traps[sig][0]) {
1744 /* We have user-defined handler */
1745 smalluint save_rcode;
1747 /* argv[0] is unused */
1748 argv[1] = G.traps[sig];
1750 save_rcode = G.last_exitcode;
1752 G.last_exitcode = save_rcode;
1754 } /* else: "" trap, ignoring signal */
1757 /* not a trap: special action */
1760 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1761 /* Builtin was ^C'ed, make it look prettier: */
1769 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1770 /* bash is observed to signal whole process groups,
1771 * not individual processes */
1772 for (job = G.job_list; job; job = job->next) {
1775 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1776 if (kill(- job->pgrp, SIGHUP) == 0)
1777 kill(- job->pgrp, SIGCONT);
1782 #if ENABLE_HUSH_FAST
1784 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1786 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1788 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1789 * This simplifies wait builtin a bit.
1793 default: /* ignored: */
1794 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1795 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1797 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1798 * Example: wait is not interrupted by TERM
1799 * in interactive shell, because TERM is ignored.
1808 static const char *get_cwd(int force)
1810 if (force || G.cwd == NULL) {
1811 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1812 * we must not try to free(bb_msg_unknown) */
1813 if (G.cwd == bb_msg_unknown)
1815 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1817 G.cwd = bb_msg_unknown;
1824 * Shell and environment variable support
1826 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1828 struct variable **pp;
1829 struct variable *cur;
1832 while ((cur = *pp) != NULL) {
1833 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1840 static const char* FAST_FUNC get_local_var_value(const char *name)
1842 struct variable **vpp;
1843 unsigned len = strlen(name);
1845 if (G.expanded_assignments) {
1846 char **cpp = G.expanded_assignments;
1849 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1850 return cp + len + 1;
1855 vpp = get_ptr_to_local_var(name, len);
1857 return (*vpp)->varstr + len + 1;
1859 if (strcmp(name, "PPID") == 0)
1860 return utoa(G.root_ppid);
1861 // bash compat: UID? EUID?
1862 #if ENABLE_HUSH_RANDOM_SUPPORT
1863 if (strcmp(name, "RANDOM") == 0)
1864 return utoa(next_random(&G.random_gen));
1869 /* str holds "NAME=VAL" and is expected to be malloced.
1870 * We take ownership of it.
1872 * 0: do not change export flag
1873 * (if creating new variable, flag will be 0)
1874 * 1: set export flag and putenv the variable
1875 * -1: clear export flag and unsetenv the variable
1876 * flg_read_only is set only when we handle -R var=val
1878 #if !BB_MMU && ENABLE_HUSH_LOCAL
1879 /* all params are used */
1880 #elif BB_MMU && ENABLE_HUSH_LOCAL
1881 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1882 set_local_var(str, flg_export, local_lvl)
1883 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1884 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1885 set_local_var(str, flg_export)
1886 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1887 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1888 set_local_var(str, flg_export, flg_read_only)
1890 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1892 struct variable **var_pp;
1893 struct variable *cur;
1897 eq_sign = strchr(str, '=');
1898 if (!eq_sign) { /* not expected to ever happen? */
1903 name_len = eq_sign - str + 1; /* including '=' */
1904 var_pp = &G.top_var;
1905 while ((cur = *var_pp) != NULL) {
1906 if (strncmp(cur->varstr, str, name_len) != 0) {
1907 var_pp = &cur->next;
1910 /* We found an existing var with this name */
1911 if (cur->flg_read_only) {
1915 bb_error_msg("%s: readonly variable", str);
1919 if (flg_export == -1) { // "&& cur->flg_export" ?
1920 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1925 #if ENABLE_HUSH_LOCAL
1926 if (cur->func_nest_level < local_lvl) {
1927 /* New variable is declared as local,
1928 * and existing one is global, or local
1929 * from enclosing function.
1930 * Remove and save old one: */
1931 *var_pp = cur->next;
1932 cur->next = *G.shadowed_vars_pp;
1933 *G.shadowed_vars_pp = cur;
1934 /* bash 3.2.33(1) and exported vars:
1936 * # f() { local z=a; env | grep ^z; }
1942 if (cur->flg_export)
1947 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1952 if (cur->max_len != 0) {
1953 if (cur->max_len >= strlen(str)) {
1954 /* This one is from startup env, reuse space */
1955 strcpy(cur->varstr, str);
1959 /* max_len == 0 signifies "malloced" var, which we can
1960 * (and has to) free */
1964 goto set_str_and_exp;
1967 /* Not found - create new variable struct */
1968 cur = xzalloc(sizeof(*cur));
1969 #if ENABLE_HUSH_LOCAL
1970 cur->func_nest_level = local_lvl;
1972 cur->next = *var_pp;
1978 cur->flg_read_only = flg_read_only;
1981 if (flg_export == 1)
1982 cur->flg_export = 1;
1983 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1984 cmdedit_update_prompt();
1985 if (cur->flg_export) {
1986 if (flg_export == -1) {
1987 cur->flg_export = 0;
1988 /* unsetenv was already done */
1990 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1991 return putenv(cur->varstr);
1997 /* Used at startup and after each cd */
1998 static void set_pwd_var(int exp)
2000 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2001 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2004 static int unset_local_var_len(const char *name, int name_len)
2006 struct variable *cur;
2007 struct variable **var_pp;
2010 return EXIT_SUCCESS;
2011 var_pp = &G.top_var;
2012 while ((cur = *var_pp) != NULL) {
2013 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2014 if (cur->flg_read_only) {
2015 bb_error_msg("%s: readonly variable", name);
2016 return EXIT_FAILURE;
2018 *var_pp = cur->next;
2019 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2020 bb_unsetenv(cur->varstr);
2021 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2022 cmdedit_update_prompt();
2026 return EXIT_SUCCESS;
2028 var_pp = &cur->next;
2030 return EXIT_SUCCESS;
2033 static int unset_local_var(const char *name)
2035 return unset_local_var_len(name, strlen(name));
2038 static void unset_vars(char **strings)
2046 const char *eq = strchrnul(*v, '=');
2047 unset_local_var_len(*v, (int)(eq - *v));
2053 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2055 char *var = xasprintf("%s=%s", name, val);
2056 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2061 * Helpers for "var1=val1 var2=val2 cmd" feature
2063 static void add_vars(struct variable *var)
2065 struct variable *next;
2069 var->next = G.top_var;
2071 if (var->flg_export) {
2072 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2073 putenv(var->varstr);
2075 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2081 static struct variable *set_vars_and_save_old(char **strings)
2084 struct variable *old = NULL;
2090 struct variable *var_p;
2091 struct variable **var_pp;
2094 eq = strchr(*s, '=');
2096 var_pp = get_ptr_to_local_var(*s, eq - *s);
2098 /* Remove variable from global linked list */
2100 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2101 *var_pp = var_p->next;
2102 /* Add it to returned list */
2106 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2117 static void reinit_unicode_for_hush(void)
2119 /* Unicode support should be activated even if LANG is set
2120 * _during_ shell execution, not only if it was set when
2121 * shell was started. Therefore, re-check LANG every time:
2123 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2124 || ENABLE_UNICODE_USING_LOCALE
2126 const char *s = get_local_var_value("LC_ALL");
2127 if (!s) s = get_local_var_value("LC_CTYPE");
2128 if (!s) s = get_local_var_value("LANG");
2134 * in_str support (strings, and "strings" read from files).
2137 #if ENABLE_HUSH_INTERACTIVE
2138 /* To test correct lineedit/interactive behavior, type from command line:
2144 * It excercises a lot of corner cases.
2146 static void cmdedit_update_prompt(void)
2148 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2149 G.PS1 = get_local_var_value("PS1");
2152 G.PS2 = get_local_var_value("PS2");
2159 static const char *setup_prompt_string(int promptmode)
2161 const char *prompt_str;
2162 debug_printf("setup_prompt_string %d ", promptmode);
2163 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2164 /* Set up the prompt */
2165 if (promptmode == 0) { /* PS1 */
2167 /* bash uses $PWD value, even if it is set by user.
2168 * It uses current dir only if PWD is unset.
2169 * We always use current dir. */
2170 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2175 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2176 debug_printf("prompt_str '%s'\n", prompt_str);
2179 static int get_user_input(struct in_str *i)
2182 const char *prompt_str;
2184 prompt_str = setup_prompt_string(i->promptmode);
2185 # if ENABLE_FEATURE_EDITING
2187 reinit_unicode_for_hush();
2189 /* buglet: SIGINT will not make new prompt to appear _at once_,
2190 * only after <Enter>. (^C will work) */
2191 r = read_line_input(G.line_input_state, prompt_str,
2192 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2195 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2196 check_and_run_traps();
2197 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2199 /* EOF/error detected */
2201 i->peek_buf[0] = r = EOF;
2204 i->p = G.user_input_buf;
2205 return (unsigned char)*i->p++;
2209 if (i->last_char == '\0' || i->last_char == '\n') {
2210 /* Why check_and_run_traps here? Try this interactively:
2211 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2212 * $ <[enter], repeatedly...>
2213 * Without check_and_run_traps, handler never runs.
2215 check_and_run_traps();
2216 fputs(prompt_str, stdout);
2220 } while (G.flag_SIGINT || r == '\0');
2224 /* This is the magic location that prints prompts
2225 * and gets data back from the user */
2226 static int fgetc_interactive(struct in_str *i)
2229 /* If it's interactive stdin, get new line. */
2230 if (G_interactive_fd && i->file == stdin) {
2231 /* Returns first char (or EOF), the rest is in i->p[] */
2232 ch = get_user_input(i);
2233 i->promptmode = 1; /* PS2 */
2235 /* Not stdin: script file, sourced file, etc */
2236 do ch = fgetc(i->file); while (ch == '\0');
2241 static inline int fgetc_interactive(struct in_str *i)
2244 do ch = fgetc(i->file); while (ch == '\0');
2247 #endif /* INTERACTIVE */
2249 static int FAST_FUNC file_get(struct in_str *i)
2253 #if ENABLE_FEATURE_EDITING
2254 /* This can be stdin, check line editing char[] buffer */
2255 if (i->p && *i->p != '\0') {
2256 ch = (unsigned char)*i->p++;
2260 /* peek_buf[] is an int array, not char. Can contain EOF. */
2261 ch = i->peek_buf[0];
2263 int ch2 = i->peek_buf[1];
2264 i->peek_buf[0] = ch2;
2265 if (ch2 == 0) /* very likely, avoid redundant write */
2271 ch = fgetc_interactive(i);
2273 debug_printf("file_get: got '%c' %d\n", ch, ch);
2278 static int FAST_FUNC file_peek(struct in_str *i)
2282 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2283 /* This can be stdin, check line editing char[] buffer */
2284 if (i->p && *i->p != '\0')
2285 return (unsigned char)*i->p;
2287 /* peek_buf[] is an int array, not char. Can contain EOF. */
2288 ch = i->peek_buf[0];
2292 /* Need to get a new char */
2293 ch = fgetc_interactive(i);
2294 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2296 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2297 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2303 i->peek_buf[0] = ch;
2304 /*i->peek_buf[1] = 0; - already is */
2308 static int FAST_FUNC static_get(struct in_str *i)
2310 int ch = (unsigned char)*i->p;
2319 static int FAST_FUNC static_peek(struct in_str *i)
2321 /* Doesn't report EOF on NUL. None of the callers care. */
2322 return (unsigned char)*i->p;
2325 /* Only ever called if i_peek() was called, and did not return EOF.
2326 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2327 * not end-of-line. Therefore we never need to read a new editing line here.
2329 static int i_peek2(struct in_str *i)
2333 /* There are two cases when i->p[] buffer exists.
2334 * (1) it's a string in_str.
2335 * (2) It's a file, and we have a saved line editing buffer.
2336 * In both cases, we know that i->p[0] exists and not NUL, and
2337 * the peek2 result is in i->p[1].
2340 return (unsigned char)i->p[1];
2342 /* Now we know it is a file-based in_str. */
2344 /* peek_buf[] is an int array, not char. Can contain EOF. */
2345 /* Is there 2nd char? */
2346 ch = i->peek_buf[1];
2348 /* We did not read it yet, get it now */
2349 do ch = fgetc(i->file); while (ch == '\0');
2350 i->peek_buf[1] = ch;
2353 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2357 static void setup_file_in_str(struct in_str *i, FILE *f)
2359 memset(i, 0, sizeof(*i));
2361 i->peek = file_peek;
2362 /* i->promptmode = 0; - PS1 (memset did it) */
2367 static void setup_string_in_str(struct in_str *i, const char *s)
2369 memset(i, 0, sizeof(*i));
2370 i->get = static_get;
2371 i->peek = static_peek;
2372 /* i->promptmode = 0; - PS1 (memset did it) */
2380 #define B_CHUNK (32 * sizeof(char*))
2382 static void o_reset_to_empty_unquoted(o_string *o)
2385 o->has_quoted_part = 0;
2390 static void o_free(o_string *o)
2393 memset(o, 0, sizeof(*o));
2396 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2401 static void o_grow_by(o_string *o, int len)
2403 if (o->length + len > o->maxlen) {
2404 o->maxlen += (2 * len) | (B_CHUNK-1);
2405 o->data = xrealloc(o->data, 1 + o->maxlen);
2409 static void o_addchr(o_string *o, int ch)
2411 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2412 if (o->length < o->maxlen) {
2413 /* likely. avoid o_grow_by() call */
2415 o->data[o->length] = ch;
2417 o->data[o->length] = '\0';
2425 /* Valid only if we know o_string is not empty */
2426 static void o_delchr(o_string *o)
2429 o->data[o->length] = '\0';
2433 static void o_addblock(o_string *o, const char *str, int len)
2436 memcpy(&o->data[o->length], str, len);
2438 o->data[o->length] = '\0';
2441 static void o_addstr(o_string *o, const char *str)
2443 o_addblock(o, str, strlen(str));
2447 static void nommu_addchr(o_string *o, int ch)
2453 # define nommu_addchr(o, str) ((void)0)
2456 static void o_addstr_with_NUL(o_string *o, const char *str)
2458 o_addblock(o, str, strlen(str) + 1);
2462 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2463 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2464 * Apparently, on unquoted $v bash still does globbing
2465 * ("v='*.txt'; echo $v" prints all .txt files),
2466 * but NOT brace expansion! Thus, there should be TWO independent
2467 * quoting mechanisms on $v expansion side: one protects
2468 * $v from brace expansion, and other additionally protects "$v" against globbing.
2469 * We have only second one.
2472 #if ENABLE_HUSH_BRACE_EXPANSION
2473 # define MAYBE_BRACES "{}"
2475 # define MAYBE_BRACES ""
2478 /* My analysis of quoting semantics tells me that state information
2479 * is associated with a destination, not a source.
2481 static void o_addqchr(o_string *o, int ch)
2484 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2489 o->data[o->length] = '\\';
2492 o->data[o->length] = ch;
2494 o->data[o->length] = '\0';
2497 static void o_addQchr(o_string *o, int ch)
2500 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2501 && strchr("*?[\\" MAYBE_BRACES, ch)
2504 o->data[o->length] = '\\';
2508 o->data[o->length] = ch;
2510 o->data[o->length] = '\0';
2513 static void o_addqblock(o_string *o, const char *str, int len)
2518 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2519 if (ordinary_cnt > len) /* paranoia */
2521 o_addblock(o, str, ordinary_cnt);
2522 if (ordinary_cnt == len)
2523 return; /* NUL is already added by o_addblock */
2524 str += ordinary_cnt;
2525 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2529 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2531 o->data[o->length] = '\\';
2535 o->data[o->length] = ch;
2538 o->data[o->length] = '\0';
2541 static void o_addQblock(o_string *o, const char *str, int len)
2543 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2544 o_addblock(o, str, len);
2547 o_addqblock(o, str, len);
2550 static void o_addQstr(o_string *o, const char *str)
2552 o_addQblock(o, str, strlen(str));
2555 /* A special kind of o_string for $VAR and `cmd` expansion.
2556 * It contains char* list[] at the beginning, which is grown in 16 element
2557 * increments. Actual string data starts at the next multiple of 16 * (char*).
2558 * list[i] contains an INDEX (int!) into this string data.
2559 * It means that if list[] needs to grow, data needs to be moved higher up
2560 * but list[i]'s need not be modified.
2561 * NB: remembering how many list[i]'s you have there is crucial.
2562 * o_finalize_list() operation post-processes this structure - calculates
2563 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2565 #if DEBUG_EXPAND || DEBUG_GLOB
2566 static void debug_print_list(const char *prefix, o_string *o, int n)
2568 char **list = (char**)o->data;
2569 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2573 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2574 prefix, list, n, string_start, o->length, o->maxlen,
2575 !!(o->o_expflags & EXP_FLAG_GLOB),
2577 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2580 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2581 o->data + (int)(uintptr_t)list[i] + string_start,
2582 o->data + (int)(uintptr_t)list[i] + string_start);
2586 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2588 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2592 # define debug_print_list(prefix, o, n) ((void)0)
2595 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2596 * in list[n] so that it points past last stored byte so far.
2597 * It returns n+1. */
2598 static int o_save_ptr_helper(o_string *o, int n)
2600 char **list = (char**)o->data;
2604 if (!o->has_empty_slot) {
2605 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2606 string_len = o->length - string_start;
2607 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2608 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2609 /* list[n] points to string_start, make space for 16 more pointers */
2610 o->maxlen += 0x10 * sizeof(list[0]);
2611 o->data = xrealloc(o->data, o->maxlen + 1);
2612 list = (char**)o->data;
2613 memmove(list + n + 0x10, list + n, string_len);
2614 o->length += 0x10 * sizeof(list[0]);
2616 debug_printf_list("list[%d]=%d string_start=%d\n",
2617 n, string_len, string_start);
2620 /* We have empty slot at list[n], reuse without growth */
2621 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2622 string_len = o->length - string_start;
2623 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2624 n, string_len, string_start);
2625 o->has_empty_slot = 0;
2627 o->has_quoted_part = 0;
2628 list[n] = (char*)(uintptr_t)string_len;
2632 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2633 static int o_get_last_ptr(o_string *o, int n)
2635 char **list = (char**)o->data;
2636 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2638 return ((int)(uintptr_t)list[n-1]) + string_start;
2641 #if ENABLE_HUSH_BRACE_EXPANSION
2642 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2643 * first, it processes even {a} (no commas), second,
2644 * I didn't manage to make it return strings when they don't match
2645 * existing files. Need to re-implement it.
2649 static int glob_needed(const char *s)
2658 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2664 /* Return pointer to next closing brace or to comma */
2665 static const char *next_brace_sub(const char *cp)
2669 while (*cp != '\0') {
2676 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2682 return *cp != '\0' ? cp : NULL;
2684 /* Recursive brace globber. Note: may garble pattern[]. */
2685 static int glob_brace(char *pattern, o_string *o, int n)
2687 char *new_pattern_buf;
2694 debug_printf_glob("glob_brace('%s')\n", pattern);
2700 if (*begin == '{') {
2701 /* Find the first sub-pattern and at the same time
2702 * find the rest after the closing brace */
2703 next = next_brace_sub(begin);
2705 /* An illegal expression */
2709 /* "{abc}" with no commas - illegal
2710 * brace expr, disregard and skip it */
2716 if (*begin == '\\' && begin[1] != '\0')
2720 debug_printf_glob("begin:%s\n", begin);
2721 debug_printf_glob("next:%s\n", next);
2723 /* Now find the end of the whole brace expression */
2725 while (*rest != '}') {
2726 rest = next_brace_sub(rest);
2728 /* An illegal expression */
2731 debug_printf_glob("rest:%s\n", rest);
2733 rest_len = strlen(++rest) + 1;
2735 /* We are sure the brace expression is well-formed */
2737 /* Allocate working buffer large enough for our work */
2738 new_pattern_buf = xmalloc(strlen(pattern));
2740 /* We have a brace expression. BEGIN points to the opening {,
2741 * NEXT points past the terminator of the first element, and REST
2742 * points past the final }. We will accumulate result names from
2743 * recursive runs for each brace alternative in the buffer using
2748 /* Construct the new glob expression */
2751 mempcpy(new_pattern_buf,
2752 /* We know the prefix for all sub-patterns */
2753 pattern, begin - pattern),
2757 /* Note: glob_brace() may garble new_pattern_buf[].
2758 * That's why we re-copy prefix every time (1st memcpy above).
2760 n = glob_brace(new_pattern_buf, o, n);
2762 /* We saw the last entry */
2766 next = next_brace_sub(next);
2768 free(new_pattern_buf);
2776 memset(&globdata, 0, sizeof(globdata));
2777 gr = glob(pattern, 0, NULL, &globdata);
2778 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2780 if (gr == GLOB_NOMATCH) {
2781 globfree(&globdata);
2782 /* NB: garbles parameter */
2783 unbackslash(pattern);
2784 o_addstr_with_NUL(o, pattern);
2785 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2786 return o_save_ptr_helper(o, n);
2788 if (gr == GLOB_NOSPACE)
2789 bb_error_msg_and_die(bb_msg_memory_exhausted);
2790 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2791 * but we didn't specify it. Paranoia again. */
2792 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2794 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2795 char **argv = globdata.gl_pathv;
2797 o_addstr_with_NUL(o, *argv);
2798 n = o_save_ptr_helper(o, n);
2804 globfree(&globdata);
2808 /* Performs globbing on last list[],
2809 * saving each result as a new list[].
2811 static int perform_glob(o_string *o, int n)
2813 char *pattern, *copy;
2815 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2817 return o_save_ptr_helper(o, n);
2818 pattern = o->data + o_get_last_ptr(o, n);
2819 debug_printf_glob("glob pattern '%s'\n", pattern);
2820 if (!glob_needed(pattern)) {
2821 /* unbackslash last string in o in place, fix length */
2822 o->length = unbackslash(pattern) - o->data;
2823 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2824 return o_save_ptr_helper(o, n);
2827 copy = xstrdup(pattern);
2828 /* "forget" pattern in o */
2829 o->length = pattern - o->data;
2830 n = glob_brace(copy, o, n);
2833 debug_print_list("perform_glob returning", o, n);
2837 #else /* !HUSH_BRACE_EXPANSION */
2840 static int glob_needed(const char *s)
2849 if (*s == '*' || *s == '[' || *s == '?')
2855 /* Performs globbing on last list[],
2856 * saving each result as a new list[].
2858 static int perform_glob(o_string *o, int n)
2864 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2866 return o_save_ptr_helper(o, n);
2867 pattern = o->data + o_get_last_ptr(o, n);
2868 debug_printf_glob("glob pattern '%s'\n", pattern);
2869 if (!glob_needed(pattern)) {
2871 /* unbackslash last string in o in place, fix length */
2872 o->length = unbackslash(pattern) - o->data;
2873 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2874 return o_save_ptr_helper(o, n);
2877 memset(&globdata, 0, sizeof(globdata));
2878 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2879 * If we glob "*.\*" and don't find anything, we need
2880 * to fall back to using literal "*.*", but GLOB_NOCHECK
2881 * will return "*.\*"!
2883 gr = glob(pattern, 0, NULL, &globdata);
2884 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2886 if (gr == GLOB_NOMATCH) {
2887 globfree(&globdata);
2890 if (gr == GLOB_NOSPACE)
2891 bb_error_msg_and_die(bb_msg_memory_exhausted);
2892 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2893 * but we didn't specify it. Paranoia again. */
2894 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2896 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2897 char **argv = globdata.gl_pathv;
2898 /* "forget" pattern in o */
2899 o->length = pattern - o->data;
2901 o_addstr_with_NUL(o, *argv);
2902 n = o_save_ptr_helper(o, n);
2908 globfree(&globdata);
2910 debug_print_list("perform_glob returning", o, n);
2914 #endif /* !HUSH_BRACE_EXPANSION */
2916 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2917 * Otherwise, just finish current list[] and start new */
2918 static int o_save_ptr(o_string *o, int n)
2920 if (o->o_expflags & EXP_FLAG_GLOB) {
2921 /* If o->has_empty_slot, list[n] was already globbed
2922 * (if it was requested back then when it was filled)
2923 * so don't do that again! */
2924 if (!o->has_empty_slot)
2925 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2927 return o_save_ptr_helper(o, n);
2930 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2931 static char **o_finalize_list(o_string *o, int n)
2936 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2938 debug_print_list("finalized", o, n);
2939 debug_printf_expand("finalized n:%d\n", n);
2940 list = (char**)o->data;
2941 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2945 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2950 static void free_pipe_list(struct pipe *pi);
2952 /* Returns pi->next - next pipe in the list */
2953 static struct pipe *free_pipe(struct pipe *pi)
2958 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2959 for (i = 0; i < pi->num_cmds; i++) {
2960 struct command *command;
2961 struct redir_struct *r, *rnext;
2963 command = &pi->cmds[i];
2964 debug_printf_clean(" command %d:\n", i);
2965 if (command->argv) {
2969 for (a = 0, p = command->argv; *p; a++, p++) {
2970 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2973 free_strings(command->argv);
2974 //command->argv = NULL;
2976 /* not "else if": on syntax error, we may have both! */
2977 if (command->group) {
2978 debug_printf_clean(" begin group (cmd_type:%d)\n",
2980 free_pipe_list(command->group);
2981 debug_printf_clean(" end group\n");
2982 //command->group = NULL;
2984 /* else is crucial here.
2985 * If group != NULL, child_func is meaningless */
2986 #if ENABLE_HUSH_FUNCTIONS
2987 else if (command->child_func) {
2988 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2989 command->child_func->parent_cmd = NULL;
2993 free(command->group_as_string);
2994 //command->group_as_string = NULL;
2996 for (r = command->redirects; r; r = rnext) {
2997 debug_printf_clean(" redirect %d%s",
2998 r->rd_fd, redir_table[r->rd_type].descrip);
2999 /* guard against the case >$FOO, where foo is unset or blank */
3000 if (r->rd_filename) {
3001 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3002 free(r->rd_filename);
3003 //r->rd_filename = NULL;
3005 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3009 //command->redirects = NULL;
3011 free(pi->cmds); /* children are an array, they get freed all at once */
3015 //pi->cmdtext = NULL;
3023 static void free_pipe_list(struct pipe *pi)
3027 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3029 debug_printf_clean("pipe followup code %d\n", pi->followup);
3035 /*** Parsing routines ***/
3037 #ifndef debug_print_tree
3038 static void debug_print_tree(struct pipe *pi, int lvl)
3040 static const char *const PIPE[] = {
3046 static const char *RES[] = {
3047 [RES_NONE ] = "NONE" ,
3050 [RES_THEN ] = "THEN" ,
3051 [RES_ELIF ] = "ELIF" ,
3052 [RES_ELSE ] = "ELSE" ,
3055 # if ENABLE_HUSH_LOOPS
3056 [RES_FOR ] = "FOR" ,
3057 [RES_WHILE] = "WHILE",
3058 [RES_UNTIL] = "UNTIL",
3060 [RES_DONE ] = "DONE" ,
3062 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3065 # if ENABLE_HUSH_CASE
3066 [RES_CASE ] = "CASE" ,
3067 [RES_CASE_IN ] = "CASE_IN" ,
3068 [RES_MATCH] = "MATCH",
3069 [RES_CASE_BODY] = "CASE_BODY",
3070 [RES_ESAC ] = "ESAC" ,
3072 [RES_XXXX ] = "XXXX" ,
3073 [RES_SNTX ] = "SNTX" ,
3075 static const char *const CMDTYPE[] = {
3079 # if ENABLE_HUSH_FUNCTIONS
3088 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3089 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3091 while (prn < pi->num_cmds) {
3092 struct command *command = &pi->cmds[prn];
3093 char **argv = command->argv;
3095 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3097 command->assignment_cnt);
3098 if (command->group) {
3099 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3100 CMDTYPE[command->cmd_type],
3103 , " group_as_string:", command->group_as_string
3108 debug_print_tree(command->group, lvl+1);
3112 if (argv) while (*argv) {
3113 fdprintf(2, " '%s'", *argv);
3123 #endif /* debug_print_tree */
3125 static struct pipe *new_pipe(void)
3128 pi = xzalloc(sizeof(struct pipe));
3129 /*pi->followup = 0; - deliberately invalid value */
3130 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3134 /* Command (member of a pipe) is complete, or we start a new pipe
3135 * if ctx->command is NULL.
3136 * No errors possible here.
3138 static int done_command(struct parse_context *ctx)
3140 /* The command is really already in the pipe structure, so
3141 * advance the pipe counter and make a new, null command. */
3142 struct pipe *pi = ctx->pipe;
3143 struct command *command = ctx->command;
3145 #if 0 /* Instead we emit error message at run time */
3146 if (ctx->pending_redirect) {
3147 /* For example, "cmd >" (no filename to redirect to) */
3148 die_if_script("syntax error: %s", "invalid redirect");
3149 ctx->pending_redirect = NULL;
3154 if (IS_NULL_CMD(command)) {
3155 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3159 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3160 //debug_print_tree(ctx->list_head, 20);
3162 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3165 /* Only real trickiness here is that the uncommitted
3166 * command structure is not counted in pi->num_cmds. */
3167 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3168 ctx->command = command = &pi->cmds[pi->num_cmds];
3170 memset(command, 0, sizeof(*command));
3171 return pi->num_cmds; /* used only for 0/nonzero check */
3174 static void done_pipe(struct parse_context *ctx, pipe_style type)
3178 debug_printf_parse("done_pipe entered, followup %d\n", type);
3179 /* Close previous command */
3180 not_null = done_command(ctx);
3181 ctx->pipe->followup = type;
3183 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3184 ctx->ctx_inverted = 0;
3185 ctx->pipe->res_word = ctx->ctx_res_w;
3188 /* Without this check, even just <enter> on command line generates
3189 * tree of three NOPs (!). Which is harmless but annoying.
3190 * IOW: it is safe to do it unconditionally. */
3193 || ctx->ctx_res_w == RES_FI
3195 #if ENABLE_HUSH_LOOPS
3196 || ctx->ctx_res_w == RES_DONE
3197 || ctx->ctx_res_w == RES_FOR
3198 || ctx->ctx_res_w == RES_IN
3200 #if ENABLE_HUSH_CASE
3201 || ctx->ctx_res_w == RES_ESAC
3205 debug_printf_parse("done_pipe: adding new pipe: "
3206 "not_null:%d ctx->ctx_res_w:%d\n",
3207 not_null, ctx->ctx_res_w);
3209 ctx->pipe->next = new_p;
3211 /* RES_THEN, RES_DO etc are "sticky" -
3212 * they remain set for pipes inside if/while.
3213 * This is used to control execution.
3214 * RES_FOR and RES_IN are NOT sticky (needed to support
3215 * cases where variable or value happens to match a keyword):
3217 #if ENABLE_HUSH_LOOPS
3218 if (ctx->ctx_res_w == RES_FOR
3219 || ctx->ctx_res_w == RES_IN)
3220 ctx->ctx_res_w = RES_NONE;
3222 #if ENABLE_HUSH_CASE
3223 if (ctx->ctx_res_w == RES_MATCH)
3224 ctx->ctx_res_w = RES_CASE_BODY;
3225 if (ctx->ctx_res_w == RES_CASE)
3226 ctx->ctx_res_w = RES_CASE_IN;
3228 ctx->command = NULL; /* trick done_command below */
3229 /* Create the memory for command, roughly:
3230 * ctx->pipe->cmds = new struct command;
3231 * ctx->command = &ctx->pipe->cmds[0];
3234 //debug_print_tree(ctx->list_head, 10);
3236 debug_printf_parse("done_pipe return\n");
3239 static void initialize_context(struct parse_context *ctx)
3241 memset(ctx, 0, sizeof(*ctx));
3242 ctx->pipe = ctx->list_head = new_pipe();
3243 /* Create the memory for command, roughly:
3244 * ctx->pipe->cmds = new struct command;
3245 * ctx->command = &ctx->pipe->cmds[0];
3250 /* If a reserved word is found and processed, parse context is modified
3251 * and 1 is returned.
3254 struct reserved_combo {
3257 unsigned char assignment_flag;
3261 FLAG_END = (1 << RES_NONE ),
3263 FLAG_IF = (1 << RES_IF ),
3264 FLAG_THEN = (1 << RES_THEN ),
3265 FLAG_ELIF = (1 << RES_ELIF ),
3266 FLAG_ELSE = (1 << RES_ELSE ),
3267 FLAG_FI = (1 << RES_FI ),
3269 # if ENABLE_HUSH_LOOPS
3270 FLAG_FOR = (1 << RES_FOR ),
3271 FLAG_WHILE = (1 << RES_WHILE),
3272 FLAG_UNTIL = (1 << RES_UNTIL),
3273 FLAG_DO = (1 << RES_DO ),
3274 FLAG_DONE = (1 << RES_DONE ),
3275 FLAG_IN = (1 << RES_IN ),
3277 # if ENABLE_HUSH_CASE
3278 FLAG_MATCH = (1 << RES_MATCH),
3279 FLAG_ESAC = (1 << RES_ESAC ),
3281 FLAG_START = (1 << RES_XXXX ),
3284 static const struct reserved_combo* match_reserved_word(o_string *word)
3286 /* Mostly a list of accepted follow-up reserved words.
3287 * FLAG_END means we are done with the sequence, and are ready
3288 * to turn the compound list into a command.
3289 * FLAG_START means the word must start a new compound list.
3291 static const struct reserved_combo reserved_list[] = {
3293 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3294 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3295 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3296 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3297 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3298 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3300 # if ENABLE_HUSH_LOOPS
3301 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3302 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3303 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3304 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3305 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3306 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3308 # if ENABLE_HUSH_CASE
3309 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3310 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3313 const struct reserved_combo *r;
3315 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3316 if (strcmp(word->data, r->literal) == 0)
3321 /* Return 0: not a keyword, 1: keyword
3323 static int reserved_word(o_string *word, struct parse_context *ctx)
3325 # if ENABLE_HUSH_CASE
3326 static const struct reserved_combo reserved_match = {
3327 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3330 const struct reserved_combo *r;
3332 if (word->has_quoted_part)
3334 r = match_reserved_word(word);
3338 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3339 # if ENABLE_HUSH_CASE
3340 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3341 /* "case word IN ..." - IN part starts first MATCH part */
3342 r = &reserved_match;
3345 if (r->flag == 0) { /* '!' */
3346 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3347 syntax_error("! ! command");
3348 ctx->ctx_res_w = RES_SNTX;
3350 ctx->ctx_inverted = 1;
3353 if (r->flag & FLAG_START) {
3354 struct parse_context *old;
3356 old = xmalloc(sizeof(*old));
3357 debug_printf_parse("push stack %p\n", old);
3358 *old = *ctx; /* physical copy */
3359 initialize_context(ctx);
3361 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3362 syntax_error_at(word->data);
3363 ctx->ctx_res_w = RES_SNTX;
3366 /* "{...} fi" is ok. "{...} if" is not
3368 * if { echo foo; } then { echo bar; } fi */
3369 if (ctx->command->group)
3370 done_pipe(ctx, PIPE_SEQ);
3373 ctx->ctx_res_w = r->res;
3374 ctx->old_flag = r->flag;
3375 word->o_assignment = r->assignment_flag;
3376 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3378 if (ctx->old_flag & FLAG_END) {
3379 struct parse_context *old;
3381 done_pipe(ctx, PIPE_SEQ);
3382 debug_printf_parse("pop stack %p\n", ctx->stack);
3384 old->command->group = ctx->list_head;
3385 old->command->cmd_type = CMD_NORMAL;
3387 /* At this point, the compound command's string is in
3388 * ctx->as_string... except for the leading keyword!
3389 * Consider this example: "echo a | if true; then echo a; fi"
3390 * ctx->as_string will contain "true; then echo a; fi",
3391 * with "if " remaining in old->as_string!
3395 int len = old->as_string.length;
3396 /* Concatenate halves */
3397 o_addstr(&old->as_string, ctx->as_string.data);
3398 o_free_unsafe(&ctx->as_string);
3399 /* Find where leading keyword starts in first half */
3400 str = old->as_string.data + len;
3401 if (str > old->as_string.data)
3402 str--; /* skip whitespace after keyword */
3403 while (str > old->as_string.data && isalpha(str[-1]))
3405 /* Ugh, we're done with this horrid hack */
3406 old->command->group_as_string = xstrdup(str);
3407 debug_printf_parse("pop, remembering as:'%s'\n",
3408 old->command->group_as_string);
3411 *ctx = *old; /* physical copy */
3416 #endif /* HAS_KEYWORDS */
3418 /* Word is complete, look at it and update parsing context.
3419 * Normal return is 0. Syntax errors return 1.
3420 * Note: on return, word is reset, but not o_free'd!
3422 static int done_word(o_string *word, struct parse_context *ctx)
3424 struct command *command = ctx->command;
3426 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3427 if (word->length == 0 && !word->has_quoted_part) {
3428 debug_printf_parse("done_word return 0: true null, ignored\n");
3432 if (ctx->pending_redirect) {
3433 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3434 * only if run as "bash", not "sh" */
3435 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3437 * ...the word that follows the redirection operator
3438 * shall be subjected to tilde expansion, parameter expansion,
3439 * command substitution, arithmetic expansion, and quote
3440 * removal. Pathname expansion shall not be performed
3441 * on the word by a non-interactive shell; an interactive
3442 * shell may perform it, but shall do so only when
3443 * the expansion would result in one word."
3445 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3446 /* Cater for >\file case:
3447 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3448 * Same with heredocs:
3449 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3451 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3452 unbackslash(ctx->pending_redirect->rd_filename);
3453 /* Is it <<"HEREDOC"? */
3454 if (word->has_quoted_part) {
3455 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3458 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3459 ctx->pending_redirect = NULL;
3462 # if ENABLE_HUSH_CASE
3463 if (ctx->ctx_dsemicolon
3464 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3466 /* already done when ctx_dsemicolon was set to 1: */
3467 /* ctx->ctx_res_w = RES_MATCH; */
3468 ctx->ctx_dsemicolon = 0;
3471 if (!command->argv /* if it's the first word... */
3472 # if ENABLE_HUSH_LOOPS
3473 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3474 && ctx->ctx_res_w != RES_IN
3476 # if ENABLE_HUSH_CASE
3477 && ctx->ctx_res_w != RES_CASE
3480 int reserved = reserved_word(word, ctx);
3481 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3483 o_reset_to_empty_unquoted(word);
3484 debug_printf_parse("done_word return %d\n",
3485 (ctx->ctx_res_w == RES_SNTX));
3486 return (ctx->ctx_res_w == RES_SNTX);
3488 # if ENABLE_HUSH_BASH_COMPAT
3489 if (strcmp(word->data, "[[") == 0) {
3490 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3496 if (command->group) {
3497 /* "{ echo foo; } echo bar" - bad */
3498 syntax_error_at(word->data);
3499 debug_printf_parse("done_word return 1: syntax error, "
3500 "groups and arglists don't mix\n");
3504 /* If this word wasn't an assignment, next ones definitely
3505 * can't be assignments. Even if they look like ones. */
3506 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3507 && word->o_assignment != WORD_IS_KEYWORD
3509 word->o_assignment = NOT_ASSIGNMENT;
3511 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3512 command->assignment_cnt++;
3513 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3515 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3516 word->o_assignment = MAYBE_ASSIGNMENT;
3518 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3520 if (word->has_quoted_part
3521 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3522 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3523 /* (otherwise it's known to be not empty and is already safe) */
3525 /* exclude "$@" - it can expand to no word despite "" */
3526 char *p = word->data;
3527 while (p[0] == SPECIAL_VAR_SYMBOL
3528 && (p[1] & 0x7f) == '@'
3529 && p[2] == SPECIAL_VAR_SYMBOL
3534 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3535 debug_print_strings("word appended to argv", command->argv);
3538 #if ENABLE_HUSH_LOOPS
3539 if (ctx->ctx_res_w == RES_FOR) {
3540 if (word->has_quoted_part
3541 || !is_well_formed_var_name(command->argv[0], '\0')
3543 /* bash says just "not a valid identifier" */
3544 syntax_error("not a valid identifier in for");
3547 /* Force FOR to have just one word (variable name) */
3548 /* NB: basically, this makes hush see "for v in ..."
3549 * syntax as if it is "for v; in ...". FOR and IN become
3550 * two pipe structs in parse tree. */
3551 done_pipe(ctx, PIPE_SEQ);
3554 #if ENABLE_HUSH_CASE
3555 /* Force CASE to have just one word */
3556 if (ctx->ctx_res_w == RES_CASE) {
3557 done_pipe(ctx, PIPE_SEQ);
3561 o_reset_to_empty_unquoted(word);
3563 debug_printf_parse("done_word return 0\n");
3568 /* Peek ahead in the input to find out if we have a "&n" construct,
3569 * as in "2>&1", that represents duplicating a file descriptor.
3571 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3572 * REDIRFD_SYNTAX_ERR if syntax error,
3573 * REDIRFD_TO_FILE if no & was seen,
3574 * or the number found.
3577 #define parse_redir_right_fd(as_string, input) \
3578 parse_redir_right_fd(input)
3580 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3586 return REDIRFD_TO_FILE;
3588 ch = i_getch(input); /* get the & */
3589 nommu_addchr(as_string, ch);
3592 ch = i_getch(input);
3593 nommu_addchr(as_string, ch);
3594 return REDIRFD_CLOSE;
3598 while (ch != EOF && isdigit(ch)) {
3599 d = d*10 + (ch-'0');
3601 ch = i_getch(input);
3602 nommu_addchr(as_string, ch);
3607 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3609 bb_error_msg("ambiguous redirect");
3610 return REDIRFD_SYNTAX_ERR;
3613 /* Return code is 0 normal, 1 if a syntax error is detected
3615 static int parse_redirect(struct parse_context *ctx,
3618 struct in_str *input)
3620 struct command *command = ctx->command;
3621 struct redir_struct *redir;
3622 struct redir_struct **redirp;
3625 dup_num = REDIRFD_TO_FILE;
3626 if (style != REDIRECT_HEREDOC) {
3627 /* Check for a '>&1' type redirect */
3628 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3629 if (dup_num == REDIRFD_SYNTAX_ERR)
3632 int ch = i_peek(input);
3633 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3634 if (dup_num) { /* <<-... */
3635 ch = i_getch(input);
3636 nommu_addchr(&ctx->as_string, ch);
3641 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3642 int ch = i_peek(input);
3644 /* >|FILE redirect ("clobbering" >).
3645 * Since we do not support "set -o noclobber" yet,
3646 * >| and > are the same for now. Just eat |.
3648 ch = i_getch(input);
3649 nommu_addchr(&ctx->as_string, ch);
3653 /* Create a new redir_struct and append it to the linked list */
3654 redirp = &command->redirects;
3655 while ((redir = *redirp) != NULL) {
3656 redirp = &(redir->next);
3658 *redirp = redir = xzalloc(sizeof(*redir));
3659 /* redir->next = NULL; */
3660 /* redir->rd_filename = NULL; */
3661 redir->rd_type = style;
3662 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3664 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3665 redir_table[style].descrip);
3667 redir->rd_dup = dup_num;
3668 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3669 /* Erik had a check here that the file descriptor in question
3670 * is legit; I postpone that to "run time"
3671 * A "-" representation of "close me" shows up as a -3 here */
3672 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3673 redir->rd_fd, redir->rd_dup);
3675 #if 0 /* Instead we emit error message at run time */
3676 if (ctx->pending_redirect) {
3677 /* For example, "cmd > <file" */
3678 die_if_script("syntax error: %s", "invalid redirect");
3681 /* Set ctx->pending_redirect, so we know what to do at the
3682 * end of the next parsed word. */
3683 ctx->pending_redirect = redir;
3688 /* If a redirect is immediately preceded by a number, that number is
3689 * supposed to tell which file descriptor to redirect. This routine
3690 * looks for such preceding numbers. In an ideal world this routine
3691 * needs to handle all the following classes of redirects...
3692 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3693 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3694 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3695 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3697 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3699 * ... If n is quoted, the number shall not be recognized as part of
3700 * the redirection expression. For example:
3702 * writes the character 2 into file a"
3703 * We are getting it right by setting ->has_quoted_part on any \<char>
3705 * A -1 return means no valid number was found,
3706 * the caller should use the appropriate default for this redirection.
3708 static int redirect_opt_num(o_string *o)
3712 if (o->data == NULL)
3714 num = bb_strtou(o->data, NULL, 10);
3715 if (errno || num < 0)
3717 o_reset_to_empty_unquoted(o);
3722 #define fetch_till_str(as_string, input, word, skip_tabs) \
3723 fetch_till_str(input, word, skip_tabs)
3725 static char *fetch_till_str(o_string *as_string,
3726 struct in_str *input,
3730 o_string heredoc = NULL_O_STRING;
3732 int prev = 0; /* not \ */
3738 ch = i_getch(input);
3740 nommu_addchr(as_string, ch);
3741 if ((ch == '\n' || ch == EOF)
3742 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3744 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3745 heredoc.data[past_EOL] = '\0';
3746 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3747 return heredoc.data;
3749 while (ch == '\n') {
3750 o_addchr(&heredoc, ch);
3753 past_EOL = heredoc.length;
3755 ch = i_getch(input);
3757 nommu_addchr(as_string, ch);
3758 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3762 o_free_unsafe(&heredoc);
3765 o_addchr(&heredoc, ch);
3766 nommu_addchr(as_string, ch);
3767 if (prev == '\\' && ch == '\\')
3768 /* Correctly handle foo\\<eol> (not a line cont.) */
3769 prev = 0; /* not \ */
3775 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3776 * and load them all. There should be exactly heredoc_cnt of them.
3778 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3780 struct pipe *pi = ctx->list_head;
3782 while (pi && heredoc_cnt) {
3784 struct command *cmd = pi->cmds;
3786 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3788 cmd->argv ? cmd->argv[0] : "NONE");
3789 for (i = 0; i < pi->num_cmds; i++) {
3790 struct redir_struct *redir = cmd->redirects;
3792 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3793 i, cmd->argv ? cmd->argv[0] : "NONE");
3795 if (redir->rd_type == REDIRECT_HEREDOC) {
3798 redir->rd_type = REDIRECT_HEREDOC2;
3799 /* redir->rd_dup is (ab)used to indicate <<- */
3800 p = fetch_till_str(&ctx->as_string, input,
3801 redir->rd_filename, redir->rd_dup);
3803 syntax_error("unexpected EOF in here document");
3806 free(redir->rd_filename);
3807 redir->rd_filename = p;
3810 redir = redir->next;
3817 /* Should be 0. If it isn't, it's a parse error */
3819 bb_error_msg_and_die("heredoc BUG 2");
3825 static int run_list(struct pipe *pi);
3827 #define parse_stream(pstring, input, end_trigger) \
3828 parse_stream(input, end_trigger)
3830 static struct pipe *parse_stream(char **pstring,
3831 struct in_str *input,
3835 #if !ENABLE_HUSH_FUNCTIONS
3836 #define parse_group(dest, ctx, input, ch) \
3837 parse_group(ctx, input, ch)
3839 static int parse_group(o_string *dest, struct parse_context *ctx,
3840 struct in_str *input, int ch)
3842 /* dest contains characters seen prior to ( or {.
3843 * Typically it's empty, but for function defs,
3844 * it contains function name (without '()'). */
3845 struct pipe *pipe_list;
3847 struct command *command = ctx->command;
3849 debug_printf_parse("parse_group entered\n");
3850 #if ENABLE_HUSH_FUNCTIONS
3851 if (ch == '(' && !dest->has_quoted_part) {
3853 if (done_word(dest, ctx))
3856 goto skip; /* (... */
3857 if (command->argv[1]) { /* word word ... (... */
3858 syntax_error_unexpected_ch('(');
3861 /* it is "word(..." or "word (..." */
3863 ch = i_getch(input);
3864 while (ch == ' ' || ch == '\t');
3866 syntax_error_unexpected_ch(ch);
3869 nommu_addchr(&ctx->as_string, ch);
3871 ch = i_getch(input);
3872 while (ch == ' ' || ch == '\t' || ch == '\n');
3874 syntax_error_unexpected_ch(ch);
3877 nommu_addchr(&ctx->as_string, ch);
3878 command->cmd_type = CMD_FUNCDEF;
3883 #if 0 /* Prevented by caller */
3884 if (command->argv /* word [word]{... */
3885 || dest->length /* word{... */
3886 || dest->has_quoted_part /* ""{... */
3889 debug_printf_parse("parse_group return 1: "
3890 "syntax error, groups and arglists don't mix\n");
3895 #if ENABLE_HUSH_FUNCTIONS
3901 command->cmd_type = CMD_SUBSHELL;
3903 /* bash does not allow "{echo...", requires whitespace */
3904 ch = i_getch(input);
3905 if (ch != ' ' && ch != '\t' && ch != '\n') {
3906 syntax_error_unexpected_ch(ch);
3909 nommu_addchr(&ctx->as_string, ch);
3914 # define as_string NULL
3916 char *as_string = NULL;
3918 pipe_list = parse_stream(&as_string, input, endch);
3921 o_addstr(&ctx->as_string, as_string);
3923 /* empty ()/{} or parse error? */
3924 if (!pipe_list || pipe_list == ERR_PTR) {
3925 /* parse_stream already emitted error msg */
3928 debug_printf_parse("parse_group return 1: "
3929 "parse_stream returned %p\n", pipe_list);
3932 command->group = pipe_list;
3934 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3935 command->group_as_string = as_string;
3936 debug_printf_parse("end of group, remembering as:'%s'\n",
3937 command->group_as_string);
3941 debug_printf_parse("parse_group return 0\n");
3943 /* command remains "open", available for possible redirects */
3946 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
3951 ch = i_getch(input);
3954 ch2 = i_peek(input);
3957 /* backslash+newline, skip it */
3962 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
3970 ch2 = i_peek2(input);
3973 /* backslash+newline, skip it */
3979 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3980 /* Subroutines for copying $(...) and `...` things */
3981 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3983 static int add_till_single_quote(o_string *dest, struct in_str *input)
3986 int ch = i_getch(input);
3988 syntax_error_unterm_ch('\'');
3996 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3997 static int add_till_double_quote(o_string *dest, struct in_str *input)
4000 int ch = i_getch(input);
4002 syntax_error_unterm_ch('"');
4007 if (ch == '\\') { /* \x. Copy both chars. */
4009 ch = i_getch(input);
4013 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4018 //if (ch == '$') ...
4021 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4023 * "Within the backquoted style of command substitution, backslash
4024 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4025 * The search for the matching backquote shall be satisfied by the first
4026 * backquote found without a preceding backslash; during this search,
4027 * if a non-escaped backquote is encountered within a shell comment,
4028 * a here-document, an embedded command substitution of the $(command)
4029 * form, or a quoted string, undefined results occur. A single-quoted
4030 * or double-quoted string that begins, but does not end, within the
4031 * "`...`" sequence produces undefined results."
4033 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4035 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4038 int ch = i_getch(input);
4042 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4043 ch = i_getch(input);
4047 && (!in_dquote || ch != '"')
4049 o_addchr(dest, '\\');
4053 syntax_error_unterm_ch('`');
4059 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4060 * quoting and nested ()s.
4061 * "With the $(command) style of command substitution, all characters
4062 * following the open parenthesis to the matching closing parenthesis
4063 * constitute the command. Any valid shell script can be used for command,
4064 * except a script consisting solely of redirections which produces
4065 * unspecified results."
4067 * echo $(echo '(TEST)' BEST) (TEST) BEST
4068 * echo $(echo 'TEST)' BEST) TEST) BEST
4069 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4071 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4072 * can contain arbitrary constructs, just like $(cmd).
4073 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4074 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4076 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4077 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4080 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4081 # if ENABLE_HUSH_BASH_COMPAT
4082 char end_char2 = end_ch >> 8;
4084 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4087 ch = i_getch(input);
4089 syntax_error_unterm_ch(end_ch);
4092 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4095 /* we look for closing )) of $((EXPR)) */
4096 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4097 i_getch(input); /* eat second ')' */
4102 if (ch == '(' || ch == '{') {
4103 ch = (ch == '(' ? ')' : '}');
4104 if (!add_till_closing_bracket(dest, input, ch))
4110 if (!add_till_single_quote(dest, input))
4116 if (!add_till_double_quote(dest, input))
4122 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4128 /* \x. Copy verbatim. Important for \(, \) */
4129 ch = i_getch(input);
4131 syntax_error_unterm_ch(')');
4136 /* "backslash+newline", ignore both */
4137 o_delchr(dest); /* undo insertion of '\' */
4147 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
4149 /* Return code: 0 for OK, 1 for syntax error */
4151 #define parse_dollar(as_string, dest, input, quote_mask) \
4152 parse_dollar(dest, input, quote_mask)
4153 #define as_string NULL
4155 static int parse_dollar(o_string *as_string,
4157 struct in_str *input, unsigned char quote_mask)
4159 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4161 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4163 ch = i_getch(input);
4164 nommu_addchr(as_string, ch);
4166 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4168 debug_printf_parse(": '%c'\n", ch);
4169 o_addchr(dest, ch | quote_mask);
4171 ch = i_peek_and_eat_bkslash_nl(input);
4172 if (!isalnum(ch) && ch != '_') {
4173 /* End of variable name reached */
4176 ch = i_getch(input);
4177 nommu_addchr(as_string, ch);
4179 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4180 } else if (isdigit(ch)) {
4182 ch = i_getch(input);
4183 nommu_addchr(as_string, ch);
4184 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4185 debug_printf_parse(": '%c'\n", ch);
4186 o_addchr(dest, ch | quote_mask);
4187 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4188 } else switch (ch) {
4190 case '!': /* last bg pid */
4191 case '?': /* last exit code */
4192 case '#': /* number of args */
4193 case '*': /* args */
4194 case '@': /* args */
4195 goto make_one_char_var;
4197 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4199 ch = i_getch(input); /* eat '{' */
4200 nommu_addchr(as_string, ch);
4202 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4203 /* It should be ${?}, or ${#var},
4204 * or even ${?+subst} - operator acting on a special variable,
4205 * or the beginning of variable name.
4208 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4211 syntax_error_unterm_str("${name}");
4212 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4215 nommu_addchr(as_string, ch);
4218 /* It's possible to just call add_till_closing_bracket() at this point.
4219 * However, this regresses some of our testsuite cases
4220 * which check invalid constructs like ${%}.
4221 * Oh well... let's check that the var name part is fine... */
4227 debug_printf_parse(": '%c'\n", ch);
4229 ch = i_getch(input);
4230 nommu_addchr(as_string, ch);
4234 if (!isalnum(ch) && ch != '_') {
4236 unsigned char last_ch;
4237 /* handle parameter expansions
4238 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4240 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4241 goto bad_dollar_syntax;
4243 /* Eat everything until closing '}' (or ':') */
4245 if (ENABLE_HUSH_BASH_COMPAT
4247 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4249 /* It's ${var:N[:M]} thing */
4250 end_ch = '}' * 0x100 + ':';
4252 if (ENABLE_HUSH_BASH_COMPAT
4255 /* It's ${var/[/]pattern[/repl]} thing */
4256 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4258 nommu_addchr(as_string, '/');
4261 end_ch = '}' * 0x100 + '/';
4267 #if ENABLE_HUSH_DOLLAR_OPS
4268 last_ch = add_till_closing_bracket(dest, input, end_ch);
4269 if (last_ch == 0) /* error? */
4272 #error Simple code to only allow ${var} is not implemented
4275 o_addstr(as_string, dest->data + pos);
4276 o_addchr(as_string, last_ch);
4279 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4280 /* close the first block: */
4281 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4282 /* while parsing N from ${var:N[:M]}
4283 * or pattern from ${var/[/]pattern[/repl]} */
4284 if ((end_ch & 0xff) == last_ch) {
4285 /* got ':' or '/'- parse the rest */
4290 if (end_ch == '}' * 0x100 + ':') {
4291 /* it's ${var:N} - emulate :999999999 */
4292 o_addstr(dest, "999999999");
4293 } /* else: it's ${var/[/]pattern} */
4298 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4301 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
4305 ch = i_getch(input);
4306 nommu_addchr(as_string, ch);
4307 # if ENABLE_SH_MATH_SUPPORT
4308 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4309 ch = i_getch(input);
4310 nommu_addchr(as_string, ch);
4311 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4312 o_addchr(dest, /*quote_mask |*/ '+');
4315 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4316 return 0; /* error */
4318 o_addstr(as_string, dest->data + pos);
4319 o_addchr(as_string, ')');
4320 o_addchr(as_string, ')');
4322 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4326 # if ENABLE_HUSH_TICK
4327 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4328 o_addchr(dest, quote_mask | '`');
4331 if (!add_till_closing_bracket(dest, input, ')'))
4332 return 0; /* error */
4334 o_addstr(as_string, dest->data + pos);
4335 o_addchr(as_string, ')');
4337 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4343 ch = i_getch(input);
4344 nommu_addchr(as_string, ch);
4345 ch = i_peek_and_eat_bkslash_nl(input);
4346 if (isalnum(ch)) { /* it's $_name or $_123 */
4351 /* TODO: $_ and $-: */
4352 /* $_ Shell or shell script name; or last argument of last command
4353 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4354 * but in command's env, set to full pathname used to invoke it */
4355 /* $- Option flags set by set builtin or shell options (-i etc) */
4357 o_addQchr(dest, '$');
4359 debug_printf_parse("parse_dollar return 1 (ok)\n");
4365 # if ENABLE_HUSH_BASH_COMPAT
4366 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4367 encode_string(dest, input, dquote_end, process_bkslash)
4369 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4370 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4371 encode_string(dest, input, dquote_end)
4373 #define as_string NULL
4377 # if ENABLE_HUSH_BASH_COMPAT
4378 /* all parameters are needed, no macro tricks */
4380 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4381 encode_string(as_string, dest, input, dquote_end)
4384 static int encode_string(o_string *as_string,
4386 struct in_str *input,
4388 int process_bkslash)
4390 #if !ENABLE_HUSH_BASH_COMPAT
4391 const int process_bkslash = 1;
4397 ch = i_getch(input);
4399 nommu_addchr(as_string, ch);
4400 if (ch == dquote_end) { /* may be only '"' or EOF */
4401 debug_printf_parse("encode_string return 1 (ok)\n");
4404 /* note: can't move it above ch == dquote_end check! */
4406 syntax_error_unterm_ch('"');
4407 return 0; /* error */
4411 next = i_peek(input);
4413 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4414 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4415 if (process_bkslash && ch == '\\') {
4417 syntax_error("\\<eof>");
4421 * "The backslash retains its special meaning [in "..."]
4422 * only when followed by one of the following characters:
4423 * $, `, ", \, or <newline>. A double quote may be quoted
4424 * within double quotes by preceding it with a backslash."
4425 * NB: in (unquoted) heredoc, above does not apply to ",
4426 * therefore we check for it by "next == dquote_end" cond.
4428 if (next == dquote_end || strchr("$`\\\n", next)) {
4429 ch = i_getch(input); /* eat next */
4431 goto again; /* skip \<newline> */
4432 } /* else: ch remains == '\\', and we double it below: */
4433 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4434 nommu_addchr(as_string, ch);
4438 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4439 debug_printf_parse("encode_string return 0: "
4440 "parse_dollar returned 0 (error)\n");
4445 #if ENABLE_HUSH_TICK
4447 //unsigned pos = dest->length;
4448 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4449 o_addchr(dest, 0x80 | '`');
4450 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4451 return 0; /* error */
4452 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4453 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4457 o_addQchr(dest, ch);
4463 * Scan input until EOF or end_trigger char.
4464 * Return a list of pipes to execute, or NULL on EOF
4465 * or if end_trigger character is met.
4466 * On syntax error, exit if shell is not interactive,
4467 * reset parsing machinery and start parsing anew,
4468 * or return ERR_PTR.
4470 static struct pipe *parse_stream(char **pstring,
4471 struct in_str *input,
4474 struct parse_context ctx;
4475 o_string dest = NULL_O_STRING;
4478 /* Single-quote triggers a bypass of the main loop until its mate is
4479 * found. When recursing, quote state is passed in via dest->o_expflags.
4481 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4482 end_trigger ? end_trigger : 'X');
4485 /* If very first arg is "" or '', dest.data may end up NULL.
4486 * Preventing this: */
4487 o_addchr(&dest, '\0');
4490 /* We used to separate words on $IFS here. This was wrong.
4491 * $IFS is used only for word splitting when $var is expanded,
4492 * here we should use blank chars as separators, not $IFS
4495 if (MAYBE_ASSIGNMENT != 0)
4496 dest.o_assignment = MAYBE_ASSIGNMENT;
4497 initialize_context(&ctx);
4500 const char *is_blank;
4501 const char *is_special;
4505 redir_type redir_style;
4507 ch = i_getch(input);
4508 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4509 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4514 syntax_error_unterm_str("here document");
4517 /* end_trigger == '}' case errors out earlier,
4518 * checking only ')' */
4519 if (end_trigger == ')') {
4520 syntax_error_unterm_ch('(');
4524 if (done_word(&dest, &ctx)) {
4528 done_pipe(&ctx, PIPE_SEQ);
4530 /* If we got nothing... */
4531 /* (this makes bare "&" cmd a no-op.
4532 * bash says: "syntax error near unexpected token '&'") */
4533 if (pi->num_cmds == 0
4534 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4540 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4542 *pstring = ctx.as_string.data;
4544 o_free_unsafe(&ctx.as_string);
4547 debug_printf_parse("parse_stream return %p\n", pi);
4550 nommu_addchr(&ctx.as_string, ch);
4554 next = i_peek(input);
4556 is_special = "{}<>;&|()#'" /* special outside of "str" */
4557 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4558 /* Are { and } special here? */
4559 if (ctx.command->argv /* word [word]{... - non-special */
4560 || dest.length /* word{... - non-special */
4561 || dest.has_quoted_part /* ""{... - non-special */
4562 || (next != ';' /* }; - special */
4563 && next != ')' /* }) - special */
4564 && next != '&' /* }& and }&& ... - special */
4565 && next != '|' /* }|| ... - special */
4566 && !strchr(defifs, next) /* {word - non-special */
4569 /* They are not special, skip "{}" */
4572 is_special = strchr(is_special, ch);
4573 is_blank = strchr(defifs, ch);
4575 if (!is_special && !is_blank) { /* ordinary char */
4577 o_addQchr(&dest, ch);
4578 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4579 || dest.o_assignment == WORD_IS_KEYWORD)
4581 && is_well_formed_var_name(dest.data, '=')
4583 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4584 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4590 if (done_word(&dest, &ctx)) {
4594 /* Is this a case when newline is simply ignored?
4596 * "cmd | <newline> cmd ..."
4597 * "case ... in <newline> word) ..."
4599 if (IS_NULL_CMD(ctx.command)
4600 && dest.length == 0 && !dest.has_quoted_part
4602 /* This newline can be ignored. But...
4603 * Without check #1, interactive shell
4604 * ignores even bare <newline>,
4605 * and shows the continuation prompt:
4606 * ps1_prompt$ <enter>
4607 * ps2> _ <=== wrong, should be ps1
4608 * Without check #2, "cmd & <newline>"
4609 * is similarly mistreated.
4610 * (BTW, this makes "cmd & cmd"
4611 * and "cmd && cmd" non-orthogonal.
4612 * Really, ask yourself, why
4613 * "cmd && <newline>" doesn't start
4614 * cmd but waits for more input?
4617 struct pipe *pi = ctx.list_head;
4618 if (pi->num_cmds != 0 /* check #1 */
4619 && pi->followup != PIPE_BG /* check #2 */
4624 /* Treat newline as a command separator. */
4625 done_pipe(&ctx, PIPE_SEQ);
4626 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4628 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4633 dest.o_assignment = MAYBE_ASSIGNMENT;
4634 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4636 /* note: if (is_blank) continue;
4637 * will still trigger for us */
4641 /* "cmd}" or "cmd }..." without semicolon or &:
4642 * } is an ordinary char in this case, even inside { cmd; }
4643 * Pathological example: { ""}; } should exec "}" cmd
4646 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4647 || dest.length != 0 /* word} */
4648 || dest.has_quoted_part /* ""} */
4652 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4653 goto skip_end_trigger;
4654 /* else: } does terminate a group */
4657 if (end_trigger && end_trigger == ch
4658 && (ch != ';' || heredoc_cnt == 0)
4659 #if ENABLE_HUSH_CASE
4661 || ctx.ctx_res_w != RES_MATCH
4662 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4667 /* This is technically valid:
4668 * { cat <<HERE; }; echo Ok
4672 * but we don't support this.
4673 * We require heredoc to be in enclosing {}/(),
4676 syntax_error_unterm_str("here document");
4679 if (done_word(&dest, &ctx)) {
4682 done_pipe(&ctx, PIPE_SEQ);
4683 dest.o_assignment = MAYBE_ASSIGNMENT;
4684 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4685 /* Do we sit outside of any if's, loops or case's? */
4687 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4691 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4693 *pstring = ctx.as_string.data;
4695 o_free_unsafe(&ctx.as_string);
4698 debug_printf_parse("parse_stream return %p: "
4699 "end_trigger char found\n",
4701 return ctx.list_head;
4708 /* Catch <, > before deciding whether this word is
4709 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4712 redir_fd = redirect_opt_num(&dest);
4713 if (done_word(&dest, &ctx)) {
4716 redir_style = REDIRECT_OVERWRITE;
4718 redir_style = REDIRECT_APPEND;
4719 ch = i_getch(input);
4720 nommu_addchr(&ctx.as_string, ch);
4723 else if (next == '(') {
4724 syntax_error(">(process) not supported");
4728 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4730 continue; /* back to top of while (1) */
4732 redir_fd = redirect_opt_num(&dest);
4733 if (done_word(&dest, &ctx)) {
4736 redir_style = REDIRECT_INPUT;
4738 redir_style = REDIRECT_HEREDOC;
4740 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4741 ch = i_getch(input);
4742 nommu_addchr(&ctx.as_string, ch);
4743 } else if (next == '>') {
4744 redir_style = REDIRECT_IO;
4745 ch = i_getch(input);
4746 nommu_addchr(&ctx.as_string, ch);
4749 else if (next == '(') {
4750 syntax_error("<(process) not supported");
4754 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4756 continue; /* back to top of while (1) */
4758 if (dest.length == 0 && !dest.has_quoted_part) {
4759 /* skip "#comment" */
4762 if (ch == EOF || ch == '\n')
4765 /* note: we do not add it to &ctx.as_string */
4767 nommu_addchr(&ctx.as_string, '\n');
4768 continue; /* back to top of while (1) */
4773 /* It's "\<newline>" */
4775 /* Remove trailing '\' from ctx.as_string */
4776 ctx.as_string.data[--ctx.as_string.length] = '\0';
4778 ch = i_getch(input); /* eat it */
4779 continue; /* back to top of while (1) */
4784 if (dest.o_assignment == MAYBE_ASSIGNMENT
4785 /* check that we are not in word in "a=1 2>word b=1": */
4786 && !ctx.pending_redirect
4788 /* ch is a special char and thus this word
4789 * cannot be an assignment */
4790 dest.o_assignment = NOT_ASSIGNMENT;
4791 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4794 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4797 case '#': /* non-comment #: "echo a#b" etc */
4798 o_addQchr(&dest, ch);
4802 syntax_error("\\<eof>");
4805 ch = i_getch(input);
4806 /* note: ch != '\n' (that case does not reach this place) */
4807 o_addchr(&dest, '\\');
4808 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4809 o_addchr(&dest, ch);
4810 nommu_addchr(&ctx.as_string, ch);
4811 /* Example: echo Hello \2>file
4812 * we need to know that word 2 is quoted */
4813 dest.has_quoted_part = 1;
4816 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4817 debug_printf_parse("parse_stream parse error: "
4818 "parse_dollar returned 0 (error)\n");
4823 dest.has_quoted_part = 1;
4824 if (next == '\'' && !ctx.pending_redirect) {
4825 insert_empty_quoted_str_marker:
4826 nommu_addchr(&ctx.as_string, next);
4827 i_getch(input); /* eat second ' */
4828 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4829 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4832 ch = i_getch(input);
4834 syntax_error_unterm_ch('\'');
4837 nommu_addchr(&ctx.as_string, ch);
4840 o_addqchr(&dest, ch);
4845 dest.has_quoted_part = 1;
4846 if (next == '"' && !ctx.pending_redirect)
4847 goto insert_empty_quoted_str_marker;
4848 if (dest.o_assignment == NOT_ASSIGNMENT)
4849 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4850 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4852 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4854 #if ENABLE_HUSH_TICK
4856 USE_FOR_NOMMU(unsigned pos;)
4858 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4859 o_addchr(&dest, '`');
4860 USE_FOR_NOMMU(pos = dest.length;)
4861 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4864 o_addstr(&ctx.as_string, dest.data + pos);
4865 o_addchr(&ctx.as_string, '`');
4867 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4868 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4873 #if ENABLE_HUSH_CASE
4876 if (done_word(&dest, &ctx)) {
4879 done_pipe(&ctx, PIPE_SEQ);
4880 #if ENABLE_HUSH_CASE
4881 /* Eat multiple semicolons, detect
4882 * whether it means something special */
4887 ch = i_getch(input);
4888 nommu_addchr(&ctx.as_string, ch);
4889 if (ctx.ctx_res_w == RES_CASE_BODY) {
4890 ctx.ctx_dsemicolon = 1;
4891 ctx.ctx_res_w = RES_MATCH;
4897 /* We just finished a cmd. New one may start
4898 * with an assignment */
4899 dest.o_assignment = MAYBE_ASSIGNMENT;
4900 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4903 if (done_word(&dest, &ctx)) {
4907 ch = i_getch(input);
4908 nommu_addchr(&ctx.as_string, ch);
4909 done_pipe(&ctx, PIPE_AND);
4911 done_pipe(&ctx, PIPE_BG);
4915 if (done_word(&dest, &ctx)) {
4918 #if ENABLE_HUSH_CASE
4919 if (ctx.ctx_res_w == RES_MATCH)
4920 break; /* we are in case's "word | word)" */
4922 if (next == '|') { /* || */
4923 ch = i_getch(input);
4924 nommu_addchr(&ctx.as_string, ch);
4925 done_pipe(&ctx, PIPE_OR);
4927 /* we could pick up a file descriptor choice here
4928 * with redirect_opt_num(), but bash doesn't do it.
4929 * "echo foo 2| cat" yields "foo 2". */
4934 #if ENABLE_HUSH_CASE
4935 /* "case... in [(]word)..." - skip '(' */
4936 if (ctx.ctx_res_w == RES_MATCH
4937 && ctx.command->argv == NULL /* not (word|(... */
4938 && dest.length == 0 /* not word(... */
4939 && dest.has_quoted_part == 0 /* not ""(... */
4945 if (parse_group(&dest, &ctx, input, ch) != 0) {
4950 #if ENABLE_HUSH_CASE
4951 if (ctx.ctx_res_w == RES_MATCH)
4955 /* proper use of this character is caught by end_trigger:
4956 * if we see {, we call parse_group(..., end_trigger='}')
4957 * and it will match } earlier (not here). */
4958 syntax_error_unexpected_ch(ch);
4962 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4968 struct parse_context *pctx;
4969 IF_HAS_KEYWORDS(struct parse_context *p2;)
4971 /* Clean up allocated tree.
4972 * Sample for finding leaks on syntax error recovery path.
4973 * Run it from interactive shell, watch pmap `pidof hush`.
4974 * while if false; then false; fi; do break; fi
4975 * Samples to catch leaks at execution:
4976 * while if (true | {true;}); then echo ok; fi; do break; done
4977 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4981 /* Update pipe/command counts,
4982 * otherwise freeing may miss some */
4983 done_pipe(pctx, PIPE_SEQ);
4984 debug_printf_clean("freeing list %p from ctx %p\n",
4985 pctx->list_head, pctx);
4986 debug_print_tree(pctx->list_head, 0);
4987 free_pipe_list(pctx->list_head);
4988 debug_printf_clean("freed list %p\n", pctx->list_head);
4990 o_free_unsafe(&pctx->as_string);
4992 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4996 IF_HAS_KEYWORDS(pctx = p2;)
4997 } while (HAS_KEYWORDS && pctx);
5000 G.last_exitcode = 1;
5011 /*** Execution routines ***/
5013 /* Expansion can recurse, need forward decls: */
5014 #if !ENABLE_HUSH_BASH_COMPAT
5015 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5016 #define expand_string_to_string(str, do_unbackslash) \
5017 expand_string_to_string(str)
5019 static char *expand_string_to_string(const char *str, int do_unbackslash);
5020 #if ENABLE_HUSH_TICK
5021 static int process_command_subs(o_string *dest, const char *s);
5024 /* expand_strvec_to_strvec() takes a list of strings, expands
5025 * all variable references within and returns a pointer to
5026 * a list of expanded strings, possibly with larger number
5027 * of strings. (Think VAR="a b"; echo $VAR).
5028 * This new list is allocated as a single malloc block.
5029 * NULL-terminated list of char* pointers is at the beginning of it,
5030 * followed by strings themselves.
5031 * Caller can deallocate entire list by single free(list). */
5033 /* A horde of its helpers come first: */
5035 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5037 while (--len >= 0) {
5040 #if ENABLE_HUSH_BRACE_EXPANSION
5041 if (c == '{' || c == '}') {
5042 /* { -> \{, } -> \} */
5044 /* And now we want to add { or } and continue:
5047 * luckily, just falling throught achieves this.
5053 /* \z -> \\\z; \<eol> -> \\<eol> */
5058 o_addchr(o, *str++);
5064 /* Store given string, finalizing the word and starting new one whenever
5065 * we encounter IFS char(s). This is used for expanding variable values.
5066 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5067 * Return in *ended_with_ifs:
5068 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5070 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5072 int last_is_ifs = 0;
5077 if (!*str) /* EOL - do not finalize word */
5079 word_len = strcspn(str, G.ifs);
5081 /* We have WORD_LEN leading non-IFS chars */
5082 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5083 o_addblock(output, str, word_len);
5085 /* Protect backslashes against globbing up :)
5086 * Example: "v='\*'; echo b$v" prints "b\*"
5087 * (and does not try to glob on "*")
5089 o_addblock_duplicate_backslash(output, str, word_len);
5090 /*/ Why can't we do it easier? */
5091 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5092 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5096 if (!*str) /* EOL - do not finalize word */
5100 /* We know str here points to at least one IFS char */
5102 str += strspn(str, G.ifs); /* skip IFS chars */
5103 if (!*str) /* EOL - do not finalize word */
5106 /* Start new word... but not always! */
5107 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5108 if (output->has_quoted_part
5109 /* Case "v=' a'; echo $v":
5110 * here nothing precedes the space in $v expansion,
5111 * therefore we should not finish the word
5112 * (IOW: if there *is* word to finalize, only then do it):
5114 || (n > 0 && output->data[output->length - 1])
5116 o_addchr(output, '\0');
5117 debug_print_list("expand_on_ifs", output, n);
5118 n = o_save_ptr(output, n);
5123 *ended_with_ifs = last_is_ifs;
5124 debug_print_list("expand_on_ifs[1]", output, n);
5128 /* Helper to expand $((...)) and heredoc body. These act as if
5129 * they are in double quotes, with the exception that they are not :).
5130 * Just the rules are similar: "expand only $var and `cmd`"
5132 * Returns malloced string.
5133 * As an optimization, we return NULL if expansion is not needed.
5135 #if !ENABLE_HUSH_BASH_COMPAT
5136 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5137 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5138 encode_then_expand_string(str)
5140 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5143 struct in_str input;
5144 o_string dest = NULL_O_STRING;
5146 if (!strchr(str, '$')
5147 && !strchr(str, '\\')
5148 #if ENABLE_HUSH_TICK
5149 && !strchr(str, '`')
5155 /* We need to expand. Example:
5156 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5158 setup_string_in_str(&input, str);
5159 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5160 //TODO: error check (encode_string returns 0 on error)?
5161 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5162 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5163 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5164 o_free_unsafe(&dest);
5168 #if ENABLE_SH_MATH_SUPPORT
5169 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5171 arith_state_t math_state;
5175 math_state.lookupvar = get_local_var_value;
5176 math_state.setvar = set_local_var_from_halves;
5177 //math_state.endofname = endofname;
5178 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5179 res = arith(&math_state, exp_str ? exp_str : arg);
5182 *errmsg_p = math_state.errmsg;
5183 if (math_state.errmsg)
5184 die_if_script(math_state.errmsg);
5189 #if ENABLE_HUSH_BASH_COMPAT
5190 /* ${var/[/]pattern[/repl]} helpers */
5191 static char *strstr_pattern(char *val, const char *pattern, int *size)
5194 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5195 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5202 /* Optimization: if "*pat" did not match the start of "string",
5203 * we know that "tring", "ring" etc will not match too:
5205 if (pattern[0] == '*')
5210 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5212 char *result = NULL;
5213 unsigned res_len = 0;
5214 unsigned repl_len = strlen(repl);
5218 char *s = strstr_pattern(val, pattern, &size);
5222 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5223 memcpy(result + res_len, val, s - val);
5225 strcpy(result + res_len, repl);
5226 res_len += repl_len;
5227 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5233 if (val[0] && result) {
5234 result = xrealloc(result, res_len + strlen(val) + 1);
5235 strcpy(result + res_len, val);
5236 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5238 debug_printf_varexp("result:'%s'\n", result);
5244 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5246 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5248 const char *val = NULL;
5249 char *to_be_freed = NULL;
5254 char exp_save = exp_save; /* for compiler */
5255 char *exp_saveptr; /* points to expansion operator */
5256 char *exp_word = exp_word; /* for compiler */
5259 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5261 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5263 first_char = arg[0] = arg0 & 0x7f;
5266 if (first_char == '#' /* ${#... */
5267 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5269 /* It must be length operator: ${#var} */
5273 /* Maybe handle parameter expansion */
5274 if (exp_saveptr /* if 2nd char is one of expansion operators */
5275 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5277 /* ${?:0}, ${#[:]%0} etc */
5278 exp_saveptr = var + 1;
5280 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5281 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5283 exp_op = exp_save = *exp_saveptr;
5285 exp_word = exp_saveptr + 1;
5286 if (exp_op == ':') {
5287 exp_op = *exp_word++;
5288 //TODO: try ${var:} and ${var:bogus} in non-bash config
5289 if (ENABLE_HUSH_BASH_COMPAT
5290 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5292 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5297 *exp_saveptr = '\0';
5298 } /* else: it's not an expansion op, but bare ${var} */
5301 /* Look up the variable in question */
5302 if (isdigit(var[0])) {
5303 /* parse_dollar should have vetted var for us */
5304 int n = xatoi_positive(var);
5305 if (n < G.global_argc)
5306 val = G.global_argv[n];
5307 /* else val remains NULL: $N with too big N */
5311 val = utoa(G.root_pid);
5313 case '!': /* bg pid */
5314 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5316 case '?': /* exitcode */
5317 val = utoa(G.last_exitcode);
5319 case '#': /* argc */
5320 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5323 val = get_local_var_value(var);
5327 /* Handle any expansions */
5328 if (exp_op == 'L') {
5329 reinit_unicode_for_hush();
5330 debug_printf_expand("expand: length(%s)=", val);
5331 val = utoa(val ? unicode_strlen(val) : 0);
5332 debug_printf_expand("%s\n", val);
5333 } else if (exp_op) {
5334 if (exp_op == '%' || exp_op == '#') {
5335 /* Standard-mandated substring removal ops:
5336 * ${parameter%word} - remove smallest suffix pattern
5337 * ${parameter%%word} - remove largest suffix pattern
5338 * ${parameter#word} - remove smallest prefix pattern
5339 * ${parameter##word} - remove largest prefix pattern
5341 * Word is expanded to produce a glob pattern.
5342 * Then var's value is matched to it and matching part removed.
5344 if (val && val[0]) {
5348 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5349 if (exp_op == *exp_word) /* ## or %% */
5351 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5353 exp_word = exp_exp_word;
5354 /* HACK ALERT. We depend here on the fact that
5355 * G.global_argv and results of utoa and get_local_var_value
5356 * are actually in writable memory:
5357 * scan_and_match momentarily stores NULs there. */
5359 loc = scan_and_match(t, exp_word, scan_flags);
5360 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5361 // exp_op, t, exp_word, loc);
5363 if (loc) { /* match was found */
5364 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5365 val = loc; /* take right part */
5367 val = to_be_freed = xstrndup(val, loc - val); /* left */
5371 #if ENABLE_HUSH_BASH_COMPAT
5372 else if (exp_op == '/' || exp_op == '\\') {
5373 /* It's ${var/[/]pattern[/repl]} thing.
5374 * Note that in encoded form it has TWO parts:
5375 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5376 * and if // is used, it is encoded as \:
5377 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5379 /* Empty variable always gives nothing: */
5380 // "v=''; echo ${v/*/w}" prints "", not "w"
5381 if (val && val[0]) {
5382 /* pattern uses non-standard expansion.
5383 * repl should be unbackslashed and globbed
5384 * by the usual expansion rules:
5386 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5387 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5388 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5389 * v='a bz'; echo ${v/a*z/\z} prints "z"
5390 * (note that a*z _pattern_ is never globbed!)
5392 char *pattern, *repl, *t;
5393 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5395 pattern = xstrdup(exp_word);
5396 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5397 *p++ = SPECIAL_VAR_SYMBOL;
5399 p = strchr(p, SPECIAL_VAR_SYMBOL);
5401 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5402 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5403 /* HACK ALERT. We depend here on the fact that
5404 * G.global_argv and results of utoa and get_local_var_value
5405 * are actually in writable memory:
5406 * replace_pattern momentarily stores NULs there. */
5408 to_be_freed = replace_pattern(t,
5410 (repl ? repl : exp_word),
5412 if (to_be_freed) /* at least one replace happened */
5419 else if (exp_op == ':') {
5420 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5421 /* It's ${var:N[:M]} bashism.
5422 * Note that in encoded form it has TWO parts:
5423 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5428 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5431 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5432 *p++ = SPECIAL_VAR_SYMBOL;
5434 p = strchr(p, SPECIAL_VAR_SYMBOL);
5436 len = expand_and_evaluate_arith(exp_word, &errmsg);
5439 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5440 if (len >= 0) { /* bash compat: len < 0 is illegal */
5441 if (beg < 0) /* bash compat */
5443 debug_printf_varexp("from val:'%s'\n", val);
5444 if (len == 0 || !val || beg >= strlen(val)) {
5448 /* Paranoia. What if user entered 9999999999999
5449 * which fits in arith_t but not int? */
5452 val = to_be_freed = xstrndup(val + beg, len);
5454 debug_printf_varexp("val:'%s'\n", val);
5458 die_if_script("malformed ${%s:...}", var);
5461 } else { /* one of "-=+?" */
5462 /* Standard-mandated substitution ops:
5463 * ${var?word} - indicate error if unset
5464 * If var is unset, word (or a message indicating it is unset
5465 * if word is null) is written to standard error
5466 * and the shell exits with a non-zero exit status.
5467 * Otherwise, the value of var is substituted.
5468 * ${var-word} - use default value
5469 * If var is unset, word is substituted.
5470 * ${var=word} - assign and use default value
5471 * If var is unset, word is assigned to var.
5472 * In all cases, final value of var is substituted.
5473 * ${var+word} - use alternative value
5474 * If var is unset, null is substituted.
5475 * Otherwise, word is substituted.
5477 * Word is subjected to tilde expansion, parameter expansion,
5478 * command substitution, and arithmetic expansion.
5479 * If word is not needed, it is not expanded.
5481 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5482 * but also treat null var as if it is unset.
5484 int use_word = (!val || ((exp_save == ':') && !val[0]));
5486 use_word = !use_word;
5487 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5488 (exp_save == ':') ? "true" : "false", use_word);
5490 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5492 exp_word = to_be_freed;
5493 if (exp_op == '?') {
5494 /* mimic bash message */
5495 die_if_script("%s: %s",
5497 exp_word[0] ? exp_word : "parameter null or not set"
5499 //TODO: how interactive bash aborts expansion mid-command?
5504 if (exp_op == '=') {
5505 /* ${var=[word]} or ${var:=[word]} */
5506 if (isdigit(var[0]) || var[0] == '#') {
5507 /* mimic bash message */
5508 die_if_script("$%s: cannot assign in this way", var);
5511 char *new_var = xasprintf("%s=%s", var, val);
5512 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5516 } /* one of "-=+?" */
5518 *exp_saveptr = exp_save;
5524 *to_be_freed_pp = to_be_freed;
5528 /* Expand all variable references in given string, adding words to list[]
5529 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5530 * to be filled). This routine is extremely tricky: has to deal with
5531 * variables/parameters with whitespace, $* and $@, and constructs like
5532 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5533 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5535 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5536 * expansion of right-hand side of assignment == 1-element expand.
5538 char cant_be_null = 0; /* only bit 0x80 matters */
5539 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5542 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5543 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5544 debug_print_list("expand_vars_to_list", output, n);
5545 n = o_save_ptr(output, n);
5546 debug_print_list("expand_vars_to_list[0]", output, n);
5548 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5550 char *to_be_freed = NULL;
5551 const char *val = NULL;
5552 #if ENABLE_HUSH_TICK
5553 o_string subst_result = NULL_O_STRING;
5555 #if ENABLE_SH_MATH_SUPPORT
5556 char arith_buf[sizeof(arith_t)*3 + 2];
5560 o_addchr(output, '\0');
5561 n = o_save_ptr(output, n);
5565 o_addblock(output, arg, p - arg);
5566 debug_print_list("expand_vars_to_list[1]", output, n);
5568 p = strchr(p, SPECIAL_VAR_SYMBOL);
5570 /* Fetch special var name (if it is indeed one of them)
5571 * and quote bit, force the bit on if singleword expansion -
5572 * important for not getting v=$@ expand to many words. */
5573 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5575 /* Is this variable quoted and thus expansion can't be null?
5576 * "$@" is special. Even if quoted, it can still
5577 * expand to nothing (not even an empty string),
5578 * thus it is excluded. */
5579 if ((first_ch & 0x7f) != '@')
5580 cant_be_null |= first_ch;
5582 switch (first_ch & 0x7f) {
5583 /* Highest bit in first_ch indicates that var is double-quoted */
5587 if (!G.global_argv[1])
5590 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5591 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5592 while (G.global_argv[i]) {
5593 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5594 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5595 if (G.global_argv[i++][0] && G.global_argv[i]) {
5596 /* this argv[] is not empty and not last:
5597 * put terminating NUL, start new word */
5598 o_addchr(output, '\0');
5599 debug_print_list("expand_vars_to_list[2]", output, n);
5600 n = o_save_ptr(output, n);
5601 debug_print_list("expand_vars_to_list[3]", output, n);
5605 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5606 * and in this case should treat it like '$*' - see 'else...' below */
5607 if (first_ch == ('@'|0x80) /* quoted $@ */
5608 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5611 o_addQstr(output, G.global_argv[i]);
5612 if (++i >= G.global_argc)
5614 o_addchr(output, '\0');
5615 debug_print_list("expand_vars_to_list[4]", output, n);
5616 n = o_save_ptr(output, n);
5618 } else { /* quoted $* (or v="$@" case): add as one word */
5620 o_addQstr(output, G.global_argv[i]);
5621 if (!G.global_argv[++i])
5624 o_addchr(output, G.ifs[0]);
5626 output->has_quoted_part = 1;
5630 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5631 /* "Empty variable", used to make "" etc to not disappear */
5632 output->has_quoted_part = 1;
5634 cant_be_null = 0x80;
5636 #if ENABLE_HUSH_TICK
5637 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5638 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5640 /* Can't just stuff it into output o_string,
5641 * expanded result may need to be globbed
5642 * and $IFS-splitted */
5643 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5644 G.last_exitcode = process_command_subs(&subst_result, arg);
5645 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5646 val = subst_result.data;
5649 #if ENABLE_SH_MATH_SUPPORT
5650 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5653 arg++; /* skip '+' */
5654 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5655 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5656 res = expand_and_evaluate_arith(arg, NULL);
5657 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5658 sprintf(arith_buf, ARITH_FMT, res);
5664 val = expand_one_var(&to_be_freed, arg, &p);
5665 IF_HUSH_TICK(store_val:)
5666 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5667 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5668 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5669 if (val && val[0]) {
5670 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5673 } else { /* quoted $VAR, val will be appended below */
5674 output->has_quoted_part = 1;
5675 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5676 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5679 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5681 if (val && val[0]) {
5682 o_addQstr(output, val);
5686 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5687 * Do the check to avoid writing to a const string. */
5688 if (*p != SPECIAL_VAR_SYMBOL)
5689 *p = SPECIAL_VAR_SYMBOL;
5691 #if ENABLE_HUSH_TICK
5692 o_free(&subst_result);
5695 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5699 o_addchr(output, '\0');
5700 n = o_save_ptr(output, n);
5702 debug_print_list("expand_vars_to_list[a]", output, n);
5703 /* this part is literal, and it was already pre-quoted
5704 * if needed (much earlier), do not use o_addQstr here! */
5705 o_addstr_with_NUL(output, arg);
5706 debug_print_list("expand_vars_to_list[b]", output, n);
5707 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5708 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5711 /* allow to reuse list[n] later without re-growth */
5712 output->has_empty_slot = 1;
5714 o_addchr(output, '\0');
5720 static char **expand_variables(char **argv, unsigned expflags)
5724 o_string output = NULL_O_STRING;
5726 output.o_expflags = expflags;
5730 n = expand_vars_to_list(&output, n, *argv);
5733 debug_print_list("expand_variables", &output, n);
5735 /* output.data (malloced in one block) gets returned in "list" */
5736 list = o_finalize_list(&output, n);
5737 debug_print_strings("expand_variables[1]", list);
5741 static char **expand_strvec_to_strvec(char **argv)
5743 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5746 #if ENABLE_HUSH_BASH_COMPAT
5747 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5749 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5753 /* Used for expansion of right hand of assignments,
5754 * $((...)), heredocs, variable espansion parts.
5756 * NB: should NOT do globbing!
5757 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5759 static char *expand_string_to_string(const char *str, int do_unbackslash)
5761 #if !ENABLE_HUSH_BASH_COMPAT
5762 const int do_unbackslash = 1;
5764 char *argv[2], **list;
5766 debug_printf_expand("string_to_string<='%s'\n", str);
5767 /* This is generally an optimization, but it also
5768 * handles "", which otherwise trips over !list[0] check below.
5769 * (is this ever happens that we actually get str="" here?)
5771 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5772 //TODO: Can use on strings with \ too, just unbackslash() them?
5773 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5774 return xstrdup(str);
5777 argv[0] = (char*)str;
5779 list = expand_variables(argv, do_unbackslash
5780 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5781 : EXP_FLAG_SINGLEWORD
5784 if (!list[0] || list[1])
5785 bb_error_msg_and_die("BUG in varexp2");
5786 /* actually, just move string 2*sizeof(char*) bytes back */
5787 overlapping_strcpy((char*)list, list[0]);
5789 unbackslash((char*)list);
5790 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5794 /* Used for "eval" builtin */
5795 static char* expand_strvec_to_string(char **argv)
5799 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5800 /* Convert all NULs to spaces */
5805 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5806 bb_error_msg_and_die("BUG in varexp3");
5807 /* bash uses ' ' regardless of $IFS contents */
5812 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
5813 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5817 static char **expand_assignments(char **argv, int count)
5822 G.expanded_assignments = p = NULL;
5823 /* Expand assignments into one string each */
5824 for (i = 0; i < count; i++) {
5825 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5827 G.expanded_assignments = NULL;
5832 static void switch_off_special_sigs(unsigned mask)
5835 while ((mask >>= 1) != 0) {
5840 if (G.traps[sig] && !G.traps[sig][0])
5841 /* trap is '', has to remain SIG_IGN */
5844 G.traps[sig] = NULL;
5846 /* We are here only if no trap or trap was not '' */
5847 install_sighandler(sig, SIG_DFL);
5853 void re_execute_shell(char ***to_free, const char *s,
5854 char *g_argv0, char **g_argv,
5855 char **builtin_argv) NORETURN;
5857 static void reset_traps_to_defaults(void)
5859 /* This function is always called in a child shell
5860 * after fork (not vfork, NOMMU doesn't use this function).
5865 /* Child shells are not interactive.
5866 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5867 * Testcase: (while :; do :; done) + ^Z should background.
5868 * Same goes for SIGTERM, SIGHUP, SIGINT.
5870 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5871 if (!G.traps && !mask)
5872 return; /* already no traps and no special sigs */
5874 /* Switch off special sigs */
5875 switch_off_special_sigs(mask);
5877 G_fatal_sig_mask = 0;
5879 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5880 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5881 * remain set in G.special_sig_mask */
5886 /* Reset all sigs to default except ones with empty traps */
5887 for (sig = 0; sig < NSIG; sig++) {
5889 continue; /* no trap: nothing to do */
5890 if (!G.traps[sig][0])
5891 continue; /* empty trap: has to remain SIG_IGN */
5892 /* sig has non-empty trap, reset it: */
5894 G.traps[sig] = NULL;
5895 /* There is no signal for trap 0 (EXIT) */
5898 install_sighandler(sig, pick_sighandler(sig));
5904 static void re_execute_shell(char ***to_free, const char *s,
5905 char *g_argv0, char **g_argv,
5906 char **builtin_argv) NORETURN;
5907 static void re_execute_shell(char ***to_free, const char *s,
5908 char *g_argv0, char **g_argv,
5909 char **builtin_argv)
5911 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5912 /* delims + 2 * (number of bytes in printed hex numbers) */
5913 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5914 char *heredoc_argv[4];
5915 struct variable *cur;
5916 # if ENABLE_HUSH_FUNCTIONS
5917 struct function *funcp;
5921 unsigned long long empty_trap_mask;
5923 if (!g_argv0) { /* heredoc */
5924 argv = heredoc_argv;
5925 argv[0] = (char *) G.argv0_for_re_execing;
5926 argv[1] = (char *) "-<";
5927 argv[2] = (char *) s;
5929 pp = &argv[3]; /* used as pointer to empty environment */
5935 if (pp) while (*pp++)
5938 empty_trap_mask = 0;
5941 for (sig = 1; sig < NSIG; sig++) {
5942 if (G.traps[sig] && !G.traps[sig][0])
5943 empty_trap_mask |= 1LL << sig;
5947 sprintf(param_buf, NOMMU_HACK_FMT
5948 , (unsigned) G.root_pid
5949 , (unsigned) G.root_ppid
5950 , (unsigned) G.last_bg_pid
5951 , (unsigned) G.last_exitcode
5954 IF_HUSH_LOOPS(, G.depth_of_loop)
5956 # undef NOMMU_HACK_FMT
5957 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5958 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5961 for (cur = G.top_var; cur; cur = cur->next) {
5962 if (!cur->flg_export || cur->flg_read_only)
5965 # if ENABLE_HUSH_FUNCTIONS
5966 for (funcp = G.top_func; funcp; funcp = funcp->next)
5972 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5973 *pp++ = (char *) G.argv0_for_re_execing;
5975 for (cur = G.top_var; cur; cur = cur->next) {
5976 if (strcmp(cur->varstr, hush_version_str) == 0)
5978 if (cur->flg_read_only) {
5979 *pp++ = (char *) "-R";
5980 *pp++ = cur->varstr;
5981 } else if (!cur->flg_export) {
5982 *pp++ = (char *) "-V";
5983 *pp++ = cur->varstr;
5986 # if ENABLE_HUSH_FUNCTIONS
5987 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5988 *pp++ = (char *) "-F";
5989 *pp++ = funcp->name;
5990 *pp++ = funcp->body_as_string;
5993 /* We can pass activated traps here. Say, -Tnn:trap_string
5995 * However, POSIX says that subshells reset signals with traps
5997 * I tested bash-3.2 and it not only does that with true subshells
5998 * of the form ( list ), but with any forked children shells.
5999 * I set trap "echo W" WINCH; and then tried:
6001 * { echo 1; sleep 20; echo 2; } &
6002 * while true; do echo 1; sleep 20; echo 2; break; done &
6003 * true | { echo 1; sleep 20; echo 2; } | cat
6005 * In all these cases sending SIGWINCH to the child shell
6006 * did not run the trap. If I add trap "echo V" WINCH;
6007 * _inside_ group (just before echo 1), it works.
6009 * I conclude it means we don't need to pass active traps here.
6011 *pp++ = (char *) "-c";
6014 while (*++builtin_argv)
6015 *pp++ = *builtin_argv;
6016 *pp++ = (char *) "";
6021 /* *pp = NULL; - is already there */
6025 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6026 /* Don't propagate SIG_IGN to the child */
6027 if (SPECIAL_JOBSTOP_SIGS != 0)
6028 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6029 execve(bb_busybox_exec_path, argv, pp);
6030 /* Fallback. Useful for init=/bin/hush usage etc */
6031 if (argv[0][0] == '/')
6032 execve(argv[0], argv, pp);
6033 xfunc_error_retval = 127;
6034 bb_error_msg_and_die("can't re-execute the shell");
6036 #endif /* !BB_MMU */
6039 static int run_and_free_list(struct pipe *pi);
6041 /* Executing from string: eval, sh -c '...'
6042 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6043 * end_trigger controls how often we stop parsing
6044 * NUL: parse all, execute, return
6045 * ';': parse till ';' or newline, execute, repeat till EOF
6047 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6049 /* Why we need empty flag?
6050 * An obscure corner case "false; ``; echo $?":
6051 * empty command in `` should still set $? to 0.
6052 * But we can't just set $? to 0 at the start,
6053 * this breaks "false; echo `echo $?`" case.
6057 struct pipe *pipe_list;
6059 #if ENABLE_HUSH_INTERACTIVE
6060 if (end_trigger == ';')
6061 inp->promptmode = 0; /* PS1 */
6063 pipe_list = parse_stream(NULL, inp, end_trigger);
6064 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6065 /* If we are in "big" script
6066 * (not in `cmd` or something similar)...
6068 if (pipe_list == ERR_PTR && end_trigger == ';') {
6069 /* Discard cached input (rest of line) */
6070 int ch = inp->last_char;
6071 while (ch != EOF && ch != '\n') {
6072 //bb_error_msg("Discarded:'%c'", ch);
6077 /* This stream isn't empty */
6081 if (!pipe_list && empty)
6082 G.last_exitcode = 0;
6085 debug_print_tree(pipe_list, 0);
6086 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6087 run_and_free_list(pipe_list);
6089 if (G_flag_return_in_progress == 1)
6094 static void parse_and_run_string(const char *s)
6096 struct in_str input;
6097 setup_string_in_str(&input, s);
6098 parse_and_run_stream(&input, '\0');
6101 static void parse_and_run_file(FILE *f)
6103 struct in_str input;
6104 setup_file_in_str(&input, f);
6105 parse_and_run_stream(&input, ';');
6108 #if ENABLE_HUSH_TICK
6109 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6114 char **to_free = NULL;
6118 pid = BB_MMU ? xfork() : xvfork();
6119 if (pid == 0) { /* child */
6120 disable_restore_tty_pgrp_on_exit();
6121 /* Process substitution is not considered to be usual
6122 * 'command execution'.
6123 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6130 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6131 close(channel[0]); /* NB: close _first_, then move fd! */
6132 xmove_fd(channel[1], 1);
6133 /* Prevent it from trying to handle ctrl-z etc */
6134 IF_HUSH_JOB(G.run_list_level = 1;)
6135 /* Awful hack for `trap` or $(trap).
6137 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6138 * contains an example where "trap" is executed in a subshell:
6140 * save_traps=$(trap)
6142 * eval "$save_traps"
6144 * Standard does not say that "trap" in subshell shall print
6145 * parent shell's traps. It only says that its output
6146 * must have suitable form, but then, in the above example
6147 * (which is not supposed to be normative), it implies that.
6149 * bash (and probably other shell) does implement it
6150 * (traps are reset to defaults, but "trap" still shows them),
6151 * but as a result, "trap" logic is hopelessly messed up:
6154 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6155 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6156 * # true | trap <--- trap is in subshell - no output (ditto)
6157 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6158 * trap -- 'echo Ho' SIGWINCH
6159 * # echo `(trap)` <--- in subshell in subshell - output
6160 * trap -- 'echo Ho' SIGWINCH
6161 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6162 * trap -- 'echo Ho' SIGWINCH
6164 * The rules when to forget and when to not forget traps
6165 * get really complex and nonsensical.
6167 * Our solution: ONLY bare $(trap) or `trap` is special.
6169 s = skip_whitespace(s);
6170 if (is_prefixed_with(s, "trap")
6171 && skip_whitespace(s + 4)[0] == '\0'
6173 static const char *const argv[] = { NULL, NULL };
6174 builtin_trap((char**)argv);
6175 fflush_all(); /* important */
6179 reset_traps_to_defaults();
6180 parse_and_run_string(s);
6181 _exit(G.last_exitcode);
6183 /* We re-execute after vfork on NOMMU. This makes this script safe:
6184 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6185 * huge=`cat BIG` # was blocking here forever
6188 re_execute_shell(&to_free,
6198 # if ENABLE_HUSH_FAST
6200 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6201 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6202 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6204 enable_restore_tty_pgrp_on_exit();
6209 return remember_FILE(xfdopen_for_read(channel[0]));
6212 /* Return code is exit status of the process that is run. */
6213 static int process_command_subs(o_string *dest, const char *s)
6216 struct in_str pipe_str;
6218 int status, ch, eol_cnt;
6220 fp = generate_stream_from_string(s, &pid);
6222 /* Now send results of command back into original context */
6223 setup_file_in_str(&pipe_str, fp);
6225 while ((ch = i_getch(&pipe_str)) != EOF) {
6231 o_addchr(dest, '\n');
6234 o_addQchr(dest, ch);
6237 debug_printf("done reading from `cmd` pipe, closing it\n");
6238 fclose_and_forget(fp);
6239 /* We need to extract exitcode. Test case
6240 * "true; echo `sleep 1; false` $?"
6242 safe_waitpid(pid, &status, 0);
6243 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6244 return WEXITSTATUS(status);
6246 #endif /* ENABLE_HUSH_TICK */
6249 static void setup_heredoc(struct redir_struct *redir)
6251 struct fd_pair pair;
6254 /* the _body_ of heredoc (misleading field name) */
6255 const char *heredoc = redir->rd_filename;
6262 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6263 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6267 len = strlen(heredoc);
6269 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6271 xmove_fd(pair.rd, redir->rd_fd);
6273 /* Try writing without forking. Newer kernels have
6274 * dynamically growing pipes. Must use non-blocking write! */
6277 written = write(pair.wr, heredoc, len);
6288 ndelay_off(pair.wr);
6290 /* Okay, pipe buffer was not big enough */
6291 /* Note: we must not create a stray child (bastard? :)
6292 * for the unsuspecting parent process. Child creates a grandchild
6293 * and exits before parent execs the process which consumes heredoc
6294 * (that exec happens after we return from this function) */
6301 disable_restore_tty_pgrp_on_exit();
6302 pid = BB_MMU ? xfork() : xvfork();
6306 close(redir->rd_fd); /* read side of the pipe */
6308 full_write(pair.wr, heredoc, len); /* may loop or block */
6311 /* Delegate blocking writes to another process */
6312 xmove_fd(pair.wr, STDOUT_FILENO);
6313 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6317 #if ENABLE_HUSH_FAST
6319 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6321 enable_restore_tty_pgrp_on_exit();
6327 wait(NULL); /* wait till child has died */
6330 /* fd: redirect wants this fd to be used (e.g. 3>file).
6331 * Move all conflicting internally used fds,
6332 * and remember them so that we can restore them later.
6334 static int save_fds_on_redirect(int fd, int squirrel[3])
6337 /* Handle redirects of fds 0,1,2 */
6339 /* If we collide with an already moved stdio fd... */
6340 if (fd == squirrel[0]) {
6341 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6344 if (fd == squirrel[1]) {
6345 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6348 if (fd == squirrel[2]) {
6349 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6352 /* If we are about to redirect stdio fd, and did not yet move it... */
6353 if (fd <= 2 && squirrel[fd] < 0) {
6354 /* We avoid taking stdio fds */
6355 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6356 if (squirrel[fd] < 0 && errno != EBADF)
6358 return 0; /* "we did not close fd" */
6362 #if ENABLE_HUSH_INTERACTIVE
6363 if (fd != 0 && fd == G.interactive_fd) {
6364 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6369 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6370 * (1) Redirect in a forked child. No need to save FILEs' fds,
6371 * we aren't going to use them anymore, ok to trash.
6372 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6373 * but how are we doing to use them?
6374 * "fileno(fd) = new_fd" can't be done.
6379 return save_FILEs_on_redirect(fd);
6382 static void restore_redirects(int squirrel[3])
6385 for (i = 0; i <= 2; i++) {
6388 /* We simply die on error */
6393 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6395 restore_redirected_FILEs();
6398 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6399 * and stderr if they are redirected. */
6400 static int setup_redirects(struct command *prog, int squirrel[])
6403 struct redir_struct *redir;
6405 for (redir = prog->redirects; redir; redir = redir->next) {
6406 if (redir->rd_type == REDIRECT_HEREDOC2) {
6407 /* "rd_fd<<HERE" case */
6408 save_fds_on_redirect(redir->rd_fd, squirrel);
6409 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6411 debug_printf_parse("set heredoc '%s'\n",
6412 redir->rd_filename);
6413 setup_heredoc(redir);
6417 if (redir->rd_dup == REDIRFD_TO_FILE) {
6418 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6420 if (redir->rd_filename == NULL) {
6423 * "cmd >" (no filename)
6424 * "cmd > <file" (2nd redirect starts too early)
6426 die_if_script("syntax error: %s", "invalid redirect");
6429 mode = redir_table[redir->rd_type].mode;
6430 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6431 openfd = open_or_warn(p, mode);
6434 /* Error message from open_or_warn can be lost
6435 * if stderr has been redirected, but bash
6436 * and ash both lose it as well
6437 * (though zsh doesn't!)
6442 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6443 openfd = redir->rd_dup;
6446 if (openfd != redir->rd_fd) {
6447 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6448 if (openfd == REDIRFD_CLOSE) {
6449 /* "rd_fd >&-" means "close me" */
6451 /* ^^^ optimization: saving may already
6452 * have closed it. If not... */
6453 close(redir->rd_fd);
6456 xdup2(openfd, redir->rd_fd);
6457 if (redir->rd_dup == REDIRFD_TO_FILE)
6458 /* "rd_fd > FILE" */
6460 /* else: "rd_fd > rd_dup" */
6467 static char *find_in_path(const char *arg)
6470 const char *PATH = get_local_var_value("PATH");
6476 const char *end = strchrnul(PATH, ':');
6477 int sz = end - PATH; /* must be int! */
6481 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6483 /* We have xxx::yyyy in $PATH,
6484 * it means "use current dir" */
6487 if (access(ret, F_OK) == 0)
6500 static const struct built_in_command *find_builtin_helper(const char *name,
6501 const struct built_in_command *x,
6502 const struct built_in_command *end)
6505 if (strcmp(name, x->b_cmd) != 0) {
6509 debug_printf_exec("found builtin '%s'\n", name);
6514 static const struct built_in_command *find_builtin1(const char *name)
6516 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6518 static const struct built_in_command *find_builtin(const char *name)
6520 const struct built_in_command *x = find_builtin1(name);
6523 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6526 #if ENABLE_HUSH_FUNCTIONS
6527 static struct function **find_function_slot(const char *name)
6529 struct function **funcpp = &G.top_func;
6531 if (strcmp(name, (*funcpp)->name) == 0) {
6534 funcpp = &(*funcpp)->next;
6539 static const struct function *find_function(const char *name)
6541 const struct function *funcp = *find_function_slot(name);
6543 debug_printf_exec("found function '%s'\n", name);
6547 /* Note: takes ownership on name ptr */
6548 static struct function *new_function(char *name)
6550 struct function **funcpp = find_function_slot(name);
6551 struct function *funcp = *funcpp;
6553 if (funcp != NULL) {
6554 struct command *cmd = funcp->parent_cmd;
6555 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6557 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6559 /* Note: if !funcp->body, do not free body_as_string!
6560 * This is a special case of "-F name body" function:
6561 * body_as_string was not malloced! */
6563 free_pipe_list(funcp->body);
6565 free(funcp->body_as_string);
6569 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6570 cmd->argv[0] = funcp->name;
6571 cmd->group = funcp->body;
6573 cmd->group_as_string = funcp->body_as_string;
6577 debug_printf_exec("remembering new function '%s'\n", name);
6578 funcp = *funcpp = xzalloc(sizeof(*funcp));
6579 /*funcp->next = NULL;*/
6586 static void unset_func(const char *name)
6588 struct function **funcpp = find_function_slot(name);
6589 struct function *funcp = *funcpp;
6591 if (funcp != NULL) {
6592 debug_printf_exec("freeing function '%s'\n", funcp->name);
6593 *funcpp = funcp->next;
6594 /* funcp is unlinked now, deleting it.
6595 * Note: if !funcp->body, the function was created by
6596 * "-F name body", do not free ->body_as_string
6597 * and ->name as they were not malloced. */
6599 free_pipe_list(funcp->body);
6602 free(funcp->body_as_string);
6610 #define exec_function(to_free, funcp, argv) \
6611 exec_function(funcp, argv)
6613 static void exec_function(char ***to_free,
6614 const struct function *funcp,
6615 char **argv) NORETURN;
6616 static void exec_function(char ***to_free,
6617 const struct function *funcp,
6623 argv[0] = G.global_argv[0];
6624 G.global_argv = argv;
6628 /* On MMU, funcp->body is always non-NULL */
6629 n = run_list(funcp->body);
6633 re_execute_shell(to_free,
6634 funcp->body_as_string,
6641 static int run_function(const struct function *funcp, char **argv)
6647 save_and_replace_G_args(&sv, argv);
6649 /* "we are in function, ok to use return" */
6650 sv_flg = G_flag_return_in_progress;
6651 G_flag_return_in_progress = -1;
6652 # if ENABLE_HUSH_LOCAL
6653 G.func_nest_level++;
6656 /* On MMU, funcp->body is always non-NULL */
6659 /* Function defined by -F */
6660 parse_and_run_string(funcp->body_as_string);
6661 rc = G.last_exitcode;
6665 rc = run_list(funcp->body);
6668 # if ENABLE_HUSH_LOCAL
6670 struct variable *var;
6671 struct variable **var_pp;
6673 var_pp = &G.top_var;
6674 while ((var = *var_pp) != NULL) {
6675 if (var->func_nest_level < G.func_nest_level) {
6676 var_pp = &var->next;
6680 if (var->flg_export)
6681 bb_unsetenv(var->varstr);
6682 /* Remove from global list */
6683 *var_pp = var->next;
6689 G.func_nest_level--;
6692 G_flag_return_in_progress = sv_flg;
6694 restore_G_args(&sv, argv);
6698 #endif /* ENABLE_HUSH_FUNCTIONS */
6702 #define exec_builtin(to_free, x, argv) \
6703 exec_builtin(x, argv)
6705 #define exec_builtin(to_free, x, argv) \
6706 exec_builtin(to_free, argv)
6708 static void exec_builtin(char ***to_free,
6709 const struct built_in_command *x,
6710 char **argv) NORETURN;
6711 static void exec_builtin(char ***to_free,
6712 const struct built_in_command *x,
6718 rcode = x->b_function(argv);
6723 /* On NOMMU, we must never block!
6724 * Example: { sleep 99 | read line; } & echo Ok
6726 re_execute_shell(to_free,
6735 static void execvp_or_die(char **argv) NORETURN;
6736 static void execvp_or_die(char **argv)
6738 debug_printf_exec("execing '%s'\n", argv[0]);
6739 /* Don't propagate SIG_IGN to the child */
6740 if (SPECIAL_JOBSTOP_SIGS != 0)
6741 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6742 execvp(argv[0], argv);
6743 bb_perror_msg("can't execute '%s'", argv[0]);
6744 _exit(127); /* bash compat */
6747 #if ENABLE_HUSH_MODE_X
6748 static void dump_cmd_in_x_mode(char **argv)
6750 if (G_x_mode && argv) {
6751 /* We want to output the line in one write op */
6759 len += strlen(argv[n++]) + 1;
6765 p += sprintf(p, " %s", argv[n++]);
6773 # define dump_cmd_in_x_mode(argv) ((void)0)
6777 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6778 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6779 #define pseudo_exec(nommu_save, command, argv_expanded) \
6780 pseudo_exec(command, argv_expanded)
6783 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6785 * Don't exit() here. If you don't exec, use _exit instead.
6786 * The at_exit handlers apparently confuse the calling process,
6787 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6789 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6790 char **argv, int assignment_cnt,
6791 char **argv_expanded) NORETURN;
6792 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6793 char **argv, int assignment_cnt,
6794 char **argv_expanded)
6798 new_env = expand_assignments(argv, assignment_cnt);
6799 dump_cmd_in_x_mode(new_env);
6801 if (!argv[assignment_cnt]) {
6802 /* Case when we are here: ... | var=val | ...
6803 * (note that we do not exit early, i.e., do not optimize out
6804 * expand_assignments(): think about ... | var=`sleep 1` | ...
6806 free_strings(new_env);
6807 _exit(EXIT_SUCCESS);
6811 set_vars_and_save_old(new_env);
6812 free(new_env); /* optional */
6813 /* we can also destroy set_vars_and_save_old's return value,
6816 nommu_save->new_env = new_env;
6817 nommu_save->old_vars = set_vars_and_save_old(new_env);
6820 if (argv_expanded) {
6821 argv = argv_expanded;
6823 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6825 nommu_save->argv = argv;
6828 dump_cmd_in_x_mode(argv);
6830 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6831 if (strchr(argv[0], '/') != NULL)
6835 /* Check if the command matches any of the builtins.
6836 * Depending on context, this might be redundant. But it's
6837 * easier to waste a few CPU cycles than it is to figure out
6838 * if this is one of those cases.
6841 /* On NOMMU, it is more expensive to re-execute shell
6842 * just in order to run echo or test builtin.
6843 * It's better to skip it here and run corresponding
6844 * non-builtin later. */
6845 const struct built_in_command *x;
6846 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6848 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6851 #if ENABLE_HUSH_FUNCTIONS
6852 /* Check if the command matches any functions */
6854 const struct function *funcp = find_function(argv[0]);
6856 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6861 #if ENABLE_FEATURE_SH_STANDALONE
6862 /* Check if the command matches any busybox applets */
6864 int a = find_applet_by_name(argv[0]);
6866 # if BB_MMU /* see above why on NOMMU it is not allowed */
6867 if (APPLET_IS_NOEXEC(a)) {
6868 /* Do not leak open fds from opened script files etc */
6869 close_all_FILE_list();
6870 debug_printf_exec("running applet '%s'\n", argv[0]);
6871 run_applet_no_and_exit(a, argv);
6874 /* Re-exec ourselves */
6875 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6876 /* Don't propagate SIG_IGN to the child */
6877 if (SPECIAL_JOBSTOP_SIGS != 0)
6878 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6879 execv(bb_busybox_exec_path, argv);
6880 /* If they called chroot or otherwise made the binary no longer
6881 * executable, fall through */
6886 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6889 execvp_or_die(argv);
6892 /* Called after [v]fork() in run_pipe
6894 static void pseudo_exec(nommu_save_t *nommu_save,
6895 struct command *command,
6896 char **argv_expanded) NORETURN;
6897 static void pseudo_exec(nommu_save_t *nommu_save,
6898 struct command *command,
6899 char **argv_expanded)
6901 if (command->argv) {
6902 pseudo_exec_argv(nommu_save, command->argv,
6903 command->assignment_cnt, argv_expanded);
6906 if (command->group) {
6907 /* Cases when we are here:
6910 * ... | ( list ) | ...
6911 * ... | { list } | ...
6915 debug_printf_exec("pseudo_exec: run_list\n");
6916 reset_traps_to_defaults();
6917 rcode = run_list(command->group);
6918 /* OK to leak memory by not calling free_pipe_list,
6919 * since this process is about to exit */
6922 re_execute_shell(&nommu_save->argv_from_re_execing,
6923 command->group_as_string,
6930 /* Case when we are here: ... | >file */
6931 debug_printf_exec("pseudo_exec'ed null command\n");
6932 _exit(EXIT_SUCCESS);
6936 static const char *get_cmdtext(struct pipe *pi)
6942 /* This is subtle. ->cmdtext is created only on first backgrounding.
6943 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6944 * On subsequent bg argv is trashed, but we won't use it */
6947 argv = pi->cmds[0].argv;
6948 if (!argv || !argv[0]) {
6949 pi->cmdtext = xzalloc(1);
6955 len += strlen(*argv) + 1;
6959 argv = pi->cmds[0].argv;
6961 len = strlen(*argv);
6962 memcpy(p, *argv, len);
6970 static void insert_bg_job(struct pipe *pi)
6972 struct pipe *job, **jobp;
6975 /* Linear search for the ID of the job to use */
6977 for (job = G.job_list; job; job = job->next)
6978 if (job->jobid >= pi->jobid)
6979 pi->jobid = job->jobid + 1;
6981 /* Add job to the list of running jobs */
6983 while ((job = *jobp) != NULL)
6985 job = *jobp = xmalloc(sizeof(*job));
6987 *job = *pi; /* physical copy */
6989 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6990 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6991 for (i = 0; i < pi->num_cmds; i++) {
6992 job->cmds[i].pid = pi->cmds[i].pid;
6993 /* all other fields are not used and stay zero */
6995 job->cmdtext = xstrdup(get_cmdtext(pi));
6997 if (G_interactive_fd)
6998 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6999 G.last_jobid = job->jobid;
7002 static void remove_bg_job(struct pipe *pi)
7004 struct pipe *prev_pipe;
7006 if (pi == G.job_list) {
7007 G.job_list = pi->next;
7009 prev_pipe = G.job_list;
7010 while (prev_pipe->next != pi)
7011 prev_pipe = prev_pipe->next;
7012 prev_pipe->next = pi->next;
7015 G.last_jobid = G.job_list->jobid;
7020 /* Remove a backgrounded job */
7021 static void delete_finished_bg_job(struct pipe *pi)
7028 /* Check to see if any processes have exited -- if they
7029 * have, figure out why and see if a job has completed */
7030 static int checkjobs(struct pipe *fg_pipe)
7040 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7042 attributes = WUNTRACED;
7043 if (fg_pipe == NULL)
7044 attributes |= WNOHANG;
7047 #if ENABLE_HUSH_FAST
7048 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7049 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7050 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7051 /* There was neither fork nor SIGCHLD since last waitpid */
7052 /* Avoid doing waitpid syscall if possible */
7053 if (!G.we_have_children) {
7057 if (fg_pipe == NULL) { /* is WNOHANG set? */
7058 /* We have children, but they did not exit
7059 * or stop yet (we saw no SIGCHLD) */
7062 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7066 /* Do we do this right?
7067 * bash-3.00# sleep 20 | false
7069 * [3]+ Stopped sleep 20 | false
7070 * bash-3.00# echo $?
7071 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7072 * [hush 1.14.0: yes we do it right]
7079 #if ENABLE_HUSH_FAST
7080 i = G.count_SIGCHLD;
7082 childpid = waitpid(-1, &status, attributes);
7083 if (childpid <= 0) {
7084 if (childpid && errno != ECHILD)
7085 bb_perror_msg("waitpid");
7086 #if ENABLE_HUSH_FAST
7087 else { /* Until next SIGCHLD, waitpid's are useless */
7088 G.we_have_children = (childpid == 0);
7089 G.handled_SIGCHLD = i;
7090 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7095 dead = WIFEXITED(status) || WIFSIGNALED(status);
7098 if (WIFSTOPPED(status))
7099 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7100 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7101 if (WIFSIGNALED(status))
7102 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7103 childpid, WTERMSIG(status), WEXITSTATUS(status));
7104 if (WIFEXITED(status))
7105 debug_printf_jobs("pid %d exited, exitcode %d\n",
7106 childpid, WEXITSTATUS(status));
7108 /* Were we asked to wait for fg pipe? */
7110 i = fg_pipe->num_cmds;
7112 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7113 if (fg_pipe->cmds[i].pid != childpid)
7117 fg_pipe->cmds[i].pid = 0;
7118 fg_pipe->alive_cmds--;
7119 ex = WEXITSTATUS(status);
7120 /* bash prints killer signal's name for *last*
7121 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7122 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7124 if (WIFSIGNALED(status)) {
7125 int sig = WTERMSIG(status);
7126 if (i == fg_pipe->num_cmds-1)
7127 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7128 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7129 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7130 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7131 * Maybe we need to use sig | 128? */
7134 fg_pipe->cmds[i].cmd_exitcode = ex;
7136 fg_pipe->stopped_cmds++;
7138 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7139 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7140 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
7141 /* All processes in fg pipe have exited or stopped */
7142 i = fg_pipe->num_cmds;
7144 rcode = fg_pipe->cmds[i].cmd_exitcode;
7145 /* usually last process gives overall exitstatus,
7146 * but with "set -o pipefail", last *failed* process does */
7147 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7150 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
7151 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7152 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7153 * and "killall -STOP cat" */
7154 if (G_interactive_fd) {
7156 if (fg_pipe->alive_cmds != 0)
7157 insert_bg_job(fg_pipe);
7161 if (fg_pipe->alive_cmds == 0)
7164 /* There are still running processes in the fg pipe */
7165 goto wait_more; /* do waitpid again */
7167 /* it wasnt fg_pipe, look for process in bg pipes */
7171 /* We asked to wait for bg or orphaned children */
7172 /* No need to remember exitcode in this case */
7173 for (pi = G.job_list; pi; pi = pi->next) {
7174 for (i = 0; i < pi->num_cmds; i++) {
7175 if (pi->cmds[i].pid == childpid)
7176 goto found_pi_and_prognum;
7179 /* Happens when shell is used as init process (init=/bin/sh) */
7180 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7181 continue; /* do waitpid again */
7183 found_pi_and_prognum:
7186 pi->cmds[i].pid = 0;
7188 if (!pi->alive_cmds) {
7189 if (G_interactive_fd)
7190 printf(JOB_STATUS_FORMAT, pi->jobid,
7191 "Done", pi->cmdtext);
7192 delete_finished_bg_job(pi);
7199 } /* while (waitpid succeeds)... */
7205 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7208 int rcode = checkjobs(fg_pipe);
7209 if (G_saved_tty_pgrp) {
7210 /* Job finished, move the shell to the foreground */
7211 p = getpgrp(); /* our process group id */
7212 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7213 tcsetpgrp(G_interactive_fd, p);
7219 /* Start all the jobs, but don't wait for anything to finish.
7222 * Return code is normally -1, when the caller has to wait for children
7223 * to finish to determine the exit status of the pipe. If the pipe
7224 * is a simple builtin command, however, the action is done by the
7225 * time run_pipe returns, and the exit code is provided as the
7228 * Returns -1 only if started some children. IOW: we have to
7229 * mask out retvals of builtins etc with 0xff!
7231 * The only case when we do not need to [v]fork is when the pipe
7232 * is single, non-backgrounded, non-subshell command. Examples:
7233 * cmd ; ... { list } ; ...
7234 * cmd && ... { list } && ...
7235 * cmd || ... { list } || ...
7236 * If it is, then we can run cmd as a builtin, NOFORK,
7237 * or (if SH_STANDALONE) an applet, and we can run the { list }
7238 * with run_list. If it isn't one of these, we fork and exec cmd.
7240 * Cases when we must fork:
7241 * non-single: cmd | cmd
7242 * backgrounded: cmd & { list } &
7243 * subshell: ( list ) [&]
7245 #if !ENABLE_HUSH_MODE_X
7246 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7247 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7249 static int redirect_and_varexp_helper(char ***new_env_p,
7250 struct variable **old_vars_p,
7251 struct command *command,
7253 char **argv_expanded)
7255 /* setup_redirects acts on file descriptors, not FILEs.
7256 * This is perfect for work that comes after exec().
7257 * Is it really safe for inline use? Experimentally,
7258 * things seem to work. */
7259 int rcode = setup_redirects(command, squirrel);
7261 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7262 *new_env_p = new_env;
7263 dump_cmd_in_x_mode(new_env);
7264 dump_cmd_in_x_mode(argv_expanded);
7266 *old_vars_p = set_vars_and_save_old(new_env);
7270 static NOINLINE int run_pipe(struct pipe *pi)
7272 static const char *const null_ptr = NULL;
7276 struct command *command;
7277 char **argv_expanded;
7279 /* it is not always needed, but we aim to smaller code */
7280 int squirrel[] = { -1, -1, -1 };
7283 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7286 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7287 * Result should be 3 lines: q w e, qwe, q w e
7289 G.ifs = get_local_var_value("IFS");
7293 IF_HUSH_JOB(pi->pgrp = -1;)
7294 pi->stopped_cmds = 0;
7295 command = &pi->cmds[0];
7296 argv_expanded = NULL;
7298 if (pi->num_cmds != 1
7299 || pi->followup == PIPE_BG
7300 || command->cmd_type == CMD_SUBSHELL
7307 debug_printf_exec(": group:%p argv:'%s'\n",
7308 command->group, command->argv ? command->argv[0] : "NONE");
7310 if (command->group) {
7311 #if ENABLE_HUSH_FUNCTIONS
7312 if (command->cmd_type == CMD_FUNCDEF) {
7313 /* "executing" func () { list } */
7314 struct function *funcp;
7316 funcp = new_function(command->argv[0]);
7317 /* funcp->name is already set to argv[0] */
7318 funcp->body = command->group;
7320 funcp->body_as_string = command->group_as_string;
7321 command->group_as_string = NULL;
7323 command->group = NULL;
7324 command->argv[0] = NULL;
7325 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7326 funcp->parent_cmd = command;
7327 command->child_func = funcp;
7329 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7331 return EXIT_SUCCESS;
7335 debug_printf("non-subshell group\n");
7336 rcode = 1; /* exitcode if redir failed */
7337 if (setup_redirects(command, squirrel) == 0) {
7338 debug_printf_exec(": run_list\n");
7339 rcode = run_list(command->group) & 0xff;
7341 restore_redirects(squirrel);
7342 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7344 debug_printf_exec("run_pipe: return %d\n", rcode);
7348 argv = command->argv ? command->argv : (char **) &null_ptr;
7350 const struct built_in_command *x;
7351 #if ENABLE_HUSH_FUNCTIONS
7352 const struct function *funcp;
7356 char **new_env = NULL;
7357 struct variable *old_vars = NULL;
7359 if (argv[command->assignment_cnt] == NULL) {
7360 /* Assignments, but no command */
7361 /* Ensure redirects take effect (that is, create files).
7362 * Try "a=t >file" */
7363 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7364 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7365 /* Set shell variables */
7369 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7370 /* Do we need to flag set_local_var() errors?
7371 * "assignment to readonly var" and "putenv error"
7376 /* Redirect error sets $? to 1. Otherwise,
7377 * if evaluating assignment value set $?, retain it.
7378 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7380 rcode = G.last_exitcode;
7381 /* Exit, _skipping_ variable restoring code: */
7382 goto clean_up_and_ret0;
7384 #else /* Older, bigger, but more correct code */
7386 rcode = setup_redirects(command, squirrel);
7387 restore_redirects(squirrel);
7388 /* Set shell variables */
7390 bb_putchar_stderr('+');
7392 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7394 fprintf(stderr, " %s", p);
7395 debug_printf_exec("set shell var:'%s'->'%s'\n",
7397 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7398 /* Do we need to flag set_local_var() errors?
7399 * "assignment to readonly var" and "putenv error"
7404 bb_putchar_stderr('\n');
7405 /* Redirect error sets $? to 1. Otherwise,
7406 * if evaluating assignment value set $?, retain it.
7407 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7409 rcode = G.last_exitcode;
7410 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7412 debug_printf_exec("run_pipe: return %d\n", rcode);
7417 /* Expand the rest into (possibly) many strings each */
7418 #if ENABLE_HUSH_BASH_COMPAT
7419 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7420 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7424 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7427 /* if someone gives us an empty string: `cmd with empty output` */
7428 if (!argv_expanded[0]) {
7429 free(argv_expanded);
7431 return G.last_exitcode;
7434 x = find_builtin(argv_expanded[0]);
7435 #if ENABLE_HUSH_FUNCTIONS
7438 funcp = find_function(argv_expanded[0]);
7442 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7443 debug_printf("exec with redirects only\n");
7444 rcode = setup_redirects(command, NULL);
7445 /* rcode=1 can be if redir file can't be opened */
7446 goto clean_up_and_ret1;
7449 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7452 debug_printf_exec(": builtin '%s' '%s'...\n",
7453 x->b_cmd, argv_expanded[1]);
7455 rcode = x->b_function(argv_expanded) & 0xff;
7458 #if ENABLE_HUSH_FUNCTIONS
7460 # if ENABLE_HUSH_LOCAL
7461 struct variable **sv;
7462 sv = G.shadowed_vars_pp;
7463 G.shadowed_vars_pp = &old_vars;
7465 debug_printf_exec(": function '%s' '%s'...\n",
7466 funcp->name, argv_expanded[1]);
7467 rcode = run_function(funcp, argv_expanded) & 0xff;
7468 # if ENABLE_HUSH_LOCAL
7469 G.shadowed_vars_pp = sv;
7475 unset_vars(new_env);
7477 /* clean_up_and_ret0: */
7478 restore_redirects(squirrel);
7480 free(argv_expanded);
7481 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7483 debug_printf_exec("run_pipe return %d\n", rcode);
7487 if (ENABLE_FEATURE_SH_NOFORK) {
7488 int n = find_applet_by_name(argv_expanded[0]);
7489 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7490 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7492 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7493 argv_expanded[0], argv_expanded[1]);
7494 rcode = run_nofork_applet(n, argv_expanded);
7496 goto clean_up_and_ret;
7499 /* It is neither builtin nor applet. We must fork. */
7503 /* NB: argv_expanded may already be created, and that
7504 * might include `cmd` runs! Do not rerun it! We *must*
7505 * use argv_expanded if it's non-NULL */
7507 /* Going to fork a child per each pipe member */
7512 while (cmd_no < pi->num_cmds) {
7513 struct fd_pair pipefds;
7515 volatile nommu_save_t nommu_save;
7516 nommu_save.new_env = NULL;
7517 nommu_save.old_vars = NULL;
7518 nommu_save.argv = NULL;
7519 nommu_save.argv_from_re_execing = NULL;
7521 command = &pi->cmds[cmd_no];
7523 if (command->argv) {
7524 debug_printf_exec(": pipe member '%s' '%s'...\n",
7525 command->argv[0], command->argv[1]);
7527 debug_printf_exec(": pipe member with no argv\n");
7530 /* pipes are inserted between pairs of commands */
7533 if (cmd_no < pi->num_cmds)
7534 xpiped_pair(pipefds);
7536 command->pid = BB_MMU ? fork() : vfork();
7537 if (!command->pid) { /* child */
7539 disable_restore_tty_pgrp_on_exit();
7540 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7542 /* Every child adds itself to new process group
7543 * with pgid == pid_of_first_child_in_pipe */
7544 if (G.run_list_level == 1 && G_interactive_fd) {
7547 if (pgrp < 0) /* true for 1st process only */
7549 if (setpgid(0, pgrp) == 0
7550 && pi->followup != PIPE_BG
7551 && G_saved_tty_pgrp /* we have ctty */
7553 /* We do it in *every* child, not just first,
7555 tcsetpgrp(G_interactive_fd, pgrp);
7559 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7560 /* 1st cmd in backgrounded pipe
7561 * should have its stdin /dev/null'ed */
7563 if (open(bb_dev_null, O_RDONLY))
7564 xopen("/", O_RDONLY);
7566 xmove_fd(next_infd, 0);
7568 xmove_fd(pipefds.wr, 1);
7571 /* Like bash, explicit redirects override pipes,
7572 * and the pipe fd (fd#1) is available for dup'ing:
7573 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7574 * of cmd1 goes into pipe.
7576 if (setup_redirects(command, NULL)) {
7577 /* Happens when redir file can't be opened:
7578 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7580 * hush: can't open '/qwe/rty': No such file or directory
7582 * (echo BAR is not executed, it hits _exit(1) below)
7587 /* Stores to nommu_save list of env vars putenv'ed
7588 * (NOMMU, on MMU we don't need that) */
7589 /* cast away volatility... */
7590 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7591 /* pseudo_exec() does not return */
7594 /* parent or error */
7595 #if ENABLE_HUSH_FAST
7597 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7599 enable_restore_tty_pgrp_on_exit();
7601 /* Clean up after vforked child */
7602 free(nommu_save.argv);
7603 free(nommu_save.argv_from_re_execing);
7604 unset_vars(nommu_save.new_env);
7605 add_vars(nommu_save.old_vars);
7607 free(argv_expanded);
7608 argv_expanded = NULL;
7609 if (command->pid < 0) { /* [v]fork failed */
7610 /* Clearly indicate, was it fork or vfork */
7611 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7615 /* Second and next children need to know pid of first one */
7617 pi->pgrp = command->pid;
7623 if (cmd_no < pi->num_cmds)
7625 /* Pass read (output) pipe end to next iteration */
7626 next_infd = pipefds.rd;
7629 if (!pi->alive_cmds) {
7631 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7636 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7640 /* NB: called by pseudo_exec, and therefore must not modify any
7641 * global data until exec/_exit (we can be a child after vfork!) */
7642 static int run_list(struct pipe *pi)
7644 #if ENABLE_HUSH_CASE
7645 char *case_word = NULL;
7647 #if ENABLE_HUSH_LOOPS
7648 struct pipe *loop_top = NULL;
7649 char **for_lcur = NULL;
7650 char **for_list = NULL;
7652 smallint last_followup;
7654 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7655 smalluint cond_code = 0;
7657 enum { cond_code = 0 };
7660 smallint rword; /* RES_foo */
7661 smallint last_rword; /* ditto */
7664 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7667 #if ENABLE_HUSH_LOOPS
7668 /* Check syntax for "for" */
7671 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7672 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7674 /* current word is FOR or IN (BOLD in comments below) */
7675 if (cpipe->next == NULL) {
7676 syntax_error("malformed for");
7678 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7681 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7682 if (cpipe->next->res_word == RES_DO)
7684 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7685 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7686 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7688 syntax_error("malformed for");
7690 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7697 /* Past this point, all code paths should jump to ret: label
7698 * in order to return, no direct "return" statements please.
7699 * This helps to ensure that no memory is leaked. */
7707 last_rword = RES_XXXX;
7709 last_followup = PIPE_SEQ;
7710 rcode = G.last_exitcode;
7712 /* Go through list of pipes, (maybe) executing them. */
7713 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7716 if (G_flag_return_in_progress == 1)
7719 IF_HAS_KEYWORDS(rword = pi->res_word;)
7720 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7721 rword, cond_code, last_rword);
7722 #if ENABLE_HUSH_LOOPS
7723 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7724 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7726 /* start of a loop: remember where loop starts */
7731 /* Still in the same "if...", "then..." or "do..." branch? */
7732 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7733 if ((rcode == 0 && last_followup == PIPE_OR)
7734 || (rcode != 0 && last_followup == PIPE_AND)
7736 /* It is "<true> || CMD" or "<false> && CMD"
7737 * and we should not execute CMD */
7738 debug_printf_exec("skipped cmd because of || or &&\n");
7739 last_followup = pi->followup;
7740 goto dont_check_jobs_but_continue;
7743 last_followup = pi->followup;
7744 IF_HAS_KEYWORDS(last_rword = rword;)
7747 if (rword == RES_THEN) {
7748 /* if false; then ... fi has exitcode 0! */
7749 G.last_exitcode = rcode = EXIT_SUCCESS;
7750 /* "if <false> THEN cmd": skip cmd */
7754 if (rword == RES_ELSE || rword == RES_ELIF) {
7755 /* "if <true> then ... ELSE/ELIF cmd":
7756 * skip cmd and all following ones */
7761 #if ENABLE_HUSH_LOOPS
7762 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7764 /* first loop through for */
7766 static const char encoded_dollar_at[] ALIGN1 = {
7767 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7768 }; /* encoded representation of "$@" */
7769 static const char *const encoded_dollar_at_argv[] = {
7770 encoded_dollar_at, NULL
7771 }; /* argv list with one element: "$@" */
7774 vals = (char**)encoded_dollar_at_argv;
7775 if (pi->next->res_word == RES_IN) {
7776 /* if no variable values after "in" we skip "for" */
7777 if (!pi->next->cmds[0].argv) {
7778 G.last_exitcode = rcode = EXIT_SUCCESS;
7779 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7782 vals = pi->next->cmds[0].argv;
7783 } /* else: "for var; do..." -> assume "$@" list */
7784 /* create list of variable values */
7785 debug_print_strings("for_list made from", vals);
7786 for_list = expand_strvec_to_strvec(vals);
7787 for_lcur = for_list;
7788 debug_print_strings("for_list", for_list);
7791 /* "for" loop is over, clean up */
7797 /* Insert next value from for_lcur */
7798 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7799 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7802 if (rword == RES_IN) {
7803 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7805 if (rword == RES_DONE) {
7806 continue; /* "done" has no cmds too */
7809 #if ENABLE_HUSH_CASE
7810 if (rword == RES_CASE) {
7811 case_word = expand_strvec_to_string(pi->cmds->argv);
7814 if (rword == RES_MATCH) {
7817 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7819 /* all prev words didn't match, does this one match? */
7820 argv = pi->cmds->argv;
7822 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7823 /* TODO: which FNM_xxx flags to use? */
7824 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7826 if (cond_code == 0) { /* match! we will execute this branch */
7827 free(case_word); /* make future "word)" stop */
7835 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7837 continue; /* not matched yet, skip this pipe */
7840 /* Just pressing <enter> in shell should check for jobs.
7841 * OTOH, in non-interactive shell this is useless
7842 * and only leads to extra job checks */
7843 if (pi->num_cmds == 0) {
7844 if (G_interactive_fd)
7845 goto check_jobs_and_continue;
7849 /* After analyzing all keywords and conditions, we decided
7850 * to execute this pipe. NB: have to do checkjobs(NULL)
7851 * after run_pipe to collect any background children,
7852 * even if list execution is to be stopped. */
7853 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7856 #if ENABLE_HUSH_LOOPS
7857 G.flag_break_continue = 0;
7859 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7861 /* We ran a builtin, function, or group.
7862 * rcode is already known
7863 * and we don't need to wait for anything. */
7864 G.last_exitcode = rcode;
7865 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7866 check_and_run_traps();
7867 #if ENABLE_HUSH_LOOPS
7868 /* Was it "break" or "continue"? */
7869 if (G.flag_break_continue) {
7870 smallint fbc = G.flag_break_continue;
7871 /* We might fall into outer *loop*,
7872 * don't want to break it too */
7874 G.depth_break_continue--;
7875 if (G.depth_break_continue == 0)
7876 G.flag_break_continue = 0;
7877 /* else: e.g. "continue 2" should *break* once, *then* continue */
7878 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7879 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7883 /* "continue": simulate end of loop */
7888 if (G_flag_return_in_progress == 1) {
7892 } else if (pi->followup == PIPE_BG) {
7893 /* What does bash do with attempts to background builtins? */
7894 /* even bash 3.2 doesn't do that well with nested bg:
7895 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7896 * I'm NOT treating inner &'s as jobs */
7897 check_and_run_traps();
7899 if (G.run_list_level == 1)
7902 /* Last command's pid goes to $! */
7903 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7904 G.last_exitcode = rcode = EXIT_SUCCESS;
7905 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7908 if (G.run_list_level == 1 && G_interactive_fd) {
7909 /* Waits for completion, then fg's main shell */
7910 rcode = checkjobs_and_fg_shell(pi);
7911 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7912 check_and_run_traps();
7915 { /* This one just waits for completion */
7916 rcode = checkjobs(pi);
7917 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7918 check_and_run_traps();
7920 G.last_exitcode = rcode;
7924 /* Analyze how result affects subsequent commands */
7926 if (rword == RES_IF || rword == RES_ELIF)
7929 check_jobs_and_continue:
7931 dont_check_jobs_but_continue: ;
7932 #if ENABLE_HUSH_LOOPS
7933 /* Beware of "while false; true; do ..."! */
7935 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7936 /* check for RES_DONE is needed for "while ...; do \n done" case */
7938 if (rword == RES_WHILE) {
7940 /* "while false; do...done" - exitcode 0 */
7941 G.last_exitcode = rcode = EXIT_SUCCESS;
7942 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7946 if (rword == RES_UNTIL) {
7948 debug_printf_exec(": until expr is true: breaking\n");
7959 #if ENABLE_HUSH_LOOPS
7964 #if ENABLE_HUSH_CASE
7968 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7972 /* Select which version we will use */
7973 static int run_and_free_list(struct pipe *pi)
7976 debug_printf_exec("run_and_free_list entered\n");
7977 if (!G.o_opt[OPT_O_NOEXEC]) {
7978 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7979 rcode = run_list(pi);
7981 /* free_pipe_list has the side effect of clearing memory.
7982 * In the long run that function can be merged with run_list,
7983 * but doing that now would hobble the debugging effort. */
7985 debug_printf_exec("run_and_free_list return %d\n", rcode);
7990 static void install_sighandlers(unsigned mask)
7992 sighandler_t old_handler;
7994 while ((mask >>= 1) != 0) {
7998 old_handler = install_sighandler(sig, pick_sighandler(sig));
7999 /* POSIX allows shell to re-enable SIGCHLD
8000 * even if it was SIG_IGN on entry.
8001 * Therefore we skip IGN check for it:
8005 if (old_handler == SIG_IGN) {
8006 /* oops... restore back to IGN, and record this fact */
8007 install_sighandler(sig, old_handler);
8009 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8011 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8016 /* Called a few times only (or even once if "sh -c") */
8017 static void install_special_sighandlers(void)
8021 /* Which signals are shell-special? */
8022 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8023 if (G_interactive_fd) {
8024 mask |= SPECIAL_INTERACTIVE_SIGS;
8025 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8026 mask |= SPECIAL_JOBSTOP_SIGS;
8028 /* Careful, do not re-install handlers we already installed */
8029 if (G.special_sig_mask != mask) {
8030 unsigned diff = mask & ~G.special_sig_mask;
8031 G.special_sig_mask = mask;
8032 install_sighandlers(diff);
8038 /* Set handlers to restore tty pgrp and exit */
8039 static void install_fatal_sighandlers(void)
8043 /* We will restore tty pgrp on these signals */
8045 + (1 << SIGILL ) * HUSH_DEBUG
8046 + (1 << SIGFPE ) * HUSH_DEBUG
8047 + (1 << SIGBUS ) * HUSH_DEBUG
8048 + (1 << SIGSEGV) * HUSH_DEBUG
8049 + (1 << SIGTRAP) * HUSH_DEBUG
8051 /* bash 3.2 seems to handle these just like 'fatal' ones */
8054 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8055 * if we aren't interactive... but in this case
8056 * we never want to restore pgrp on exit, and this fn is not called
8058 /*+ (1 << SIGHUP )*/
8059 /*+ (1 << SIGTERM)*/
8060 /*+ (1 << SIGINT )*/
8062 G_fatal_sig_mask = mask;
8064 install_sighandlers(mask);
8068 static int set_mode(int state, char mode, const char *o_opt)
8073 G.o_opt[OPT_O_NOEXEC] = state;
8076 IF_HUSH_MODE_X(G_x_mode = state;)
8080 /* "set -+o" without parameter.
8081 * in bash, set -o produces this output:
8085 * We always use the second form.
8087 const char *p = o_opt_strings;
8090 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8096 idx = index_in_strings(o_opt_strings, o_opt);
8098 G.o_opt[idx] = state;
8102 return EXIT_FAILURE;
8104 return EXIT_SUCCESS;
8107 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8108 int hush_main(int argc, char **argv)
8111 OPT_login = (1 << 0),
8115 unsigned builtin_argc;
8117 struct variable *cur_var;
8118 struct variable *shell_ver;
8121 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8122 G.last_exitcode = EXIT_SUCCESS;
8124 #if ENABLE_HUSH_FAST
8125 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8128 G.argv0_for_re_execing = argv[0];
8130 /* Deal with HUSH_VERSION */
8131 shell_ver = xzalloc(sizeof(*shell_ver));
8132 shell_ver->flg_export = 1;
8133 shell_ver->flg_read_only = 1;
8134 /* Code which handles ${var<op>...} needs writable values for all variables,
8135 * therefore we xstrdup: */
8136 shell_ver->varstr = xstrdup(hush_version_str);
8137 /* Create shell local variables from the values
8138 * currently living in the environment */
8139 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8140 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8141 G.top_var = shell_ver;
8142 cur_var = G.top_var;
8145 char *value = strchr(*e, '=');
8146 if (value) { /* paranoia */
8147 cur_var->next = xzalloc(sizeof(*cur_var));
8148 cur_var = cur_var->next;
8149 cur_var->varstr = *e;
8150 cur_var->max_len = strlen(*e);
8151 cur_var->flg_export = 1;
8155 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8156 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8157 putenv(shell_ver->varstr);
8160 set_pwd_var(/*exp:*/ 1);
8162 #if ENABLE_HUSH_BASH_COMPAT
8163 /* Set (but not export) HOSTNAME unless already set */
8164 if (!get_local_var_value("HOSTNAME")) {
8167 set_local_var_from_halves("HOSTNAME", uts.nodename);
8169 /* bash also exports SHLVL and _,
8170 * and sets (but doesn't export) the following variables:
8172 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8173 * BASH_VERSION='3.2.0(1)-release'
8175 * MACHTYPE=i386-pc-linux-gnu
8177 * PPID=<NNNNN> - we also do it elsewhere
8188 * PIPESTATUS=([0]="0")
8189 * HISTFILE=/<xxx>/.bash_history
8193 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8195 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8206 #if ENABLE_FEATURE_EDITING
8207 G.line_input_state = new_line_input_t(FOR_SHELL);
8210 /* Initialize some more globals to non-zero values */
8211 cmdedit_update_prompt();
8213 die_func = restore_ttypgrp_and__exit;
8215 /* Shell is non-interactive at first. We need to call
8216 * install_special_sighandlers() if we are going to execute "sh <script>",
8217 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8218 * If we later decide that we are interactive, we run install_special_sighandlers()
8219 * in order to intercept (more) signals.
8223 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8224 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8227 opt = getopt(argc, argv, "+c:xinsl"
8230 # if ENABLE_HUSH_FUNCTIONS
8240 * sh ... -c 'script'
8241 * sh ... -c 'script' ARG0 [ARG1...]
8242 * On NOMMU, if builtin_argc != 0,
8243 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8244 * "" needs to be replaced with NULL
8245 * and BARGV vector fed to builtin function.
8246 * Note: the form without ARG0 never happens:
8247 * sh ... -c 'builtin' BARGV... ""
8250 G.root_pid = getpid();
8251 G.root_ppid = getppid();
8253 G.global_argv = argv + optind;
8254 G.global_argc = argc - optind;
8256 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8257 const struct built_in_command *x;
8259 install_special_sighandlers();
8260 x = find_builtin(optarg);
8261 if (x) { /* paranoia */
8262 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8263 G.global_argv += builtin_argc;
8264 G.global_argv[-1] = NULL; /* replace "" */
8266 G.last_exitcode = x->b_function(argv + optind - 1);
8270 if (!G.global_argv[0]) {
8271 /* -c 'script' (no params): prevent empty $0 */
8272 G.global_argv--; /* points to argv[i] of 'script' */
8273 G.global_argv[0] = argv[0];
8275 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8276 install_special_sighandlers();
8277 parse_and_run_string(optarg);
8280 /* Well, we cannot just declare interactiveness,
8281 * we have to have some stuff (ctty, etc) */
8282 /* G_interactive_fd++; */
8285 /* "-s" means "read from stdin", but this is how we always
8286 * operate, so simply do nothing here. */
8292 case '<': /* "big heredoc" support */
8293 full_write1_str(optarg);
8296 unsigned long long empty_trap_mask;
8298 G.root_pid = bb_strtou(optarg, &optarg, 16);
8300 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8302 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8304 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8306 builtin_argc = bb_strtou(optarg, &optarg, 16);
8308 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8309 if (empty_trap_mask != 0) {
8311 install_special_sighandlers();
8312 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8313 for (sig = 1; sig < NSIG; sig++) {
8314 if (empty_trap_mask & (1LL << sig)) {
8315 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8316 install_sighandler(sig, SIG_IGN);
8320 # if ENABLE_HUSH_LOOPS
8322 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8328 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8330 # if ENABLE_HUSH_FUNCTIONS
8332 struct function *funcp = new_function(optarg);
8333 /* funcp->name is already set to optarg */
8334 /* funcp->body is set to NULL. It's a special case. */
8335 funcp->body_as_string = argv[optind];
8343 if (set_mode(1, opt, NULL) == 0) /* no error */
8347 fprintf(stderr, "Usage: sh [FILE]...\n"
8348 " or: sh -c command [args]...\n\n");
8354 } /* option parsing loop */
8356 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8357 G.global_argc = argc - (optind - 1);
8358 G.global_argv = argv + (optind - 1);
8359 G.global_argv[0] = argv[0];
8362 G.root_pid = getpid();
8363 G.root_ppid = getppid();
8366 /* If we are login shell... */
8367 if (flags & OPT_login) {
8369 debug_printf("sourcing /etc/profile\n");
8370 input = fopen_for_read("/etc/profile");
8371 if (input != NULL) {
8372 remember_FILE(input);
8373 install_special_sighandlers();
8374 parse_and_run_file(input);
8375 fclose_and_forget(input);
8377 /* bash: after sourcing /etc/profile,
8378 * tries to source (in the given order):
8379 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8380 * stopping on first found. --noprofile turns this off.
8381 * bash also sources ~/.bash_logout on exit.
8382 * If called as sh, skips .bash_XXX files.
8386 if (G.global_argv[1]) {
8389 * "bash <script>" (which is never interactive (unless -i?))
8390 * sources $BASH_ENV here (without scanning $PATH).
8391 * If called as sh, does the same but with $ENV.
8395 debug_printf("running script '%s'\n", G.global_argv[0]);
8396 input = xfopen_for_read(G.global_argv[0]);
8397 remember_FILE(input);
8398 install_special_sighandlers();
8399 parse_and_run_file(input);
8400 #if ENABLE_FEATURE_CLEAN_UP
8401 fclose_and_forget(input);
8406 /* Up to here, shell was non-interactive. Now it may become one.
8407 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8410 /* A shell is interactive if the '-i' flag was given,
8411 * or if all of the following conditions are met:
8413 * no arguments remaining or the -s flag given
8414 * standard input is a terminal
8415 * standard output is a terminal
8416 * Refer to Posix.2, the description of the 'sh' utility.
8419 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8420 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8421 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8422 if (G_saved_tty_pgrp < 0)
8423 G_saved_tty_pgrp = 0;
8425 /* try to dup stdin to high fd#, >= 255 */
8426 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8427 if (G_interactive_fd < 0) {
8428 /* try to dup to any fd */
8429 G_interactive_fd = dup(STDIN_FILENO);
8430 if (G_interactive_fd < 0) {
8432 G_interactive_fd = 0;
8433 G_saved_tty_pgrp = 0;
8436 // TODO: track & disallow any attempts of user
8437 // to (inadvertently) close/redirect G_interactive_fd
8439 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8440 if (G_interactive_fd) {
8441 close_on_exec_on(G_interactive_fd);
8443 if (G_saved_tty_pgrp) {
8444 /* If we were run as 'hush &', sleep until we are
8445 * in the foreground (tty pgrp == our pgrp).
8446 * If we get started under a job aware app (like bash),
8447 * make sure we are now in charge so we don't fight over
8448 * who gets the foreground */
8450 pid_t shell_pgrp = getpgrp();
8451 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8452 if (G_saved_tty_pgrp == shell_pgrp)
8454 /* send TTIN to ourself (should stop us) */
8455 kill(- shell_pgrp, SIGTTIN);
8459 /* Install more signal handlers */
8460 install_special_sighandlers();
8462 if (G_saved_tty_pgrp) {
8463 /* Set other signals to restore saved_tty_pgrp */
8464 install_fatal_sighandlers();
8465 /* Put ourselves in our own process group
8466 * (bash, too, does this only if ctty is available) */
8467 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8468 /* Grab control of the terminal */
8469 tcsetpgrp(G_interactive_fd, getpid());
8471 enable_restore_tty_pgrp_on_exit();
8473 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8475 const char *hp = get_local_var_value("HISTFILE");
8477 hp = get_local_var_value("HOME");
8479 hp = concat_path_file(hp, ".hush_history");
8484 G.line_input_state->hist_file = hp;
8485 //set_local_var(xasprintf("HISTFILE=%s", ...));
8487 # if ENABLE_FEATURE_SH_HISTFILESIZE
8488 hp = get_local_var_value("HISTFILESIZE");
8489 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8494 install_special_sighandlers();
8496 #elif ENABLE_HUSH_INTERACTIVE
8497 /* No job control compiled in, only prompt/line editing */
8498 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8499 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8500 if (G_interactive_fd < 0) {
8501 /* try to dup to any fd */
8502 G_interactive_fd = dup(STDIN_FILENO);
8503 if (G_interactive_fd < 0)
8505 G_interactive_fd = 0;
8508 if (G_interactive_fd) {
8509 close_on_exec_on(G_interactive_fd);
8511 install_special_sighandlers();
8513 /* We have interactiveness code disabled */
8514 install_special_sighandlers();
8517 * if interactive but not a login shell, sources ~/.bashrc
8518 * (--norc turns this off, --rcfile <file> overrides)
8521 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8522 /* note: ash and hush share this string */
8523 printf("\n\n%s %s\n"
8524 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8527 "hush - the humble shell"
8531 parse_and_run_file(stdin);
8534 hush_exit(G.last_exitcode);
8539 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8540 int msh_main(int argc, char **argv)
8542 bb_error_msg("msh is deprecated, please use hush instead");
8543 return hush_main(argc, argv);
8551 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8556 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8563 return applet_main_func(argc, argv - argc);
8566 static int FAST_FUNC builtin_test(char **argv)
8568 return run_applet_main(argv, test_main);
8571 static int FAST_FUNC builtin_echo(char **argv)
8573 return run_applet_main(argv, echo_main);
8577 static int FAST_FUNC builtin_printf(char **argv)
8579 return run_applet_main(argv, printf_main);
8583 static char **skip_dash_dash(char **argv)
8586 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8591 static int FAST_FUNC builtin_eval(char **argv)
8593 int rcode = EXIT_SUCCESS;
8595 argv = skip_dash_dash(argv);
8597 char *str = expand_strvec_to_string(argv);
8599 * eval "echo Hi; done" ("done" is syntax error):
8600 * "echo Hi" will not execute too.
8602 parse_and_run_string(str);
8604 rcode = G.last_exitcode;
8609 static int FAST_FUNC builtin_cd(char **argv)
8613 argv = skip_dash_dash(argv);
8615 if (newdir == NULL) {
8616 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8617 * bash says "bash: cd: HOME not set" and does nothing
8620 const char *home = get_local_var_value("HOME");
8621 newdir = home ? home : "/";
8623 if (chdir(newdir)) {
8624 /* Mimic bash message exactly */
8625 bb_perror_msg("cd: %s", newdir);
8626 return EXIT_FAILURE;
8628 /* Read current dir (get_cwd(1) is inside) and set PWD.
8629 * Note: do not enforce exporting. If PWD was unset or unexported,
8630 * set it again, but do not export. bash does the same.
8632 set_pwd_var(/*exp:*/ 0);
8633 return EXIT_SUCCESS;
8636 static int FAST_FUNC builtin_exec(char **argv)
8638 argv = skip_dash_dash(argv);
8639 if (argv[0] == NULL)
8640 return EXIT_SUCCESS; /* bash does this */
8642 /* Careful: we can end up here after [v]fork. Do not restore
8643 * tty pgrp then, only top-level shell process does that */
8644 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8645 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8647 /* TODO: if exec fails, bash does NOT exit! We do.
8648 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8649 * and tcsetpgrp, and this is inherently racy.
8651 execvp_or_die(argv);
8654 static int FAST_FUNC builtin_exit(char **argv)
8656 debug_printf_exec("%s()\n", __func__);
8658 /* interactive bash:
8659 * # trap "echo EEE" EXIT
8662 * There are stopped jobs.
8663 * (if there are _stopped_ jobs, running ones don't count)
8666 * EEE (then bash exits)
8668 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8671 /* note: EXIT trap is run by hush_exit */
8672 argv = skip_dash_dash(argv);
8673 if (argv[0] == NULL)
8674 hush_exit(G.last_exitcode);
8675 /* mimic bash: exit 123abc == exit 255 + error msg */
8676 xfunc_error_retval = 255;
8677 /* bash: exit -2 == exit 254, no error msg */
8678 hush_exit(xatoi(argv[0]) & 0xff);
8681 static void print_escaped(const char *s)
8686 const char *p = strchrnul(s, '\'');
8687 /* print 'xxxx', possibly just '' */
8688 printf("'%.*s'", (int)(p - s), s);
8693 /* s points to '; print "'''...'''" */
8695 do putchar('\''); while (*++s == '\'');
8700 #if !ENABLE_HUSH_LOCAL
8701 #define helper_export_local(argv, exp, lvl) \
8702 helper_export_local(argv, exp)
8704 static void helper_export_local(char **argv, int exp, int lvl)
8708 char *name_end = strchrnul(name, '=');
8710 /* So far we do not check that name is valid (TODO?) */
8712 if (*name_end == '\0') {
8713 struct variable *var, **vpp;
8715 vpp = get_ptr_to_local_var(name, name_end - name);
8716 var = vpp ? *vpp : NULL;
8718 if (exp == -1) { /* unexporting? */
8719 /* export -n NAME (without =VALUE) */
8721 var->flg_export = 0;
8722 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8724 } /* else: export -n NOT_EXISTING_VAR: no-op */
8727 if (exp == 1) { /* exporting? */
8728 /* export NAME (without =VALUE) */
8730 var->flg_export = 1;
8731 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8732 putenv(var->varstr);
8736 #if ENABLE_HUSH_LOCAL
8737 if (exp == 0 /* local? */
8738 && var && var->func_nest_level == lvl
8740 /* "local x=abc; ...; local x" - ignore second local decl */
8744 /* Exporting non-existing variable.
8745 * bash does not put it in environment,
8746 * but remembers that it is exported,
8747 * and does put it in env when it is set later.
8748 * We just set it to "" and export. */
8749 /* Or, it's "local NAME" (without =VALUE).
8750 * bash sets the value to "". */
8751 name = xasprintf("%s=", name);
8753 /* (Un)exporting/making local NAME=VALUE */
8754 name = xstrdup(name);
8756 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8760 static int FAST_FUNC builtin_export(char **argv)
8762 unsigned opt_unexport;
8764 #if ENABLE_HUSH_EXPORT_N
8765 /* "!": do not abort on errors */
8766 opt_unexport = getopt32(argv, "!n");
8767 if (opt_unexport == (uint32_t)-1)
8768 return EXIT_FAILURE;
8775 if (argv[0] == NULL) {
8782 /* ash emits: export VAR='VAL'
8783 * bash: declare -x VAR="VAL"
8784 * we follow ash example */
8785 const char *s = *e++;
8786 const char *p = strchr(s, '=');
8788 if (!p) /* wtf? take next variable */
8791 printf("export %.*s", (int)(p - s) + 1, s);
8792 print_escaped(p + 1);
8796 /*fflush_all(); - done after each builtin anyway */
8798 return EXIT_SUCCESS;
8801 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8803 return EXIT_SUCCESS;
8806 #if ENABLE_HUSH_LOCAL
8807 static int FAST_FUNC builtin_local(char **argv)
8809 if (G.func_nest_level == 0) {
8810 bb_error_msg("%s: not in a function", argv[0]);
8811 return EXIT_FAILURE; /* bash compat */
8813 helper_export_local(argv, 0, G.func_nest_level);
8814 return EXIT_SUCCESS;
8818 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8819 static int FAST_FUNC builtin_unset(char **argv)
8824 /* "!": do not abort on errors */
8825 /* "+": stop at 1st non-option */
8826 opts = getopt32(argv, "!+vf");
8827 if (opts == (unsigned)-1)
8828 return EXIT_FAILURE;
8830 bb_error_msg("unset: -v and -f are exclusive");
8831 return EXIT_FAILURE;
8837 if (!(opts & 2)) { /* not -f */
8838 if (unset_local_var(*argv)) {
8839 /* unset <nonexistent_var> doesn't fail.
8840 * Error is when one tries to unset RO var.
8841 * Message was printed by unset_local_var. */
8845 #if ENABLE_HUSH_FUNCTIONS
8855 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8856 * built-in 'set' handler
8858 * set [-abCefhmnuvx] [-o option] [argument...]
8859 * set [+abCefhmnuvx] [+o option] [argument...]
8860 * set -- [argument...]
8863 * Implementations shall support the options in both their hyphen and
8864 * plus-sign forms. These options can also be specified as options to sh.
8866 * Write out all variables and their values: set
8867 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8868 * Turn on the -x and -v options: set -xv
8869 * Unset all positional parameters: set --
8870 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8871 * Set the positional parameters to the expansion of x, even if x expands
8872 * with a leading '-' or '+': set -- $x
8874 * So far, we only support "set -- [argument...]" and some of the short names.
8876 static int FAST_FUNC builtin_set(char **argv)
8879 char **pp, **g_argv;
8880 char *arg = *++argv;
8884 for (e = G.top_var; e; e = e->next)
8886 return EXIT_SUCCESS;
8890 if (strcmp(arg, "--") == 0) {
8894 if (arg[0] != '+' && arg[0] != '-')
8896 for (n = 1; arg[n]; ++n) {
8897 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8899 if (arg[n] == 'o' && argv[1])
8902 } while ((arg = *++argv) != NULL);
8903 /* Now argv[0] is 1st argument */
8906 return EXIT_SUCCESS;
8909 /* NB: G.global_argv[0] ($0) is never freed/changed */
8910 g_argv = G.global_argv;
8911 if (G.global_args_malloced) {
8917 G.global_args_malloced = 1;
8918 pp = xzalloc(sizeof(pp[0]) * 2);
8919 pp[0] = g_argv[0]; /* retain $0 */
8922 /* This realloc's G.global_argv */
8923 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8930 return EXIT_SUCCESS;
8932 /* Nothing known, so abort */
8934 bb_error_msg("set: %s: invalid option", arg);
8935 return EXIT_FAILURE;
8938 static int FAST_FUNC builtin_shift(char **argv)
8941 argv = skip_dash_dash(argv);
8945 if (n >= 0 && n < G.global_argc) {
8946 if (G.global_args_malloced) {
8949 free(G.global_argv[m++]);
8952 memmove(&G.global_argv[1], &G.global_argv[n+1],
8953 G.global_argc * sizeof(G.global_argv[0]));
8954 return EXIT_SUCCESS;
8956 return EXIT_FAILURE;
8959 /* Interruptibility of read builtin in bash
8960 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8962 * Empty trap makes read ignore corresponding signal, for any signal.
8965 * - terminates non-interactive shell;
8966 * - interrupts read in interactive shell;
8967 * if it has non-empty trap:
8968 * - executes trap and returns to command prompt in interactive shell;
8969 * - executes trap and returns to read in non-interactive shell;
8971 * - is ignored (does not interrupt) read in interactive shell;
8972 * - terminates non-interactive shell;
8973 * if it has non-empty trap:
8974 * - executes trap and returns to read;
8976 * - terminates shell (regardless of interactivity);
8977 * if it has non-empty trap:
8978 * - executes trap and returns to read;
8980 static int FAST_FUNC builtin_read(char **argv)
8990 /* "!": do not abort on errors.
8991 * Option string must start with "sr" to match BUILTIN_READ_xxx
8993 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8994 if (read_flags == (uint32_t)-1)
8995 return EXIT_FAILURE;
8997 ifs = get_local_var_value("IFS"); /* can be NULL */
9000 r = shell_builtin_read(set_local_var_from_halves,
9010 if ((uintptr_t)r == 1 && errno == EINTR) {
9011 unsigned sig = check_and_run_traps();
9012 if (sig && sig != SIGINT)
9016 if ((uintptr_t)r > 1) {
9017 bb_error_msg("%s", r);
9018 r = (char*)(uintptr_t)1;
9021 return (uintptr_t)r;
9024 static int FAST_FUNC builtin_trap(char **argv)
9030 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
9035 /* No args: print all trapped */
9036 for (i = 0; i < NSIG; ++i) {
9039 print_escaped(G.traps[i]);
9040 /* note: bash adds "SIG", but only if invoked
9041 * as "bash". If called as "sh", or if set -o posix,
9042 * then it prints short signal names.
9043 * We are printing short names: */
9044 printf(" %s\n", get_signame(i));
9047 /*fflush_all(); - done after each builtin anyway */
9048 return EXIT_SUCCESS;
9052 /* If first arg is a number: reset all specified signals */
9053 sig = bb_strtou(*argv, NULL, 10);
9059 sighandler_t handler;
9061 sig = get_signum(*argv++);
9062 if (sig < 0 || sig >= NSIG) {
9064 /* Mimic bash message exactly */
9065 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
9070 G.traps[sig] = xstrdup(new_cmd);
9072 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9073 get_signame(sig), sig, G.traps[sig]);
9075 /* There is no signal for 0 (EXIT) */
9080 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9082 /* We are removing trap handler */
9083 handler = pick_sighandler(sig);
9084 install_sighandler(sig, handler);
9089 if (!argv[1]) { /* no second arg */
9090 bb_error_msg("trap: invalid arguments");
9091 return EXIT_FAILURE;
9094 /* First arg is "-": reset all specified to default */
9095 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9096 /* Everything else: set arg as signal handler
9097 * (includes "" case, which ignores signal) */
9098 if (argv[0][0] == '-') {
9099 if (argv[0][1] == '\0') { /* "-" */
9100 /* new_cmd remains NULL: "reset these sigs" */
9103 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9106 /* else: "-something", no special meaning */
9111 goto process_sig_list;
9114 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9115 static int FAST_FUNC builtin_type(char **argv)
9117 int ret = EXIT_SUCCESS;
9123 if (0) {} /* make conditional compile easier below */
9124 /*else if (find_alias(*argv))
9125 type = "an alias";*/
9126 #if ENABLE_HUSH_FUNCTIONS
9127 else if (find_function(*argv))
9128 type = "a function";
9130 else if (find_builtin(*argv))
9131 type = "a shell builtin";
9132 else if ((path = find_in_path(*argv)) != NULL)
9135 bb_error_msg("type: %s: not found", *argv);
9140 printf("%s is %s\n", *argv, type);
9148 /* built-in 'fg' and 'bg' handler */
9149 static int FAST_FUNC builtin_fg_bg(char **argv)
9154 if (!G_interactive_fd)
9155 return EXIT_FAILURE;
9157 /* If they gave us no args, assume they want the last backgrounded task */
9159 for (pi = G.job_list; pi; pi = pi->next) {
9160 if (pi->jobid == G.last_jobid) {
9164 bb_error_msg("%s: no current job", argv[0]);
9165 return EXIT_FAILURE;
9167 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
9168 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
9169 return EXIT_FAILURE;
9171 for (pi = G.job_list; pi; pi = pi->next) {
9172 if (pi->jobid == jobnum) {
9176 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
9177 return EXIT_FAILURE;
9179 /* TODO: bash prints a string representation
9180 * of job being foregrounded (like "sleep 1 | cat") */
9181 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
9182 /* Put the job into the foreground. */
9183 tcsetpgrp(G_interactive_fd, pi->pgrp);
9186 /* Restart the processes in the job */
9187 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9188 for (i = 0; i < pi->num_cmds; i++) {
9189 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
9191 pi->stopped_cmds = 0;
9193 i = kill(- pi->pgrp, SIGCONT);
9195 if (errno == ESRCH) {
9196 delete_finished_bg_job(pi);
9197 return EXIT_SUCCESS;
9199 bb_perror_msg("kill (SIGCONT)");
9202 if (argv[0][0] == 'f') {
9204 return checkjobs_and_fg_shell(pi);
9206 return EXIT_SUCCESS;
9210 #if ENABLE_HUSH_HELP
9211 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9213 const struct built_in_command *x;
9216 "Built-in commands:\n"
9217 "------------------\n");
9218 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9220 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9222 return EXIT_SUCCESS;
9226 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9227 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9229 show_history(G.line_input_state);
9230 return EXIT_SUCCESS;
9235 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9238 const char *status_string;
9240 for (job = G.job_list; job; job = job->next) {
9241 if (job->alive_cmds == job->stopped_cmds)
9242 status_string = "Stopped";
9244 status_string = "Running";
9246 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9248 return EXIT_SUCCESS;
9253 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
9258 # ifdef M_TRIM_THRESHOLD
9259 /* Optional. Reduces probability of false positives */
9262 /* Crude attempt to find where "free memory" starts,
9263 * sans fragmentation. */
9265 l = (unsigned long)p;
9268 if (l < (unsigned long)p) l = (unsigned long)p;
9271 if (!G.memleak_value)
9272 G.memleak_value = l;
9274 l -= G.memleak_value;
9281 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9286 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9289 return EXIT_SUCCESS;
9292 static int FAST_FUNC builtin_source(char **argv)
9294 char *arg_path, *filename;
9297 #if ENABLE_HUSH_FUNCTIONS
9301 argv = skip_dash_dash(argv);
9304 /* bash says: "bash: .: filename argument required" */
9305 return 2; /* bash compat */
9308 if (!strchr(filename, '/')) {
9309 arg_path = find_in_path(filename);
9311 filename = arg_path;
9313 input = remember_FILE(fopen_or_warn(filename, "r"));
9316 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9317 /* POSIX: non-interactive shell should abort here,
9318 * not merely fail. So far no one complained :)
9320 return EXIT_FAILURE;
9323 #if ENABLE_HUSH_FUNCTIONS
9324 sv_flg = G_flag_return_in_progress;
9325 /* "we are inside sourced file, ok to use return" */
9326 G_flag_return_in_progress = -1;
9329 save_and_replace_G_args(&sv, argv);
9331 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9332 G.last_exitcode = 0;
9333 parse_and_run_file(input);
9334 fclose_and_forget(input);
9337 restore_G_args(&sv, argv);
9338 #if ENABLE_HUSH_FUNCTIONS
9339 G_flag_return_in_progress = sv_flg;
9342 return G.last_exitcode;
9345 static int FAST_FUNC builtin_umask(char **argv)
9352 argv = skip_dash_dash(argv);
9354 mode_t old_mask = mask;
9356 /* numeric umasks are taken as-is */
9357 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9358 if (!isdigit(argv[0][0]))
9360 mask = bb_parse_mode(argv[0], mask);
9361 if (!isdigit(argv[0][0]))
9363 if ((unsigned)mask > 0777) {
9366 * bash: umask: 'q': invalid symbolic mode operator
9367 * bash: umask: 999: octal number out of range
9369 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9374 printf("%04o\n", (unsigned) mask);
9375 /* fall through and restore mask which we set to 0 */
9379 return !rc; /* rc != 0 - success */
9382 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9383 static int FAST_FUNC builtin_wait(char **argv)
9385 int ret = EXIT_SUCCESS;
9388 argv = skip_dash_dash(argv);
9389 if (argv[0] == NULL) {
9390 /* Don't care about wait results */
9391 /* Note 1: must wait until there are no more children */
9392 /* Note 2: must be interruptible */
9394 * $ sleep 3 & sleep 6 & wait
9399 * $ sleep 3 & sleep 6 & wait
9403 * ^C <-- after ~4 sec from keyboard
9408 sigset_t oldset, allsigs;
9410 /* waitpid is not interruptible by SA_RESTARTed
9411 * signals which we use. Thus, this ugly dance:
9414 /* Make sure possible SIGCHLD is stored in kernel's
9415 * pending signal mask before we call waitpid.
9416 * Or else we may race with SIGCHLD, lose it,
9417 * and get stuck in sigwaitinfo...
9419 sigfillset(&allsigs);
9420 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9422 if (!sigisemptyset(&G.pending_set)) {
9423 /* Crap! we raced with some signal! */
9428 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9429 if (errno == ECHILD) {
9430 sigprocmask(SIG_SETMASK, &oldset, NULL);
9434 /* Wait for SIGCHLD or any other signal */
9435 //sig = sigwaitinfo(&allsigs, NULL);
9436 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9437 /* Note: sigsuspend invokes signal handler */
9438 sigsuspend(&oldset);
9440 sigprocmask(SIG_SETMASK, &oldset, NULL);
9442 /* So, did we get a signal? */
9444 // raise(sig); /* run handler */
9445 sig = check_and_run_traps();
9446 if (sig /*&& sig != SIGCHLD - always true */) {
9451 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9456 /* This is probably buggy wrt interruptible-ness */
9458 pid_t pid = bb_strtou(*argv, NULL, 10);
9460 /* mimic bash message */
9461 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9462 return EXIT_FAILURE;
9464 if (waitpid(pid, &status, 0) == pid) {
9465 ret = WEXITSTATUS(status);
9466 if (WIFSIGNALED(status))
9467 ret = 128 + WTERMSIG(status);
9469 bb_perror_msg("wait %s", *argv);
9478 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9479 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9482 def = bb_strtou(argv[1], NULL, 10);
9483 if (errno || def < def_min || argv[2]) {
9484 bb_error_msg("%s: bad arguments", argv[0]);
9492 #if ENABLE_HUSH_LOOPS
9493 static int FAST_FUNC builtin_break(char **argv)
9496 if (G.depth_of_loop == 0) {
9497 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9498 /* if we came from builtin_continue(), need to undo "= 1" */
9499 G.flag_break_continue = 0;
9500 return EXIT_SUCCESS; /* bash compat */
9502 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9504 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9505 if (depth == UINT_MAX)
9506 G.flag_break_continue = BC_BREAK;
9507 if (G.depth_of_loop < depth)
9508 G.depth_break_continue = G.depth_of_loop;
9510 return EXIT_SUCCESS;
9513 static int FAST_FUNC builtin_continue(char **argv)
9515 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9516 return builtin_break(argv);
9520 #if ENABLE_HUSH_FUNCTIONS
9521 static int FAST_FUNC builtin_return(char **argv)
9525 if (G_flag_return_in_progress != -1) {
9526 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9527 return EXIT_FAILURE; /* bash compat */
9530 G_flag_return_in_progress = 1;
9533 * out of range: wraps around at 256, does not error out
9534 * non-numeric param:
9535 * f() { false; return qwe; }; f; echo $?
9536 * bash: return: qwe: numeric argument required <== we do this
9537 * 255 <== we also do this
9539 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);