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)
49 * follow IFS rules more precisely, including update semantics
50 * builtins mandated by standards we don't support:
51 * [un]alias, command, fc, getopts, newgrp, readonly, times
52 * make complex ${var%...} constructs support optional
53 * make here documents optional
56 * redirection of stdout+stderr: &> and >&
57 * reserved words: function select
58 * advanced test: [[ ]]
59 * process substitution: <(list) and >(list)
62 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
63 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
64 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
66 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
67 * This is exactly equivalent to let "EXPR".
68 * $[EXPR]: synonym for $((EXPR))
71 * In bash, export builtin is special, its arguments are assignments
72 * and therefore expansion of them should be "one-word" expansion:
73 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
75 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
76 * ls: cannot access i=a: No such file or directory
77 * ls: cannot access b: No such file or directory
78 * Note1: same applies to local builtin.
79 * Note2: bash 3.2.33(1) does this only if export word itself
81 * $ export i=`echo 'aaa bbb'`; echo "$i"
83 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
86 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
87 || defined(__APPLE__) \
89 # include <malloc.h> /* for malloc_trim */
92 /* #include <dmalloc.h> */
96 #include <sys/utsname.h> /* for setting $HOSTNAME */
98 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
100 #include "shell_common.h"
103 #if ENABLE_HUSH_RANDOM_SUPPORT
106 # define CLEAR_RANDOM_T(rnd) ((void)0)
108 #ifndef F_DUPFD_CLOEXEC
109 # define F_DUPFD_CLOEXEC F_DUPFD
112 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
116 //config: bool "hush"
119 //config: hush is a small shell (25k). It handles the normal flow control
120 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
121 //config: case/esac. Redirections, here documents, $((arithmetic))
122 //config: and functions are supported.
124 //config: It will compile and work on no-mmu systems.
126 //config: It does not handle select, aliases, tilde expansion,
127 //config: &>file and >&file redirection of stdout+stderr.
129 //config:config HUSH_BASH_COMPAT
130 //config: bool "bash-compatible extensions"
132 //config: depends on HUSH
134 //config: Enable bash-compatible extensions.
136 //config:config HUSH_BRACE_EXPANSION
137 //config: bool "Brace expansion"
139 //config: depends on HUSH_BASH_COMPAT
141 //config: Enable {abc,def} extension.
143 //config:config HUSH_HELP
144 //config: bool "help builtin"
146 //config: depends on HUSH
148 //config: Enable help builtin in hush. Code size + ~1 kbyte.
150 //config:config HUSH_INTERACTIVE
151 //config: bool "Interactive mode"
153 //config: depends on HUSH
155 //config: Enable interactive mode (prompt and command editing).
156 //config: Without this, hush simply reads and executes commands
157 //config: from stdin just like a shell script from a file.
158 //config: No prompt, no PS1/PS2 magic shell variables.
160 //config:config HUSH_SAVEHISTORY
161 //config: bool "Save command history to .hush_history"
163 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
165 //config: Enable history saving in hush.
167 //config:config HUSH_JOB
168 //config: bool "Job control"
170 //config: depends on HUSH_INTERACTIVE
172 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
173 //config: command (not entire shell), fg/bg builtins work. Without this option,
174 //config: "cmd &" still works by simply spawning a process and immediately
175 //config: prompting for next command (or executing next command in a script),
176 //config: but no separate process group is formed.
178 //config:config HUSH_TICK
179 //config: bool "Process substitution"
181 //config: depends on HUSH
183 //config: Enable process substitution `command` and $(command) in hush.
185 //config:config HUSH_IF
186 //config: bool "Support if/then/elif/else/fi"
188 //config: depends on HUSH
190 //config: Enable if/then/elif/else/fi in hush.
192 //config:config HUSH_LOOPS
193 //config: bool "Support for, while and until loops"
195 //config: depends on HUSH
197 //config: Enable for, while and until loops in hush.
199 //config:config HUSH_CASE
200 //config: bool "Support case ... esac statement"
202 //config: depends on HUSH
204 //config: Enable case ... esac statement in hush. +400 bytes.
206 //config:config HUSH_FUNCTIONS
207 //config: bool "Support funcname() { commands; } syntax"
209 //config: depends on HUSH
211 //config: Enable support for shell functions in hush. +800 bytes.
213 //config:config HUSH_LOCAL
214 //config: bool "Support local builtin"
216 //config: depends on HUSH_FUNCTIONS
218 //config: Enable support for local variables in functions.
220 //config:config HUSH_RANDOM_SUPPORT
221 //config: bool "Pseudorandom generator and $RANDOM variable"
223 //config: depends on HUSH
225 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
226 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
228 //config:config HUSH_EXPORT_N
229 //config: bool "Support 'export -n' option"
231 //config: depends on HUSH
233 //config: export -n unexports variables. It is a bash extension.
235 //config:config HUSH_MODE_X
236 //config: bool "Support 'hush -x' option and 'set -x' command"
238 //config: depends on HUSH
240 //config: This instructs hush to print commands before execution.
241 //config: Adds ~300 bytes.
244 //config: bool "msh (deprecated: aliased to hush)"
246 //config: select HUSH
248 //config: msh is deprecated and will be removed, please migrate to hush.
251 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
252 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
253 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
254 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
256 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
257 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
259 /* -i (interactive) and -s (read stdin) are also accepted,
260 * but currently do nothing, therefore aren't shown in help.
261 * NOMMU-specific options are not meant to be used by users,
262 * therefore we don't show them either.
264 //usage:#define hush_trivial_usage
265 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
266 //usage:#define hush_full_usage "\n\n"
267 //usage: "Unix shell interpreter"
269 //usage:#define msh_trivial_usage hush_trivial_usage
270 //usage:#define msh_full_usage hush_full_usage
272 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
273 //usage:# define sh_trivial_usage hush_trivial_usage
274 //usage:# define sh_full_usage hush_full_usage
276 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
277 //usage:# define bash_trivial_usage hush_trivial_usage
278 //usage:# define bash_full_usage hush_full_usage
283 #define LEAK_HUNTING 0
284 #define BUILD_AS_NOMMU 0
285 /* Enable/disable sanity checks. Ok to enable in production,
286 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
287 * Keeping 1 for now even in released versions.
290 /* Slightly bigger (+200 bytes), but faster hush.
291 * So far it only enables a trick with counting SIGCHLDs and forks,
292 * which allows us to do fewer waitpid's.
293 * (we can detect a case where neither forks were done nor SIGCHLDs happened
294 * and therefore waitpid will return the same result as last time)
296 #define ENABLE_HUSH_FAST 0
297 /* TODO: implement simplified code for users which do not need ${var%...} ops
298 * So far ${var%...} ops are always enabled:
300 #define ENABLE_HUSH_DOLLAR_OPS 1
305 # undef USE_FOR_NOMMU
308 # define USE_FOR_NOMMU(...) __VA_ARGS__
309 # define USE_FOR_MMU(...)
312 #include "NUM_APPLETS.h"
314 /* STANDALONE does not make sense, and won't compile */
315 # undef CONFIG_FEATURE_SH_STANDALONE
316 # undef ENABLE_FEATURE_SH_STANDALONE
317 # undef IF_FEATURE_SH_STANDALONE
318 # undef IF_NOT_FEATURE_SH_STANDALONE
319 # define ENABLE_FEATURE_SH_STANDALONE 0
320 # define IF_FEATURE_SH_STANDALONE(...)
321 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
324 #if !ENABLE_HUSH_INTERACTIVE
325 # undef ENABLE_FEATURE_EDITING
326 # define ENABLE_FEATURE_EDITING 0
327 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
328 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
329 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
330 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
333 /* Do we support ANY keywords? */
334 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
335 # define HAS_KEYWORDS 1
336 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
337 # define IF_HAS_NO_KEYWORDS(...)
339 # define HAS_KEYWORDS 0
340 # define IF_HAS_KEYWORDS(...)
341 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
344 /* If you comment out one of these below, it will be #defined later
345 * to perform debug printfs to stderr: */
346 #define debug_printf(...) do {} while (0)
347 /* Finer-grained debug switches */
348 #define debug_printf_parse(...) do {} while (0)
349 #define debug_print_tree(a, b) do {} while (0)
350 #define debug_printf_exec(...) do {} while (0)
351 #define debug_printf_env(...) do {} while (0)
352 #define debug_printf_jobs(...) do {} while (0)
353 #define debug_printf_expand(...) do {} while (0)
354 #define debug_printf_varexp(...) do {} while (0)
355 #define debug_printf_glob(...) do {} while (0)
356 #define debug_printf_list(...) do {} while (0)
357 #define debug_printf_subst(...) do {} while (0)
358 #define debug_printf_clean(...) do {} while (0)
360 #define ERR_PTR ((void*)(long)1)
362 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
364 #define _SPECIAL_VARS_STR "_*@$!?#"
365 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
366 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
367 #if ENABLE_HUSH_BASH_COMPAT
368 /* Support / and // replace ops */
369 /* Note that // is stored as \ in "encoded" string representation */
370 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
371 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
372 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
374 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
375 # define VAR_SUBST_OPS "%#:-=+?"
376 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
379 #define SPECIAL_VAR_SYMBOL 3
383 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
385 /* This supports saving pointers malloced in vfork child,
386 * to be freed in the parent.
389 typedef struct nommu_save_t {
391 struct variable *old_vars;
393 char **argv_from_re_execing;
406 #if ENABLE_HUSH_LOOPS
413 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
418 /* three pseudo-keywords support contrived "case" syntax: */
419 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
420 RES_MATCH , /* "word)" */
421 RES_CASE_BODY, /* "this command is inside CASE" */
428 typedef struct o_string {
430 int length; /* position where data is appended */
433 /* At least some part of the string was inside '' or "",
434 * possibly empty one: word"", wo''rd etc. */
435 smallint has_quoted_part;
436 smallint has_empty_slot;
437 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
440 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
442 /* Protect newly added chars against globbing
443 * by prepending \ to *, ?, [, \ */
444 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
447 MAYBE_ASSIGNMENT = 0,
448 DEFINITELY_ASSIGNMENT = 1,
450 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
453 /* Used for initialization: o_string foo = NULL_O_STRING; */
454 #define NULL_O_STRING { NULL }
456 #ifndef debug_printf_parse
457 static const char *const assignment_flag[] = {
459 "DEFINITELY_ASSIGNMENT",
465 typedef struct in_str {
467 #if ENABLE_HUSH_INTERACTIVE
468 smallint promptmode; /* 0: PS1, 1: PS2 */
473 int (*get) (struct in_str *) FAST_FUNC;
474 int (*peek) (struct in_str *) FAST_FUNC;
476 #define i_getch(input) ((input)->get(input))
477 #define i_peek(input) ((input)->peek(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;
782 # define G_flag_return_in_progress (G.flag_return_in_progress)
784 # define G_flag_return_in_progress 0
786 smallint exiting; /* used to prevent EXIT trap recursion */
787 /* These four support $?, $#, and $1 */
788 smalluint last_exitcode;
789 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
790 smalluint global_args_malloced;
791 /* how many non-NULL argv's we have. NB: $# + 1 */
795 char *argv0_for_re_execing;
797 #if ENABLE_HUSH_LOOPS
798 unsigned depth_break_continue;
799 unsigned depth_of_loop;
803 struct variable *top_var;
804 char **expanded_assignments;
805 #if ENABLE_HUSH_FUNCTIONS
806 struct function *top_func;
807 # if ENABLE_HUSH_LOCAL
808 struct variable **shadowed_vars_pp;
809 unsigned func_nest_level;
812 /* Signal and trap handling */
814 unsigned count_SIGCHLD;
815 unsigned handled_SIGCHLD;
816 smallint we_have_children;
818 struct FILE_list *FILE_list;
819 /* Which signals have non-DFL handler (even with no traps set)?
820 * Set at the start to:
821 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
822 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
823 * The rest is cleared right before execv syscalls.
824 * Other than these two times, never modified.
826 unsigned special_sig_mask;
828 unsigned fatal_sig_mask;
829 # define G_fatal_sig_mask G.fatal_sig_mask
831 # define G_fatal_sig_mask 0
833 char **traps; /* char *traps[NSIG] */
834 sigset_t pending_set;
836 unsigned long memleak_value;
840 #if ENABLE_FEATURE_EDITING
841 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
844 #define G (*ptr_to_globals)
845 /* Not #defining name to G.name - this quickly gets unwieldy
846 * (too many defines). Also, I actually prefer to see when a variable
847 * is global, thus "G." prefix is a useful hint */
848 #define INIT_G() do { \
849 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
850 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
851 sigfillset(&G.sa.sa_mask); \
852 G.sa.sa_flags = SA_RESTART; \
856 /* Function prototypes for builtins */
857 static int builtin_cd(char **argv) FAST_FUNC;
858 static int builtin_echo(char **argv) FAST_FUNC;
859 static int builtin_eval(char **argv) FAST_FUNC;
860 static int builtin_exec(char **argv) FAST_FUNC;
861 static int builtin_exit(char **argv) FAST_FUNC;
862 static int builtin_export(char **argv) FAST_FUNC;
864 static int builtin_fg_bg(char **argv) FAST_FUNC;
865 static int builtin_jobs(char **argv) FAST_FUNC;
868 static int builtin_help(char **argv) FAST_FUNC;
870 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
871 static int builtin_history(char **argv) FAST_FUNC;
873 #if ENABLE_HUSH_LOCAL
874 static int builtin_local(char **argv) FAST_FUNC;
877 static int builtin_memleak(char **argv) FAST_FUNC;
880 static int builtin_printf(char **argv) FAST_FUNC;
882 static int builtin_pwd(char **argv) FAST_FUNC;
883 static int builtin_read(char **argv) FAST_FUNC;
884 static int builtin_set(char **argv) FAST_FUNC;
885 static int builtin_shift(char **argv) FAST_FUNC;
886 static int builtin_source(char **argv) FAST_FUNC;
887 static int builtin_test(char **argv) FAST_FUNC;
888 static int builtin_trap(char **argv) FAST_FUNC;
889 static int builtin_type(char **argv) FAST_FUNC;
890 static int builtin_true(char **argv) FAST_FUNC;
891 static int builtin_umask(char **argv) FAST_FUNC;
892 static int builtin_unset(char **argv) FAST_FUNC;
893 static int builtin_wait(char **argv) FAST_FUNC;
894 #if ENABLE_HUSH_LOOPS
895 static int builtin_break(char **argv) FAST_FUNC;
896 static int builtin_continue(char **argv) FAST_FUNC;
898 #if ENABLE_HUSH_FUNCTIONS
899 static int builtin_return(char **argv) FAST_FUNC;
902 /* Table of built-in functions. They can be forked or not, depending on
903 * context: within pipes, they fork. As simple commands, they do not.
904 * When used in non-forking context, they can change global variables
905 * in the parent shell process. If forked, of course they cannot.
906 * For example, 'unset foo | whatever' will parse and run, but foo will
907 * still be set at the end. */
908 struct built_in_command {
910 int (*b_function)(char **argv) FAST_FUNC;
913 # define BLTIN(cmd, func, help) { cmd, func, help }
915 # define BLTIN(cmd, func, help) { cmd, func }
919 static const struct built_in_command bltins1[] = {
920 BLTIN("." , builtin_source , "Run commands in a file"),
921 BLTIN(":" , builtin_true , NULL),
923 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
925 #if ENABLE_HUSH_LOOPS
926 BLTIN("break" , builtin_break , "Exit from a loop"),
928 BLTIN("cd" , builtin_cd , "Change directory"),
929 #if ENABLE_HUSH_LOOPS
930 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
932 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
933 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
934 BLTIN("exit" , builtin_exit , "Exit"),
935 BLTIN("export" , builtin_export , "Set environment variables"),
937 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
940 BLTIN("help" , builtin_help , NULL),
942 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
943 BLTIN("history" , builtin_history , "Show command history"),
946 BLTIN("jobs" , builtin_jobs , "List jobs"),
948 #if ENABLE_HUSH_LOCAL
949 BLTIN("local" , builtin_local , "Set local variables"),
952 BLTIN("memleak" , builtin_memleak , NULL),
954 BLTIN("read" , builtin_read , "Input into variable"),
955 #if ENABLE_HUSH_FUNCTIONS
956 BLTIN("return" , builtin_return , "Return from a function"),
958 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
959 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
960 #if ENABLE_HUSH_BASH_COMPAT
961 BLTIN("source" , builtin_source , "Run commands in a file"),
963 BLTIN("trap" , builtin_trap , "Trap signals"),
964 BLTIN("true" , builtin_true , NULL),
965 BLTIN("type" , builtin_type , "Show command type"),
966 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
967 BLTIN("umask" , builtin_umask , "Set file creation mask"),
968 BLTIN("unset" , builtin_unset , "Unset variables"),
969 BLTIN("wait" , builtin_wait , "Wait for process"),
971 /* For now, echo and test are unconditionally enabled.
972 * Maybe make it configurable? */
973 static const struct built_in_command bltins2[] = {
974 BLTIN("[" , builtin_test , NULL),
975 BLTIN("echo" , builtin_echo , NULL),
977 BLTIN("printf" , builtin_printf , NULL),
979 BLTIN("pwd" , builtin_pwd , NULL),
980 BLTIN("test" , builtin_test , NULL),
987 /* prevent disasters with G.debug_indent < 0 */
988 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
989 # define debug_enter() (G.debug_indent++)
990 # define debug_leave() (G.debug_indent--)
992 # define indent() ((void)0)
993 # define debug_enter() ((void)0)
994 # define debug_leave() ((void)0)
998 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1001 #ifndef debug_printf_parse
1002 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1005 #ifndef debug_printf_exec
1006 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1009 #ifndef debug_printf_env
1010 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1013 #ifndef debug_printf_jobs
1014 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1015 # define DEBUG_JOBS 1
1017 # define DEBUG_JOBS 0
1020 #ifndef debug_printf_expand
1021 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1022 # define DEBUG_EXPAND 1
1024 # define DEBUG_EXPAND 0
1027 #ifndef debug_printf_varexp
1028 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1031 #ifndef debug_printf_glob
1032 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1033 # define DEBUG_GLOB 1
1035 # define DEBUG_GLOB 0
1038 #ifndef debug_printf_list
1039 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1042 #ifndef debug_printf_subst
1043 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1046 #ifndef debug_printf_clean
1047 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1048 # define DEBUG_CLEAN 1
1050 # define DEBUG_CLEAN 0
1054 static void debug_print_strings(const char *prefix, char **vv)
1057 fdprintf(2, "%s:\n", prefix);
1059 fdprintf(2, " '%s'\n", *vv++);
1062 # define debug_print_strings(prefix, vv) ((void)0)
1066 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1069 static void *xxmalloc(int lineno, size_t size)
1071 void *ptr = xmalloc((size + 0xff) & ~0xff);
1072 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1075 static void *xxrealloc(int lineno, void *ptr, size_t size)
1077 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1078 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1081 static char *xxstrdup(int lineno, const char *str)
1083 char *ptr = xstrdup(str);
1084 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1087 static void xxfree(void *ptr)
1089 fdprintf(2, "free %p\n", ptr);
1092 # define xmalloc(s) xxmalloc(__LINE__, s)
1093 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1094 # define xstrdup(s) xxstrdup(__LINE__, s)
1095 # define free(p) xxfree(p)
1099 /* Syntax and runtime errors. They always abort scripts.
1100 * In interactive use they usually discard unparsed and/or unexecuted commands
1101 * and return to the prompt.
1102 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1105 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1106 # define syntax_error(lineno, msg) syntax_error(msg)
1107 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1108 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1109 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1110 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1113 static void die_if_script(unsigned lineno, const char *fmt, ...)
1118 bb_error_msg("hush.c:%u", lineno);
1121 bb_verror_msg(fmt, p, NULL);
1123 if (!G_interactive_fd)
1127 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1130 bb_error_msg("syntax error: %s", msg);
1132 bb_error_msg("syntax error");
1135 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1137 bb_error_msg("syntax error at '%s'", msg);
1140 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1142 bb_error_msg("syntax error: unterminated %s", s);
1145 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1147 char msg[2] = { ch, '\0' };
1148 syntax_error_unterm_str(lineno, msg);
1151 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1156 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1160 # undef die_if_script
1161 # undef syntax_error
1162 # undef syntax_error_at
1163 # undef syntax_error_unterm_ch
1164 # undef syntax_error_unterm_str
1165 # undef syntax_error_unexpected_ch
1167 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1168 # define syntax_error(msg) syntax_error(__LINE__, msg)
1169 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1170 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1171 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1172 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1176 #if ENABLE_HUSH_INTERACTIVE
1177 static void cmdedit_update_prompt(void);
1179 # define cmdedit_update_prompt() ((void)0)
1183 /* Utility functions
1185 /* Replace each \x with x in place, return ptr past NUL. */
1186 static char *unbackslash(char *src)
1188 char *dst = src = strchrnul(src, '\\');
1192 if ((*dst++ = *src++) == '\0')
1198 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1219 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1220 v[count1 + count2] = NULL;
1223 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1227 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1229 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1230 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1233 #define add_strings_to_strings(strings, add, need_to_dup) \
1234 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1237 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1238 static char **add_string_to_strings(char **strings, char *add)
1243 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1246 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1248 char **ptr = add_string_to_strings(strings, add);
1249 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1252 #define add_string_to_strings(strings, add) \
1253 xx_add_string_to_strings(__LINE__, strings, add)
1256 static void free_strings(char **strings)
1271 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1273 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1274 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1276 /* fd was not open? */
1286 /* Manipulating the list of open FILEs */
1287 static FILE *remember_FILE(FILE *fp)
1290 struct FILE_list *n = xmalloc(sizeof(*n));
1291 n->next = G.FILE_list;
1295 close_on_exec_on(n->fd);
1299 static void fclose_and_forget(FILE *fp)
1301 struct FILE_list **pp = &G.FILE_list;
1303 struct FILE_list *cur = *pp;
1304 if (cur->fp == fp) {
1313 static int save_FILEs_on_redirect(int fd)
1315 struct FILE_list *fl = G.FILE_list;
1318 /* We use it only on script files, they are all CLOEXEC */
1319 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1326 static void restore_redirected_FILEs(void)
1328 struct FILE_list *fl = G.FILE_list;
1330 int should_be = fileno(fl->fp);
1331 if (fl->fd != should_be) {
1332 xmove_fd(fl->fd, should_be);
1338 #if ENABLE_FEATURE_SH_STANDALONE
1339 static void close_all_FILE_list(void)
1341 struct FILE_list *fl = G.FILE_list;
1343 /* fclose would also free FILE object.
1344 * It is disastrous if we share memory with a vforked parent.
1345 * I'm not sure we never come here after vfork.
1346 * Therefore just close fd, nothing more.
1348 /*fclose(fl->fp); - unsafe */
1356 /* Helpers for setting new $n and restoring them back
1358 typedef struct save_arg_t {
1362 smallint sv_g_malloced;
1365 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1369 sv->sv_argv0 = argv[0];
1370 sv->sv_g_argv = G.global_argv;
1371 sv->sv_g_argc = G.global_argc;
1372 sv->sv_g_malloced = G.global_args_malloced;
1374 argv[0] = G.global_argv[0]; /* retain $0 */
1375 G.global_argv = argv;
1376 G.global_args_malloced = 0;
1384 static void restore_G_args(save_arg_t *sv, char **argv)
1388 if (G.global_args_malloced) {
1389 /* someone ran "set -- arg1 arg2 ...", undo */
1391 while (*++pp) /* note: does not free $0 */
1393 free(G.global_argv);
1395 argv[0] = sv->sv_argv0;
1396 G.global_argv = sv->sv_g_argv;
1397 G.global_argc = sv->sv_g_argc;
1398 G.global_args_malloced = sv->sv_g_malloced;
1402 /* Basic theory of signal handling in shell
1403 * ========================================
1404 * This does not describe what hush does, rather, it is current understanding
1405 * what it _should_ do. If it doesn't, it's a bug.
1406 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1408 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1409 * is finished or backgrounded. It is the same in interactive and
1410 * non-interactive shells, and is the same regardless of whether
1411 * a user trap handler is installed or a shell special one is in effect.
1412 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1413 * backgrounds (i.e. stops) or kills all members of currently running
1416 * Wait builtin is interruptible by signals for which user trap is set
1417 * or by SIGINT in interactive shell.
1419 * Trap handlers will execute even within trap handlers. (right?)
1421 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1422 * except for handlers set to '' (empty string).
1424 * If job control is off, backgrounded commands ("cmd &")
1425 * have SIGINT, SIGQUIT set to SIG_IGN.
1427 * Commands which are run in command substitution ("`cmd`")
1428 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1430 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1431 * by the shell from its parent.
1433 * Signals which differ from SIG_DFL action
1434 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1437 * SIGTERM (interactive): ignore
1438 * SIGHUP (interactive):
1439 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1440 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1441 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1442 * that all pipe members are stopped. Try this in bash:
1443 * while :; do :; done - ^Z does not background it
1444 * (while :; do :; done) - ^Z backgrounds it
1445 * SIGINT (interactive): wait for last pipe, ignore the rest
1446 * of the command line, show prompt. NB: ^C does not send SIGINT
1447 * to interactive shell while shell is waiting for a pipe,
1448 * since shell is bg'ed (is not in foreground process group).
1449 * Example 1: this waits 5 sec, but does not execute ls:
1450 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1451 * Example 2: this does not wait and does not execute ls:
1452 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1453 * Example 3: this does not wait 5 sec, but executes ls:
1454 * "sleep 5; ls -l" + press ^C
1455 * Example 4: this does not wait and does not execute ls:
1456 * "sleep 5 & wait; ls -l" + press ^C
1458 * (What happens to signals which are IGN on shell start?)
1459 * (What happens with signal mask on shell start?)
1461 * Old implementation
1462 * ==================
1463 * We use in-kernel pending signal mask to determine which signals were sent.
1464 * We block all signals which we don't want to take action immediately,
1465 * i.e. we block all signals which need to have special handling as described
1466 * above, and all signals which have traps set.
1467 * After each pipe execution, we extract any pending signals via sigtimedwait()
1470 * unsigned special_sig_mask: a mask of such "special" signals
1471 * sigset_t blocked_set: current blocked signal set
1474 * clear bit in blocked_set unless it is also in special_sig_mask
1475 * "trap 'cmd' SIGxxx":
1476 * set bit in blocked_set (even if 'cmd' is '')
1477 * after [v]fork, if we plan to be a shell:
1478 * unblock signals with special interactive handling
1479 * (child shell is not interactive),
1480 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1481 * after [v]fork, if we plan to exec:
1482 * POSIX says fork clears pending signal mask in child - no need to clear it.
1483 * Restore blocked signal set to one inherited by shell just prior to exec.
1485 * Note: as a result, we do not use signal handlers much. The only uses
1486 * are to count SIGCHLDs
1487 * and to restore tty pgrp on signal-induced exit.
1490 * Standard says "When a subshell is entered, traps that are not being ignored
1491 * are set to the default actions". bash interprets it so that traps which
1492 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1494 * Problem: the above approach makes it unwieldy to catch signals while
1495 * we are in read builtin, or while we read commands from stdin:
1496 * masked signals are not visible!
1498 * New implementation
1499 * ==================
1500 * We record each signal we are interested in by installing signal handler
1501 * for them - a bit like emulating kernel pending signal mask in userspace.
1502 * We are interested in: signals which need to have special handling
1503 * as described above, and all signals which have traps set.
1504 * Signals are recorded in pending_set.
1505 * After each pipe execution, we extract any pending signals
1508 * unsigned special_sig_mask: a mask of shell-special signals.
1509 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1510 * char *traps[sig] if trap for sig is set (even if it's '').
1511 * sigset_t pending_set: set of sigs we received.
1514 * if sig is in special_sig_mask, set handler back to:
1515 * record_pending_signo, or to IGN if it's a tty stop signal
1516 * if sig is in fatal_sig_mask, set handler back to sigexit.
1517 * else: set handler back to SIG_DFL
1518 * "trap 'cmd' SIGxxx":
1519 * set handler to record_pending_signo.
1521 * set handler to SIG_IGN.
1522 * after [v]fork, if we plan to be a shell:
1523 * set signals with special interactive handling to SIG_DFL
1524 * (because child shell is not interactive),
1525 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1526 * after [v]fork, if we plan to exec:
1527 * POSIX says fork clears pending signal mask in child - no need to clear it.
1529 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1530 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1533 * Standard says "When a subshell is entered, traps that are not being ignored
1534 * are set to the default actions". bash interprets it so that traps which
1535 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1538 SPECIAL_INTERACTIVE_SIGS = 0
1543 SPECIAL_JOBSTOP_SIGS = 0
1552 static void record_pending_signo(int sig)
1554 sigaddset(&G.pending_set, sig);
1555 #if ENABLE_HUSH_FAST
1556 if (sig == SIGCHLD) {
1558 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1563 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1565 struct sigaction old_sa;
1567 /* We could use signal() to install handlers... almost:
1568 * except that we need to mask ALL signals while handlers run.
1569 * I saw signal nesting in strace, race window isn't small.
1570 * SA_RESTART is also needed, but in Linux, signal()
1571 * sets SA_RESTART too.
1573 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1574 /* sigfillset(&G.sa.sa_mask); - already done */
1575 /* G.sa.sa_flags = SA_RESTART; - already done */
1576 G.sa.sa_handler = handler;
1577 sigaction(sig, &G.sa, &old_sa);
1578 return old_sa.sa_handler;
1581 static void hush_exit(int exitcode) NORETURN;
1582 static void fflush_and__exit(void) NORETURN;
1583 static void restore_ttypgrp_and__exit(void) NORETURN;
1585 static void restore_ttypgrp_and__exit(void)
1587 /* xfunc has failed! die die die */
1588 /* no EXIT traps, this is an escape hatch! */
1590 hush_exit(xfunc_error_retval);
1593 /* Needed only on some libc:
1594 * It was observed that on exit(), fgetc'ed buffered data
1595 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1596 * With the net effect that even after fork(), not vfork(),
1597 * exit() in NOEXECed applet in "sh SCRIPT":
1598 * noexec_applet_here
1599 * echo END_OF_SCRIPT
1600 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1601 * This makes "echo END_OF_SCRIPT" executed twice.
1602 * Similar problems can be seen with die_if_script() -> xfunc_die()
1603 * and in `cmd` handling.
1604 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1606 static void fflush_and__exit(void)
1609 _exit(xfunc_error_retval);
1614 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1615 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1616 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1617 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1619 /* Restores tty foreground process group, and exits.
1620 * May be called as signal handler for fatal signal
1621 * (will resend signal to itself, producing correct exit state)
1622 * or called directly with -EXITCODE.
1623 * We also call it if xfunc is exiting.
1625 static void sigexit(int sig) NORETURN;
1626 static void sigexit(int sig)
1628 /* Careful: we can end up here after [v]fork. Do not restore
1629 * tty pgrp then, only top-level shell process does that */
1630 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1631 /* Disable all signals: job control, SIGPIPE, etc.
1632 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1634 sigprocmask_allsigs(SIG_BLOCK);
1635 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1638 /* Not a signal, just exit */
1642 kill_myself_with_sig(sig); /* does not return */
1646 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1647 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1651 static sighandler_t pick_sighandler(unsigned sig)
1653 sighandler_t handler = SIG_DFL;
1654 if (sig < sizeof(unsigned)*8) {
1655 unsigned sigmask = (1 << sig);
1659 if (G_fatal_sig_mask & sigmask)
1663 /* sig has special handling? */
1664 if (G.special_sig_mask & sigmask) {
1665 handler = record_pending_signo;
1666 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1667 * in order to ignore them: they will be raised
1668 * in an endless loop when we try to do some
1669 * terminal ioctls! We do have to _ignore_ these.
1671 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1678 /* Restores tty foreground process group, and exits. */
1679 static void hush_exit(int exitcode)
1681 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1682 save_history(G.line_input_state);
1686 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1688 /* argv[0] is unused */
1689 argv[1] = G.traps[0];
1691 G.exiting = 1; /* prevent EXIT trap recursion */
1692 /* Note: G.traps[0] is not cleared!
1693 * "trap" will still show it, if executed
1698 #if ENABLE_FEATURE_CLEAN_UP
1700 struct variable *cur_var;
1701 if (G.cwd != bb_msg_unknown)
1703 cur_var = G.top_var;
1705 struct variable *tmp = cur_var;
1706 if (!cur_var->max_len)
1707 free(cur_var->varstr);
1708 cur_var = cur_var->next;
1716 sigexit(- (exitcode & 0xff));
1723 //TODO: return a mask of ALL handled sigs?
1724 static int check_and_run_traps(void)
1731 if (sigisemptyset(&G.pending_set))
1736 if (sigismember(&G.pending_set, sig)) {
1737 sigdelset(&G.pending_set, sig);
1740 } while (sig < NSIG);
1743 if (G.traps && G.traps[sig]) {
1744 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1745 if (G.traps[sig][0]) {
1746 /* We have user-defined handler */
1747 smalluint save_rcode;
1749 /* argv[0] is unused */
1750 argv[1] = G.traps[sig];
1752 save_rcode = G.last_exitcode;
1754 G.last_exitcode = save_rcode;
1756 } /* else: "" trap, ignoring signal */
1759 /* not a trap: special action */
1762 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1763 /* Builtin was ^C'ed, make it look prettier: */
1771 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1772 /* bash is observed to signal whole process groups,
1773 * not individual processes */
1774 for (job = G.job_list; job; job = job->next) {
1777 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1778 if (kill(- job->pgrp, SIGHUP) == 0)
1779 kill(- job->pgrp, SIGCONT);
1784 #if ENABLE_HUSH_FAST
1786 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1788 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1790 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1791 * This simplifies wait builtin a bit.
1795 default: /* ignored: */
1796 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1797 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1799 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1800 * Example: wait is not interrupted by TERM
1801 * in interactive shell, because TERM is ignored.
1810 static const char *get_cwd(int force)
1812 if (force || G.cwd == NULL) {
1813 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1814 * we must not try to free(bb_msg_unknown) */
1815 if (G.cwd == bb_msg_unknown)
1817 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1819 G.cwd = bb_msg_unknown;
1826 * Shell and environment variable support
1828 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1830 struct variable **pp;
1831 struct variable *cur;
1834 while ((cur = *pp) != NULL) {
1835 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1842 static const char* FAST_FUNC get_local_var_value(const char *name)
1844 struct variable **vpp;
1845 unsigned len = strlen(name);
1847 if (G.expanded_assignments) {
1848 char **cpp = G.expanded_assignments;
1851 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1852 return cp + len + 1;
1857 vpp = get_ptr_to_local_var(name, len);
1859 return (*vpp)->varstr + len + 1;
1861 if (strcmp(name, "PPID") == 0)
1862 return utoa(G.root_ppid);
1863 // bash compat: UID? EUID?
1864 #if ENABLE_HUSH_RANDOM_SUPPORT
1865 if (strcmp(name, "RANDOM") == 0)
1866 return utoa(next_random(&G.random_gen));
1871 /* str holds "NAME=VAL" and is expected to be malloced.
1872 * We take ownership of it.
1874 * 0: do not change export flag
1875 * (if creating new variable, flag will be 0)
1876 * 1: set export flag and putenv the variable
1877 * -1: clear export flag and unsetenv the variable
1878 * flg_read_only is set only when we handle -R var=val
1880 #if !BB_MMU && ENABLE_HUSH_LOCAL
1881 /* all params are used */
1882 #elif BB_MMU && ENABLE_HUSH_LOCAL
1883 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1884 set_local_var(str, flg_export, local_lvl)
1885 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1886 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1887 set_local_var(str, flg_export)
1888 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1889 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1890 set_local_var(str, flg_export, flg_read_only)
1892 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1894 struct variable **var_pp;
1895 struct variable *cur;
1896 char *free_me = NULL;
1900 eq_sign = strchr(str, '=');
1901 if (!eq_sign) { /* not expected to ever happen? */
1906 name_len = eq_sign - str + 1; /* including '=' */
1907 var_pp = &G.top_var;
1908 while ((cur = *var_pp) != NULL) {
1909 if (strncmp(cur->varstr, str, name_len) != 0) {
1910 var_pp = &cur->next;
1914 /* We found an existing var with this name */
1915 if (cur->flg_read_only) {
1919 bb_error_msg("%s: readonly variable", str);
1923 if (flg_export == -1) { // "&& cur->flg_export" ?
1924 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1929 #if ENABLE_HUSH_LOCAL
1930 if (cur->func_nest_level < local_lvl) {
1931 /* New variable is declared as local,
1932 * and existing one is global, or local
1933 * from enclosing function.
1934 * Remove and save old one: */
1935 *var_pp = cur->next;
1936 cur->next = *G.shadowed_vars_pp;
1937 *G.shadowed_vars_pp = cur;
1938 /* bash 3.2.33(1) and exported vars:
1940 * # f() { local z=a; env | grep ^z; }
1946 if (cur->flg_export)
1951 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1956 if (cur->max_len != 0) {
1957 if (cur->max_len >= strlen(str)) {
1958 /* This one is from startup env, reuse space */
1959 strcpy(cur->varstr, str);
1964 goto set_str_and_exp;
1966 /* max_len == 0 signifies "malloced" var, which we can
1967 * (and have to) free. But we can't free(cur->varstr) here:
1968 * if cur->flg_export is 1, it is in the environment.
1969 * We should either unsetenv+free, or wait until putenv,
1970 * then putenv(new)+free(old).
1972 free_me = cur->varstr;
1973 goto set_str_and_exp;
1976 /* Not found - create new variable struct */
1977 cur = xzalloc(sizeof(*cur));
1978 #if ENABLE_HUSH_LOCAL
1979 cur->func_nest_level = local_lvl;
1981 cur->next = *var_pp;
1987 cur->flg_read_only = flg_read_only;
1990 if (flg_export == 1)
1991 cur->flg_export = 1;
1992 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1993 cmdedit_update_prompt();
1994 if (cur->flg_export) {
1995 if (flg_export == -1) {
1996 cur->flg_export = 0;
1997 /* unsetenv was already done */
2000 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2001 i = putenv(cur->varstr);
2002 /* only now we can free old exported malloced string */
2011 /* Used at startup and after each cd */
2012 static void set_pwd_var(int exp)
2014 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2015 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2018 static int unset_local_var_len(const char *name, int name_len)
2020 struct variable *cur;
2021 struct variable **var_pp;
2024 return EXIT_SUCCESS;
2025 var_pp = &G.top_var;
2026 while ((cur = *var_pp) != NULL) {
2027 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2028 if (cur->flg_read_only) {
2029 bb_error_msg("%s: readonly variable", name);
2030 return EXIT_FAILURE;
2032 *var_pp = cur->next;
2033 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2034 bb_unsetenv(cur->varstr);
2035 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2036 cmdedit_update_prompt();
2040 return EXIT_SUCCESS;
2042 var_pp = &cur->next;
2044 return EXIT_SUCCESS;
2047 static int unset_local_var(const char *name)
2049 return unset_local_var_len(name, strlen(name));
2052 static void unset_vars(char **strings)
2060 const char *eq = strchrnul(*v, '=');
2061 unset_local_var_len(*v, (int)(eq - *v));
2067 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2069 char *var = xasprintf("%s=%s", name, val);
2070 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2075 * Helpers for "var1=val1 var2=val2 cmd" feature
2077 static void add_vars(struct variable *var)
2079 struct variable *next;
2083 var->next = G.top_var;
2085 if (var->flg_export) {
2086 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2087 putenv(var->varstr);
2089 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2095 static struct variable *set_vars_and_save_old(char **strings)
2098 struct variable *old = NULL;
2104 struct variable *var_p;
2105 struct variable **var_pp;
2108 eq = strchr(*s, '=');
2110 var_pp = get_ptr_to_local_var(*s, eq - *s);
2112 /* Remove variable from global linked list */
2114 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2115 *var_pp = var_p->next;
2116 /* Add it to returned list */
2120 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2131 static void reinit_unicode_for_hush(void)
2133 /* Unicode support should be activated even if LANG is set
2134 * _during_ shell execution, not only if it was set when
2135 * shell was started. Therefore, re-check LANG every time:
2137 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2138 || ENABLE_UNICODE_USING_LOCALE
2140 const char *s = get_local_var_value("LC_ALL");
2141 if (!s) s = get_local_var_value("LC_CTYPE");
2142 if (!s) s = get_local_var_value("LANG");
2148 * in_str support (strings, and "strings" read from files).
2151 #if ENABLE_HUSH_INTERACTIVE
2152 /* To test correct lineedit/interactive behavior, type from command line:
2158 * It excercises a lot of corner cases.
2160 static void cmdedit_update_prompt(void)
2162 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2163 G.PS1 = get_local_var_value("PS1");
2166 G.PS2 = get_local_var_value("PS2");
2173 static const char *setup_prompt_string(int promptmode)
2175 const char *prompt_str;
2176 debug_printf("setup_prompt_string %d ", promptmode);
2177 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2178 /* Set up the prompt */
2179 if (promptmode == 0) { /* PS1 */
2181 /* bash uses $PWD value, even if it is set by user.
2182 * It uses current dir only if PWD is unset.
2183 * We always use current dir. */
2184 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2189 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2190 debug_printf("prompt_str '%s'\n", prompt_str);
2193 static int get_user_input(struct in_str *i)
2196 const char *prompt_str;
2198 prompt_str = setup_prompt_string(i->promptmode);
2199 # if ENABLE_FEATURE_EDITING
2201 reinit_unicode_for_hush();
2203 /* buglet: SIGINT will not make new prompt to appear _at once_,
2204 * only after <Enter>. (^C will work) */
2205 r = read_line_input(G.line_input_state, prompt_str,
2206 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2209 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2210 check_and_run_traps();
2211 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2213 /* EOF/error detected */
2215 i->peek_buf[0] = r = EOF;
2218 i->p = G.user_input_buf;
2219 return (unsigned char)*i->p++;
2223 if (i->last_char == '\0' || i->last_char == '\n') {
2224 /* Why check_and_run_traps here? Try this interactively:
2225 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2226 * $ <[enter], repeatedly...>
2227 * Without check_and_run_traps, handler never runs.
2229 check_and_run_traps();
2230 fputs(prompt_str, stdout);
2234 } while (G.flag_SIGINT || r == '\0');
2238 /* This is the magic location that prints prompts
2239 * and gets data back from the user */
2240 static int fgetc_interactive(struct in_str *i)
2243 /* If it's interactive stdin, get new line. */
2244 if (G_interactive_fd && i->file == stdin) {
2245 /* Returns first char (or EOF), the rest is in i->p[] */
2246 ch = get_user_input(i);
2247 i->promptmode = 1; /* PS2 */
2249 /* Not stdin: script file, sourced file, etc */
2250 do ch = fgetc(i->file); while (ch == '\0');
2255 static inline int fgetc_interactive(struct in_str *i)
2258 do ch = fgetc(i->file); while (ch == '\0');
2261 #endif /* INTERACTIVE */
2263 static int FAST_FUNC file_get(struct in_str *i)
2267 #if ENABLE_FEATURE_EDITING
2268 /* This can be stdin, check line editing char[] buffer */
2269 if (i->p && *i->p != '\0') {
2270 ch = (unsigned char)*i->p++;
2274 /* peek_buf[] is an int array, not char. Can contain EOF. */
2275 ch = i->peek_buf[0];
2277 int ch2 = i->peek_buf[1];
2278 i->peek_buf[0] = ch2;
2279 if (ch2 == 0) /* very likely, avoid redundant write */
2285 ch = fgetc_interactive(i);
2287 debug_printf("file_get: got '%c' %d\n", ch, ch);
2292 static int FAST_FUNC file_peek(struct in_str *i)
2296 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2297 /* This can be stdin, check line editing char[] buffer */
2298 if (i->p && *i->p != '\0')
2299 return (unsigned char)*i->p;
2301 /* peek_buf[] is an int array, not char. Can contain EOF. */
2302 ch = i->peek_buf[0];
2306 /* Need to get a new char */
2307 ch = fgetc_interactive(i);
2308 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2310 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2311 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2317 i->peek_buf[0] = ch;
2318 /*i->peek_buf[1] = 0; - already is */
2322 static int FAST_FUNC static_get(struct in_str *i)
2324 int ch = (unsigned char)*i->p;
2333 static int FAST_FUNC static_peek(struct in_str *i)
2335 /* Doesn't report EOF on NUL. None of the callers care. */
2336 return (unsigned char)*i->p;
2339 /* Only ever called if i_peek() was called, and did not return EOF.
2340 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2341 * not end-of-line. Therefore we never need to read a new editing line here.
2343 static int i_peek2(struct in_str *i)
2347 /* There are two cases when i->p[] buffer exists.
2348 * (1) it's a string in_str.
2349 * (2) It's a file, and we have a saved line editing buffer.
2350 * In both cases, we know that i->p[0] exists and not NUL, and
2351 * the peek2 result is in i->p[1].
2354 return (unsigned char)i->p[1];
2356 /* Now we know it is a file-based in_str. */
2358 /* peek_buf[] is an int array, not char. Can contain EOF. */
2359 /* Is there 2nd char? */
2360 ch = i->peek_buf[1];
2362 /* We did not read it yet, get it now */
2363 do ch = fgetc(i->file); while (ch == '\0');
2364 i->peek_buf[1] = ch;
2367 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2371 static void setup_file_in_str(struct in_str *i, FILE *f)
2373 memset(i, 0, sizeof(*i));
2375 i->peek = file_peek;
2376 /* i->promptmode = 0; - PS1 (memset did it) */
2381 static void setup_string_in_str(struct in_str *i, const char *s)
2383 memset(i, 0, sizeof(*i));
2384 i->get = static_get;
2385 i->peek = static_peek;
2386 /* i->promptmode = 0; - PS1 (memset did it) */
2394 #define B_CHUNK (32 * sizeof(char*))
2396 static void o_reset_to_empty_unquoted(o_string *o)
2399 o->has_quoted_part = 0;
2404 static void o_free(o_string *o)
2407 memset(o, 0, sizeof(*o));
2410 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2415 static void o_grow_by(o_string *o, int len)
2417 if (o->length + len > o->maxlen) {
2418 o->maxlen += (2 * len) | (B_CHUNK-1);
2419 o->data = xrealloc(o->data, 1 + o->maxlen);
2423 static void o_addchr(o_string *o, int ch)
2425 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2426 if (o->length < o->maxlen) {
2427 /* likely. avoid o_grow_by() call */
2429 o->data[o->length] = ch;
2431 o->data[o->length] = '\0';
2439 /* Valid only if we know o_string is not empty */
2440 static void o_delchr(o_string *o)
2443 o->data[o->length] = '\0';
2447 static void o_addblock(o_string *o, const char *str, int len)
2450 memcpy(&o->data[o->length], str, len);
2452 o->data[o->length] = '\0';
2455 static void o_addstr(o_string *o, const char *str)
2457 o_addblock(o, str, strlen(str));
2461 static void nommu_addchr(o_string *o, int ch)
2467 # define nommu_addchr(o, str) ((void)0)
2470 static void o_addstr_with_NUL(o_string *o, const char *str)
2472 o_addblock(o, str, strlen(str) + 1);
2476 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2477 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2478 * Apparently, on unquoted $v bash still does globbing
2479 * ("v='*.txt'; echo $v" prints all .txt files),
2480 * but NOT brace expansion! Thus, there should be TWO independent
2481 * quoting mechanisms on $v expansion side: one protects
2482 * $v from brace expansion, and other additionally protects "$v" against globbing.
2483 * We have only second one.
2486 #if ENABLE_HUSH_BRACE_EXPANSION
2487 # define MAYBE_BRACES "{}"
2489 # define MAYBE_BRACES ""
2492 /* My analysis of quoting semantics tells me that state information
2493 * is associated with a destination, not a source.
2495 static void o_addqchr(o_string *o, int ch)
2498 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2503 o->data[o->length] = '\\';
2506 o->data[o->length] = ch;
2508 o->data[o->length] = '\0';
2511 static void o_addQchr(o_string *o, int ch)
2514 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2515 && strchr("*?[\\" MAYBE_BRACES, ch)
2518 o->data[o->length] = '\\';
2522 o->data[o->length] = ch;
2524 o->data[o->length] = '\0';
2527 static void o_addqblock(o_string *o, const char *str, int len)
2532 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2533 if (ordinary_cnt > len) /* paranoia */
2535 o_addblock(o, str, ordinary_cnt);
2536 if (ordinary_cnt == len)
2537 return; /* NUL is already added by o_addblock */
2538 str += ordinary_cnt;
2539 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2543 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2545 o->data[o->length] = '\\';
2549 o->data[o->length] = ch;
2552 o->data[o->length] = '\0';
2555 static void o_addQblock(o_string *o, const char *str, int len)
2557 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2558 o_addblock(o, str, len);
2561 o_addqblock(o, str, len);
2564 static void o_addQstr(o_string *o, const char *str)
2566 o_addQblock(o, str, strlen(str));
2569 /* A special kind of o_string for $VAR and `cmd` expansion.
2570 * It contains char* list[] at the beginning, which is grown in 16 element
2571 * increments. Actual string data starts at the next multiple of 16 * (char*).
2572 * list[i] contains an INDEX (int!) into this string data.
2573 * It means that if list[] needs to grow, data needs to be moved higher up
2574 * but list[i]'s need not be modified.
2575 * NB: remembering how many list[i]'s you have there is crucial.
2576 * o_finalize_list() operation post-processes this structure - calculates
2577 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2579 #if DEBUG_EXPAND || DEBUG_GLOB
2580 static void debug_print_list(const char *prefix, o_string *o, int n)
2582 char **list = (char**)o->data;
2583 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2587 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2588 prefix, list, n, string_start, o->length, o->maxlen,
2589 !!(o->o_expflags & EXP_FLAG_GLOB),
2591 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2594 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2595 o->data + (int)(uintptr_t)list[i] + string_start,
2596 o->data + (int)(uintptr_t)list[i] + string_start);
2600 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2602 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2606 # define debug_print_list(prefix, o, n) ((void)0)
2609 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2610 * in list[n] so that it points past last stored byte so far.
2611 * It returns n+1. */
2612 static int o_save_ptr_helper(o_string *o, int n)
2614 char **list = (char**)o->data;
2618 if (!o->has_empty_slot) {
2619 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2620 string_len = o->length - string_start;
2621 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2622 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2623 /* list[n] points to string_start, make space for 16 more pointers */
2624 o->maxlen += 0x10 * sizeof(list[0]);
2625 o->data = xrealloc(o->data, o->maxlen + 1);
2626 list = (char**)o->data;
2627 memmove(list + n + 0x10, list + n, string_len);
2628 o->length += 0x10 * sizeof(list[0]);
2630 debug_printf_list("list[%d]=%d string_start=%d\n",
2631 n, string_len, string_start);
2634 /* We have empty slot at list[n], reuse without growth */
2635 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2636 string_len = o->length - string_start;
2637 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2638 n, string_len, string_start);
2639 o->has_empty_slot = 0;
2641 o->has_quoted_part = 0;
2642 list[n] = (char*)(uintptr_t)string_len;
2646 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2647 static int o_get_last_ptr(o_string *o, int n)
2649 char **list = (char**)o->data;
2650 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2652 return ((int)(uintptr_t)list[n-1]) + string_start;
2655 #if ENABLE_HUSH_BRACE_EXPANSION
2656 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2657 * first, it processes even {a} (no commas), second,
2658 * I didn't manage to make it return strings when they don't match
2659 * existing files. Need to re-implement it.
2663 static int glob_needed(const char *s)
2672 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2678 /* Return pointer to next closing brace or to comma */
2679 static const char *next_brace_sub(const char *cp)
2683 while (*cp != '\0') {
2690 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2696 return *cp != '\0' ? cp : NULL;
2698 /* Recursive brace globber. Note: may garble pattern[]. */
2699 static int glob_brace(char *pattern, o_string *o, int n)
2701 char *new_pattern_buf;
2708 debug_printf_glob("glob_brace('%s')\n", pattern);
2714 if (*begin == '{') {
2715 /* Find the first sub-pattern and at the same time
2716 * find the rest after the closing brace */
2717 next = next_brace_sub(begin);
2719 /* An illegal expression */
2723 /* "{abc}" with no commas - illegal
2724 * brace expr, disregard and skip it */
2730 if (*begin == '\\' && begin[1] != '\0')
2734 debug_printf_glob("begin:%s\n", begin);
2735 debug_printf_glob("next:%s\n", next);
2737 /* Now find the end of the whole brace expression */
2739 while (*rest != '}') {
2740 rest = next_brace_sub(rest);
2742 /* An illegal expression */
2745 debug_printf_glob("rest:%s\n", rest);
2747 rest_len = strlen(++rest) + 1;
2749 /* We are sure the brace expression is well-formed */
2751 /* Allocate working buffer large enough for our work */
2752 new_pattern_buf = xmalloc(strlen(pattern));
2754 /* We have a brace expression. BEGIN points to the opening {,
2755 * NEXT points past the terminator of the first element, and REST
2756 * points past the final }. We will accumulate result names from
2757 * recursive runs for each brace alternative in the buffer using
2762 /* Construct the new glob expression */
2765 mempcpy(new_pattern_buf,
2766 /* We know the prefix for all sub-patterns */
2767 pattern, begin - pattern),
2771 /* Note: glob_brace() may garble new_pattern_buf[].
2772 * That's why we re-copy prefix every time (1st memcpy above).
2774 n = glob_brace(new_pattern_buf, o, n);
2776 /* We saw the last entry */
2780 next = next_brace_sub(next);
2782 free(new_pattern_buf);
2790 memset(&globdata, 0, sizeof(globdata));
2791 gr = glob(pattern, 0, NULL, &globdata);
2792 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2794 if (gr == GLOB_NOMATCH) {
2795 globfree(&globdata);
2796 /* NB: garbles parameter */
2797 unbackslash(pattern);
2798 o_addstr_with_NUL(o, pattern);
2799 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2800 return o_save_ptr_helper(o, n);
2802 if (gr == GLOB_NOSPACE)
2803 bb_error_msg_and_die(bb_msg_memory_exhausted);
2804 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2805 * but we didn't specify it. Paranoia again. */
2806 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2808 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2809 char **argv = globdata.gl_pathv;
2811 o_addstr_with_NUL(o, *argv);
2812 n = o_save_ptr_helper(o, n);
2818 globfree(&globdata);
2822 /* Performs globbing on last list[],
2823 * saving each result as a new list[].
2825 static int perform_glob(o_string *o, int n)
2827 char *pattern, *copy;
2829 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2831 return o_save_ptr_helper(o, n);
2832 pattern = o->data + o_get_last_ptr(o, n);
2833 debug_printf_glob("glob pattern '%s'\n", pattern);
2834 if (!glob_needed(pattern)) {
2835 /* unbackslash last string in o in place, fix length */
2836 o->length = unbackslash(pattern) - o->data;
2837 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2838 return o_save_ptr_helper(o, n);
2841 copy = xstrdup(pattern);
2842 /* "forget" pattern in o */
2843 o->length = pattern - o->data;
2844 n = glob_brace(copy, o, n);
2847 debug_print_list("perform_glob returning", o, n);
2851 #else /* !HUSH_BRACE_EXPANSION */
2854 static int glob_needed(const char *s)
2863 if (*s == '*' || *s == '[' || *s == '?')
2869 /* Performs globbing on last list[],
2870 * saving each result as a new list[].
2872 static int perform_glob(o_string *o, int n)
2878 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2880 return o_save_ptr_helper(o, n);
2881 pattern = o->data + o_get_last_ptr(o, n);
2882 debug_printf_glob("glob pattern '%s'\n", pattern);
2883 if (!glob_needed(pattern)) {
2885 /* unbackslash last string in o in place, fix length */
2886 o->length = unbackslash(pattern) - o->data;
2887 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2888 return o_save_ptr_helper(o, n);
2891 memset(&globdata, 0, sizeof(globdata));
2892 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2893 * If we glob "*.\*" and don't find anything, we need
2894 * to fall back to using literal "*.*", but GLOB_NOCHECK
2895 * will return "*.\*"!
2897 gr = glob(pattern, 0, NULL, &globdata);
2898 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2900 if (gr == GLOB_NOMATCH) {
2901 globfree(&globdata);
2904 if (gr == GLOB_NOSPACE)
2905 bb_error_msg_and_die(bb_msg_memory_exhausted);
2906 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2907 * but we didn't specify it. Paranoia again. */
2908 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2910 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2911 char **argv = globdata.gl_pathv;
2912 /* "forget" pattern in o */
2913 o->length = pattern - o->data;
2915 o_addstr_with_NUL(o, *argv);
2916 n = o_save_ptr_helper(o, n);
2922 globfree(&globdata);
2924 debug_print_list("perform_glob returning", o, n);
2928 #endif /* !HUSH_BRACE_EXPANSION */
2930 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2931 * Otherwise, just finish current list[] and start new */
2932 static int o_save_ptr(o_string *o, int n)
2934 if (o->o_expflags & EXP_FLAG_GLOB) {
2935 /* If o->has_empty_slot, list[n] was already globbed
2936 * (if it was requested back then when it was filled)
2937 * so don't do that again! */
2938 if (!o->has_empty_slot)
2939 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2941 return o_save_ptr_helper(o, n);
2944 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2945 static char **o_finalize_list(o_string *o, int n)
2950 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2952 debug_print_list("finalized", o, n);
2953 debug_printf_expand("finalized n:%d\n", n);
2954 list = (char**)o->data;
2955 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2959 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2964 static void free_pipe_list(struct pipe *pi);
2966 /* Returns pi->next - next pipe in the list */
2967 static struct pipe *free_pipe(struct pipe *pi)
2972 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2973 for (i = 0; i < pi->num_cmds; i++) {
2974 struct command *command;
2975 struct redir_struct *r, *rnext;
2977 command = &pi->cmds[i];
2978 debug_printf_clean(" command %d:\n", i);
2979 if (command->argv) {
2983 for (a = 0, p = command->argv; *p; a++, p++) {
2984 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2987 free_strings(command->argv);
2988 //command->argv = NULL;
2990 /* not "else if": on syntax error, we may have both! */
2991 if (command->group) {
2992 debug_printf_clean(" begin group (cmd_type:%d)\n",
2994 free_pipe_list(command->group);
2995 debug_printf_clean(" end group\n");
2996 //command->group = NULL;
2998 /* else is crucial here.
2999 * If group != NULL, child_func is meaningless */
3000 #if ENABLE_HUSH_FUNCTIONS
3001 else if (command->child_func) {
3002 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3003 command->child_func->parent_cmd = NULL;
3007 free(command->group_as_string);
3008 //command->group_as_string = NULL;
3010 for (r = command->redirects; r; r = rnext) {
3011 debug_printf_clean(" redirect %d%s",
3012 r->rd_fd, redir_table[r->rd_type].descrip);
3013 /* guard against the case >$FOO, where foo is unset or blank */
3014 if (r->rd_filename) {
3015 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3016 free(r->rd_filename);
3017 //r->rd_filename = NULL;
3019 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3023 //command->redirects = NULL;
3025 free(pi->cmds); /* children are an array, they get freed all at once */
3029 //pi->cmdtext = NULL;
3037 static void free_pipe_list(struct pipe *pi)
3041 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3043 debug_printf_clean("pipe followup code %d\n", pi->followup);
3049 /*** Parsing routines ***/
3051 #ifndef debug_print_tree
3052 static void debug_print_tree(struct pipe *pi, int lvl)
3054 static const char *const PIPE[] = {
3060 static const char *RES[] = {
3061 [RES_NONE ] = "NONE" ,
3064 [RES_THEN ] = "THEN" ,
3065 [RES_ELIF ] = "ELIF" ,
3066 [RES_ELSE ] = "ELSE" ,
3069 # if ENABLE_HUSH_LOOPS
3070 [RES_FOR ] = "FOR" ,
3071 [RES_WHILE] = "WHILE",
3072 [RES_UNTIL] = "UNTIL",
3074 [RES_DONE ] = "DONE" ,
3076 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3079 # if ENABLE_HUSH_CASE
3080 [RES_CASE ] = "CASE" ,
3081 [RES_CASE_IN ] = "CASE_IN" ,
3082 [RES_MATCH] = "MATCH",
3083 [RES_CASE_BODY] = "CASE_BODY",
3084 [RES_ESAC ] = "ESAC" ,
3086 [RES_XXXX ] = "XXXX" ,
3087 [RES_SNTX ] = "SNTX" ,
3089 static const char *const CMDTYPE[] = {
3093 # if ENABLE_HUSH_FUNCTIONS
3102 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3103 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3105 while (prn < pi->num_cmds) {
3106 struct command *command = &pi->cmds[prn];
3107 char **argv = command->argv;
3109 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3111 command->assignment_cnt);
3112 if (command->group) {
3113 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3114 CMDTYPE[command->cmd_type],
3117 , " group_as_string:", command->group_as_string
3122 debug_print_tree(command->group, lvl+1);
3126 if (argv) while (*argv) {
3127 fdprintf(2, " '%s'", *argv);
3137 #endif /* debug_print_tree */
3139 static struct pipe *new_pipe(void)
3142 pi = xzalloc(sizeof(struct pipe));
3143 /*pi->followup = 0; - deliberately invalid value */
3144 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3148 /* Command (member of a pipe) is complete, or we start a new pipe
3149 * if ctx->command is NULL.
3150 * No errors possible here.
3152 static int done_command(struct parse_context *ctx)
3154 /* The command is really already in the pipe structure, so
3155 * advance the pipe counter and make a new, null command. */
3156 struct pipe *pi = ctx->pipe;
3157 struct command *command = ctx->command;
3159 #if 0 /* Instead we emit error message at run time */
3160 if (ctx->pending_redirect) {
3161 /* For example, "cmd >" (no filename to redirect to) */
3162 die_if_script("syntax error: %s", "invalid redirect");
3163 ctx->pending_redirect = NULL;
3168 if (IS_NULL_CMD(command)) {
3169 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3173 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3174 //debug_print_tree(ctx->list_head, 20);
3176 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3179 /* Only real trickiness here is that the uncommitted
3180 * command structure is not counted in pi->num_cmds. */
3181 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3182 ctx->command = command = &pi->cmds[pi->num_cmds];
3184 memset(command, 0, sizeof(*command));
3185 return pi->num_cmds; /* used only for 0/nonzero check */
3188 static void done_pipe(struct parse_context *ctx, pipe_style type)
3192 debug_printf_parse("done_pipe entered, followup %d\n", type);
3193 /* Close previous command */
3194 not_null = done_command(ctx);
3195 ctx->pipe->followup = type;
3197 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3198 ctx->ctx_inverted = 0;
3199 ctx->pipe->res_word = ctx->ctx_res_w;
3202 /* Without this check, even just <enter> on command line generates
3203 * tree of three NOPs (!). Which is harmless but annoying.
3204 * IOW: it is safe to do it unconditionally. */
3207 || ctx->ctx_res_w == RES_FI
3209 #if ENABLE_HUSH_LOOPS
3210 || ctx->ctx_res_w == RES_DONE
3211 || ctx->ctx_res_w == RES_FOR
3212 || ctx->ctx_res_w == RES_IN
3214 #if ENABLE_HUSH_CASE
3215 || ctx->ctx_res_w == RES_ESAC
3219 debug_printf_parse("done_pipe: adding new pipe: "
3220 "not_null:%d ctx->ctx_res_w:%d\n",
3221 not_null, ctx->ctx_res_w);
3223 ctx->pipe->next = new_p;
3225 /* RES_THEN, RES_DO etc are "sticky" -
3226 * they remain set for pipes inside if/while.
3227 * This is used to control execution.
3228 * RES_FOR and RES_IN are NOT sticky (needed to support
3229 * cases where variable or value happens to match a keyword):
3231 #if ENABLE_HUSH_LOOPS
3232 if (ctx->ctx_res_w == RES_FOR
3233 || ctx->ctx_res_w == RES_IN)
3234 ctx->ctx_res_w = RES_NONE;
3236 #if ENABLE_HUSH_CASE
3237 if (ctx->ctx_res_w == RES_MATCH)
3238 ctx->ctx_res_w = RES_CASE_BODY;
3239 if (ctx->ctx_res_w == RES_CASE)
3240 ctx->ctx_res_w = RES_CASE_IN;
3242 ctx->command = NULL; /* trick done_command below */
3243 /* Create the memory for command, roughly:
3244 * ctx->pipe->cmds = new struct command;
3245 * ctx->command = &ctx->pipe->cmds[0];
3248 //debug_print_tree(ctx->list_head, 10);
3250 debug_printf_parse("done_pipe return\n");
3253 static void initialize_context(struct parse_context *ctx)
3255 memset(ctx, 0, sizeof(*ctx));
3256 ctx->pipe = ctx->list_head = new_pipe();
3257 /* Create the memory for command, roughly:
3258 * ctx->pipe->cmds = new struct command;
3259 * ctx->command = &ctx->pipe->cmds[0];
3264 /* If a reserved word is found and processed, parse context is modified
3265 * and 1 is returned.
3268 struct reserved_combo {
3271 unsigned char assignment_flag;
3275 FLAG_END = (1 << RES_NONE ),
3277 FLAG_IF = (1 << RES_IF ),
3278 FLAG_THEN = (1 << RES_THEN ),
3279 FLAG_ELIF = (1 << RES_ELIF ),
3280 FLAG_ELSE = (1 << RES_ELSE ),
3281 FLAG_FI = (1 << RES_FI ),
3283 # if ENABLE_HUSH_LOOPS
3284 FLAG_FOR = (1 << RES_FOR ),
3285 FLAG_WHILE = (1 << RES_WHILE),
3286 FLAG_UNTIL = (1 << RES_UNTIL),
3287 FLAG_DO = (1 << RES_DO ),
3288 FLAG_DONE = (1 << RES_DONE ),
3289 FLAG_IN = (1 << RES_IN ),
3291 # if ENABLE_HUSH_CASE
3292 FLAG_MATCH = (1 << RES_MATCH),
3293 FLAG_ESAC = (1 << RES_ESAC ),
3295 FLAG_START = (1 << RES_XXXX ),
3298 static const struct reserved_combo* match_reserved_word(o_string *word)
3300 /* Mostly a list of accepted follow-up reserved words.
3301 * FLAG_END means we are done with the sequence, and are ready
3302 * to turn the compound list into a command.
3303 * FLAG_START means the word must start a new compound list.
3305 static const struct reserved_combo reserved_list[] = {
3307 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3308 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3309 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3310 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3311 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3312 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3314 # if ENABLE_HUSH_LOOPS
3315 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3316 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3317 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3318 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3319 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3320 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3322 # if ENABLE_HUSH_CASE
3323 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3324 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3327 const struct reserved_combo *r;
3329 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3330 if (strcmp(word->data, r->literal) == 0)
3335 /* Return 0: not a keyword, 1: keyword
3337 static int reserved_word(o_string *word, struct parse_context *ctx)
3339 # if ENABLE_HUSH_CASE
3340 static const struct reserved_combo reserved_match = {
3341 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3344 const struct reserved_combo *r;
3346 if (word->has_quoted_part)
3348 r = match_reserved_word(word);
3352 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3353 # if ENABLE_HUSH_CASE
3354 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3355 /* "case word IN ..." - IN part starts first MATCH part */
3356 r = &reserved_match;
3359 if (r->flag == 0) { /* '!' */
3360 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3361 syntax_error("! ! command");
3362 ctx->ctx_res_w = RES_SNTX;
3364 ctx->ctx_inverted = 1;
3367 if (r->flag & FLAG_START) {
3368 struct parse_context *old;
3370 old = xmalloc(sizeof(*old));
3371 debug_printf_parse("push stack %p\n", old);
3372 *old = *ctx; /* physical copy */
3373 initialize_context(ctx);
3375 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3376 syntax_error_at(word->data);
3377 ctx->ctx_res_w = RES_SNTX;
3380 /* "{...} fi" is ok. "{...} if" is not
3382 * if { echo foo; } then { echo bar; } fi */
3383 if (ctx->command->group)
3384 done_pipe(ctx, PIPE_SEQ);
3387 ctx->ctx_res_w = r->res;
3388 ctx->old_flag = r->flag;
3389 word->o_assignment = r->assignment_flag;
3390 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3392 if (ctx->old_flag & FLAG_END) {
3393 struct parse_context *old;
3395 done_pipe(ctx, PIPE_SEQ);
3396 debug_printf_parse("pop stack %p\n", ctx->stack);
3398 old->command->group = ctx->list_head;
3399 old->command->cmd_type = CMD_NORMAL;
3401 /* At this point, the compound command's string is in
3402 * ctx->as_string... except for the leading keyword!
3403 * Consider this example: "echo a | if true; then echo a; fi"
3404 * ctx->as_string will contain "true; then echo a; fi",
3405 * with "if " remaining in old->as_string!
3409 int len = old->as_string.length;
3410 /* Concatenate halves */
3411 o_addstr(&old->as_string, ctx->as_string.data);
3412 o_free_unsafe(&ctx->as_string);
3413 /* Find where leading keyword starts in first half */
3414 str = old->as_string.data + len;
3415 if (str > old->as_string.data)
3416 str--; /* skip whitespace after keyword */
3417 while (str > old->as_string.data && isalpha(str[-1]))
3419 /* Ugh, we're done with this horrid hack */
3420 old->command->group_as_string = xstrdup(str);
3421 debug_printf_parse("pop, remembering as:'%s'\n",
3422 old->command->group_as_string);
3425 *ctx = *old; /* physical copy */
3430 #endif /* HAS_KEYWORDS */
3432 /* Word is complete, look at it and update parsing context.
3433 * Normal return is 0. Syntax errors return 1.
3434 * Note: on return, word is reset, but not o_free'd!
3436 static int done_word(o_string *word, struct parse_context *ctx)
3438 struct command *command = ctx->command;
3440 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3441 if (word->length == 0 && !word->has_quoted_part) {
3442 debug_printf_parse("done_word return 0: true null, ignored\n");
3446 if (ctx->pending_redirect) {
3447 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3448 * only if run as "bash", not "sh" */
3449 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3451 * ...the word that follows the redirection operator
3452 * shall be subjected to tilde expansion, parameter expansion,
3453 * command substitution, arithmetic expansion, and quote
3454 * removal. Pathname expansion shall not be performed
3455 * on the word by a non-interactive shell; an interactive
3456 * shell may perform it, but shall do so only when
3457 * the expansion would result in one word."
3459 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3460 /* Cater for >\file case:
3461 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3462 * Same with heredocs:
3463 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3465 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3466 unbackslash(ctx->pending_redirect->rd_filename);
3467 /* Is it <<"HEREDOC"? */
3468 if (word->has_quoted_part) {
3469 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3472 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3473 ctx->pending_redirect = NULL;
3476 # if ENABLE_HUSH_CASE
3477 if (ctx->ctx_dsemicolon
3478 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3480 /* already done when ctx_dsemicolon was set to 1: */
3481 /* ctx->ctx_res_w = RES_MATCH; */
3482 ctx->ctx_dsemicolon = 0;
3485 if (!command->argv /* if it's the first word... */
3486 # if ENABLE_HUSH_LOOPS
3487 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3488 && ctx->ctx_res_w != RES_IN
3490 # if ENABLE_HUSH_CASE
3491 && ctx->ctx_res_w != RES_CASE
3494 int reserved = reserved_word(word, ctx);
3495 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3497 o_reset_to_empty_unquoted(word);
3498 debug_printf_parse("done_word return %d\n",
3499 (ctx->ctx_res_w == RES_SNTX));
3500 return (ctx->ctx_res_w == RES_SNTX);
3502 # if ENABLE_HUSH_BASH_COMPAT
3503 if (strcmp(word->data, "[[") == 0) {
3504 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3510 if (command->group) {
3511 /* "{ echo foo; } echo bar" - bad */
3512 syntax_error_at(word->data);
3513 debug_printf_parse("done_word return 1: syntax error, "
3514 "groups and arglists don't mix\n");
3518 /* If this word wasn't an assignment, next ones definitely
3519 * can't be assignments. Even if they look like ones. */
3520 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3521 && word->o_assignment != WORD_IS_KEYWORD
3523 word->o_assignment = NOT_ASSIGNMENT;
3525 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3526 command->assignment_cnt++;
3527 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3529 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3530 word->o_assignment = MAYBE_ASSIGNMENT;
3532 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3534 if (word->has_quoted_part
3535 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3536 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3537 /* (otherwise it's known to be not empty and is already safe) */
3539 /* exclude "$@" - it can expand to no word despite "" */
3540 char *p = word->data;
3541 while (p[0] == SPECIAL_VAR_SYMBOL
3542 && (p[1] & 0x7f) == '@'
3543 && p[2] == SPECIAL_VAR_SYMBOL
3548 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3549 debug_print_strings("word appended to argv", command->argv);
3552 #if ENABLE_HUSH_LOOPS
3553 if (ctx->ctx_res_w == RES_FOR) {
3554 if (word->has_quoted_part
3555 || !is_well_formed_var_name(command->argv[0], '\0')
3557 /* bash says just "not a valid identifier" */
3558 syntax_error("not a valid identifier in for");
3561 /* Force FOR to have just one word (variable name) */
3562 /* NB: basically, this makes hush see "for v in ..."
3563 * syntax as if it is "for v; in ...". FOR and IN become
3564 * two pipe structs in parse tree. */
3565 done_pipe(ctx, PIPE_SEQ);
3568 #if ENABLE_HUSH_CASE
3569 /* Force CASE to have just one word */
3570 if (ctx->ctx_res_w == RES_CASE) {
3571 done_pipe(ctx, PIPE_SEQ);
3575 o_reset_to_empty_unquoted(word);
3577 debug_printf_parse("done_word return 0\n");
3582 /* Peek ahead in the input to find out if we have a "&n" construct,
3583 * as in "2>&1", that represents duplicating a file descriptor.
3585 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3586 * REDIRFD_SYNTAX_ERR if syntax error,
3587 * REDIRFD_TO_FILE if no & was seen,
3588 * or the number found.
3591 #define parse_redir_right_fd(as_string, input) \
3592 parse_redir_right_fd(input)
3594 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3600 return REDIRFD_TO_FILE;
3602 ch = i_getch(input); /* get the & */
3603 nommu_addchr(as_string, ch);
3606 ch = i_getch(input);
3607 nommu_addchr(as_string, ch);
3608 return REDIRFD_CLOSE;
3612 while (ch != EOF && isdigit(ch)) {
3613 d = d*10 + (ch-'0');
3615 ch = i_getch(input);
3616 nommu_addchr(as_string, ch);
3621 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3623 bb_error_msg("ambiguous redirect");
3624 return REDIRFD_SYNTAX_ERR;
3627 /* Return code is 0 normal, 1 if a syntax error is detected
3629 static int parse_redirect(struct parse_context *ctx,
3632 struct in_str *input)
3634 struct command *command = ctx->command;
3635 struct redir_struct *redir;
3636 struct redir_struct **redirp;
3639 dup_num = REDIRFD_TO_FILE;
3640 if (style != REDIRECT_HEREDOC) {
3641 /* Check for a '>&1' type redirect */
3642 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3643 if (dup_num == REDIRFD_SYNTAX_ERR)
3646 int ch = i_peek(input);
3647 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3648 if (dup_num) { /* <<-... */
3649 ch = i_getch(input);
3650 nommu_addchr(&ctx->as_string, ch);
3655 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3656 int ch = i_peek(input);
3658 /* >|FILE redirect ("clobbering" >).
3659 * Since we do not support "set -o noclobber" yet,
3660 * >| and > are the same for now. Just eat |.
3662 ch = i_getch(input);
3663 nommu_addchr(&ctx->as_string, ch);
3667 /* Create a new redir_struct and append it to the linked list */
3668 redirp = &command->redirects;
3669 while ((redir = *redirp) != NULL) {
3670 redirp = &(redir->next);
3672 *redirp = redir = xzalloc(sizeof(*redir));
3673 /* redir->next = NULL; */
3674 /* redir->rd_filename = NULL; */
3675 redir->rd_type = style;
3676 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3678 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3679 redir_table[style].descrip);
3681 redir->rd_dup = dup_num;
3682 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3683 /* Erik had a check here that the file descriptor in question
3684 * is legit; I postpone that to "run time"
3685 * A "-" representation of "close me" shows up as a -3 here */
3686 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3687 redir->rd_fd, redir->rd_dup);
3689 #if 0 /* Instead we emit error message at run time */
3690 if (ctx->pending_redirect) {
3691 /* For example, "cmd > <file" */
3692 die_if_script("syntax error: %s", "invalid redirect");
3695 /* Set ctx->pending_redirect, so we know what to do at the
3696 * end of the next parsed word. */
3697 ctx->pending_redirect = redir;
3702 /* If a redirect is immediately preceded by a number, that number is
3703 * supposed to tell which file descriptor to redirect. This routine
3704 * looks for such preceding numbers. In an ideal world this routine
3705 * needs to handle all the following classes of redirects...
3706 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3707 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3708 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3709 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3711 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3713 * ... If n is quoted, the number shall not be recognized as part of
3714 * the redirection expression. For example:
3716 * writes the character 2 into file a"
3717 * We are getting it right by setting ->has_quoted_part on any \<char>
3719 * A -1 return means no valid number was found,
3720 * the caller should use the appropriate default for this redirection.
3722 static int redirect_opt_num(o_string *o)
3726 if (o->data == NULL)
3728 num = bb_strtou(o->data, NULL, 10);
3729 if (errno || num < 0)
3731 o_reset_to_empty_unquoted(o);
3736 #define fetch_till_str(as_string, input, word, skip_tabs) \
3737 fetch_till_str(input, word, skip_tabs)
3739 static char *fetch_till_str(o_string *as_string,
3740 struct in_str *input,
3744 o_string heredoc = NULL_O_STRING;
3746 int prev = 0; /* not \ */
3752 ch = i_getch(input);
3754 nommu_addchr(as_string, ch);
3755 if ((ch == '\n' || ch == EOF)
3756 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3758 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3759 heredoc.data[past_EOL] = '\0';
3760 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3761 return heredoc.data;
3763 while (ch == '\n') {
3764 o_addchr(&heredoc, ch);
3767 past_EOL = heredoc.length;
3769 ch = i_getch(input);
3771 nommu_addchr(as_string, ch);
3772 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3776 o_free_unsafe(&heredoc);
3779 o_addchr(&heredoc, ch);
3780 nommu_addchr(as_string, ch);
3781 if (prev == '\\' && ch == '\\')
3782 /* Correctly handle foo\\<eol> (not a line cont.) */
3783 prev = 0; /* not \ */
3789 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3790 * and load them all. There should be exactly heredoc_cnt of them.
3792 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3794 struct pipe *pi = ctx->list_head;
3796 while (pi && heredoc_cnt) {
3798 struct command *cmd = pi->cmds;
3800 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3802 cmd->argv ? cmd->argv[0] : "NONE");
3803 for (i = 0; i < pi->num_cmds; i++) {
3804 struct redir_struct *redir = cmd->redirects;
3806 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3807 i, cmd->argv ? cmd->argv[0] : "NONE");
3809 if (redir->rd_type == REDIRECT_HEREDOC) {
3812 redir->rd_type = REDIRECT_HEREDOC2;
3813 /* redir->rd_dup is (ab)used to indicate <<- */
3814 p = fetch_till_str(&ctx->as_string, input,
3815 redir->rd_filename, redir->rd_dup);
3817 syntax_error("unexpected EOF in here document");
3820 free(redir->rd_filename);
3821 redir->rd_filename = p;
3824 redir = redir->next;
3831 /* Should be 0. If it isn't, it's a parse error */
3833 bb_error_msg_and_die("heredoc BUG 2");
3839 static int run_list(struct pipe *pi);
3841 #define parse_stream(pstring, input, end_trigger) \
3842 parse_stream(input, end_trigger)
3844 static struct pipe *parse_stream(char **pstring,
3845 struct in_str *input,
3849 #if !ENABLE_HUSH_FUNCTIONS
3850 #define parse_group(dest, ctx, input, ch) \
3851 parse_group(ctx, input, ch)
3853 static int parse_group(o_string *dest, struct parse_context *ctx,
3854 struct in_str *input, int ch)
3856 /* dest contains characters seen prior to ( or {.
3857 * Typically it's empty, but for function defs,
3858 * it contains function name (without '()'). */
3859 struct pipe *pipe_list;
3861 struct command *command = ctx->command;
3863 debug_printf_parse("parse_group entered\n");
3864 #if ENABLE_HUSH_FUNCTIONS
3865 if (ch == '(' && !dest->has_quoted_part) {
3867 if (done_word(dest, ctx))
3870 goto skip; /* (... */
3871 if (command->argv[1]) { /* word word ... (... */
3872 syntax_error_unexpected_ch('(');
3875 /* it is "word(..." or "word (..." */
3877 ch = i_getch(input);
3878 while (ch == ' ' || ch == '\t');
3880 syntax_error_unexpected_ch(ch);
3883 nommu_addchr(&ctx->as_string, ch);
3885 ch = i_getch(input);
3886 while (ch == ' ' || ch == '\t' || ch == '\n');
3888 syntax_error_unexpected_ch(ch);
3891 nommu_addchr(&ctx->as_string, ch);
3892 command->cmd_type = CMD_FUNCDEF;
3897 #if 0 /* Prevented by caller */
3898 if (command->argv /* word [word]{... */
3899 || dest->length /* word{... */
3900 || dest->has_quoted_part /* ""{... */
3903 debug_printf_parse("parse_group return 1: "
3904 "syntax error, groups and arglists don't mix\n");
3909 #if ENABLE_HUSH_FUNCTIONS
3915 command->cmd_type = CMD_SUBSHELL;
3917 /* bash does not allow "{echo...", requires whitespace */
3919 if (ch != ' ' && ch != '\t' && ch != '\n'
3920 && ch != '(' /* but "{(..." is allowed (without whitespace) */
3922 syntax_error_unexpected_ch(ch);
3926 ch = i_getch(input);
3927 nommu_addchr(&ctx->as_string, ch);
3933 # define as_string NULL
3935 char *as_string = NULL;
3937 pipe_list = parse_stream(&as_string, input, endch);
3940 o_addstr(&ctx->as_string, as_string);
3942 /* empty ()/{} or parse error? */
3943 if (!pipe_list || pipe_list == ERR_PTR) {
3944 /* parse_stream already emitted error msg */
3947 debug_printf_parse("parse_group return 1: "
3948 "parse_stream returned %p\n", pipe_list);
3951 command->group = pipe_list;
3953 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3954 command->group_as_string = as_string;
3955 debug_printf_parse("end of group, remembering as:'%s'\n",
3956 command->group_as_string);
3960 debug_printf_parse("parse_group return 0\n");
3962 /* command remains "open", available for possible redirects */
3965 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
3970 ch = i_getch(input);
3973 ch2 = i_peek(input);
3976 /* backslash+newline, skip it */
3981 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
3989 ch2 = i_peek2(input);
3992 /* backslash+newline, skip it */
3998 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3999 /* Subroutines for copying $(...) and `...` things */
4000 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4002 static int add_till_single_quote(o_string *dest, struct in_str *input)
4005 int ch = i_getch(input);
4007 syntax_error_unterm_ch('\'');
4015 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4016 static int add_till_double_quote(o_string *dest, struct in_str *input)
4019 int ch = i_getch(input);
4021 syntax_error_unterm_ch('"');
4026 if (ch == '\\') { /* \x. Copy both chars. */
4028 ch = i_getch(input);
4032 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4037 //if (ch == '$') ...
4040 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4042 * "Within the backquoted style of command substitution, backslash
4043 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4044 * The search for the matching backquote shall be satisfied by the first
4045 * backquote found without a preceding backslash; during this search,
4046 * if a non-escaped backquote is encountered within a shell comment,
4047 * a here-document, an embedded command substitution of the $(command)
4048 * form, or a quoted string, undefined results occur. A single-quoted
4049 * or double-quoted string that begins, but does not end, within the
4050 * "`...`" sequence produces undefined results."
4052 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4054 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4057 int ch = i_getch(input);
4061 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4062 ch = i_getch(input);
4066 && (!in_dquote || ch != '"')
4068 o_addchr(dest, '\\');
4072 syntax_error_unterm_ch('`');
4078 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4079 * quoting and nested ()s.
4080 * "With the $(command) style of command substitution, all characters
4081 * following the open parenthesis to the matching closing parenthesis
4082 * constitute the command. Any valid shell script can be used for command,
4083 * except a script consisting solely of redirections which produces
4084 * unspecified results."
4086 * echo $(echo '(TEST)' BEST) (TEST) BEST
4087 * echo $(echo 'TEST)' BEST) TEST) BEST
4088 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4090 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4091 * can contain arbitrary constructs, just like $(cmd).
4092 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4093 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4095 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4096 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4099 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4100 # if ENABLE_HUSH_BASH_COMPAT
4101 char end_char2 = end_ch >> 8;
4103 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4106 ch = i_getch(input);
4108 syntax_error_unterm_ch(end_ch);
4111 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4114 /* we look for closing )) of $((EXPR)) */
4115 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4116 i_getch(input); /* eat second ')' */
4121 if (ch == '(' || ch == '{') {
4122 ch = (ch == '(' ? ')' : '}');
4123 if (!add_till_closing_bracket(dest, input, ch))
4129 if (!add_till_single_quote(dest, input))
4135 if (!add_till_double_quote(dest, input))
4141 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4147 /* \x. Copy verbatim. Important for \(, \) */
4148 ch = i_getch(input);
4150 syntax_error_unterm_ch(')');
4155 /* "backslash+newline", ignore both */
4156 o_delchr(dest); /* undo insertion of '\' */
4166 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
4168 /* Return code: 0 for OK, 1 for syntax error */
4170 #define parse_dollar(as_string, dest, input, quote_mask) \
4171 parse_dollar(dest, input, quote_mask)
4172 #define as_string NULL
4174 static int parse_dollar(o_string *as_string,
4176 struct in_str *input, unsigned char quote_mask)
4178 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4180 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4182 ch = i_getch(input);
4183 nommu_addchr(as_string, ch);
4185 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4187 debug_printf_parse(": '%c'\n", ch);
4188 o_addchr(dest, ch | quote_mask);
4190 ch = i_peek_and_eat_bkslash_nl(input);
4191 if (!isalnum(ch) && ch != '_') {
4192 /* End of variable name reached */
4195 ch = i_getch(input);
4196 nommu_addchr(as_string, ch);
4198 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4199 } else if (isdigit(ch)) {
4201 ch = i_getch(input);
4202 nommu_addchr(as_string, ch);
4203 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4204 debug_printf_parse(": '%c'\n", ch);
4205 o_addchr(dest, ch | quote_mask);
4206 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4207 } else switch (ch) {
4209 case '!': /* last bg pid */
4210 case '?': /* last exit code */
4211 case '#': /* number of args */
4212 case '*': /* args */
4213 case '@': /* args */
4214 goto make_one_char_var;
4216 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4218 ch = i_getch(input); /* eat '{' */
4219 nommu_addchr(as_string, ch);
4221 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4222 /* It should be ${?}, or ${#var},
4223 * or even ${?+subst} - operator acting on a special variable,
4224 * or the beginning of variable name.
4227 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4230 syntax_error_unterm_str("${name}");
4231 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4234 nommu_addchr(as_string, ch);
4237 /* It's possible to just call add_till_closing_bracket() at this point.
4238 * However, this regresses some of our testsuite cases
4239 * which check invalid constructs like ${%}.
4240 * Oh well... let's check that the var name part is fine... */
4246 debug_printf_parse(": '%c'\n", ch);
4248 ch = i_getch(input);
4249 nommu_addchr(as_string, ch);
4253 if (!isalnum(ch) && ch != '_') {
4255 unsigned char last_ch;
4256 /* handle parameter expansions
4257 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4259 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4260 goto bad_dollar_syntax;
4262 /* Eat everything until closing '}' (or ':') */
4264 if (ENABLE_HUSH_BASH_COMPAT
4266 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4268 /* It's ${var:N[:M]} thing */
4269 end_ch = '}' * 0x100 + ':';
4271 if (ENABLE_HUSH_BASH_COMPAT
4274 /* It's ${var/[/]pattern[/repl]} thing */
4275 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4277 nommu_addchr(as_string, '/');
4280 end_ch = '}' * 0x100 + '/';
4286 #if ENABLE_HUSH_DOLLAR_OPS
4287 last_ch = add_till_closing_bracket(dest, input, end_ch);
4288 if (last_ch == 0) /* error? */
4291 #error Simple code to only allow ${var} is not implemented
4294 o_addstr(as_string, dest->data + pos);
4295 o_addchr(as_string, last_ch);
4298 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4299 /* close the first block: */
4300 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4301 /* while parsing N from ${var:N[:M]}
4302 * or pattern from ${var/[/]pattern[/repl]} */
4303 if ((end_ch & 0xff) == last_ch) {
4304 /* got ':' or '/'- parse the rest */
4309 if (end_ch == '}' * 0x100 + ':') {
4310 /* it's ${var:N} - emulate :999999999 */
4311 o_addstr(dest, "999999999");
4312 } /* else: it's ${var/[/]pattern} */
4317 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4320 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
4324 ch = i_getch(input);
4325 nommu_addchr(as_string, ch);
4326 # if ENABLE_SH_MATH_SUPPORT
4327 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4328 ch = i_getch(input);
4329 nommu_addchr(as_string, ch);
4330 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4331 o_addchr(dest, /*quote_mask |*/ '+');
4334 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4335 return 0; /* error */
4337 o_addstr(as_string, dest->data + pos);
4338 o_addchr(as_string, ')');
4339 o_addchr(as_string, ')');
4341 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4345 # if ENABLE_HUSH_TICK
4346 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4347 o_addchr(dest, quote_mask | '`');
4350 if (!add_till_closing_bracket(dest, input, ')'))
4351 return 0; /* error */
4353 o_addstr(as_string, dest->data + pos);
4354 o_addchr(as_string, ')');
4356 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4362 ch = i_getch(input);
4363 nommu_addchr(as_string, ch);
4364 ch = i_peek_and_eat_bkslash_nl(input);
4365 if (isalnum(ch)) { /* it's $_name or $_123 */
4370 /* TODO: $_ and $-: */
4371 /* $_ Shell or shell script name; or last argument of last command
4372 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4373 * but in command's env, set to full pathname used to invoke it */
4374 /* $- Option flags set by set builtin or shell options (-i etc) */
4376 o_addQchr(dest, '$');
4378 debug_printf_parse("parse_dollar return 1 (ok)\n");
4384 # if ENABLE_HUSH_BASH_COMPAT
4385 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4386 encode_string(dest, input, dquote_end, process_bkslash)
4388 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4389 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4390 encode_string(dest, input, dquote_end)
4392 #define as_string NULL
4396 # if ENABLE_HUSH_BASH_COMPAT
4397 /* all parameters are needed, no macro tricks */
4399 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4400 encode_string(as_string, dest, input, dquote_end)
4403 static int encode_string(o_string *as_string,
4405 struct in_str *input,
4407 int process_bkslash)
4409 #if !ENABLE_HUSH_BASH_COMPAT
4410 const int process_bkslash = 1;
4416 ch = i_getch(input);
4418 nommu_addchr(as_string, ch);
4419 if (ch == dquote_end) { /* may be only '"' or EOF */
4420 debug_printf_parse("encode_string return 1 (ok)\n");
4423 /* note: can't move it above ch == dquote_end check! */
4425 syntax_error_unterm_ch('"');
4426 return 0; /* error */
4430 next = i_peek(input);
4432 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4433 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4434 if (process_bkslash && ch == '\\') {
4436 syntax_error("\\<eof>");
4440 * "The backslash retains its special meaning [in "..."]
4441 * only when followed by one of the following characters:
4442 * $, `, ", \, or <newline>. A double quote may be quoted
4443 * within double quotes by preceding it with a backslash."
4444 * NB: in (unquoted) heredoc, above does not apply to ",
4445 * therefore we check for it by "next == dquote_end" cond.
4447 if (next == dquote_end || strchr("$`\\\n", next)) {
4448 ch = i_getch(input); /* eat next */
4450 goto again; /* skip \<newline> */
4451 } /* else: ch remains == '\\', and we double it below: */
4452 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4453 nommu_addchr(as_string, ch);
4457 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4458 debug_printf_parse("encode_string return 0: "
4459 "parse_dollar returned 0 (error)\n");
4464 #if ENABLE_HUSH_TICK
4466 //unsigned pos = dest->length;
4467 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4468 o_addchr(dest, 0x80 | '`');
4469 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4470 return 0; /* error */
4471 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4472 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4476 o_addQchr(dest, ch);
4482 * Scan input until EOF or end_trigger char.
4483 * Return a list of pipes to execute, or NULL on EOF
4484 * or if end_trigger character is met.
4485 * On syntax error, exit if shell is not interactive,
4486 * reset parsing machinery and start parsing anew,
4487 * or return ERR_PTR.
4489 static struct pipe *parse_stream(char **pstring,
4490 struct in_str *input,
4493 struct parse_context ctx;
4494 o_string dest = NULL_O_STRING;
4497 /* Single-quote triggers a bypass of the main loop until its mate is
4498 * found. When recursing, quote state is passed in via dest->o_expflags.
4500 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4501 end_trigger ? end_trigger : 'X');
4504 /* If very first arg is "" or '', dest.data may end up NULL.
4505 * Preventing this: */
4506 o_addchr(&dest, '\0');
4509 /* We used to separate words on $IFS here. This was wrong.
4510 * $IFS is used only for word splitting when $var is expanded,
4511 * here we should use blank chars as separators, not $IFS
4514 if (MAYBE_ASSIGNMENT != 0)
4515 dest.o_assignment = MAYBE_ASSIGNMENT;
4516 initialize_context(&ctx);
4519 const char *is_blank;
4520 const char *is_special;
4524 redir_type redir_style;
4526 ch = i_getch(input);
4527 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4528 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4533 syntax_error_unterm_str("here document");
4536 if (end_trigger == ')') {
4537 syntax_error_unterm_ch('(');
4540 if (end_trigger == '}') {
4541 syntax_error_unterm_ch('{');
4545 if (done_word(&dest, &ctx)) {
4549 done_pipe(&ctx, PIPE_SEQ);
4551 /* If we got nothing... */
4552 /* (this makes bare "&" cmd a no-op.
4553 * bash says: "syntax error near unexpected token '&'") */
4554 if (pi->num_cmds == 0
4555 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4561 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4563 *pstring = ctx.as_string.data;
4565 o_free_unsafe(&ctx.as_string);
4568 debug_printf_parse("parse_stream return %p\n", pi);
4571 nommu_addchr(&ctx.as_string, ch);
4575 next = i_peek(input);
4577 is_special = "{}<>;&|()#'" /* special outside of "str" */
4578 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4579 /* Are { and } special here? */
4580 if (ctx.command->argv /* word [word]{... - non-special */
4581 || dest.length /* word{... - non-special */
4582 || dest.has_quoted_part /* ""{... - non-special */
4583 || (next != ';' /* }; - special */
4584 && next != ')' /* }) - special */
4585 && next != '(' /* {( - special */
4586 && next != '&' /* }& and }&& ... - special */
4587 && next != '|' /* }|| ... - special */
4588 && !strchr(defifs, next) /* {word - non-special */
4591 /* They are not special, skip "{}" */
4594 is_special = strchr(is_special, ch);
4595 is_blank = strchr(defifs, ch);
4597 if (!is_special && !is_blank) { /* ordinary char */
4599 o_addQchr(&dest, ch);
4600 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4601 || dest.o_assignment == WORD_IS_KEYWORD)
4603 && is_well_formed_var_name(dest.data, '=')
4605 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4606 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4612 if (done_word(&dest, &ctx)) {
4616 /* Is this a case when newline is simply ignored?
4618 * "cmd | <newline> cmd ..."
4619 * "case ... in <newline> word) ..."
4621 if (IS_NULL_CMD(ctx.command)
4622 && dest.length == 0 && !dest.has_quoted_part
4624 /* This newline can be ignored. But...
4625 * Without check #1, interactive shell
4626 * ignores even bare <newline>,
4627 * and shows the continuation prompt:
4628 * ps1_prompt$ <enter>
4629 * ps2> _ <=== wrong, should be ps1
4630 * Without check #2, "cmd & <newline>"
4631 * is similarly mistreated.
4632 * (BTW, this makes "cmd & cmd"
4633 * and "cmd && cmd" non-orthogonal.
4634 * Really, ask yourself, why
4635 * "cmd && <newline>" doesn't start
4636 * cmd but waits for more input?
4639 struct pipe *pi = ctx.list_head;
4640 if (pi->num_cmds != 0 /* check #1 */
4641 && pi->followup != PIPE_BG /* check #2 */
4646 /* Treat newline as a command separator. */
4647 done_pipe(&ctx, PIPE_SEQ);
4648 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4650 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4655 dest.o_assignment = MAYBE_ASSIGNMENT;
4656 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4658 /* note: if (is_blank) continue;
4659 * will still trigger for us */
4663 /* "cmd}" or "cmd }..." without semicolon or &:
4664 * } is an ordinary char in this case, even inside { cmd; }
4665 * Pathological example: { ""}; } should exec "}" cmd
4668 if (dest.length != 0 /* word} */
4669 || dest.has_quoted_part /* ""} */
4673 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4674 /* Generally, there should be semicolon: "cmd; }"
4675 * However, bash allows to omit it if "cmd" is
4676 * a group. Examples:
4679 * { echo 0 >&2 | { echo 1; } }
4680 * { while false; do :; done }
4681 * { case a in b) ;; esac }
4683 if (ctx.command->group)
4687 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4688 /* Can't be an end of {cmd}, skip the check */
4689 goto skip_end_trigger;
4690 /* else: } does terminate a group */
4693 if (end_trigger && end_trigger == ch
4694 && (ch != ';' || heredoc_cnt == 0)
4695 #if ENABLE_HUSH_CASE
4697 || ctx.ctx_res_w != RES_MATCH
4698 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4703 /* This is technically valid:
4704 * { cat <<HERE; }; echo Ok
4708 * but we don't support this.
4709 * We require heredoc to be in enclosing {}/(),
4712 syntax_error_unterm_str("here document");
4715 if (done_word(&dest, &ctx)) {
4718 done_pipe(&ctx, PIPE_SEQ);
4719 dest.o_assignment = MAYBE_ASSIGNMENT;
4720 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4721 /* Do we sit outside of any if's, loops or case's? */
4723 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4727 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4729 *pstring = ctx.as_string.data;
4731 o_free_unsafe(&ctx.as_string);
4734 debug_printf_parse("parse_stream return %p: "
4735 "end_trigger char found\n",
4737 return ctx.list_head;
4744 /* Catch <, > before deciding whether this word is
4745 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4748 redir_fd = redirect_opt_num(&dest);
4749 if (done_word(&dest, &ctx)) {
4752 redir_style = REDIRECT_OVERWRITE;
4754 redir_style = REDIRECT_APPEND;
4755 ch = i_getch(input);
4756 nommu_addchr(&ctx.as_string, ch);
4759 else if (next == '(') {
4760 syntax_error(">(process) not supported");
4764 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4766 continue; /* back to top of while (1) */
4768 redir_fd = redirect_opt_num(&dest);
4769 if (done_word(&dest, &ctx)) {
4772 redir_style = REDIRECT_INPUT;
4774 redir_style = REDIRECT_HEREDOC;
4776 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4777 ch = i_getch(input);
4778 nommu_addchr(&ctx.as_string, ch);
4779 } else if (next == '>') {
4780 redir_style = REDIRECT_IO;
4781 ch = i_getch(input);
4782 nommu_addchr(&ctx.as_string, ch);
4785 else if (next == '(') {
4786 syntax_error("<(process) not supported");
4790 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4792 continue; /* back to top of while (1) */
4794 if (dest.length == 0 && !dest.has_quoted_part) {
4795 /* skip "#comment" */
4798 if (ch == EOF || ch == '\n')
4801 /* note: we do not add it to &ctx.as_string */
4803 nommu_addchr(&ctx.as_string, '\n');
4804 continue; /* back to top of while (1) */
4809 /* It's "\<newline>" */
4811 /* Remove trailing '\' from ctx.as_string */
4812 ctx.as_string.data[--ctx.as_string.length] = '\0';
4814 ch = i_getch(input); /* eat it */
4815 continue; /* back to top of while (1) */
4820 if (dest.o_assignment == MAYBE_ASSIGNMENT
4821 /* check that we are not in word in "a=1 2>word b=1": */
4822 && !ctx.pending_redirect
4824 /* ch is a special char and thus this word
4825 * cannot be an assignment */
4826 dest.o_assignment = NOT_ASSIGNMENT;
4827 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4830 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4833 case '#': /* non-comment #: "echo a#b" etc */
4834 o_addQchr(&dest, ch);
4838 syntax_error("\\<eof>");
4841 ch = i_getch(input);
4842 /* note: ch != '\n' (that case does not reach this place) */
4843 o_addchr(&dest, '\\');
4844 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4845 o_addchr(&dest, ch);
4846 nommu_addchr(&ctx.as_string, ch);
4847 /* Example: echo Hello \2>file
4848 * we need to know that word 2 is quoted */
4849 dest.has_quoted_part = 1;
4852 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4853 debug_printf_parse("parse_stream parse error: "
4854 "parse_dollar returned 0 (error)\n");
4859 dest.has_quoted_part = 1;
4860 if (next == '\'' && !ctx.pending_redirect) {
4861 insert_empty_quoted_str_marker:
4862 nommu_addchr(&ctx.as_string, next);
4863 i_getch(input); /* eat second ' */
4864 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4865 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4868 ch = i_getch(input);
4870 syntax_error_unterm_ch('\'');
4873 nommu_addchr(&ctx.as_string, ch);
4876 o_addqchr(&dest, ch);
4881 dest.has_quoted_part = 1;
4882 if (next == '"' && !ctx.pending_redirect)
4883 goto insert_empty_quoted_str_marker;
4884 if (dest.o_assignment == NOT_ASSIGNMENT)
4885 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4886 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4888 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4890 #if ENABLE_HUSH_TICK
4892 USE_FOR_NOMMU(unsigned pos;)
4894 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4895 o_addchr(&dest, '`');
4896 USE_FOR_NOMMU(pos = dest.length;)
4897 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4900 o_addstr(&ctx.as_string, dest.data + pos);
4901 o_addchr(&ctx.as_string, '`');
4903 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4904 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4909 #if ENABLE_HUSH_CASE
4912 if (done_word(&dest, &ctx)) {
4915 done_pipe(&ctx, PIPE_SEQ);
4916 #if ENABLE_HUSH_CASE
4917 /* Eat multiple semicolons, detect
4918 * whether it means something special */
4923 ch = i_getch(input);
4924 nommu_addchr(&ctx.as_string, ch);
4925 if (ctx.ctx_res_w == RES_CASE_BODY) {
4926 ctx.ctx_dsemicolon = 1;
4927 ctx.ctx_res_w = RES_MATCH;
4933 /* We just finished a cmd. New one may start
4934 * with an assignment */
4935 dest.o_assignment = MAYBE_ASSIGNMENT;
4936 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4939 if (done_word(&dest, &ctx)) {
4943 ch = i_getch(input);
4944 nommu_addchr(&ctx.as_string, ch);
4945 done_pipe(&ctx, PIPE_AND);
4947 done_pipe(&ctx, PIPE_BG);
4951 if (done_word(&dest, &ctx)) {
4954 #if ENABLE_HUSH_CASE
4955 if (ctx.ctx_res_w == RES_MATCH)
4956 break; /* we are in case's "word | word)" */
4958 if (next == '|') { /* || */
4959 ch = i_getch(input);
4960 nommu_addchr(&ctx.as_string, ch);
4961 done_pipe(&ctx, PIPE_OR);
4963 /* we could pick up a file descriptor choice here
4964 * with redirect_opt_num(), but bash doesn't do it.
4965 * "echo foo 2| cat" yields "foo 2". */
4970 #if ENABLE_HUSH_CASE
4971 /* "case... in [(]word)..." - skip '(' */
4972 if (ctx.ctx_res_w == RES_MATCH
4973 && ctx.command->argv == NULL /* not (word|(... */
4974 && dest.length == 0 /* not word(... */
4975 && dest.has_quoted_part == 0 /* not ""(... */
4981 if (parse_group(&dest, &ctx, input, ch) != 0) {
4986 #if ENABLE_HUSH_CASE
4987 if (ctx.ctx_res_w == RES_MATCH)
4991 /* proper use of this character is caught by end_trigger:
4992 * if we see {, we call parse_group(..., end_trigger='}')
4993 * and it will match } earlier (not here). */
4994 syntax_error_unexpected_ch(ch);
4998 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5004 struct parse_context *pctx;
5005 IF_HAS_KEYWORDS(struct parse_context *p2;)
5007 /* Clean up allocated tree.
5008 * Sample for finding leaks on syntax error recovery path.
5009 * Run it from interactive shell, watch pmap `pidof hush`.
5010 * while if false; then false; fi; do break; fi
5011 * Samples to catch leaks at execution:
5012 * while if (true | {true;}); then echo ok; fi; do break; done
5013 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5017 /* Update pipe/command counts,
5018 * otherwise freeing may miss some */
5019 done_pipe(pctx, PIPE_SEQ);
5020 debug_printf_clean("freeing list %p from ctx %p\n",
5021 pctx->list_head, pctx);
5022 debug_print_tree(pctx->list_head, 0);
5023 free_pipe_list(pctx->list_head);
5024 debug_printf_clean("freed list %p\n", pctx->list_head);
5026 o_free_unsafe(&pctx->as_string);
5028 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5032 IF_HAS_KEYWORDS(pctx = p2;)
5033 } while (HAS_KEYWORDS && pctx);
5036 G.last_exitcode = 1;
5047 /*** Execution routines ***/
5049 /* Expansion can recurse, need forward decls: */
5050 #if !ENABLE_HUSH_BASH_COMPAT
5051 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5052 #define expand_string_to_string(str, do_unbackslash) \
5053 expand_string_to_string(str)
5055 static char *expand_string_to_string(const char *str, int do_unbackslash);
5056 #if ENABLE_HUSH_TICK
5057 static int process_command_subs(o_string *dest, const char *s);
5060 /* expand_strvec_to_strvec() takes a list of strings, expands
5061 * all variable references within and returns a pointer to
5062 * a list of expanded strings, possibly with larger number
5063 * of strings. (Think VAR="a b"; echo $VAR).
5064 * This new list is allocated as a single malloc block.
5065 * NULL-terminated list of char* pointers is at the beginning of it,
5066 * followed by strings themselves.
5067 * Caller can deallocate entire list by single free(list). */
5069 /* A horde of its helpers come first: */
5071 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5073 while (--len >= 0) {
5076 #if ENABLE_HUSH_BRACE_EXPANSION
5077 if (c == '{' || c == '}') {
5078 /* { -> \{, } -> \} */
5080 /* And now we want to add { or } and continue:
5083 * luckily, just falling throught achieves this.
5089 /* \z -> \\\z; \<eol> -> \\<eol> */
5094 o_addchr(o, *str++);
5100 /* Store given string, finalizing the word and starting new one whenever
5101 * we encounter IFS char(s). This is used for expanding variable values.
5102 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5103 * Return in *ended_with_ifs:
5104 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5106 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5108 int last_is_ifs = 0;
5113 if (!*str) /* EOL - do not finalize word */
5115 word_len = strcspn(str, G.ifs);
5117 /* We have WORD_LEN leading non-IFS chars */
5118 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5119 o_addblock(output, str, word_len);
5121 /* Protect backslashes against globbing up :)
5122 * Example: "v='\*'; echo b$v" prints "b\*"
5123 * (and does not try to glob on "*")
5125 o_addblock_duplicate_backslash(output, str, word_len);
5126 /*/ Why can't we do it easier? */
5127 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5128 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5132 if (!*str) /* EOL - do not finalize word */
5136 /* We know str here points to at least one IFS char */
5138 str += strspn(str, G.ifs); /* skip IFS chars */
5139 if (!*str) /* EOL - do not finalize word */
5142 /* Start new word... but not always! */
5143 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5144 if (output->has_quoted_part
5145 /* Case "v=' a'; echo $v":
5146 * here nothing precedes the space in $v expansion,
5147 * therefore we should not finish the word
5148 * (IOW: if there *is* word to finalize, only then do it):
5150 || (n > 0 && output->data[output->length - 1])
5152 o_addchr(output, '\0');
5153 debug_print_list("expand_on_ifs", output, n);
5154 n = o_save_ptr(output, n);
5159 *ended_with_ifs = last_is_ifs;
5160 debug_print_list("expand_on_ifs[1]", output, n);
5164 /* Helper to expand $((...)) and heredoc body. These act as if
5165 * they are in double quotes, with the exception that they are not :).
5166 * Just the rules are similar: "expand only $var and `cmd`"
5168 * Returns malloced string.
5169 * As an optimization, we return NULL if expansion is not needed.
5171 #if !ENABLE_HUSH_BASH_COMPAT
5172 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5173 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5174 encode_then_expand_string(str)
5176 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5179 struct in_str input;
5180 o_string dest = NULL_O_STRING;
5182 if (!strchr(str, '$')
5183 && !strchr(str, '\\')
5184 #if ENABLE_HUSH_TICK
5185 && !strchr(str, '`')
5191 /* We need to expand. Example:
5192 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5194 setup_string_in_str(&input, str);
5195 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5196 //TODO: error check (encode_string returns 0 on error)?
5197 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5198 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5199 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5200 o_free_unsafe(&dest);
5204 #if ENABLE_SH_MATH_SUPPORT
5205 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5207 arith_state_t math_state;
5211 math_state.lookupvar = get_local_var_value;
5212 math_state.setvar = set_local_var_from_halves;
5213 //math_state.endofname = endofname;
5214 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5215 res = arith(&math_state, exp_str ? exp_str : arg);
5218 *errmsg_p = math_state.errmsg;
5219 if (math_state.errmsg)
5220 die_if_script(math_state.errmsg);
5225 #if ENABLE_HUSH_BASH_COMPAT
5226 /* ${var/[/]pattern[/repl]} helpers */
5227 static char *strstr_pattern(char *val, const char *pattern, int *size)
5230 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5231 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5238 /* Optimization: if "*pat" did not match the start of "string",
5239 * we know that "tring", "ring" etc will not match too:
5241 if (pattern[0] == '*')
5246 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5248 char *result = NULL;
5249 unsigned res_len = 0;
5250 unsigned repl_len = strlen(repl);
5254 char *s = strstr_pattern(val, pattern, &size);
5258 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5259 memcpy(result + res_len, val, s - val);
5261 strcpy(result + res_len, repl);
5262 res_len += repl_len;
5263 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5269 if (val[0] && result) {
5270 result = xrealloc(result, res_len + strlen(val) + 1);
5271 strcpy(result + res_len, val);
5272 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5274 debug_printf_varexp("result:'%s'\n", result);
5280 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5282 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5284 const char *val = NULL;
5285 char *to_be_freed = NULL;
5290 char exp_save = exp_save; /* for compiler */
5291 char *exp_saveptr; /* points to expansion operator */
5292 char *exp_word = exp_word; /* for compiler */
5295 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5297 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5299 first_char = arg[0] = arg0 & 0x7f;
5302 if (first_char == '#' /* ${#... */
5303 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5305 /* It must be length operator: ${#var} */
5309 /* Maybe handle parameter expansion */
5310 if (exp_saveptr /* if 2nd char is one of expansion operators */
5311 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5313 /* ${?:0}, ${#[:]%0} etc */
5314 exp_saveptr = var + 1;
5316 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5317 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5319 exp_op = exp_save = *exp_saveptr;
5321 exp_word = exp_saveptr + 1;
5322 if (exp_op == ':') {
5323 exp_op = *exp_word++;
5324 //TODO: try ${var:} and ${var:bogus} in non-bash config
5325 if (ENABLE_HUSH_BASH_COMPAT
5326 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5328 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5333 *exp_saveptr = '\0';
5334 } /* else: it's not an expansion op, but bare ${var} */
5337 /* Look up the variable in question */
5338 if (isdigit(var[0])) {
5339 /* parse_dollar should have vetted var for us */
5340 int n = xatoi_positive(var);
5341 if (n < G.global_argc)
5342 val = G.global_argv[n];
5343 /* else val remains NULL: $N with too big N */
5347 val = utoa(G.root_pid);
5349 case '!': /* bg pid */
5350 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5352 case '?': /* exitcode */
5353 val = utoa(G.last_exitcode);
5355 case '#': /* argc */
5356 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5359 val = get_local_var_value(var);
5363 /* Handle any expansions */
5364 if (exp_op == 'L') {
5365 reinit_unicode_for_hush();
5366 debug_printf_expand("expand: length(%s)=", val);
5367 val = utoa(val ? unicode_strlen(val) : 0);
5368 debug_printf_expand("%s\n", val);
5369 } else if (exp_op) {
5370 if (exp_op == '%' || exp_op == '#') {
5371 /* Standard-mandated substring removal ops:
5372 * ${parameter%word} - remove smallest suffix pattern
5373 * ${parameter%%word} - remove largest suffix pattern
5374 * ${parameter#word} - remove smallest prefix pattern
5375 * ${parameter##word} - remove largest prefix pattern
5377 * Word is expanded to produce a glob pattern.
5378 * Then var's value is matched to it and matching part removed.
5380 if (val && val[0]) {
5384 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5385 if (exp_op == *exp_word) /* ## or %% */
5387 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5389 exp_word = exp_exp_word;
5390 /* HACK ALERT. We depend here on the fact that
5391 * G.global_argv and results of utoa and get_local_var_value
5392 * are actually in writable memory:
5393 * scan_and_match momentarily stores NULs there. */
5395 loc = scan_and_match(t, exp_word, scan_flags);
5396 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5397 // exp_op, t, exp_word, loc);
5399 if (loc) { /* match was found */
5400 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5401 val = loc; /* take right part */
5403 val = to_be_freed = xstrndup(val, loc - val); /* left */
5407 #if ENABLE_HUSH_BASH_COMPAT
5408 else if (exp_op == '/' || exp_op == '\\') {
5409 /* It's ${var/[/]pattern[/repl]} thing.
5410 * Note that in encoded form it has TWO parts:
5411 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5412 * and if // is used, it is encoded as \:
5413 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5415 /* Empty variable always gives nothing: */
5416 // "v=''; echo ${v/*/w}" prints "", not "w"
5417 if (val && val[0]) {
5418 /* pattern uses non-standard expansion.
5419 * repl should be unbackslashed and globbed
5420 * by the usual expansion rules:
5422 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5423 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5424 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5425 * v='a bz'; echo ${v/a*z/\z} prints "z"
5426 * (note that a*z _pattern_ is never globbed!)
5428 char *pattern, *repl, *t;
5429 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5431 pattern = xstrdup(exp_word);
5432 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5433 *p++ = SPECIAL_VAR_SYMBOL;
5435 p = strchr(p, SPECIAL_VAR_SYMBOL);
5437 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5438 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5439 /* HACK ALERT. We depend here on the fact that
5440 * G.global_argv and results of utoa and get_local_var_value
5441 * are actually in writable memory:
5442 * replace_pattern momentarily stores NULs there. */
5444 to_be_freed = replace_pattern(t,
5446 (repl ? repl : exp_word),
5448 if (to_be_freed) /* at least one replace happened */
5455 else if (exp_op == ':') {
5456 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5457 /* It's ${var:N[:M]} bashism.
5458 * Note that in encoded form it has TWO parts:
5459 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5464 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5467 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5468 *p++ = SPECIAL_VAR_SYMBOL;
5470 p = strchr(p, SPECIAL_VAR_SYMBOL);
5472 len = expand_and_evaluate_arith(exp_word, &errmsg);
5475 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5476 if (len >= 0) { /* bash compat: len < 0 is illegal */
5477 if (beg < 0) /* bash compat */
5479 debug_printf_varexp("from val:'%s'\n", val);
5480 if (len == 0 || !val || beg >= strlen(val)) {
5484 /* Paranoia. What if user entered 9999999999999
5485 * which fits in arith_t but not int? */
5488 val = to_be_freed = xstrndup(val + beg, len);
5490 debug_printf_varexp("val:'%s'\n", val);
5494 die_if_script("malformed ${%s:...}", var);
5497 } else { /* one of "-=+?" */
5498 /* Standard-mandated substitution ops:
5499 * ${var?word} - indicate error if unset
5500 * If var is unset, word (or a message indicating it is unset
5501 * if word is null) is written to standard error
5502 * and the shell exits with a non-zero exit status.
5503 * Otherwise, the value of var is substituted.
5504 * ${var-word} - use default value
5505 * If var is unset, word is substituted.
5506 * ${var=word} - assign and use default value
5507 * If var is unset, word is assigned to var.
5508 * In all cases, final value of var is substituted.
5509 * ${var+word} - use alternative value
5510 * If var is unset, null is substituted.
5511 * Otherwise, word is substituted.
5513 * Word is subjected to tilde expansion, parameter expansion,
5514 * command substitution, and arithmetic expansion.
5515 * If word is not needed, it is not expanded.
5517 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5518 * but also treat null var as if it is unset.
5520 int use_word = (!val || ((exp_save == ':') && !val[0]));
5522 use_word = !use_word;
5523 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5524 (exp_save == ':') ? "true" : "false", use_word);
5526 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5528 exp_word = to_be_freed;
5529 if (exp_op == '?') {
5530 /* mimic bash message */
5531 die_if_script("%s: %s",
5533 exp_word[0] ? exp_word : "parameter null or not set"
5535 //TODO: how interactive bash aborts expansion mid-command?
5540 if (exp_op == '=') {
5541 /* ${var=[word]} or ${var:=[word]} */
5542 if (isdigit(var[0]) || var[0] == '#') {
5543 /* mimic bash message */
5544 die_if_script("$%s: cannot assign in this way", var);
5547 char *new_var = xasprintf("%s=%s", var, val);
5548 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5552 } /* one of "-=+?" */
5554 *exp_saveptr = exp_save;
5560 *to_be_freed_pp = to_be_freed;
5564 /* Expand all variable references in given string, adding words to list[]
5565 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5566 * to be filled). This routine is extremely tricky: has to deal with
5567 * variables/parameters with whitespace, $* and $@, and constructs like
5568 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5569 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5571 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5572 * expansion of right-hand side of assignment == 1-element expand.
5574 char cant_be_null = 0; /* only bit 0x80 matters */
5575 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5578 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5579 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5580 debug_print_list("expand_vars_to_list", output, n);
5581 n = o_save_ptr(output, n);
5582 debug_print_list("expand_vars_to_list[0]", output, n);
5584 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5586 char *to_be_freed = NULL;
5587 const char *val = NULL;
5588 #if ENABLE_HUSH_TICK
5589 o_string subst_result = NULL_O_STRING;
5591 #if ENABLE_SH_MATH_SUPPORT
5592 char arith_buf[sizeof(arith_t)*3 + 2];
5596 o_addchr(output, '\0');
5597 n = o_save_ptr(output, n);
5601 o_addblock(output, arg, p - arg);
5602 debug_print_list("expand_vars_to_list[1]", output, n);
5604 p = strchr(p, SPECIAL_VAR_SYMBOL);
5606 /* Fetch special var name (if it is indeed one of them)
5607 * and quote bit, force the bit on if singleword expansion -
5608 * important for not getting v=$@ expand to many words. */
5609 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5611 /* Is this variable quoted and thus expansion can't be null?
5612 * "$@" is special. Even if quoted, it can still
5613 * expand to nothing (not even an empty string),
5614 * thus it is excluded. */
5615 if ((first_ch & 0x7f) != '@')
5616 cant_be_null |= first_ch;
5618 switch (first_ch & 0x7f) {
5619 /* Highest bit in first_ch indicates that var is double-quoted */
5623 if (!G.global_argv[1])
5626 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5627 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5628 while (G.global_argv[i]) {
5629 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5630 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5631 if (G.global_argv[i++][0] && G.global_argv[i]) {
5632 /* this argv[] is not empty and not last:
5633 * put terminating NUL, start new word */
5634 o_addchr(output, '\0');
5635 debug_print_list("expand_vars_to_list[2]", output, n);
5636 n = o_save_ptr(output, n);
5637 debug_print_list("expand_vars_to_list[3]", output, n);
5641 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5642 * and in this case should treat it like '$*' - see 'else...' below */
5643 if (first_ch == ('@'|0x80) /* quoted $@ */
5644 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5647 o_addQstr(output, G.global_argv[i]);
5648 if (++i >= G.global_argc)
5650 o_addchr(output, '\0');
5651 debug_print_list("expand_vars_to_list[4]", output, n);
5652 n = o_save_ptr(output, n);
5654 } else { /* quoted $* (or v="$@" case): add as one word */
5656 o_addQstr(output, G.global_argv[i]);
5657 if (!G.global_argv[++i])
5660 o_addchr(output, G.ifs[0]);
5662 output->has_quoted_part = 1;
5666 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5667 /* "Empty variable", used to make "" etc to not disappear */
5668 output->has_quoted_part = 1;
5670 cant_be_null = 0x80;
5672 #if ENABLE_HUSH_TICK
5673 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5674 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5676 /* Can't just stuff it into output o_string,
5677 * expanded result may need to be globbed
5678 * and $IFS-splitted */
5679 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5680 G.last_exitcode = process_command_subs(&subst_result, arg);
5681 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5682 val = subst_result.data;
5685 #if ENABLE_SH_MATH_SUPPORT
5686 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5689 arg++; /* skip '+' */
5690 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5691 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5692 res = expand_and_evaluate_arith(arg, NULL);
5693 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5694 sprintf(arith_buf, ARITH_FMT, res);
5700 val = expand_one_var(&to_be_freed, arg, &p);
5701 IF_HUSH_TICK(store_val:)
5702 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5703 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5704 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5705 if (val && val[0]) {
5706 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5709 } else { /* quoted $VAR, val will be appended below */
5710 output->has_quoted_part = 1;
5711 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5712 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5715 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5717 if (val && val[0]) {
5718 o_addQstr(output, val);
5722 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5723 * Do the check to avoid writing to a const string. */
5724 if (*p != SPECIAL_VAR_SYMBOL)
5725 *p = SPECIAL_VAR_SYMBOL;
5727 #if ENABLE_HUSH_TICK
5728 o_free(&subst_result);
5731 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5735 o_addchr(output, '\0');
5736 n = o_save_ptr(output, n);
5738 debug_print_list("expand_vars_to_list[a]", output, n);
5739 /* this part is literal, and it was already pre-quoted
5740 * if needed (much earlier), do not use o_addQstr here! */
5741 o_addstr_with_NUL(output, arg);
5742 debug_print_list("expand_vars_to_list[b]", output, n);
5743 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5744 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5747 /* allow to reuse list[n] later without re-growth */
5748 output->has_empty_slot = 1;
5750 o_addchr(output, '\0');
5756 static char **expand_variables(char **argv, unsigned expflags)
5760 o_string output = NULL_O_STRING;
5762 output.o_expflags = expflags;
5766 n = expand_vars_to_list(&output, n, *argv);
5769 debug_print_list("expand_variables", &output, n);
5771 /* output.data (malloced in one block) gets returned in "list" */
5772 list = o_finalize_list(&output, n);
5773 debug_print_strings("expand_variables[1]", list);
5777 static char **expand_strvec_to_strvec(char **argv)
5779 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5782 #if ENABLE_HUSH_BASH_COMPAT
5783 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5785 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5789 /* Used for expansion of right hand of assignments,
5790 * $((...)), heredocs, variable espansion parts.
5792 * NB: should NOT do globbing!
5793 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5795 static char *expand_string_to_string(const char *str, int do_unbackslash)
5797 #if !ENABLE_HUSH_BASH_COMPAT
5798 const int do_unbackslash = 1;
5800 char *argv[2], **list;
5802 debug_printf_expand("string_to_string<='%s'\n", str);
5803 /* This is generally an optimization, but it also
5804 * handles "", which otherwise trips over !list[0] check below.
5805 * (is this ever happens that we actually get str="" here?)
5807 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5808 //TODO: Can use on strings with \ too, just unbackslash() them?
5809 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5810 return xstrdup(str);
5813 argv[0] = (char*)str;
5815 list = expand_variables(argv, do_unbackslash
5816 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5817 : EXP_FLAG_SINGLEWORD
5820 if (!list[0] || list[1])
5821 bb_error_msg_and_die("BUG in varexp2");
5822 /* actually, just move string 2*sizeof(char*) bytes back */
5823 overlapping_strcpy((char*)list, list[0]);
5825 unbackslash((char*)list);
5826 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5830 /* Used for "eval" builtin */
5831 static char* expand_strvec_to_string(char **argv)
5835 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5836 /* Convert all NULs to spaces */
5841 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5842 bb_error_msg_and_die("BUG in varexp3");
5843 /* bash uses ' ' regardless of $IFS contents */
5848 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
5849 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5853 static char **expand_assignments(char **argv, int count)
5858 G.expanded_assignments = p = NULL;
5859 /* Expand assignments into one string each */
5860 for (i = 0; i < count; i++) {
5861 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5863 G.expanded_assignments = NULL;
5868 static void switch_off_special_sigs(unsigned mask)
5871 while ((mask >>= 1) != 0) {
5876 if (G.traps[sig] && !G.traps[sig][0])
5877 /* trap is '', has to remain SIG_IGN */
5880 G.traps[sig] = NULL;
5882 /* We are here only if no trap or trap was not '' */
5883 install_sighandler(sig, SIG_DFL);
5889 void re_execute_shell(char ***to_free, const char *s,
5890 char *g_argv0, char **g_argv,
5891 char **builtin_argv) NORETURN;
5893 static void reset_traps_to_defaults(void)
5895 /* This function is always called in a child shell
5896 * after fork (not vfork, NOMMU doesn't use this function).
5901 /* Child shells are not interactive.
5902 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5903 * Testcase: (while :; do :; done) + ^Z should background.
5904 * Same goes for SIGTERM, SIGHUP, SIGINT.
5906 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5907 if (!G.traps && !mask)
5908 return; /* already no traps and no special sigs */
5910 /* Switch off special sigs */
5911 switch_off_special_sigs(mask);
5913 G_fatal_sig_mask = 0;
5915 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5916 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5917 * remain set in G.special_sig_mask */
5922 /* Reset all sigs to default except ones with empty traps */
5923 for (sig = 0; sig < NSIG; sig++) {
5925 continue; /* no trap: nothing to do */
5926 if (!G.traps[sig][0])
5927 continue; /* empty trap: has to remain SIG_IGN */
5928 /* sig has non-empty trap, reset it: */
5930 G.traps[sig] = NULL;
5931 /* There is no signal for trap 0 (EXIT) */
5934 install_sighandler(sig, pick_sighandler(sig));
5940 static void re_execute_shell(char ***to_free, const char *s,
5941 char *g_argv0, char **g_argv,
5942 char **builtin_argv) NORETURN;
5943 static void re_execute_shell(char ***to_free, const char *s,
5944 char *g_argv0, char **g_argv,
5945 char **builtin_argv)
5947 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5948 /* delims + 2 * (number of bytes in printed hex numbers) */
5949 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5950 char *heredoc_argv[4];
5951 struct variable *cur;
5952 # if ENABLE_HUSH_FUNCTIONS
5953 struct function *funcp;
5957 unsigned long long empty_trap_mask;
5959 if (!g_argv0) { /* heredoc */
5960 argv = heredoc_argv;
5961 argv[0] = (char *) G.argv0_for_re_execing;
5962 argv[1] = (char *) "-<";
5963 argv[2] = (char *) s;
5965 pp = &argv[3]; /* used as pointer to empty environment */
5971 if (pp) while (*pp++)
5974 empty_trap_mask = 0;
5977 for (sig = 1; sig < NSIG; sig++) {
5978 if (G.traps[sig] && !G.traps[sig][0])
5979 empty_trap_mask |= 1LL << sig;
5983 sprintf(param_buf, NOMMU_HACK_FMT
5984 , (unsigned) G.root_pid
5985 , (unsigned) G.root_ppid
5986 , (unsigned) G.last_bg_pid
5987 , (unsigned) G.last_exitcode
5990 IF_HUSH_LOOPS(, G.depth_of_loop)
5992 # undef NOMMU_HACK_FMT
5993 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5994 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5997 for (cur = G.top_var; cur; cur = cur->next) {
5998 if (!cur->flg_export || cur->flg_read_only)
6001 # if ENABLE_HUSH_FUNCTIONS
6002 for (funcp = G.top_func; funcp; funcp = funcp->next)
6008 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6009 *pp++ = (char *) G.argv0_for_re_execing;
6011 for (cur = G.top_var; cur; cur = cur->next) {
6012 if (strcmp(cur->varstr, hush_version_str) == 0)
6014 if (cur->flg_read_only) {
6015 *pp++ = (char *) "-R";
6016 *pp++ = cur->varstr;
6017 } else if (!cur->flg_export) {
6018 *pp++ = (char *) "-V";
6019 *pp++ = cur->varstr;
6022 # if ENABLE_HUSH_FUNCTIONS
6023 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6024 *pp++ = (char *) "-F";
6025 *pp++ = funcp->name;
6026 *pp++ = funcp->body_as_string;
6029 /* We can pass activated traps here. Say, -Tnn:trap_string
6031 * However, POSIX says that subshells reset signals with traps
6033 * I tested bash-3.2 and it not only does that with true subshells
6034 * of the form ( list ), but with any forked children shells.
6035 * I set trap "echo W" WINCH; and then tried:
6037 * { echo 1; sleep 20; echo 2; } &
6038 * while true; do echo 1; sleep 20; echo 2; break; done &
6039 * true | { echo 1; sleep 20; echo 2; } | cat
6041 * In all these cases sending SIGWINCH to the child shell
6042 * did not run the trap. If I add trap "echo V" WINCH;
6043 * _inside_ group (just before echo 1), it works.
6045 * I conclude it means we don't need to pass active traps here.
6047 *pp++ = (char *) "-c";
6050 while (*++builtin_argv)
6051 *pp++ = *builtin_argv;
6052 *pp++ = (char *) "";
6057 /* *pp = NULL; - is already there */
6061 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6062 /* Don't propagate SIG_IGN to the child */
6063 if (SPECIAL_JOBSTOP_SIGS != 0)
6064 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6065 execve(bb_busybox_exec_path, argv, pp);
6066 /* Fallback. Useful for init=/bin/hush usage etc */
6067 if (argv[0][0] == '/')
6068 execve(argv[0], argv, pp);
6069 xfunc_error_retval = 127;
6070 bb_error_msg_and_die("can't re-execute the shell");
6072 #endif /* !BB_MMU */
6075 static int run_and_free_list(struct pipe *pi);
6077 /* Executing from string: eval, sh -c '...'
6078 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6079 * end_trigger controls how often we stop parsing
6080 * NUL: parse all, execute, return
6081 * ';': parse till ';' or newline, execute, repeat till EOF
6083 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6085 /* Why we need empty flag?
6086 * An obscure corner case "false; ``; echo $?":
6087 * empty command in `` should still set $? to 0.
6088 * But we can't just set $? to 0 at the start,
6089 * this breaks "false; echo `echo $?`" case.
6093 struct pipe *pipe_list;
6095 #if ENABLE_HUSH_INTERACTIVE
6096 if (end_trigger == ';')
6097 inp->promptmode = 0; /* PS1 */
6099 pipe_list = parse_stream(NULL, inp, end_trigger);
6100 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6101 /* If we are in "big" script
6102 * (not in `cmd` or something similar)...
6104 if (pipe_list == ERR_PTR && end_trigger == ';') {
6105 /* Discard cached input (rest of line) */
6106 int ch = inp->last_char;
6107 while (ch != EOF && ch != '\n') {
6108 //bb_error_msg("Discarded:'%c'", ch);
6113 /* This stream isn't empty */
6117 if (!pipe_list && empty)
6118 G.last_exitcode = 0;
6121 debug_print_tree(pipe_list, 0);
6122 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6123 run_and_free_list(pipe_list);
6125 if (G_flag_return_in_progress == 1)
6130 static void parse_and_run_string(const char *s)
6132 struct in_str input;
6133 setup_string_in_str(&input, s);
6134 parse_and_run_stream(&input, '\0');
6137 static void parse_and_run_file(FILE *f)
6139 struct in_str input;
6140 setup_file_in_str(&input, f);
6141 parse_and_run_stream(&input, ';');
6144 #if ENABLE_HUSH_TICK
6145 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6150 char **to_free = NULL;
6154 pid = BB_MMU ? xfork() : xvfork();
6155 if (pid == 0) { /* child */
6156 disable_restore_tty_pgrp_on_exit();
6157 /* Process substitution is not considered to be usual
6158 * 'command execution'.
6159 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6166 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6167 close(channel[0]); /* NB: close _first_, then move fd! */
6168 xmove_fd(channel[1], 1);
6169 /* Prevent it from trying to handle ctrl-z etc */
6170 IF_HUSH_JOB(G.run_list_level = 1;)
6171 /* Awful hack for `trap` or $(trap).
6173 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6174 * contains an example where "trap" is executed in a subshell:
6176 * save_traps=$(trap)
6178 * eval "$save_traps"
6180 * Standard does not say that "trap" in subshell shall print
6181 * parent shell's traps. It only says that its output
6182 * must have suitable form, but then, in the above example
6183 * (which is not supposed to be normative), it implies that.
6185 * bash (and probably other shell) does implement it
6186 * (traps are reset to defaults, but "trap" still shows them),
6187 * but as a result, "trap" logic is hopelessly messed up:
6190 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6191 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6192 * # true | trap <--- trap is in subshell - no output (ditto)
6193 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6194 * trap -- 'echo Ho' SIGWINCH
6195 * # echo `(trap)` <--- in subshell in subshell - output
6196 * trap -- 'echo Ho' SIGWINCH
6197 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6198 * trap -- 'echo Ho' SIGWINCH
6200 * The rules when to forget and when to not forget traps
6201 * get really complex and nonsensical.
6203 * Our solution: ONLY bare $(trap) or `trap` is special.
6205 s = skip_whitespace(s);
6206 if (is_prefixed_with(s, "trap")
6207 && skip_whitespace(s + 4)[0] == '\0'
6209 static const char *const argv[] = { NULL, NULL };
6210 builtin_trap((char**)argv);
6211 fflush_all(); /* important */
6215 reset_traps_to_defaults();
6216 parse_and_run_string(s);
6217 _exit(G.last_exitcode);
6219 /* We re-execute after vfork on NOMMU. This makes this script safe:
6220 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6221 * huge=`cat BIG` # was blocking here forever
6224 re_execute_shell(&to_free,
6234 # if ENABLE_HUSH_FAST
6236 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6237 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6238 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6240 enable_restore_tty_pgrp_on_exit();
6245 return remember_FILE(xfdopen_for_read(channel[0]));
6248 /* Return code is exit status of the process that is run. */
6249 static int process_command_subs(o_string *dest, const char *s)
6252 struct in_str pipe_str;
6254 int status, ch, eol_cnt;
6256 fp = generate_stream_from_string(s, &pid);
6258 /* Now send results of command back into original context */
6259 setup_file_in_str(&pipe_str, fp);
6261 while ((ch = i_getch(&pipe_str)) != EOF) {
6267 o_addchr(dest, '\n');
6270 o_addQchr(dest, ch);
6273 debug_printf("done reading from `cmd` pipe, closing it\n");
6274 fclose_and_forget(fp);
6275 /* We need to extract exitcode. Test case
6276 * "true; echo `sleep 1; false` $?"
6278 safe_waitpid(pid, &status, 0);
6279 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6280 return WEXITSTATUS(status);
6282 #endif /* ENABLE_HUSH_TICK */
6285 static void setup_heredoc(struct redir_struct *redir)
6287 struct fd_pair pair;
6290 /* the _body_ of heredoc (misleading field name) */
6291 const char *heredoc = redir->rd_filename;
6298 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6299 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6303 len = strlen(heredoc);
6305 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6307 xmove_fd(pair.rd, redir->rd_fd);
6309 /* Try writing without forking. Newer kernels have
6310 * dynamically growing pipes. Must use non-blocking write! */
6313 written = write(pair.wr, heredoc, len);
6324 ndelay_off(pair.wr);
6326 /* Okay, pipe buffer was not big enough */
6327 /* Note: we must not create a stray child (bastard? :)
6328 * for the unsuspecting parent process. Child creates a grandchild
6329 * and exits before parent execs the process which consumes heredoc
6330 * (that exec happens after we return from this function) */
6337 disable_restore_tty_pgrp_on_exit();
6338 pid = BB_MMU ? xfork() : xvfork();
6342 close(redir->rd_fd); /* read side of the pipe */
6344 full_write(pair.wr, heredoc, len); /* may loop or block */
6347 /* Delegate blocking writes to another process */
6348 xmove_fd(pair.wr, STDOUT_FILENO);
6349 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6353 #if ENABLE_HUSH_FAST
6355 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6357 enable_restore_tty_pgrp_on_exit();
6363 wait(NULL); /* wait till child has died */
6366 /* fd: redirect wants this fd to be used (e.g. 3>file).
6367 * Move all conflicting internally used fds,
6368 * and remember them so that we can restore them later.
6370 static int save_fds_on_redirect(int fd, int squirrel[3])
6373 /* Handle redirects of fds 0,1,2 */
6375 /* If we collide with an already moved stdio fd... */
6376 if (fd == squirrel[0]) {
6377 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6380 if (fd == squirrel[1]) {
6381 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6384 if (fd == squirrel[2]) {
6385 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6388 /* If we are about to redirect stdio fd, and did not yet move it... */
6389 if (fd <= 2 && squirrel[fd] < 0) {
6390 /* We avoid taking stdio fds */
6391 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6392 if (squirrel[fd] < 0 && errno != EBADF)
6394 return 0; /* "we did not close fd" */
6398 #if ENABLE_HUSH_INTERACTIVE
6399 if (fd != 0 && fd == G.interactive_fd) {
6400 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6405 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6406 * (1) Redirect in a forked child. No need to save FILEs' fds,
6407 * we aren't going to use them anymore, ok to trash.
6408 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6409 * but how are we doing to use them?
6410 * "fileno(fd) = new_fd" can't be done.
6415 return save_FILEs_on_redirect(fd);
6418 static void restore_redirects(int squirrel[3])
6421 for (i = 0; i <= 2; i++) {
6424 /* We simply die on error */
6429 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6431 restore_redirected_FILEs();
6434 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6435 * and stderr if they are redirected. */
6436 static int setup_redirects(struct command *prog, int squirrel[])
6439 struct redir_struct *redir;
6441 for (redir = prog->redirects; redir; redir = redir->next) {
6442 if (redir->rd_type == REDIRECT_HEREDOC2) {
6443 /* "rd_fd<<HERE" case */
6444 save_fds_on_redirect(redir->rd_fd, squirrel);
6445 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6447 debug_printf_parse("set heredoc '%s'\n",
6448 redir->rd_filename);
6449 setup_heredoc(redir);
6453 if (redir->rd_dup == REDIRFD_TO_FILE) {
6454 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6456 if (redir->rd_filename == NULL) {
6459 * "cmd >" (no filename)
6460 * "cmd > <file" (2nd redirect starts too early)
6462 die_if_script("syntax error: %s", "invalid redirect");
6465 mode = redir_table[redir->rd_type].mode;
6466 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6467 openfd = open_or_warn(p, mode);
6470 /* Error message from open_or_warn can be lost
6471 * if stderr has been redirected, but bash
6472 * and ash both lose it as well
6473 * (though zsh doesn't!)
6478 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6479 openfd = redir->rd_dup;
6482 if (openfd != redir->rd_fd) {
6483 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6484 if (openfd == REDIRFD_CLOSE) {
6485 /* "rd_fd >&-" means "close me" */
6487 /* ^^^ optimization: saving may already
6488 * have closed it. If not... */
6489 close(redir->rd_fd);
6492 xdup2(openfd, redir->rd_fd);
6493 if (redir->rd_dup == REDIRFD_TO_FILE)
6494 /* "rd_fd > FILE" */
6496 /* else: "rd_fd > rd_dup" */
6503 static char *find_in_path(const char *arg)
6506 const char *PATH = get_local_var_value("PATH");
6512 const char *end = strchrnul(PATH, ':');
6513 int sz = end - PATH; /* must be int! */
6517 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6519 /* We have xxx::yyyy in $PATH,
6520 * it means "use current dir" */
6523 if (access(ret, F_OK) == 0)
6536 static const struct built_in_command *find_builtin_helper(const char *name,
6537 const struct built_in_command *x,
6538 const struct built_in_command *end)
6541 if (strcmp(name, x->b_cmd) != 0) {
6545 debug_printf_exec("found builtin '%s'\n", name);
6550 static const struct built_in_command *find_builtin1(const char *name)
6552 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6554 static const struct built_in_command *find_builtin(const char *name)
6556 const struct built_in_command *x = find_builtin1(name);
6559 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6562 #if ENABLE_HUSH_FUNCTIONS
6563 static struct function **find_function_slot(const char *name)
6565 struct function **funcpp = &G.top_func;
6567 if (strcmp(name, (*funcpp)->name) == 0) {
6570 funcpp = &(*funcpp)->next;
6575 static const struct function *find_function(const char *name)
6577 const struct function *funcp = *find_function_slot(name);
6579 debug_printf_exec("found function '%s'\n", name);
6583 /* Note: takes ownership on name ptr */
6584 static struct function *new_function(char *name)
6586 struct function **funcpp = find_function_slot(name);
6587 struct function *funcp = *funcpp;
6589 if (funcp != NULL) {
6590 struct command *cmd = funcp->parent_cmd;
6591 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6593 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6595 /* Note: if !funcp->body, do not free body_as_string!
6596 * This is a special case of "-F name body" function:
6597 * body_as_string was not malloced! */
6599 free_pipe_list(funcp->body);
6601 free(funcp->body_as_string);
6605 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6606 cmd->argv[0] = funcp->name;
6607 cmd->group = funcp->body;
6609 cmd->group_as_string = funcp->body_as_string;
6613 debug_printf_exec("remembering new function '%s'\n", name);
6614 funcp = *funcpp = xzalloc(sizeof(*funcp));
6615 /*funcp->next = NULL;*/
6622 static void unset_func(const char *name)
6624 struct function **funcpp = find_function_slot(name);
6625 struct function *funcp = *funcpp;
6627 if (funcp != NULL) {
6628 debug_printf_exec("freeing function '%s'\n", funcp->name);
6629 *funcpp = funcp->next;
6630 /* funcp is unlinked now, deleting it.
6631 * Note: if !funcp->body, the function was created by
6632 * "-F name body", do not free ->body_as_string
6633 * and ->name as they were not malloced. */
6635 free_pipe_list(funcp->body);
6638 free(funcp->body_as_string);
6646 #define exec_function(to_free, funcp, argv) \
6647 exec_function(funcp, argv)
6649 static void exec_function(char ***to_free,
6650 const struct function *funcp,
6651 char **argv) NORETURN;
6652 static void exec_function(char ***to_free,
6653 const struct function *funcp,
6659 argv[0] = G.global_argv[0];
6660 G.global_argv = argv;
6664 /* On MMU, funcp->body is always non-NULL */
6665 n = run_list(funcp->body);
6669 re_execute_shell(to_free,
6670 funcp->body_as_string,
6677 static int run_function(const struct function *funcp, char **argv)
6683 save_and_replace_G_args(&sv, argv);
6685 /* "we are in function, ok to use return" */
6686 sv_flg = G_flag_return_in_progress;
6687 G_flag_return_in_progress = -1;
6688 # if ENABLE_HUSH_LOCAL
6689 G.func_nest_level++;
6692 /* On MMU, funcp->body is always non-NULL */
6695 /* Function defined by -F */
6696 parse_and_run_string(funcp->body_as_string);
6697 rc = G.last_exitcode;
6701 rc = run_list(funcp->body);
6704 # if ENABLE_HUSH_LOCAL
6706 struct variable *var;
6707 struct variable **var_pp;
6709 var_pp = &G.top_var;
6710 while ((var = *var_pp) != NULL) {
6711 if (var->func_nest_level < G.func_nest_level) {
6712 var_pp = &var->next;
6716 if (var->flg_export)
6717 bb_unsetenv(var->varstr);
6718 /* Remove from global list */
6719 *var_pp = var->next;
6725 G.func_nest_level--;
6728 G_flag_return_in_progress = sv_flg;
6730 restore_G_args(&sv, argv);
6734 #endif /* ENABLE_HUSH_FUNCTIONS */
6738 #define exec_builtin(to_free, x, argv) \
6739 exec_builtin(x, argv)
6741 #define exec_builtin(to_free, x, argv) \
6742 exec_builtin(to_free, argv)
6744 static void exec_builtin(char ***to_free,
6745 const struct built_in_command *x,
6746 char **argv) NORETURN;
6747 static void exec_builtin(char ***to_free,
6748 const struct built_in_command *x,
6754 rcode = x->b_function(argv);
6759 /* On NOMMU, we must never block!
6760 * Example: { sleep 99 | read line; } & echo Ok
6762 re_execute_shell(to_free,
6771 static void execvp_or_die(char **argv) NORETURN;
6772 static void execvp_or_die(char **argv)
6775 debug_printf_exec("execing '%s'\n", argv[0]);
6776 /* Don't propagate SIG_IGN to the child */
6777 if (SPECIAL_JOBSTOP_SIGS != 0)
6778 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6779 execvp(argv[0], argv);
6781 if (errno == EACCES) e = 126;
6782 if (errno == ENOENT) e = 127;
6783 bb_perror_msg("can't execute '%s'", argv[0]);
6787 #if ENABLE_HUSH_MODE_X
6788 static void dump_cmd_in_x_mode(char **argv)
6790 if (G_x_mode && argv) {
6791 /* We want to output the line in one write op */
6799 len += strlen(argv[n++]) + 1;
6805 p += sprintf(p, " %s", argv[n++]);
6813 # define dump_cmd_in_x_mode(argv) ((void)0)
6817 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6818 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6819 #define pseudo_exec(nommu_save, command, argv_expanded) \
6820 pseudo_exec(command, argv_expanded)
6823 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6825 * Don't exit() here. If you don't exec, use _exit instead.
6826 * The at_exit handlers apparently confuse the calling process,
6827 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6829 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6830 char **argv, int assignment_cnt,
6831 char **argv_expanded) NORETURN;
6832 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6833 char **argv, int assignment_cnt,
6834 char **argv_expanded)
6838 new_env = expand_assignments(argv, assignment_cnt);
6839 dump_cmd_in_x_mode(new_env);
6841 if (!argv[assignment_cnt]) {
6842 /* Case when we are here: ... | var=val | ...
6843 * (note that we do not exit early, i.e., do not optimize out
6844 * expand_assignments(): think about ... | var=`sleep 1` | ...
6846 free_strings(new_env);
6847 _exit(EXIT_SUCCESS);
6851 set_vars_and_save_old(new_env);
6852 free(new_env); /* optional */
6853 /* we can also destroy set_vars_and_save_old's return value,
6856 nommu_save->new_env = new_env;
6857 nommu_save->old_vars = set_vars_and_save_old(new_env);
6860 if (argv_expanded) {
6861 argv = argv_expanded;
6863 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6865 nommu_save->argv = argv;
6868 dump_cmd_in_x_mode(argv);
6870 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6871 if (strchr(argv[0], '/') != NULL)
6875 /* Check if the command matches any of the builtins.
6876 * Depending on context, this might be redundant. But it's
6877 * easier to waste a few CPU cycles than it is to figure out
6878 * if this is one of those cases.
6881 /* On NOMMU, it is more expensive to re-execute shell
6882 * just in order to run echo or test builtin.
6883 * It's better to skip it here and run corresponding
6884 * non-builtin later. */
6885 const struct built_in_command *x;
6886 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6888 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6891 #if ENABLE_HUSH_FUNCTIONS
6892 /* Check if the command matches any functions */
6894 const struct function *funcp = find_function(argv[0]);
6896 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6901 #if ENABLE_FEATURE_SH_STANDALONE
6902 /* Check if the command matches any busybox applets */
6904 int a = find_applet_by_name(argv[0]);
6906 # if BB_MMU /* see above why on NOMMU it is not allowed */
6907 if (APPLET_IS_NOEXEC(a)) {
6908 /* Do not leak open fds from opened script files etc */
6909 close_all_FILE_list();
6910 debug_printf_exec("running applet '%s'\n", argv[0]);
6911 run_applet_no_and_exit(a, argv);
6914 /* Re-exec ourselves */
6915 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6916 /* Don't propagate SIG_IGN to the child */
6917 if (SPECIAL_JOBSTOP_SIGS != 0)
6918 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6919 execv(bb_busybox_exec_path, argv);
6920 /* If they called chroot or otherwise made the binary no longer
6921 * executable, fall through */
6926 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6929 execvp_or_die(argv);
6932 /* Called after [v]fork() in run_pipe
6934 static void pseudo_exec(nommu_save_t *nommu_save,
6935 struct command *command,
6936 char **argv_expanded) NORETURN;
6937 static void pseudo_exec(nommu_save_t *nommu_save,
6938 struct command *command,
6939 char **argv_expanded)
6941 if (command->argv) {
6942 pseudo_exec_argv(nommu_save, command->argv,
6943 command->assignment_cnt, argv_expanded);
6946 if (command->group) {
6947 /* Cases when we are here:
6950 * ... | ( list ) | ...
6951 * ... | { list } | ...
6955 debug_printf_exec("pseudo_exec: run_list\n");
6956 reset_traps_to_defaults();
6957 rcode = run_list(command->group);
6958 /* OK to leak memory by not calling free_pipe_list,
6959 * since this process is about to exit */
6962 re_execute_shell(&nommu_save->argv_from_re_execing,
6963 command->group_as_string,
6970 /* Case when we are here: ... | >file */
6971 debug_printf_exec("pseudo_exec'ed null command\n");
6972 _exit(EXIT_SUCCESS);
6976 static const char *get_cmdtext(struct pipe *pi)
6982 /* This is subtle. ->cmdtext is created only on first backgrounding.
6983 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6984 * On subsequent bg argv is trashed, but we won't use it */
6987 argv = pi->cmds[0].argv;
6988 if (!argv || !argv[0]) {
6989 pi->cmdtext = xzalloc(1);
6995 len += strlen(*argv) + 1;
6999 argv = pi->cmds[0].argv;
7001 len = strlen(*argv);
7002 memcpy(p, *argv, len);
7010 static void insert_bg_job(struct pipe *pi)
7012 struct pipe *job, **jobp;
7015 /* Linear search for the ID of the job to use */
7017 for (job = G.job_list; job; job = job->next)
7018 if (job->jobid >= pi->jobid)
7019 pi->jobid = job->jobid + 1;
7021 /* Add job to the list of running jobs */
7023 while ((job = *jobp) != NULL)
7025 job = *jobp = xmalloc(sizeof(*job));
7027 *job = *pi; /* physical copy */
7029 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7030 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7031 for (i = 0; i < pi->num_cmds; i++) {
7032 job->cmds[i].pid = pi->cmds[i].pid;
7033 /* all other fields are not used and stay zero */
7035 job->cmdtext = xstrdup(get_cmdtext(pi));
7037 if (G_interactive_fd)
7038 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
7039 G.last_jobid = job->jobid;
7042 static void remove_bg_job(struct pipe *pi)
7044 struct pipe *prev_pipe;
7046 if (pi == G.job_list) {
7047 G.job_list = pi->next;
7049 prev_pipe = G.job_list;
7050 while (prev_pipe->next != pi)
7051 prev_pipe = prev_pipe->next;
7052 prev_pipe->next = pi->next;
7055 G.last_jobid = G.job_list->jobid;
7060 /* Remove a backgrounded job */
7061 static void delete_finished_bg_job(struct pipe *pi)
7068 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7075 dead = WIFEXITED(status) || WIFSIGNALED(status);
7078 if (WIFSTOPPED(status))
7079 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7080 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7081 if (WIFSIGNALED(status))
7082 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7083 childpid, WTERMSIG(status), WEXITSTATUS(status));
7084 if (WIFEXITED(status))
7085 debug_printf_jobs("pid %d exited, exitcode %d\n",
7086 childpid, WEXITSTATUS(status));
7088 /* Were we asked to wait for a fg pipe? */
7090 i = fg_pipe->num_cmds;
7092 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7093 if (fg_pipe->cmds[i].pid != childpid)
7097 fg_pipe->cmds[i].pid = 0;
7098 fg_pipe->alive_cmds--;
7099 ex = WEXITSTATUS(status);
7100 /* bash prints killer signal's name for *last*
7101 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7102 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7104 if (WIFSIGNALED(status)) {
7105 int sig = WTERMSIG(status);
7106 if (i == fg_pipe->num_cmds-1)
7107 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7108 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7109 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7110 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7111 * Maybe we need to use sig | 128? */
7114 fg_pipe->cmds[i].cmd_exitcode = ex;
7116 fg_pipe->stopped_cmds++;
7118 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7119 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7120 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
7121 /* All processes in fg pipe have exited or stopped */
7123 i = fg_pipe->num_cmds;
7125 rcode = fg_pipe->cmds[i].cmd_exitcode;
7126 /* usually last process gives overall exitstatus,
7127 * but with "set -o pipefail", last *failed* process does */
7128 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7131 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
7132 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7133 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7134 * and "killall -STOP cat" */
7135 if (G_interactive_fd) {
7137 if (fg_pipe->alive_cmds != 0)
7138 insert_bg_job(fg_pipe);
7142 if (fg_pipe->alive_cmds == 0)
7145 /* There are still running processes in the fg_pipe */
7148 /* It wasnt in fg_pipe, look for process in bg pipes */
7152 /* We were asked to wait for bg or orphaned children */
7153 /* No need to remember exitcode in this case */
7154 for (pi = G.job_list; pi; pi = pi->next) {
7155 for (i = 0; i < pi->num_cmds; i++) {
7156 if (pi->cmds[i].pid == childpid)
7157 goto found_pi_and_prognum;
7160 /* Happens when shell is used as init process (init=/bin/sh) */
7161 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7162 return -1; /* this wasn't a process from fg_pipe */
7164 found_pi_and_prognum:
7167 pi->cmds[i].pid = 0;
7168 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7169 if (WIFSIGNALED(status))
7170 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7172 if (!pi->alive_cmds) {
7173 if (G_interactive_fd)
7174 printf(JOB_STATUS_FORMAT, pi->jobid,
7175 "Done", pi->cmdtext);
7176 delete_finished_bg_job(pi);
7183 return -1; /* this wasn't a process from fg_pipe */
7186 /* Check to see if any processes have exited -- if they have,
7187 * figure out why and see if a job has completed.
7188 * Alternatively (fg_pipe == NULL, waitfor_pid != 0),
7189 * wait for a specific pid to complete, return exitcode+1
7190 * (this allows to distinguish zero as "no children exited" result).
7192 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7198 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7200 attributes = WUNTRACED;
7201 if (fg_pipe == NULL)
7202 attributes |= WNOHANG;
7205 #if ENABLE_HUSH_FAST
7206 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7207 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7208 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7209 /* There was neither fork nor SIGCHLD since last waitpid */
7210 /* Avoid doing waitpid syscall if possible */
7211 if (!G.we_have_children) {
7215 if (fg_pipe == NULL) { /* is WNOHANG set? */
7216 /* We have children, but they did not exit
7217 * or stop yet (we saw no SIGCHLD) */
7220 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7224 /* Do we do this right?
7225 * bash-3.00# sleep 20 | false
7227 * [3]+ Stopped sleep 20 | false
7228 * bash-3.00# echo $?
7229 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7230 * [hush 1.14.0: yes we do it right]
7234 #if ENABLE_HUSH_FAST
7236 i = G.count_SIGCHLD;
7238 childpid = waitpid(-1, &status, attributes);
7239 if (childpid <= 0) {
7240 if (childpid && errno != ECHILD)
7241 bb_perror_msg("waitpid");
7242 #if ENABLE_HUSH_FAST
7243 else { /* Until next SIGCHLD, waitpid's are useless */
7244 G.we_have_children = (childpid == 0);
7245 G.handled_SIGCHLD = i;
7246 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7249 /* ECHILD (no children), or 0 (no change in children status) */
7253 rcode = process_wait_result(fg_pipe, childpid, status);
7255 /* fg_pipe exited or stopped */
7258 if (childpid == waitfor_pid) {
7259 rcode = WEXITSTATUS(status);
7260 if (WIFSIGNALED(status))
7261 rcode = 128 + WTERMSIG(status);
7263 break; /* "wait PID" called us, give it exitcode+1 */
7265 /* This wasn't one of our processes, or */
7266 /* fg_pipe still has running processes, do waitpid again */
7267 } /* while (waitpid succeeds)... */
7273 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7276 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7277 if (G_saved_tty_pgrp) {
7278 /* Job finished, move the shell to the foreground */
7279 p = getpgrp(); /* our process group id */
7280 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7281 tcsetpgrp(G_interactive_fd, p);
7287 /* Start all the jobs, but don't wait for anything to finish.
7290 * Return code is normally -1, when the caller has to wait for children
7291 * to finish to determine the exit status of the pipe. If the pipe
7292 * is a simple builtin command, however, the action is done by the
7293 * time run_pipe returns, and the exit code is provided as the
7296 * Returns -1 only if started some children. IOW: we have to
7297 * mask out retvals of builtins etc with 0xff!
7299 * The only case when we do not need to [v]fork is when the pipe
7300 * is single, non-backgrounded, non-subshell command. Examples:
7301 * cmd ; ... { list } ; ...
7302 * cmd && ... { list } && ...
7303 * cmd || ... { list } || ...
7304 * If it is, then we can run cmd as a builtin, NOFORK,
7305 * or (if SH_STANDALONE) an applet, and we can run the { list }
7306 * with run_list. If it isn't one of these, we fork and exec cmd.
7308 * Cases when we must fork:
7309 * non-single: cmd | cmd
7310 * backgrounded: cmd & { list } &
7311 * subshell: ( list ) [&]
7313 #if !ENABLE_HUSH_MODE_X
7314 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7315 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7317 static int redirect_and_varexp_helper(char ***new_env_p,
7318 struct variable **old_vars_p,
7319 struct command *command,
7321 char **argv_expanded)
7323 /* setup_redirects acts on file descriptors, not FILEs.
7324 * This is perfect for work that comes after exec().
7325 * Is it really safe for inline use? Experimentally,
7326 * things seem to work. */
7327 int rcode = setup_redirects(command, squirrel);
7329 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7330 *new_env_p = new_env;
7331 dump_cmd_in_x_mode(new_env);
7332 dump_cmd_in_x_mode(argv_expanded);
7334 *old_vars_p = set_vars_and_save_old(new_env);
7338 static NOINLINE int run_pipe(struct pipe *pi)
7340 static const char *const null_ptr = NULL;
7344 struct command *command;
7345 char **argv_expanded;
7347 /* it is not always needed, but we aim to smaller code */
7348 int squirrel[] = { -1, -1, -1 };
7351 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7354 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7355 * Result should be 3 lines: q w e, qwe, q w e
7357 G.ifs = get_local_var_value("IFS");
7361 IF_HUSH_JOB(pi->pgrp = -1;)
7362 pi->stopped_cmds = 0;
7363 command = &pi->cmds[0];
7364 argv_expanded = NULL;
7366 if (pi->num_cmds != 1
7367 || pi->followup == PIPE_BG
7368 || command->cmd_type == CMD_SUBSHELL
7375 debug_printf_exec(": group:%p argv:'%s'\n",
7376 command->group, command->argv ? command->argv[0] : "NONE");
7378 if (command->group) {
7379 #if ENABLE_HUSH_FUNCTIONS
7380 if (command->cmd_type == CMD_FUNCDEF) {
7381 /* "executing" func () { list } */
7382 struct function *funcp;
7384 funcp = new_function(command->argv[0]);
7385 /* funcp->name is already set to argv[0] */
7386 funcp->body = command->group;
7388 funcp->body_as_string = command->group_as_string;
7389 command->group_as_string = NULL;
7391 command->group = NULL;
7392 command->argv[0] = NULL;
7393 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7394 funcp->parent_cmd = command;
7395 command->child_func = funcp;
7397 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7399 return EXIT_SUCCESS;
7403 debug_printf("non-subshell group\n");
7404 rcode = 1; /* exitcode if redir failed */
7405 if (setup_redirects(command, squirrel) == 0) {
7406 debug_printf_exec(": run_list\n");
7407 rcode = run_list(command->group) & 0xff;
7409 restore_redirects(squirrel);
7410 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7412 debug_printf_exec("run_pipe: return %d\n", rcode);
7416 argv = command->argv ? command->argv : (char **) &null_ptr;
7418 const struct built_in_command *x;
7419 #if ENABLE_HUSH_FUNCTIONS
7420 const struct function *funcp;
7424 char **new_env = NULL;
7425 struct variable *old_vars = NULL;
7427 if (argv[command->assignment_cnt] == NULL) {
7428 /* Assignments, but no command */
7429 /* Ensure redirects take effect (that is, create files).
7430 * Try "a=t >file" */
7431 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7432 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7433 /* Set shell variables */
7437 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7438 /* Do we need to flag set_local_var() errors?
7439 * "assignment to readonly var" and "putenv error"
7444 /* Redirect error sets $? to 1. Otherwise,
7445 * if evaluating assignment value set $?, retain it.
7446 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7448 rcode = G.last_exitcode;
7449 /* Exit, _skipping_ variable restoring code: */
7450 goto clean_up_and_ret0;
7452 #else /* Older, bigger, but more correct code */
7454 rcode = setup_redirects(command, squirrel);
7455 restore_redirects(squirrel);
7456 /* Set shell variables */
7458 bb_putchar_stderr('+');
7460 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7462 fprintf(stderr, " %s", p);
7463 debug_printf_exec("set shell var:'%s'->'%s'\n",
7465 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7466 /* Do we need to flag set_local_var() errors?
7467 * "assignment to readonly var" and "putenv error"
7472 bb_putchar_stderr('\n');
7473 /* Redirect error sets $? to 1. Otherwise,
7474 * if evaluating assignment value set $?, retain it.
7475 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7477 rcode = G.last_exitcode;
7478 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7480 debug_printf_exec("run_pipe: return %d\n", rcode);
7485 /* Expand the rest into (possibly) many strings each */
7486 #if ENABLE_HUSH_BASH_COMPAT
7487 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7488 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7492 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7495 /* if someone gives us an empty string: `cmd with empty output` */
7496 if (!argv_expanded[0]) {
7497 free(argv_expanded);
7499 return G.last_exitcode;
7502 x = find_builtin(argv_expanded[0]);
7503 #if ENABLE_HUSH_FUNCTIONS
7506 funcp = find_function(argv_expanded[0]);
7510 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7511 debug_printf("exec with redirects only\n");
7512 rcode = setup_redirects(command, NULL);
7513 /* rcode=1 can be if redir file can't be opened */
7514 goto clean_up_and_ret1;
7517 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7520 debug_printf_exec(": builtin '%s' '%s'...\n",
7521 x->b_cmd, argv_expanded[1]);
7523 rcode = x->b_function(argv_expanded) & 0xff;
7526 #if ENABLE_HUSH_FUNCTIONS
7528 # if ENABLE_HUSH_LOCAL
7529 struct variable **sv;
7530 sv = G.shadowed_vars_pp;
7531 G.shadowed_vars_pp = &old_vars;
7533 debug_printf_exec(": function '%s' '%s'...\n",
7534 funcp->name, argv_expanded[1]);
7535 rcode = run_function(funcp, argv_expanded) & 0xff;
7536 # if ENABLE_HUSH_LOCAL
7537 G.shadowed_vars_pp = sv;
7543 unset_vars(new_env);
7545 /* clean_up_and_ret0: */
7546 restore_redirects(squirrel);
7548 free(argv_expanded);
7549 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7551 debug_printf_exec("run_pipe return %d\n", rcode);
7555 if (ENABLE_FEATURE_SH_NOFORK) {
7556 int n = find_applet_by_name(argv_expanded[0]);
7557 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7558 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7560 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7561 argv_expanded[0], argv_expanded[1]);
7562 rcode = run_nofork_applet(n, argv_expanded);
7564 goto clean_up_and_ret;
7567 /* It is neither builtin nor applet. We must fork. */
7571 /* NB: argv_expanded may already be created, and that
7572 * might include `cmd` runs! Do not rerun it! We *must*
7573 * use argv_expanded if it's non-NULL */
7575 /* Going to fork a child per each pipe member */
7580 while (cmd_no < pi->num_cmds) {
7581 struct fd_pair pipefds;
7583 volatile nommu_save_t nommu_save;
7584 nommu_save.new_env = NULL;
7585 nommu_save.old_vars = NULL;
7586 nommu_save.argv = NULL;
7587 nommu_save.argv_from_re_execing = NULL;
7589 command = &pi->cmds[cmd_no];
7591 if (command->argv) {
7592 debug_printf_exec(": pipe member '%s' '%s'...\n",
7593 command->argv[0], command->argv[1]);
7595 debug_printf_exec(": pipe member with no argv\n");
7598 /* pipes are inserted between pairs of commands */
7601 if (cmd_no < pi->num_cmds)
7602 xpiped_pair(pipefds);
7604 command->pid = BB_MMU ? fork() : vfork();
7605 if (!command->pid) { /* child */
7607 disable_restore_tty_pgrp_on_exit();
7608 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7610 /* Every child adds itself to new process group
7611 * with pgid == pid_of_first_child_in_pipe */
7612 if (G.run_list_level == 1 && G_interactive_fd) {
7615 if (pgrp < 0) /* true for 1st process only */
7617 if (setpgid(0, pgrp) == 0
7618 && pi->followup != PIPE_BG
7619 && G_saved_tty_pgrp /* we have ctty */
7621 /* We do it in *every* child, not just first,
7623 tcsetpgrp(G_interactive_fd, pgrp);
7627 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7628 /* 1st cmd in backgrounded pipe
7629 * should have its stdin /dev/null'ed */
7631 if (open(bb_dev_null, O_RDONLY))
7632 xopen("/", O_RDONLY);
7634 xmove_fd(next_infd, 0);
7636 xmove_fd(pipefds.wr, 1);
7639 /* Like bash, explicit redirects override pipes,
7640 * and the pipe fd (fd#1) is available for dup'ing:
7641 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7642 * of cmd1 goes into pipe.
7644 if (setup_redirects(command, NULL)) {
7645 /* Happens when redir file can't be opened:
7646 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7648 * hush: can't open '/qwe/rty': No such file or directory
7650 * (echo BAR is not executed, it hits _exit(1) below)
7655 /* Stores to nommu_save list of env vars putenv'ed
7656 * (NOMMU, on MMU we don't need that) */
7657 /* cast away volatility... */
7658 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7659 /* pseudo_exec() does not return */
7662 /* parent or error */
7663 #if ENABLE_HUSH_FAST
7665 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7667 enable_restore_tty_pgrp_on_exit();
7669 /* Clean up after vforked child */
7670 free(nommu_save.argv);
7671 free(nommu_save.argv_from_re_execing);
7672 unset_vars(nommu_save.new_env);
7673 add_vars(nommu_save.old_vars);
7675 free(argv_expanded);
7676 argv_expanded = NULL;
7677 if (command->pid < 0) { /* [v]fork failed */
7678 /* Clearly indicate, was it fork or vfork */
7679 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7683 /* Second and next children need to know pid of first one */
7685 pi->pgrp = command->pid;
7691 if (cmd_no < pi->num_cmds)
7693 /* Pass read (output) pipe end to next iteration */
7694 next_infd = pipefds.rd;
7697 if (!pi->alive_cmds) {
7699 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7704 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7708 /* NB: called by pseudo_exec, and therefore must not modify any
7709 * global data until exec/_exit (we can be a child after vfork!) */
7710 static int run_list(struct pipe *pi)
7712 #if ENABLE_HUSH_CASE
7713 char *case_word = NULL;
7715 #if ENABLE_HUSH_LOOPS
7716 struct pipe *loop_top = NULL;
7717 char **for_lcur = NULL;
7718 char **for_list = NULL;
7720 smallint last_followup;
7722 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7723 smalluint cond_code = 0;
7725 enum { cond_code = 0 };
7728 smallint rword; /* RES_foo */
7729 smallint last_rword; /* ditto */
7732 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7735 #if ENABLE_HUSH_LOOPS
7736 /* Check syntax for "for" */
7739 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7740 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7742 /* current word is FOR or IN (BOLD in comments below) */
7743 if (cpipe->next == NULL) {
7744 syntax_error("malformed for");
7746 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7749 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7750 if (cpipe->next->res_word == RES_DO)
7752 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7753 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7754 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7756 syntax_error("malformed for");
7758 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7765 /* Past this point, all code paths should jump to ret: label
7766 * in order to return, no direct "return" statements please.
7767 * This helps to ensure that no memory is leaked. */
7775 last_rword = RES_XXXX;
7777 last_followup = PIPE_SEQ;
7778 rcode = G.last_exitcode;
7780 /* Go through list of pipes, (maybe) executing them. */
7781 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7784 if (G_flag_return_in_progress == 1)
7787 IF_HAS_KEYWORDS(rword = pi->res_word;)
7788 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7789 rword, cond_code, last_rword);
7790 #if ENABLE_HUSH_LOOPS
7791 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7792 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7794 /* start of a loop: remember where loop starts */
7799 /* Still in the same "if...", "then..." or "do..." branch? */
7800 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7801 if ((rcode == 0 && last_followup == PIPE_OR)
7802 || (rcode != 0 && last_followup == PIPE_AND)
7804 /* It is "<true> || CMD" or "<false> && CMD"
7805 * and we should not execute CMD */
7806 debug_printf_exec("skipped cmd because of || or &&\n");
7807 last_followup = pi->followup;
7808 goto dont_check_jobs_but_continue;
7811 last_followup = pi->followup;
7812 IF_HAS_KEYWORDS(last_rword = rword;)
7815 if (rword == RES_THEN) {
7816 /* if false; then ... fi has exitcode 0! */
7817 G.last_exitcode = rcode = EXIT_SUCCESS;
7818 /* "if <false> THEN cmd": skip cmd */
7822 if (rword == RES_ELSE || rword == RES_ELIF) {
7823 /* "if <true> then ... ELSE/ELIF cmd":
7824 * skip cmd and all following ones */
7829 #if ENABLE_HUSH_LOOPS
7830 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7832 /* first loop through for */
7834 static const char encoded_dollar_at[] ALIGN1 = {
7835 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7836 }; /* encoded representation of "$@" */
7837 static const char *const encoded_dollar_at_argv[] = {
7838 encoded_dollar_at, NULL
7839 }; /* argv list with one element: "$@" */
7842 vals = (char**)encoded_dollar_at_argv;
7843 if (pi->next->res_word == RES_IN) {
7844 /* if no variable values after "in" we skip "for" */
7845 if (!pi->next->cmds[0].argv) {
7846 G.last_exitcode = rcode = EXIT_SUCCESS;
7847 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7850 vals = pi->next->cmds[0].argv;
7851 } /* else: "for var; do..." -> assume "$@" list */
7852 /* create list of variable values */
7853 debug_print_strings("for_list made from", vals);
7854 for_list = expand_strvec_to_strvec(vals);
7855 for_lcur = for_list;
7856 debug_print_strings("for_list", for_list);
7859 /* "for" loop is over, clean up */
7865 /* Insert next value from for_lcur */
7866 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7867 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7870 if (rword == RES_IN) {
7871 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7873 if (rword == RES_DONE) {
7874 continue; /* "done" has no cmds too */
7877 #if ENABLE_HUSH_CASE
7878 if (rword == RES_CASE) {
7879 debug_printf_exec("CASE cond_code:%d\n", cond_code);
7880 case_word = expand_strvec_to_string(pi->cmds->argv);
7883 if (rword == RES_MATCH) {
7886 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
7887 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7889 /* all prev words didn't match, does this one match? */
7890 argv = pi->cmds->argv;
7892 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7893 /* TODO: which FNM_xxx flags to use? */
7894 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7896 if (cond_code == 0) { /* match! we will execute this branch */
7898 case_word = NULL; /* make future "word)" stop */
7905 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7906 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
7908 continue; /* not matched yet, skip this pipe */
7910 if (rword == RES_ESAC) {
7911 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
7913 /* "case" did not match anything: still set $? (to 0) */
7914 G.last_exitcode = rcode = EXIT_SUCCESS;
7918 /* Just pressing <enter> in shell should check for jobs.
7919 * OTOH, in non-interactive shell this is useless
7920 * and only leads to extra job checks */
7921 if (pi->num_cmds == 0) {
7922 if (G_interactive_fd)
7923 goto check_jobs_and_continue;
7927 /* After analyzing all keywords and conditions, we decided
7928 * to execute this pipe. NB: have to do checkjobs(NULL)
7929 * after run_pipe to collect any background children,
7930 * even if list execution is to be stopped. */
7931 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7934 #if ENABLE_HUSH_LOOPS
7935 G.flag_break_continue = 0;
7937 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7939 /* We ran a builtin, function, or group.
7940 * rcode is already known
7941 * and we don't need to wait for anything. */
7942 G.last_exitcode = rcode;
7943 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7944 check_and_run_traps();
7945 #if ENABLE_HUSH_LOOPS
7946 /* Was it "break" or "continue"? */
7947 if (G.flag_break_continue) {
7948 smallint fbc = G.flag_break_continue;
7949 /* We might fall into outer *loop*,
7950 * don't want to break it too */
7952 G.depth_break_continue--;
7953 if (G.depth_break_continue == 0)
7954 G.flag_break_continue = 0;
7955 /* else: e.g. "continue 2" should *break* once, *then* continue */
7956 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7957 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7958 checkjobs(NULL, 0 /*(no pid to wait for)*/);
7961 /* "continue": simulate end of loop */
7966 if (G_flag_return_in_progress == 1) {
7967 checkjobs(NULL, 0 /*(no pid to wait for)*/);
7970 } else if (pi->followup == PIPE_BG) {
7971 /* What does bash do with attempts to background builtins? */
7972 /* even bash 3.2 doesn't do that well with nested bg:
7973 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7974 * I'm NOT treating inner &'s as jobs */
7975 check_and_run_traps();
7977 if (G.run_list_level == 1)
7980 /* Last command's pid goes to $! */
7981 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7982 G.last_exitcode = rcode = EXIT_SUCCESS;
7983 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7986 if (G.run_list_level == 1 && G_interactive_fd) {
7987 /* Waits for completion, then fg's main shell */
7988 rcode = checkjobs_and_fg_shell(pi);
7989 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7990 check_and_run_traps();
7993 { /* This one just waits for completion */
7994 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
7995 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7996 check_and_run_traps();
7998 G.last_exitcode = rcode;
8002 /* Analyze how result affects subsequent commands */
8004 if (rword == RES_IF || rword == RES_ELIF)
8007 check_jobs_and_continue:
8008 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8009 dont_check_jobs_but_continue: ;
8010 #if ENABLE_HUSH_LOOPS
8011 /* Beware of "while false; true; do ..."! */
8013 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8014 /* check for RES_DONE is needed for "while ...; do \n done" case */
8016 if (rword == RES_WHILE) {
8018 /* "while false; do...done" - exitcode 0 */
8019 G.last_exitcode = rcode = EXIT_SUCCESS;
8020 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8024 if (rword == RES_UNTIL) {
8026 debug_printf_exec(": until expr is true: breaking\n");
8037 #if ENABLE_HUSH_LOOPS
8042 #if ENABLE_HUSH_CASE
8046 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8050 /* Select which version we will use */
8051 static int run_and_free_list(struct pipe *pi)
8054 debug_printf_exec("run_and_free_list entered\n");
8055 if (!G.o_opt[OPT_O_NOEXEC]) {
8056 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8057 rcode = run_list(pi);
8059 /* free_pipe_list has the side effect of clearing memory.
8060 * In the long run that function can be merged with run_list,
8061 * but doing that now would hobble the debugging effort. */
8063 debug_printf_exec("run_and_free_list return %d\n", rcode);
8068 static void install_sighandlers(unsigned mask)
8070 sighandler_t old_handler;
8072 while ((mask >>= 1) != 0) {
8076 old_handler = install_sighandler(sig, pick_sighandler(sig));
8077 /* POSIX allows shell to re-enable SIGCHLD
8078 * even if it was SIG_IGN on entry.
8079 * Therefore we skip IGN check for it:
8083 if (old_handler == SIG_IGN) {
8084 /* oops... restore back to IGN, and record this fact */
8085 install_sighandler(sig, old_handler);
8087 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8089 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8094 /* Called a few times only (or even once if "sh -c") */
8095 static void install_special_sighandlers(void)
8099 /* Which signals are shell-special? */
8100 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8101 if (G_interactive_fd) {
8102 mask |= SPECIAL_INTERACTIVE_SIGS;
8103 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8104 mask |= SPECIAL_JOBSTOP_SIGS;
8106 /* Careful, do not re-install handlers we already installed */
8107 if (G.special_sig_mask != mask) {
8108 unsigned diff = mask & ~G.special_sig_mask;
8109 G.special_sig_mask = mask;
8110 install_sighandlers(diff);
8116 /* Set handlers to restore tty pgrp and exit */
8117 static void install_fatal_sighandlers(void)
8121 /* We will restore tty pgrp on these signals */
8123 + (1 << SIGILL ) * HUSH_DEBUG
8124 + (1 << SIGFPE ) * HUSH_DEBUG
8125 + (1 << SIGBUS ) * HUSH_DEBUG
8126 + (1 << SIGSEGV) * HUSH_DEBUG
8127 + (1 << SIGTRAP) * HUSH_DEBUG
8129 /* bash 3.2 seems to handle these just like 'fatal' ones */
8132 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8133 * if we aren't interactive... but in this case
8134 * we never want to restore pgrp on exit, and this fn is not called
8136 /*+ (1 << SIGHUP )*/
8137 /*+ (1 << SIGTERM)*/
8138 /*+ (1 << SIGINT )*/
8140 G_fatal_sig_mask = mask;
8142 install_sighandlers(mask);
8146 static int set_mode(int state, char mode, const char *o_opt)
8151 G.o_opt[OPT_O_NOEXEC] = state;
8154 IF_HUSH_MODE_X(G_x_mode = state;)
8158 /* "set -+o" without parameter.
8159 * in bash, set -o produces this output:
8163 * We always use the second form.
8165 const char *p = o_opt_strings;
8168 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8174 idx = index_in_strings(o_opt_strings, o_opt);
8176 G.o_opt[idx] = state;
8180 return EXIT_FAILURE;
8182 return EXIT_SUCCESS;
8185 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8186 int hush_main(int argc, char **argv)
8189 OPT_login = (1 << 0),
8193 unsigned builtin_argc;
8195 struct variable *cur_var;
8196 struct variable *shell_ver;
8199 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8200 G.last_exitcode = EXIT_SUCCESS;
8202 #if ENABLE_HUSH_FAST
8203 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8206 G.argv0_for_re_execing = argv[0];
8208 /* Deal with HUSH_VERSION */
8209 shell_ver = xzalloc(sizeof(*shell_ver));
8210 shell_ver->flg_export = 1;
8211 shell_ver->flg_read_only = 1;
8212 /* Code which handles ${var<op>...} needs writable values for all variables,
8213 * therefore we xstrdup: */
8214 shell_ver->varstr = xstrdup(hush_version_str);
8215 /* Create shell local variables from the values
8216 * currently living in the environment */
8217 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8218 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8219 G.top_var = shell_ver;
8220 cur_var = G.top_var;
8223 char *value = strchr(*e, '=');
8224 if (value) { /* paranoia */
8225 cur_var->next = xzalloc(sizeof(*cur_var));
8226 cur_var = cur_var->next;
8227 cur_var->varstr = *e;
8228 cur_var->max_len = strlen(*e);
8229 cur_var->flg_export = 1;
8233 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8234 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8235 putenv(shell_ver->varstr);
8238 set_pwd_var(/*exp:*/ 1);
8240 #if ENABLE_HUSH_BASH_COMPAT
8241 /* Set (but not export) HOSTNAME unless already set */
8242 if (!get_local_var_value("HOSTNAME")) {
8245 set_local_var_from_halves("HOSTNAME", uts.nodename);
8247 /* bash also exports SHLVL and _,
8248 * and sets (but doesn't export) the following variables:
8250 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8251 * BASH_VERSION='3.2.0(1)-release'
8253 * MACHTYPE=i386-pc-linux-gnu
8255 * PPID=<NNNNN> - we also do it elsewhere
8266 * PIPESTATUS=([0]="0")
8267 * HISTFILE=/<xxx>/.bash_history
8271 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8273 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8284 #if ENABLE_FEATURE_EDITING
8285 G.line_input_state = new_line_input_t(FOR_SHELL);
8288 /* Initialize some more globals to non-zero values */
8289 cmdedit_update_prompt();
8291 die_func = restore_ttypgrp_and__exit;
8293 /* Shell is non-interactive at first. We need to call
8294 * install_special_sighandlers() if we are going to execute "sh <script>",
8295 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8296 * If we later decide that we are interactive, we run install_special_sighandlers()
8297 * in order to intercept (more) signals.
8301 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8302 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8305 opt = getopt(argc, argv, "+c:xinsl"
8308 # if ENABLE_HUSH_FUNCTIONS
8318 * sh ... -c 'script'
8319 * sh ... -c 'script' ARG0 [ARG1...]
8320 * On NOMMU, if builtin_argc != 0,
8321 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8322 * "" needs to be replaced with NULL
8323 * and BARGV vector fed to builtin function.
8324 * Note: the form without ARG0 never happens:
8325 * sh ... -c 'builtin' BARGV... ""
8328 G.root_pid = getpid();
8329 G.root_ppid = getppid();
8331 G.global_argv = argv + optind;
8332 G.global_argc = argc - optind;
8334 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8335 const struct built_in_command *x;
8337 install_special_sighandlers();
8338 x = find_builtin(optarg);
8339 if (x) { /* paranoia */
8340 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8341 G.global_argv += builtin_argc;
8342 G.global_argv[-1] = NULL; /* replace "" */
8344 G.last_exitcode = x->b_function(argv + optind - 1);
8348 if (!G.global_argv[0]) {
8349 /* -c 'script' (no params): prevent empty $0 */
8350 G.global_argv--; /* points to argv[i] of 'script' */
8351 G.global_argv[0] = argv[0];
8353 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8354 install_special_sighandlers();
8355 parse_and_run_string(optarg);
8358 /* Well, we cannot just declare interactiveness,
8359 * we have to have some stuff (ctty, etc) */
8360 /* G_interactive_fd++; */
8363 /* "-s" means "read from stdin", but this is how we always
8364 * operate, so simply do nothing here. */
8370 case '<': /* "big heredoc" support */
8371 full_write1_str(optarg);
8374 unsigned long long empty_trap_mask;
8376 G.root_pid = bb_strtou(optarg, &optarg, 16);
8378 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8380 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8382 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8384 builtin_argc = bb_strtou(optarg, &optarg, 16);
8386 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8387 if (empty_trap_mask != 0) {
8389 install_special_sighandlers();
8390 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8391 for (sig = 1; sig < NSIG; sig++) {
8392 if (empty_trap_mask & (1LL << sig)) {
8393 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8394 install_sighandler(sig, SIG_IGN);
8398 # if ENABLE_HUSH_LOOPS
8400 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8406 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8408 # if ENABLE_HUSH_FUNCTIONS
8410 struct function *funcp = new_function(optarg);
8411 /* funcp->name is already set to optarg */
8412 /* funcp->body is set to NULL. It's a special case. */
8413 funcp->body_as_string = argv[optind];
8421 if (set_mode(1, opt, NULL) == 0) /* no error */
8425 fprintf(stderr, "Usage: sh [FILE]...\n"
8426 " or: sh -c command [args]...\n\n");
8432 } /* option parsing loop */
8434 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8435 G.global_argc = argc - (optind - 1);
8436 G.global_argv = argv + (optind - 1);
8437 G.global_argv[0] = argv[0];
8440 G.root_pid = getpid();
8441 G.root_ppid = getppid();
8444 /* If we are login shell... */
8445 if (flags & OPT_login) {
8447 debug_printf("sourcing /etc/profile\n");
8448 input = fopen_for_read("/etc/profile");
8449 if (input != NULL) {
8450 remember_FILE(input);
8451 install_special_sighandlers();
8452 parse_and_run_file(input);
8453 fclose_and_forget(input);
8455 /* bash: after sourcing /etc/profile,
8456 * tries to source (in the given order):
8457 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8458 * stopping on first found. --noprofile turns this off.
8459 * bash also sources ~/.bash_logout on exit.
8460 * If called as sh, skips .bash_XXX files.
8464 if (G.global_argv[1]) {
8467 * "bash <script>" (which is never interactive (unless -i?))
8468 * sources $BASH_ENV here (without scanning $PATH).
8469 * If called as sh, does the same but with $ENV.
8470 * Also NB, per POSIX, $ENV should undergo parameter expansion.
8474 debug_printf("running script '%s'\n", G.global_argv[0]);
8475 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
8476 input = xfopen_for_read(G.global_argv[0]);
8477 xfunc_error_retval = 1;
8478 remember_FILE(input);
8479 install_special_sighandlers();
8480 parse_and_run_file(input);
8481 #if ENABLE_FEATURE_CLEAN_UP
8482 fclose_and_forget(input);
8487 /* Up to here, shell was non-interactive. Now it may become one.
8488 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8491 /* A shell is interactive if the '-i' flag was given,
8492 * or if all of the following conditions are met:
8494 * no arguments remaining or the -s flag given
8495 * standard input is a terminal
8496 * standard output is a terminal
8497 * Refer to Posix.2, the description of the 'sh' utility.
8500 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8501 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8502 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8503 if (G_saved_tty_pgrp < 0)
8504 G_saved_tty_pgrp = 0;
8506 /* try to dup stdin to high fd#, >= 255 */
8507 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8508 if (G_interactive_fd < 0) {
8509 /* try to dup to any fd */
8510 G_interactive_fd = dup(STDIN_FILENO);
8511 if (G_interactive_fd < 0) {
8513 G_interactive_fd = 0;
8514 G_saved_tty_pgrp = 0;
8517 // TODO: track & disallow any attempts of user
8518 // to (inadvertently) close/redirect G_interactive_fd
8520 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8521 if (G_interactive_fd) {
8522 close_on_exec_on(G_interactive_fd);
8524 if (G_saved_tty_pgrp) {
8525 /* If we were run as 'hush &', sleep until we are
8526 * in the foreground (tty pgrp == our pgrp).
8527 * If we get started under a job aware app (like bash),
8528 * make sure we are now in charge so we don't fight over
8529 * who gets the foreground */
8531 pid_t shell_pgrp = getpgrp();
8532 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8533 if (G_saved_tty_pgrp == shell_pgrp)
8535 /* send TTIN to ourself (should stop us) */
8536 kill(- shell_pgrp, SIGTTIN);
8540 /* Install more signal handlers */
8541 install_special_sighandlers();
8543 if (G_saved_tty_pgrp) {
8544 /* Set other signals to restore saved_tty_pgrp */
8545 install_fatal_sighandlers();
8546 /* Put ourselves in our own process group
8547 * (bash, too, does this only if ctty is available) */
8548 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8549 /* Grab control of the terminal */
8550 tcsetpgrp(G_interactive_fd, getpid());
8552 enable_restore_tty_pgrp_on_exit();
8554 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8556 const char *hp = get_local_var_value("HISTFILE");
8558 hp = get_local_var_value("HOME");
8560 hp = concat_path_file(hp, ".hush_history");
8565 G.line_input_state->hist_file = hp;
8566 //set_local_var(xasprintf("HISTFILE=%s", ...));
8568 # if ENABLE_FEATURE_SH_HISTFILESIZE
8569 hp = get_local_var_value("HISTFILESIZE");
8570 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8575 install_special_sighandlers();
8577 #elif ENABLE_HUSH_INTERACTIVE
8578 /* No job control compiled in, only prompt/line editing */
8579 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8580 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8581 if (G_interactive_fd < 0) {
8582 /* try to dup to any fd */
8583 G_interactive_fd = dup(STDIN_FILENO);
8584 if (G_interactive_fd < 0)
8586 G_interactive_fd = 0;
8589 if (G_interactive_fd) {
8590 close_on_exec_on(G_interactive_fd);
8592 install_special_sighandlers();
8594 /* We have interactiveness code disabled */
8595 install_special_sighandlers();
8598 * if interactive but not a login shell, sources ~/.bashrc
8599 * (--norc turns this off, --rcfile <file> overrides)
8602 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8603 /* note: ash and hush share this string */
8604 printf("\n\n%s %s\n"
8605 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8608 "hush - the humble shell"
8612 parse_and_run_file(stdin);
8615 hush_exit(G.last_exitcode);
8620 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8621 int msh_main(int argc, char **argv)
8623 bb_error_msg("msh is deprecated, please use hush instead");
8624 return hush_main(argc, argv);
8632 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8637 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8644 return applet_main_func(argc, argv - argc);
8647 static int FAST_FUNC builtin_test(char **argv)
8649 return run_applet_main(argv, test_main);
8652 static int FAST_FUNC builtin_echo(char **argv)
8654 return run_applet_main(argv, echo_main);
8658 static int FAST_FUNC builtin_printf(char **argv)
8660 return run_applet_main(argv, printf_main);
8664 static char **skip_dash_dash(char **argv)
8667 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8672 static int FAST_FUNC builtin_eval(char **argv)
8674 int rcode = EXIT_SUCCESS;
8676 argv = skip_dash_dash(argv);
8678 char *str = expand_strvec_to_string(argv);
8680 * eval "echo Hi; done" ("done" is syntax error):
8681 * "echo Hi" will not execute too.
8683 parse_and_run_string(str);
8685 rcode = G.last_exitcode;
8690 static int FAST_FUNC builtin_cd(char **argv)
8694 argv = skip_dash_dash(argv);
8696 if (newdir == NULL) {
8697 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8698 * bash says "bash: cd: HOME not set" and does nothing
8701 const char *home = get_local_var_value("HOME");
8702 newdir = home ? home : "/";
8704 if (chdir(newdir)) {
8705 /* Mimic bash message exactly */
8706 bb_perror_msg("cd: %s", newdir);
8707 return EXIT_FAILURE;
8709 /* Read current dir (get_cwd(1) is inside) and set PWD.
8710 * Note: do not enforce exporting. If PWD was unset or unexported,
8711 * set it again, but do not export. bash does the same.
8713 set_pwd_var(/*exp:*/ 0);
8714 return EXIT_SUCCESS;
8717 static int FAST_FUNC builtin_exec(char **argv)
8719 argv = skip_dash_dash(argv);
8720 if (argv[0] == NULL)
8721 return EXIT_SUCCESS; /* bash does this */
8723 /* Careful: we can end up here after [v]fork. Do not restore
8724 * tty pgrp then, only top-level shell process does that */
8725 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8726 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8728 /* TODO: if exec fails, bash does NOT exit! We do.
8729 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8730 * and tcsetpgrp, and this is inherently racy.
8732 execvp_or_die(argv);
8735 static int FAST_FUNC builtin_exit(char **argv)
8737 debug_printf_exec("%s()\n", __func__);
8739 /* interactive bash:
8740 * # trap "echo EEE" EXIT
8743 * There are stopped jobs.
8744 * (if there are _stopped_ jobs, running ones don't count)
8747 * EEE (then bash exits)
8749 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8752 /* note: EXIT trap is run by hush_exit */
8753 argv = skip_dash_dash(argv);
8754 if (argv[0] == NULL)
8755 hush_exit(G.last_exitcode);
8756 /* mimic bash: exit 123abc == exit 255 + error msg */
8757 xfunc_error_retval = 255;
8758 /* bash: exit -2 == exit 254, no error msg */
8759 hush_exit(xatoi(argv[0]) & 0xff);
8762 static void print_escaped(const char *s)
8767 const char *p = strchrnul(s, '\'');
8768 /* print 'xxxx', possibly just '' */
8769 printf("'%.*s'", (int)(p - s), s);
8774 /* s points to '; print "'''...'''" */
8776 do putchar('\''); while (*++s == '\'');
8781 #if !ENABLE_HUSH_LOCAL
8782 #define helper_export_local(argv, exp, lvl) \
8783 helper_export_local(argv, exp)
8785 static void helper_export_local(char **argv, int exp, int lvl)
8789 char *name_end = strchrnul(name, '=');
8791 /* So far we do not check that name is valid (TODO?) */
8793 if (*name_end == '\0') {
8794 struct variable *var, **vpp;
8796 vpp = get_ptr_to_local_var(name, name_end - name);
8797 var = vpp ? *vpp : NULL;
8799 if (exp == -1) { /* unexporting? */
8800 /* export -n NAME (without =VALUE) */
8802 var->flg_export = 0;
8803 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8805 } /* else: export -n NOT_EXISTING_VAR: no-op */
8808 if (exp == 1) { /* exporting? */
8809 /* export NAME (without =VALUE) */
8811 var->flg_export = 1;
8812 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8813 putenv(var->varstr);
8817 #if ENABLE_HUSH_LOCAL
8818 if (exp == 0 /* local? */
8819 && var && var->func_nest_level == lvl
8821 /* "local x=abc; ...; local x" - ignore second local decl */
8825 /* Exporting non-existing variable.
8826 * bash does not put it in environment,
8827 * but remembers that it is exported,
8828 * and does put it in env when it is set later.
8829 * We just set it to "" and export. */
8830 /* Or, it's "local NAME" (without =VALUE).
8831 * bash sets the value to "". */
8832 name = xasprintf("%s=", name);
8834 /* (Un)exporting/making local NAME=VALUE */
8835 name = xstrdup(name);
8837 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8841 static int FAST_FUNC builtin_export(char **argv)
8843 unsigned opt_unexport;
8845 #if ENABLE_HUSH_EXPORT_N
8846 /* "!": do not abort on errors */
8847 opt_unexport = getopt32(argv, "!n");
8848 if (opt_unexport == (uint32_t)-1)
8849 return EXIT_FAILURE;
8856 if (argv[0] == NULL) {
8863 /* ash emits: export VAR='VAL'
8864 * bash: declare -x VAR="VAL"
8865 * we follow ash example */
8866 const char *s = *e++;
8867 const char *p = strchr(s, '=');
8869 if (!p) /* wtf? take next variable */
8872 printf("export %.*s", (int)(p - s) + 1, s);
8873 print_escaped(p + 1);
8877 /*fflush_all(); - done after each builtin anyway */
8879 return EXIT_SUCCESS;
8882 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8884 return EXIT_SUCCESS;
8887 #if ENABLE_HUSH_LOCAL
8888 static int FAST_FUNC builtin_local(char **argv)
8890 if (G.func_nest_level == 0) {
8891 bb_error_msg("%s: not in a function", argv[0]);
8892 return EXIT_FAILURE; /* bash compat */
8894 helper_export_local(argv, 0, G.func_nest_level);
8895 return EXIT_SUCCESS;
8899 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8900 static int FAST_FUNC builtin_unset(char **argv)
8905 /* "!": do not abort on errors */
8906 /* "+": stop at 1st non-option */
8907 opts = getopt32(argv, "!+vf");
8908 if (opts == (unsigned)-1)
8909 return EXIT_FAILURE;
8911 bb_error_msg("unset: -v and -f are exclusive");
8912 return EXIT_FAILURE;
8918 if (!(opts & 2)) { /* not -f */
8919 if (unset_local_var(*argv)) {
8920 /* unset <nonexistent_var> doesn't fail.
8921 * Error is when one tries to unset RO var.
8922 * Message was printed by unset_local_var. */
8926 #if ENABLE_HUSH_FUNCTIONS
8936 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8937 * built-in 'set' handler
8939 * set [-abCefhmnuvx] [-o option] [argument...]
8940 * set [+abCefhmnuvx] [+o option] [argument...]
8941 * set -- [argument...]
8944 * Implementations shall support the options in both their hyphen and
8945 * plus-sign forms. These options can also be specified as options to sh.
8947 * Write out all variables and their values: set
8948 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8949 * Turn on the -x and -v options: set -xv
8950 * Unset all positional parameters: set --
8951 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8952 * Set the positional parameters to the expansion of x, even if x expands
8953 * with a leading '-' or '+': set -- $x
8955 * So far, we only support "set -- [argument...]" and some of the short names.
8957 static int FAST_FUNC builtin_set(char **argv)
8960 char **pp, **g_argv;
8961 char *arg = *++argv;
8965 for (e = G.top_var; e; e = e->next)
8967 return EXIT_SUCCESS;
8971 if (strcmp(arg, "--") == 0) {
8975 if (arg[0] != '+' && arg[0] != '-')
8977 for (n = 1; arg[n]; ++n) {
8978 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8980 if (arg[n] == 'o' && argv[1])
8983 } while ((arg = *++argv) != NULL);
8984 /* Now argv[0] is 1st argument */
8987 return EXIT_SUCCESS;
8990 /* NB: G.global_argv[0] ($0) is never freed/changed */
8991 g_argv = G.global_argv;
8992 if (G.global_args_malloced) {
8998 G.global_args_malloced = 1;
8999 pp = xzalloc(sizeof(pp[0]) * 2);
9000 pp[0] = g_argv[0]; /* retain $0 */
9003 /* This realloc's G.global_argv */
9004 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9011 return EXIT_SUCCESS;
9013 /* Nothing known, so abort */
9015 bb_error_msg("set: %s: invalid option", arg);
9016 return EXIT_FAILURE;
9019 static int FAST_FUNC builtin_shift(char **argv)
9022 argv = skip_dash_dash(argv);
9026 if (n >= 0 && n < G.global_argc) {
9027 if (G.global_args_malloced) {
9030 free(G.global_argv[m++]);
9033 memmove(&G.global_argv[1], &G.global_argv[n+1],
9034 G.global_argc * sizeof(G.global_argv[0]));
9035 return EXIT_SUCCESS;
9037 return EXIT_FAILURE;
9040 /* Interruptibility of read builtin in bash
9041 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9043 * Empty trap makes read ignore corresponding signal, for any signal.
9046 * - terminates non-interactive shell;
9047 * - interrupts read in interactive shell;
9048 * if it has non-empty trap:
9049 * - executes trap and returns to command prompt in interactive shell;
9050 * - executes trap and returns to read in non-interactive shell;
9052 * - is ignored (does not interrupt) read in interactive shell;
9053 * - terminates non-interactive shell;
9054 * if it has non-empty trap:
9055 * - executes trap and returns to read;
9057 * - terminates shell (regardless of interactivity);
9058 * if it has non-empty trap:
9059 * - executes trap and returns to read;
9061 static int FAST_FUNC builtin_read(char **argv)
9071 /* "!": do not abort on errors.
9072 * Option string must start with "sr" to match BUILTIN_READ_xxx
9074 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9075 if (read_flags == (uint32_t)-1)
9076 return EXIT_FAILURE;
9078 ifs = get_local_var_value("IFS"); /* can be NULL */
9081 r = shell_builtin_read(set_local_var_from_halves,
9091 if ((uintptr_t)r == 1 && errno == EINTR) {
9092 unsigned sig = check_and_run_traps();
9093 if (sig && sig != SIGINT)
9097 if ((uintptr_t)r > 1) {
9098 bb_error_msg("%s", r);
9099 r = (char*)(uintptr_t)1;
9102 return (uintptr_t)r;
9105 static int FAST_FUNC builtin_trap(char **argv)
9111 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
9116 /* No args: print all trapped */
9117 for (i = 0; i < NSIG; ++i) {
9120 print_escaped(G.traps[i]);
9121 /* note: bash adds "SIG", but only if invoked
9122 * as "bash". If called as "sh", or if set -o posix,
9123 * then it prints short signal names.
9124 * We are printing short names: */
9125 printf(" %s\n", get_signame(i));
9128 /*fflush_all(); - done after each builtin anyway */
9129 return EXIT_SUCCESS;
9133 /* If first arg is a number: reset all specified signals */
9134 sig = bb_strtou(*argv, NULL, 10);
9140 sighandler_t handler;
9142 sig = get_signum(*argv++);
9143 if (sig < 0 || sig >= NSIG) {
9145 /* Mimic bash message exactly */
9146 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
9151 G.traps[sig] = xstrdup(new_cmd);
9153 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9154 get_signame(sig), sig, G.traps[sig]);
9156 /* There is no signal for 0 (EXIT) */
9161 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9163 /* We are removing trap handler */
9164 handler = pick_sighandler(sig);
9165 install_sighandler(sig, handler);
9170 if (!argv[1]) { /* no second arg */
9171 bb_error_msg("trap: invalid arguments");
9172 return EXIT_FAILURE;
9175 /* First arg is "-": reset all specified to default */
9176 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9177 /* Everything else: set arg as signal handler
9178 * (includes "" case, which ignores signal) */
9179 if (argv[0][0] == '-') {
9180 if (argv[0][1] == '\0') { /* "-" */
9181 /* new_cmd remains NULL: "reset these sigs" */
9184 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9187 /* else: "-something", no special meaning */
9192 goto process_sig_list;
9195 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9196 static int FAST_FUNC builtin_type(char **argv)
9198 int ret = EXIT_SUCCESS;
9204 if (0) {} /* make conditional compile easier below */
9205 /*else if (find_alias(*argv))
9206 type = "an alias";*/
9207 #if ENABLE_HUSH_FUNCTIONS
9208 else if (find_function(*argv))
9209 type = "a function";
9211 else if (find_builtin(*argv))
9212 type = "a shell builtin";
9213 else if ((path = find_in_path(*argv)) != NULL)
9216 bb_error_msg("type: %s: not found", *argv);
9221 printf("%s is %s\n", *argv, type);
9229 /* built-in 'fg' and 'bg' handler */
9230 static int FAST_FUNC builtin_fg_bg(char **argv)
9235 if (!G_interactive_fd)
9236 return EXIT_FAILURE;
9238 /* If they gave us no args, assume they want the last backgrounded task */
9240 for (pi = G.job_list; pi; pi = pi->next) {
9241 if (pi->jobid == G.last_jobid) {
9245 bb_error_msg("%s: no current job", argv[0]);
9246 return EXIT_FAILURE;
9248 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
9249 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
9250 return EXIT_FAILURE;
9252 for (pi = G.job_list; pi; pi = pi->next) {
9253 if (pi->jobid == jobnum) {
9257 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
9258 return EXIT_FAILURE;
9260 /* TODO: bash prints a string representation
9261 * of job being foregrounded (like "sleep 1 | cat") */
9262 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
9263 /* Put the job into the foreground. */
9264 tcsetpgrp(G_interactive_fd, pi->pgrp);
9267 /* Restart the processes in the job */
9268 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9269 for (i = 0; i < pi->num_cmds; i++) {
9270 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
9272 pi->stopped_cmds = 0;
9274 i = kill(- pi->pgrp, SIGCONT);
9276 if (errno == ESRCH) {
9277 delete_finished_bg_job(pi);
9278 return EXIT_SUCCESS;
9280 bb_perror_msg("kill (SIGCONT)");
9283 if (argv[0][0] == 'f') {
9285 return checkjobs_and_fg_shell(pi);
9287 return EXIT_SUCCESS;
9291 #if ENABLE_HUSH_HELP
9292 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9294 const struct built_in_command *x;
9297 "Built-in commands:\n"
9298 "------------------\n");
9299 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9301 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9303 return EXIT_SUCCESS;
9307 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9308 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9310 show_history(G.line_input_state);
9311 return EXIT_SUCCESS;
9316 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9319 const char *status_string;
9321 for (job = G.job_list; job; job = job->next) {
9322 if (job->alive_cmds == job->stopped_cmds)
9323 status_string = "Stopped";
9325 status_string = "Running";
9327 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9329 return EXIT_SUCCESS;
9334 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
9339 # ifdef M_TRIM_THRESHOLD
9340 /* Optional. Reduces probability of false positives */
9343 /* Crude attempt to find where "free memory" starts,
9344 * sans fragmentation. */
9346 l = (unsigned long)p;
9349 if (l < (unsigned long)p) l = (unsigned long)p;
9355 struct mallinfo mi = mallinfo();
9356 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9357 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9361 if (!G.memleak_value)
9362 G.memleak_value = l;
9364 l -= G.memleak_value;
9371 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9376 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9379 return EXIT_SUCCESS;
9382 static int FAST_FUNC builtin_source(char **argv)
9384 char *arg_path, *filename;
9387 #if ENABLE_HUSH_FUNCTIONS
9391 argv = skip_dash_dash(argv);
9394 /* bash says: "bash: .: filename argument required" */
9395 return 2; /* bash compat */
9398 if (!strchr(filename, '/')) {
9399 arg_path = find_in_path(filename);
9401 filename = arg_path;
9403 input = remember_FILE(fopen_or_warn(filename, "r"));
9406 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9407 /* POSIX: non-interactive shell should abort here,
9408 * not merely fail. So far no one complained :)
9410 return EXIT_FAILURE;
9413 #if ENABLE_HUSH_FUNCTIONS
9414 sv_flg = G_flag_return_in_progress;
9415 /* "we are inside sourced file, ok to use return" */
9416 G_flag_return_in_progress = -1;
9419 save_and_replace_G_args(&sv, argv);
9421 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9422 G.last_exitcode = 0;
9423 parse_and_run_file(input);
9424 fclose_and_forget(input);
9427 restore_G_args(&sv, argv);
9428 #if ENABLE_HUSH_FUNCTIONS
9429 G_flag_return_in_progress = sv_flg;
9432 return G.last_exitcode;
9435 static int FAST_FUNC builtin_umask(char **argv)
9442 argv = skip_dash_dash(argv);
9444 mode_t old_mask = mask;
9446 /* numeric umasks are taken as-is */
9447 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9448 if (!isdigit(argv[0][0]))
9450 mask = bb_parse_mode(argv[0], mask);
9451 if (!isdigit(argv[0][0]))
9453 if ((unsigned)mask > 0777) {
9456 * bash: umask: 'q': invalid symbolic mode operator
9457 * bash: umask: 999: octal number out of range
9459 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9464 printf("%04o\n", (unsigned) mask);
9465 /* fall through and restore mask which we set to 0 */
9469 return !rc; /* rc != 0 - success */
9472 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9473 static int wait_for_child_or_signal(pid_t waitfor_pid)
9478 sigset_t oldset, allsigs;
9480 /* waitpid is not interruptible by SA_RESTARTed
9481 * signals which we use. Thus, this ugly dance:
9484 /* Make sure possible SIGCHLD is stored in kernel's
9485 * pending signal mask before we call waitpid.
9486 * Or else we may race with SIGCHLD, lose it,
9487 * and get stuck in sigwaitinfo...
9489 sigfillset(&allsigs);
9490 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9492 if (!sigisemptyset(&G.pending_set)) {
9493 /* Crap! we raced with some signal! */
9498 /*errno = 0; - checkjobs does this */
9499 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
9500 /* if ECHILD, there are no children (ret is -1 or 0) */
9501 /* if ret == 0, no children changed state */
9502 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
9503 if (errno == ECHILD || ret--) {
9504 if (ret < 0) /* if ECHILD, may need to fix */
9506 sigprocmask(SIG_SETMASK, &oldset, NULL);
9510 /* Wait for SIGCHLD or any other signal */
9511 //sig = sigwaitinfo(&allsigs, NULL);
9512 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9513 /* Note: sigsuspend invokes signal handler */
9514 sigsuspend(&oldset);
9516 sigprocmask(SIG_SETMASK, &oldset, NULL);
9518 /* So, did we get a signal? */
9520 // raise(sig); /* run handler */
9521 sig = check_and_run_traps();
9522 if (sig /*&& sig != SIGCHLD - always true */) {
9527 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9532 static int FAST_FUNC builtin_wait(char **argv)
9537 argv = skip_dash_dash(argv);
9538 if (argv[0] == NULL) {
9539 /* Don't care about wait results */
9540 /* Note 1: must wait until there are no more children */
9541 /* Note 2: must be interruptible */
9543 * $ sleep 3 & sleep 6 & wait
9548 * $ sleep 3 & sleep 6 & wait
9552 * ^C <-- after ~4 sec from keyboard
9555 return wait_for_child_or_signal(0 /*(no pid to wait for)*/);
9558 /* TODO: support "wait %jobspec" */
9560 pid_t pid = bb_strtou(*argv, NULL, 10);
9561 if (errno || pid <= 0) {
9562 /* mimic bash message */
9563 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9565 continue; /* bash checks all argv[] */
9567 /* Do we have such child? */
9568 ret = waitpid(pid, &status, WNOHANG);
9571 if (errno == ECHILD) {
9572 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9573 /* "wait $!" but last bg task has already exited. Try:
9574 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9575 * In bash it prints exitcode 0, then 3.
9577 ret = 0; /* FIXME */
9580 /* Example: "wait 1". mimic bash message */
9581 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
9584 bb_perror_msg("wait %s", *argv);
9587 continue; /* bash checks all argv[] */
9590 /* Yes, and it still runs */
9591 ret = wait_for_child_or_signal(pid);
9593 /* Yes, and it just exited */
9594 process_wait_result(NULL, pid, status);
9595 ret = WEXITSTATUS(status);
9596 if (WIFSIGNALED(status))
9597 ret = 128 + WTERMSIG(status);
9604 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9605 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9608 def = bb_strtou(argv[1], NULL, 10);
9609 if (errno || def < def_min || argv[2]) {
9610 bb_error_msg("%s: bad arguments", argv[0]);
9618 #if ENABLE_HUSH_LOOPS
9619 static int FAST_FUNC builtin_break(char **argv)
9622 if (G.depth_of_loop == 0) {
9623 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9624 /* if we came from builtin_continue(), need to undo "= 1" */
9625 G.flag_break_continue = 0;
9626 return EXIT_SUCCESS; /* bash compat */
9628 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9630 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9631 if (depth == UINT_MAX)
9632 G.flag_break_continue = BC_BREAK;
9633 if (G.depth_of_loop < depth)
9634 G.depth_break_continue = G.depth_of_loop;
9636 return EXIT_SUCCESS;
9639 static int FAST_FUNC builtin_continue(char **argv)
9641 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9642 return builtin_break(argv);
9646 #if ENABLE_HUSH_FUNCTIONS
9647 static int FAST_FUNC builtin_return(char **argv)
9651 if (G_flag_return_in_progress != -1) {
9652 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9653 return EXIT_FAILURE; /* bash compat */
9656 G_flag_return_in_progress = 1;
9659 * out of range: wraps around at 256, does not error out
9660 * non-numeric param:
9661 * f() { false; return qwe; }; f; echo $?
9662 * bash: return: qwe: numeric argument required <== we do this
9663 * 255 <== we also do this
9665 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);