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;
473 int (*peek2) (struct in_str *) FAST_FUNC;
475 #define i_getch(input) ((input)->get(input))
476 #define i_peek(input) ((input)->peek(input))
477 #define i_peek2(input) ((input)->peek2(input))
479 /* The descrip member of this structure is only used to make
480 * debugging output pretty */
481 static const struct {
483 signed char default_fd;
486 { O_RDONLY, 0, "<" },
487 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
488 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
489 { O_CREAT|O_RDWR, 1, "<>" },
490 { O_RDONLY, 0, "<<" },
491 /* Should not be needed. Bogus default_fd helps in debugging */
492 /* { O_RDONLY, 77, "<<" }, */
495 struct redir_struct {
496 struct redir_struct *next;
497 char *rd_filename; /* filename */
498 int rd_fd; /* fd to redirect */
499 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
501 smallint rd_type; /* (enum redir_type) */
502 /* note: for heredocs, rd_filename contains heredoc delimiter,
503 * and subsequently heredoc itself; and rd_dup is a bitmask:
504 * bit 0: do we need to trim leading tabs?
505 * bit 1: is heredoc quoted (<<'delim' syntax) ?
508 typedef enum redir_type {
510 REDIRECT_OVERWRITE = 1,
513 REDIRECT_HEREDOC = 4,
514 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
517 REDIRFD_SYNTAX_ERR = -2,
518 REDIRFD_TO_FILE = -1,
519 /* otherwise, rd_fd is redirected to rd_dup */
521 HEREDOC_SKIPTABS = 1,
527 pid_t pid; /* 0 if exited */
528 int assignment_cnt; /* how many argv[i] are assignments? */
529 smallint cmd_type; /* CMD_xxx */
531 #define CMD_SUBSHELL 1
532 #if ENABLE_HUSH_BASH_COMPAT
533 /* used for "[[ EXPR ]]" */
534 # define CMD_SINGLEWORD_NOGLOB 2
536 #if ENABLE_HUSH_FUNCTIONS
537 # define CMD_FUNCDEF 3
540 smalluint cmd_exitcode;
541 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
544 char *group_as_string;
546 #if ENABLE_HUSH_FUNCTIONS
547 struct function *child_func;
548 /* This field is used to prevent a bug here:
549 * while...do f1() {a;}; f1; f1() {b;}; f1; done
550 * When we execute "f1() {a;}" cmd, we create new function and clear
551 * cmd->group, cmd->group_as_string, cmd->argv[0].
552 * When we execute "f1() {b;}", we notice that f1 exists,
553 * and that its "parent cmd" struct is still "alive",
554 * we put those fields back into cmd->xxx
555 * (struct function has ->parent_cmd ptr to facilitate that).
556 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
557 * Without this trick, loop would execute a;b;b;b;...
558 * instead of correct sequence a;b;a;b;...
559 * When command is freed, it severs the link
560 * (sets ->child_func->parent_cmd to NULL).
563 char **argv; /* command name and arguments */
564 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
565 * and on execution these are substituted with their values.
566 * Substitution can make _several_ words out of one argv[n]!
567 * Example: argv[0]=='.^C*^C.' here: echo .$*.
568 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
570 struct redir_struct *redirects; /* I/O redirections */
572 /* Is there anything in this command at all? */
573 #define IS_NULL_CMD(cmd) \
574 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
578 int num_cmds; /* total number of commands in pipe */
579 int alive_cmds; /* number of commands running (not exited) */
580 int stopped_cmds; /* number of commands alive, but stopped */
582 int jobid; /* job number */
583 pid_t pgrp; /* process group ID for the job */
584 char *cmdtext; /* name of job */
586 struct command *cmds; /* array of commands in pipe */
587 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
588 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
589 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
591 typedef enum pipe_style {
597 /* Is there anything in this pipe at all? */
598 #define IS_NULL_PIPE(pi) \
599 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
601 /* This holds pointers to the various results of parsing */
602 struct parse_context {
603 /* linked list of pipes */
604 struct pipe *list_head;
605 /* last pipe (being constructed right now) */
607 /* last command in pipe (being constructed right now) */
608 struct command *command;
609 /* last redirect in command->redirects list */
610 struct redir_struct *pending_redirect;
616 smallint ctx_inverted; /* "! cmd | cmd" */
618 smallint ctx_dsemicolon; /* ";;" seen */
620 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
622 /* group we are enclosed in:
623 * example: "if pipe1; pipe2; then pipe3; fi"
624 * when we see "if" or "then", we malloc and copy current context,
625 * and make ->stack point to it. then we parse pipeN.
626 * when closing "then" / fi" / whatever is found,
627 * we move list_head into ->stack->command->group,
628 * copy ->stack into current context, and delete ->stack.
629 * (parsing of { list } and ( list ) doesn't use this method)
631 struct parse_context *stack;
635 /* On program start, environ points to initial environment.
636 * putenv adds new pointers into it, unsetenv removes them.
637 * Neither of these (de)allocates the strings.
638 * setenv allocates new strings in malloc space and does putenv,
639 * and thus setenv is unusable (leaky) for shell's purposes */
640 #define setenv(...) setenv_is_leaky_dont_use()
642 struct variable *next;
643 char *varstr; /* points to "name=" portion */
644 #if ENABLE_HUSH_LOCAL
645 unsigned func_nest_level;
647 int max_len; /* if > 0, name is part of initial env; else name is malloced */
648 smallint flg_export; /* putenv should be done on this var */
649 smallint flg_read_only;
657 #if ENABLE_HUSH_FUNCTIONS
659 struct function *next;
661 struct command *parent_cmd;
664 char *body_as_string;
670 /* set -/+o OPT support. (TODO: make it optional)
671 * bash supports the following opts:
682 * interactive-comments on
700 static const char o_opt_strings[] ALIGN1 =
703 #if ENABLE_HUSH_MODE_X
710 #if ENABLE_HUSH_MODE_X
718 struct FILE_list *next;
724 /* "Globals" within this file */
725 /* Sorted roughly by size (smaller offsets == smaller code) */
727 /* interactive_fd != 0 means we are an interactive shell.
728 * If we are, then saved_tty_pgrp can also be != 0, meaning
729 * that controlling tty is available. With saved_tty_pgrp == 0,
730 * job control still works, but terminal signals
731 * (^C, ^Z, ^Y, ^\) won't work at all, and background
732 * process groups can only be created with "cmd &".
733 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
734 * to give tty to the foreground process group,
735 * and will take it back when the group is stopped (^Z)
738 #if ENABLE_HUSH_INTERACTIVE
739 /* 'interactive_fd' is a fd# open to ctty, if we have one
740 * _AND_ if we decided to act interactively */
744 # define G_interactive_fd (G.interactive_fd)
746 # define G_interactive_fd 0
748 #if ENABLE_FEATURE_EDITING
749 line_input_t *line_input_state;
754 #if ENABLE_HUSH_RANDOM_SUPPORT
760 pid_t saved_tty_pgrp;
761 struct pipe *job_list;
762 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
764 # define G_saved_tty_pgrp 0
766 char o_opt[NUM_OPT_O];
767 #if ENABLE_HUSH_MODE_X
768 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
772 smallint flag_SIGINT;
773 #if ENABLE_HUSH_LOOPS
774 smallint flag_break_continue;
776 #if ENABLE_HUSH_FUNCTIONS
777 /* 0: outside of a function (or sourced file)
778 * -1: inside of a function, ok to use return builtin
779 * 1: return is invoked, skip all till end of func
781 smallint flag_return_in_progress;
783 smallint exiting; /* used to prevent EXIT trap recursion */
784 /* These four support $?, $#, and $1 */
785 smalluint last_exitcode;
786 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
787 smalluint global_args_malloced;
788 /* how many non-NULL argv's we have. NB: $# + 1 */
792 char *argv0_for_re_execing;
794 #if ENABLE_HUSH_LOOPS
795 unsigned depth_break_continue;
796 unsigned depth_of_loop;
800 struct variable *top_var;
801 char **expanded_assignments;
802 #if ENABLE_HUSH_FUNCTIONS
803 struct function *top_func;
804 # if ENABLE_HUSH_LOCAL
805 struct variable **shadowed_vars_pp;
806 unsigned func_nest_level;
809 /* Signal and trap handling */
811 unsigned count_SIGCHLD;
812 unsigned handled_SIGCHLD;
813 smallint we_have_children;
815 struct FILE_list *FILE_list;
816 /* Which signals have non-DFL handler (even with no traps set)?
817 * Set at the start to:
818 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
819 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
820 * The rest is cleared right before execv syscalls.
821 * Other than these two times, never modified.
823 unsigned special_sig_mask;
825 unsigned fatal_sig_mask;
826 # define G_fatal_sig_mask G.fatal_sig_mask
828 # define G_fatal_sig_mask 0
830 char **traps; /* char *traps[NSIG] */
831 sigset_t pending_set;
833 unsigned long memleak_value;
837 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
839 #define G (*ptr_to_globals)
840 /* Not #defining name to G.name - this quickly gets unwieldy
841 * (too many defines). Also, I actually prefer to see when a variable
842 * is global, thus "G." prefix is a useful hint */
843 #define INIT_G() do { \
844 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
845 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
846 sigfillset(&G.sa.sa_mask); \
847 G.sa.sa_flags = SA_RESTART; \
851 /* Function prototypes for builtins */
852 static int builtin_cd(char **argv) FAST_FUNC;
853 static int builtin_echo(char **argv) FAST_FUNC;
854 static int builtin_eval(char **argv) FAST_FUNC;
855 static int builtin_exec(char **argv) FAST_FUNC;
856 static int builtin_exit(char **argv) FAST_FUNC;
857 static int builtin_export(char **argv) FAST_FUNC;
859 static int builtin_fg_bg(char **argv) FAST_FUNC;
860 static int builtin_jobs(char **argv) FAST_FUNC;
863 static int builtin_help(char **argv) FAST_FUNC;
865 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
866 static int builtin_history(char **argv) FAST_FUNC;
868 #if ENABLE_HUSH_LOCAL
869 static int builtin_local(char **argv) FAST_FUNC;
872 static int builtin_memleak(char **argv) FAST_FUNC;
875 static int builtin_printf(char **argv) FAST_FUNC;
877 static int builtin_pwd(char **argv) FAST_FUNC;
878 static int builtin_read(char **argv) FAST_FUNC;
879 static int builtin_set(char **argv) FAST_FUNC;
880 static int builtin_shift(char **argv) FAST_FUNC;
881 static int builtin_source(char **argv) FAST_FUNC;
882 static int builtin_test(char **argv) FAST_FUNC;
883 static int builtin_trap(char **argv) FAST_FUNC;
884 static int builtin_type(char **argv) FAST_FUNC;
885 static int builtin_true(char **argv) FAST_FUNC;
886 static int builtin_umask(char **argv) FAST_FUNC;
887 static int builtin_unset(char **argv) FAST_FUNC;
888 static int builtin_wait(char **argv) FAST_FUNC;
889 #if ENABLE_HUSH_LOOPS
890 static int builtin_break(char **argv) FAST_FUNC;
891 static int builtin_continue(char **argv) FAST_FUNC;
893 #if ENABLE_HUSH_FUNCTIONS
894 static int builtin_return(char **argv) FAST_FUNC;
897 /* Table of built-in functions. They can be forked or not, depending on
898 * context: within pipes, they fork. As simple commands, they do not.
899 * When used in non-forking context, they can change global variables
900 * in the parent shell process. If forked, of course they cannot.
901 * For example, 'unset foo | whatever' will parse and run, but foo will
902 * still be set at the end. */
903 struct built_in_command {
905 int (*b_function)(char **argv) FAST_FUNC;
908 # define BLTIN(cmd, func, help) { cmd, func, help }
910 # define BLTIN(cmd, func, help) { cmd, func }
914 static const struct built_in_command bltins1[] = {
915 BLTIN("." , builtin_source , "Run commands in a file"),
916 BLTIN(":" , builtin_true , NULL),
918 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
920 #if ENABLE_HUSH_LOOPS
921 BLTIN("break" , builtin_break , "Exit from a loop"),
923 BLTIN("cd" , builtin_cd , "Change directory"),
924 #if ENABLE_HUSH_LOOPS
925 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
927 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
928 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
929 BLTIN("exit" , builtin_exit , "Exit"),
930 BLTIN("export" , builtin_export , "Set environment variables"),
932 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
935 BLTIN("help" , builtin_help , NULL),
937 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
938 BLTIN("history" , builtin_history , "Show command history"),
941 BLTIN("jobs" , builtin_jobs , "List jobs"),
943 #if ENABLE_HUSH_LOCAL
944 BLTIN("local" , builtin_local , "Set local variables"),
947 BLTIN("memleak" , builtin_memleak , NULL),
949 BLTIN("read" , builtin_read , "Input into variable"),
950 #if ENABLE_HUSH_FUNCTIONS
951 BLTIN("return" , builtin_return , "Return from a function"),
953 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
954 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
955 #if ENABLE_HUSH_BASH_COMPAT
956 BLTIN("source" , builtin_source , "Run commands in a file"),
958 BLTIN("trap" , builtin_trap , "Trap signals"),
959 BLTIN("true" , builtin_true , NULL),
960 BLTIN("type" , builtin_type , "Show command type"),
961 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
962 BLTIN("umask" , builtin_umask , "Set file creation mask"),
963 BLTIN("unset" , builtin_unset , "Unset variables"),
964 BLTIN("wait" , builtin_wait , "Wait for process"),
966 /* For now, echo and test are unconditionally enabled.
967 * Maybe make it configurable? */
968 static const struct built_in_command bltins2[] = {
969 BLTIN("[" , builtin_test , NULL),
970 BLTIN("echo" , builtin_echo , NULL),
972 BLTIN("printf" , builtin_printf , NULL),
974 BLTIN("pwd" , builtin_pwd , NULL),
975 BLTIN("test" , builtin_test , NULL),
982 /* prevent disasters with G.debug_indent < 0 */
983 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
984 # define debug_enter() (G.debug_indent++)
985 # define debug_leave() (G.debug_indent--)
987 # define indent() ((void)0)
988 # define debug_enter() ((void)0)
989 # define debug_leave() ((void)0)
993 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
996 #ifndef debug_printf_parse
997 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1000 #ifndef debug_printf_exec
1001 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1004 #ifndef debug_printf_env
1005 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1008 #ifndef debug_printf_jobs
1009 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1010 # define DEBUG_JOBS 1
1012 # define DEBUG_JOBS 0
1015 #ifndef debug_printf_expand
1016 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1017 # define DEBUG_EXPAND 1
1019 # define DEBUG_EXPAND 0
1022 #ifndef debug_printf_varexp
1023 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1026 #ifndef debug_printf_glob
1027 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1028 # define DEBUG_GLOB 1
1030 # define DEBUG_GLOB 0
1033 #ifndef debug_printf_list
1034 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1037 #ifndef debug_printf_subst
1038 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1041 #ifndef debug_printf_clean
1042 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1043 # define DEBUG_CLEAN 1
1045 # define DEBUG_CLEAN 0
1049 static void debug_print_strings(const char *prefix, char **vv)
1052 fdprintf(2, "%s:\n", prefix);
1054 fdprintf(2, " '%s'\n", *vv++);
1057 # define debug_print_strings(prefix, vv) ((void)0)
1061 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1064 static void *xxmalloc(int lineno, size_t size)
1066 void *ptr = xmalloc((size + 0xff) & ~0xff);
1067 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1070 static void *xxrealloc(int lineno, void *ptr, size_t size)
1072 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1073 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1076 static char *xxstrdup(int lineno, const char *str)
1078 char *ptr = xstrdup(str);
1079 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1082 static void xxfree(void *ptr)
1084 fdprintf(2, "free %p\n", ptr);
1087 # define xmalloc(s) xxmalloc(__LINE__, s)
1088 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1089 # define xstrdup(s) xxstrdup(__LINE__, s)
1090 # define free(p) xxfree(p)
1094 /* Syntax and runtime errors. They always abort scripts.
1095 * In interactive use they usually discard unparsed and/or unexecuted commands
1096 * and return to the prompt.
1097 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1100 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1101 # define syntax_error(lineno, msg) syntax_error(msg)
1102 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1103 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1104 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1105 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1108 static void die_if_script(unsigned lineno, const char *fmt, ...)
1113 bb_error_msg("hush.c:%u", lineno);
1116 bb_verror_msg(fmt, p, NULL);
1118 if (!G_interactive_fd)
1122 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1125 bb_error_msg("syntax error: %s", msg);
1127 bb_error_msg("syntax error");
1130 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1132 bb_error_msg("syntax error at '%s'", msg);
1135 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1137 bb_error_msg("syntax error: unterminated %s", s);
1140 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1142 char msg[2] = { ch, '\0' };
1143 syntax_error_unterm_str(lineno, msg);
1146 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1151 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1155 # undef die_if_script
1156 # undef syntax_error
1157 # undef syntax_error_at
1158 # undef syntax_error_unterm_ch
1159 # undef syntax_error_unterm_str
1160 # undef syntax_error_unexpected_ch
1162 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1163 # define syntax_error(msg) syntax_error(__LINE__, msg)
1164 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1165 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1166 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1167 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1171 #if ENABLE_HUSH_INTERACTIVE
1172 static void cmdedit_update_prompt(void);
1174 # define cmdedit_update_prompt() ((void)0)
1178 /* Utility functions
1180 /* Replace each \x with x in place, return ptr past NUL. */
1181 static char *unbackslash(char *src)
1183 char *dst = src = strchrnul(src, '\\');
1187 if ((*dst++ = *src++) == '\0')
1193 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1214 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1215 v[count1 + count2] = NULL;
1218 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1222 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1224 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1225 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1228 #define add_strings_to_strings(strings, add, need_to_dup) \
1229 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1232 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1233 static char **add_string_to_strings(char **strings, char *add)
1238 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1241 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1243 char **ptr = add_string_to_strings(strings, add);
1244 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1247 #define add_string_to_strings(strings, add) \
1248 xx_add_string_to_strings(__LINE__, strings, add)
1251 static void free_strings(char **strings)
1266 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1268 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1269 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1271 /* fd was not open? */
1281 /* Manipulating the list of open FILEs */
1282 static FILE *remember_FILE(FILE *fp)
1285 struct FILE_list *n = xmalloc(sizeof(*n));
1286 n->next = G.FILE_list;
1290 close_on_exec_on(n->fd);
1294 static void fclose_and_forget(FILE *fp)
1296 struct FILE_list **pp = &G.FILE_list;
1298 struct FILE_list *cur = *pp;
1299 if (cur->fp == fp) {
1308 static int save_FILEs_on_redirect(int fd)
1310 struct FILE_list *fl = G.FILE_list;
1313 /* We use it only on script files, they are all CLOEXEC */
1314 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1321 static void restore_redirected_FILEs(void)
1323 struct FILE_list *fl = G.FILE_list;
1325 int should_be = fileno(fl->fp);
1326 if (fl->fd != should_be) {
1327 xmove_fd(fl->fd, should_be);
1333 #if ENABLE_FEATURE_SH_STANDALONE
1334 static void close_all_FILE_list(void)
1336 struct FILE_list *fl = G.FILE_list;
1338 /* fclose would also free FILE object.
1339 * It is disastrous if we share memory with a vforked parent.
1340 * I'm not sure we never come here after vfork.
1341 * Therefore just close fd, nothing more.
1343 /*fclose(fl->fp); - unsafe */
1351 /* Helpers for setting new $n and restoring them back
1353 typedef struct save_arg_t {
1357 smallint sv_g_malloced;
1360 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1364 sv->sv_argv0 = argv[0];
1365 sv->sv_g_argv = G.global_argv;
1366 sv->sv_g_argc = G.global_argc;
1367 sv->sv_g_malloced = G.global_args_malloced;
1369 argv[0] = G.global_argv[0]; /* retain $0 */
1370 G.global_argv = argv;
1371 G.global_args_malloced = 0;
1379 static void restore_G_args(save_arg_t *sv, char **argv)
1383 if (G.global_args_malloced) {
1384 /* someone ran "set -- arg1 arg2 ...", undo */
1386 while (*++pp) /* note: does not free $0 */
1388 free(G.global_argv);
1390 argv[0] = sv->sv_argv0;
1391 G.global_argv = sv->sv_g_argv;
1392 G.global_argc = sv->sv_g_argc;
1393 G.global_args_malloced = sv->sv_g_malloced;
1397 /* Basic theory of signal handling in shell
1398 * ========================================
1399 * This does not describe what hush does, rather, it is current understanding
1400 * what it _should_ do. If it doesn't, it's a bug.
1401 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1403 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1404 * is finished or backgrounded. It is the same in interactive and
1405 * non-interactive shells, and is the same regardless of whether
1406 * a user trap handler is installed or a shell special one is in effect.
1407 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1408 * backgrounds (i.e. stops) or kills all members of currently running
1411 * Wait builtin is interruptible by signals for which user trap is set
1412 * or by SIGINT in interactive shell.
1414 * Trap handlers will execute even within trap handlers. (right?)
1416 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1417 * except for handlers set to '' (empty string).
1419 * If job control is off, backgrounded commands ("cmd &")
1420 * have SIGINT, SIGQUIT set to SIG_IGN.
1422 * Commands which are run in command substitution ("`cmd`")
1423 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1425 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1426 * by the shell from its parent.
1428 * Signals which differ from SIG_DFL action
1429 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1432 * SIGTERM (interactive): ignore
1433 * SIGHUP (interactive):
1434 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1435 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1436 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1437 * that all pipe members are stopped. Try this in bash:
1438 * while :; do :; done - ^Z does not background it
1439 * (while :; do :; done) - ^Z backgrounds it
1440 * SIGINT (interactive): wait for last pipe, ignore the rest
1441 * of the command line, show prompt. NB: ^C does not send SIGINT
1442 * to interactive shell while shell is waiting for a pipe,
1443 * since shell is bg'ed (is not in foreground process group).
1444 * Example 1: this waits 5 sec, but does not execute ls:
1445 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1446 * Example 2: this does not wait and does not execute ls:
1447 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1448 * Example 3: this does not wait 5 sec, but executes ls:
1449 * "sleep 5; ls -l" + press ^C
1450 * Example 4: this does not wait and does not execute ls:
1451 * "sleep 5 & wait; ls -l" + press ^C
1453 * (What happens to signals which are IGN on shell start?)
1454 * (What happens with signal mask on shell start?)
1456 * Old implementation
1457 * ==================
1458 * We use in-kernel pending signal mask to determine which signals were sent.
1459 * We block all signals which we don't want to take action immediately,
1460 * i.e. we block all signals which need to have special handling as described
1461 * above, and all signals which have traps set.
1462 * After each pipe execution, we extract any pending signals via sigtimedwait()
1465 * unsigned special_sig_mask: a mask of such "special" signals
1466 * sigset_t blocked_set: current blocked signal set
1469 * clear bit in blocked_set unless it is also in special_sig_mask
1470 * "trap 'cmd' SIGxxx":
1471 * set bit in blocked_set (even if 'cmd' is '')
1472 * after [v]fork, if we plan to be a shell:
1473 * unblock signals with special interactive handling
1474 * (child shell is not interactive),
1475 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1476 * after [v]fork, if we plan to exec:
1477 * POSIX says fork clears pending signal mask in child - no need to clear it.
1478 * Restore blocked signal set to one inherited by shell just prior to exec.
1480 * Note: as a result, we do not use signal handlers much. The only uses
1481 * are to count SIGCHLDs
1482 * and to restore tty pgrp on signal-induced exit.
1485 * Standard says "When a subshell is entered, traps that are not being ignored
1486 * are set to the default actions". bash interprets it so that traps which
1487 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1489 * Problem: the above approach makes it unwieldy to catch signals while
1490 * we are in read builtin, or while we read commands from stdin:
1491 * masked signals are not visible!
1493 * New implementation
1494 * ==================
1495 * We record each signal we are interested in by installing signal handler
1496 * for them - a bit like emulating kernel pending signal mask in userspace.
1497 * We are interested in: signals which need to have special handling
1498 * as described above, and all signals which have traps set.
1499 * Signals are recorded in pending_set.
1500 * After each pipe execution, we extract any pending signals
1503 * unsigned special_sig_mask: a mask of shell-special signals.
1504 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1505 * char *traps[sig] if trap for sig is set (even if it's '').
1506 * sigset_t pending_set: set of sigs we received.
1509 * if sig is in special_sig_mask, set handler back to:
1510 * record_pending_signo, or to IGN if it's a tty stop signal
1511 * if sig is in fatal_sig_mask, set handler back to sigexit.
1512 * else: set handler back to SIG_DFL
1513 * "trap 'cmd' SIGxxx":
1514 * set handler to record_pending_signo.
1516 * set handler to SIG_IGN.
1517 * after [v]fork, if we plan to be a shell:
1518 * set signals with special interactive handling to SIG_DFL
1519 * (because child shell is not interactive),
1520 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1521 * after [v]fork, if we plan to exec:
1522 * POSIX says fork clears pending signal mask in child - no need to clear it.
1524 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1525 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1528 * Standard says "When a subshell is entered, traps that are not being ignored
1529 * are set to the default actions". bash interprets it so that traps which
1530 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1533 SPECIAL_INTERACTIVE_SIGS = 0
1538 SPECIAL_JOBSTOP_SIGS = 0
1547 static void record_pending_signo(int sig)
1549 sigaddset(&G.pending_set, sig);
1550 #if ENABLE_HUSH_FAST
1551 if (sig == SIGCHLD) {
1553 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1558 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1560 struct sigaction old_sa;
1562 /* We could use signal() to install handlers... almost:
1563 * except that we need to mask ALL signals while handlers run.
1564 * I saw signal nesting in strace, race window isn't small.
1565 * SA_RESTART is also needed, but in Linux, signal()
1566 * sets SA_RESTART too.
1568 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1569 /* sigfillset(&G.sa.sa_mask); - already done */
1570 /* G.sa.sa_flags = SA_RESTART; - already done */
1571 G.sa.sa_handler = handler;
1572 sigaction(sig, &G.sa, &old_sa);
1573 return old_sa.sa_handler;
1576 static void hush_exit(int exitcode) NORETURN;
1577 static void fflush_and__exit(void) NORETURN;
1578 static void restore_ttypgrp_and__exit(void) NORETURN;
1580 static void restore_ttypgrp_and__exit(void)
1582 /* xfunc has failed! die die die */
1583 /* no EXIT traps, this is an escape hatch! */
1585 hush_exit(xfunc_error_retval);
1588 /* Needed only on some libc:
1589 * It was observed that on exit(), fgetc'ed buffered data
1590 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1591 * With the net effect that even after fork(), not vfork(),
1592 * exit() in NOEXECed applet in "sh SCRIPT":
1593 * noexec_applet_here
1594 * echo END_OF_SCRIPT
1595 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1596 * This makes "echo END_OF_SCRIPT" executed twice.
1597 * Similar problems can be seen with die_if_script() -> xfunc_die()
1598 * and in `cmd` handling.
1599 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1601 static void fflush_and__exit(void)
1604 _exit(xfunc_error_retval);
1609 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1610 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1611 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1612 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1614 /* Restores tty foreground process group, and exits.
1615 * May be called as signal handler for fatal signal
1616 * (will resend signal to itself, producing correct exit state)
1617 * or called directly with -EXITCODE.
1618 * We also call it if xfunc is exiting.
1620 static void sigexit(int sig) NORETURN;
1621 static void sigexit(int sig)
1623 /* Careful: we can end up here after [v]fork. Do not restore
1624 * tty pgrp then, only top-level shell process does that */
1625 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1626 /* Disable all signals: job control, SIGPIPE, etc.
1627 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1629 sigprocmask_allsigs(SIG_BLOCK);
1630 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1633 /* Not a signal, just exit */
1637 kill_myself_with_sig(sig); /* does not return */
1641 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1642 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1646 static sighandler_t pick_sighandler(unsigned sig)
1648 sighandler_t handler = SIG_DFL;
1649 if (sig < sizeof(unsigned)*8) {
1650 unsigned sigmask = (1 << sig);
1654 if (G_fatal_sig_mask & sigmask)
1658 /* sig has special handling? */
1659 if (G.special_sig_mask & sigmask) {
1660 handler = record_pending_signo;
1661 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1662 * in order to ignore them: they will be raised
1663 * in an endless loop when we try to do some
1664 * terminal ioctls! We do have to _ignore_ these.
1666 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1673 /* Restores tty foreground process group, and exits. */
1674 static void hush_exit(int exitcode)
1676 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1677 save_history(G.line_input_state);
1681 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1683 /* argv[0] is unused */
1684 argv[1] = G.traps[0];
1686 G.exiting = 1; /* prevent EXIT trap recursion */
1687 /* Note: G.traps[0] is not cleared!
1688 * "trap" will still show it, if executed
1693 #if ENABLE_FEATURE_CLEAN_UP
1695 struct variable *cur_var;
1696 if (G.cwd != bb_msg_unknown)
1698 cur_var = G.top_var;
1700 struct variable *tmp = cur_var;
1701 if (!cur_var->max_len)
1702 free(cur_var->varstr);
1703 cur_var = cur_var->next;
1711 sigexit(- (exitcode & 0xff));
1718 //TODO: return a mask of ALL handled sigs?
1719 static int check_and_run_traps(void)
1726 if (sigisemptyset(&G.pending_set))
1731 if (sigismember(&G.pending_set, sig)) {
1732 sigdelset(&G.pending_set, sig);
1735 } while (sig < NSIG);
1738 if (G.traps && G.traps[sig]) {
1739 if (G.traps[sig][0]) {
1740 /* We have user-defined handler */
1741 smalluint save_rcode;
1743 /* argv[0] is unused */
1744 argv[1] = G.traps[sig];
1746 save_rcode = G.last_exitcode;
1748 G.last_exitcode = save_rcode;
1750 } /* else: "" trap, ignoring signal */
1753 /* not a trap: special action */
1756 /* Builtin was ^C'ed, make it look prettier: */
1764 /* bash is observed to signal whole process groups,
1765 * not individual processes */
1766 for (job = G.job_list; job; job = job->next) {
1769 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1770 if (kill(- job->pgrp, SIGHUP) == 0)
1771 kill(- job->pgrp, SIGCONT);
1776 #if ENABLE_HUSH_FAST
1779 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1781 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1782 * This simplifies wait builtin a bit.
1786 default: /* ignored: */
1787 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1789 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1790 * Example: wait is not interrupted by TERM
1791 * in interactive shell, because TERM is ignored.
1800 static const char *get_cwd(int force)
1802 if (force || G.cwd == NULL) {
1803 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1804 * we must not try to free(bb_msg_unknown) */
1805 if (G.cwd == bb_msg_unknown)
1807 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1809 G.cwd = bb_msg_unknown;
1816 * Shell and environment variable support
1818 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1820 struct variable **pp;
1821 struct variable *cur;
1824 while ((cur = *pp) != NULL) {
1825 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1832 static const char* FAST_FUNC get_local_var_value(const char *name)
1834 struct variable **vpp;
1835 unsigned len = strlen(name);
1837 if (G.expanded_assignments) {
1838 char **cpp = G.expanded_assignments;
1841 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1842 return cp + len + 1;
1847 vpp = get_ptr_to_local_var(name, len);
1849 return (*vpp)->varstr + len + 1;
1851 if (strcmp(name, "PPID") == 0)
1852 return utoa(G.root_ppid);
1853 // bash compat: UID? EUID?
1854 #if ENABLE_HUSH_RANDOM_SUPPORT
1855 if (strcmp(name, "RANDOM") == 0)
1856 return utoa(next_random(&G.random_gen));
1861 /* str holds "NAME=VAL" and is expected to be malloced.
1862 * We take ownership of it.
1864 * 0: do not change export flag
1865 * (if creating new variable, flag will be 0)
1866 * 1: set export flag and putenv the variable
1867 * -1: clear export flag and unsetenv the variable
1868 * flg_read_only is set only when we handle -R var=val
1870 #if !BB_MMU && ENABLE_HUSH_LOCAL
1871 /* all params are used */
1872 #elif BB_MMU && ENABLE_HUSH_LOCAL
1873 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1874 set_local_var(str, flg_export, local_lvl)
1875 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1876 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1877 set_local_var(str, flg_export)
1878 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1879 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1880 set_local_var(str, flg_export, flg_read_only)
1882 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1884 struct variable **var_pp;
1885 struct variable *cur;
1889 eq_sign = strchr(str, '=');
1890 if (!eq_sign) { /* not expected to ever happen? */
1895 name_len = eq_sign - str + 1; /* including '=' */
1896 var_pp = &G.top_var;
1897 while ((cur = *var_pp) != NULL) {
1898 if (strncmp(cur->varstr, str, name_len) != 0) {
1899 var_pp = &cur->next;
1902 /* We found an existing var with this name */
1903 if (cur->flg_read_only) {
1907 bb_error_msg("%s: readonly variable", str);
1911 if (flg_export == -1) { // "&& cur->flg_export" ?
1912 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1917 #if ENABLE_HUSH_LOCAL
1918 if (cur->func_nest_level < local_lvl) {
1919 /* New variable is declared as local,
1920 * and existing one is global, or local
1921 * from enclosing function.
1922 * Remove and save old one: */
1923 *var_pp = cur->next;
1924 cur->next = *G.shadowed_vars_pp;
1925 *G.shadowed_vars_pp = cur;
1926 /* bash 3.2.33(1) and exported vars:
1928 * # f() { local z=a; env | grep ^z; }
1934 if (cur->flg_export)
1939 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1944 if (cur->max_len != 0) {
1945 if (cur->max_len >= strlen(str)) {
1946 /* This one is from startup env, reuse space */
1947 strcpy(cur->varstr, str);
1951 /* max_len == 0 signifies "malloced" var, which we can
1952 * (and has to) free */
1956 goto set_str_and_exp;
1959 /* Not found - create new variable struct */
1960 cur = xzalloc(sizeof(*cur));
1961 #if ENABLE_HUSH_LOCAL
1962 cur->func_nest_level = local_lvl;
1964 cur->next = *var_pp;
1970 cur->flg_read_only = flg_read_only;
1973 if (flg_export == 1)
1974 cur->flg_export = 1;
1975 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1976 cmdedit_update_prompt();
1977 if (cur->flg_export) {
1978 if (flg_export == -1) {
1979 cur->flg_export = 0;
1980 /* unsetenv was already done */
1982 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1983 return putenv(cur->varstr);
1989 /* Used at startup and after each cd */
1990 static void set_pwd_var(int exp)
1992 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1993 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1996 static int unset_local_var_len(const char *name, int name_len)
1998 struct variable *cur;
1999 struct variable **var_pp;
2002 return EXIT_SUCCESS;
2003 var_pp = &G.top_var;
2004 while ((cur = *var_pp) != NULL) {
2005 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2006 if (cur->flg_read_only) {
2007 bb_error_msg("%s: readonly variable", name);
2008 return EXIT_FAILURE;
2010 *var_pp = cur->next;
2011 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2012 bb_unsetenv(cur->varstr);
2013 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2014 cmdedit_update_prompt();
2018 return EXIT_SUCCESS;
2020 var_pp = &cur->next;
2022 return EXIT_SUCCESS;
2025 static int unset_local_var(const char *name)
2027 return unset_local_var_len(name, strlen(name));
2030 static void unset_vars(char **strings)
2038 const char *eq = strchrnul(*v, '=');
2039 unset_local_var_len(*v, (int)(eq - *v));
2045 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2047 char *var = xasprintf("%s=%s", name, val);
2048 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2053 * Helpers for "var1=val1 var2=val2 cmd" feature
2055 static void add_vars(struct variable *var)
2057 struct variable *next;
2061 var->next = G.top_var;
2063 if (var->flg_export) {
2064 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2065 putenv(var->varstr);
2067 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2073 static struct variable *set_vars_and_save_old(char **strings)
2076 struct variable *old = NULL;
2082 struct variable *var_p;
2083 struct variable **var_pp;
2086 eq = strchr(*s, '=');
2088 var_pp = get_ptr_to_local_var(*s, eq - *s);
2090 /* Remove variable from global linked list */
2092 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2093 *var_pp = var_p->next;
2094 /* Add it to returned list */
2098 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2109 static void reinit_unicode_for_hush(void)
2111 /* Unicode support should be activated even if LANG is set
2112 * _during_ shell execution, not only if it was set when
2113 * shell was started. Therefore, re-check LANG every time:
2115 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2116 || ENABLE_UNICODE_USING_LOCALE
2118 const char *s = get_local_var_value("LC_ALL");
2119 if (!s) s = get_local_var_value("LC_CTYPE");
2120 if (!s) s = get_local_var_value("LANG");
2126 * in_str support (strings, and "strings" read from files).
2129 #if ENABLE_HUSH_INTERACTIVE
2130 static void cmdedit_update_prompt(void)
2132 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2133 G.PS1 = get_local_var_value("PS1");
2136 G.PS2 = get_local_var_value("PS2");
2143 static const char *setup_prompt_string(int promptmode)
2145 const char *prompt_str;
2146 debug_printf("setup_prompt_string %d ", promptmode);
2147 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2148 /* Set up the prompt */
2149 if (promptmode == 0) { /* PS1 */
2151 /* bash uses $PWD value, even if it is set by user.
2152 * It uses current dir only if PWD is unset.
2153 * We always use current dir. */
2154 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2159 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2160 debug_printf("result '%s'\n", prompt_str);
2163 static int get_user_input(struct in_str *i)
2166 const char *prompt_str;
2168 prompt_str = setup_prompt_string(i->promptmode);
2169 # if ENABLE_FEATURE_EDITING
2170 /* Enable command line editing only while a command line
2171 * is actually being read */
2173 reinit_unicode_for_hush();
2175 /* buglet: SIGINT will not make new prompt to appear _at once_,
2176 * only after <Enter>. (^C will work) */
2177 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2178 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2179 check_and_run_traps();
2180 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2181 i->p = G.user_input_buf;
2183 /* EOF/error detected */
2184 G.user_input_buf[0] = '\0';
2185 i->peek_buf[1] = i->peek_buf[0] = r = EOF;
2188 return (unsigned char)*i->p++;
2192 if (i->last_char == '\0' || i->last_char == '\n') {
2193 /* Why check_and_run_traps here? Try this interactively:
2194 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2195 * $ <[enter], repeatedly...>
2196 * Without check_and_run_traps, handler never runs.
2198 check_and_run_traps();
2199 fputs(prompt_str, stdout);
2203 } while (G.flag_SIGINT || r == '\0');
2207 #endif /* INTERACTIVE */
2209 /* This is the magic location that prints prompts
2210 * and gets data back from the user */
2211 static int FAST_FUNC file_get(struct in_str *i)
2215 /* If there is data waiting, eat it up */
2216 /* peek_buf[] is an int array, not char. Can contain EOF. */
2217 ch = i->peek_buf[0];
2219 int ch2 = i->peek_buf[1];
2220 i->peek_buf[0] = ch2;
2221 if (ch2 == 0) /* very likely, avoid redundant write */
2227 #if ENABLE_HUSH_INTERACTIVE
2228 /* This can be stdin, check line editing char[] buffer */
2229 if (i->p && *i->p != '\0') {
2230 ch = (unsigned char)*i->p++;
2234 * If it's interactive stdin, get new line.
2236 if (G_interactive_fd && i->file == stdin) {
2237 /* Returns first char (or EOF), the rest are in i->p[] */
2238 ch = get_user_input(i);
2239 i->promptmode = 1; /* PS2 */
2242 /* Not stdin: script file */
2244 do ch = fgetc(i->file); while (ch == '\0');
2246 debug_printf("file_get: got '%c' %d\n", ch, ch);
2251 /* All callers guarantee this routine will never
2252 * be used right after a newline, so prompting is not needed.
2254 static int FAST_FUNC file_peek(struct in_str *i)
2258 /* peek_buf[] is an int array, not char. Can contain EOF. */
2259 ch = i->peek_buf[0];
2263 #if ENABLE_HUSH_INTERACTIVE
2264 /* This can be stdin, check line editing char[] buffer */
2265 if (i->p && *i->p != '\0')
2266 return (unsigned char)*i->p;
2269 do ch = fgetc(i->file); while (ch == '\0');
2270 i->peek_buf[0] = ch;
2272 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2276 /* Only ever called if i_peek() was called, and did not return EOF */
2277 static int FAST_FUNC file_peek2(struct in_str *i)
2281 /* peek_buf[] is an int array, not char. Can contain EOF. */
2282 ch = i->peek_buf[0];
2284 /* peek_buf[] is not empty. Is there 2nd char? */
2285 ch = i->peek_buf[1];
2287 /* We did not read it yet, get it now */
2288 do ch = fgetc(i->file); while (ch == '\0');
2289 i->peek_buf[1] = ch;
2294 #if ENABLE_HUSH_INTERACTIVE
2295 /* This can be stdin, check line editing char[] buffer */
2296 if (i->p && i->p[0] != '\0')
2300 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2304 static int FAST_FUNC static_get(struct in_str *i)
2315 static int FAST_FUNC static_peek(struct in_str *i)
2317 /* Doesn't report EOF on NUL. None of the callers care. */
2321 /* Only ever called if i_peek() was called, and did not return EOF */
2322 static int FAST_FUNC static_peek2(struct in_str *i)
2327 static void setup_file_in_str(struct in_str *i, FILE *f)
2329 memset(i, 0, sizeof(*i));
2331 i->peek = file_peek;
2332 i->peek2 = file_peek2;
2333 /* i->promptmode = 0; - PS1 (memset did it) */
2338 static void setup_string_in_str(struct in_str *i, const char *s)
2340 memset(i, 0, sizeof(*i));
2341 i->get = static_get;
2342 i->peek = static_peek;
2343 i->peek2 = static_peek2;
2344 /* i->promptmode = 0; - PS1 (memset did it) */
2352 #define B_CHUNK (32 * sizeof(char*))
2354 static void o_reset_to_empty_unquoted(o_string *o)
2357 o->has_quoted_part = 0;
2362 static void o_free(o_string *o)
2365 memset(o, 0, sizeof(*o));
2368 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2373 static void o_grow_by(o_string *o, int len)
2375 if (o->length + len > o->maxlen) {
2376 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2377 o->data = xrealloc(o->data, 1 + o->maxlen);
2381 static void o_addchr(o_string *o, int ch)
2383 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2385 o->data[o->length] = ch;
2387 o->data[o->length] = '\0';
2390 static void o_addblock(o_string *o, const char *str, int len)
2393 memcpy(&o->data[o->length], str, len);
2395 o->data[o->length] = '\0';
2398 static void o_addstr(o_string *o, const char *str)
2400 o_addblock(o, str, strlen(str));
2404 static void nommu_addchr(o_string *o, int ch)
2410 # define nommu_addchr(o, str) ((void)0)
2413 static void o_addstr_with_NUL(o_string *o, const char *str)
2415 o_addblock(o, str, strlen(str) + 1);
2419 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2420 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2421 * Apparently, on unquoted $v bash still does globbing
2422 * ("v='*.txt'; echo $v" prints all .txt files),
2423 * but NOT brace expansion! Thus, there should be TWO independent
2424 * quoting mechanisms on $v expansion side: one protects
2425 * $v from brace expansion, and other additionally protects "$v" against globbing.
2426 * We have only second one.
2429 #if ENABLE_HUSH_BRACE_EXPANSION
2430 # define MAYBE_BRACES "{}"
2432 # define MAYBE_BRACES ""
2435 /* My analysis of quoting semantics tells me that state information
2436 * is associated with a destination, not a source.
2438 static void o_addqchr(o_string *o, int ch)
2441 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2446 o->data[o->length] = '\\';
2449 o->data[o->length] = ch;
2451 o->data[o->length] = '\0';
2454 static void o_addQchr(o_string *o, int ch)
2457 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2458 && strchr("*?[\\" MAYBE_BRACES, ch)
2461 o->data[o->length] = '\\';
2465 o->data[o->length] = ch;
2467 o->data[o->length] = '\0';
2470 static void o_addqblock(o_string *o, const char *str, int len)
2475 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2476 if (ordinary_cnt > len) /* paranoia */
2478 o_addblock(o, str, ordinary_cnt);
2479 if (ordinary_cnt == len)
2480 return; /* NUL is already added by o_addblock */
2481 str += ordinary_cnt;
2482 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2486 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2488 o->data[o->length] = '\\';
2492 o->data[o->length] = ch;
2495 o->data[o->length] = '\0';
2498 static void o_addQblock(o_string *o, const char *str, int len)
2500 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2501 o_addblock(o, str, len);
2504 o_addqblock(o, str, len);
2507 static void o_addQstr(o_string *o, const char *str)
2509 o_addQblock(o, str, strlen(str));
2512 /* A special kind of o_string for $VAR and `cmd` expansion.
2513 * It contains char* list[] at the beginning, which is grown in 16 element
2514 * increments. Actual string data starts at the next multiple of 16 * (char*).
2515 * list[i] contains an INDEX (int!) into this string data.
2516 * It means that if list[] needs to grow, data needs to be moved higher up
2517 * but list[i]'s need not be modified.
2518 * NB: remembering how many list[i]'s you have there is crucial.
2519 * o_finalize_list() operation post-processes this structure - calculates
2520 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2522 #if DEBUG_EXPAND || DEBUG_GLOB
2523 static void debug_print_list(const char *prefix, o_string *o, int n)
2525 char **list = (char**)o->data;
2526 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2530 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2531 prefix, list, n, string_start, o->length, o->maxlen,
2532 !!(o->o_expflags & EXP_FLAG_GLOB),
2534 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2537 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2538 o->data + (int)(uintptr_t)list[i] + string_start,
2539 o->data + (int)(uintptr_t)list[i] + string_start);
2543 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2545 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2549 # define debug_print_list(prefix, o, n) ((void)0)
2552 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2553 * in list[n] so that it points past last stored byte so far.
2554 * It returns n+1. */
2555 static int o_save_ptr_helper(o_string *o, int n)
2557 char **list = (char**)o->data;
2561 if (!o->has_empty_slot) {
2562 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2563 string_len = o->length - string_start;
2564 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2565 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2566 /* list[n] points to string_start, make space for 16 more pointers */
2567 o->maxlen += 0x10 * sizeof(list[0]);
2568 o->data = xrealloc(o->data, o->maxlen + 1);
2569 list = (char**)o->data;
2570 memmove(list + n + 0x10, list + n, string_len);
2571 o->length += 0x10 * sizeof(list[0]);
2573 debug_printf_list("list[%d]=%d string_start=%d\n",
2574 n, string_len, string_start);
2577 /* We have empty slot at list[n], reuse without growth */
2578 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2579 string_len = o->length - string_start;
2580 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2581 n, string_len, string_start);
2582 o->has_empty_slot = 0;
2584 o->has_quoted_part = 0;
2585 list[n] = (char*)(uintptr_t)string_len;
2589 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2590 static int o_get_last_ptr(o_string *o, int n)
2592 char **list = (char**)o->data;
2593 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2595 return ((int)(uintptr_t)list[n-1]) + string_start;
2598 #if ENABLE_HUSH_BRACE_EXPANSION
2599 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2600 * first, it processes even {a} (no commas), second,
2601 * I didn't manage to make it return strings when they don't match
2602 * existing files. Need to re-implement it.
2606 static int glob_needed(const char *s)
2615 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2621 /* Return pointer to next closing brace or to comma */
2622 static const char *next_brace_sub(const char *cp)
2626 while (*cp != '\0') {
2633 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2639 return *cp != '\0' ? cp : NULL;
2641 /* Recursive brace globber. Note: may garble pattern[]. */
2642 static int glob_brace(char *pattern, o_string *o, int n)
2644 char *new_pattern_buf;
2651 debug_printf_glob("glob_brace('%s')\n", pattern);
2657 if (*begin == '{') {
2658 /* Find the first sub-pattern and at the same time
2659 * find the rest after the closing brace */
2660 next = next_brace_sub(begin);
2662 /* An illegal expression */
2666 /* "{abc}" with no commas - illegal
2667 * brace expr, disregard and skip it */
2673 if (*begin == '\\' && begin[1] != '\0')
2677 debug_printf_glob("begin:%s\n", begin);
2678 debug_printf_glob("next:%s\n", next);
2680 /* Now find the end of the whole brace expression */
2682 while (*rest != '}') {
2683 rest = next_brace_sub(rest);
2685 /* An illegal expression */
2688 debug_printf_glob("rest:%s\n", rest);
2690 rest_len = strlen(++rest) + 1;
2692 /* We are sure the brace expression is well-formed */
2694 /* Allocate working buffer large enough for our work */
2695 new_pattern_buf = xmalloc(strlen(pattern));
2697 /* We have a brace expression. BEGIN points to the opening {,
2698 * NEXT points past the terminator of the first element, and REST
2699 * points past the final }. We will accumulate result names from
2700 * recursive runs for each brace alternative in the buffer using
2705 /* Construct the new glob expression */
2708 mempcpy(new_pattern_buf,
2709 /* We know the prefix for all sub-patterns */
2710 pattern, begin - pattern),
2714 /* Note: glob_brace() may garble new_pattern_buf[].
2715 * That's why we re-copy prefix every time (1st memcpy above).
2717 n = glob_brace(new_pattern_buf, o, n);
2719 /* We saw the last entry */
2723 next = next_brace_sub(next);
2725 free(new_pattern_buf);
2733 memset(&globdata, 0, sizeof(globdata));
2734 gr = glob(pattern, 0, NULL, &globdata);
2735 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2737 if (gr == GLOB_NOMATCH) {
2738 globfree(&globdata);
2739 /* NB: garbles parameter */
2740 unbackslash(pattern);
2741 o_addstr_with_NUL(o, pattern);
2742 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2743 return o_save_ptr_helper(o, n);
2745 if (gr == GLOB_NOSPACE)
2746 bb_error_msg_and_die(bb_msg_memory_exhausted);
2747 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2748 * but we didn't specify it. Paranoia again. */
2749 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2751 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2752 char **argv = globdata.gl_pathv;
2754 o_addstr_with_NUL(o, *argv);
2755 n = o_save_ptr_helper(o, n);
2761 globfree(&globdata);
2765 /* Performs globbing on last list[],
2766 * saving each result as a new list[].
2768 static int perform_glob(o_string *o, int n)
2770 char *pattern, *copy;
2772 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2774 return o_save_ptr_helper(o, n);
2775 pattern = o->data + o_get_last_ptr(o, n);
2776 debug_printf_glob("glob pattern '%s'\n", pattern);
2777 if (!glob_needed(pattern)) {
2778 /* unbackslash last string in o in place, fix length */
2779 o->length = unbackslash(pattern) - o->data;
2780 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2781 return o_save_ptr_helper(o, n);
2784 copy = xstrdup(pattern);
2785 /* "forget" pattern in o */
2786 o->length = pattern - o->data;
2787 n = glob_brace(copy, o, n);
2790 debug_print_list("perform_glob returning", o, n);
2794 #else /* !HUSH_BRACE_EXPANSION */
2797 static int glob_needed(const char *s)
2806 if (*s == '*' || *s == '[' || *s == '?')
2812 /* Performs globbing on last list[],
2813 * saving each result as a new list[].
2815 static int perform_glob(o_string *o, int n)
2821 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2823 return o_save_ptr_helper(o, n);
2824 pattern = o->data + o_get_last_ptr(o, n);
2825 debug_printf_glob("glob pattern '%s'\n", pattern);
2826 if (!glob_needed(pattern)) {
2828 /* unbackslash last string in o in place, fix length */
2829 o->length = unbackslash(pattern) - o->data;
2830 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2831 return o_save_ptr_helper(o, n);
2834 memset(&globdata, 0, sizeof(globdata));
2835 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2836 * If we glob "*.\*" and don't find anything, we need
2837 * to fall back to using literal "*.*", but GLOB_NOCHECK
2838 * will return "*.\*"!
2840 gr = glob(pattern, 0, NULL, &globdata);
2841 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2843 if (gr == GLOB_NOMATCH) {
2844 globfree(&globdata);
2847 if (gr == GLOB_NOSPACE)
2848 bb_error_msg_and_die(bb_msg_memory_exhausted);
2849 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2850 * but we didn't specify it. Paranoia again. */
2851 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2853 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2854 char **argv = globdata.gl_pathv;
2855 /* "forget" pattern in o */
2856 o->length = pattern - o->data;
2858 o_addstr_with_NUL(o, *argv);
2859 n = o_save_ptr_helper(o, n);
2865 globfree(&globdata);
2867 debug_print_list("perform_glob returning", o, n);
2871 #endif /* !HUSH_BRACE_EXPANSION */
2873 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2874 * Otherwise, just finish current list[] and start new */
2875 static int o_save_ptr(o_string *o, int n)
2877 if (o->o_expflags & EXP_FLAG_GLOB) {
2878 /* If o->has_empty_slot, list[n] was already globbed
2879 * (if it was requested back then when it was filled)
2880 * so don't do that again! */
2881 if (!o->has_empty_slot)
2882 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2884 return o_save_ptr_helper(o, n);
2887 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2888 static char **o_finalize_list(o_string *o, int n)
2893 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2895 debug_print_list("finalized", o, n);
2896 debug_printf_expand("finalized n:%d\n", n);
2897 list = (char**)o->data;
2898 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2902 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2907 static void free_pipe_list(struct pipe *pi);
2909 /* Returns pi->next - next pipe in the list */
2910 static struct pipe *free_pipe(struct pipe *pi)
2915 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2916 for (i = 0; i < pi->num_cmds; i++) {
2917 struct command *command;
2918 struct redir_struct *r, *rnext;
2920 command = &pi->cmds[i];
2921 debug_printf_clean(" command %d:\n", i);
2922 if (command->argv) {
2926 for (a = 0, p = command->argv; *p; a++, p++) {
2927 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2930 free_strings(command->argv);
2931 //command->argv = NULL;
2933 /* not "else if": on syntax error, we may have both! */
2934 if (command->group) {
2935 debug_printf_clean(" begin group (cmd_type:%d)\n",
2937 free_pipe_list(command->group);
2938 debug_printf_clean(" end group\n");
2939 //command->group = NULL;
2941 /* else is crucial here.
2942 * If group != NULL, child_func is meaningless */
2943 #if ENABLE_HUSH_FUNCTIONS
2944 else if (command->child_func) {
2945 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2946 command->child_func->parent_cmd = NULL;
2950 free(command->group_as_string);
2951 //command->group_as_string = NULL;
2953 for (r = command->redirects; r; r = rnext) {
2954 debug_printf_clean(" redirect %d%s",
2955 r->rd_fd, redir_table[r->rd_type].descrip);
2956 /* guard against the case >$FOO, where foo is unset or blank */
2957 if (r->rd_filename) {
2958 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2959 free(r->rd_filename);
2960 //r->rd_filename = NULL;
2962 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2966 //command->redirects = NULL;
2968 free(pi->cmds); /* children are an array, they get freed all at once */
2972 //pi->cmdtext = NULL;
2980 static void free_pipe_list(struct pipe *pi)
2984 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2986 debug_printf_clean("pipe followup code %d\n", pi->followup);
2992 /*** Parsing routines ***/
2994 #ifndef debug_print_tree
2995 static void debug_print_tree(struct pipe *pi, int lvl)
2997 static const char *const PIPE[] = {
3003 static const char *RES[] = {
3004 [RES_NONE ] = "NONE" ,
3007 [RES_THEN ] = "THEN" ,
3008 [RES_ELIF ] = "ELIF" ,
3009 [RES_ELSE ] = "ELSE" ,
3012 # if ENABLE_HUSH_LOOPS
3013 [RES_FOR ] = "FOR" ,
3014 [RES_WHILE] = "WHILE",
3015 [RES_UNTIL] = "UNTIL",
3017 [RES_DONE ] = "DONE" ,
3019 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3022 # if ENABLE_HUSH_CASE
3023 [RES_CASE ] = "CASE" ,
3024 [RES_CASE_IN ] = "CASE_IN" ,
3025 [RES_MATCH] = "MATCH",
3026 [RES_CASE_BODY] = "CASE_BODY",
3027 [RES_ESAC ] = "ESAC" ,
3029 [RES_XXXX ] = "XXXX" ,
3030 [RES_SNTX ] = "SNTX" ,
3032 static const char *const CMDTYPE[] = {
3036 # if ENABLE_HUSH_FUNCTIONS
3045 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3046 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3048 while (prn < pi->num_cmds) {
3049 struct command *command = &pi->cmds[prn];
3050 char **argv = command->argv;
3052 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3054 command->assignment_cnt);
3055 if (command->group) {
3056 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3057 CMDTYPE[command->cmd_type],
3060 , " group_as_string:", command->group_as_string
3065 debug_print_tree(command->group, lvl+1);
3069 if (argv) while (*argv) {
3070 fdprintf(2, " '%s'", *argv);
3080 #endif /* debug_print_tree */
3082 static struct pipe *new_pipe(void)
3085 pi = xzalloc(sizeof(struct pipe));
3086 /*pi->followup = 0; - deliberately invalid value */
3087 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3091 /* Command (member of a pipe) is complete, or we start a new pipe
3092 * if ctx->command is NULL.
3093 * No errors possible here.
3095 static int done_command(struct parse_context *ctx)
3097 /* The command is really already in the pipe structure, so
3098 * advance the pipe counter and make a new, null command. */
3099 struct pipe *pi = ctx->pipe;
3100 struct command *command = ctx->command;
3102 #if 0 /* Instead we emit error message at run time */
3103 if (ctx->pending_redirect) {
3104 /* For example, "cmd >" (no filename to redirect to) */
3105 die_if_script("syntax error: %s", "invalid redirect");
3106 ctx->pending_redirect = NULL;
3111 if (IS_NULL_CMD(command)) {
3112 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3116 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3117 //debug_print_tree(ctx->list_head, 20);
3119 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3122 /* Only real trickiness here is that the uncommitted
3123 * command structure is not counted in pi->num_cmds. */
3124 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3125 ctx->command = command = &pi->cmds[pi->num_cmds];
3127 memset(command, 0, sizeof(*command));
3128 return pi->num_cmds; /* used only for 0/nonzero check */
3131 static void done_pipe(struct parse_context *ctx, pipe_style type)
3135 debug_printf_parse("done_pipe entered, followup %d\n", type);
3136 /* Close previous command */
3137 not_null = done_command(ctx);
3138 ctx->pipe->followup = type;
3140 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3141 ctx->ctx_inverted = 0;
3142 ctx->pipe->res_word = ctx->ctx_res_w;
3145 /* Without this check, even just <enter> on command line generates
3146 * tree of three NOPs (!). Which is harmless but annoying.
3147 * IOW: it is safe to do it unconditionally. */
3150 || ctx->ctx_res_w == RES_FI
3152 #if ENABLE_HUSH_LOOPS
3153 || ctx->ctx_res_w == RES_DONE
3154 || ctx->ctx_res_w == RES_FOR
3155 || ctx->ctx_res_w == RES_IN
3157 #if ENABLE_HUSH_CASE
3158 || ctx->ctx_res_w == RES_ESAC
3162 debug_printf_parse("done_pipe: adding new pipe: "
3163 "not_null:%d ctx->ctx_res_w:%d\n",
3164 not_null, ctx->ctx_res_w);
3166 ctx->pipe->next = new_p;
3168 /* RES_THEN, RES_DO etc are "sticky" -
3169 * they remain set for pipes inside if/while.
3170 * This is used to control execution.
3171 * RES_FOR and RES_IN are NOT sticky (needed to support
3172 * cases where variable or value happens to match a keyword):
3174 #if ENABLE_HUSH_LOOPS
3175 if (ctx->ctx_res_w == RES_FOR
3176 || ctx->ctx_res_w == RES_IN)
3177 ctx->ctx_res_w = RES_NONE;
3179 #if ENABLE_HUSH_CASE
3180 if (ctx->ctx_res_w == RES_MATCH)
3181 ctx->ctx_res_w = RES_CASE_BODY;
3182 if (ctx->ctx_res_w == RES_CASE)
3183 ctx->ctx_res_w = RES_CASE_IN;
3185 ctx->command = NULL; /* trick done_command below */
3186 /* Create the memory for command, roughly:
3187 * ctx->pipe->cmds = new struct command;
3188 * ctx->command = &ctx->pipe->cmds[0];
3191 //debug_print_tree(ctx->list_head, 10);
3193 debug_printf_parse("done_pipe return\n");
3196 static void initialize_context(struct parse_context *ctx)
3198 memset(ctx, 0, sizeof(*ctx));
3199 ctx->pipe = ctx->list_head = new_pipe();
3200 /* Create the memory for command, roughly:
3201 * ctx->pipe->cmds = new struct command;
3202 * ctx->command = &ctx->pipe->cmds[0];
3207 /* If a reserved word is found and processed, parse context is modified
3208 * and 1 is returned.
3211 struct reserved_combo {
3214 unsigned char assignment_flag;
3218 FLAG_END = (1 << RES_NONE ),
3220 FLAG_IF = (1 << RES_IF ),
3221 FLAG_THEN = (1 << RES_THEN ),
3222 FLAG_ELIF = (1 << RES_ELIF ),
3223 FLAG_ELSE = (1 << RES_ELSE ),
3224 FLAG_FI = (1 << RES_FI ),
3226 # if ENABLE_HUSH_LOOPS
3227 FLAG_FOR = (1 << RES_FOR ),
3228 FLAG_WHILE = (1 << RES_WHILE),
3229 FLAG_UNTIL = (1 << RES_UNTIL),
3230 FLAG_DO = (1 << RES_DO ),
3231 FLAG_DONE = (1 << RES_DONE ),
3232 FLAG_IN = (1 << RES_IN ),
3234 # if ENABLE_HUSH_CASE
3235 FLAG_MATCH = (1 << RES_MATCH),
3236 FLAG_ESAC = (1 << RES_ESAC ),
3238 FLAG_START = (1 << RES_XXXX ),
3241 static const struct reserved_combo* match_reserved_word(o_string *word)
3243 /* Mostly a list of accepted follow-up reserved words.
3244 * FLAG_END means we are done with the sequence, and are ready
3245 * to turn the compound list into a command.
3246 * FLAG_START means the word must start a new compound list.
3248 static const struct reserved_combo reserved_list[] = {
3250 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3251 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3252 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3253 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3254 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3255 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3257 # if ENABLE_HUSH_LOOPS
3258 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3259 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3260 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3261 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3262 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3263 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3265 # if ENABLE_HUSH_CASE
3266 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3267 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3270 const struct reserved_combo *r;
3272 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3273 if (strcmp(word->data, r->literal) == 0)
3278 /* Return 0: not a keyword, 1: keyword
3280 static int reserved_word(o_string *word, struct parse_context *ctx)
3282 # if ENABLE_HUSH_CASE
3283 static const struct reserved_combo reserved_match = {
3284 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3287 const struct reserved_combo *r;
3289 if (word->has_quoted_part)
3291 r = match_reserved_word(word);
3295 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3296 # if ENABLE_HUSH_CASE
3297 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3298 /* "case word IN ..." - IN part starts first MATCH part */
3299 r = &reserved_match;
3302 if (r->flag == 0) { /* '!' */
3303 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3304 syntax_error("! ! command");
3305 ctx->ctx_res_w = RES_SNTX;
3307 ctx->ctx_inverted = 1;
3310 if (r->flag & FLAG_START) {
3311 struct parse_context *old;
3313 old = xmalloc(sizeof(*old));
3314 debug_printf_parse("push stack %p\n", old);
3315 *old = *ctx; /* physical copy */
3316 initialize_context(ctx);
3318 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3319 syntax_error_at(word->data);
3320 ctx->ctx_res_w = RES_SNTX;
3323 /* "{...} fi" is ok. "{...} if" is not
3325 * if { echo foo; } then { echo bar; } fi */
3326 if (ctx->command->group)
3327 done_pipe(ctx, PIPE_SEQ);
3330 ctx->ctx_res_w = r->res;
3331 ctx->old_flag = r->flag;
3332 word->o_assignment = r->assignment_flag;
3333 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3335 if (ctx->old_flag & FLAG_END) {
3336 struct parse_context *old;
3338 done_pipe(ctx, PIPE_SEQ);
3339 debug_printf_parse("pop stack %p\n", ctx->stack);
3341 old->command->group = ctx->list_head;
3342 old->command->cmd_type = CMD_NORMAL;
3344 /* At this point, the compound command's string is in
3345 * ctx->as_string... except for the leading keyword!
3346 * Consider this example: "echo a | if true; then echo a; fi"
3347 * ctx->as_string will contain "true; then echo a; fi",
3348 * with "if " remaining in old->as_string!
3352 int len = old->as_string.length;
3353 /* Concatenate halves */
3354 o_addstr(&old->as_string, ctx->as_string.data);
3355 o_free_unsafe(&ctx->as_string);
3356 /* Find where leading keyword starts in first half */
3357 str = old->as_string.data + len;
3358 if (str > old->as_string.data)
3359 str--; /* skip whitespace after keyword */
3360 while (str > old->as_string.data && isalpha(str[-1]))
3362 /* Ugh, we're done with this horrid hack */
3363 old->command->group_as_string = xstrdup(str);
3364 debug_printf_parse("pop, remembering as:'%s'\n",
3365 old->command->group_as_string);
3368 *ctx = *old; /* physical copy */
3373 #endif /* HAS_KEYWORDS */
3375 /* Word is complete, look at it and update parsing context.
3376 * Normal return is 0. Syntax errors return 1.
3377 * Note: on return, word is reset, but not o_free'd!
3379 static int done_word(o_string *word, struct parse_context *ctx)
3381 struct command *command = ctx->command;
3383 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3384 if (word->length == 0 && !word->has_quoted_part) {
3385 debug_printf_parse("done_word return 0: true null, ignored\n");
3389 if (ctx->pending_redirect) {
3390 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3391 * only if run as "bash", not "sh" */
3392 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3394 * ...the word that follows the redirection operator
3395 * shall be subjected to tilde expansion, parameter expansion,
3396 * command substitution, arithmetic expansion, and quote
3397 * removal. Pathname expansion shall not be performed
3398 * on the word by a non-interactive shell; an interactive
3399 * shell may perform it, but shall do so only when
3400 * the expansion would result in one word."
3402 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3403 /* Cater for >\file case:
3404 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3405 * Same with heredocs:
3406 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3408 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3409 unbackslash(ctx->pending_redirect->rd_filename);
3410 /* Is it <<"HEREDOC"? */
3411 if (word->has_quoted_part) {
3412 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3415 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3416 ctx->pending_redirect = NULL;
3419 # if ENABLE_HUSH_CASE
3420 if (ctx->ctx_dsemicolon
3421 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3423 /* already done when ctx_dsemicolon was set to 1: */
3424 /* ctx->ctx_res_w = RES_MATCH; */
3425 ctx->ctx_dsemicolon = 0;
3428 if (!command->argv /* if it's the first word... */
3429 # if ENABLE_HUSH_LOOPS
3430 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3431 && ctx->ctx_res_w != RES_IN
3433 # if ENABLE_HUSH_CASE
3434 && ctx->ctx_res_w != RES_CASE
3437 int reserved = reserved_word(word, ctx);
3438 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3440 o_reset_to_empty_unquoted(word);
3441 debug_printf_parse("done_word return %d\n",
3442 (ctx->ctx_res_w == RES_SNTX));
3443 return (ctx->ctx_res_w == RES_SNTX);
3445 # if ENABLE_HUSH_BASH_COMPAT
3446 if (strcmp(word->data, "[[") == 0) {
3447 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3453 if (command->group) {
3454 /* "{ echo foo; } echo bar" - bad */
3455 syntax_error_at(word->data);
3456 debug_printf_parse("done_word return 1: syntax error, "
3457 "groups and arglists don't mix\n");
3461 /* If this word wasn't an assignment, next ones definitely
3462 * can't be assignments. Even if they look like ones. */
3463 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3464 && word->o_assignment != WORD_IS_KEYWORD
3466 word->o_assignment = NOT_ASSIGNMENT;
3468 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3469 command->assignment_cnt++;
3470 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3472 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3473 word->o_assignment = MAYBE_ASSIGNMENT;
3475 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3477 if (word->has_quoted_part
3478 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3479 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3480 /* (otherwise it's known to be not empty and is already safe) */
3482 /* exclude "$@" - it can expand to no word despite "" */
3483 char *p = word->data;
3484 while (p[0] == SPECIAL_VAR_SYMBOL
3485 && (p[1] & 0x7f) == '@'
3486 && p[2] == SPECIAL_VAR_SYMBOL
3491 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3492 debug_print_strings("word appended to argv", command->argv);
3495 #if ENABLE_HUSH_LOOPS
3496 if (ctx->ctx_res_w == RES_FOR) {
3497 if (word->has_quoted_part
3498 || !is_well_formed_var_name(command->argv[0], '\0')
3500 /* bash says just "not a valid identifier" */
3501 syntax_error("not a valid identifier in for");
3504 /* Force FOR to have just one word (variable name) */
3505 /* NB: basically, this makes hush see "for v in ..."
3506 * syntax as if it is "for v; in ...". FOR and IN become
3507 * two pipe structs in parse tree. */
3508 done_pipe(ctx, PIPE_SEQ);
3511 #if ENABLE_HUSH_CASE
3512 /* Force CASE to have just one word */
3513 if (ctx->ctx_res_w == RES_CASE) {
3514 done_pipe(ctx, PIPE_SEQ);
3518 o_reset_to_empty_unquoted(word);
3520 debug_printf_parse("done_word return 0\n");
3525 /* Peek ahead in the input to find out if we have a "&n" construct,
3526 * as in "2>&1", that represents duplicating a file descriptor.
3528 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3529 * REDIRFD_SYNTAX_ERR if syntax error,
3530 * REDIRFD_TO_FILE if no & was seen,
3531 * or the number found.
3534 #define parse_redir_right_fd(as_string, input) \
3535 parse_redir_right_fd(input)
3537 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3543 return REDIRFD_TO_FILE;
3545 ch = i_getch(input); /* get the & */
3546 nommu_addchr(as_string, ch);
3549 ch = i_getch(input);
3550 nommu_addchr(as_string, ch);
3551 return REDIRFD_CLOSE;
3555 while (ch != EOF && isdigit(ch)) {
3556 d = d*10 + (ch-'0');
3558 ch = i_getch(input);
3559 nommu_addchr(as_string, ch);
3564 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3566 bb_error_msg("ambiguous redirect");
3567 return REDIRFD_SYNTAX_ERR;
3570 /* Return code is 0 normal, 1 if a syntax error is detected
3572 static int parse_redirect(struct parse_context *ctx,
3575 struct in_str *input)
3577 struct command *command = ctx->command;
3578 struct redir_struct *redir;
3579 struct redir_struct **redirp;
3582 dup_num = REDIRFD_TO_FILE;
3583 if (style != REDIRECT_HEREDOC) {
3584 /* Check for a '>&1' type redirect */
3585 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3586 if (dup_num == REDIRFD_SYNTAX_ERR)
3589 int ch = i_peek(input);
3590 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3591 if (dup_num) { /* <<-... */
3592 ch = i_getch(input);
3593 nommu_addchr(&ctx->as_string, ch);
3598 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3599 int ch = i_peek(input);
3601 /* >|FILE redirect ("clobbering" >).
3602 * Since we do not support "set -o noclobber" yet,
3603 * >| and > are the same for now. Just eat |.
3605 ch = i_getch(input);
3606 nommu_addchr(&ctx->as_string, ch);
3610 /* Create a new redir_struct and append it to the linked list */
3611 redirp = &command->redirects;
3612 while ((redir = *redirp) != NULL) {
3613 redirp = &(redir->next);
3615 *redirp = redir = xzalloc(sizeof(*redir));
3616 /* redir->next = NULL; */
3617 /* redir->rd_filename = NULL; */
3618 redir->rd_type = style;
3619 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3621 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3622 redir_table[style].descrip);
3624 redir->rd_dup = dup_num;
3625 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3626 /* Erik had a check here that the file descriptor in question
3627 * is legit; I postpone that to "run time"
3628 * A "-" representation of "close me" shows up as a -3 here */
3629 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3630 redir->rd_fd, redir->rd_dup);
3632 #if 0 /* Instead we emit error message at run time */
3633 if (ctx->pending_redirect) {
3634 /* For example, "cmd > <file" */
3635 die_if_script("syntax error: %s", "invalid redirect");
3638 /* Set ctx->pending_redirect, so we know what to do at the
3639 * end of the next parsed word. */
3640 ctx->pending_redirect = redir;
3645 /* If a redirect is immediately preceded by a number, that number is
3646 * supposed to tell which file descriptor to redirect. This routine
3647 * looks for such preceding numbers. In an ideal world this routine
3648 * needs to handle all the following classes of redirects...
3649 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3650 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3651 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3652 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3654 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3656 * ... If n is quoted, the number shall not be recognized as part of
3657 * the redirection expression. For example:
3659 * writes the character 2 into file a"
3660 * We are getting it right by setting ->has_quoted_part on any \<char>
3662 * A -1 return means no valid number was found,
3663 * the caller should use the appropriate default for this redirection.
3665 static int redirect_opt_num(o_string *o)
3669 if (o->data == NULL)
3671 num = bb_strtou(o->data, NULL, 10);
3672 if (errno || num < 0)
3674 o_reset_to_empty_unquoted(o);
3679 #define fetch_till_str(as_string, input, word, skip_tabs) \
3680 fetch_till_str(input, word, skip_tabs)
3682 static char *fetch_till_str(o_string *as_string,
3683 struct in_str *input,
3687 o_string heredoc = NULL_O_STRING;
3689 int prev = 0; /* not \ */
3695 ch = i_getch(input);
3697 nommu_addchr(as_string, ch);
3698 if ((ch == '\n' || ch == EOF)
3699 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3701 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3702 heredoc.data[past_EOL] = '\0';
3703 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3704 return heredoc.data;
3706 while (ch == '\n') {
3707 o_addchr(&heredoc, ch);
3710 past_EOL = heredoc.length;
3712 ch = i_getch(input);
3714 nommu_addchr(as_string, ch);
3715 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3719 o_free_unsafe(&heredoc);
3722 o_addchr(&heredoc, ch);
3723 nommu_addchr(as_string, ch);
3724 if (prev == '\\' && ch == '\\')
3725 /* Correctly handle foo\\<eol> (not a line cont.) */
3726 prev = 0; /* not \ */
3732 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3733 * and load them all. There should be exactly heredoc_cnt of them.
3735 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3737 struct pipe *pi = ctx->list_head;
3739 while (pi && heredoc_cnt) {
3741 struct command *cmd = pi->cmds;
3743 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3745 cmd->argv ? cmd->argv[0] : "NONE");
3746 for (i = 0; i < pi->num_cmds; i++) {
3747 struct redir_struct *redir = cmd->redirects;
3749 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3750 i, cmd->argv ? cmd->argv[0] : "NONE");
3752 if (redir->rd_type == REDIRECT_HEREDOC) {
3755 redir->rd_type = REDIRECT_HEREDOC2;
3756 /* redir->rd_dup is (ab)used to indicate <<- */
3757 p = fetch_till_str(&ctx->as_string, input,
3758 redir->rd_filename, redir->rd_dup);
3760 syntax_error("unexpected EOF in here document");
3763 free(redir->rd_filename);
3764 redir->rd_filename = p;
3767 redir = redir->next;
3774 /* Should be 0. If it isn't, it's a parse error */
3776 bb_error_msg_and_die("heredoc BUG 2");
3782 static int run_list(struct pipe *pi);
3784 #define parse_stream(pstring, input, end_trigger) \
3785 parse_stream(input, end_trigger)
3787 static struct pipe *parse_stream(char **pstring,
3788 struct in_str *input,
3792 #if !ENABLE_HUSH_FUNCTIONS
3793 #define parse_group(dest, ctx, input, ch) \
3794 parse_group(ctx, input, ch)
3796 static int parse_group(o_string *dest, struct parse_context *ctx,
3797 struct in_str *input, int ch)
3799 /* dest contains characters seen prior to ( or {.
3800 * Typically it's empty, but for function defs,
3801 * it contains function name (without '()'). */
3802 struct pipe *pipe_list;
3804 struct command *command = ctx->command;
3806 debug_printf_parse("parse_group entered\n");
3807 #if ENABLE_HUSH_FUNCTIONS
3808 if (ch == '(' && !dest->has_quoted_part) {
3810 if (done_word(dest, ctx))
3813 goto skip; /* (... */
3814 if (command->argv[1]) { /* word word ... (... */
3815 syntax_error_unexpected_ch('(');
3818 /* it is "word(..." or "word (..." */
3820 ch = i_getch(input);
3821 while (ch == ' ' || ch == '\t');
3823 syntax_error_unexpected_ch(ch);
3826 nommu_addchr(&ctx->as_string, ch);
3828 ch = i_getch(input);
3829 while (ch == ' ' || ch == '\t' || ch == '\n');
3831 syntax_error_unexpected_ch(ch);
3834 nommu_addchr(&ctx->as_string, ch);
3835 command->cmd_type = CMD_FUNCDEF;
3840 #if 0 /* Prevented by caller */
3841 if (command->argv /* word [word]{... */
3842 || dest->length /* word{... */
3843 || dest->has_quoted_part /* ""{... */
3846 debug_printf_parse("parse_group return 1: "
3847 "syntax error, groups and arglists don't mix\n");
3852 #if ENABLE_HUSH_FUNCTIONS
3858 command->cmd_type = CMD_SUBSHELL;
3860 /* bash does not allow "{echo...", requires whitespace */
3861 ch = i_getch(input);
3862 if (ch != ' ' && ch != '\t' && ch != '\n') {
3863 syntax_error_unexpected_ch(ch);
3866 nommu_addchr(&ctx->as_string, ch);
3871 # define as_string NULL
3873 char *as_string = NULL;
3875 pipe_list = parse_stream(&as_string, input, endch);
3878 o_addstr(&ctx->as_string, as_string);
3880 /* empty ()/{} or parse error? */
3881 if (!pipe_list || pipe_list == ERR_PTR) {
3882 /* parse_stream already emitted error msg */
3885 debug_printf_parse("parse_group return 1: "
3886 "parse_stream returned %p\n", pipe_list);
3889 command->group = pipe_list;
3891 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3892 command->group_as_string = as_string;
3893 debug_printf_parse("end of group, remembering as:'%s'\n",
3894 command->group_as_string);
3898 debug_printf_parse("parse_group return 0\n");
3900 /* command remains "open", available for possible redirects */
3903 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3904 /* Subroutines for copying $(...) and `...` things */
3905 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3907 static int add_till_single_quote(o_string *dest, struct in_str *input)
3910 int ch = i_getch(input);
3912 syntax_error_unterm_ch('\'');
3920 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3921 static int add_till_double_quote(o_string *dest, struct in_str *input)
3924 int ch = i_getch(input);
3926 syntax_error_unterm_ch('"');
3931 if (ch == '\\') { /* \x. Copy both chars. */
3933 ch = i_getch(input);
3937 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3942 //if (ch == '$') ...
3945 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3947 * "Within the backquoted style of command substitution, backslash
3948 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3949 * The search for the matching backquote shall be satisfied by the first
3950 * backquote found without a preceding backslash; during this search,
3951 * if a non-escaped backquote is encountered within a shell comment,
3952 * a here-document, an embedded command substitution of the $(command)
3953 * form, or a quoted string, undefined results occur. A single-quoted
3954 * or double-quoted string that begins, but does not end, within the
3955 * "`...`" sequence produces undefined results."
3957 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3959 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3962 int ch = i_getch(input);
3966 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3967 ch = i_getch(input);
3971 && (!in_dquote || ch != '"')
3973 o_addchr(dest, '\\');
3977 syntax_error_unterm_ch('`');
3983 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3984 * quoting and nested ()s.
3985 * "With the $(command) style of command substitution, all characters
3986 * following the open parenthesis to the matching closing parenthesis
3987 * constitute the command. Any valid shell script can be used for command,
3988 * except a script consisting solely of redirections which produces
3989 * unspecified results."
3991 * echo $(echo '(TEST)' BEST) (TEST) BEST
3992 * echo $(echo 'TEST)' BEST) TEST) BEST
3993 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3995 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3996 * can contain arbitrary constructs, just like $(cmd).
3997 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3998 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4000 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4001 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4004 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4005 # if ENABLE_HUSH_BASH_COMPAT
4006 char end_char2 = end_ch >> 8;
4008 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4011 ch = i_getch(input);
4013 syntax_error_unterm_ch(end_ch);
4016 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4019 /* we look for closing )) of $((EXPR)) */
4020 if (i_peek(input) == end_ch) {
4021 i_getch(input); /* eat second ')' */
4026 if (ch == '(' || ch == '{') {
4027 ch = (ch == '(' ? ')' : '}');
4028 if (!add_till_closing_bracket(dest, input, ch))
4034 if (!add_till_single_quote(dest, input))
4040 if (!add_till_double_quote(dest, input))
4046 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4052 /* \x. Copy verbatim. Important for \(, \) */
4053 ch = i_getch(input);
4055 syntax_error_unterm_ch(')');
4064 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
4066 /* Return code: 0 for OK, 1 for syntax error */
4068 #define parse_dollar(as_string, dest, input, quote_mask) \
4069 parse_dollar(dest, input, quote_mask)
4070 #define as_string NULL
4072 static int parse_dollar(o_string *as_string,
4074 struct in_str *input, unsigned char quote_mask)
4076 int ch = i_peek(input); /* first character after the $ */
4078 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4080 ch = i_getch(input);
4081 nommu_addchr(as_string, ch);
4083 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4085 debug_printf_parse(": '%c'\n", ch);
4086 o_addchr(dest, ch | quote_mask);
4090 if (!isalnum(ch) && ch != '_') {
4092 /* If backslash+newline, skip it */
4093 int ch2 = i_peek2(input);
4100 /* End of variable name reached */
4103 ch = i_getch(input);
4104 nommu_addchr(as_string, ch);
4106 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4107 } else if (isdigit(ch)) {
4109 ch = i_getch(input);
4110 nommu_addchr(as_string, ch);
4111 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4112 debug_printf_parse(": '%c'\n", ch);
4113 o_addchr(dest, ch | quote_mask);
4114 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4115 } else switch (ch) {
4117 case '!': /* last bg pid */
4118 case '?': /* last exit code */
4119 case '#': /* number of args */
4120 case '*': /* args */
4121 case '@': /* args */
4122 goto make_one_char_var;
4124 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4126 ch = i_getch(input); /* eat '{' */
4127 nommu_addchr(as_string, ch);
4129 ch = i_getch(input); /* first char after '{' */
4130 /* It should be ${?}, or ${#var},
4131 * or even ${?+subst} - operator acting on a special variable,
4132 * or the beginning of variable name.
4135 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4138 syntax_error_unterm_str("${name}");
4139 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4142 nommu_addchr(as_string, ch);
4145 /* It's possible to just call add_till_closing_bracket() at this point.
4146 * However, this regresses some of our testsuite cases
4147 * which check invalid constructs like ${%}.
4148 * Oh well... let's check that the var name part is fine... */
4154 debug_printf_parse(": '%c'\n", ch);
4156 ch = i_getch(input);
4157 nommu_addchr(as_string, ch);
4161 if (!isalnum(ch) && ch != '_') {
4163 unsigned char last_ch;
4164 /* handle parameter expansions
4165 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4167 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4168 goto bad_dollar_syntax;
4170 /* Eat everything until closing '}' (or ':') */
4172 if (ENABLE_HUSH_BASH_COMPAT
4174 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4176 /* It's ${var:N[:M]} thing */
4177 end_ch = '}' * 0x100 + ':';
4179 if (ENABLE_HUSH_BASH_COMPAT
4182 /* It's ${var/[/]pattern[/repl]} thing */
4183 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4185 nommu_addchr(as_string, '/');
4188 end_ch = '}' * 0x100 + '/';
4194 #if ENABLE_HUSH_DOLLAR_OPS
4195 last_ch = add_till_closing_bracket(dest, input, end_ch);
4196 if (last_ch == 0) /* error? */
4199 #error Simple code to only allow ${var} is not implemented
4202 o_addstr(as_string, dest->data + pos);
4203 o_addchr(as_string, last_ch);
4206 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4207 /* close the first block: */
4208 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4209 /* while parsing N from ${var:N[:M]}
4210 * or pattern from ${var/[/]pattern[/repl]} */
4211 if ((end_ch & 0xff) == last_ch) {
4212 /* got ':' or '/'- parse the rest */
4217 if (end_ch == '}' * 0x100 + ':') {
4218 /* it's ${var:N} - emulate :999999999 */
4219 o_addstr(dest, "999999999");
4220 } /* else: it's ${var/[/]pattern} */
4225 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4228 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
4232 ch = i_getch(input);
4233 nommu_addchr(as_string, ch);
4234 # if ENABLE_SH_MATH_SUPPORT
4235 if (i_peek(input) == '(') {
4236 ch = i_getch(input);
4237 nommu_addchr(as_string, ch);
4238 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4239 o_addchr(dest, /*quote_mask |*/ '+');
4242 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4243 return 0; /* error */
4245 o_addstr(as_string, dest->data + pos);
4246 o_addchr(as_string, ')');
4247 o_addchr(as_string, ')');
4249 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4253 # if ENABLE_HUSH_TICK
4254 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4255 o_addchr(dest, quote_mask | '`');
4258 if (!add_till_closing_bracket(dest, input, ')'))
4259 return 0; /* error */
4261 o_addstr(as_string, dest->data + pos);
4262 o_addchr(as_string, ')');
4264 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4270 ch = i_getch(input);
4271 nommu_addchr(as_string, ch);
4273 if (isalnum(ch)) { /* it's $_name or $_123 */
4278 /* TODO: $_ and $-: */
4279 /* $_ Shell or shell script name; or last argument of last command
4280 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4281 * but in command's env, set to full pathname used to invoke it */
4282 /* $- Option flags set by set builtin or shell options (-i etc) */
4284 o_addQchr(dest, '$');
4286 debug_printf_parse("parse_dollar return 1 (ok)\n");
4292 # if ENABLE_HUSH_BASH_COMPAT
4293 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4294 encode_string(dest, input, dquote_end, process_bkslash)
4296 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4297 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4298 encode_string(dest, input, dquote_end)
4300 #define as_string NULL
4304 # if ENABLE_HUSH_BASH_COMPAT
4305 /* all parameters are needed, no macro tricks */
4307 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4308 encode_string(as_string, dest, input, dquote_end)
4311 static int encode_string(o_string *as_string,
4313 struct in_str *input,
4315 int process_bkslash)
4317 #if !ENABLE_HUSH_BASH_COMPAT
4318 const int process_bkslash = 1;
4324 ch = i_getch(input);
4326 nommu_addchr(as_string, ch);
4327 if (ch == dquote_end) { /* may be only '"' or EOF */
4328 debug_printf_parse("encode_string return 1 (ok)\n");
4331 /* note: can't move it above ch == dquote_end check! */
4333 syntax_error_unterm_ch('"');
4334 return 0; /* error */
4338 next = i_peek(input);
4340 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4341 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4342 if (process_bkslash && ch == '\\') {
4344 syntax_error("\\<eof>");
4348 * "The backslash retains its special meaning [in "..."]
4349 * only when followed by one of the following characters:
4350 * $, `, ", \, or <newline>. A double quote may be quoted
4351 * within double quotes by preceding it with a backslash."
4352 * NB: in (unquoted) heredoc, above does not apply to ",
4353 * therefore we check for it by "next == dquote_end" cond.
4355 if (next == dquote_end || strchr("$`\\\n", next)) {
4356 ch = i_getch(input); /* eat next */
4358 goto again; /* skip \<newline> */
4359 } /* else: ch remains == '\\', and we double it below: */
4360 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4361 nommu_addchr(as_string, ch);
4365 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4366 debug_printf_parse("encode_string return 0: "
4367 "parse_dollar returned 0 (error)\n");
4372 #if ENABLE_HUSH_TICK
4374 //unsigned pos = dest->length;
4375 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4376 o_addchr(dest, 0x80 | '`');
4377 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4378 return 0; /* error */
4379 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4380 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4384 o_addQchr(dest, ch);
4390 * Scan input until EOF or end_trigger char.
4391 * Return a list of pipes to execute, or NULL on EOF
4392 * or if end_trigger character is met.
4393 * On syntax error, exit if shell is not interactive,
4394 * reset parsing machinery and start parsing anew,
4395 * or return ERR_PTR.
4397 static struct pipe *parse_stream(char **pstring,
4398 struct in_str *input,
4401 struct parse_context ctx;
4402 o_string dest = NULL_O_STRING;
4405 /* Single-quote triggers a bypass of the main loop until its mate is
4406 * found. When recursing, quote state is passed in via dest->o_expflags.
4408 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4409 end_trigger ? end_trigger : 'X');
4412 /* If very first arg is "" or '', dest.data may end up NULL.
4413 * Preventing this: */
4414 o_addchr(&dest, '\0');
4417 /* We used to separate words on $IFS here. This was wrong.
4418 * $IFS is used only for word splitting when $var is expanded,
4419 * here we should use blank chars as separators, not $IFS
4422 if (MAYBE_ASSIGNMENT != 0)
4423 dest.o_assignment = MAYBE_ASSIGNMENT;
4424 initialize_context(&ctx);
4427 const char *is_blank;
4428 const char *is_special;
4432 redir_type redir_style;
4434 ch = i_getch(input);
4435 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4436 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4441 syntax_error_unterm_str("here document");
4444 /* end_trigger == '}' case errors out earlier,
4445 * checking only ')' */
4446 if (end_trigger == ')') {
4447 syntax_error_unterm_ch('(');
4451 if (done_word(&dest, &ctx)) {
4455 done_pipe(&ctx, PIPE_SEQ);
4457 /* If we got nothing... */
4458 /* (this makes bare "&" cmd a no-op.
4459 * bash says: "syntax error near unexpected token '&'") */
4460 if (pi->num_cmds == 0
4461 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4467 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4469 *pstring = ctx.as_string.data;
4471 o_free_unsafe(&ctx.as_string);
4474 debug_printf_parse("parse_stream return %p\n", pi);
4477 nommu_addchr(&ctx.as_string, ch);
4481 next = i_peek(input);
4483 is_special = "{}<>;&|()#'" /* special outside of "str" */
4484 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4485 /* Are { and } special here? */
4486 if (ctx.command->argv /* word [word]{... - non-special */
4487 || dest.length /* word{... - non-special */
4488 || dest.has_quoted_part /* ""{... - non-special */
4489 || (next != ';' /* }; - special */
4490 && next != ')' /* }) - special */
4491 && next != '&' /* }& and }&& ... - special */
4492 && next != '|' /* }|| ... - special */
4493 && !strchr(defifs, next) /* {word - non-special */
4496 /* They are not special, skip "{}" */
4499 is_special = strchr(is_special, ch);
4500 is_blank = strchr(defifs, ch);
4502 if (!is_special && !is_blank) { /* ordinary char */
4504 o_addQchr(&dest, ch);
4505 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4506 || dest.o_assignment == WORD_IS_KEYWORD)
4508 && is_well_formed_var_name(dest.data, '=')
4510 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4511 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4517 if (done_word(&dest, &ctx)) {
4521 /* Is this a case when newline is simply ignored?
4523 * "cmd | <newline> cmd ..."
4524 * "case ... in <newline> word) ..."
4526 if (IS_NULL_CMD(ctx.command)
4527 && dest.length == 0 && !dest.has_quoted_part
4529 /* This newline can be ignored. But...
4530 * Without check #1, interactive shell
4531 * ignores even bare <newline>,
4532 * and shows the continuation prompt:
4533 * ps1_prompt$ <enter>
4534 * ps2> _ <=== wrong, should be ps1
4535 * Without check #2, "cmd & <newline>"
4536 * is similarly mistreated.
4537 * (BTW, this makes "cmd & cmd"
4538 * and "cmd && cmd" non-orthogonal.
4539 * Really, ask yourself, why
4540 * "cmd && <newline>" doesn't start
4541 * cmd but waits for more input?
4544 struct pipe *pi = ctx.list_head;
4545 if (pi->num_cmds != 0 /* check #1 */
4546 && pi->followup != PIPE_BG /* check #2 */
4551 /* Treat newline as a command separator. */
4552 done_pipe(&ctx, PIPE_SEQ);
4553 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4555 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4560 dest.o_assignment = MAYBE_ASSIGNMENT;
4561 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4563 /* note: if (is_blank) continue;
4564 * will still trigger for us */
4568 /* "cmd}" or "cmd }..." without semicolon or &:
4569 * } is an ordinary char in this case, even inside { cmd; }
4570 * Pathological example: { ""}; } should exec "}" cmd
4573 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4574 || dest.length != 0 /* word} */
4575 || dest.has_quoted_part /* ""} */
4579 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4580 goto skip_end_trigger;
4581 /* else: } does terminate a group */
4584 if (end_trigger && end_trigger == ch
4585 && (ch != ';' || heredoc_cnt == 0)
4586 #if ENABLE_HUSH_CASE
4588 || ctx.ctx_res_w != RES_MATCH
4589 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4594 /* This is technically valid:
4595 * { cat <<HERE; }; echo Ok
4599 * but we don't support this.
4600 * We require heredoc to be in enclosing {}/(),
4603 syntax_error_unterm_str("here document");
4606 if (done_word(&dest, &ctx)) {
4609 done_pipe(&ctx, PIPE_SEQ);
4610 dest.o_assignment = MAYBE_ASSIGNMENT;
4611 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4612 /* Do we sit outside of any if's, loops or case's? */
4614 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4618 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4620 *pstring = ctx.as_string.data;
4622 o_free_unsafe(&ctx.as_string);
4625 debug_printf_parse("parse_stream return %p: "
4626 "end_trigger char found\n",
4628 return ctx.list_head;
4635 /* Catch <, > before deciding whether this word is
4636 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4639 redir_fd = redirect_opt_num(&dest);
4640 if (done_word(&dest, &ctx)) {
4643 redir_style = REDIRECT_OVERWRITE;
4645 redir_style = REDIRECT_APPEND;
4646 ch = i_getch(input);
4647 nommu_addchr(&ctx.as_string, ch);
4650 else if (next == '(') {
4651 syntax_error(">(process) not supported");
4655 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4657 continue; /* back to top of while (1) */
4659 redir_fd = redirect_opt_num(&dest);
4660 if (done_word(&dest, &ctx)) {
4663 redir_style = REDIRECT_INPUT;
4665 redir_style = REDIRECT_HEREDOC;
4667 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4668 ch = i_getch(input);
4669 nommu_addchr(&ctx.as_string, ch);
4670 } else if (next == '>') {
4671 redir_style = REDIRECT_IO;
4672 ch = i_getch(input);
4673 nommu_addchr(&ctx.as_string, ch);
4676 else if (next == '(') {
4677 syntax_error("<(process) not supported");
4681 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4683 continue; /* back to top of while (1) */
4685 if (dest.length == 0 && !dest.has_quoted_part) {
4686 /* skip "#comment" */
4689 if (ch == EOF || ch == '\n')
4692 /* note: we do not add it to &ctx.as_string */
4694 nommu_addchr(&ctx.as_string, '\n');
4695 continue; /* back to top of while (1) */
4700 /* It's "\<newline>" */
4702 /* Remove trailing '\' from ctx.as_string */
4703 ctx.as_string.data[--ctx.as_string.length] = '\0';
4705 ch = i_getch(input); /* eat it */
4706 continue; /* back to top of while (1) */
4711 if (dest.o_assignment == MAYBE_ASSIGNMENT
4712 /* check that we are not in word in "a=1 2>word b=1": */
4713 && !ctx.pending_redirect
4715 /* ch is a special char and thus this word
4716 * cannot be an assignment */
4717 dest.o_assignment = NOT_ASSIGNMENT;
4718 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4721 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4724 case '#': /* non-comment #: "echo a#b" etc */
4725 o_addQchr(&dest, ch);
4729 syntax_error("\\<eof>");
4732 ch = i_getch(input);
4733 /* note: ch != '\n' (that case does not reach this place) */
4734 o_addchr(&dest, '\\');
4735 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4736 o_addchr(&dest, ch);
4737 nommu_addchr(&ctx.as_string, ch);
4738 /* Example: echo Hello \2>file
4739 * we need to know that word 2 is quoted */
4740 dest.has_quoted_part = 1;
4743 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4744 debug_printf_parse("parse_stream parse error: "
4745 "parse_dollar returned 0 (error)\n");
4750 dest.has_quoted_part = 1;
4751 if (next == '\'' && !ctx.pending_redirect) {
4752 insert_empty_quoted_str_marker:
4753 nommu_addchr(&ctx.as_string, next);
4754 i_getch(input); /* eat second ' */
4755 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4756 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4759 ch = i_getch(input);
4761 syntax_error_unterm_ch('\'');
4764 nommu_addchr(&ctx.as_string, ch);
4767 o_addqchr(&dest, ch);
4772 dest.has_quoted_part = 1;
4773 if (next == '"' && !ctx.pending_redirect)
4774 goto insert_empty_quoted_str_marker;
4775 if (dest.o_assignment == NOT_ASSIGNMENT)
4776 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4777 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4779 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4781 #if ENABLE_HUSH_TICK
4783 USE_FOR_NOMMU(unsigned pos;)
4785 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4786 o_addchr(&dest, '`');
4787 USE_FOR_NOMMU(pos = dest.length;)
4788 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4791 o_addstr(&ctx.as_string, dest.data + pos);
4792 o_addchr(&ctx.as_string, '`');
4794 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4795 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4800 #if ENABLE_HUSH_CASE
4803 if (done_word(&dest, &ctx)) {
4806 done_pipe(&ctx, PIPE_SEQ);
4807 #if ENABLE_HUSH_CASE
4808 /* Eat multiple semicolons, detect
4809 * whether it means something special */
4814 ch = i_getch(input);
4815 nommu_addchr(&ctx.as_string, ch);
4816 if (ctx.ctx_res_w == RES_CASE_BODY) {
4817 ctx.ctx_dsemicolon = 1;
4818 ctx.ctx_res_w = RES_MATCH;
4824 /* We just finished a cmd. New one may start
4825 * with an assignment */
4826 dest.o_assignment = MAYBE_ASSIGNMENT;
4827 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4830 if (done_word(&dest, &ctx)) {
4834 ch = i_getch(input);
4835 nommu_addchr(&ctx.as_string, ch);
4836 done_pipe(&ctx, PIPE_AND);
4838 done_pipe(&ctx, PIPE_BG);
4842 if (done_word(&dest, &ctx)) {
4845 #if ENABLE_HUSH_CASE
4846 if (ctx.ctx_res_w == RES_MATCH)
4847 break; /* we are in case's "word | word)" */
4849 if (next == '|') { /* || */
4850 ch = i_getch(input);
4851 nommu_addchr(&ctx.as_string, ch);
4852 done_pipe(&ctx, PIPE_OR);
4854 /* we could pick up a file descriptor choice here
4855 * with redirect_opt_num(), but bash doesn't do it.
4856 * "echo foo 2| cat" yields "foo 2". */
4861 #if ENABLE_HUSH_CASE
4862 /* "case... in [(]word)..." - skip '(' */
4863 if (ctx.ctx_res_w == RES_MATCH
4864 && ctx.command->argv == NULL /* not (word|(... */
4865 && dest.length == 0 /* not word(... */
4866 && dest.has_quoted_part == 0 /* not ""(... */
4872 if (parse_group(&dest, &ctx, input, ch) != 0) {
4877 #if ENABLE_HUSH_CASE
4878 if (ctx.ctx_res_w == RES_MATCH)
4882 /* proper use of this character is caught by end_trigger:
4883 * if we see {, we call parse_group(..., end_trigger='}')
4884 * and it will match } earlier (not here). */
4885 syntax_error_unexpected_ch(ch);
4889 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4895 struct parse_context *pctx;
4896 IF_HAS_KEYWORDS(struct parse_context *p2;)
4898 /* Clean up allocated tree.
4899 * Sample for finding leaks on syntax error recovery path.
4900 * Run it from interactive shell, watch pmap `pidof hush`.
4901 * while if false; then false; fi; do break; fi
4902 * Samples to catch leaks at execution:
4903 * while if (true | {true;}); then echo ok; fi; do break; done
4904 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4908 /* Update pipe/command counts,
4909 * otherwise freeing may miss some */
4910 done_pipe(pctx, PIPE_SEQ);
4911 debug_printf_clean("freeing list %p from ctx %p\n",
4912 pctx->list_head, pctx);
4913 debug_print_tree(pctx->list_head, 0);
4914 free_pipe_list(pctx->list_head);
4915 debug_printf_clean("freed list %p\n", pctx->list_head);
4917 o_free_unsafe(&pctx->as_string);
4919 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4923 IF_HAS_KEYWORDS(pctx = p2;)
4924 } while (HAS_KEYWORDS && pctx);
4927 G.last_exitcode = 1;
4938 /*** Execution routines ***/
4940 /* Expansion can recurse, need forward decls: */
4941 #if !ENABLE_HUSH_BASH_COMPAT
4942 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4943 #define expand_string_to_string(str, do_unbackslash) \
4944 expand_string_to_string(str)
4946 static char *expand_string_to_string(const char *str, int do_unbackslash);
4947 #if ENABLE_HUSH_TICK
4948 static int process_command_subs(o_string *dest, const char *s);
4951 /* expand_strvec_to_strvec() takes a list of strings, expands
4952 * all variable references within and returns a pointer to
4953 * a list of expanded strings, possibly with larger number
4954 * of strings. (Think VAR="a b"; echo $VAR).
4955 * This new list is allocated as a single malloc block.
4956 * NULL-terminated list of char* pointers is at the beginning of it,
4957 * followed by strings themselves.
4958 * Caller can deallocate entire list by single free(list). */
4960 /* A horde of its helpers come first: */
4962 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4964 while (--len >= 0) {
4967 #if ENABLE_HUSH_BRACE_EXPANSION
4968 if (c == '{' || c == '}') {
4969 /* { -> \{, } -> \} */
4971 /* And now we want to add { or } and continue:
4974 * luckily, just falling throught achieves this.
4980 /* \z -> \\\z; \<eol> -> \\<eol> */
4985 o_addchr(o, *str++);
4991 /* Store given string, finalizing the word and starting new one whenever
4992 * we encounter IFS char(s). This is used for expanding variable values.
4993 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4994 * Return in *ended_with_ifs:
4995 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4997 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
4999 int last_is_ifs = 0;
5004 if (!*str) /* EOL - do not finalize word */
5006 word_len = strcspn(str, G.ifs);
5008 /* We have WORD_LEN leading non-IFS chars */
5009 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5010 o_addblock(output, str, word_len);
5012 /* Protect backslashes against globbing up :)
5013 * Example: "v='\*'; echo b$v" prints "b\*"
5014 * (and does not try to glob on "*")
5016 o_addblock_duplicate_backslash(output, str, word_len);
5017 /*/ Why can't we do it easier? */
5018 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5019 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5023 if (!*str) /* EOL - do not finalize word */
5027 /* We know str here points to at least one IFS char */
5029 str += strspn(str, G.ifs); /* skip IFS chars */
5030 if (!*str) /* EOL - do not finalize word */
5033 /* Start new word... but not always! */
5034 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5035 if (output->has_quoted_part
5036 /* Case "v=' a'; echo $v":
5037 * here nothing precedes the space in $v expansion,
5038 * therefore we should not finish the word
5039 * (IOW: if there *is* word to finalize, only then do it):
5041 || (n > 0 && output->data[output->length - 1])
5043 o_addchr(output, '\0');
5044 debug_print_list("expand_on_ifs", output, n);
5045 n = o_save_ptr(output, n);
5050 *ended_with_ifs = last_is_ifs;
5051 debug_print_list("expand_on_ifs[1]", output, n);
5055 /* Helper to expand $((...)) and heredoc body. These act as if
5056 * they are in double quotes, with the exception that they are not :).
5057 * Just the rules are similar: "expand only $var and `cmd`"
5059 * Returns malloced string.
5060 * As an optimization, we return NULL if expansion is not needed.
5062 #if !ENABLE_HUSH_BASH_COMPAT
5063 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5064 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5065 encode_then_expand_string(str)
5067 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5070 struct in_str input;
5071 o_string dest = NULL_O_STRING;
5073 if (!strchr(str, '$')
5074 && !strchr(str, '\\')
5075 #if ENABLE_HUSH_TICK
5076 && !strchr(str, '`')
5082 /* We need to expand. Example:
5083 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5085 setup_string_in_str(&input, str);
5086 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5087 //TODO: error check (encode_string returns 0 on error)?
5088 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5089 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5090 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5091 o_free_unsafe(&dest);
5095 #if ENABLE_SH_MATH_SUPPORT
5096 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5098 arith_state_t math_state;
5102 math_state.lookupvar = get_local_var_value;
5103 math_state.setvar = set_local_var_from_halves;
5104 //math_state.endofname = endofname;
5105 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5106 res = arith(&math_state, exp_str ? exp_str : arg);
5109 *errmsg_p = math_state.errmsg;
5110 if (math_state.errmsg)
5111 die_if_script(math_state.errmsg);
5116 #if ENABLE_HUSH_BASH_COMPAT
5117 /* ${var/[/]pattern[/repl]} helpers */
5118 static char *strstr_pattern(char *val, const char *pattern, int *size)
5121 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5122 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5129 /* Optimization: if "*pat" did not match the start of "string",
5130 * we know that "tring", "ring" etc will not match too:
5132 if (pattern[0] == '*')
5137 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5139 char *result = NULL;
5140 unsigned res_len = 0;
5141 unsigned repl_len = strlen(repl);
5145 char *s = strstr_pattern(val, pattern, &size);
5149 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5150 memcpy(result + res_len, val, s - val);
5152 strcpy(result + res_len, repl);
5153 res_len += repl_len;
5154 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5160 if (val[0] && result) {
5161 result = xrealloc(result, res_len + strlen(val) + 1);
5162 strcpy(result + res_len, val);
5163 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5165 debug_printf_varexp("result:'%s'\n", result);
5171 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5173 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5175 const char *val = NULL;
5176 char *to_be_freed = NULL;
5181 char exp_save = exp_save; /* for compiler */
5182 char *exp_saveptr; /* points to expansion operator */
5183 char *exp_word = exp_word; /* for compiler */
5186 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5188 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5190 first_char = arg[0] = arg0 & 0x7f;
5193 if (first_char == '#' /* ${#... */
5194 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5196 /* It must be length operator: ${#var} */
5200 /* Maybe handle parameter expansion */
5201 if (exp_saveptr /* if 2nd char is one of expansion operators */
5202 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5204 /* ${?:0}, ${#[:]%0} etc */
5205 exp_saveptr = var + 1;
5207 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5208 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5210 exp_op = exp_save = *exp_saveptr;
5212 exp_word = exp_saveptr + 1;
5213 if (exp_op == ':') {
5214 exp_op = *exp_word++;
5215 //TODO: try ${var:} and ${var:bogus} in non-bash config
5216 if (ENABLE_HUSH_BASH_COMPAT
5217 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5219 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5224 *exp_saveptr = '\0';
5225 } /* else: it's not an expansion op, but bare ${var} */
5228 /* Look up the variable in question */
5229 if (isdigit(var[0])) {
5230 /* parse_dollar should have vetted var for us */
5231 int n = xatoi_positive(var);
5232 if (n < G.global_argc)
5233 val = G.global_argv[n];
5234 /* else val remains NULL: $N with too big N */
5238 val = utoa(G.root_pid);
5240 case '!': /* bg pid */
5241 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5243 case '?': /* exitcode */
5244 val = utoa(G.last_exitcode);
5246 case '#': /* argc */
5247 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5250 val = get_local_var_value(var);
5254 /* Handle any expansions */
5255 if (exp_op == 'L') {
5256 reinit_unicode_for_hush();
5257 debug_printf_expand("expand: length(%s)=", val);
5258 val = utoa(val ? unicode_strlen(val) : 0);
5259 debug_printf_expand("%s\n", val);
5260 } else if (exp_op) {
5261 if (exp_op == '%' || exp_op == '#') {
5262 /* Standard-mandated substring removal ops:
5263 * ${parameter%word} - remove smallest suffix pattern
5264 * ${parameter%%word} - remove largest suffix pattern
5265 * ${parameter#word} - remove smallest prefix pattern
5266 * ${parameter##word} - remove largest prefix pattern
5268 * Word is expanded to produce a glob pattern.
5269 * Then var's value is matched to it and matching part removed.
5271 if (val && val[0]) {
5275 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5276 if (exp_op == *exp_word) /* ## or %% */
5278 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5280 exp_word = exp_exp_word;
5281 /* HACK ALERT. We depend here on the fact that
5282 * G.global_argv and results of utoa and get_local_var_value
5283 * are actually in writable memory:
5284 * scan_and_match momentarily stores NULs there. */
5286 loc = scan_and_match(t, exp_word, scan_flags);
5287 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5288 // exp_op, t, exp_word, loc);
5290 if (loc) { /* match was found */
5291 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5292 val = loc; /* take right part */
5294 val = to_be_freed = xstrndup(val, loc - val); /* left */
5298 #if ENABLE_HUSH_BASH_COMPAT
5299 else if (exp_op == '/' || exp_op == '\\') {
5300 /* It's ${var/[/]pattern[/repl]} thing.
5301 * Note that in encoded form it has TWO parts:
5302 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5303 * and if // is used, it is encoded as \:
5304 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5306 /* Empty variable always gives nothing: */
5307 // "v=''; echo ${v/*/w}" prints "", not "w"
5308 if (val && val[0]) {
5309 /* pattern uses non-standard expansion.
5310 * repl should be unbackslashed and globbed
5311 * by the usual expansion rules:
5313 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5314 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5315 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5316 * v='a bz'; echo ${v/a*z/\z} prints "z"
5317 * (note that a*z _pattern_ is never globbed!)
5319 char *pattern, *repl, *t;
5320 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5322 pattern = xstrdup(exp_word);
5323 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5324 *p++ = SPECIAL_VAR_SYMBOL;
5326 p = strchr(p, SPECIAL_VAR_SYMBOL);
5328 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5329 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5330 /* HACK ALERT. We depend here on the fact that
5331 * G.global_argv and results of utoa and get_local_var_value
5332 * are actually in writable memory:
5333 * replace_pattern momentarily stores NULs there. */
5335 to_be_freed = replace_pattern(t,
5337 (repl ? repl : exp_word),
5339 if (to_be_freed) /* at least one replace happened */
5346 else if (exp_op == ':') {
5347 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5348 /* It's ${var:N[:M]} bashism.
5349 * Note that in encoded form it has TWO parts:
5350 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5355 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5358 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5359 *p++ = SPECIAL_VAR_SYMBOL;
5361 p = strchr(p, SPECIAL_VAR_SYMBOL);
5363 len = expand_and_evaluate_arith(exp_word, &errmsg);
5366 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5367 if (len >= 0) { /* bash compat: len < 0 is illegal */
5368 if (beg < 0) /* bash compat */
5370 debug_printf_varexp("from val:'%s'\n", val);
5371 if (len == 0 || !val || beg >= strlen(val)) {
5375 /* Paranoia. What if user entered 9999999999999
5376 * which fits in arith_t but not int? */
5379 val = to_be_freed = xstrndup(val + beg, len);
5381 debug_printf_varexp("val:'%s'\n", val);
5385 die_if_script("malformed ${%s:...}", var);
5388 } else { /* one of "-=+?" */
5389 /* Standard-mandated substitution ops:
5390 * ${var?word} - indicate error if unset
5391 * If var is unset, word (or a message indicating it is unset
5392 * if word is null) is written to standard error
5393 * and the shell exits with a non-zero exit status.
5394 * Otherwise, the value of var is substituted.
5395 * ${var-word} - use default value
5396 * If var is unset, word is substituted.
5397 * ${var=word} - assign and use default value
5398 * If var is unset, word is assigned to var.
5399 * In all cases, final value of var is substituted.
5400 * ${var+word} - use alternative value
5401 * If var is unset, null is substituted.
5402 * Otherwise, word is substituted.
5404 * Word is subjected to tilde expansion, parameter expansion,
5405 * command substitution, and arithmetic expansion.
5406 * If word is not needed, it is not expanded.
5408 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5409 * but also treat null var as if it is unset.
5411 int use_word = (!val || ((exp_save == ':') && !val[0]));
5413 use_word = !use_word;
5414 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5415 (exp_save == ':') ? "true" : "false", use_word);
5417 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5419 exp_word = to_be_freed;
5420 if (exp_op == '?') {
5421 /* mimic bash message */
5422 die_if_script("%s: %s",
5424 exp_word[0] ? exp_word : "parameter null or not set"
5426 //TODO: how interactive bash aborts expansion mid-command?
5431 if (exp_op == '=') {
5432 /* ${var=[word]} or ${var:=[word]} */
5433 if (isdigit(var[0]) || var[0] == '#') {
5434 /* mimic bash message */
5435 die_if_script("$%s: cannot assign in this way", var);
5438 char *new_var = xasprintf("%s=%s", var, val);
5439 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5443 } /* one of "-=+?" */
5445 *exp_saveptr = exp_save;
5451 *to_be_freed_pp = to_be_freed;
5455 /* Expand all variable references in given string, adding words to list[]
5456 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5457 * to be filled). This routine is extremely tricky: has to deal with
5458 * variables/parameters with whitespace, $* and $@, and constructs like
5459 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5460 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5462 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5463 * expansion of right-hand side of assignment == 1-element expand.
5465 char cant_be_null = 0; /* only bit 0x80 matters */
5466 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5469 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5470 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5471 debug_print_list("expand_vars_to_list", output, n);
5472 n = o_save_ptr(output, n);
5473 debug_print_list("expand_vars_to_list[0]", output, n);
5475 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5477 char *to_be_freed = NULL;
5478 const char *val = NULL;
5479 #if ENABLE_HUSH_TICK
5480 o_string subst_result = NULL_O_STRING;
5482 #if ENABLE_SH_MATH_SUPPORT
5483 char arith_buf[sizeof(arith_t)*3 + 2];
5487 o_addchr(output, '\0');
5488 n = o_save_ptr(output, n);
5492 o_addblock(output, arg, p - arg);
5493 debug_print_list("expand_vars_to_list[1]", output, n);
5495 p = strchr(p, SPECIAL_VAR_SYMBOL);
5497 /* Fetch special var name (if it is indeed one of them)
5498 * and quote bit, force the bit on if singleword expansion -
5499 * important for not getting v=$@ expand to many words. */
5500 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5502 /* Is this variable quoted and thus expansion can't be null?
5503 * "$@" is special. Even if quoted, it can still
5504 * expand to nothing (not even an empty string),
5505 * thus it is excluded. */
5506 if ((first_ch & 0x7f) != '@')
5507 cant_be_null |= first_ch;
5509 switch (first_ch & 0x7f) {
5510 /* Highest bit in first_ch indicates that var is double-quoted */
5514 if (!G.global_argv[1])
5517 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5518 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5519 while (G.global_argv[i]) {
5520 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5521 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5522 if (G.global_argv[i++][0] && G.global_argv[i]) {
5523 /* this argv[] is not empty and not last:
5524 * put terminating NUL, start new word */
5525 o_addchr(output, '\0');
5526 debug_print_list("expand_vars_to_list[2]", output, n);
5527 n = o_save_ptr(output, n);
5528 debug_print_list("expand_vars_to_list[3]", output, n);
5532 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5533 * and in this case should treat it like '$*' - see 'else...' below */
5534 if (first_ch == ('@'|0x80) /* quoted $@ */
5535 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5538 o_addQstr(output, G.global_argv[i]);
5539 if (++i >= G.global_argc)
5541 o_addchr(output, '\0');
5542 debug_print_list("expand_vars_to_list[4]", output, n);
5543 n = o_save_ptr(output, n);
5545 } else { /* quoted $* (or v="$@" case): add as one word */
5547 o_addQstr(output, G.global_argv[i]);
5548 if (!G.global_argv[++i])
5551 o_addchr(output, G.ifs[0]);
5553 output->has_quoted_part = 1;
5557 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5558 /* "Empty variable", used to make "" etc to not disappear */
5559 output->has_quoted_part = 1;
5561 cant_be_null = 0x80;
5563 #if ENABLE_HUSH_TICK
5564 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5565 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5567 /* Can't just stuff it into output o_string,
5568 * expanded result may need to be globbed
5569 * and $IFS-splitted */
5570 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5571 G.last_exitcode = process_command_subs(&subst_result, arg);
5572 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5573 val = subst_result.data;
5576 #if ENABLE_SH_MATH_SUPPORT
5577 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5580 arg++; /* skip '+' */
5581 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5582 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5583 res = expand_and_evaluate_arith(arg, NULL);
5584 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5585 sprintf(arith_buf, ARITH_FMT, res);
5591 val = expand_one_var(&to_be_freed, arg, &p);
5592 IF_HUSH_TICK(store_val:)
5593 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5594 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5595 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5596 if (val && val[0]) {
5597 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5600 } else { /* quoted $VAR, val will be appended below */
5601 output->has_quoted_part = 1;
5602 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5603 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5606 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5608 if (val && val[0]) {
5609 o_addQstr(output, val);
5613 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5614 * Do the check to avoid writing to a const string. */
5615 if (*p != SPECIAL_VAR_SYMBOL)
5616 *p = SPECIAL_VAR_SYMBOL;
5618 #if ENABLE_HUSH_TICK
5619 o_free(&subst_result);
5622 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5626 o_addchr(output, '\0');
5627 n = o_save_ptr(output, n);
5629 debug_print_list("expand_vars_to_list[a]", output, n);
5630 /* this part is literal, and it was already pre-quoted
5631 * if needed (much earlier), do not use o_addQstr here! */
5632 o_addstr_with_NUL(output, arg);
5633 debug_print_list("expand_vars_to_list[b]", output, n);
5634 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5635 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5638 /* allow to reuse list[n] later without re-growth */
5639 output->has_empty_slot = 1;
5641 o_addchr(output, '\0');
5647 static char **expand_variables(char **argv, unsigned expflags)
5651 o_string output = NULL_O_STRING;
5653 output.o_expflags = expflags;
5657 n = expand_vars_to_list(&output, n, *argv);
5660 debug_print_list("expand_variables", &output, n);
5662 /* output.data (malloced in one block) gets returned in "list" */
5663 list = o_finalize_list(&output, n);
5664 debug_print_strings("expand_variables[1]", list);
5668 static char **expand_strvec_to_strvec(char **argv)
5670 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5673 #if ENABLE_HUSH_BASH_COMPAT
5674 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5676 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5680 /* Used for expansion of right hand of assignments,
5681 * $((...)), heredocs, variable espansion parts.
5683 * NB: should NOT do globbing!
5684 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5686 static char *expand_string_to_string(const char *str, int do_unbackslash)
5688 #if !ENABLE_HUSH_BASH_COMPAT
5689 const int do_unbackslash = 1;
5691 char *argv[2], **list;
5693 debug_printf_expand("string_to_string<='%s'\n", str);
5694 /* This is generally an optimization, but it also
5695 * handles "", which otherwise trips over !list[0] check below.
5696 * (is this ever happens that we actually get str="" here?)
5698 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5699 //TODO: Can use on strings with \ too, just unbackslash() them?
5700 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5701 return xstrdup(str);
5704 argv[0] = (char*)str;
5706 list = expand_variables(argv, do_unbackslash
5707 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5708 : EXP_FLAG_SINGLEWORD
5711 if (!list[0] || list[1])
5712 bb_error_msg_and_die("BUG in varexp2");
5713 /* actually, just move string 2*sizeof(char*) bytes back */
5714 overlapping_strcpy((char*)list, list[0]);
5716 unbackslash((char*)list);
5717 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5721 /* Used for "eval" builtin */
5722 static char* expand_strvec_to_string(char **argv)
5726 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5727 /* Convert all NULs to spaces */
5732 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5733 bb_error_msg_and_die("BUG in varexp3");
5734 /* bash uses ' ' regardless of $IFS contents */
5739 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
5740 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5744 static char **expand_assignments(char **argv, int count)
5749 G.expanded_assignments = p = NULL;
5750 /* Expand assignments into one string each */
5751 for (i = 0; i < count; i++) {
5752 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5754 G.expanded_assignments = NULL;
5759 static void switch_off_special_sigs(unsigned mask)
5762 while ((mask >>= 1) != 0) {
5767 if (G.traps[sig] && !G.traps[sig][0])
5768 /* trap is '', has to remain SIG_IGN */
5771 G.traps[sig] = NULL;
5773 /* We are here only if no trap or trap was not '' */
5774 install_sighandler(sig, SIG_DFL);
5780 void re_execute_shell(char ***to_free, const char *s,
5781 char *g_argv0, char **g_argv,
5782 char **builtin_argv) NORETURN;
5784 static void reset_traps_to_defaults(void)
5786 /* This function is always called in a child shell
5787 * after fork (not vfork, NOMMU doesn't use this function).
5792 /* Child shells are not interactive.
5793 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5794 * Testcase: (while :; do :; done) + ^Z should background.
5795 * Same goes for SIGTERM, SIGHUP, SIGINT.
5797 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5798 if (!G.traps && !mask)
5799 return; /* already no traps and no special sigs */
5801 /* Switch off special sigs */
5802 switch_off_special_sigs(mask);
5804 G_fatal_sig_mask = 0;
5806 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5807 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5808 * remain set in G.special_sig_mask */
5813 /* Reset all sigs to default except ones with empty traps */
5814 for (sig = 0; sig < NSIG; sig++) {
5816 continue; /* no trap: nothing to do */
5817 if (!G.traps[sig][0])
5818 continue; /* empty trap: has to remain SIG_IGN */
5819 /* sig has non-empty trap, reset it: */
5821 G.traps[sig] = NULL;
5822 /* There is no signal for trap 0 (EXIT) */
5825 install_sighandler(sig, pick_sighandler(sig));
5831 static void re_execute_shell(char ***to_free, const char *s,
5832 char *g_argv0, char **g_argv,
5833 char **builtin_argv) NORETURN;
5834 static void re_execute_shell(char ***to_free, const char *s,
5835 char *g_argv0, char **g_argv,
5836 char **builtin_argv)
5838 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5839 /* delims + 2 * (number of bytes in printed hex numbers) */
5840 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5841 char *heredoc_argv[4];
5842 struct variable *cur;
5843 # if ENABLE_HUSH_FUNCTIONS
5844 struct function *funcp;
5848 unsigned long long empty_trap_mask;
5850 if (!g_argv0) { /* heredoc */
5851 argv = heredoc_argv;
5852 argv[0] = (char *) G.argv0_for_re_execing;
5853 argv[1] = (char *) "-<";
5854 argv[2] = (char *) s;
5856 pp = &argv[3]; /* used as pointer to empty environment */
5862 if (pp) while (*pp++)
5865 empty_trap_mask = 0;
5868 for (sig = 1; sig < NSIG; sig++) {
5869 if (G.traps[sig] && !G.traps[sig][0])
5870 empty_trap_mask |= 1LL << sig;
5874 sprintf(param_buf, NOMMU_HACK_FMT
5875 , (unsigned) G.root_pid
5876 , (unsigned) G.root_ppid
5877 , (unsigned) G.last_bg_pid
5878 , (unsigned) G.last_exitcode
5881 IF_HUSH_LOOPS(, G.depth_of_loop)
5883 # undef NOMMU_HACK_FMT
5884 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5885 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5888 for (cur = G.top_var; cur; cur = cur->next) {
5889 if (!cur->flg_export || cur->flg_read_only)
5892 # if ENABLE_HUSH_FUNCTIONS
5893 for (funcp = G.top_func; funcp; funcp = funcp->next)
5899 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5900 *pp++ = (char *) G.argv0_for_re_execing;
5902 for (cur = G.top_var; cur; cur = cur->next) {
5903 if (strcmp(cur->varstr, hush_version_str) == 0)
5905 if (cur->flg_read_only) {
5906 *pp++ = (char *) "-R";
5907 *pp++ = cur->varstr;
5908 } else if (!cur->flg_export) {
5909 *pp++ = (char *) "-V";
5910 *pp++ = cur->varstr;
5913 # if ENABLE_HUSH_FUNCTIONS
5914 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5915 *pp++ = (char *) "-F";
5916 *pp++ = funcp->name;
5917 *pp++ = funcp->body_as_string;
5920 /* We can pass activated traps here. Say, -Tnn:trap_string
5922 * However, POSIX says that subshells reset signals with traps
5924 * I tested bash-3.2 and it not only does that with true subshells
5925 * of the form ( list ), but with any forked children shells.
5926 * I set trap "echo W" WINCH; and then tried:
5928 * { echo 1; sleep 20; echo 2; } &
5929 * while true; do echo 1; sleep 20; echo 2; break; done &
5930 * true | { echo 1; sleep 20; echo 2; } | cat
5932 * In all these cases sending SIGWINCH to the child shell
5933 * did not run the trap. If I add trap "echo V" WINCH;
5934 * _inside_ group (just before echo 1), it works.
5936 * I conclude it means we don't need to pass active traps here.
5938 *pp++ = (char *) "-c";
5941 while (*++builtin_argv)
5942 *pp++ = *builtin_argv;
5943 *pp++ = (char *) "";
5948 /* *pp = NULL; - is already there */
5952 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5953 /* Don't propagate SIG_IGN to the child */
5954 if (SPECIAL_JOBSTOP_SIGS != 0)
5955 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5956 execve(bb_busybox_exec_path, argv, pp);
5957 /* Fallback. Useful for init=/bin/hush usage etc */
5958 if (argv[0][0] == '/')
5959 execve(argv[0], argv, pp);
5960 xfunc_error_retval = 127;
5961 bb_error_msg_and_die("can't re-execute the shell");
5963 #endif /* !BB_MMU */
5966 static int run_and_free_list(struct pipe *pi);
5968 /* Executing from string: eval, sh -c '...'
5969 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5970 * end_trigger controls how often we stop parsing
5971 * NUL: parse all, execute, return
5972 * ';': parse till ';' or newline, execute, repeat till EOF
5974 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5976 /* Why we need empty flag?
5977 * An obscure corner case "false; ``; echo $?":
5978 * empty command in `` should still set $? to 0.
5979 * But we can't just set $? to 0 at the start,
5980 * this breaks "false; echo `echo $?`" case.
5984 struct pipe *pipe_list;
5986 #if ENABLE_HUSH_INTERACTIVE
5987 if (end_trigger == ';')
5988 inp->promptmode = 0; /* PS1 */
5990 pipe_list = parse_stream(NULL, inp, end_trigger);
5991 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5992 /* If we are in "big" script
5993 * (not in `cmd` or something similar)...
5995 if (pipe_list == ERR_PTR && end_trigger == ';') {
5996 /* Discard cached input (rest of line) */
5997 int ch = inp->last_char;
5998 while (ch != EOF && ch != '\n') {
5999 //bb_error_msg("Discarded:'%c'", ch);
6004 /* This stream isn't empty */
6008 if (!pipe_list && empty)
6009 G.last_exitcode = 0;
6012 debug_print_tree(pipe_list, 0);
6013 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6014 run_and_free_list(pipe_list);
6016 #if ENABLE_HUSH_FUNCTIONS
6017 if (G.flag_return_in_progress == 1)
6023 static void parse_and_run_string(const char *s)
6025 struct in_str input;
6026 setup_string_in_str(&input, s);
6027 parse_and_run_stream(&input, '\0');
6030 static void parse_and_run_file(FILE *f)
6032 struct in_str input;
6033 setup_file_in_str(&input, f);
6034 parse_and_run_stream(&input, ';');
6037 #if ENABLE_HUSH_TICK
6038 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6043 char **to_free = NULL;
6047 pid = BB_MMU ? xfork() : xvfork();
6048 if (pid == 0) { /* child */
6049 disable_restore_tty_pgrp_on_exit();
6050 /* Process substitution is not considered to be usual
6051 * 'command execution'.
6052 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6059 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6060 close(channel[0]); /* NB: close _first_, then move fd! */
6061 xmove_fd(channel[1], 1);
6062 /* Prevent it from trying to handle ctrl-z etc */
6063 IF_HUSH_JOB(G.run_list_level = 1;)
6064 /* Awful hack for `trap` or $(trap).
6066 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6067 * contains an example where "trap" is executed in a subshell:
6069 * save_traps=$(trap)
6071 * eval "$save_traps"
6073 * Standard does not say that "trap" in subshell shall print
6074 * parent shell's traps. It only says that its output
6075 * must have suitable form, but then, in the above example
6076 * (which is not supposed to be normative), it implies that.
6078 * bash (and probably other shell) does implement it
6079 * (traps are reset to defaults, but "trap" still shows them),
6080 * but as a result, "trap" logic is hopelessly messed up:
6083 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6084 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6085 * # true | trap <--- trap is in subshell - no output (ditto)
6086 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6087 * trap -- 'echo Ho' SIGWINCH
6088 * # echo `(trap)` <--- in subshell in subshell - output
6089 * trap -- 'echo Ho' SIGWINCH
6090 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6091 * trap -- 'echo Ho' SIGWINCH
6093 * The rules when to forget and when to not forget traps
6094 * get really complex and nonsensical.
6096 * Our solution: ONLY bare $(trap) or `trap` is special.
6098 s = skip_whitespace(s);
6099 if (is_prefixed_with(s, "trap")
6100 && skip_whitespace(s + 4)[0] == '\0'
6102 static const char *const argv[] = { NULL, NULL };
6103 builtin_trap((char**)argv);
6104 fflush_all(); /* important */
6108 reset_traps_to_defaults();
6109 parse_and_run_string(s);
6110 _exit(G.last_exitcode);
6112 /* We re-execute after vfork on NOMMU. This makes this script safe:
6113 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6114 * huge=`cat BIG` # was blocking here forever
6117 re_execute_shell(&to_free,
6127 # if ENABLE_HUSH_FAST
6129 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6130 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6131 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6133 enable_restore_tty_pgrp_on_exit();
6138 return remember_FILE(xfdopen_for_read(channel[0]));
6141 /* Return code is exit status of the process that is run. */
6142 static int process_command_subs(o_string *dest, const char *s)
6145 struct in_str pipe_str;
6147 int status, ch, eol_cnt;
6149 fp = generate_stream_from_string(s, &pid);
6151 /* Now send results of command back into original context */
6152 setup_file_in_str(&pipe_str, fp);
6154 while ((ch = i_getch(&pipe_str)) != EOF) {
6160 o_addchr(dest, '\n');
6163 o_addQchr(dest, ch);
6166 debug_printf("done reading from `cmd` pipe, closing it\n");
6167 fclose_and_forget(fp);
6168 /* We need to extract exitcode. Test case
6169 * "true; echo `sleep 1; false` $?"
6171 safe_waitpid(pid, &status, 0);
6172 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6173 return WEXITSTATUS(status);
6175 #endif /* ENABLE_HUSH_TICK */
6178 static void setup_heredoc(struct redir_struct *redir)
6180 struct fd_pair pair;
6183 /* the _body_ of heredoc (misleading field name) */
6184 const char *heredoc = redir->rd_filename;
6191 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6192 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6196 len = strlen(heredoc);
6198 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6200 xmove_fd(pair.rd, redir->rd_fd);
6202 /* Try writing without forking. Newer kernels have
6203 * dynamically growing pipes. Must use non-blocking write! */
6206 written = write(pair.wr, heredoc, len);
6217 ndelay_off(pair.wr);
6219 /* Okay, pipe buffer was not big enough */
6220 /* Note: we must not create a stray child (bastard? :)
6221 * for the unsuspecting parent process. Child creates a grandchild
6222 * and exits before parent execs the process which consumes heredoc
6223 * (that exec happens after we return from this function) */
6230 disable_restore_tty_pgrp_on_exit();
6231 pid = BB_MMU ? xfork() : xvfork();
6235 close(redir->rd_fd); /* read side of the pipe */
6237 full_write(pair.wr, heredoc, len); /* may loop or block */
6240 /* Delegate blocking writes to another process */
6241 xmove_fd(pair.wr, STDOUT_FILENO);
6242 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6246 #if ENABLE_HUSH_FAST
6248 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6250 enable_restore_tty_pgrp_on_exit();
6256 wait(NULL); /* wait till child has died */
6259 /* fd: redirect wants this fd to be used (e.g. 3>file).
6260 * Move all conflicting internally used fds,
6261 * and remember them so that we can restore them later.
6263 static int save_fds_on_redirect(int fd, int squirrel[3])
6266 /* Handle redirects of fds 0,1,2 */
6268 /* If we collide with an already moved stdio fd... */
6269 if (fd == squirrel[0]) {
6270 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6273 if (fd == squirrel[1]) {
6274 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6277 if (fd == squirrel[2]) {
6278 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6281 /* If we are about to redirect stdio fd, and did not yet move it... */
6282 if (fd <= 2 && squirrel[fd] < 0) {
6283 /* We avoid taking stdio fds */
6284 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6285 if (squirrel[fd] < 0 && errno != EBADF)
6287 return 0; /* "we did not close fd" */
6291 #if ENABLE_HUSH_INTERACTIVE
6292 if (fd != 0 && fd == G.interactive_fd) {
6293 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6298 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6299 * (1) Redirect in a forked child. No need to save FILEs' fds,
6300 * we aren't going to use them anymore, ok to trash.
6301 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6302 * but how are we doing to use them?
6303 * "fileno(fd) = new_fd" can't be done.
6308 return save_FILEs_on_redirect(fd);
6311 static void restore_redirects(int squirrel[3])
6314 for (i = 0; i <= 2; i++) {
6317 /* We simply die on error */
6322 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6324 restore_redirected_FILEs();
6327 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6328 * and stderr if they are redirected. */
6329 static int setup_redirects(struct command *prog, int squirrel[])
6332 struct redir_struct *redir;
6334 for (redir = prog->redirects; redir; redir = redir->next) {
6335 if (redir->rd_type == REDIRECT_HEREDOC2) {
6336 /* "rd_fd<<HERE" case */
6337 save_fds_on_redirect(redir->rd_fd, squirrel);
6338 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6340 debug_printf_parse("set heredoc '%s'\n",
6341 redir->rd_filename);
6342 setup_heredoc(redir);
6346 if (redir->rd_dup == REDIRFD_TO_FILE) {
6347 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6349 if (redir->rd_filename == NULL) {
6352 * "cmd >" (no filename)
6353 * "cmd > <file" (2nd redirect starts too early)
6355 die_if_script("syntax error: %s", "invalid redirect");
6358 mode = redir_table[redir->rd_type].mode;
6359 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6360 openfd = open_or_warn(p, mode);
6363 /* Error message from open_or_warn can be lost
6364 * if stderr has been redirected, but bash
6365 * and ash both lose it as well
6366 * (though zsh doesn't!)
6371 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6372 openfd = redir->rd_dup;
6375 if (openfd != redir->rd_fd) {
6376 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6377 if (openfd == REDIRFD_CLOSE) {
6378 /* "rd_fd >&-" means "close me" */
6380 /* ^^^ optimization: saving may already
6381 * have closed it. If not... */
6382 close(redir->rd_fd);
6385 xdup2(openfd, redir->rd_fd);
6386 if (redir->rd_dup == REDIRFD_TO_FILE)
6387 /* "rd_fd > FILE" */
6389 /* else: "rd_fd > rd_dup" */
6396 static char *find_in_path(const char *arg)
6399 const char *PATH = get_local_var_value("PATH");
6405 const char *end = strchrnul(PATH, ':');
6406 int sz = end - PATH; /* must be int! */
6410 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6412 /* We have xxx::yyyy in $PATH,
6413 * it means "use current dir" */
6416 if (access(ret, F_OK) == 0)
6429 static const struct built_in_command *find_builtin_helper(const char *name,
6430 const struct built_in_command *x,
6431 const struct built_in_command *end)
6434 if (strcmp(name, x->b_cmd) != 0) {
6438 debug_printf_exec("found builtin '%s'\n", name);
6443 static const struct built_in_command *find_builtin1(const char *name)
6445 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6447 static const struct built_in_command *find_builtin(const char *name)
6449 const struct built_in_command *x = find_builtin1(name);
6452 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6455 #if ENABLE_HUSH_FUNCTIONS
6456 static struct function **find_function_slot(const char *name)
6458 struct function **funcpp = &G.top_func;
6460 if (strcmp(name, (*funcpp)->name) == 0) {
6463 funcpp = &(*funcpp)->next;
6468 static const struct function *find_function(const char *name)
6470 const struct function *funcp = *find_function_slot(name);
6472 debug_printf_exec("found function '%s'\n", name);
6476 /* Note: takes ownership on name ptr */
6477 static struct function *new_function(char *name)
6479 struct function **funcpp = find_function_slot(name);
6480 struct function *funcp = *funcpp;
6482 if (funcp != NULL) {
6483 struct command *cmd = funcp->parent_cmd;
6484 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6486 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6488 /* Note: if !funcp->body, do not free body_as_string!
6489 * This is a special case of "-F name body" function:
6490 * body_as_string was not malloced! */
6492 free_pipe_list(funcp->body);
6494 free(funcp->body_as_string);
6498 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6499 cmd->argv[0] = funcp->name;
6500 cmd->group = funcp->body;
6502 cmd->group_as_string = funcp->body_as_string;
6506 debug_printf_exec("remembering new function '%s'\n", name);
6507 funcp = *funcpp = xzalloc(sizeof(*funcp));
6508 /*funcp->next = NULL;*/
6515 static void unset_func(const char *name)
6517 struct function **funcpp = find_function_slot(name);
6518 struct function *funcp = *funcpp;
6520 if (funcp != NULL) {
6521 debug_printf_exec("freeing function '%s'\n", funcp->name);
6522 *funcpp = funcp->next;
6523 /* funcp is unlinked now, deleting it.
6524 * Note: if !funcp->body, the function was created by
6525 * "-F name body", do not free ->body_as_string
6526 * and ->name as they were not malloced. */
6528 free_pipe_list(funcp->body);
6531 free(funcp->body_as_string);
6539 #define exec_function(to_free, funcp, argv) \
6540 exec_function(funcp, argv)
6542 static void exec_function(char ***to_free,
6543 const struct function *funcp,
6544 char **argv) NORETURN;
6545 static void exec_function(char ***to_free,
6546 const struct function *funcp,
6552 argv[0] = G.global_argv[0];
6553 G.global_argv = argv;
6557 /* On MMU, funcp->body is always non-NULL */
6558 n = run_list(funcp->body);
6562 re_execute_shell(to_free,
6563 funcp->body_as_string,
6570 static int run_function(const struct function *funcp, char **argv)
6576 save_and_replace_G_args(&sv, argv);
6578 /* "we are in function, ok to use return" */
6579 sv_flg = G.flag_return_in_progress;
6580 G.flag_return_in_progress = -1;
6581 # if ENABLE_HUSH_LOCAL
6582 G.func_nest_level++;
6585 /* On MMU, funcp->body is always non-NULL */
6588 /* Function defined by -F */
6589 parse_and_run_string(funcp->body_as_string);
6590 rc = G.last_exitcode;
6594 rc = run_list(funcp->body);
6597 # if ENABLE_HUSH_LOCAL
6599 struct variable *var;
6600 struct variable **var_pp;
6602 var_pp = &G.top_var;
6603 while ((var = *var_pp) != NULL) {
6604 if (var->func_nest_level < G.func_nest_level) {
6605 var_pp = &var->next;
6609 if (var->flg_export)
6610 bb_unsetenv(var->varstr);
6611 /* Remove from global list */
6612 *var_pp = var->next;
6618 G.func_nest_level--;
6621 G.flag_return_in_progress = sv_flg;
6623 restore_G_args(&sv, argv);
6627 #endif /* ENABLE_HUSH_FUNCTIONS */
6631 #define exec_builtin(to_free, x, argv) \
6632 exec_builtin(x, argv)
6634 #define exec_builtin(to_free, x, argv) \
6635 exec_builtin(to_free, argv)
6637 static void exec_builtin(char ***to_free,
6638 const struct built_in_command *x,
6639 char **argv) NORETURN;
6640 static void exec_builtin(char ***to_free,
6641 const struct built_in_command *x,
6647 rcode = x->b_function(argv);
6652 /* On NOMMU, we must never block!
6653 * Example: { sleep 99 | read line; } & echo Ok
6655 re_execute_shell(to_free,
6664 static void execvp_or_die(char **argv) NORETURN;
6665 static void execvp_or_die(char **argv)
6667 debug_printf_exec("execing '%s'\n", argv[0]);
6668 /* Don't propagate SIG_IGN to the child */
6669 if (SPECIAL_JOBSTOP_SIGS != 0)
6670 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6671 execvp(argv[0], argv);
6672 bb_perror_msg("can't execute '%s'", argv[0]);
6673 _exit(127); /* bash compat */
6676 #if ENABLE_HUSH_MODE_X
6677 static void dump_cmd_in_x_mode(char **argv)
6679 if (G_x_mode && argv) {
6680 /* We want to output the line in one write op */
6688 len += strlen(argv[n++]) + 1;
6694 p += sprintf(p, " %s", argv[n++]);
6702 # define dump_cmd_in_x_mode(argv) ((void)0)
6706 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6707 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6708 #define pseudo_exec(nommu_save, command, argv_expanded) \
6709 pseudo_exec(command, argv_expanded)
6712 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6714 * Don't exit() here. If you don't exec, use _exit instead.
6715 * The at_exit handlers apparently confuse the calling process,
6716 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6718 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6719 char **argv, int assignment_cnt,
6720 char **argv_expanded) NORETURN;
6721 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6722 char **argv, int assignment_cnt,
6723 char **argv_expanded)
6727 new_env = expand_assignments(argv, assignment_cnt);
6728 dump_cmd_in_x_mode(new_env);
6730 if (!argv[assignment_cnt]) {
6731 /* Case when we are here: ... | var=val | ...
6732 * (note that we do not exit early, i.e., do not optimize out
6733 * expand_assignments(): think about ... | var=`sleep 1` | ...
6735 free_strings(new_env);
6736 _exit(EXIT_SUCCESS);
6740 set_vars_and_save_old(new_env);
6741 free(new_env); /* optional */
6742 /* we can also destroy set_vars_and_save_old's return value,
6745 nommu_save->new_env = new_env;
6746 nommu_save->old_vars = set_vars_and_save_old(new_env);
6749 if (argv_expanded) {
6750 argv = argv_expanded;
6752 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6754 nommu_save->argv = argv;
6757 dump_cmd_in_x_mode(argv);
6759 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6760 if (strchr(argv[0], '/') != NULL)
6764 /* Check if the command matches any of the builtins.
6765 * Depending on context, this might be redundant. But it's
6766 * easier to waste a few CPU cycles than it is to figure out
6767 * if this is one of those cases.
6770 /* On NOMMU, it is more expensive to re-execute shell
6771 * just in order to run echo or test builtin.
6772 * It's better to skip it here and run corresponding
6773 * non-builtin later. */
6774 const struct built_in_command *x;
6775 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6777 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6780 #if ENABLE_HUSH_FUNCTIONS
6781 /* Check if the command matches any functions */
6783 const struct function *funcp = find_function(argv[0]);
6785 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6790 #if ENABLE_FEATURE_SH_STANDALONE
6791 /* Check if the command matches any busybox applets */
6793 int a = find_applet_by_name(argv[0]);
6795 # if BB_MMU /* see above why on NOMMU it is not allowed */
6796 if (APPLET_IS_NOEXEC(a)) {
6797 /* Do not leak open fds from opened script files etc */
6798 close_all_FILE_list();
6799 debug_printf_exec("running applet '%s'\n", argv[0]);
6800 run_applet_no_and_exit(a, argv);
6803 /* Re-exec ourselves */
6804 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6805 /* Don't propagate SIG_IGN to the child */
6806 if (SPECIAL_JOBSTOP_SIGS != 0)
6807 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6808 execv(bb_busybox_exec_path, argv);
6809 /* If they called chroot or otherwise made the binary no longer
6810 * executable, fall through */
6815 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6818 execvp_or_die(argv);
6821 /* Called after [v]fork() in run_pipe
6823 static void pseudo_exec(nommu_save_t *nommu_save,
6824 struct command *command,
6825 char **argv_expanded) NORETURN;
6826 static void pseudo_exec(nommu_save_t *nommu_save,
6827 struct command *command,
6828 char **argv_expanded)
6830 if (command->argv) {
6831 pseudo_exec_argv(nommu_save, command->argv,
6832 command->assignment_cnt, argv_expanded);
6835 if (command->group) {
6836 /* Cases when we are here:
6839 * ... | ( list ) | ...
6840 * ... | { list } | ...
6844 debug_printf_exec("pseudo_exec: run_list\n");
6845 reset_traps_to_defaults();
6846 rcode = run_list(command->group);
6847 /* OK to leak memory by not calling free_pipe_list,
6848 * since this process is about to exit */
6851 re_execute_shell(&nommu_save->argv_from_re_execing,
6852 command->group_as_string,
6859 /* Case when we are here: ... | >file */
6860 debug_printf_exec("pseudo_exec'ed null command\n");
6861 _exit(EXIT_SUCCESS);
6865 static const char *get_cmdtext(struct pipe *pi)
6871 /* This is subtle. ->cmdtext is created only on first backgrounding.
6872 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6873 * On subsequent bg argv is trashed, but we won't use it */
6876 argv = pi->cmds[0].argv;
6877 if (!argv || !argv[0]) {
6878 pi->cmdtext = xzalloc(1);
6884 len += strlen(*argv) + 1;
6888 argv = pi->cmds[0].argv;
6890 len = strlen(*argv);
6891 memcpy(p, *argv, len);
6899 static void insert_bg_job(struct pipe *pi)
6901 struct pipe *job, **jobp;
6904 /* Linear search for the ID of the job to use */
6906 for (job = G.job_list; job; job = job->next)
6907 if (job->jobid >= pi->jobid)
6908 pi->jobid = job->jobid + 1;
6910 /* Add job to the list of running jobs */
6912 while ((job = *jobp) != NULL)
6914 job = *jobp = xmalloc(sizeof(*job));
6916 *job = *pi; /* physical copy */
6918 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6919 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6920 for (i = 0; i < pi->num_cmds; i++) {
6921 job->cmds[i].pid = pi->cmds[i].pid;
6922 /* all other fields are not used and stay zero */
6924 job->cmdtext = xstrdup(get_cmdtext(pi));
6926 if (G_interactive_fd)
6927 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6928 G.last_jobid = job->jobid;
6931 static void remove_bg_job(struct pipe *pi)
6933 struct pipe *prev_pipe;
6935 if (pi == G.job_list) {
6936 G.job_list = pi->next;
6938 prev_pipe = G.job_list;
6939 while (prev_pipe->next != pi)
6940 prev_pipe = prev_pipe->next;
6941 prev_pipe->next = pi->next;
6944 G.last_jobid = G.job_list->jobid;
6949 /* Remove a backgrounded job */
6950 static void delete_finished_bg_job(struct pipe *pi)
6957 /* Check to see if any processes have exited -- if they
6958 * have, figure out why and see if a job has completed */
6959 static int checkjobs(struct pipe *fg_pipe)
6969 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6971 attributes = WUNTRACED;
6972 if (fg_pipe == NULL)
6973 attributes |= WNOHANG;
6976 #if ENABLE_HUSH_FAST
6977 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6978 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6979 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6980 /* There was neither fork nor SIGCHLD since last waitpid */
6981 /* Avoid doing waitpid syscall if possible */
6982 if (!G.we_have_children) {
6986 if (fg_pipe == NULL) { /* is WNOHANG set? */
6987 /* We have children, but they did not exit
6988 * or stop yet (we saw no SIGCHLD) */
6991 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6995 /* Do we do this right?
6996 * bash-3.00# sleep 20 | false
6998 * [3]+ Stopped sleep 20 | false
6999 * bash-3.00# echo $?
7000 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7001 * [hush 1.14.0: yes we do it right]
7008 #if ENABLE_HUSH_FAST
7009 i = G.count_SIGCHLD;
7011 childpid = waitpid(-1, &status, attributes);
7012 if (childpid <= 0) {
7013 if (childpid && errno != ECHILD)
7014 bb_perror_msg("waitpid");
7015 #if ENABLE_HUSH_FAST
7016 else { /* Until next SIGCHLD, waitpid's are useless */
7017 G.we_have_children = (childpid == 0);
7018 G.handled_SIGCHLD = i;
7019 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7024 dead = WIFEXITED(status) || WIFSIGNALED(status);
7027 if (WIFSTOPPED(status))
7028 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7029 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7030 if (WIFSIGNALED(status))
7031 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7032 childpid, WTERMSIG(status), WEXITSTATUS(status));
7033 if (WIFEXITED(status))
7034 debug_printf_jobs("pid %d exited, exitcode %d\n",
7035 childpid, WEXITSTATUS(status));
7037 /* Were we asked to wait for fg pipe? */
7039 i = fg_pipe->num_cmds;
7041 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7042 if (fg_pipe->cmds[i].pid != childpid)
7046 fg_pipe->cmds[i].pid = 0;
7047 fg_pipe->alive_cmds--;
7048 ex = WEXITSTATUS(status);
7049 /* bash prints killer signal's name for *last*
7050 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7051 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7053 if (WIFSIGNALED(status)) {
7054 int sig = WTERMSIG(status);
7055 if (i == fg_pipe->num_cmds-1)
7056 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7057 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7058 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7059 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7060 * Maybe we need to use sig | 128? */
7063 fg_pipe->cmds[i].cmd_exitcode = ex;
7065 fg_pipe->stopped_cmds++;
7067 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7068 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7069 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
7070 /* All processes in fg pipe have exited or stopped */
7071 i = fg_pipe->num_cmds;
7073 rcode = fg_pipe->cmds[i].cmd_exitcode;
7074 /* usually last process gives overall exitstatus,
7075 * but with "set -o pipefail", last *failed* process does */
7076 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7079 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
7080 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7081 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7082 * and "killall -STOP cat" */
7083 if (G_interactive_fd) {
7085 if (fg_pipe->alive_cmds != 0)
7086 insert_bg_job(fg_pipe);
7090 if (fg_pipe->alive_cmds == 0)
7093 /* There are still running processes in the fg pipe */
7094 goto wait_more; /* do waitpid again */
7096 /* it wasnt fg_pipe, look for process in bg pipes */
7100 /* We asked to wait for bg or orphaned children */
7101 /* No need to remember exitcode in this case */
7102 for (pi = G.job_list; pi; pi = pi->next) {
7103 for (i = 0; i < pi->num_cmds; i++) {
7104 if (pi->cmds[i].pid == childpid)
7105 goto found_pi_and_prognum;
7108 /* Happens when shell is used as init process (init=/bin/sh) */
7109 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7110 continue; /* do waitpid again */
7112 found_pi_and_prognum:
7115 pi->cmds[i].pid = 0;
7117 if (!pi->alive_cmds) {
7118 if (G_interactive_fd)
7119 printf(JOB_STATUS_FORMAT, pi->jobid,
7120 "Done", pi->cmdtext);
7121 delete_finished_bg_job(pi);
7128 } /* while (waitpid succeeds)... */
7134 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7137 int rcode = checkjobs(fg_pipe);
7138 if (G_saved_tty_pgrp) {
7139 /* Job finished, move the shell to the foreground */
7140 p = getpgrp(); /* our process group id */
7141 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7142 tcsetpgrp(G_interactive_fd, p);
7148 /* Start all the jobs, but don't wait for anything to finish.
7151 * Return code is normally -1, when the caller has to wait for children
7152 * to finish to determine the exit status of the pipe. If the pipe
7153 * is a simple builtin command, however, the action is done by the
7154 * time run_pipe returns, and the exit code is provided as the
7157 * Returns -1 only if started some children. IOW: we have to
7158 * mask out retvals of builtins etc with 0xff!
7160 * The only case when we do not need to [v]fork is when the pipe
7161 * is single, non-backgrounded, non-subshell command. Examples:
7162 * cmd ; ... { list } ; ...
7163 * cmd && ... { list } && ...
7164 * cmd || ... { list } || ...
7165 * If it is, then we can run cmd as a builtin, NOFORK,
7166 * or (if SH_STANDALONE) an applet, and we can run the { list }
7167 * with run_list. If it isn't one of these, we fork and exec cmd.
7169 * Cases when we must fork:
7170 * non-single: cmd | cmd
7171 * backgrounded: cmd & { list } &
7172 * subshell: ( list ) [&]
7174 #if !ENABLE_HUSH_MODE_X
7175 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7176 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7178 static int redirect_and_varexp_helper(char ***new_env_p,
7179 struct variable **old_vars_p,
7180 struct command *command,
7182 char **argv_expanded)
7184 /* setup_redirects acts on file descriptors, not FILEs.
7185 * This is perfect for work that comes after exec().
7186 * Is it really safe for inline use? Experimentally,
7187 * things seem to work. */
7188 int rcode = setup_redirects(command, squirrel);
7190 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7191 *new_env_p = new_env;
7192 dump_cmd_in_x_mode(new_env);
7193 dump_cmd_in_x_mode(argv_expanded);
7195 *old_vars_p = set_vars_and_save_old(new_env);
7199 static NOINLINE int run_pipe(struct pipe *pi)
7201 static const char *const null_ptr = NULL;
7205 struct command *command;
7206 char **argv_expanded;
7208 /* it is not always needed, but we aim to smaller code */
7209 int squirrel[] = { -1, -1, -1 };
7212 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7215 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7216 * Result should be 3 lines: q w e, qwe, q w e
7218 G.ifs = get_local_var_value("IFS");
7222 IF_HUSH_JOB(pi->pgrp = -1;)
7223 pi->stopped_cmds = 0;
7224 command = &pi->cmds[0];
7225 argv_expanded = NULL;
7227 if (pi->num_cmds != 1
7228 || pi->followup == PIPE_BG
7229 || command->cmd_type == CMD_SUBSHELL
7236 debug_printf_exec(": group:%p argv:'%s'\n",
7237 command->group, command->argv ? command->argv[0] : "NONE");
7239 if (command->group) {
7240 #if ENABLE_HUSH_FUNCTIONS
7241 if (command->cmd_type == CMD_FUNCDEF) {
7242 /* "executing" func () { list } */
7243 struct function *funcp;
7245 funcp = new_function(command->argv[0]);
7246 /* funcp->name is already set to argv[0] */
7247 funcp->body = command->group;
7249 funcp->body_as_string = command->group_as_string;
7250 command->group_as_string = NULL;
7252 command->group = NULL;
7253 command->argv[0] = NULL;
7254 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7255 funcp->parent_cmd = command;
7256 command->child_func = funcp;
7258 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7260 return EXIT_SUCCESS;
7264 debug_printf("non-subshell group\n");
7265 rcode = 1; /* exitcode if redir failed */
7266 if (setup_redirects(command, squirrel) == 0) {
7267 debug_printf_exec(": run_list\n");
7268 rcode = run_list(command->group) & 0xff;
7270 restore_redirects(squirrel);
7271 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7273 debug_printf_exec("run_pipe: return %d\n", rcode);
7277 argv = command->argv ? command->argv : (char **) &null_ptr;
7279 const struct built_in_command *x;
7280 #if ENABLE_HUSH_FUNCTIONS
7281 const struct function *funcp;
7285 char **new_env = NULL;
7286 struct variable *old_vars = NULL;
7288 if (argv[command->assignment_cnt] == NULL) {
7289 /* Assignments, but no command */
7290 /* Ensure redirects take effect (that is, create files).
7291 * Try "a=t >file" */
7292 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7293 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7294 /* Set shell variables */
7298 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7299 /* Do we need to flag set_local_var() errors?
7300 * "assignment to readonly var" and "putenv error"
7305 /* Redirect error sets $? to 1. Otherwise,
7306 * if evaluating assignment value set $?, retain it.
7307 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7309 rcode = G.last_exitcode;
7310 /* Exit, _skipping_ variable restoring code: */
7311 goto clean_up_and_ret0;
7313 #else /* Older, bigger, but more correct code */
7315 rcode = setup_redirects(command, squirrel);
7316 restore_redirects(squirrel);
7317 /* Set shell variables */
7319 bb_putchar_stderr('+');
7321 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7323 fprintf(stderr, " %s", p);
7324 debug_printf_exec("set shell var:'%s'->'%s'\n",
7326 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7327 /* Do we need to flag set_local_var() errors?
7328 * "assignment to readonly var" and "putenv error"
7333 bb_putchar_stderr('\n');
7334 /* Redirect error sets $? to 1. Otherwise,
7335 * if evaluating assignment value set $?, retain it.
7336 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7338 rcode = G.last_exitcode;
7339 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7341 debug_printf_exec("run_pipe: return %d\n", rcode);
7346 /* Expand the rest into (possibly) many strings each */
7347 #if ENABLE_HUSH_BASH_COMPAT
7348 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7349 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7353 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7356 /* if someone gives us an empty string: `cmd with empty output` */
7357 if (!argv_expanded[0]) {
7358 free(argv_expanded);
7360 return G.last_exitcode;
7363 x = find_builtin(argv_expanded[0]);
7364 #if ENABLE_HUSH_FUNCTIONS
7367 funcp = find_function(argv_expanded[0]);
7371 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7372 debug_printf("exec with redirects only\n");
7373 rcode = setup_redirects(command, NULL);
7374 /* rcode=1 can be if redir file can't be opened */
7375 goto clean_up_and_ret1;
7378 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7381 debug_printf_exec(": builtin '%s' '%s'...\n",
7382 x->b_cmd, argv_expanded[1]);
7384 rcode = x->b_function(argv_expanded) & 0xff;
7387 #if ENABLE_HUSH_FUNCTIONS
7389 # if ENABLE_HUSH_LOCAL
7390 struct variable **sv;
7391 sv = G.shadowed_vars_pp;
7392 G.shadowed_vars_pp = &old_vars;
7394 debug_printf_exec(": function '%s' '%s'...\n",
7395 funcp->name, argv_expanded[1]);
7396 rcode = run_function(funcp, argv_expanded) & 0xff;
7397 # if ENABLE_HUSH_LOCAL
7398 G.shadowed_vars_pp = sv;
7404 unset_vars(new_env);
7406 /* clean_up_and_ret0: */
7407 restore_redirects(squirrel);
7409 free(argv_expanded);
7410 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7412 debug_printf_exec("run_pipe return %d\n", rcode);
7416 if (ENABLE_FEATURE_SH_NOFORK) {
7417 int n = find_applet_by_name(argv_expanded[0]);
7418 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7419 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7421 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7422 argv_expanded[0], argv_expanded[1]);
7423 rcode = run_nofork_applet(n, argv_expanded);
7425 goto clean_up_and_ret;
7428 /* It is neither builtin nor applet. We must fork. */
7432 /* NB: argv_expanded may already be created, and that
7433 * might include `cmd` runs! Do not rerun it! We *must*
7434 * use argv_expanded if it's non-NULL */
7436 /* Going to fork a child per each pipe member */
7441 while (cmd_no < pi->num_cmds) {
7442 struct fd_pair pipefds;
7444 volatile nommu_save_t nommu_save;
7445 nommu_save.new_env = NULL;
7446 nommu_save.old_vars = NULL;
7447 nommu_save.argv = NULL;
7448 nommu_save.argv_from_re_execing = NULL;
7450 command = &pi->cmds[cmd_no];
7452 if (command->argv) {
7453 debug_printf_exec(": pipe member '%s' '%s'...\n",
7454 command->argv[0], command->argv[1]);
7456 debug_printf_exec(": pipe member with no argv\n");
7459 /* pipes are inserted between pairs of commands */
7462 if (cmd_no < pi->num_cmds)
7463 xpiped_pair(pipefds);
7465 command->pid = BB_MMU ? fork() : vfork();
7466 if (!command->pid) { /* child */
7468 disable_restore_tty_pgrp_on_exit();
7469 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7471 /* Every child adds itself to new process group
7472 * with pgid == pid_of_first_child_in_pipe */
7473 if (G.run_list_level == 1 && G_interactive_fd) {
7476 if (pgrp < 0) /* true for 1st process only */
7478 if (setpgid(0, pgrp) == 0
7479 && pi->followup != PIPE_BG
7480 && G_saved_tty_pgrp /* we have ctty */
7482 /* We do it in *every* child, not just first,
7484 tcsetpgrp(G_interactive_fd, pgrp);
7488 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7489 /* 1st cmd in backgrounded pipe
7490 * should have its stdin /dev/null'ed */
7492 if (open(bb_dev_null, O_RDONLY))
7493 xopen("/", O_RDONLY);
7495 xmove_fd(next_infd, 0);
7497 xmove_fd(pipefds.wr, 1);
7500 /* Like bash, explicit redirects override pipes,
7501 * and the pipe fd (fd#1) is available for dup'ing:
7502 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7503 * of cmd1 goes into pipe.
7505 if (setup_redirects(command, NULL)) {
7506 /* Happens when redir file can't be opened:
7507 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7509 * hush: can't open '/qwe/rty': No such file or directory
7511 * (echo BAR is not executed, it hits _exit(1) below)
7516 /* Stores to nommu_save list of env vars putenv'ed
7517 * (NOMMU, on MMU we don't need that) */
7518 /* cast away volatility... */
7519 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7520 /* pseudo_exec() does not return */
7523 /* parent or error */
7524 #if ENABLE_HUSH_FAST
7526 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7528 enable_restore_tty_pgrp_on_exit();
7530 /* Clean up after vforked child */
7531 free(nommu_save.argv);
7532 free(nommu_save.argv_from_re_execing);
7533 unset_vars(nommu_save.new_env);
7534 add_vars(nommu_save.old_vars);
7536 free(argv_expanded);
7537 argv_expanded = NULL;
7538 if (command->pid < 0) { /* [v]fork failed */
7539 /* Clearly indicate, was it fork or vfork */
7540 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7544 /* Second and next children need to know pid of first one */
7546 pi->pgrp = command->pid;
7552 if (cmd_no < pi->num_cmds)
7554 /* Pass read (output) pipe end to next iteration */
7555 next_infd = pipefds.rd;
7558 if (!pi->alive_cmds) {
7560 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7565 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7569 /* NB: called by pseudo_exec, and therefore must not modify any
7570 * global data until exec/_exit (we can be a child after vfork!) */
7571 static int run_list(struct pipe *pi)
7573 #if ENABLE_HUSH_CASE
7574 char *case_word = NULL;
7576 #if ENABLE_HUSH_LOOPS
7577 struct pipe *loop_top = NULL;
7578 char **for_lcur = NULL;
7579 char **for_list = NULL;
7581 smallint last_followup;
7583 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7584 smalluint cond_code = 0;
7586 enum { cond_code = 0 };
7589 smallint rword; /* RES_foo */
7590 smallint last_rword; /* ditto */
7593 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7596 #if ENABLE_HUSH_LOOPS
7597 /* Check syntax for "for" */
7600 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7601 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7603 /* current word is FOR or IN (BOLD in comments below) */
7604 if (cpipe->next == NULL) {
7605 syntax_error("malformed for");
7607 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7610 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7611 if (cpipe->next->res_word == RES_DO)
7613 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7614 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7615 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7617 syntax_error("malformed for");
7619 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7626 /* Past this point, all code paths should jump to ret: label
7627 * in order to return, no direct "return" statements please.
7628 * This helps to ensure that no memory is leaked. */
7636 last_rword = RES_XXXX;
7638 last_followup = PIPE_SEQ;
7639 rcode = G.last_exitcode;
7641 /* Go through list of pipes, (maybe) executing them. */
7642 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7646 IF_HAS_KEYWORDS(rword = pi->res_word;)
7647 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7648 rword, cond_code, last_rword);
7649 #if ENABLE_HUSH_LOOPS
7650 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7651 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7653 /* start of a loop: remember where loop starts */
7658 /* Still in the same "if...", "then..." or "do..." branch? */
7659 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7660 if ((rcode == 0 && last_followup == PIPE_OR)
7661 || (rcode != 0 && last_followup == PIPE_AND)
7663 /* It is "<true> || CMD" or "<false> && CMD"
7664 * and we should not execute CMD */
7665 debug_printf_exec("skipped cmd because of || or &&\n");
7666 last_followup = pi->followup;
7667 goto dont_check_jobs_but_continue;
7670 last_followup = pi->followup;
7671 IF_HAS_KEYWORDS(last_rword = rword;)
7674 if (rword == RES_THEN) {
7675 /* if false; then ... fi has exitcode 0! */
7676 G.last_exitcode = rcode = EXIT_SUCCESS;
7677 /* "if <false> THEN cmd": skip cmd */
7681 if (rword == RES_ELSE || rword == RES_ELIF) {
7682 /* "if <true> then ... ELSE/ELIF cmd":
7683 * skip cmd and all following ones */
7688 #if ENABLE_HUSH_LOOPS
7689 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7691 /* first loop through for */
7693 static const char encoded_dollar_at[] ALIGN1 = {
7694 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7695 }; /* encoded representation of "$@" */
7696 static const char *const encoded_dollar_at_argv[] = {
7697 encoded_dollar_at, NULL
7698 }; /* argv list with one element: "$@" */
7701 vals = (char**)encoded_dollar_at_argv;
7702 if (pi->next->res_word == RES_IN) {
7703 /* if no variable values after "in" we skip "for" */
7704 if (!pi->next->cmds[0].argv) {
7705 G.last_exitcode = rcode = EXIT_SUCCESS;
7706 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7709 vals = pi->next->cmds[0].argv;
7710 } /* else: "for var; do..." -> assume "$@" list */
7711 /* create list of variable values */
7712 debug_print_strings("for_list made from", vals);
7713 for_list = expand_strvec_to_strvec(vals);
7714 for_lcur = for_list;
7715 debug_print_strings("for_list", for_list);
7718 /* "for" loop is over, clean up */
7724 /* Insert next value from for_lcur */
7725 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7726 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7729 if (rword == RES_IN) {
7730 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7732 if (rword == RES_DONE) {
7733 continue; /* "done" has no cmds too */
7736 #if ENABLE_HUSH_CASE
7737 if (rword == RES_CASE) {
7738 case_word = expand_strvec_to_string(pi->cmds->argv);
7741 if (rword == RES_MATCH) {
7744 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7746 /* all prev words didn't match, does this one match? */
7747 argv = pi->cmds->argv;
7749 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7750 /* TODO: which FNM_xxx flags to use? */
7751 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7753 if (cond_code == 0) { /* match! we will execute this branch */
7754 free(case_word); /* make future "word)" stop */
7762 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7764 continue; /* not matched yet, skip this pipe */
7767 /* Just pressing <enter> in shell should check for jobs.
7768 * OTOH, in non-interactive shell this is useless
7769 * and only leads to extra job checks */
7770 if (pi->num_cmds == 0) {
7771 if (G_interactive_fd)
7772 goto check_jobs_and_continue;
7776 /* After analyzing all keywords and conditions, we decided
7777 * to execute this pipe. NB: have to do checkjobs(NULL)
7778 * after run_pipe to collect any background children,
7779 * even if list execution is to be stopped. */
7780 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7783 #if ENABLE_HUSH_LOOPS
7784 G.flag_break_continue = 0;
7786 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7788 /* We ran a builtin, function, or group.
7789 * rcode is already known
7790 * and we don't need to wait for anything. */
7791 G.last_exitcode = rcode;
7792 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7793 check_and_run_traps();
7794 #if ENABLE_HUSH_LOOPS
7795 /* Was it "break" or "continue"? */
7796 if (G.flag_break_continue) {
7797 smallint fbc = G.flag_break_continue;
7798 /* We might fall into outer *loop*,
7799 * don't want to break it too */
7801 G.depth_break_continue--;
7802 if (G.depth_break_continue == 0)
7803 G.flag_break_continue = 0;
7804 /* else: e.g. "continue 2" should *break* once, *then* continue */
7805 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7806 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7810 /* "continue": simulate end of loop */
7815 #if ENABLE_HUSH_FUNCTIONS
7816 if (G.flag_return_in_progress == 1) {
7821 } else if (pi->followup == PIPE_BG) {
7822 /* What does bash do with attempts to background builtins? */
7823 /* even bash 3.2 doesn't do that well with nested bg:
7824 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7825 * I'm NOT treating inner &'s as jobs */
7826 check_and_run_traps();
7828 if (G.run_list_level == 1)
7831 /* Last command's pid goes to $! */
7832 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7833 G.last_exitcode = rcode = EXIT_SUCCESS;
7834 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7837 if (G.run_list_level == 1 && G_interactive_fd) {
7838 /* Waits for completion, then fg's main shell */
7839 rcode = checkjobs_and_fg_shell(pi);
7840 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7841 check_and_run_traps();
7844 { /* This one just waits for completion */
7845 rcode = checkjobs(pi);
7846 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7847 check_and_run_traps();
7849 G.last_exitcode = rcode;
7853 /* Analyze how result affects subsequent commands */
7855 if (rword == RES_IF || rword == RES_ELIF)
7858 check_jobs_and_continue:
7860 dont_check_jobs_but_continue: ;
7861 #if ENABLE_HUSH_LOOPS
7862 /* Beware of "while false; true; do ..."! */
7864 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7865 /* check for RES_DONE is needed for "while ...; do \n done" case */
7867 if (rword == RES_WHILE) {
7869 /* "while false; do...done" - exitcode 0 */
7870 G.last_exitcode = rcode = EXIT_SUCCESS;
7871 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7875 if (rword == RES_UNTIL) {
7877 debug_printf_exec(": until expr is true: breaking\n");
7888 #if ENABLE_HUSH_LOOPS
7893 #if ENABLE_HUSH_CASE
7897 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7901 /* Select which version we will use */
7902 static int run_and_free_list(struct pipe *pi)
7905 debug_printf_exec("run_and_free_list entered\n");
7906 if (!G.o_opt[OPT_O_NOEXEC]) {
7907 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7908 rcode = run_list(pi);
7910 /* free_pipe_list has the side effect of clearing memory.
7911 * In the long run that function can be merged with run_list,
7912 * but doing that now would hobble the debugging effort. */
7914 debug_printf_exec("run_and_free_list return %d\n", rcode);
7919 static void install_sighandlers(unsigned mask)
7921 sighandler_t old_handler;
7923 while ((mask >>= 1) != 0) {
7927 old_handler = install_sighandler(sig, pick_sighandler(sig));
7928 /* POSIX allows shell to re-enable SIGCHLD
7929 * even if it was SIG_IGN on entry.
7930 * Therefore we skip IGN check for it:
7934 if (old_handler == SIG_IGN) {
7935 /* oops... restore back to IGN, and record this fact */
7936 install_sighandler(sig, old_handler);
7938 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7940 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7945 /* Called a few times only (or even once if "sh -c") */
7946 static void install_special_sighandlers(void)
7950 /* Which signals are shell-special? */
7951 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7952 if (G_interactive_fd) {
7953 mask |= SPECIAL_INTERACTIVE_SIGS;
7954 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7955 mask |= SPECIAL_JOBSTOP_SIGS;
7957 /* Careful, do not re-install handlers we already installed */
7958 if (G.special_sig_mask != mask) {
7959 unsigned diff = mask & ~G.special_sig_mask;
7960 G.special_sig_mask = mask;
7961 install_sighandlers(diff);
7967 /* Set handlers to restore tty pgrp and exit */
7968 static void install_fatal_sighandlers(void)
7972 /* We will restore tty pgrp on these signals */
7974 + (1 << SIGILL ) * HUSH_DEBUG
7975 + (1 << SIGFPE ) * HUSH_DEBUG
7976 + (1 << SIGBUS ) * HUSH_DEBUG
7977 + (1 << SIGSEGV) * HUSH_DEBUG
7978 + (1 << SIGTRAP) * HUSH_DEBUG
7980 /* bash 3.2 seems to handle these just like 'fatal' ones */
7983 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7984 * if we aren't interactive... but in this case
7985 * we never want to restore pgrp on exit, and this fn is not called
7987 /*+ (1 << SIGHUP )*/
7988 /*+ (1 << SIGTERM)*/
7989 /*+ (1 << SIGINT )*/
7991 G_fatal_sig_mask = mask;
7993 install_sighandlers(mask);
7997 static int set_mode(int state, char mode, const char *o_opt)
8002 G.o_opt[OPT_O_NOEXEC] = state;
8005 IF_HUSH_MODE_X(G_x_mode = state;)
8009 /* "set -+o" without parameter.
8010 * in bash, set -o produces this output:
8014 * We always use the second form.
8016 const char *p = o_opt_strings;
8019 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8025 idx = index_in_strings(o_opt_strings, o_opt);
8027 G.o_opt[idx] = state;
8031 return EXIT_FAILURE;
8033 return EXIT_SUCCESS;
8036 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8037 int hush_main(int argc, char **argv)
8040 OPT_login = (1 << 0),
8044 unsigned builtin_argc;
8046 struct variable *cur_var;
8047 struct variable *shell_ver;
8050 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8051 G.last_exitcode = EXIT_SUCCESS;
8053 #if ENABLE_HUSH_FAST
8054 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8057 G.argv0_for_re_execing = argv[0];
8059 /* Deal with HUSH_VERSION */
8060 shell_ver = xzalloc(sizeof(*shell_ver));
8061 shell_ver->flg_export = 1;
8062 shell_ver->flg_read_only = 1;
8063 /* Code which handles ${var<op>...} needs writable values for all variables,
8064 * therefore we xstrdup: */
8065 shell_ver->varstr = xstrdup(hush_version_str);
8066 /* Create shell local variables from the values
8067 * currently living in the environment */
8068 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8069 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8070 G.top_var = shell_ver;
8071 cur_var = G.top_var;
8074 char *value = strchr(*e, '=');
8075 if (value) { /* paranoia */
8076 cur_var->next = xzalloc(sizeof(*cur_var));
8077 cur_var = cur_var->next;
8078 cur_var->varstr = *e;
8079 cur_var->max_len = strlen(*e);
8080 cur_var->flg_export = 1;
8084 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8085 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8086 putenv(shell_ver->varstr);
8089 set_pwd_var(/*exp:*/ 1);
8091 #if ENABLE_HUSH_BASH_COMPAT
8092 /* Set (but not export) HOSTNAME unless already set */
8093 if (!get_local_var_value("HOSTNAME")) {
8096 set_local_var_from_halves("HOSTNAME", uts.nodename);
8098 /* bash also exports SHLVL and _,
8099 * and sets (but doesn't export) the following variables:
8101 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8102 * BASH_VERSION='3.2.0(1)-release'
8104 * MACHTYPE=i386-pc-linux-gnu
8106 * PPID=<NNNNN> - we also do it elsewhere
8117 * PIPESTATUS=([0]="0")
8118 * HISTFILE=/<xxx>/.bash_history
8122 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8124 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8135 #if ENABLE_FEATURE_EDITING
8136 G.line_input_state = new_line_input_t(FOR_SHELL);
8139 /* Initialize some more globals to non-zero values */
8140 cmdedit_update_prompt();
8142 die_func = restore_ttypgrp_and__exit;
8144 /* Shell is non-interactive at first. We need to call
8145 * install_special_sighandlers() if we are going to execute "sh <script>",
8146 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8147 * If we later decide that we are interactive, we run install_special_sighandlers()
8148 * in order to intercept (more) signals.
8152 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8153 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8156 opt = getopt(argc, argv, "+c:xinsl"
8159 # if ENABLE_HUSH_FUNCTIONS
8169 * sh ... -c 'script'
8170 * sh ... -c 'script' ARG0 [ARG1...]
8171 * On NOMMU, if builtin_argc != 0,
8172 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8173 * "" needs to be replaced with NULL
8174 * and BARGV vector fed to builtin function.
8175 * Note: the form without ARG0 never happens:
8176 * sh ... -c 'builtin' BARGV... ""
8179 G.root_pid = getpid();
8180 G.root_ppid = getppid();
8182 G.global_argv = argv + optind;
8183 G.global_argc = argc - optind;
8185 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8186 const struct built_in_command *x;
8188 install_special_sighandlers();
8189 x = find_builtin(optarg);
8190 if (x) { /* paranoia */
8191 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8192 G.global_argv += builtin_argc;
8193 G.global_argv[-1] = NULL; /* replace "" */
8195 G.last_exitcode = x->b_function(argv + optind - 1);
8199 if (!G.global_argv[0]) {
8200 /* -c 'script' (no params): prevent empty $0 */
8201 G.global_argv--; /* points to argv[i] of 'script' */
8202 G.global_argv[0] = argv[0];
8204 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8205 install_special_sighandlers();
8206 parse_and_run_string(optarg);
8209 /* Well, we cannot just declare interactiveness,
8210 * we have to have some stuff (ctty, etc) */
8211 /* G_interactive_fd++; */
8214 /* "-s" means "read from stdin", but this is how we always
8215 * operate, so simply do nothing here. */
8221 case '<': /* "big heredoc" support */
8222 full_write1_str(optarg);
8225 unsigned long long empty_trap_mask;
8227 G.root_pid = bb_strtou(optarg, &optarg, 16);
8229 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8231 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8233 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8235 builtin_argc = bb_strtou(optarg, &optarg, 16);
8237 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8238 if (empty_trap_mask != 0) {
8240 install_special_sighandlers();
8241 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8242 for (sig = 1; sig < NSIG; sig++) {
8243 if (empty_trap_mask & (1LL << sig)) {
8244 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8245 install_sighandler(sig, SIG_IGN);
8249 # if ENABLE_HUSH_LOOPS
8251 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8257 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8259 # if ENABLE_HUSH_FUNCTIONS
8261 struct function *funcp = new_function(optarg);
8262 /* funcp->name is already set to optarg */
8263 /* funcp->body is set to NULL. It's a special case. */
8264 funcp->body_as_string = argv[optind];
8272 if (set_mode(1, opt, NULL) == 0) /* no error */
8276 fprintf(stderr, "Usage: sh [FILE]...\n"
8277 " or: sh -c command [args]...\n\n");
8283 } /* option parsing loop */
8285 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8286 G.global_argc = argc - (optind - 1);
8287 G.global_argv = argv + (optind - 1);
8288 G.global_argv[0] = argv[0];
8291 G.root_pid = getpid();
8292 G.root_ppid = getppid();
8295 /* If we are login shell... */
8296 if (flags & OPT_login) {
8298 debug_printf("sourcing /etc/profile\n");
8299 input = fopen_for_read("/etc/profile");
8300 if (input != NULL) {
8301 remember_FILE(input);
8302 install_special_sighandlers();
8303 parse_and_run_file(input);
8304 fclose_and_forget(input);
8306 /* bash: after sourcing /etc/profile,
8307 * tries to source (in the given order):
8308 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8309 * stopping on first found. --noprofile turns this off.
8310 * bash also sources ~/.bash_logout on exit.
8311 * If called as sh, skips .bash_XXX files.
8315 if (G.global_argv[1]) {
8318 * "bash <script>" (which is never interactive (unless -i?))
8319 * sources $BASH_ENV here (without scanning $PATH).
8320 * If called as sh, does the same but with $ENV.
8324 debug_printf("running script '%s'\n", G.global_argv[0]);
8325 input = xfopen_for_read(G.global_argv[0]);
8326 remember_FILE(input);
8327 install_special_sighandlers();
8328 parse_and_run_file(input);
8329 #if ENABLE_FEATURE_CLEAN_UP
8330 fclose_and_forget(input);
8335 /* Up to here, shell was non-interactive. Now it may become one.
8336 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8339 /* A shell is interactive if the '-i' flag was given,
8340 * or if all of the following conditions are met:
8342 * no arguments remaining or the -s flag given
8343 * standard input is a terminal
8344 * standard output is a terminal
8345 * Refer to Posix.2, the description of the 'sh' utility.
8348 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8349 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8350 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8351 if (G_saved_tty_pgrp < 0)
8352 G_saved_tty_pgrp = 0;
8354 /* try to dup stdin to high fd#, >= 255 */
8355 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8356 if (G_interactive_fd < 0) {
8357 /* try to dup to any fd */
8358 G_interactive_fd = dup(STDIN_FILENO);
8359 if (G_interactive_fd < 0) {
8361 G_interactive_fd = 0;
8362 G_saved_tty_pgrp = 0;
8365 // TODO: track & disallow any attempts of user
8366 // to (inadvertently) close/redirect G_interactive_fd
8368 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8369 if (G_interactive_fd) {
8370 close_on_exec_on(G_interactive_fd);
8372 if (G_saved_tty_pgrp) {
8373 /* If we were run as 'hush &', sleep until we are
8374 * in the foreground (tty pgrp == our pgrp).
8375 * If we get started under a job aware app (like bash),
8376 * make sure we are now in charge so we don't fight over
8377 * who gets the foreground */
8379 pid_t shell_pgrp = getpgrp();
8380 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8381 if (G_saved_tty_pgrp == shell_pgrp)
8383 /* send TTIN to ourself (should stop us) */
8384 kill(- shell_pgrp, SIGTTIN);
8388 /* Install more signal handlers */
8389 install_special_sighandlers();
8391 if (G_saved_tty_pgrp) {
8392 /* Set other signals to restore saved_tty_pgrp */
8393 install_fatal_sighandlers();
8394 /* Put ourselves in our own process group
8395 * (bash, too, does this only if ctty is available) */
8396 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8397 /* Grab control of the terminal */
8398 tcsetpgrp(G_interactive_fd, getpid());
8400 enable_restore_tty_pgrp_on_exit();
8402 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8404 const char *hp = get_local_var_value("HISTFILE");
8406 hp = get_local_var_value("HOME");
8408 hp = concat_path_file(hp, ".hush_history");
8413 G.line_input_state->hist_file = hp;
8414 //set_local_var(xasprintf("HISTFILE=%s", ...));
8416 # if ENABLE_FEATURE_SH_HISTFILESIZE
8417 hp = get_local_var_value("HISTFILESIZE");
8418 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8423 install_special_sighandlers();
8425 #elif ENABLE_HUSH_INTERACTIVE
8426 /* No job control compiled in, only prompt/line editing */
8427 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8428 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8429 if (G_interactive_fd < 0) {
8430 /* try to dup to any fd */
8431 G_interactive_fd = dup(STDIN_FILENO);
8432 if (G_interactive_fd < 0)
8434 G_interactive_fd = 0;
8437 if (G_interactive_fd) {
8438 close_on_exec_on(G_interactive_fd);
8440 install_special_sighandlers();
8442 /* We have interactiveness code disabled */
8443 install_special_sighandlers();
8446 * if interactive but not a login shell, sources ~/.bashrc
8447 * (--norc turns this off, --rcfile <file> overrides)
8450 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8451 /* note: ash and hush share this string */
8452 printf("\n\n%s %s\n"
8453 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8456 "hush - the humble shell"
8460 parse_and_run_file(stdin);
8463 hush_exit(G.last_exitcode);
8468 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8469 int msh_main(int argc, char **argv)
8471 //bb_error_msg("msh is deprecated, please use hush instead");
8472 return hush_main(argc, argv);
8480 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8485 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8492 return applet_main_func(argc, argv - argc);
8495 static int FAST_FUNC builtin_test(char **argv)
8497 return run_applet_main(argv, test_main);
8500 static int FAST_FUNC builtin_echo(char **argv)
8502 return run_applet_main(argv, echo_main);
8506 static int FAST_FUNC builtin_printf(char **argv)
8508 return run_applet_main(argv, printf_main);
8512 static char **skip_dash_dash(char **argv)
8515 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8520 static int FAST_FUNC builtin_eval(char **argv)
8522 int rcode = EXIT_SUCCESS;
8524 argv = skip_dash_dash(argv);
8526 char *str = expand_strvec_to_string(argv);
8528 * eval "echo Hi; done" ("done" is syntax error):
8529 * "echo Hi" will not execute too.
8531 parse_and_run_string(str);
8533 rcode = G.last_exitcode;
8538 static int FAST_FUNC builtin_cd(char **argv)
8542 argv = skip_dash_dash(argv);
8544 if (newdir == NULL) {
8545 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8546 * bash says "bash: cd: HOME not set" and does nothing
8549 const char *home = get_local_var_value("HOME");
8550 newdir = home ? home : "/";
8552 if (chdir(newdir)) {
8553 /* Mimic bash message exactly */
8554 bb_perror_msg("cd: %s", newdir);
8555 return EXIT_FAILURE;
8557 /* Read current dir (get_cwd(1) is inside) and set PWD.
8558 * Note: do not enforce exporting. If PWD was unset or unexported,
8559 * set it again, but do not export. bash does the same.
8561 set_pwd_var(/*exp:*/ 0);
8562 return EXIT_SUCCESS;
8565 static int FAST_FUNC builtin_exec(char **argv)
8567 argv = skip_dash_dash(argv);
8568 if (argv[0] == NULL)
8569 return EXIT_SUCCESS; /* bash does this */
8571 /* Careful: we can end up here after [v]fork. Do not restore
8572 * tty pgrp then, only top-level shell process does that */
8573 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8574 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8576 /* TODO: if exec fails, bash does NOT exit! We do.
8577 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8578 * and tcsetpgrp, and this is inherently racy.
8580 execvp_or_die(argv);
8583 static int FAST_FUNC builtin_exit(char **argv)
8585 debug_printf_exec("%s()\n", __func__);
8587 /* interactive bash:
8588 * # trap "echo EEE" EXIT
8591 * There are stopped jobs.
8592 * (if there are _stopped_ jobs, running ones don't count)
8595 * EEE (then bash exits)
8597 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8600 /* note: EXIT trap is run by hush_exit */
8601 argv = skip_dash_dash(argv);
8602 if (argv[0] == NULL)
8603 hush_exit(G.last_exitcode);
8604 /* mimic bash: exit 123abc == exit 255 + error msg */
8605 xfunc_error_retval = 255;
8606 /* bash: exit -2 == exit 254, no error msg */
8607 hush_exit(xatoi(argv[0]) & 0xff);
8610 static void print_escaped(const char *s)
8615 const char *p = strchrnul(s, '\'');
8616 /* print 'xxxx', possibly just '' */
8617 printf("'%.*s'", (int)(p - s), s);
8622 /* s points to '; print "'''...'''" */
8624 do putchar('\''); while (*++s == '\'');
8629 #if !ENABLE_HUSH_LOCAL
8630 #define helper_export_local(argv, exp, lvl) \
8631 helper_export_local(argv, exp)
8633 static void helper_export_local(char **argv, int exp, int lvl)
8637 char *name_end = strchrnul(name, '=');
8639 /* So far we do not check that name is valid (TODO?) */
8641 if (*name_end == '\0') {
8642 struct variable *var, **vpp;
8644 vpp = get_ptr_to_local_var(name, name_end - name);
8645 var = vpp ? *vpp : NULL;
8647 if (exp == -1) { /* unexporting? */
8648 /* export -n NAME (without =VALUE) */
8650 var->flg_export = 0;
8651 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8653 } /* else: export -n NOT_EXISTING_VAR: no-op */
8656 if (exp == 1) { /* exporting? */
8657 /* export NAME (without =VALUE) */
8659 var->flg_export = 1;
8660 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8661 putenv(var->varstr);
8665 /* Exporting non-existing variable.
8666 * bash does not put it in environment,
8667 * but remembers that it is exported,
8668 * and does put it in env when it is set later.
8669 * We just set it to "" and export. */
8670 /* Or, it's "local NAME" (without =VALUE).
8671 * bash sets the value to "". */
8672 name = xasprintf("%s=", name);
8674 /* (Un)exporting/making local NAME=VALUE */
8675 name = xstrdup(name);
8677 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8681 static int FAST_FUNC builtin_export(char **argv)
8683 unsigned opt_unexport;
8685 #if ENABLE_HUSH_EXPORT_N
8686 /* "!": do not abort on errors */
8687 opt_unexport = getopt32(argv, "!n");
8688 if (opt_unexport == (uint32_t)-1)
8689 return EXIT_FAILURE;
8696 if (argv[0] == NULL) {
8703 /* ash emits: export VAR='VAL'
8704 * bash: declare -x VAR="VAL"
8705 * we follow ash example */
8706 const char *s = *e++;
8707 const char *p = strchr(s, '=');
8709 if (!p) /* wtf? take next variable */
8712 printf("export %.*s", (int)(p - s) + 1, s);
8713 print_escaped(p + 1);
8717 /*fflush_all(); - done after each builtin anyway */
8719 return EXIT_SUCCESS;
8722 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8724 return EXIT_SUCCESS;
8727 #if ENABLE_HUSH_LOCAL
8728 static int FAST_FUNC builtin_local(char **argv)
8730 if (G.func_nest_level == 0) {
8731 bb_error_msg("%s: not in a function", argv[0]);
8732 return EXIT_FAILURE; /* bash compat */
8734 helper_export_local(argv, 0, G.func_nest_level);
8735 return EXIT_SUCCESS;
8739 static int FAST_FUNC builtin_trap(char **argv)
8745 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8750 /* No args: print all trapped */
8751 for (i = 0; i < NSIG; ++i) {
8754 print_escaped(G.traps[i]);
8755 /* note: bash adds "SIG", but only if invoked
8756 * as "bash". If called as "sh", or if set -o posix,
8757 * then it prints short signal names.
8758 * We are printing short names: */
8759 printf(" %s\n", get_signame(i));
8762 /*fflush_all(); - done after each builtin anyway */
8763 return EXIT_SUCCESS;
8767 /* If first arg is a number: reset all specified signals */
8768 sig = bb_strtou(*argv, NULL, 10);
8774 sighandler_t handler;
8776 sig = get_signum(*argv++);
8777 if (sig < 0 || sig >= NSIG) {
8779 /* Mimic bash message exactly */
8780 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8785 G.traps[sig] = xstrdup(new_cmd);
8787 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8788 get_signame(sig), sig, G.traps[sig]);
8790 /* There is no signal for 0 (EXIT) */
8795 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8797 /* We are removing trap handler */
8798 handler = pick_sighandler(sig);
8799 install_sighandler(sig, handler);
8804 if (!argv[1]) { /* no second arg */
8805 bb_error_msg("trap: invalid arguments");
8806 return EXIT_FAILURE;
8809 /* First arg is "-": reset all specified to default */
8810 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8811 /* Everything else: set arg as signal handler
8812 * (includes "" case, which ignores signal) */
8813 if (argv[0][0] == '-') {
8814 if (argv[0][1] == '\0') { /* "-" */
8815 /* new_cmd remains NULL: "reset these sigs" */
8818 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8821 /* else: "-something", no special meaning */
8826 goto process_sig_list;
8829 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8830 static int FAST_FUNC builtin_type(char **argv)
8832 int ret = EXIT_SUCCESS;
8838 if (0) {} /* make conditional compile easier below */
8839 /*else if (find_alias(*argv))
8840 type = "an alias";*/
8841 #if ENABLE_HUSH_FUNCTIONS
8842 else if (find_function(*argv))
8843 type = "a function";
8845 else if (find_builtin(*argv))
8846 type = "a shell builtin";
8847 else if ((path = find_in_path(*argv)) != NULL)
8850 bb_error_msg("type: %s: not found", *argv);
8855 printf("%s is %s\n", *argv, type);
8863 /* built-in 'fg' and 'bg' handler */
8864 static int FAST_FUNC builtin_fg_bg(char **argv)
8869 if (!G_interactive_fd)
8870 return EXIT_FAILURE;
8872 /* If they gave us no args, assume they want the last backgrounded task */
8874 for (pi = G.job_list; pi; pi = pi->next) {
8875 if (pi->jobid == G.last_jobid) {
8879 bb_error_msg("%s: no current job", argv[0]);
8880 return EXIT_FAILURE;
8882 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8883 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8884 return EXIT_FAILURE;
8886 for (pi = G.job_list; pi; pi = pi->next) {
8887 if (pi->jobid == jobnum) {
8891 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8892 return EXIT_FAILURE;
8894 /* TODO: bash prints a string representation
8895 * of job being foregrounded (like "sleep 1 | cat") */
8896 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8897 /* Put the job into the foreground. */
8898 tcsetpgrp(G_interactive_fd, pi->pgrp);
8901 /* Restart the processes in the job */
8902 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8903 for (i = 0; i < pi->num_cmds; i++) {
8904 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8906 pi->stopped_cmds = 0;
8908 i = kill(- pi->pgrp, SIGCONT);
8910 if (errno == ESRCH) {
8911 delete_finished_bg_job(pi);
8912 return EXIT_SUCCESS;
8914 bb_perror_msg("kill (SIGCONT)");
8917 if (argv[0][0] == 'f') {
8919 return checkjobs_and_fg_shell(pi);
8921 return EXIT_SUCCESS;
8925 #if ENABLE_HUSH_HELP
8926 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8928 const struct built_in_command *x;
8931 "Built-in commands:\n"
8932 "------------------\n");
8933 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8935 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8938 return EXIT_SUCCESS;
8942 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
8943 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8945 show_history(G.line_input_state);
8946 return EXIT_SUCCESS;
8951 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8954 const char *status_string;
8956 for (job = G.job_list; job; job = job->next) {
8957 if (job->alive_cmds == job->stopped_cmds)
8958 status_string = "Stopped";
8960 status_string = "Running";
8962 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8964 return EXIT_SUCCESS;
8969 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8974 # ifdef M_TRIM_THRESHOLD
8975 /* Optional. Reduces probability of false positives */
8978 /* Crude attempt to find where "free memory" starts,
8979 * sans fragmentation. */
8981 l = (unsigned long)p;
8984 if (l < (unsigned long)p) l = (unsigned long)p;
8987 if (!G.memleak_value)
8988 G.memleak_value = l;
8990 l -= G.memleak_value;
8997 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9002 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9005 return EXIT_SUCCESS;
9008 /* Interruptibility of read builtin in bash
9009 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9011 * Empty trap makes read ignore corresponding signal, for any signal.
9014 * - terminates non-interactive shell;
9015 * - interrupts read in interactive shell;
9016 * if it has non-empty trap:
9017 * - executes trap and returns to command prompt in interactive shell;
9018 * - executes trap and returns to read in non-interactive shell;
9020 * - is ignored (does not interrupt) read in interactive shell;
9021 * - terminates non-interactive shell;
9022 * if it has non-empty trap:
9023 * - executes trap and returns to read;
9025 * - terminates shell (regardless of interactivity);
9026 * if it has non-empty trap:
9027 * - executes trap and returns to read;
9029 static int FAST_FUNC builtin_read(char **argv)
9039 /* "!": do not abort on errors.
9040 * Option string must start with "sr" to match BUILTIN_READ_xxx
9042 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9043 if (read_flags == (uint32_t)-1)
9044 return EXIT_FAILURE;
9046 ifs = get_local_var_value("IFS"); /* can be NULL */
9049 r = shell_builtin_read(set_local_var_from_halves,
9059 if ((uintptr_t)r == 1 && errno == EINTR) {
9060 unsigned sig = check_and_run_traps();
9061 if (sig && sig != SIGINT)
9065 if ((uintptr_t)r > 1) {
9066 bb_error_msg("%s", r);
9067 r = (char*)(uintptr_t)1;
9070 return (uintptr_t)r;
9073 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9074 * built-in 'set' handler
9076 * set [-abCefhmnuvx] [-o option] [argument...]
9077 * set [+abCefhmnuvx] [+o option] [argument...]
9078 * set -- [argument...]
9081 * Implementations shall support the options in both their hyphen and
9082 * plus-sign forms. These options can also be specified as options to sh.
9084 * Write out all variables and their values: set
9085 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9086 * Turn on the -x and -v options: set -xv
9087 * Unset all positional parameters: set --
9088 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9089 * Set the positional parameters to the expansion of x, even if x expands
9090 * with a leading '-' or '+': set -- $x
9092 * So far, we only support "set -- [argument...]" and some of the short names.
9094 static int FAST_FUNC builtin_set(char **argv)
9097 char **pp, **g_argv;
9098 char *arg = *++argv;
9102 for (e = G.top_var; e; e = e->next)
9104 return EXIT_SUCCESS;
9108 if (strcmp(arg, "--") == 0) {
9112 if (arg[0] != '+' && arg[0] != '-')
9114 for (n = 1; arg[n]; ++n) {
9115 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9117 if (arg[n] == 'o' && argv[1])
9120 } while ((arg = *++argv) != NULL);
9121 /* Now argv[0] is 1st argument */
9124 return EXIT_SUCCESS;
9127 /* NB: G.global_argv[0] ($0) is never freed/changed */
9128 g_argv = G.global_argv;
9129 if (G.global_args_malloced) {
9135 G.global_args_malloced = 1;
9136 pp = xzalloc(sizeof(pp[0]) * 2);
9137 pp[0] = g_argv[0]; /* retain $0 */
9140 /* This realloc's G.global_argv */
9141 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9148 return EXIT_SUCCESS;
9150 /* Nothing known, so abort */
9152 bb_error_msg("set: %s: invalid option", arg);
9153 return EXIT_FAILURE;
9156 static int FAST_FUNC builtin_shift(char **argv)
9159 argv = skip_dash_dash(argv);
9163 if (n >= 0 && n < G.global_argc) {
9164 if (G.global_args_malloced) {
9167 free(G.global_argv[m++]);
9170 memmove(&G.global_argv[1], &G.global_argv[n+1],
9171 G.global_argc * sizeof(G.global_argv[0]));
9172 return EXIT_SUCCESS;
9174 return EXIT_FAILURE;
9177 static int FAST_FUNC builtin_source(char **argv)
9179 char *arg_path, *filename;
9182 #if ENABLE_HUSH_FUNCTIONS
9186 argv = skip_dash_dash(argv);
9189 /* bash says: "bash: .: filename argument required" */
9190 return 2; /* bash compat */
9193 if (!strchr(filename, '/')) {
9194 arg_path = find_in_path(filename);
9196 filename = arg_path;
9198 input = remember_FILE(fopen_or_warn(filename, "r"));
9201 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9202 /* POSIX: non-interactive shell should abort here,
9203 * not merely fail. So far no one complained :)
9205 return EXIT_FAILURE;
9208 #if ENABLE_HUSH_FUNCTIONS
9209 sv_flg = G.flag_return_in_progress;
9210 /* "we are inside sourced file, ok to use return" */
9211 G.flag_return_in_progress = -1;
9214 save_and_replace_G_args(&sv, argv);
9216 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9217 G.last_exitcode = 0;
9218 parse_and_run_file(input);
9219 fclose_and_forget(input);
9222 restore_G_args(&sv, argv);
9223 #if ENABLE_HUSH_FUNCTIONS
9224 G.flag_return_in_progress = sv_flg;
9227 return G.last_exitcode;
9230 static int FAST_FUNC builtin_umask(char **argv)
9237 argv = skip_dash_dash(argv);
9239 mode_t old_mask = mask;
9241 /* numeric umasks are taken as-is */
9242 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9243 if (!isdigit(argv[0][0]))
9245 mask = bb_parse_mode(argv[0], mask);
9246 if (!isdigit(argv[0][0]))
9248 if ((unsigned)mask > 0777) {
9251 * bash: umask: 'q': invalid symbolic mode operator
9252 * bash: umask: 999: octal number out of range
9254 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9259 printf("%04o\n", (unsigned) mask);
9260 /* fall through and restore mask which we set to 0 */
9264 return !rc; /* rc != 0 - success */
9267 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9268 static int FAST_FUNC builtin_unset(char **argv)
9273 /* "!": do not abort on errors */
9274 /* "+": stop at 1st non-option */
9275 opts = getopt32(argv, "!+vf");
9276 if (opts == (unsigned)-1)
9277 return EXIT_FAILURE;
9279 bb_error_msg("unset: -v and -f are exclusive");
9280 return EXIT_FAILURE;
9286 if (!(opts & 2)) { /* not -f */
9287 if (unset_local_var(*argv)) {
9288 /* unset <nonexistent_var> doesn't fail.
9289 * Error is when one tries to unset RO var.
9290 * Message was printed by unset_local_var. */
9294 #if ENABLE_HUSH_FUNCTIONS
9304 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9305 static int FAST_FUNC builtin_wait(char **argv)
9307 int ret = EXIT_SUCCESS;
9310 argv = skip_dash_dash(argv);
9311 if (argv[0] == NULL) {
9312 /* Don't care about wait results */
9313 /* Note 1: must wait until there are no more children */
9314 /* Note 2: must be interruptible */
9316 * $ sleep 3 & sleep 6 & wait
9321 * $ sleep 3 & sleep 6 & wait
9325 * ^C <-- after ~4 sec from keyboard
9330 sigset_t oldset, allsigs;
9332 /* waitpid is not interruptible by SA_RESTARTed
9333 * signals which we use. Thus, this ugly dance:
9336 /* Make sure possible SIGCHLD is stored in kernel's
9337 * pending signal mask before we call waitpid.
9338 * Or else we may race with SIGCHLD, lose it,
9339 * and get stuck in sigwaitinfo...
9341 sigfillset(&allsigs);
9342 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9344 if (!sigisemptyset(&G.pending_set)) {
9345 /* Crap! we raced with some signal! */
9350 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9351 if (errno == ECHILD) {
9352 sigprocmask(SIG_SETMASK, &oldset, NULL);
9356 /* Wait for SIGCHLD or any other signal */
9357 //sig = sigwaitinfo(&allsigs, NULL);
9358 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9359 /* Note: sigsuspend invokes signal handler */
9360 sigsuspend(&oldset);
9362 sigprocmask(SIG_SETMASK, &oldset, NULL);
9364 /* So, did we get a signal? */
9366 // raise(sig); /* run handler */
9367 sig = check_and_run_traps();
9368 if (sig /*&& sig != SIGCHLD - always true */) {
9373 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9378 /* This is probably buggy wrt interruptible-ness */
9380 pid_t pid = bb_strtou(*argv, NULL, 10);
9382 /* mimic bash message */
9383 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9384 return EXIT_FAILURE;
9386 if (waitpid(pid, &status, 0) == pid) {
9387 ret = WEXITSTATUS(status);
9388 if (WIFSIGNALED(status))
9389 ret = 128 + WTERMSIG(status);
9391 bb_perror_msg("wait %s", *argv);
9400 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9401 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9404 def = bb_strtou(argv[1], NULL, 10);
9405 if (errno || def < def_min || argv[2]) {
9406 bb_error_msg("%s: bad arguments", argv[0]);
9414 #if ENABLE_HUSH_LOOPS
9415 static int FAST_FUNC builtin_break(char **argv)
9418 if (G.depth_of_loop == 0) {
9419 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9420 /* if we came from builtin_continue(), need to undo "= 1" */
9421 G.flag_break_continue = 0;
9422 return EXIT_SUCCESS; /* bash compat */
9424 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9426 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9427 if (depth == UINT_MAX)
9428 G.flag_break_continue = BC_BREAK;
9429 if (G.depth_of_loop < depth)
9430 G.depth_break_continue = G.depth_of_loop;
9432 return EXIT_SUCCESS;
9435 static int FAST_FUNC builtin_continue(char **argv)
9437 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9438 return builtin_break(argv);
9442 #if ENABLE_HUSH_FUNCTIONS
9443 static int FAST_FUNC builtin_return(char **argv)
9447 if (G.flag_return_in_progress != -1) {
9448 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9449 return EXIT_FAILURE; /* bash compat */
9452 G.flag_return_in_progress = 1;
9455 * out of range: wraps around at 256, does not error out
9456 * non-numeric param:
9457 * f() { false; return qwe; }; f; echo $?
9458 * bash: return: qwe: numeric argument required <== we do this
9459 * 255 <== we also do this
9461 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);