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 * make complex ${var%...} constructs support optional
45 * make here documents optional
46 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
50 * builtins mandated by standards we don't support:
51 * [un]alias, command, fc, getopts:
52 * command -v CMD: print "/path/to/CMD"
53 * prints "CMD" for builtins
54 * prints "alias ALIAS='EXPANSION'" for aliases
55 * prints nothing and sets $? to 1 if not found
56 * command -V CMD: print "CMD is /path/CMD|a shell builtin|etc"
57 * command [-p] CMD: run CMD, even if a function CMD also exists
58 * (can use this to override standalone shell as well)
59 * -p: use default $PATH
60 * command BLTIN: disables special-ness (e.g. errors do not abort)
61 * getopts: getopt() for shells
62 * fc -l[nr] [BEG] [END]: list range of commands in history
63 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
64 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
67 * redirection of stdout+stderr: &> and >&
68 * reserved words: function select
69 * advanced test: [[ ]]
70 * process substitution: <(list) and >(list)
73 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
74 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
75 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
77 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
78 * This is exactly equivalent to let "EXPR".
79 * $[EXPR]: synonym for $((EXPR))
80 * indirect expansion: ${!VAR}
81 * substring op on @: ${@:n:m}
84 * Some builtins mandated by standards:
85 * newgrp [GRP]: not a builtin in bash but a suid binary
86 * which spawns a new shell with new group ID
87 * In bash, export builtin is special, its arguments are assignments
88 * and therefore expansion of them should be "one-word" expansion:
89 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
91 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
92 * ls: cannot access i=a: No such file or directory
93 * ls: cannot access b: No such file or directory
94 * Note1: same applies to local builtin.
95 * Note2: bash 3.2.33(1) does this only if export word itself
97 * $ export i=`echo 'aaa bbb'`; echo "$i"
99 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
103 //config: bool "hush (64 kb)"
106 //config: hush is a small shell. It handles the normal flow control
107 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
108 //config: case/esac. Redirections, here documents, $((arithmetic))
109 //config: and functions are supported.
111 //config: It will compile and work on no-mmu systems.
113 //config: It does not handle select, aliases, tilde expansion,
114 //config: &>file and >&file redirection of stdout+stderr.
116 //config:config HUSH_BASH_COMPAT
117 //config: bool "bash-compatible extensions"
119 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
121 //config:config HUSH_BRACE_EXPANSION
122 //config: bool "Brace expansion"
124 //config: depends on HUSH_BASH_COMPAT
126 //config: Enable {abc,def} extension.
128 //config:config HUSH_INTERACTIVE
129 //config: bool "Interactive mode"
131 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
133 //config: Enable interactive mode (prompt and command editing).
134 //config: Without this, hush simply reads and executes commands
135 //config: from stdin just like a shell script from a file.
136 //config: No prompt, no PS1/PS2 magic shell variables.
138 //config:config HUSH_SAVEHISTORY
139 //config: bool "Save command history to .hush_history"
141 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
143 //config:config HUSH_JOB
144 //config: bool "Job control"
146 //config: depends on HUSH_INTERACTIVE
148 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
149 //config: command (not entire shell), fg/bg builtins work. Without this option,
150 //config: "cmd &" still works by simply spawning a process and immediately
151 //config: prompting for next command (or executing next command in a script),
152 //config: but no separate process group is formed.
154 //config:config HUSH_TICK
155 //config: bool "Support process substitution"
157 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
159 //config: Enable `command` and $(command).
161 //config:config HUSH_IF
162 //config: bool "Support if/then/elif/else/fi"
164 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
166 //config:config HUSH_LOOPS
167 //config: bool "Support for, while and until loops"
169 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
171 //config:config HUSH_CASE
172 //config: bool "Support case ... esac statement"
174 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
176 //config: Enable case ... esac statement. +400 bytes.
178 //config:config HUSH_FUNCTIONS
179 //config: bool "Support funcname() { commands; } syntax"
181 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
183 //config: Enable support for shell functions. +800 bytes.
185 //config:config HUSH_LOCAL
186 //config: bool "local builtin"
188 //config: depends on HUSH_FUNCTIONS
190 //config: Enable support for local variables in functions.
192 //config:config HUSH_RANDOM_SUPPORT
193 //config: bool "Pseudorandom generator and $RANDOM variable"
195 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
197 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
198 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
200 //config:config HUSH_MODE_X
201 //config: bool "Support 'hush -x' option and 'set -x' command"
203 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
205 //config: This instructs hush to print commands before execution.
206 //config: Adds ~300 bytes.
208 //config:config HUSH_ECHO
209 //config: bool "echo builtin"
211 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
213 //config:config HUSH_PRINTF
214 //config: bool "printf builtin"
216 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
218 //config:config HUSH_TEST
219 //config: bool "test builtin"
221 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
223 //config:config HUSH_HELP
224 //config: bool "help builtin"
226 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
228 //config:config HUSH_EXPORT
229 //config: bool "export builtin"
231 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
233 //config:config HUSH_EXPORT_N
234 //config: bool "Support 'export -n' option"
236 //config: depends on HUSH_EXPORT
238 //config: export -n unexports variables. It is a bash extension.
240 //config:config HUSH_READONLY
241 //config: bool "readonly builtin"
243 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
245 //config: Enable support for read-only variables.
247 //config:config HUSH_KILL
248 //config: bool "kill builtin (supports kill %jobspec)"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config:config HUSH_WAIT
253 //config: bool "wait builtin"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_TRAP
258 //config: bool "trap builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_TYPE
263 //config: bool "type builtin"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
267 //config:config HUSH_TIMES
268 //config: bool "times builtin"
270 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272 //config:config HUSH_READ
273 //config: bool "read builtin"
275 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
277 //config:config HUSH_SET
278 //config: bool "set builtin"
280 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
282 //config:config HUSH_UNSET
283 //config: bool "unset builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config:config HUSH_ULIMIT
288 //config: bool "ulimit builtin"
290 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
292 //config:config HUSH_UMASK
293 //config: bool "umask builtin"
295 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
297 //config:config HUSH_MEMLEAK
298 //config: bool "memleak builtin (debugging)"
300 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
302 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
303 // APPLET_ODDNAME:name main location suid_type help
304 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
305 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
307 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
308 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
309 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
310 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
312 /* -i (interactive) and -s (read stdin) are also accepted,
313 * but currently do nothing, therefore aren't shown in help.
314 * NOMMU-specific options are not meant to be used by users,
315 * therefore we don't show them either.
317 //usage:#define hush_trivial_usage
318 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
319 //usage:#define hush_full_usage "\n\n"
320 //usage: "Unix shell interpreter"
322 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
323 || defined(__APPLE__) \
325 # include <malloc.h> /* for malloc_trim */
328 /* #include <dmalloc.h> */
330 # include <fnmatch.h>
332 #include <sys/times.h>
333 #include <sys/utsname.h> /* for setting $HOSTNAME */
335 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
337 #include "shell_common.h"
340 #if ENABLE_HUSH_RANDOM_SUPPORT
343 # define CLEAR_RANDOM_T(rnd) ((void)0)
345 #ifndef F_DUPFD_CLOEXEC
346 # define F_DUPFD_CLOEXEC F_DUPFD
349 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
353 /* So far, all bash compat is controlled by one config option */
354 /* Separate defines document which part of code implements what */
355 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
356 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
357 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
358 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
359 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
360 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
364 #define LEAK_HUNTING 0
365 #define BUILD_AS_NOMMU 0
366 /* Enable/disable sanity checks. Ok to enable in production,
367 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
368 * Keeping 1 for now even in released versions.
371 /* Slightly bigger (+200 bytes), but faster hush.
372 * So far it only enables a trick with counting SIGCHLDs and forks,
373 * which allows us to do fewer waitpid's.
374 * (we can detect a case where neither forks were done nor SIGCHLDs happened
375 * and therefore waitpid will return the same result as last time)
377 #define ENABLE_HUSH_FAST 0
378 /* TODO: implement simplified code for users which do not need ${var%...} ops
379 * So far ${var%...} ops are always enabled:
381 #define ENABLE_HUSH_DOLLAR_OPS 1
386 # undef USE_FOR_NOMMU
389 # define USE_FOR_NOMMU(...) __VA_ARGS__
390 # define USE_FOR_MMU(...)
393 #include "NUM_APPLETS.h"
395 /* STANDALONE does not make sense, and won't compile */
396 # undef CONFIG_FEATURE_SH_STANDALONE
397 # undef ENABLE_FEATURE_SH_STANDALONE
398 # undef IF_FEATURE_SH_STANDALONE
399 # undef IF_NOT_FEATURE_SH_STANDALONE
400 # define ENABLE_FEATURE_SH_STANDALONE 0
401 # define IF_FEATURE_SH_STANDALONE(...)
402 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
405 #if !ENABLE_HUSH_INTERACTIVE
406 # undef ENABLE_FEATURE_EDITING
407 # define ENABLE_FEATURE_EDITING 0
408 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
409 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
410 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
411 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
414 /* Do we support ANY keywords? */
415 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
416 # define HAS_KEYWORDS 1
417 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
418 # define IF_HAS_NO_KEYWORDS(...)
420 # define HAS_KEYWORDS 0
421 # define IF_HAS_KEYWORDS(...)
422 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
425 /* If you comment out one of these below, it will be #defined later
426 * to perform debug printfs to stderr: */
427 #define debug_printf(...) do {} while (0)
428 /* Finer-grained debug switches */
429 #define debug_printf_parse(...) do {} while (0)
430 #define debug_print_tree(a, b) do {} while (0)
431 #define debug_printf_exec(...) do {} while (0)
432 #define debug_printf_env(...) do {} while (0)
433 #define debug_printf_jobs(...) do {} while (0)
434 #define debug_printf_expand(...) do {} while (0)
435 #define debug_printf_varexp(...) do {} while (0)
436 #define debug_printf_glob(...) do {} while (0)
437 #define debug_printf_redir(...) do {} while (0)
438 #define debug_printf_list(...) do {} while (0)
439 #define debug_printf_subst(...) do {} while (0)
440 #define debug_printf_clean(...) do {} while (0)
442 #define ERR_PTR ((void*)(long)1)
444 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
446 #define _SPECIAL_VARS_STR "_*@$!?#"
447 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
448 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
449 #if BASH_PATTERN_SUBST
450 /* Support / and // replace ops */
451 /* Note that // is stored as \ in "encoded" string representation */
452 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
453 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
454 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
456 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
457 # define VAR_SUBST_OPS "%#:-=+?"
458 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
461 #define SPECIAL_VAR_SYMBOL 3
465 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
467 /* This supports saving pointers malloced in vfork child,
468 * to be freed in the parent.
471 typedef struct nommu_save_t {
473 struct variable *old_vars;
475 char **argv_from_re_execing;
488 #if ENABLE_HUSH_LOOPS
495 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
500 /* three pseudo-keywords support contrived "case" syntax: */
501 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
502 RES_MATCH , /* "word)" */
503 RES_CASE_BODY, /* "this command is inside CASE" */
510 typedef struct o_string {
512 int length; /* position where data is appended */
515 /* At least some part of the string was inside '' or "",
516 * possibly empty one: word"", wo''rd etc. */
517 smallint has_quoted_part;
518 smallint has_empty_slot;
519 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
522 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
524 /* Protect newly added chars against globbing
525 * by prepending \ to *, ?, [, \ */
526 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
529 MAYBE_ASSIGNMENT = 0,
530 DEFINITELY_ASSIGNMENT = 1,
532 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
535 /* Used for initialization: o_string foo = NULL_O_STRING; */
536 #define NULL_O_STRING { NULL }
538 #ifndef debug_printf_parse
539 static const char *const assignment_flag[] = {
541 "DEFINITELY_ASSIGNMENT",
547 typedef struct in_str {
549 #if ENABLE_HUSH_INTERACTIVE
550 smallint promptmode; /* 0: PS1, 1: PS2 */
557 /* The descrip member of this structure is only used to make
558 * debugging output pretty */
559 static const struct {
561 signed char default_fd;
564 { O_RDONLY, 0, "<" },
565 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
566 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
567 { O_CREAT|O_RDWR, 1, "<>" },
568 { O_RDONLY, 0, "<<" },
569 /* Should not be needed. Bogus default_fd helps in debugging */
570 /* { O_RDONLY, 77, "<<" }, */
573 struct redir_struct {
574 struct redir_struct *next;
575 char *rd_filename; /* filename */
576 int rd_fd; /* fd to redirect */
577 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
579 smallint rd_type; /* (enum redir_type) */
580 /* note: for heredocs, rd_filename contains heredoc delimiter,
581 * and subsequently heredoc itself; and rd_dup is a bitmask:
582 * bit 0: do we need to trim leading tabs?
583 * bit 1: is heredoc quoted (<<'delim' syntax) ?
586 typedef enum redir_type {
588 REDIRECT_OVERWRITE = 1,
591 REDIRECT_HEREDOC = 4,
592 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
595 REDIRFD_SYNTAX_ERR = -2,
596 REDIRFD_TO_FILE = -1,
597 /* otherwise, rd_fd is redirected to rd_dup */
599 HEREDOC_SKIPTABS = 1,
605 pid_t pid; /* 0 if exited */
606 int assignment_cnt; /* how many argv[i] are assignments? */
607 smallint cmd_type; /* CMD_xxx */
609 #define CMD_SUBSHELL 1
611 /* used for "[[ EXPR ]]" */
612 # define CMD_SINGLEWORD_NOGLOB 2
614 #if ENABLE_HUSH_FUNCTIONS
615 # define CMD_FUNCDEF 3
618 smalluint cmd_exitcode;
619 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
622 char *group_as_string;
624 #if ENABLE_HUSH_FUNCTIONS
625 struct function *child_func;
626 /* This field is used to prevent a bug here:
627 * while...do f1() {a;}; f1; f1() {b;}; f1; done
628 * When we execute "f1() {a;}" cmd, we create new function and clear
629 * cmd->group, cmd->group_as_string, cmd->argv[0].
630 * When we execute "f1() {b;}", we notice that f1 exists,
631 * and that its "parent cmd" struct is still "alive",
632 * we put those fields back into cmd->xxx
633 * (struct function has ->parent_cmd ptr to facilitate that).
634 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
635 * Without this trick, loop would execute a;b;b;b;...
636 * instead of correct sequence a;b;a;b;...
637 * When command is freed, it severs the link
638 * (sets ->child_func->parent_cmd to NULL).
641 char **argv; /* command name and arguments */
642 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
643 * and on execution these are substituted with their values.
644 * Substitution can make _several_ words out of one argv[n]!
645 * Example: argv[0]=='.^C*^C.' here: echo .$*.
646 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
648 struct redir_struct *redirects; /* I/O redirections */
650 /* Is there anything in this command at all? */
651 #define IS_NULL_CMD(cmd) \
652 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
656 int num_cmds; /* total number of commands in pipe */
657 int alive_cmds; /* number of commands running (not exited) */
658 int stopped_cmds; /* number of commands alive, but stopped */
660 unsigned jobid; /* job number */
661 pid_t pgrp; /* process group ID for the job */
662 char *cmdtext; /* name of job */
664 struct command *cmds; /* array of commands in pipe */
665 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
666 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
667 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
669 typedef enum pipe_style {
675 /* Is there anything in this pipe at all? */
676 #define IS_NULL_PIPE(pi) \
677 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
679 /* This holds pointers to the various results of parsing */
680 struct parse_context {
681 /* linked list of pipes */
682 struct pipe *list_head;
683 /* last pipe (being constructed right now) */
685 /* last command in pipe (being constructed right now) */
686 struct command *command;
687 /* last redirect in command->redirects list */
688 struct redir_struct *pending_redirect;
694 smallint ctx_inverted; /* "! cmd | cmd" */
696 smallint ctx_dsemicolon; /* ";;" seen */
698 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
700 /* group we are enclosed in:
701 * example: "if pipe1; pipe2; then pipe3; fi"
702 * when we see "if" or "then", we malloc and copy current context,
703 * and make ->stack point to it. then we parse pipeN.
704 * when closing "then" / fi" / whatever is found,
705 * we move list_head into ->stack->command->group,
706 * copy ->stack into current context, and delete ->stack.
707 * (parsing of { list } and ( list ) doesn't use this method)
709 struct parse_context *stack;
713 /* On program start, environ points to initial environment.
714 * putenv adds new pointers into it, unsetenv removes them.
715 * Neither of these (de)allocates the strings.
716 * setenv allocates new strings in malloc space and does putenv,
717 * and thus setenv is unusable (leaky) for shell's purposes */
718 #define setenv(...) setenv_is_leaky_dont_use()
720 struct variable *next;
721 char *varstr; /* points to "name=" portion */
722 #if ENABLE_HUSH_LOCAL
723 unsigned func_nest_level;
725 int max_len; /* if > 0, name is part of initial env; else name is malloced */
726 smallint flg_export; /* putenv should be done on this var */
727 smallint flg_read_only;
735 #if ENABLE_HUSH_FUNCTIONS
737 struct function *next;
739 struct command *parent_cmd;
742 char *body_as_string;
748 /* set -/+o OPT support. (TODO: make it optional)
749 * bash supports the following opts:
760 * interactive-comments on
778 static const char o_opt_strings[] ALIGN1 =
782 #if ENABLE_HUSH_MODE_X
790 #if ENABLE_HUSH_MODE_X
798 struct FILE_list *next;
804 /* "Globals" within this file */
805 /* Sorted roughly by size (smaller offsets == smaller code) */
807 /* interactive_fd != 0 means we are an interactive shell.
808 * If we are, then saved_tty_pgrp can also be != 0, meaning
809 * that controlling tty is available. With saved_tty_pgrp == 0,
810 * job control still works, but terminal signals
811 * (^C, ^Z, ^Y, ^\) won't work at all, and background
812 * process groups can only be created with "cmd &".
813 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
814 * to give tty to the foreground process group,
815 * and will take it back when the group is stopped (^Z)
818 #if ENABLE_HUSH_INTERACTIVE
819 /* 'interactive_fd' is a fd# open to ctty, if we have one
820 * _AND_ if we decided to act interactively */
824 # define G_interactive_fd (G.interactive_fd)
826 # define G_interactive_fd 0
828 #if ENABLE_FEATURE_EDITING
829 line_input_t *line_input_state;
834 #if ENABLE_HUSH_RANDOM_SUPPORT
840 pid_t saved_tty_pgrp;
841 struct pipe *job_list;
842 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
844 # define G_saved_tty_pgrp 0
846 /* How deeply are we in context where "set -e" is ignored */
848 /* "set -e" rules (do we follow them correctly?):
849 * Exit if pipe, list, or compound command exits with a non-zero status.
850 * Shell does not exit if failed command is part of condition in
851 * if/while, part of && or || list except the last command, any command
852 * in a pipe but the last, or if the command's return value is being
853 * inverted with !. If a compound command other than a subshell returns a
854 * non-zero status because a command failed while -e was being ignored, the
855 * shell does not exit. A trap on ERR, if set, is executed before the shell
856 * exits [ERR is a bashism].
858 * If a compound command or function executes in a context where -e is
859 * ignored, none of the commands executed within are affected by the -e
860 * setting. If a compound command or function sets -e while executing in a
861 * context where -e is ignored, that setting does not have any effect until
862 * the compound command or the command containing the function call completes.
865 char o_opt[NUM_OPT_O];
866 #if ENABLE_HUSH_MODE_X
867 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
871 smallint flag_SIGINT;
872 #if ENABLE_HUSH_LOOPS
873 smallint flag_break_continue;
875 #if ENABLE_HUSH_FUNCTIONS
876 /* 0: outside of a function (or sourced file)
877 * -1: inside of a function, ok to use return builtin
878 * 1: return is invoked, skip all till end of func
880 smallint flag_return_in_progress;
881 # define G_flag_return_in_progress (G.flag_return_in_progress)
883 # define G_flag_return_in_progress 0
885 smallint exiting; /* used to prevent EXIT trap recursion */
886 /* These four support $?, $#, and $1 */
887 smalluint last_exitcode;
888 smalluint last_bg_pid_exitcode;
890 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
891 smalluint global_args_malloced;
892 # define G_global_args_malloced (G.global_args_malloced)
894 # define G_global_args_malloced 0
896 /* how many non-NULL argv's we have. NB: $# + 1 */
900 char *argv0_for_re_execing;
902 #if ENABLE_HUSH_LOOPS
903 unsigned depth_break_continue;
904 unsigned depth_of_loop;
908 struct variable *top_var;
909 char **expanded_assignments;
910 #if ENABLE_HUSH_FUNCTIONS
911 struct function *top_func;
912 # if ENABLE_HUSH_LOCAL
913 struct variable **shadowed_vars_pp;
914 unsigned func_nest_level;
917 /* Signal and trap handling */
919 unsigned count_SIGCHLD;
920 unsigned handled_SIGCHLD;
921 smallint we_have_children;
923 struct FILE_list *FILE_list;
924 /* Which signals have non-DFL handler (even with no traps set)?
925 * Set at the start to:
926 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
927 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
928 * The rest is cleared right before execv syscalls.
929 * Other than these two times, never modified.
931 unsigned special_sig_mask;
933 unsigned fatal_sig_mask;
934 # define G_fatal_sig_mask (G.fatal_sig_mask)
936 # define G_fatal_sig_mask 0
939 char **traps; /* char *traps[NSIG] */
940 # define G_traps G.traps
942 # define G_traps ((char**)NULL)
944 sigset_t pending_set;
945 #if ENABLE_HUSH_MEMLEAK
946 unsigned long memleak_value;
952 #if ENABLE_FEATURE_EDITING
953 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
956 #define G (*ptr_to_globals)
957 /* Not #defining name to G.name - this quickly gets unwieldy
958 * (too many defines). Also, I actually prefer to see when a variable
959 * is global, thus "G." prefix is a useful hint */
960 #define INIT_G() do { \
961 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
962 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
963 sigfillset(&G.sa.sa_mask); \
964 G.sa.sa_flags = SA_RESTART; \
968 /* Function prototypes for builtins */
969 static int builtin_cd(char **argv) FAST_FUNC;
971 static int builtin_echo(char **argv) FAST_FUNC;
973 static int builtin_eval(char **argv) FAST_FUNC;
974 static int builtin_exec(char **argv) FAST_FUNC;
975 static int builtin_exit(char **argv) FAST_FUNC;
976 #if ENABLE_HUSH_EXPORT
977 static int builtin_export(char **argv) FAST_FUNC;
979 #if ENABLE_HUSH_READONLY
980 static int builtin_readonly(char **argv) FAST_FUNC;
983 static int builtin_fg_bg(char **argv) FAST_FUNC;
984 static int builtin_jobs(char **argv) FAST_FUNC;
987 static int builtin_help(char **argv) FAST_FUNC;
989 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
990 static int builtin_history(char **argv) FAST_FUNC;
992 #if ENABLE_HUSH_LOCAL
993 static int builtin_local(char **argv) FAST_FUNC;
995 #if ENABLE_HUSH_MEMLEAK
996 static int builtin_memleak(char **argv) FAST_FUNC;
998 #if ENABLE_HUSH_PRINTF
999 static int builtin_printf(char **argv) FAST_FUNC;
1001 static int builtin_pwd(char **argv) FAST_FUNC;
1002 #if ENABLE_HUSH_READ
1003 static int builtin_read(char **argv) FAST_FUNC;
1006 static int builtin_set(char **argv) FAST_FUNC;
1008 static int builtin_shift(char **argv) FAST_FUNC;
1009 static int builtin_source(char **argv) FAST_FUNC;
1010 #if ENABLE_HUSH_TEST || BASH_TEST2
1011 static int builtin_test(char **argv) FAST_FUNC;
1013 #if ENABLE_HUSH_TRAP
1014 static int builtin_trap(char **argv) FAST_FUNC;
1016 #if ENABLE_HUSH_TYPE
1017 static int builtin_type(char **argv) FAST_FUNC;
1019 #if ENABLE_HUSH_TIMES
1020 static int builtin_times(char **argv) FAST_FUNC;
1022 static int builtin_true(char **argv) FAST_FUNC;
1023 #if ENABLE_HUSH_UMASK
1024 static int builtin_umask(char **argv) FAST_FUNC;
1026 #if ENABLE_HUSH_UNSET
1027 static int builtin_unset(char **argv) FAST_FUNC;
1029 #if ENABLE_HUSH_KILL
1030 static int builtin_kill(char **argv) FAST_FUNC;
1032 #if ENABLE_HUSH_WAIT
1033 static int builtin_wait(char **argv) FAST_FUNC;
1035 #if ENABLE_HUSH_LOOPS
1036 static int builtin_break(char **argv) FAST_FUNC;
1037 static int builtin_continue(char **argv) FAST_FUNC;
1039 #if ENABLE_HUSH_FUNCTIONS
1040 static int builtin_return(char **argv) FAST_FUNC;
1043 /* Table of built-in functions. They can be forked or not, depending on
1044 * context: within pipes, they fork. As simple commands, they do not.
1045 * When used in non-forking context, they can change global variables
1046 * in the parent shell process. If forked, of course they cannot.
1047 * For example, 'unset foo | whatever' will parse and run, but foo will
1048 * still be set at the end. */
1049 struct built_in_command {
1051 int (*b_function)(char **argv) FAST_FUNC;
1052 #if ENABLE_HUSH_HELP
1053 const char *b_descr;
1054 # define BLTIN(cmd, func, help) { cmd, func, help }
1056 # define BLTIN(cmd, func, help) { cmd, func }
1060 static const struct built_in_command bltins1[] = {
1061 BLTIN("." , builtin_source , "Run commands in file"),
1062 BLTIN(":" , builtin_true , NULL),
1064 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1066 #if ENABLE_HUSH_LOOPS
1067 BLTIN("break" , builtin_break , "Exit loop"),
1069 BLTIN("cd" , builtin_cd , "Change directory"),
1070 #if ENABLE_HUSH_LOOPS
1071 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1073 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1074 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1075 BLTIN("exit" , builtin_exit , NULL),
1076 #if ENABLE_HUSH_EXPORT
1077 BLTIN("export" , builtin_export , "Set environment variables"),
1080 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1082 #if ENABLE_HUSH_HELP
1083 BLTIN("help" , builtin_help , NULL),
1085 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1086 BLTIN("history" , builtin_history , "Show history"),
1089 BLTIN("jobs" , builtin_jobs , "List jobs"),
1091 #if ENABLE_HUSH_KILL
1092 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1094 #if ENABLE_HUSH_LOCAL
1095 BLTIN("local" , builtin_local , "Set local variables"),
1097 #if ENABLE_HUSH_MEMLEAK
1098 BLTIN("memleak" , builtin_memleak , NULL),
1100 #if ENABLE_HUSH_READ
1101 BLTIN("read" , builtin_read , "Input into variable"),
1103 #if ENABLE_HUSH_READONLY
1104 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1106 #if ENABLE_HUSH_FUNCTIONS
1107 BLTIN("return" , builtin_return , "Return from function"),
1110 BLTIN("set" , builtin_set , "Set positional parameters"),
1112 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1114 BLTIN("source" , builtin_source , NULL),
1116 #if ENABLE_HUSH_TIMES
1117 BLTIN("times" , builtin_times , NULL),
1119 #if ENABLE_HUSH_TRAP
1120 BLTIN("trap" , builtin_trap , "Trap signals"),
1122 BLTIN("true" , builtin_true , NULL),
1123 #if ENABLE_HUSH_TYPE
1124 BLTIN("type" , builtin_type , "Show command type"),
1126 #if ENABLE_HUSH_ULIMIT
1127 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1129 #if ENABLE_HUSH_UMASK
1130 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1132 #if ENABLE_HUSH_UNSET
1133 BLTIN("unset" , builtin_unset , "Unset variables"),
1135 #if ENABLE_HUSH_WAIT
1136 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1139 /* These builtins won't be used if we are on NOMMU and need to re-exec
1140 * (it's cheaper to run an external program in this case):
1142 static const struct built_in_command bltins2[] = {
1143 #if ENABLE_HUSH_TEST
1144 BLTIN("[" , builtin_test , NULL),
1147 BLTIN("[[" , builtin_test , NULL),
1149 #if ENABLE_HUSH_ECHO
1150 BLTIN("echo" , builtin_echo , NULL),
1152 #if ENABLE_HUSH_PRINTF
1153 BLTIN("printf" , builtin_printf , NULL),
1155 BLTIN("pwd" , builtin_pwd , NULL),
1156 #if ENABLE_HUSH_TEST
1157 BLTIN("test" , builtin_test , NULL),
1165 /* prevent disasters with G.debug_indent < 0 */
1166 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1167 # define debug_enter() (G.debug_indent++)
1168 # define debug_leave() (G.debug_indent--)
1170 # define indent() ((void)0)
1171 # define debug_enter() ((void)0)
1172 # define debug_leave() ((void)0)
1175 #ifndef debug_printf
1176 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1179 #ifndef debug_printf_parse
1180 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1183 #ifndef debug_printf_exec
1184 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1187 #ifndef debug_printf_env
1188 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1191 #ifndef debug_printf_jobs
1192 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1193 # define DEBUG_JOBS 1
1195 # define DEBUG_JOBS 0
1198 #ifndef debug_printf_expand
1199 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1200 # define DEBUG_EXPAND 1
1202 # define DEBUG_EXPAND 0
1205 #ifndef debug_printf_varexp
1206 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1209 #ifndef debug_printf_glob
1210 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1211 # define DEBUG_GLOB 1
1213 # define DEBUG_GLOB 0
1216 #ifndef debug_printf_redir
1217 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1220 #ifndef debug_printf_list
1221 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1224 #ifndef debug_printf_subst
1225 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1228 #ifndef debug_printf_clean
1229 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1230 # define DEBUG_CLEAN 1
1232 # define DEBUG_CLEAN 0
1236 static void debug_print_strings(const char *prefix, char **vv)
1239 fdprintf(2, "%s:\n", prefix);
1241 fdprintf(2, " '%s'\n", *vv++);
1244 # define debug_print_strings(prefix, vv) ((void)0)
1248 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1251 static void *xxmalloc(int lineno, size_t size)
1253 void *ptr = xmalloc((size + 0xff) & ~0xff);
1254 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1257 static void *xxrealloc(int lineno, void *ptr, size_t size)
1259 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1260 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1263 static char *xxstrdup(int lineno, const char *str)
1265 char *ptr = xstrdup(str);
1266 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1269 static void xxfree(void *ptr)
1271 fdprintf(2, "free %p\n", ptr);
1274 # define xmalloc(s) xxmalloc(__LINE__, s)
1275 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1276 # define xstrdup(s) xxstrdup(__LINE__, s)
1277 # define free(p) xxfree(p)
1281 /* Syntax and runtime errors. They always abort scripts.
1282 * In interactive use they usually discard unparsed and/or unexecuted commands
1283 * and return to the prompt.
1284 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1287 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1288 # define syntax_error(lineno, msg) syntax_error(msg)
1289 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1290 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1291 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1292 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1295 static void die_if_script(void)
1297 if (!G_interactive_fd) {
1298 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1299 xfunc_error_retval = G.last_exitcode;
1304 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1309 bb_error_msg("hush.c:%u", lineno);
1312 bb_verror_msg(fmt, p, NULL);
1317 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1320 bb_error_msg("syntax error: %s", msg);
1322 bb_error_msg("syntax error");
1326 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1328 bb_error_msg("syntax error at '%s'", msg);
1332 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1334 bb_error_msg("syntax error: unterminated %s", s);
1335 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1339 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1341 char msg[2] = { ch, '\0' };
1342 syntax_error_unterm_str(lineno, msg);
1345 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1351 bb_error_msg("hush.c:%u", lineno);
1353 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1358 # undef msg_and_die_if_script
1359 # undef syntax_error
1360 # undef syntax_error_at
1361 # undef syntax_error_unterm_ch
1362 # undef syntax_error_unterm_str
1363 # undef syntax_error_unexpected_ch
1365 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1366 # define syntax_error(msg) syntax_error(__LINE__, msg)
1367 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1368 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1369 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1370 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1374 #if ENABLE_HUSH_INTERACTIVE
1375 static void cmdedit_update_prompt(void);
1377 # define cmdedit_update_prompt() ((void)0)
1381 /* Utility functions
1383 /* Replace each \x with x in place, return ptr past NUL. */
1384 static char *unbackslash(char *src)
1386 char *dst = src = strchrnul(src, '\\');
1390 if ((*dst++ = *src++) == '\0')
1396 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1417 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1418 v[count1 + count2] = NULL;
1421 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1425 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1427 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1428 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1431 #define add_strings_to_strings(strings, add, need_to_dup) \
1432 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1435 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1436 static char **add_string_to_strings(char **strings, char *add)
1441 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1444 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1446 char **ptr = add_string_to_strings(strings, add);
1447 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1450 #define add_string_to_strings(strings, add) \
1451 xx_add_string_to_strings(__LINE__, strings, add)
1454 static void free_strings(char **strings)
1468 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1472 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1482 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1486 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1492 /* fd was not open? */
1497 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1498 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1504 /* Manipulating the list of open FILEs */
1505 static FILE *remember_FILE(FILE *fp)
1508 struct FILE_list *n = xmalloc(sizeof(*n));
1509 n->next = G.FILE_list;
1513 close_on_exec_on(n->fd);
1517 static void fclose_and_forget(FILE *fp)
1519 struct FILE_list **pp = &G.FILE_list;
1521 struct FILE_list *cur = *pp;
1522 if (cur->fp == fp) {
1531 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1533 struct FILE_list *fl = G.FILE_list;
1536 /* We use it only on script files, they are all CLOEXEC */
1537 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1538 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1545 static void restore_redirected_FILEs(void)
1547 struct FILE_list *fl = G.FILE_list;
1549 int should_be = fileno(fl->fp);
1550 if (fl->fd != should_be) {
1551 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1552 xmove_fd(fl->fd, should_be);
1558 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1559 static void close_all_FILE_list(void)
1561 struct FILE_list *fl = G.FILE_list;
1563 /* fclose would also free FILE object.
1564 * It is disastrous if we share memory with a vforked parent.
1565 * I'm not sure we never come here after vfork.
1566 * Therefore just close fd, nothing more.
1568 /*fclose(fl->fp); - unsafe */
1574 static int fd_in_FILEs(int fd)
1576 struct FILE_list *fl = G.FILE_list;
1586 /* Helpers for setting new $n and restoring them back
1588 typedef struct save_arg_t {
1592 IF_HUSH_SET(smallint sv_g_malloced;)
1595 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1597 sv->sv_argv0 = argv[0];
1598 sv->sv_g_argv = G.global_argv;
1599 sv->sv_g_argc = G.global_argc;
1600 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1602 argv[0] = G.global_argv[0]; /* retain $0 */
1603 G.global_argv = argv;
1604 IF_HUSH_SET(G.global_args_malloced = 0;)
1606 G.global_argc = 1 + string_array_len(argv + 1);
1609 static void restore_G_args(save_arg_t *sv, char **argv)
1612 if (G.global_args_malloced) {
1613 /* someone ran "set -- arg1 arg2 ...", undo */
1614 char **pp = G.global_argv;
1615 while (*++pp) /* note: does not free $0 */
1617 free(G.global_argv);
1620 argv[0] = sv->sv_argv0;
1621 G.global_argv = sv->sv_g_argv;
1622 G.global_argc = sv->sv_g_argc;
1623 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1627 /* Basic theory of signal handling in shell
1628 * ========================================
1629 * This does not describe what hush does, rather, it is current understanding
1630 * what it _should_ do. If it doesn't, it's a bug.
1631 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1633 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1634 * is finished or backgrounded. It is the same in interactive and
1635 * non-interactive shells, and is the same regardless of whether
1636 * a user trap handler is installed or a shell special one is in effect.
1637 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1638 * backgrounds (i.e. stops) or kills all members of currently running
1641 * Wait builtin is interruptible by signals for which user trap is set
1642 * or by SIGINT in interactive shell.
1644 * Trap handlers will execute even within trap handlers. (right?)
1646 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1647 * except for handlers set to '' (empty string).
1649 * If job control is off, backgrounded commands ("cmd &")
1650 * have SIGINT, SIGQUIT set to SIG_IGN.
1652 * Commands which are run in command substitution ("`cmd`")
1653 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1655 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1656 * by the shell from its parent.
1658 * Signals which differ from SIG_DFL action
1659 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1662 * SIGTERM (interactive): ignore
1663 * SIGHUP (interactive):
1664 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1665 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1666 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1667 * that all pipe members are stopped. Try this in bash:
1668 * while :; do :; done - ^Z does not background it
1669 * (while :; do :; done) - ^Z backgrounds it
1670 * SIGINT (interactive): wait for last pipe, ignore the rest
1671 * of the command line, show prompt. NB: ^C does not send SIGINT
1672 * to interactive shell while shell is waiting for a pipe,
1673 * since shell is bg'ed (is not in foreground process group).
1674 * Example 1: this waits 5 sec, but does not execute ls:
1675 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1676 * Example 2: this does not wait and does not execute ls:
1677 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1678 * Example 3: this does not wait 5 sec, but executes ls:
1679 * "sleep 5; ls -l" + press ^C
1680 * Example 4: this does not wait and does not execute ls:
1681 * "sleep 5 & wait; ls -l" + press ^C
1683 * (What happens to signals which are IGN on shell start?)
1684 * (What happens with signal mask on shell start?)
1686 * Old implementation
1687 * ==================
1688 * We use in-kernel pending signal mask to determine which signals were sent.
1689 * We block all signals which we don't want to take action immediately,
1690 * i.e. we block all signals which need to have special handling as described
1691 * above, and all signals which have traps set.
1692 * After each pipe execution, we extract any pending signals via sigtimedwait()
1695 * unsigned special_sig_mask: a mask of such "special" signals
1696 * sigset_t blocked_set: current blocked signal set
1699 * clear bit in blocked_set unless it is also in special_sig_mask
1700 * "trap 'cmd' SIGxxx":
1701 * set bit in blocked_set (even if 'cmd' is '')
1702 * after [v]fork, if we plan to be a shell:
1703 * unblock signals with special interactive handling
1704 * (child shell is not interactive),
1705 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1706 * after [v]fork, if we plan to exec:
1707 * POSIX says fork clears pending signal mask in child - no need to clear it.
1708 * Restore blocked signal set to one inherited by shell just prior to exec.
1710 * Note: as a result, we do not use signal handlers much. The only uses
1711 * are to count SIGCHLDs
1712 * and to restore tty pgrp on signal-induced exit.
1715 * Standard says "When a subshell is entered, traps that are not being ignored
1716 * are set to the default actions". bash interprets it so that traps which
1717 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1719 * Problem: the above approach makes it unwieldy to catch signals while
1720 * we are in read builtin, or while we read commands from stdin:
1721 * masked signals are not visible!
1723 * New implementation
1724 * ==================
1725 * We record each signal we are interested in by installing signal handler
1726 * for them - a bit like emulating kernel pending signal mask in userspace.
1727 * We are interested in: signals which need to have special handling
1728 * as described above, and all signals which have traps set.
1729 * Signals are recorded in pending_set.
1730 * After each pipe execution, we extract any pending signals
1733 * unsigned special_sig_mask: a mask of shell-special signals.
1734 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1735 * char *traps[sig] if trap for sig is set (even if it's '').
1736 * sigset_t pending_set: set of sigs we received.
1739 * if sig is in special_sig_mask, set handler back to:
1740 * record_pending_signo, or to IGN if it's a tty stop signal
1741 * if sig is in fatal_sig_mask, set handler back to sigexit.
1742 * else: set handler back to SIG_DFL
1743 * "trap 'cmd' SIGxxx":
1744 * set handler to record_pending_signo.
1746 * set handler to SIG_IGN.
1747 * after [v]fork, if we plan to be a shell:
1748 * set signals with special interactive handling to SIG_DFL
1749 * (because child shell is not interactive),
1750 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1751 * after [v]fork, if we plan to exec:
1752 * POSIX says fork clears pending signal mask in child - no need to clear it.
1754 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1755 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1758 * Standard says "When a subshell is entered, traps that are not being ignored
1759 * are set to the default actions". bash interprets it so that traps which
1760 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1763 SPECIAL_INTERACTIVE_SIGS = 0
1768 SPECIAL_JOBSTOP_SIGS = 0
1777 static void record_pending_signo(int sig)
1779 sigaddset(&G.pending_set, sig);
1780 #if ENABLE_HUSH_FAST
1781 if (sig == SIGCHLD) {
1783 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1788 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1790 struct sigaction old_sa;
1792 /* We could use signal() to install handlers... almost:
1793 * except that we need to mask ALL signals while handlers run.
1794 * I saw signal nesting in strace, race window isn't small.
1795 * SA_RESTART is also needed, but in Linux, signal()
1796 * sets SA_RESTART too.
1798 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1799 /* sigfillset(&G.sa.sa_mask); - already done */
1800 /* G.sa.sa_flags = SA_RESTART; - already done */
1801 G.sa.sa_handler = handler;
1802 sigaction(sig, &G.sa, &old_sa);
1803 return old_sa.sa_handler;
1806 static void hush_exit(int exitcode) NORETURN;
1808 static void restore_ttypgrp_and__exit(void) NORETURN;
1809 static void restore_ttypgrp_and__exit(void)
1811 /* xfunc has failed! die die die */
1812 /* no EXIT traps, this is an escape hatch! */
1814 hush_exit(xfunc_error_retval);
1819 /* Needed only on some libc:
1820 * It was observed that on exit(), fgetc'ed buffered data
1821 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1822 * With the net effect that even after fork(), not vfork(),
1823 * exit() in NOEXECed applet in "sh SCRIPT":
1824 * noexec_applet_here
1825 * echo END_OF_SCRIPT
1826 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1827 * This makes "echo END_OF_SCRIPT" executed twice.
1828 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1829 * and in `cmd` handling.
1830 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1832 static void fflush_and__exit(void) NORETURN;
1833 static void fflush_and__exit(void)
1836 _exit(xfunc_error_retval);
1839 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1840 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1841 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1842 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1844 /* Restores tty foreground process group, and exits.
1845 * May be called as signal handler for fatal signal
1846 * (will resend signal to itself, producing correct exit state)
1847 * or called directly with -EXITCODE.
1848 * We also call it if xfunc is exiting.
1850 static void sigexit(int sig) NORETURN;
1851 static void sigexit(int sig)
1853 /* Careful: we can end up here after [v]fork. Do not restore
1854 * tty pgrp then, only top-level shell process does that */
1855 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1856 /* Disable all signals: job control, SIGPIPE, etc.
1857 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1859 sigprocmask_allsigs(SIG_BLOCK);
1860 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1863 /* Not a signal, just exit */
1867 kill_myself_with_sig(sig); /* does not return */
1871 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1872 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1876 static sighandler_t pick_sighandler(unsigned sig)
1878 sighandler_t handler = SIG_DFL;
1879 if (sig < sizeof(unsigned)*8) {
1880 unsigned sigmask = (1 << sig);
1884 if (G_fatal_sig_mask & sigmask)
1888 /* sig has special handling? */
1889 if (G.special_sig_mask & sigmask) {
1890 handler = record_pending_signo;
1891 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1892 * in order to ignore them: they will be raised
1893 * in an endless loop when we try to do some
1894 * terminal ioctls! We do have to _ignore_ these.
1896 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1903 /* Restores tty foreground process group, and exits. */
1904 static void hush_exit(int exitcode)
1906 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1907 save_history(G.line_input_state);
1911 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1913 /* argv[0] is unused */
1914 argv[1] = G_traps[0];
1916 G.exiting = 1; /* prevent EXIT trap recursion */
1917 /* Note: G_traps[0] is not cleared!
1918 * "trap" will still show it, if executed
1923 #if ENABLE_FEATURE_CLEAN_UP
1925 struct variable *cur_var;
1926 if (G.cwd != bb_msg_unknown)
1928 cur_var = G.top_var;
1930 struct variable *tmp = cur_var;
1931 if (!cur_var->max_len)
1932 free(cur_var->varstr);
1933 cur_var = cur_var->next;
1941 sigexit(- (exitcode & 0xff));
1948 //TODO: return a mask of ALL handled sigs?
1949 static int check_and_run_traps(void)
1956 if (sigisemptyset(&G.pending_set))
1961 if (sigismember(&G.pending_set, sig)) {
1962 sigdelset(&G.pending_set, sig);
1965 } while (sig < NSIG);
1968 if (G_traps && G_traps[sig]) {
1969 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1970 if (G_traps[sig][0]) {
1971 /* We have user-defined handler */
1972 smalluint save_rcode;
1974 /* argv[0] is unused */
1975 argv[1] = G_traps[sig];
1977 save_rcode = G.last_exitcode;
1979 //FIXME: shouldn't it be set to 128 + sig instead?
1980 G.last_exitcode = save_rcode;
1982 } /* else: "" trap, ignoring signal */
1985 /* not a trap: special action */
1988 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1994 //TODO: why are we doing this? ash and dash don't do this,
1995 //they have no handler for SIGHUP at all,
1996 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
1998 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1999 /* bash is observed to signal whole process groups,
2000 * not individual processes */
2001 for (job = G.job_list; job; job = job->next) {
2004 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2005 if (kill(- job->pgrp, SIGHUP) == 0)
2006 kill(- job->pgrp, SIGCONT);
2011 #if ENABLE_HUSH_FAST
2013 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2015 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2017 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2018 * This simplifies wait builtin a bit.
2022 default: /* ignored: */
2023 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2024 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2026 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2027 * Example: wait is not interrupted by TERM
2028 * in interactive shell, because TERM is ignored.
2037 static const char *get_cwd(int force)
2039 if (force || G.cwd == NULL) {
2040 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2041 * we must not try to free(bb_msg_unknown) */
2042 if (G.cwd == bb_msg_unknown)
2044 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2046 G.cwd = bb_msg_unknown;
2053 * Shell and environment variable support
2055 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2057 struct variable **pp;
2058 struct variable *cur;
2061 while ((cur = *pp) != NULL) {
2062 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2069 static const char* FAST_FUNC get_local_var_value(const char *name)
2071 struct variable **vpp;
2072 unsigned len = strlen(name);
2074 if (G.expanded_assignments) {
2075 char **cpp = G.expanded_assignments;
2078 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2079 return cp + len + 1;
2084 vpp = get_ptr_to_local_var(name, len);
2086 return (*vpp)->varstr + len + 1;
2088 if (strcmp(name, "PPID") == 0)
2089 return utoa(G.root_ppid);
2090 // bash compat: UID? EUID?
2091 #if ENABLE_HUSH_RANDOM_SUPPORT
2092 if (strcmp(name, "RANDOM") == 0)
2093 return utoa(next_random(&G.random_gen));
2098 /* str holds "NAME=VAL" and is expected to be malloced.
2099 * We take ownership of it.
2101 #define SETFLAG_EXPORT (1 << 0)
2102 #define SETFLAG_UNEXPORT (1 << 1)
2103 #define SETFLAG_MAKE_RO (1 << 2)
2104 #define SETFLAG_LOCAL_SHIFT 3
2105 static int set_local_var(char *str, unsigned flags)
2107 struct variable **var_pp;
2108 struct variable *cur;
2109 char *free_me = NULL;
2112 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2114 eq_sign = strchr(str, '=');
2115 if (!eq_sign) { /* not expected to ever happen? */
2120 name_len = eq_sign - str + 1; /* including '=' */
2121 var_pp = &G.top_var;
2122 while ((cur = *var_pp) != NULL) {
2123 if (strncmp(cur->varstr, str, name_len) != 0) {
2124 var_pp = &cur->next;
2128 /* We found an existing var with this name */
2129 if (cur->flg_read_only) {
2130 bb_error_msg("%s: readonly variable", str);
2132 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2133 //but export per se succeeds (does put the var in env). We don't mimic that.
2136 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2137 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2142 #if ENABLE_HUSH_LOCAL
2143 if (cur->func_nest_level < local_lvl) {
2144 /* New variable is declared as local,
2145 * and existing one is global, or local
2146 * from enclosing function.
2147 * Remove and save old one: */
2148 *var_pp = cur->next;
2149 cur->next = *G.shadowed_vars_pp;
2150 *G.shadowed_vars_pp = cur;
2151 /* bash 3.2.33(1) and exported vars:
2153 * # f() { local z=a; env | grep ^z; }
2159 if (cur->flg_export)
2160 flags |= SETFLAG_EXPORT;
2164 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2169 if (cur->max_len != 0) {
2170 if (cur->max_len >= strlen(str)) {
2171 /* This one is from startup env, reuse space */
2172 strcpy(cur->varstr, str);
2177 goto set_str_and_exp;
2179 /* max_len == 0 signifies "malloced" var, which we can
2180 * (and have to) free. But we can't free(cur->varstr) here:
2181 * if cur->flg_export is 1, it is in the environment.
2182 * We should either unsetenv+free, or wait until putenv,
2183 * then putenv(new)+free(old).
2185 free_me = cur->varstr;
2186 goto set_str_and_exp;
2189 /* Not found - create new variable struct */
2190 cur = xzalloc(sizeof(*cur));
2191 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2192 cur->next = *var_pp;
2198 #if !BB_MMU || ENABLE_HUSH_READONLY
2199 if (flags & SETFLAG_MAKE_RO) {
2200 cur->flg_read_only = 1;
2203 if (flags & SETFLAG_EXPORT)
2204 cur->flg_export = 1;
2205 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2206 cmdedit_update_prompt();
2207 if (cur->flg_export) {
2208 if (flags & SETFLAG_UNEXPORT) {
2209 cur->flg_export = 0;
2210 /* unsetenv was already done */
2213 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2214 i = putenv(cur->varstr);
2215 /* only now we can free old exported malloced string */
2224 /* Used at startup and after each cd */
2225 static void set_pwd_var(unsigned flag)
2227 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2230 static int unset_local_var_len(const char *name, int name_len)
2232 struct variable *cur;
2233 struct variable **var_pp;
2236 return EXIT_SUCCESS;
2237 var_pp = &G.top_var;
2238 while ((cur = *var_pp) != NULL) {
2239 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2240 if (cur->flg_read_only) {
2241 bb_error_msg("%s: readonly variable", name);
2242 return EXIT_FAILURE;
2244 *var_pp = cur->next;
2245 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2246 bb_unsetenv(cur->varstr);
2247 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2248 cmdedit_update_prompt();
2252 return EXIT_SUCCESS;
2254 var_pp = &cur->next;
2256 return EXIT_SUCCESS;
2259 #if ENABLE_HUSH_UNSET
2260 static int unset_local_var(const char *name)
2262 return unset_local_var_len(name, strlen(name));
2266 static void unset_vars(char **strings)
2274 const char *eq = strchrnul(*v, '=');
2275 unset_local_var_len(*v, (int)(eq - *v));
2281 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ
2282 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2284 char *var = xasprintf("%s=%s", name, val);
2285 set_local_var(var, /*flag:*/ 0);
2291 * Helpers for "var1=val1 var2=val2 cmd" feature
2293 static void add_vars(struct variable *var)
2295 struct variable *next;
2299 var->next = G.top_var;
2301 if (var->flg_export) {
2302 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2303 putenv(var->varstr);
2305 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2311 static struct variable *set_vars_and_save_old(char **strings)
2314 struct variable *old = NULL;
2320 struct variable *var_p;
2321 struct variable **var_pp;
2324 eq = strchr(*s, '=');
2326 var_pp = get_ptr_to_local_var(*s, eq - *s);
2329 if (var_p->flg_read_only) {
2331 bb_error_msg("%s: readonly variable", *s);
2333 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2334 * If VAR is readonly, leaving it in the list
2335 * after asssignment error (msg above)
2336 * causes doubled error message later, on unset.
2338 debug_printf_env("removing/freeing '%s' element\n", *s);
2341 do { *p = p[1]; p++; } while (*p);
2344 /* Remove variable from global linked list */
2345 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2346 *var_pp = var_p->next;
2347 /* Add it to returned list */
2351 set_local_var(*s, SETFLAG_EXPORT);
2363 static void reinit_unicode_for_hush(void)
2365 /* Unicode support should be activated even if LANG is set
2366 * _during_ shell execution, not only if it was set when
2367 * shell was started. Therefore, re-check LANG every time:
2369 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2370 || ENABLE_UNICODE_USING_LOCALE
2372 const char *s = get_local_var_value("LC_ALL");
2373 if (!s) s = get_local_var_value("LC_CTYPE");
2374 if (!s) s = get_local_var_value("LANG");
2380 * in_str support (strings, and "strings" read from files).
2383 #if ENABLE_HUSH_INTERACTIVE
2384 /* To test correct lineedit/interactive behavior, type from command line:
2390 * It exercises a lot of corner cases.
2392 static void cmdedit_update_prompt(void)
2394 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2395 G.PS1 = get_local_var_value("PS1");
2398 G.PS2 = get_local_var_value("PS2");
2405 static const char *setup_prompt_string(int promptmode)
2407 const char *prompt_str;
2408 debug_printf("setup_prompt_string %d ", promptmode);
2409 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2410 /* Set up the prompt */
2411 if (promptmode == 0) { /* PS1 */
2413 /* bash uses $PWD value, even if it is set by user.
2414 * It uses current dir only if PWD is unset.
2415 * We always use current dir. */
2416 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2421 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2422 debug_printf("prompt_str '%s'\n", prompt_str);
2425 static int get_user_input(struct in_str *i)
2428 const char *prompt_str;
2430 prompt_str = setup_prompt_string(i->promptmode);
2431 # if ENABLE_FEATURE_EDITING
2433 reinit_unicode_for_hush();
2434 if (G.flag_SIGINT) {
2435 /* There was ^C'ed, make it look prettier: */
2439 /* buglet: SIGINT will not make new prompt to appear _at once_,
2440 * only after <Enter>. (^C works immediately) */
2441 r = read_line_input(G.line_input_state, prompt_str,
2442 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2444 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2447 check_and_run_traps();
2448 if (r != 0 && !G.flag_SIGINT)
2450 /* ^C or SIGINT: repeat */
2451 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2452 write(STDOUT_FILENO, "^C", 2);
2453 G.last_exitcode = 128 + SIGINT;
2456 /* EOF/error detected */
2458 i->peek_buf[0] = r = EOF;
2461 i->p = G.user_input_buf;
2462 return (unsigned char)*i->p++;
2466 if (i->last_char == '\0' || i->last_char == '\n') {
2467 /* Why check_and_run_traps here? Try this interactively:
2468 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2469 * $ <[enter], repeatedly...>
2470 * Without check_and_run_traps, handler never runs.
2472 check_and_run_traps();
2473 fputs(prompt_str, stdout);
2476 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2478 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2479 * no ^C masking happens during fgetc, no special code for ^C:
2480 * it generates SIGINT as usual.
2482 check_and_run_traps();
2484 G.last_exitcode = 128 + SIGINT;
2491 /* This is the magic location that prints prompts
2492 * and gets data back from the user */
2493 static int fgetc_interactive(struct in_str *i)
2496 /* If it's interactive stdin, get new line. */
2497 if (G_interactive_fd && i->file == stdin) {
2498 /* Returns first char (or EOF), the rest is in i->p[] */
2499 ch = get_user_input(i);
2500 i->promptmode = 1; /* PS2 */
2502 /* Not stdin: script file, sourced file, etc */
2503 do ch = fgetc(i->file); while (ch == '\0');
2508 static inline int fgetc_interactive(struct in_str *i)
2511 do ch = fgetc(i->file); while (ch == '\0');
2514 #endif /* INTERACTIVE */
2516 static int i_getch(struct in_str *i)
2521 /* string-based in_str */
2522 ch = (unsigned char)*i->p;
2531 /* FILE-based in_str */
2533 #if ENABLE_FEATURE_EDITING
2534 /* This can be stdin, check line editing char[] buffer */
2535 if (i->p && *i->p != '\0') {
2536 ch = (unsigned char)*i->p++;
2540 /* peek_buf[] is an int array, not char. Can contain EOF. */
2541 ch = i->peek_buf[0];
2543 int ch2 = i->peek_buf[1];
2544 i->peek_buf[0] = ch2;
2545 if (ch2 == 0) /* very likely, avoid redundant write */
2551 ch = fgetc_interactive(i);
2553 debug_printf("file_get: got '%c' %d\n", ch, ch);
2558 static int i_peek(struct in_str *i)
2563 /* string-based in_str */
2564 /* Doesn't report EOF on NUL. None of the callers care. */
2565 return (unsigned char)*i->p;
2568 /* FILE-based in_str */
2570 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2571 /* This can be stdin, check line editing char[] buffer */
2572 if (i->p && *i->p != '\0')
2573 return (unsigned char)*i->p;
2575 /* peek_buf[] is an int array, not char. Can contain EOF. */
2576 ch = i->peek_buf[0];
2580 /* Need to get a new char */
2581 ch = fgetc_interactive(i);
2582 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2584 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2585 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2591 i->peek_buf[0] = ch;
2592 /*i->peek_buf[1] = 0; - already is */
2596 /* Only ever called if i_peek() was called, and did not return EOF.
2597 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2598 * not end-of-line. Therefore we never need to read a new editing line here.
2600 static int i_peek2(struct in_str *i)
2604 /* There are two cases when i->p[] buffer exists.
2605 * (1) it's a string in_str.
2606 * (2) It's a file, and we have a saved line editing buffer.
2607 * In both cases, we know that i->p[0] exists and not NUL, and
2608 * the peek2 result is in i->p[1].
2611 return (unsigned char)i->p[1];
2613 /* Now we know it is a file-based in_str. */
2615 /* peek_buf[] is an int array, not char. Can contain EOF. */
2616 /* Is there 2nd char? */
2617 ch = i->peek_buf[1];
2619 /* We did not read it yet, get it now */
2620 do ch = fgetc(i->file); while (ch == '\0');
2621 i->peek_buf[1] = ch;
2624 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2628 static void setup_file_in_str(struct in_str *i, FILE *f)
2630 memset(i, 0, sizeof(*i));
2631 /* i->promptmode = 0; - PS1 (memset did it) */
2636 static void setup_string_in_str(struct in_str *i, const char *s)
2638 memset(i, 0, sizeof(*i));
2639 /* i->promptmode = 0; - PS1 (memset did it) */
2640 /*i->file = NULL */;
2648 #define B_CHUNK (32 * sizeof(char*))
2650 static void o_reset_to_empty_unquoted(o_string *o)
2653 o->has_quoted_part = 0;
2658 static void o_free(o_string *o)
2661 memset(o, 0, sizeof(*o));
2664 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2669 static void o_grow_by(o_string *o, int len)
2671 if (o->length + len > o->maxlen) {
2672 o->maxlen += (2 * len) | (B_CHUNK-1);
2673 o->data = xrealloc(o->data, 1 + o->maxlen);
2677 static void o_addchr(o_string *o, int ch)
2679 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2680 if (o->length < o->maxlen) {
2681 /* likely. avoid o_grow_by() call */
2683 o->data[o->length] = ch;
2685 o->data[o->length] = '\0';
2693 /* Valid only if we know o_string is not empty */
2694 static void o_delchr(o_string *o)
2697 o->data[o->length] = '\0';
2701 static void o_addblock(o_string *o, const char *str, int len)
2704 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2708 static void o_addstr(o_string *o, const char *str)
2710 o_addblock(o, str, strlen(str));
2714 static void nommu_addchr(o_string *o, int ch)
2720 # define nommu_addchr(o, str) ((void)0)
2723 static void o_addstr_with_NUL(o_string *o, const char *str)
2725 o_addblock(o, str, strlen(str) + 1);
2729 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2730 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2731 * Apparently, on unquoted $v bash still does globbing
2732 * ("v='*.txt'; echo $v" prints all .txt files),
2733 * but NOT brace expansion! Thus, there should be TWO independent
2734 * quoting mechanisms on $v expansion side: one protects
2735 * $v from brace expansion, and other additionally protects "$v" against globbing.
2736 * We have only second one.
2739 #if ENABLE_HUSH_BRACE_EXPANSION
2740 # define MAYBE_BRACES "{}"
2742 # define MAYBE_BRACES ""
2745 /* My analysis of quoting semantics tells me that state information
2746 * is associated with a destination, not a source.
2748 static void o_addqchr(o_string *o, int ch)
2751 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2756 o->data[o->length] = '\\';
2759 o->data[o->length] = ch;
2761 o->data[o->length] = '\0';
2764 static void o_addQchr(o_string *o, int ch)
2767 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2768 && strchr("*?[\\" MAYBE_BRACES, ch)
2771 o->data[o->length] = '\\';
2775 o->data[o->length] = ch;
2777 o->data[o->length] = '\0';
2780 static void o_addqblock(o_string *o, const char *str, int len)
2785 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2786 if (ordinary_cnt > len) /* paranoia */
2788 o_addblock(o, str, ordinary_cnt);
2789 if (ordinary_cnt == len)
2790 return; /* NUL is already added by o_addblock */
2791 str += ordinary_cnt;
2792 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2796 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2798 o->data[o->length] = '\\';
2802 o->data[o->length] = ch;
2805 o->data[o->length] = '\0';
2808 static void o_addQblock(o_string *o, const char *str, int len)
2810 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2811 o_addblock(o, str, len);
2814 o_addqblock(o, str, len);
2817 static void o_addQstr(o_string *o, const char *str)
2819 o_addQblock(o, str, strlen(str));
2822 /* A special kind of o_string for $VAR and `cmd` expansion.
2823 * It contains char* list[] at the beginning, which is grown in 16 element
2824 * increments. Actual string data starts at the next multiple of 16 * (char*).
2825 * list[i] contains an INDEX (int!) into this string data.
2826 * It means that if list[] needs to grow, data needs to be moved higher up
2827 * but list[i]'s need not be modified.
2828 * NB: remembering how many list[i]'s you have there is crucial.
2829 * o_finalize_list() operation post-processes this structure - calculates
2830 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2832 #if DEBUG_EXPAND || DEBUG_GLOB
2833 static void debug_print_list(const char *prefix, o_string *o, int n)
2835 char **list = (char**)o->data;
2836 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2840 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2841 prefix, list, n, string_start, o->length, o->maxlen,
2842 !!(o->o_expflags & EXP_FLAG_GLOB),
2844 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2847 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2848 o->data + (int)(uintptr_t)list[i] + string_start,
2849 o->data + (int)(uintptr_t)list[i] + string_start);
2853 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2855 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2859 # define debug_print_list(prefix, o, n) ((void)0)
2862 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2863 * in list[n] so that it points past last stored byte so far.
2864 * It returns n+1. */
2865 static int o_save_ptr_helper(o_string *o, int n)
2867 char **list = (char**)o->data;
2871 if (!o->has_empty_slot) {
2872 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2873 string_len = o->length - string_start;
2874 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2875 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2876 /* list[n] points to string_start, make space for 16 more pointers */
2877 o->maxlen += 0x10 * sizeof(list[0]);
2878 o->data = xrealloc(o->data, o->maxlen + 1);
2879 list = (char**)o->data;
2880 memmove(list + n + 0x10, list + n, string_len);
2881 o->length += 0x10 * sizeof(list[0]);
2883 debug_printf_list("list[%d]=%d string_start=%d\n",
2884 n, string_len, string_start);
2887 /* We have empty slot at list[n], reuse without growth */
2888 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2889 string_len = o->length - string_start;
2890 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2891 n, string_len, string_start);
2892 o->has_empty_slot = 0;
2894 o->has_quoted_part = 0;
2895 list[n] = (char*)(uintptr_t)string_len;
2899 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2900 static int o_get_last_ptr(o_string *o, int n)
2902 char **list = (char**)o->data;
2903 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2905 return ((int)(uintptr_t)list[n-1]) + string_start;
2908 #if ENABLE_HUSH_BRACE_EXPANSION
2909 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2910 * first, it processes even {a} (no commas), second,
2911 * I didn't manage to make it return strings when they don't match
2912 * existing files. Need to re-implement it.
2916 static int glob_needed(const char *s)
2925 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2931 /* Return pointer to next closing brace or to comma */
2932 static const char *next_brace_sub(const char *cp)
2936 while (*cp != '\0') {
2943 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2949 return *cp != '\0' ? cp : NULL;
2951 /* Recursive brace globber. Note: may garble pattern[]. */
2952 static int glob_brace(char *pattern, o_string *o, int n)
2954 char *new_pattern_buf;
2961 debug_printf_glob("glob_brace('%s')\n", pattern);
2967 if (*begin == '{') {
2968 /* Find the first sub-pattern and at the same time
2969 * find the rest after the closing brace */
2970 next = next_brace_sub(begin);
2972 /* An illegal expression */
2976 /* "{abc}" with no commas - illegal
2977 * brace expr, disregard and skip it */
2983 if (*begin == '\\' && begin[1] != '\0')
2987 debug_printf_glob("begin:%s\n", begin);
2988 debug_printf_glob("next:%s\n", next);
2990 /* Now find the end of the whole brace expression */
2992 while (*rest != '}') {
2993 rest = next_brace_sub(rest);
2995 /* An illegal expression */
2998 debug_printf_glob("rest:%s\n", rest);
3000 rest_len = strlen(++rest) + 1;
3002 /* We are sure the brace expression is well-formed */
3004 /* Allocate working buffer large enough for our work */
3005 new_pattern_buf = xmalloc(strlen(pattern));
3007 /* We have a brace expression. BEGIN points to the opening {,
3008 * NEXT points past the terminator of the first element, and REST
3009 * points past the final }. We will accumulate result names from
3010 * recursive runs for each brace alternative in the buffer using
3015 /* Construct the new glob expression */
3018 mempcpy(new_pattern_buf,
3019 /* We know the prefix for all sub-patterns */
3020 pattern, begin - pattern),
3024 /* Note: glob_brace() may garble new_pattern_buf[].
3025 * That's why we re-copy prefix every time (1st memcpy above).
3027 n = glob_brace(new_pattern_buf, o, n);
3029 /* We saw the last entry */
3033 next = next_brace_sub(next);
3035 free(new_pattern_buf);
3043 memset(&globdata, 0, sizeof(globdata));
3044 gr = glob(pattern, 0, NULL, &globdata);
3045 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3047 if (gr == GLOB_NOMATCH) {
3048 globfree(&globdata);
3049 /* NB: garbles parameter */
3050 unbackslash(pattern);
3051 o_addstr_with_NUL(o, pattern);
3052 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3053 return o_save_ptr_helper(o, n);
3055 if (gr == GLOB_NOSPACE)
3056 bb_error_msg_and_die(bb_msg_memory_exhausted);
3057 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3058 * but we didn't specify it. Paranoia again. */
3059 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3061 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3062 char **argv = globdata.gl_pathv;
3064 o_addstr_with_NUL(o, *argv);
3065 n = o_save_ptr_helper(o, n);
3071 globfree(&globdata);
3075 /* Performs globbing on last list[],
3076 * saving each result as a new list[].
3078 static int perform_glob(o_string *o, int n)
3080 char *pattern, *copy;
3082 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3084 return o_save_ptr_helper(o, n);
3085 pattern = o->data + o_get_last_ptr(o, n);
3086 debug_printf_glob("glob pattern '%s'\n", pattern);
3087 if (!glob_needed(pattern)) {
3088 /* unbackslash last string in o in place, fix length */
3089 o->length = unbackslash(pattern) - o->data;
3090 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3091 return o_save_ptr_helper(o, n);
3094 copy = xstrdup(pattern);
3095 /* "forget" pattern in o */
3096 o->length = pattern - o->data;
3097 n = glob_brace(copy, o, n);
3100 debug_print_list("perform_glob returning", o, n);
3104 #else /* !HUSH_BRACE_EXPANSION */
3107 static int glob_needed(const char *s)
3116 if (*s == '*' || *s == '[' || *s == '?')
3122 /* Performs globbing on last list[],
3123 * saving each result as a new list[].
3125 static int perform_glob(o_string *o, int n)
3131 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3133 return o_save_ptr_helper(o, n);
3134 pattern = o->data + o_get_last_ptr(o, n);
3135 debug_printf_glob("glob pattern '%s'\n", pattern);
3136 if (!glob_needed(pattern)) {
3138 /* unbackslash last string in o in place, fix length */
3139 o->length = unbackslash(pattern) - o->data;
3140 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3141 return o_save_ptr_helper(o, n);
3144 memset(&globdata, 0, sizeof(globdata));
3145 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3146 * If we glob "*.\*" and don't find anything, we need
3147 * to fall back to using literal "*.*", but GLOB_NOCHECK
3148 * will return "*.\*"!
3150 gr = glob(pattern, 0, NULL, &globdata);
3151 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3153 if (gr == GLOB_NOMATCH) {
3154 globfree(&globdata);
3157 if (gr == GLOB_NOSPACE)
3158 bb_error_msg_and_die(bb_msg_memory_exhausted);
3159 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3160 * but we didn't specify it. Paranoia again. */
3161 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3163 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3164 char **argv = globdata.gl_pathv;
3165 /* "forget" pattern in o */
3166 o->length = pattern - o->data;
3168 o_addstr_with_NUL(o, *argv);
3169 n = o_save_ptr_helper(o, n);
3175 globfree(&globdata);
3177 debug_print_list("perform_glob returning", o, n);
3181 #endif /* !HUSH_BRACE_EXPANSION */
3183 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3184 * Otherwise, just finish current list[] and start new */
3185 static int o_save_ptr(o_string *o, int n)
3187 if (o->o_expflags & EXP_FLAG_GLOB) {
3188 /* If o->has_empty_slot, list[n] was already globbed
3189 * (if it was requested back then when it was filled)
3190 * so don't do that again! */
3191 if (!o->has_empty_slot)
3192 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3194 return o_save_ptr_helper(o, n);
3197 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3198 static char **o_finalize_list(o_string *o, int n)
3203 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3205 debug_print_list("finalized", o, n);
3206 debug_printf_expand("finalized n:%d\n", n);
3207 list = (char**)o->data;
3208 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3212 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3217 static void free_pipe_list(struct pipe *pi);
3219 /* Returns pi->next - next pipe in the list */
3220 static struct pipe *free_pipe(struct pipe *pi)
3225 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3226 for (i = 0; i < pi->num_cmds; i++) {
3227 struct command *command;
3228 struct redir_struct *r, *rnext;
3230 command = &pi->cmds[i];
3231 debug_printf_clean(" command %d:\n", i);
3232 if (command->argv) {
3236 for (a = 0, p = command->argv; *p; a++, p++) {
3237 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3240 free_strings(command->argv);
3241 //command->argv = NULL;
3243 /* not "else if": on syntax error, we may have both! */
3244 if (command->group) {
3245 debug_printf_clean(" begin group (cmd_type:%d)\n",
3247 free_pipe_list(command->group);
3248 debug_printf_clean(" end group\n");
3249 //command->group = NULL;
3251 /* else is crucial here.
3252 * If group != NULL, child_func is meaningless */
3253 #if ENABLE_HUSH_FUNCTIONS
3254 else if (command->child_func) {
3255 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3256 command->child_func->parent_cmd = NULL;
3260 free(command->group_as_string);
3261 //command->group_as_string = NULL;
3263 for (r = command->redirects; r; r = rnext) {
3264 debug_printf_clean(" redirect %d%s",
3265 r->rd_fd, redir_table[r->rd_type].descrip);
3266 /* guard against the case >$FOO, where foo is unset or blank */
3267 if (r->rd_filename) {
3268 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3269 free(r->rd_filename);
3270 //r->rd_filename = NULL;
3272 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3276 //command->redirects = NULL;
3278 free(pi->cmds); /* children are an array, they get freed all at once */
3282 //pi->cmdtext = NULL;
3290 static void free_pipe_list(struct pipe *pi)
3294 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3296 debug_printf_clean("pipe followup code %d\n", pi->followup);
3302 /*** Parsing routines ***/
3304 #ifndef debug_print_tree
3305 static void debug_print_tree(struct pipe *pi, int lvl)
3307 static const char *const PIPE[] = {
3313 static const char *RES[] = {
3314 [RES_NONE ] = "NONE" ,
3317 [RES_THEN ] = "THEN" ,
3318 [RES_ELIF ] = "ELIF" ,
3319 [RES_ELSE ] = "ELSE" ,
3322 # if ENABLE_HUSH_LOOPS
3323 [RES_FOR ] = "FOR" ,
3324 [RES_WHILE] = "WHILE",
3325 [RES_UNTIL] = "UNTIL",
3327 [RES_DONE ] = "DONE" ,
3329 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3332 # if ENABLE_HUSH_CASE
3333 [RES_CASE ] = "CASE" ,
3334 [RES_CASE_IN ] = "CASE_IN" ,
3335 [RES_MATCH] = "MATCH",
3336 [RES_CASE_BODY] = "CASE_BODY",
3337 [RES_ESAC ] = "ESAC" ,
3339 [RES_XXXX ] = "XXXX" ,
3340 [RES_SNTX ] = "SNTX" ,
3342 static const char *const CMDTYPE[] = {
3346 # if ENABLE_HUSH_FUNCTIONS
3355 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3356 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3358 while (prn < pi->num_cmds) {
3359 struct command *command = &pi->cmds[prn];
3360 char **argv = command->argv;
3362 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3364 command->assignment_cnt);
3365 if (command->group) {
3366 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3367 CMDTYPE[command->cmd_type],
3370 , " group_as_string:", command->group_as_string
3375 debug_print_tree(command->group, lvl+1);
3379 if (argv) while (*argv) {
3380 fdprintf(2, " '%s'", *argv);
3390 #endif /* debug_print_tree */
3392 static struct pipe *new_pipe(void)
3395 pi = xzalloc(sizeof(struct pipe));
3396 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3400 /* Command (member of a pipe) is complete, or we start a new pipe
3401 * if ctx->command is NULL.
3402 * No errors possible here.
3404 static int done_command(struct parse_context *ctx)
3406 /* The command is really already in the pipe structure, so
3407 * advance the pipe counter and make a new, null command. */
3408 struct pipe *pi = ctx->pipe;
3409 struct command *command = ctx->command;
3411 #if 0 /* Instead we emit error message at run time */
3412 if (ctx->pending_redirect) {
3413 /* For example, "cmd >" (no filename to redirect to) */
3414 syntax_error("invalid redirect");
3415 ctx->pending_redirect = NULL;
3420 if (IS_NULL_CMD(command)) {
3421 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3425 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3426 //debug_print_tree(ctx->list_head, 20);
3428 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3431 /* Only real trickiness here is that the uncommitted
3432 * command structure is not counted in pi->num_cmds. */
3433 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3434 ctx->command = command = &pi->cmds[pi->num_cmds];
3436 memset(command, 0, sizeof(*command));
3437 return pi->num_cmds; /* used only for 0/nonzero check */
3440 static void done_pipe(struct parse_context *ctx, pipe_style type)
3444 debug_printf_parse("done_pipe entered, followup %d\n", type);
3445 /* Close previous command */
3446 not_null = done_command(ctx);
3448 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3449 ctx->ctx_inverted = 0;
3450 ctx->pipe->res_word = ctx->ctx_res_w;
3452 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3453 /* Necessary since && and || have precedence over &:
3454 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3455 * in a backgrounded subshell.
3458 struct command *command;
3460 /* Is this actually this construct, all pipes end with && or ||? */
3461 pi = ctx->list_head;
3462 while (pi != ctx->pipe) {
3463 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3468 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3469 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3470 pi = xzalloc(sizeof(*pi));
3471 pi->followup = PIPE_BG;
3473 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3474 command = &pi->cmds[0];
3475 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3476 command->cmd_type = CMD_NORMAL;
3477 command->group = ctx->list_head;
3479 command->group_as_string = xstrndup(
3480 ctx->as_string.data,
3481 ctx->as_string.length - 1 /* do not copy last char, "&" */
3484 /* Replace all pipes in ctx with one newly created */
3485 ctx->list_head = ctx->pipe = pi;
3488 ctx->pipe->followup = type;
3491 /* Without this check, even just <enter> on command line generates
3492 * tree of three NOPs (!). Which is harmless but annoying.
3493 * IOW: it is safe to do it unconditionally. */
3496 || ctx->ctx_res_w == RES_FI
3498 #if ENABLE_HUSH_LOOPS
3499 || ctx->ctx_res_w == RES_DONE
3500 || ctx->ctx_res_w == RES_FOR
3501 || ctx->ctx_res_w == RES_IN
3503 #if ENABLE_HUSH_CASE
3504 || ctx->ctx_res_w == RES_ESAC
3508 debug_printf_parse("done_pipe: adding new pipe: "
3509 "not_null:%d ctx->ctx_res_w:%d\n",
3510 not_null, ctx->ctx_res_w);
3512 ctx->pipe->next = new_p;
3514 /* RES_THEN, RES_DO etc are "sticky" -
3515 * they remain set for pipes inside if/while.
3516 * This is used to control execution.
3517 * RES_FOR and RES_IN are NOT sticky (needed to support
3518 * cases where variable or value happens to match a keyword):
3520 #if ENABLE_HUSH_LOOPS
3521 if (ctx->ctx_res_w == RES_FOR
3522 || ctx->ctx_res_w == RES_IN)
3523 ctx->ctx_res_w = RES_NONE;
3525 #if ENABLE_HUSH_CASE
3526 if (ctx->ctx_res_w == RES_MATCH)
3527 ctx->ctx_res_w = RES_CASE_BODY;
3528 if (ctx->ctx_res_w == RES_CASE)
3529 ctx->ctx_res_w = RES_CASE_IN;
3531 ctx->command = NULL; /* trick done_command below */
3532 /* Create the memory for command, roughly:
3533 * ctx->pipe->cmds = new struct command;
3534 * ctx->command = &ctx->pipe->cmds[0];
3537 //debug_print_tree(ctx->list_head, 10);
3539 debug_printf_parse("done_pipe return\n");
3542 static void initialize_context(struct parse_context *ctx)
3544 memset(ctx, 0, sizeof(*ctx));
3545 ctx->pipe = ctx->list_head = new_pipe();
3546 /* Create the memory for command, roughly:
3547 * ctx->pipe->cmds = new struct command;
3548 * ctx->command = &ctx->pipe->cmds[0];
3553 /* If a reserved word is found and processed, parse context is modified
3554 * and 1 is returned.
3557 struct reserved_combo {
3560 unsigned char assignment_flag;
3564 FLAG_END = (1 << RES_NONE ),
3566 FLAG_IF = (1 << RES_IF ),
3567 FLAG_THEN = (1 << RES_THEN ),
3568 FLAG_ELIF = (1 << RES_ELIF ),
3569 FLAG_ELSE = (1 << RES_ELSE ),
3570 FLAG_FI = (1 << RES_FI ),
3572 # if ENABLE_HUSH_LOOPS
3573 FLAG_FOR = (1 << RES_FOR ),
3574 FLAG_WHILE = (1 << RES_WHILE),
3575 FLAG_UNTIL = (1 << RES_UNTIL),
3576 FLAG_DO = (1 << RES_DO ),
3577 FLAG_DONE = (1 << RES_DONE ),
3578 FLAG_IN = (1 << RES_IN ),
3580 # if ENABLE_HUSH_CASE
3581 FLAG_MATCH = (1 << RES_MATCH),
3582 FLAG_ESAC = (1 << RES_ESAC ),
3584 FLAG_START = (1 << RES_XXXX ),
3587 static const struct reserved_combo* match_reserved_word(o_string *word)
3589 /* Mostly a list of accepted follow-up reserved words.
3590 * FLAG_END means we are done with the sequence, and are ready
3591 * to turn the compound list into a command.
3592 * FLAG_START means the word must start a new compound list.
3594 static const struct reserved_combo reserved_list[] = {
3596 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3597 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3598 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3599 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3600 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3601 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3603 # if ENABLE_HUSH_LOOPS
3604 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3605 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3606 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3607 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3608 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3609 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3611 # if ENABLE_HUSH_CASE
3612 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3613 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3616 const struct reserved_combo *r;
3618 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3619 if (strcmp(word->data, r->literal) == 0)
3624 /* Return 0: not a keyword, 1: keyword
3626 static int reserved_word(o_string *word, struct parse_context *ctx)
3628 # if ENABLE_HUSH_CASE
3629 static const struct reserved_combo reserved_match = {
3630 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3633 const struct reserved_combo *r;
3635 if (word->has_quoted_part)
3637 r = match_reserved_word(word);
3641 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3642 # if ENABLE_HUSH_CASE
3643 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3644 /* "case word IN ..." - IN part starts first MATCH part */
3645 r = &reserved_match;
3648 if (r->flag == 0) { /* '!' */
3649 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3650 syntax_error("! ! command");
3651 ctx->ctx_res_w = RES_SNTX;
3653 ctx->ctx_inverted = 1;
3656 if (r->flag & FLAG_START) {
3657 struct parse_context *old;
3659 old = xmemdup(ctx, sizeof(*ctx));
3660 debug_printf_parse("push stack %p\n", old);
3661 initialize_context(ctx);
3663 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3664 syntax_error_at(word->data);
3665 ctx->ctx_res_w = RES_SNTX;
3668 /* "{...} fi" is ok. "{...} if" is not
3670 * if { echo foo; } then { echo bar; } fi */
3671 if (ctx->command->group)
3672 done_pipe(ctx, PIPE_SEQ);
3675 ctx->ctx_res_w = r->res;
3676 ctx->old_flag = r->flag;
3677 word->o_assignment = r->assignment_flag;
3678 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3680 if (ctx->old_flag & FLAG_END) {
3681 struct parse_context *old;
3683 done_pipe(ctx, PIPE_SEQ);
3684 debug_printf_parse("pop stack %p\n", ctx->stack);
3686 old->command->group = ctx->list_head;
3687 old->command->cmd_type = CMD_NORMAL;
3689 /* At this point, the compound command's string is in
3690 * ctx->as_string... except for the leading keyword!
3691 * Consider this example: "echo a | if true; then echo a; fi"
3692 * ctx->as_string will contain "true; then echo a; fi",
3693 * with "if " remaining in old->as_string!
3697 int len = old->as_string.length;
3698 /* Concatenate halves */
3699 o_addstr(&old->as_string, ctx->as_string.data);
3700 o_free_unsafe(&ctx->as_string);
3701 /* Find where leading keyword starts in first half */
3702 str = old->as_string.data + len;
3703 if (str > old->as_string.data)
3704 str--; /* skip whitespace after keyword */
3705 while (str > old->as_string.data && isalpha(str[-1]))
3707 /* Ugh, we're done with this horrid hack */
3708 old->command->group_as_string = xstrdup(str);
3709 debug_printf_parse("pop, remembering as:'%s'\n",
3710 old->command->group_as_string);
3713 *ctx = *old; /* physical copy */
3718 #endif /* HAS_KEYWORDS */
3720 /* Word is complete, look at it and update parsing context.
3721 * Normal return is 0. Syntax errors return 1.
3722 * Note: on return, word is reset, but not o_free'd!
3724 static int done_word(o_string *word, struct parse_context *ctx)
3726 struct command *command = ctx->command;
3728 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3729 if (word->length == 0 && !word->has_quoted_part) {
3730 debug_printf_parse("done_word return 0: true null, ignored\n");
3734 if (ctx->pending_redirect) {
3735 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3736 * only if run as "bash", not "sh" */
3737 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3739 * ...the word that follows the redirection operator
3740 * shall be subjected to tilde expansion, parameter expansion,
3741 * command substitution, arithmetic expansion, and quote
3742 * removal. Pathname expansion shall not be performed
3743 * on the word by a non-interactive shell; an interactive
3744 * shell may perform it, but shall do so only when
3745 * the expansion would result in one word."
3747 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3748 /* Cater for >\file case:
3749 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3750 * Same with heredocs:
3751 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3753 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3754 unbackslash(ctx->pending_redirect->rd_filename);
3755 /* Is it <<"HEREDOC"? */
3756 if (word->has_quoted_part) {
3757 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3760 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3761 ctx->pending_redirect = NULL;
3764 # if ENABLE_HUSH_CASE
3765 if (ctx->ctx_dsemicolon
3766 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3768 /* already done when ctx_dsemicolon was set to 1: */
3769 /* ctx->ctx_res_w = RES_MATCH; */
3770 ctx->ctx_dsemicolon = 0;
3773 if (!command->argv /* if it's the first word... */
3774 # if ENABLE_HUSH_LOOPS
3775 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3776 && ctx->ctx_res_w != RES_IN
3778 # if ENABLE_HUSH_CASE
3779 && ctx->ctx_res_w != RES_CASE
3782 int reserved = reserved_word(word, ctx);
3783 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3785 o_reset_to_empty_unquoted(word);
3786 debug_printf_parse("done_word return %d\n",
3787 (ctx->ctx_res_w == RES_SNTX));
3788 return (ctx->ctx_res_w == RES_SNTX);
3791 if (strcmp(word->data, "[[") == 0) {
3792 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3798 if (command->group) {
3799 /* "{ echo foo; } echo bar" - bad */
3800 syntax_error_at(word->data);
3801 debug_printf_parse("done_word return 1: syntax error, "
3802 "groups and arglists don't mix\n");
3806 /* If this word wasn't an assignment, next ones definitely
3807 * can't be assignments. Even if they look like ones. */
3808 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3809 && word->o_assignment != WORD_IS_KEYWORD
3811 word->o_assignment = NOT_ASSIGNMENT;
3813 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3814 command->assignment_cnt++;
3815 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3817 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3818 word->o_assignment = MAYBE_ASSIGNMENT;
3820 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3822 if (word->has_quoted_part
3823 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3824 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3825 /* (otherwise it's known to be not empty and is already safe) */
3827 /* exclude "$@" - it can expand to no word despite "" */
3828 char *p = word->data;
3829 while (p[0] == SPECIAL_VAR_SYMBOL
3830 && (p[1] & 0x7f) == '@'
3831 && p[2] == SPECIAL_VAR_SYMBOL
3836 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3837 debug_print_strings("word appended to argv", command->argv);
3840 #if ENABLE_HUSH_LOOPS
3841 if (ctx->ctx_res_w == RES_FOR) {
3842 if (word->has_quoted_part
3843 || !is_well_formed_var_name(command->argv[0], '\0')
3845 /* bash says just "not a valid identifier" */
3846 syntax_error("not a valid identifier in for");
3849 /* Force FOR to have just one word (variable name) */
3850 /* NB: basically, this makes hush see "for v in ..."
3851 * syntax as if it is "for v; in ...". FOR and IN become
3852 * two pipe structs in parse tree. */
3853 done_pipe(ctx, PIPE_SEQ);
3856 #if ENABLE_HUSH_CASE
3857 /* Force CASE to have just one word */
3858 if (ctx->ctx_res_w == RES_CASE) {
3859 done_pipe(ctx, PIPE_SEQ);
3863 o_reset_to_empty_unquoted(word);
3865 debug_printf_parse("done_word return 0\n");
3870 /* Peek ahead in the input to find out if we have a "&n" construct,
3871 * as in "2>&1", that represents duplicating a file descriptor.
3873 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3874 * REDIRFD_SYNTAX_ERR if syntax error,
3875 * REDIRFD_TO_FILE if no & was seen,
3876 * or the number found.
3879 #define parse_redir_right_fd(as_string, input) \
3880 parse_redir_right_fd(input)
3882 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3888 return REDIRFD_TO_FILE;
3890 ch = i_getch(input); /* get the & */
3891 nommu_addchr(as_string, ch);
3894 ch = i_getch(input);
3895 nommu_addchr(as_string, ch);
3896 return REDIRFD_CLOSE;
3900 while (ch != EOF && isdigit(ch)) {
3901 d = d*10 + (ch-'0');
3903 ch = i_getch(input);
3904 nommu_addchr(as_string, ch);
3909 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3911 bb_error_msg("ambiguous redirect");
3912 return REDIRFD_SYNTAX_ERR;
3915 /* Return code is 0 normal, 1 if a syntax error is detected
3917 static int parse_redirect(struct parse_context *ctx,
3920 struct in_str *input)
3922 struct command *command = ctx->command;
3923 struct redir_struct *redir;
3924 struct redir_struct **redirp;
3927 dup_num = REDIRFD_TO_FILE;
3928 if (style != REDIRECT_HEREDOC) {
3929 /* Check for a '>&1' type redirect */
3930 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3931 if (dup_num == REDIRFD_SYNTAX_ERR)
3934 int ch = i_peek(input);
3935 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3936 if (dup_num) { /* <<-... */
3937 ch = i_getch(input);
3938 nommu_addchr(&ctx->as_string, ch);
3943 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3944 int ch = i_peek(input);
3946 /* >|FILE redirect ("clobbering" >).
3947 * Since we do not support "set -o noclobber" yet,
3948 * >| and > are the same for now. Just eat |.
3950 ch = i_getch(input);
3951 nommu_addchr(&ctx->as_string, ch);
3955 /* Create a new redir_struct and append it to the linked list */
3956 redirp = &command->redirects;
3957 while ((redir = *redirp) != NULL) {
3958 redirp = &(redir->next);
3960 *redirp = redir = xzalloc(sizeof(*redir));
3961 /* redir->next = NULL; */
3962 /* redir->rd_filename = NULL; */
3963 redir->rd_type = style;
3964 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3966 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3967 redir_table[style].descrip);
3969 redir->rd_dup = dup_num;
3970 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3971 /* Erik had a check here that the file descriptor in question
3972 * is legit; I postpone that to "run time"
3973 * A "-" representation of "close me" shows up as a -3 here */
3974 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3975 redir->rd_fd, redir->rd_dup);
3977 #if 0 /* Instead we emit error message at run time */
3978 if (ctx->pending_redirect) {
3979 /* For example, "cmd > <file" */
3980 syntax_error("invalid redirect");
3983 /* Set ctx->pending_redirect, so we know what to do at the
3984 * end of the next parsed word. */
3985 ctx->pending_redirect = redir;
3990 /* If a redirect is immediately preceded by a number, that number is
3991 * supposed to tell which file descriptor to redirect. This routine
3992 * looks for such preceding numbers. In an ideal world this routine
3993 * needs to handle all the following classes of redirects...
3994 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3995 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3996 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3997 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3999 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4001 * ... If n is quoted, the number shall not be recognized as part of
4002 * the redirection expression. For example:
4004 * writes the character 2 into file a"
4005 * We are getting it right by setting ->has_quoted_part on any \<char>
4007 * A -1 return means no valid number was found,
4008 * the caller should use the appropriate default for this redirection.
4010 static int redirect_opt_num(o_string *o)
4014 if (o->data == NULL)
4016 num = bb_strtou(o->data, NULL, 10);
4017 if (errno || num < 0)
4019 o_reset_to_empty_unquoted(o);
4024 #define fetch_till_str(as_string, input, word, skip_tabs) \
4025 fetch_till_str(input, word, skip_tabs)
4027 static char *fetch_till_str(o_string *as_string,
4028 struct in_str *input,
4032 o_string heredoc = NULL_O_STRING;
4034 int prev = 0; /* not \ */
4040 ch = i_getch(input);
4042 nommu_addchr(as_string, ch);
4043 if (ch == '\n' || ch == EOF) {
4045 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4046 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4047 heredoc.data[past_EOL] = '\0';
4048 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4049 return heredoc.data;
4052 /* This is a new line.
4053 * Remember position and backslash-escaping status.
4055 o_addchr(&heredoc, ch);
4058 past_EOL = heredoc.length;
4059 /* Get 1st char of next line, possibly skipping leading tabs */
4061 ch = i_getch(input);
4063 nommu_addchr(as_string, ch);
4064 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4065 /* If this immediately ended the line,
4066 * go back to end-of-line checks.
4069 goto check_heredoc_end;
4074 o_free_unsafe(&heredoc);
4077 o_addchr(&heredoc, ch);
4078 nommu_addchr(as_string, ch);
4079 if (prev == '\\' && ch == '\\')
4080 /* Correctly handle foo\\<eol> (not a line cont.) */
4081 prev = 0; /* not \ */
4087 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4088 * and load them all. There should be exactly heredoc_cnt of them.
4090 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4092 struct pipe *pi = ctx->list_head;
4094 while (pi && heredoc_cnt) {
4096 struct command *cmd = pi->cmds;
4098 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4100 cmd->argv ? cmd->argv[0] : "NONE");
4101 for (i = 0; i < pi->num_cmds; i++) {
4102 struct redir_struct *redir = cmd->redirects;
4104 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4105 i, cmd->argv ? cmd->argv[0] : "NONE");
4107 if (redir->rd_type == REDIRECT_HEREDOC) {
4110 redir->rd_type = REDIRECT_HEREDOC2;
4111 /* redir->rd_dup is (ab)used to indicate <<- */
4112 p = fetch_till_str(&ctx->as_string, input,
4113 redir->rd_filename, redir->rd_dup);
4115 syntax_error("unexpected EOF in here document");
4118 free(redir->rd_filename);
4119 redir->rd_filename = p;
4122 redir = redir->next;
4129 /* Should be 0. If it isn't, it's a parse error */
4131 bb_error_msg_and_die("heredoc BUG 2");
4137 static int run_list(struct pipe *pi);
4139 #define parse_stream(pstring, input, end_trigger) \
4140 parse_stream(input, end_trigger)
4142 static struct pipe *parse_stream(char **pstring,
4143 struct in_str *input,
4147 #if !ENABLE_HUSH_FUNCTIONS
4148 #define parse_group(dest, ctx, input, ch) \
4149 parse_group(ctx, input, ch)
4151 static int parse_group(o_string *dest, struct parse_context *ctx,
4152 struct in_str *input, int ch)
4154 /* dest contains characters seen prior to ( or {.
4155 * Typically it's empty, but for function defs,
4156 * it contains function name (without '()'). */
4157 struct pipe *pipe_list;
4159 struct command *command = ctx->command;
4161 debug_printf_parse("parse_group entered\n");
4162 #if ENABLE_HUSH_FUNCTIONS
4163 if (ch == '(' && !dest->has_quoted_part) {
4165 if (done_word(dest, ctx))
4168 goto skip; /* (... */
4169 if (command->argv[1]) { /* word word ... (... */
4170 syntax_error_unexpected_ch('(');
4173 /* it is "word(..." or "word (..." */
4175 ch = i_getch(input);
4176 while (ch == ' ' || ch == '\t');
4178 syntax_error_unexpected_ch(ch);
4181 nommu_addchr(&ctx->as_string, ch);
4183 ch = i_getch(input);
4184 while (ch == ' ' || ch == '\t' || ch == '\n');
4186 syntax_error_unexpected_ch(ch);
4189 nommu_addchr(&ctx->as_string, ch);
4190 command->cmd_type = CMD_FUNCDEF;
4195 #if 0 /* Prevented by caller */
4196 if (command->argv /* word [word]{... */
4197 || dest->length /* word{... */
4198 || dest->has_quoted_part /* ""{... */
4201 debug_printf_parse("parse_group return 1: "
4202 "syntax error, groups and arglists don't mix\n");
4207 #if ENABLE_HUSH_FUNCTIONS
4213 command->cmd_type = CMD_SUBSHELL;
4215 /* bash does not allow "{echo...", requires whitespace */
4217 if (ch != ' ' && ch != '\t' && ch != '\n'
4218 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4220 syntax_error_unexpected_ch(ch);
4224 ch = i_getch(input);
4225 nommu_addchr(&ctx->as_string, ch);
4231 # define as_string NULL
4233 char *as_string = NULL;
4235 pipe_list = parse_stream(&as_string, input, endch);
4238 o_addstr(&ctx->as_string, as_string);
4240 /* empty ()/{} or parse error? */
4241 if (!pipe_list || pipe_list == ERR_PTR) {
4242 /* parse_stream already emitted error msg */
4245 debug_printf_parse("parse_group return 1: "
4246 "parse_stream returned %p\n", pipe_list);
4249 command->group = pipe_list;
4251 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4252 command->group_as_string = as_string;
4253 debug_printf_parse("end of group, remembering as:'%s'\n",
4254 command->group_as_string);
4258 debug_printf_parse("parse_group return 0\n");
4260 /* command remains "open", available for possible redirects */
4263 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4268 ch = i_getch(input);
4271 ch2 = i_peek(input);
4274 /* backslash+newline, skip it */
4279 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4287 ch2 = i_peek2(input);
4290 /* backslash+newline, skip it */
4296 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4297 /* Subroutines for copying $(...) and `...` things */
4298 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4300 static int add_till_single_quote(o_string *dest, struct in_str *input)
4303 int ch = i_getch(input);
4305 syntax_error_unterm_ch('\'');
4313 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4314 static int add_till_double_quote(o_string *dest, struct in_str *input)
4317 int ch = i_getch(input);
4319 syntax_error_unterm_ch('"');
4324 if (ch == '\\') { /* \x. Copy both chars. */
4326 ch = i_getch(input);
4330 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4335 //if (ch == '$') ...
4338 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4340 * "Within the backquoted style of command substitution, backslash
4341 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4342 * The search for the matching backquote shall be satisfied by the first
4343 * backquote found without a preceding backslash; during this search,
4344 * if a non-escaped backquote is encountered within a shell comment,
4345 * a here-document, an embedded command substitution of the $(command)
4346 * form, or a quoted string, undefined results occur. A single-quoted
4347 * or double-quoted string that begins, but does not end, within the
4348 * "`...`" sequence produces undefined results."
4350 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4352 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4355 int ch = i_getch(input);
4359 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4360 ch = i_getch(input);
4364 && (!in_dquote || ch != '"')
4366 o_addchr(dest, '\\');
4370 syntax_error_unterm_ch('`');
4376 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4377 * quoting and nested ()s.
4378 * "With the $(command) style of command substitution, all characters
4379 * following the open parenthesis to the matching closing parenthesis
4380 * constitute the command. Any valid shell script can be used for command,
4381 * except a script consisting solely of redirections which produces
4382 * unspecified results."
4384 * echo $(echo '(TEST)' BEST) (TEST) BEST
4385 * echo $(echo 'TEST)' BEST) TEST) BEST
4386 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4388 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4389 * can contain arbitrary constructs, just like $(cmd).
4390 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4391 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4393 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4394 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4397 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4398 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4399 char end_char2 = end_ch >> 8;
4401 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4404 ch = i_getch(input);
4406 syntax_error_unterm_ch(end_ch);
4410 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4416 /* we look for closing )) of $((EXPR)) */
4417 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4418 i_getch(input); /* eat second ')' */
4423 if (ch == '(' || ch == '{') {
4424 ch = (ch == '(' ? ')' : '}');
4425 if (!add_till_closing_bracket(dest, input, ch))
4431 if (!add_till_single_quote(dest, input))
4437 if (!add_till_double_quote(dest, input))
4443 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4449 /* \x. Copy verbatim. Important for \(, \) */
4450 ch = i_getch(input);
4452 syntax_error_unterm_ch(')');
4457 /* "backslash+newline", ignore both */
4458 o_delchr(dest); /* undo insertion of '\' */
4468 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4470 /* Return code: 0 for OK, 1 for syntax error */
4472 #define parse_dollar(as_string, dest, input, quote_mask) \
4473 parse_dollar(dest, input, quote_mask)
4474 #define as_string NULL
4476 static int parse_dollar(o_string *as_string,
4478 struct in_str *input, unsigned char quote_mask)
4480 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4482 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4484 ch = i_getch(input);
4485 nommu_addchr(as_string, ch);
4487 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4489 debug_printf_parse(": '%c'\n", ch);
4490 o_addchr(dest, ch | quote_mask);
4492 ch = i_peek_and_eat_bkslash_nl(input);
4493 if (!isalnum(ch) && ch != '_') {
4494 /* End of variable name reached */
4497 ch = i_getch(input);
4498 nommu_addchr(as_string, ch);
4500 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4501 } else if (isdigit(ch)) {
4503 ch = i_getch(input);
4504 nommu_addchr(as_string, ch);
4505 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4506 debug_printf_parse(": '%c'\n", ch);
4507 o_addchr(dest, ch | quote_mask);
4508 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4509 } else switch (ch) {
4511 case '!': /* last bg pid */
4512 case '?': /* last exit code */
4513 case '#': /* number of args */
4514 case '*': /* args */
4515 case '@': /* args */
4516 goto make_one_char_var;
4520 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4522 ch = i_getch(input); /* eat '{' */
4523 nommu_addchr(as_string, ch);
4525 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4526 /* It should be ${?}, or ${#var},
4527 * or even ${?+subst} - operator acting on a special variable,
4528 * or the beginning of variable name.
4531 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4534 syntax_error_unterm_str("${name}");
4535 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4538 nommu_addchr(as_string, ch);
4542 /* It's possible to just call add_till_closing_bracket() at this point.
4543 * However, this regresses some of our testsuite cases
4544 * which check invalid constructs like ${%}.
4545 * Oh well... let's check that the var name part is fine... */
4551 debug_printf_parse(": '%c'\n", ch);
4553 ch = i_getch(input);
4554 nommu_addchr(as_string, ch);
4558 if (!isalnum(ch) && ch != '_') {
4560 unsigned char last_ch;
4561 /* handle parameter expansions
4562 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4564 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4565 if (len_single_ch != '#'
4566 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4567 || i_peek(input) != '}'
4569 goto bad_dollar_syntax;
4571 /* else: it's "length of C" ${#C} op,
4572 * where C is a single char
4573 * special var name, e.g. ${#!}.
4576 /* Eat everything until closing '}' (or ':') */
4580 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4582 /* It's ${var:N[:M]} thing */
4583 end_ch = '}' * 0x100 + ':';
4585 if (BASH_PATTERN_SUBST
4588 /* It's ${var/[/]pattern[/repl]} thing */
4589 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4591 nommu_addchr(as_string, '/');
4594 end_ch = '}' * 0x100 + '/';
4600 #if ENABLE_HUSH_DOLLAR_OPS
4601 last_ch = add_till_closing_bracket(dest, input, end_ch);
4602 if (last_ch == 0) /* error? */
4605 #error Simple code to only allow ${var} is not implemented
4608 o_addstr(as_string, dest->data + pos);
4609 o_addchr(as_string, last_ch);
4612 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4613 && (end_ch & 0xff00)
4615 /* close the first block: */
4616 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4617 /* while parsing N from ${var:N[:M]}
4618 * or pattern from ${var/[/]pattern[/repl]} */
4619 if ((end_ch & 0xff) == last_ch) {
4620 /* got ':' or '/'- parse the rest */
4625 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4626 /* it's ${var:N} - emulate :999999999 */
4627 o_addstr(dest, "999999999");
4628 } /* else: it's ${var/[/]pattern} */
4632 len_single_ch = 0; /* it can't be ${#C} op */
4634 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4637 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4641 ch = i_getch(input);
4642 nommu_addchr(as_string, ch);
4643 # if ENABLE_FEATURE_SH_MATH
4644 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4645 ch = i_getch(input);
4646 nommu_addchr(as_string, ch);
4647 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4648 o_addchr(dest, /*quote_mask |*/ '+');
4651 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4652 return 0; /* error */
4654 o_addstr(as_string, dest->data + pos);
4655 o_addchr(as_string, ')');
4656 o_addchr(as_string, ')');
4658 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4662 # if ENABLE_HUSH_TICK
4663 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4664 o_addchr(dest, quote_mask | '`');
4667 if (!add_till_closing_bracket(dest, input, ')'))
4668 return 0; /* error */
4670 o_addstr(as_string, dest->data + pos);
4671 o_addchr(as_string, ')');
4673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4679 ch = i_getch(input);
4680 nommu_addchr(as_string, ch);
4681 ch = i_peek_and_eat_bkslash_nl(input);
4682 if (isalnum(ch)) { /* it's $_name or $_123 */
4687 /* TODO: $_ and $-: */
4688 /* $_ Shell or shell script name; or last argument of last command
4689 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4690 * but in command's env, set to full pathname used to invoke it */
4691 /* $- Option flags set by set builtin or shell options (-i etc) */
4693 o_addQchr(dest, '$');
4695 debug_printf_parse("parse_dollar return 1 (ok)\n");
4701 # if BASH_PATTERN_SUBST
4702 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4703 encode_string(dest, input, dquote_end, process_bkslash)
4705 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4706 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4707 encode_string(dest, input, dquote_end)
4709 #define as_string NULL
4713 # if BASH_PATTERN_SUBST
4714 /* all parameters are needed, no macro tricks */
4716 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4717 encode_string(as_string, dest, input, dquote_end)
4720 static int encode_string(o_string *as_string,
4722 struct in_str *input,
4724 int process_bkslash)
4726 #if !BASH_PATTERN_SUBST
4727 const int process_bkslash = 1;
4733 ch = i_getch(input);
4735 nommu_addchr(as_string, ch);
4736 if (ch == dquote_end) { /* may be only '"' or EOF */
4737 debug_printf_parse("encode_string return 1 (ok)\n");
4740 /* note: can't move it above ch == dquote_end check! */
4742 syntax_error_unterm_ch('"');
4743 return 0; /* error */
4747 next = i_peek(input);
4749 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4750 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4751 if (process_bkslash && ch == '\\') {
4753 syntax_error("\\<eof>");
4757 * "The backslash retains its special meaning [in "..."]
4758 * only when followed by one of the following characters:
4759 * $, `, ", \, or <newline>. A double quote may be quoted
4760 * within double quotes by preceding it with a backslash."
4761 * NB: in (unquoted) heredoc, above does not apply to ",
4762 * therefore we check for it by "next == dquote_end" cond.
4764 if (next == dquote_end || strchr("$`\\\n", next)) {
4765 ch = i_getch(input); /* eat next */
4767 goto again; /* skip \<newline> */
4768 } /* else: ch remains == '\\', and we double it below: */
4769 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4770 nommu_addchr(as_string, ch);
4774 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4775 debug_printf_parse("encode_string return 0: "
4776 "parse_dollar returned 0 (error)\n");
4781 #if ENABLE_HUSH_TICK
4783 //unsigned pos = dest->length;
4784 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4785 o_addchr(dest, 0x80 | '`');
4786 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4787 return 0; /* error */
4788 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4789 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4793 o_addQchr(dest, ch);
4799 * Scan input until EOF or end_trigger char.
4800 * Return a list of pipes to execute, or NULL on EOF
4801 * or if end_trigger character is met.
4802 * On syntax error, exit if shell is not interactive,
4803 * reset parsing machinery and start parsing anew,
4804 * or return ERR_PTR.
4806 static struct pipe *parse_stream(char **pstring,
4807 struct in_str *input,
4810 struct parse_context ctx;
4811 o_string dest = NULL_O_STRING;
4814 /* Single-quote triggers a bypass of the main loop until its mate is
4815 * found. When recursing, quote state is passed in via dest->o_expflags.
4817 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4818 end_trigger ? end_trigger : 'X');
4821 /* If very first arg is "" or '', dest.data may end up NULL.
4822 * Preventing this: */
4823 o_addchr(&dest, '\0');
4826 /* We used to separate words on $IFS here. This was wrong.
4827 * $IFS is used only for word splitting when $var is expanded,
4828 * here we should use blank chars as separators, not $IFS
4831 if (MAYBE_ASSIGNMENT != 0)
4832 dest.o_assignment = MAYBE_ASSIGNMENT;
4833 initialize_context(&ctx);
4836 const char *is_blank;
4837 const char *is_special;
4841 redir_type redir_style;
4843 ch = i_getch(input);
4844 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4845 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4850 syntax_error_unterm_str("here document");
4853 if (end_trigger == ')') {
4854 syntax_error_unterm_ch('(');
4857 if (end_trigger == '}') {
4858 syntax_error_unterm_ch('{');
4862 if (done_word(&dest, &ctx)) {
4866 done_pipe(&ctx, PIPE_SEQ);
4868 /* If we got nothing... */
4869 /* (this makes bare "&" cmd a no-op.
4870 * bash says: "syntax error near unexpected token '&'") */
4871 if (pi->num_cmds == 0
4872 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4878 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4880 *pstring = ctx.as_string.data;
4882 o_free_unsafe(&ctx.as_string);
4885 debug_printf_parse("parse_stream return %p\n", pi);
4888 nommu_addchr(&ctx.as_string, ch);
4892 next = i_peek(input);
4894 is_special = "{}<>;&|()#'" /* special outside of "str" */
4895 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4896 /* Are { and } special here? */
4897 if (ctx.command->argv /* word [word]{... - non-special */
4898 || dest.length /* word{... - non-special */
4899 || dest.has_quoted_part /* ""{... - non-special */
4900 || (next != ';' /* }; - special */
4901 && next != ')' /* }) - special */
4902 && next != '(' /* {( - special */
4903 && next != '&' /* }& and }&& ... - special */
4904 && next != '|' /* }|| ... - special */
4905 && !strchr(defifs, next) /* {word - non-special */
4908 /* They are not special, skip "{}" */
4911 is_special = strchr(is_special, ch);
4912 is_blank = strchr(defifs, ch);
4914 if (!is_special && !is_blank) { /* ordinary char */
4916 o_addQchr(&dest, ch);
4917 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4918 || dest.o_assignment == WORD_IS_KEYWORD)
4920 && is_well_formed_var_name(dest.data, '=')
4922 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4923 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4929 if (done_word(&dest, &ctx)) {
4933 /* Is this a case when newline is simply ignored?
4935 * "cmd | <newline> cmd ..."
4936 * "case ... in <newline> word) ..."
4938 if (IS_NULL_CMD(ctx.command)
4939 && dest.length == 0 && !dest.has_quoted_part
4941 /* This newline can be ignored. But...
4942 * Without check #1, interactive shell
4943 * ignores even bare <newline>,
4944 * and shows the continuation prompt:
4945 * ps1_prompt$ <enter>
4946 * ps2> _ <=== wrong, should be ps1
4947 * Without check #2, "cmd & <newline>"
4948 * is similarly mistreated.
4949 * (BTW, this makes "cmd & cmd"
4950 * and "cmd && cmd" non-orthogonal.
4951 * Really, ask yourself, why
4952 * "cmd && <newline>" doesn't start
4953 * cmd but waits for more input?
4954 * The only reason is that it might be
4955 * a "cmd1 && <nl> cmd2 &" construct,
4956 * cmd1 may need to run in BG).
4958 struct pipe *pi = ctx.list_head;
4959 if (pi->num_cmds != 0 /* check #1 */
4960 && pi->followup != PIPE_BG /* check #2 */
4965 /* Treat newline as a command separator. */
4966 done_pipe(&ctx, PIPE_SEQ);
4967 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4969 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4974 dest.o_assignment = MAYBE_ASSIGNMENT;
4975 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4977 /* note: if (is_blank) continue;
4978 * will still trigger for us */
4982 /* "cmd}" or "cmd }..." without semicolon or &:
4983 * } is an ordinary char in this case, even inside { cmd; }
4984 * Pathological example: { ""}; } should exec "}" cmd
4987 if (dest.length != 0 /* word} */
4988 || dest.has_quoted_part /* ""} */
4992 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4993 /* Generally, there should be semicolon: "cmd; }"
4994 * However, bash allows to omit it if "cmd" is
4995 * a group. Examples:
4998 * { echo 0 >&2 | { echo 1; } }
4999 * { while false; do :; done }
5000 * { case a in b) ;; esac }
5002 if (ctx.command->group)
5006 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5007 /* Can't be an end of {cmd}, skip the check */
5008 goto skip_end_trigger;
5009 /* else: } does terminate a group */
5012 if (end_trigger && end_trigger == ch
5013 && (ch != ';' || heredoc_cnt == 0)
5014 #if ENABLE_HUSH_CASE
5016 || ctx.ctx_res_w != RES_MATCH
5017 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5022 /* This is technically valid:
5023 * { cat <<HERE; }; echo Ok
5027 * but we don't support this.
5028 * We require heredoc to be in enclosing {}/(),
5031 syntax_error_unterm_str("here document");
5034 if (done_word(&dest, &ctx)) {
5037 done_pipe(&ctx, PIPE_SEQ);
5038 dest.o_assignment = MAYBE_ASSIGNMENT;
5039 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5040 /* Do we sit outside of any if's, loops or case's? */
5042 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5046 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5048 *pstring = ctx.as_string.data;
5050 o_free_unsafe(&ctx.as_string);
5052 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5053 /* Example: bare "{ }", "()" */
5054 G.last_exitcode = 2; /* bash compat */
5055 syntax_error_unexpected_ch(ch);
5058 debug_printf_parse("parse_stream return %p: "
5059 "end_trigger char found\n",
5062 return ctx.list_head;
5069 /* Catch <, > before deciding whether this word is
5070 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5073 redir_fd = redirect_opt_num(&dest);
5074 if (done_word(&dest, &ctx)) {
5077 redir_style = REDIRECT_OVERWRITE;
5079 redir_style = REDIRECT_APPEND;
5080 ch = i_getch(input);
5081 nommu_addchr(&ctx.as_string, ch);
5084 else if (next == '(') {
5085 syntax_error(">(process) not supported");
5089 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5091 continue; /* back to top of while (1) */
5093 redir_fd = redirect_opt_num(&dest);
5094 if (done_word(&dest, &ctx)) {
5097 redir_style = REDIRECT_INPUT;
5099 redir_style = REDIRECT_HEREDOC;
5101 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5102 ch = i_getch(input);
5103 nommu_addchr(&ctx.as_string, ch);
5104 } else if (next == '>') {
5105 redir_style = REDIRECT_IO;
5106 ch = i_getch(input);
5107 nommu_addchr(&ctx.as_string, ch);
5110 else if (next == '(') {
5111 syntax_error("<(process) not supported");
5115 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5117 continue; /* back to top of while (1) */
5119 if (dest.length == 0 && !dest.has_quoted_part) {
5120 /* skip "#comment" */
5123 if (ch == EOF || ch == '\n')
5126 /* note: we do not add it to &ctx.as_string */
5128 nommu_addchr(&ctx.as_string, '\n');
5129 continue; /* back to top of while (1) */
5134 /* It's "\<newline>" */
5136 /* Remove trailing '\' from ctx.as_string */
5137 ctx.as_string.data[--ctx.as_string.length] = '\0';
5139 ch = i_getch(input); /* eat it */
5140 continue; /* back to top of while (1) */
5145 if (dest.o_assignment == MAYBE_ASSIGNMENT
5146 /* check that we are not in word in "a=1 2>word b=1": */
5147 && !ctx.pending_redirect
5149 /* ch is a special char and thus this word
5150 * cannot be an assignment */
5151 dest.o_assignment = NOT_ASSIGNMENT;
5152 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5155 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5158 case '#': /* non-comment #: "echo a#b" etc */
5159 o_addQchr(&dest, ch);
5163 syntax_error("\\<eof>");
5166 ch = i_getch(input);
5167 /* note: ch != '\n' (that case does not reach this place) */
5168 o_addchr(&dest, '\\');
5169 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5170 o_addchr(&dest, ch);
5171 nommu_addchr(&ctx.as_string, ch);
5172 /* Example: echo Hello \2>file
5173 * we need to know that word 2 is quoted */
5174 dest.has_quoted_part = 1;
5177 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5178 debug_printf_parse("parse_stream parse error: "
5179 "parse_dollar returned 0 (error)\n");
5184 dest.has_quoted_part = 1;
5185 if (next == '\'' && !ctx.pending_redirect) {
5186 insert_empty_quoted_str_marker:
5187 nommu_addchr(&ctx.as_string, next);
5188 i_getch(input); /* eat second ' */
5189 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5190 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5193 ch = i_getch(input);
5195 syntax_error_unterm_ch('\'');
5198 nommu_addchr(&ctx.as_string, ch);
5201 o_addqchr(&dest, ch);
5206 dest.has_quoted_part = 1;
5207 if (next == '"' && !ctx.pending_redirect)
5208 goto insert_empty_quoted_str_marker;
5209 if (dest.o_assignment == NOT_ASSIGNMENT)
5210 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5211 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5213 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5215 #if ENABLE_HUSH_TICK
5217 USE_FOR_NOMMU(unsigned pos;)
5219 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5220 o_addchr(&dest, '`');
5221 USE_FOR_NOMMU(pos = dest.length;)
5222 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5225 o_addstr(&ctx.as_string, dest.data + pos);
5226 o_addchr(&ctx.as_string, '`');
5228 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5229 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5234 #if ENABLE_HUSH_CASE
5237 if (done_word(&dest, &ctx)) {
5240 done_pipe(&ctx, PIPE_SEQ);
5241 #if ENABLE_HUSH_CASE
5242 /* Eat multiple semicolons, detect
5243 * whether it means something special */
5248 ch = i_getch(input);
5249 nommu_addchr(&ctx.as_string, ch);
5250 if (ctx.ctx_res_w == RES_CASE_BODY) {
5251 ctx.ctx_dsemicolon = 1;
5252 ctx.ctx_res_w = RES_MATCH;
5258 /* We just finished a cmd. New one may start
5259 * with an assignment */
5260 dest.o_assignment = MAYBE_ASSIGNMENT;
5261 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5264 if (done_word(&dest, &ctx)) {
5268 ch = i_getch(input);
5269 nommu_addchr(&ctx.as_string, ch);
5270 done_pipe(&ctx, PIPE_AND);
5272 done_pipe(&ctx, PIPE_BG);
5276 if (done_word(&dest, &ctx)) {
5279 #if ENABLE_HUSH_CASE
5280 if (ctx.ctx_res_w == RES_MATCH)
5281 break; /* we are in case's "word | word)" */
5283 if (next == '|') { /* || */
5284 ch = i_getch(input);
5285 nommu_addchr(&ctx.as_string, ch);
5286 done_pipe(&ctx, PIPE_OR);
5288 /* we could pick up a file descriptor choice here
5289 * with redirect_opt_num(), but bash doesn't do it.
5290 * "echo foo 2| cat" yields "foo 2". */
5295 #if ENABLE_HUSH_CASE
5296 /* "case... in [(]word)..." - skip '(' */
5297 if (ctx.ctx_res_w == RES_MATCH
5298 && ctx.command->argv == NULL /* not (word|(... */
5299 && dest.length == 0 /* not word(... */
5300 && dest.has_quoted_part == 0 /* not ""(... */
5306 if (parse_group(&dest, &ctx, input, ch) != 0) {
5311 #if ENABLE_HUSH_CASE
5312 if (ctx.ctx_res_w == RES_MATCH)
5316 /* proper use of this character is caught by end_trigger:
5317 * if we see {, we call parse_group(..., end_trigger='}')
5318 * and it will match } earlier (not here). */
5319 G.last_exitcode = 2;
5320 syntax_error_unexpected_ch(ch);
5324 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5329 G.last_exitcode = 1;
5332 struct parse_context *pctx;
5333 IF_HAS_KEYWORDS(struct parse_context *p2;)
5335 /* Clean up allocated tree.
5336 * Sample for finding leaks on syntax error recovery path.
5337 * Run it from interactive shell, watch pmap `pidof hush`.
5338 * while if false; then false; fi; do break; fi
5339 * Samples to catch leaks at execution:
5340 * while if (true | { true;}); then echo ok; fi; do break; done
5341 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5345 /* Update pipe/command counts,
5346 * otherwise freeing may miss some */
5347 done_pipe(pctx, PIPE_SEQ);
5348 debug_printf_clean("freeing list %p from ctx %p\n",
5349 pctx->list_head, pctx);
5350 debug_print_tree(pctx->list_head, 0);
5351 free_pipe_list(pctx->list_head);
5352 debug_printf_clean("freed list %p\n", pctx->list_head);
5354 o_free_unsafe(&pctx->as_string);
5356 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5360 IF_HAS_KEYWORDS(pctx = p2;)
5361 } while (HAS_KEYWORDS && pctx);
5374 /*** Execution routines ***/
5376 /* Expansion can recurse, need forward decls: */
5377 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5378 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5379 #define expand_string_to_string(str, do_unbackslash) \
5380 expand_string_to_string(str)
5382 static char *expand_string_to_string(const char *str, int do_unbackslash);
5383 #if ENABLE_HUSH_TICK
5384 static int process_command_subs(o_string *dest, const char *s);
5387 /* expand_strvec_to_strvec() takes a list of strings, expands
5388 * all variable references within and returns a pointer to
5389 * a list of expanded strings, possibly with larger number
5390 * of strings. (Think VAR="a b"; echo $VAR).
5391 * This new list is allocated as a single malloc block.
5392 * NULL-terminated list of char* pointers is at the beginning of it,
5393 * followed by strings themselves.
5394 * Caller can deallocate entire list by single free(list). */
5396 /* A horde of its helpers come first: */
5398 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5400 while (--len >= 0) {
5403 #if ENABLE_HUSH_BRACE_EXPANSION
5404 if (c == '{' || c == '}') {
5405 /* { -> \{, } -> \} */
5407 /* And now we want to add { or } and continue:
5410 * luckily, just falling through achieves this.
5416 /* \z -> \\\z; \<eol> -> \\<eol> */
5421 o_addchr(o, *str++);
5427 /* Store given string, finalizing the word and starting new one whenever
5428 * we encounter IFS char(s). This is used for expanding variable values.
5429 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5430 * Return in *ended_with_ifs:
5431 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5433 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5435 int last_is_ifs = 0;
5440 if (!*str) /* EOL - do not finalize word */
5442 word_len = strcspn(str, G.ifs);
5444 /* We have WORD_LEN leading non-IFS chars */
5445 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5446 o_addblock(output, str, word_len);
5448 /* Protect backslashes against globbing up :)
5449 * Example: "v='\*'; echo b$v" prints "b\*"
5450 * (and does not try to glob on "*")
5452 o_addblock_duplicate_backslash(output, str, word_len);
5453 /*/ Why can't we do it easier? */
5454 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5455 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5459 if (!*str) /* EOL - do not finalize word */
5463 /* We know str here points to at least one IFS char */
5465 str += strspn(str, G.ifs); /* skip IFS chars */
5466 if (!*str) /* EOL - do not finalize word */
5469 /* Start new word... but not always! */
5470 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5471 if (output->has_quoted_part
5472 /* Case "v=' a'; echo $v":
5473 * here nothing precedes the space in $v expansion,
5474 * therefore we should not finish the word
5475 * (IOW: if there *is* word to finalize, only then do it):
5477 || (n > 0 && output->data[output->length - 1])
5479 o_addchr(output, '\0');
5480 debug_print_list("expand_on_ifs", output, n);
5481 n = o_save_ptr(output, n);
5486 *ended_with_ifs = last_is_ifs;
5487 debug_print_list("expand_on_ifs[1]", output, n);
5491 /* Helper to expand $((...)) and heredoc body. These act as if
5492 * they are in double quotes, with the exception that they are not :).
5493 * Just the rules are similar: "expand only $var and `cmd`"
5495 * Returns malloced string.
5496 * As an optimization, we return NULL if expansion is not needed.
5498 #if !BASH_PATTERN_SUBST
5499 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5500 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5501 encode_then_expand_string(str)
5503 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5505 #if !BASH_PATTERN_SUBST
5506 const int do_unbackslash = 1;
5509 struct in_str input;
5510 o_string dest = NULL_O_STRING;
5512 if (!strchr(str, '$')
5513 && !strchr(str, '\\')
5514 #if ENABLE_HUSH_TICK
5515 && !strchr(str, '`')
5521 /* We need to expand. Example:
5522 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5524 setup_string_in_str(&input, str);
5525 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5526 //TODO: error check (encode_string returns 0 on error)?
5527 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5528 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5529 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5530 o_free_unsafe(&dest);
5534 #if ENABLE_FEATURE_SH_MATH
5535 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5537 arith_state_t math_state;
5541 math_state.lookupvar = get_local_var_value;
5542 math_state.setvar = set_local_var_from_halves;
5543 //math_state.endofname = endofname;
5544 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5545 res = arith(&math_state, exp_str ? exp_str : arg);
5548 *errmsg_p = math_state.errmsg;
5549 if (math_state.errmsg)
5550 msg_and_die_if_script(math_state.errmsg);
5555 #if BASH_PATTERN_SUBST
5556 /* ${var/[/]pattern[/repl]} helpers */
5557 static char *strstr_pattern(char *val, const char *pattern, int *size)
5560 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5561 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5568 /* Optimization: if "*pat" did not match the start of "string",
5569 * we know that "tring", "ring" etc will not match too:
5571 if (pattern[0] == '*')
5576 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5578 char *result = NULL;
5579 unsigned res_len = 0;
5580 unsigned repl_len = strlen(repl);
5584 char *s = strstr_pattern(val, pattern, &size);
5588 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5589 strcpy(mempcpy(result + res_len, val, s - val), repl);
5590 res_len += (s - val) + repl_len;
5591 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5597 if (*val && result) {
5598 result = xrealloc(result, res_len + strlen(val) + 1);
5599 strcpy(result + res_len, val);
5600 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5602 debug_printf_varexp("result:'%s'\n", result);
5605 #endif /* BASH_PATTERN_SUBST */
5608 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5610 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5612 const char *val = NULL;
5613 char *to_be_freed = NULL;
5618 char exp_save = exp_save; /* for compiler */
5619 char *exp_saveptr; /* points to expansion operator */
5620 char *exp_word = exp_word; /* for compiler */
5623 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5625 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5627 first_char = arg[0] = arg0 & 0x7f;
5630 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5631 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5632 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5633 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5635 /* It must be length operator: ${#var} */
5639 /* Maybe handle parameter expansion */
5640 if (exp_saveptr /* if 2nd char is one of expansion operators */
5641 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5643 /* ${?:0}, ${#[:]%0} etc */
5644 exp_saveptr = var + 1;
5646 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5647 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5649 exp_op = exp_save = *exp_saveptr;
5651 exp_word = exp_saveptr + 1;
5652 if (exp_op == ':') {
5653 exp_op = *exp_word++;
5654 //TODO: try ${var:} and ${var:bogus} in non-bash config
5656 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5658 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5663 *exp_saveptr = '\0';
5664 } /* else: it's not an expansion op, but bare ${var} */
5667 /* Look up the variable in question */
5668 if (isdigit(var[0])) {
5669 /* parse_dollar should have vetted var for us */
5670 int n = xatoi_positive(var);
5671 if (n < G.global_argc)
5672 val = G.global_argv[n];
5673 /* else val remains NULL: $N with too big N */
5677 val = utoa(G.root_pid);
5679 case '!': /* bg pid */
5680 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5682 case '?': /* exitcode */
5683 val = utoa(G.last_exitcode);
5685 case '#': /* argc */
5686 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5689 val = get_local_var_value(var);
5693 /* Handle any expansions */
5694 if (exp_op == 'L') {
5695 reinit_unicode_for_hush();
5696 debug_printf_expand("expand: length(%s)=", val);
5697 val = utoa(val ? unicode_strlen(val) : 0);
5698 debug_printf_expand("%s\n", val);
5699 } else if (exp_op) {
5700 if (exp_op == '%' || exp_op == '#') {
5701 /* Standard-mandated substring removal ops:
5702 * ${parameter%word} - remove smallest suffix pattern
5703 * ${parameter%%word} - remove largest suffix pattern
5704 * ${parameter#word} - remove smallest prefix pattern
5705 * ${parameter##word} - remove largest prefix pattern
5707 * Word is expanded to produce a glob pattern.
5708 * Then var's value is matched to it and matching part removed.
5710 if (val && val[0]) {
5714 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5715 if (exp_op == *exp_word) /* ## or %% */
5717 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5719 exp_word = exp_exp_word;
5720 /* HACK ALERT. We depend here on the fact that
5721 * G.global_argv and results of utoa and get_local_var_value
5722 * are actually in writable memory:
5723 * scan_and_match momentarily stores NULs there. */
5725 loc = scan_and_match(t, exp_word, scan_flags);
5726 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5727 // exp_op, t, exp_word, loc);
5729 if (loc) { /* match was found */
5730 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5731 val = loc; /* take right part */
5733 val = to_be_freed = xstrndup(val, loc - val); /* left */
5737 #if BASH_PATTERN_SUBST
5738 else if (exp_op == '/' || exp_op == '\\') {
5739 /* It's ${var/[/]pattern[/repl]} thing.
5740 * Note that in encoded form it has TWO parts:
5741 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5742 * and if // is used, it is encoded as \:
5743 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5745 /* Empty variable always gives nothing: */
5746 // "v=''; echo ${v/*/w}" prints "", not "w"
5747 if (val && val[0]) {
5748 /* pattern uses non-standard expansion.
5749 * repl should be unbackslashed and globbed
5750 * by the usual expansion rules:
5752 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5753 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5754 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5755 * v='a bz'; echo ${v/a*z/\z} prints "z"
5756 * (note that a*z _pattern_ is never globbed!)
5758 char *pattern, *repl, *t;
5759 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5761 pattern = xstrdup(exp_word);
5762 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5763 *p++ = SPECIAL_VAR_SYMBOL;
5765 p = strchr(p, SPECIAL_VAR_SYMBOL);
5767 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5768 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5769 /* HACK ALERT. We depend here on the fact that
5770 * G.global_argv and results of utoa and get_local_var_value
5771 * are actually in writable memory:
5772 * replace_pattern momentarily stores NULs there. */
5774 to_be_freed = replace_pattern(t,
5776 (repl ? repl : exp_word),
5778 if (to_be_freed) /* at least one replace happened */
5784 #endif /* BASH_PATTERN_SUBST */
5785 else if (exp_op == ':') {
5786 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5787 /* It's ${var:N[:M]} bashism.
5788 * Note that in encoded form it has TWO parts:
5789 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5794 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5797 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5798 *p++ = SPECIAL_VAR_SYMBOL;
5800 p = strchr(p, SPECIAL_VAR_SYMBOL);
5802 len = expand_and_evaluate_arith(exp_word, &errmsg);
5805 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5807 /* negative beg counts from the end */
5808 beg = (arith_t)strlen(val) + beg;
5809 if (beg < 0) /* ${v: -999999} is "" */
5812 debug_printf_varexp("from val:'%s'\n", val);
5814 /* in bash, len=-n means strlen()-n */
5815 len = (arith_t)strlen(val) - beg + len;
5816 if (len < 0) /* bash compat */
5817 msg_and_die_if_script("%s: substring expression < 0", var);
5819 if (len <= 0 || !val || beg >= strlen(val)) {
5823 /* Paranoia. What if user entered 9999999999999
5824 * which fits in arith_t but not int? */
5827 val = to_be_freed = xstrndup(val + beg, len);
5829 debug_printf_varexp("val:'%s'\n", val);
5830 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5831 msg_and_die_if_script("malformed ${%s:...}", var);
5834 } else { /* one of "-=+?" */
5835 /* Standard-mandated substitution ops:
5836 * ${var?word} - indicate error if unset
5837 * If var is unset, word (or a message indicating it is unset
5838 * if word is null) is written to standard error
5839 * and the shell exits with a non-zero exit status.
5840 * Otherwise, the value of var is substituted.
5841 * ${var-word} - use default value
5842 * If var is unset, word is substituted.
5843 * ${var=word} - assign and use default value
5844 * If var is unset, word is assigned to var.
5845 * In all cases, final value of var is substituted.
5846 * ${var+word} - use alternative value
5847 * If var is unset, null is substituted.
5848 * Otherwise, word is substituted.
5850 * Word is subjected to tilde expansion, parameter expansion,
5851 * command substitution, and arithmetic expansion.
5852 * If word is not needed, it is not expanded.
5854 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5855 * but also treat null var as if it is unset.
5857 int use_word = (!val || ((exp_save == ':') && !val[0]));
5859 use_word = !use_word;
5860 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5861 (exp_save == ':') ? "true" : "false", use_word);
5863 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5865 exp_word = to_be_freed;
5866 if (exp_op == '?') {
5867 /* mimic bash message */
5868 msg_and_die_if_script("%s: %s",
5872 : "parameter null or not set"
5873 /* ash has more specific messages, a-la: */
5874 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
5876 //TODO: how interactive bash aborts expansion mid-command?
5881 if (exp_op == '=') {
5882 /* ${var=[word]} or ${var:=[word]} */
5883 if (isdigit(var[0]) || var[0] == '#') {
5884 /* mimic bash message */
5885 msg_and_die_if_script("$%s: cannot assign in this way", var);
5888 char *new_var = xasprintf("%s=%s", var, val);
5889 set_local_var(new_var, /*flag:*/ 0);
5893 } /* one of "-=+?" */
5895 *exp_saveptr = exp_save;
5901 *to_be_freed_pp = to_be_freed;
5905 /* Expand all variable references in given string, adding words to list[]
5906 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5907 * to be filled). This routine is extremely tricky: has to deal with
5908 * variables/parameters with whitespace, $* and $@, and constructs like
5909 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5910 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5912 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5913 * expansion of right-hand side of assignment == 1-element expand.
5915 char cant_be_null = 0; /* only bit 0x80 matters */
5916 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5919 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5920 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5921 debug_print_list("expand_vars_to_list", output, n);
5922 n = o_save_ptr(output, n);
5923 debug_print_list("expand_vars_to_list[0]", output, n);
5925 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5927 char *to_be_freed = NULL;
5928 const char *val = NULL;
5929 #if ENABLE_HUSH_TICK
5930 o_string subst_result = NULL_O_STRING;
5932 #if ENABLE_FEATURE_SH_MATH
5933 char arith_buf[sizeof(arith_t)*3 + 2];
5937 o_addchr(output, '\0');
5938 n = o_save_ptr(output, n);
5942 o_addblock(output, arg, p - arg);
5943 debug_print_list("expand_vars_to_list[1]", output, n);
5945 p = strchr(p, SPECIAL_VAR_SYMBOL);
5947 /* Fetch special var name (if it is indeed one of them)
5948 * and quote bit, force the bit on if singleword expansion -
5949 * important for not getting v=$@ expand to many words. */
5950 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5952 /* Is this variable quoted and thus expansion can't be null?
5953 * "$@" is special. Even if quoted, it can still
5954 * expand to nothing (not even an empty string),
5955 * thus it is excluded. */
5956 if ((first_ch & 0x7f) != '@')
5957 cant_be_null |= first_ch;
5959 switch (first_ch & 0x7f) {
5960 /* Highest bit in first_ch indicates that var is double-quoted */
5964 if (!G.global_argv[1])
5967 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5968 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5969 while (G.global_argv[i]) {
5970 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5971 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5972 if (G.global_argv[i++][0] && G.global_argv[i]) {
5973 /* this argv[] is not empty and not last:
5974 * put terminating NUL, start new word */
5975 o_addchr(output, '\0');
5976 debug_print_list("expand_vars_to_list[2]", output, n);
5977 n = o_save_ptr(output, n);
5978 debug_print_list("expand_vars_to_list[3]", output, n);
5982 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5983 * and in this case should treat it like '$*' - see 'else...' below */
5984 if (first_ch == ('@'|0x80) /* quoted $@ */
5985 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5988 o_addQstr(output, G.global_argv[i]);
5989 if (++i >= G.global_argc)
5991 o_addchr(output, '\0');
5992 debug_print_list("expand_vars_to_list[4]", output, n);
5993 n = o_save_ptr(output, n);
5995 } else { /* quoted $* (or v="$@" case): add as one word */
5997 o_addQstr(output, G.global_argv[i]);
5998 if (!G.global_argv[++i])
6001 o_addchr(output, G.ifs[0]);
6003 output->has_quoted_part = 1;
6007 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6008 /* "Empty variable", used to make "" etc to not disappear */
6009 output->has_quoted_part = 1;
6011 cant_be_null = 0x80;
6013 #if ENABLE_HUSH_TICK
6014 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6015 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6017 /* Can't just stuff it into output o_string,
6018 * expanded result may need to be globbed
6020 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6021 G.last_exitcode = process_command_subs(&subst_result, arg);
6022 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6023 val = subst_result.data;
6026 #if ENABLE_FEATURE_SH_MATH
6027 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6030 arg++; /* skip '+' */
6031 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6032 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6033 res = expand_and_evaluate_arith(arg, NULL);
6034 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6035 sprintf(arith_buf, ARITH_FMT, res);
6041 val = expand_one_var(&to_be_freed, arg, &p);
6042 IF_HUSH_TICK(store_val:)
6043 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6044 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6045 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6046 if (val && val[0]) {
6047 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6050 } else { /* quoted $VAR, val will be appended below */
6051 output->has_quoted_part = 1;
6052 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6053 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6056 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6058 if (val && val[0]) {
6059 o_addQstr(output, val);
6063 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6064 * Do the check to avoid writing to a const string. */
6065 if (*p != SPECIAL_VAR_SYMBOL)
6066 *p = SPECIAL_VAR_SYMBOL;
6068 #if ENABLE_HUSH_TICK
6069 o_free(&subst_result);
6072 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6076 o_addchr(output, '\0');
6077 n = o_save_ptr(output, n);
6079 debug_print_list("expand_vars_to_list[a]", output, n);
6080 /* this part is literal, and it was already pre-quoted
6081 * if needed (much earlier), do not use o_addQstr here! */
6082 o_addstr_with_NUL(output, arg);
6083 debug_print_list("expand_vars_to_list[b]", output, n);
6084 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6085 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6088 /* allow to reuse list[n] later without re-growth */
6089 output->has_empty_slot = 1;
6091 o_addchr(output, '\0');
6097 static char **expand_variables(char **argv, unsigned expflags)
6101 o_string output = NULL_O_STRING;
6103 output.o_expflags = expflags;
6107 n = expand_vars_to_list(&output, n, *argv);
6110 debug_print_list("expand_variables", &output, n);
6112 /* output.data (malloced in one block) gets returned in "list" */
6113 list = o_finalize_list(&output, n);
6114 debug_print_strings("expand_variables[1]", list);
6118 static char **expand_strvec_to_strvec(char **argv)
6120 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6124 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6126 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6130 /* Used for expansion of right hand of assignments,
6131 * $((...)), heredocs, variable espansion parts.
6133 * NB: should NOT do globbing!
6134 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6136 static char *expand_string_to_string(const char *str, int do_unbackslash)
6138 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6139 const int do_unbackslash = 1;
6141 char *argv[2], **list;
6143 debug_printf_expand("string_to_string<='%s'\n", str);
6144 /* This is generally an optimization, but it also
6145 * handles "", which otherwise trips over !list[0] check below.
6146 * (is this ever happens that we actually get str="" here?)
6148 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6149 //TODO: Can use on strings with \ too, just unbackslash() them?
6150 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6151 return xstrdup(str);
6154 argv[0] = (char*)str;
6156 list = expand_variables(argv, do_unbackslash
6157 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6158 : EXP_FLAG_SINGLEWORD
6161 if (!list[0] || list[1])
6162 bb_error_msg_and_die("BUG in varexp2");
6163 /* actually, just move string 2*sizeof(char*) bytes back */
6164 overlapping_strcpy((char*)list, list[0]);
6166 unbackslash((char*)list);
6167 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6171 /* Used for "eval" builtin and case string */
6172 static char* expand_strvec_to_string(char **argv)
6176 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6177 /* Convert all NULs to spaces */
6182 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6183 bb_error_msg_and_die("BUG in varexp3");
6184 /* bash uses ' ' regardless of $IFS contents */
6189 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6190 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6194 static char **expand_assignments(char **argv, int count)
6199 G.expanded_assignments = p = NULL;
6200 /* Expand assignments into one string each */
6201 for (i = 0; i < count; i++) {
6202 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6204 G.expanded_assignments = NULL;
6209 static void switch_off_special_sigs(unsigned mask)
6212 while ((mask >>= 1) != 0) {
6216 #if ENABLE_HUSH_TRAP
6218 if (G_traps[sig] && !G_traps[sig][0])
6219 /* trap is '', has to remain SIG_IGN */
6222 G_traps[sig] = NULL;
6225 /* We are here only if no trap or trap was not '' */
6226 install_sighandler(sig, SIG_DFL);
6232 void re_execute_shell(char ***to_free, const char *s,
6233 char *g_argv0, char **g_argv,
6234 char **builtin_argv) NORETURN;
6236 static void reset_traps_to_defaults(void)
6238 /* This function is always called in a child shell
6239 * after fork (not vfork, NOMMU doesn't use this function).
6241 IF_HUSH_TRAP(unsigned sig;)
6244 /* Child shells are not interactive.
6245 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6246 * Testcase: (while :; do :; done) + ^Z should background.
6247 * Same goes for SIGTERM, SIGHUP, SIGINT.
6249 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6250 if (!G_traps && !mask)
6251 return; /* already no traps and no special sigs */
6253 /* Switch off special sigs */
6254 switch_off_special_sigs(mask);
6255 # if ENABLE_HUSH_JOB
6256 G_fatal_sig_mask = 0;
6258 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6259 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6260 * remain set in G.special_sig_mask */
6262 # if ENABLE_HUSH_TRAP
6266 /* Reset all sigs to default except ones with empty traps */
6267 for (sig = 0; sig < NSIG; sig++) {
6269 continue; /* no trap: nothing to do */
6270 if (!G_traps[sig][0])
6271 continue; /* empty trap: has to remain SIG_IGN */
6272 /* sig has non-empty trap, reset it: */
6274 G_traps[sig] = NULL;
6275 /* There is no signal for trap 0 (EXIT) */
6278 install_sighandler(sig, pick_sighandler(sig));
6285 static void re_execute_shell(char ***to_free, const char *s,
6286 char *g_argv0, char **g_argv,
6287 char **builtin_argv) NORETURN;
6288 static void re_execute_shell(char ***to_free, const char *s,
6289 char *g_argv0, char **g_argv,
6290 char **builtin_argv)
6292 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6293 /* delims + 2 * (number of bytes in printed hex numbers) */
6294 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6295 char *heredoc_argv[4];
6296 struct variable *cur;
6297 # if ENABLE_HUSH_FUNCTIONS
6298 struct function *funcp;
6302 unsigned long long empty_trap_mask;
6304 if (!g_argv0) { /* heredoc */
6305 argv = heredoc_argv;
6306 argv[0] = (char *) G.argv0_for_re_execing;
6307 argv[1] = (char *) "-<";
6308 argv[2] = (char *) s;
6310 pp = &argv[3]; /* used as pointer to empty environment */
6316 if (pp) while (*pp++)
6319 empty_trap_mask = 0;
6322 for (sig = 1; sig < NSIG; sig++) {
6323 if (G_traps[sig] && !G_traps[sig][0])
6324 empty_trap_mask |= 1LL << sig;
6328 sprintf(param_buf, NOMMU_HACK_FMT
6329 , (unsigned) G.root_pid
6330 , (unsigned) G.root_ppid
6331 , (unsigned) G.last_bg_pid
6332 , (unsigned) G.last_exitcode
6335 IF_HUSH_LOOPS(, G.depth_of_loop)
6337 # undef NOMMU_HACK_FMT
6338 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6339 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6342 for (cur = G.top_var; cur; cur = cur->next) {
6343 if (!cur->flg_export || cur->flg_read_only)
6346 # if ENABLE_HUSH_FUNCTIONS
6347 for (funcp = G.top_func; funcp; funcp = funcp->next)
6353 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6354 *pp++ = (char *) G.argv0_for_re_execing;
6356 for (cur = G.top_var; cur; cur = cur->next) {
6357 if (strcmp(cur->varstr, hush_version_str) == 0)
6359 if (cur->flg_read_only) {
6360 *pp++ = (char *) "-R";
6361 *pp++ = cur->varstr;
6362 } else if (!cur->flg_export) {
6363 *pp++ = (char *) "-V";
6364 *pp++ = cur->varstr;
6367 # if ENABLE_HUSH_FUNCTIONS
6368 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6369 *pp++ = (char *) "-F";
6370 *pp++ = funcp->name;
6371 *pp++ = funcp->body_as_string;
6374 /* We can pass activated traps here. Say, -Tnn:trap_string
6376 * However, POSIX says that subshells reset signals with traps
6378 * I tested bash-3.2 and it not only does that with true subshells
6379 * of the form ( list ), but with any forked children shells.
6380 * I set trap "echo W" WINCH; and then tried:
6382 * { echo 1; sleep 20; echo 2; } &
6383 * while true; do echo 1; sleep 20; echo 2; break; done &
6384 * true | { echo 1; sleep 20; echo 2; } | cat
6386 * In all these cases sending SIGWINCH to the child shell
6387 * did not run the trap. If I add trap "echo V" WINCH;
6388 * _inside_ group (just before echo 1), it works.
6390 * I conclude it means we don't need to pass active traps here.
6392 *pp++ = (char *) "-c";
6395 while (*++builtin_argv)
6396 *pp++ = *builtin_argv;
6397 *pp++ = (char *) "";
6402 /* *pp = NULL; - is already there */
6406 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6407 /* Don't propagate SIG_IGN to the child */
6408 if (SPECIAL_JOBSTOP_SIGS != 0)
6409 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6410 execve(bb_busybox_exec_path, argv, pp);
6411 /* Fallback. Useful for init=/bin/hush usage etc */
6412 if (argv[0][0] == '/')
6413 execve(argv[0], argv, pp);
6414 xfunc_error_retval = 127;
6415 bb_error_msg_and_die("can't re-execute the shell");
6417 #endif /* !BB_MMU */
6420 static int run_and_free_list(struct pipe *pi);
6422 /* Executing from string: eval, sh -c '...'
6423 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6424 * end_trigger controls how often we stop parsing
6425 * NUL: parse all, execute, return
6426 * ';': parse till ';' or newline, execute, repeat till EOF
6428 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6430 /* Why we need empty flag?
6431 * An obscure corner case "false; ``; echo $?":
6432 * empty command in `` should still set $? to 0.
6433 * But we can't just set $? to 0 at the start,
6434 * this breaks "false; echo `echo $?`" case.
6438 struct pipe *pipe_list;
6440 #if ENABLE_HUSH_INTERACTIVE
6441 if (end_trigger == ';')
6442 inp->promptmode = 0; /* PS1 */
6444 pipe_list = parse_stream(NULL, inp, end_trigger);
6445 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6446 /* If we are in "big" script
6447 * (not in `cmd` or something similar)...
6449 if (pipe_list == ERR_PTR && end_trigger == ';') {
6450 /* Discard cached input (rest of line) */
6451 int ch = inp->last_char;
6452 while (ch != EOF && ch != '\n') {
6453 //bb_error_msg("Discarded:'%c'", ch);
6458 /* This stream isn't empty */
6462 if (!pipe_list && empty)
6463 G.last_exitcode = 0;
6466 debug_print_tree(pipe_list, 0);
6467 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6468 run_and_free_list(pipe_list);
6470 if (G_flag_return_in_progress == 1)
6475 static void parse_and_run_string(const char *s)
6477 struct in_str input;
6478 setup_string_in_str(&input, s);
6479 parse_and_run_stream(&input, '\0');
6482 static void parse_and_run_file(FILE *f)
6484 struct in_str input;
6485 setup_file_in_str(&input, f);
6486 parse_and_run_stream(&input, ';');
6489 #if ENABLE_HUSH_TICK
6490 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6495 char **to_free = NULL;
6499 pid = BB_MMU ? xfork() : xvfork();
6500 if (pid == 0) { /* child */
6501 disable_restore_tty_pgrp_on_exit();
6502 /* Process substitution is not considered to be usual
6503 * 'command execution'.
6504 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6511 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6512 close(channel[0]); /* NB: close _first_, then move fd! */
6513 xmove_fd(channel[1], 1);
6514 /* Prevent it from trying to handle ctrl-z etc */
6515 IF_HUSH_JOB(G.run_list_level = 1;)
6516 # if ENABLE_HUSH_TRAP
6517 /* Awful hack for `trap` or $(trap).
6519 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6520 * contains an example where "trap" is executed in a subshell:
6522 * save_traps=$(trap)
6524 * eval "$save_traps"
6526 * Standard does not say that "trap" in subshell shall print
6527 * parent shell's traps. It only says that its output
6528 * must have suitable form, but then, in the above example
6529 * (which is not supposed to be normative), it implies that.
6531 * bash (and probably other shell) does implement it
6532 * (traps are reset to defaults, but "trap" still shows them),
6533 * but as a result, "trap" logic is hopelessly messed up:
6536 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6537 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6538 * # true | trap <--- trap is in subshell - no output (ditto)
6539 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6540 * trap -- 'echo Ho' SIGWINCH
6541 * # echo `(trap)` <--- in subshell in subshell - output
6542 * trap -- 'echo Ho' SIGWINCH
6543 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6544 * trap -- 'echo Ho' SIGWINCH
6546 * The rules when to forget and when to not forget traps
6547 * get really complex and nonsensical.
6549 * Our solution: ONLY bare $(trap) or `trap` is special.
6551 s = skip_whitespace(s);
6552 if (is_prefixed_with(s, "trap")
6553 && skip_whitespace(s + 4)[0] == '\0'
6555 static const char *const argv[] = { NULL, NULL };
6556 builtin_trap((char**)argv);
6557 fflush_all(); /* important */
6562 reset_traps_to_defaults();
6563 parse_and_run_string(s);
6564 _exit(G.last_exitcode);
6566 /* We re-execute after vfork on NOMMU. This makes this script safe:
6567 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6568 * huge=`cat BIG` # was blocking here forever
6571 re_execute_shell(&to_free,
6581 # if ENABLE_HUSH_FAST
6583 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6584 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6585 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6587 enable_restore_tty_pgrp_on_exit();
6592 return remember_FILE(xfdopen_for_read(channel[0]));
6595 /* Return code is exit status of the process that is run. */
6596 static int process_command_subs(o_string *dest, const char *s)
6599 struct in_str pipe_str;
6601 int status, ch, eol_cnt;
6603 fp = generate_stream_from_string(s, &pid);
6605 /* Now send results of command back into original context */
6606 setup_file_in_str(&pipe_str, fp);
6608 while ((ch = i_getch(&pipe_str)) != EOF) {
6614 o_addchr(dest, '\n');
6617 o_addQchr(dest, ch);
6620 debug_printf("done reading from `cmd` pipe, closing it\n");
6621 fclose_and_forget(fp);
6622 /* We need to extract exitcode. Test case
6623 * "true; echo `sleep 1; false` $?"
6625 safe_waitpid(pid, &status, 0);
6626 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6627 return WEXITSTATUS(status);
6629 #endif /* ENABLE_HUSH_TICK */
6632 static void setup_heredoc(struct redir_struct *redir)
6634 struct fd_pair pair;
6637 /* the _body_ of heredoc (misleading field name) */
6638 const char *heredoc = redir->rd_filename;
6645 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6646 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6650 len = strlen(heredoc);
6652 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6654 xmove_fd(pair.rd, redir->rd_fd);
6656 /* Try writing without forking. Newer kernels have
6657 * dynamically growing pipes. Must use non-blocking write! */
6660 written = write(pair.wr, heredoc, len);
6671 ndelay_off(pair.wr);
6673 /* Okay, pipe buffer was not big enough */
6674 /* Note: we must not create a stray child (bastard? :)
6675 * for the unsuspecting parent process. Child creates a grandchild
6676 * and exits before parent execs the process which consumes heredoc
6677 * (that exec happens after we return from this function) */
6684 disable_restore_tty_pgrp_on_exit();
6685 pid = BB_MMU ? xfork() : xvfork();
6689 close(redir->rd_fd); /* read side of the pipe */
6691 full_write(pair.wr, heredoc, len); /* may loop or block */
6694 /* Delegate blocking writes to another process */
6695 xmove_fd(pair.wr, STDOUT_FILENO);
6696 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6700 #if ENABLE_HUSH_FAST
6702 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6704 enable_restore_tty_pgrp_on_exit();
6710 wait(NULL); /* wait till child has died */
6716 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6717 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6720 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6722 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6723 sq[i].orig_fd = orig;
6724 sq[i].moved_to = moved;
6725 sq[i+1].orig_fd = -1; /* end marker */
6729 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6734 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6735 /* If we collide with an already moved fd... */
6736 if (fd == sq[i].moved_to) {
6737 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6738 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6739 if (sq[i].moved_to < 0) /* what? */
6743 if (fd == sq[i].orig_fd) {
6744 /* Example: echo Hello >/dev/null 1>&2 */
6745 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6750 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6751 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6752 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6753 if (moved_to < 0 && errno != EBADF)
6755 return append_squirrel(sq, i, fd, moved_to);
6758 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6762 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6763 /* If we collide with an already moved fd... */
6764 if (fd == sq[i].orig_fd) {
6766 * "echo 3>FILE 3>&- 3>FILE"
6767 * "echo 3>&- 3>FILE"
6768 * No need for last redirect to insert
6769 * another "need to close 3" indicator.
6771 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6776 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6777 return append_squirrel(sq, i, fd, -1);
6780 /* fd: redirect wants this fd to be used (e.g. 3>file).
6781 * Move all conflicting internally used fds,
6782 * and remember them so that we can restore them later.
6784 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6786 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6789 #if ENABLE_HUSH_INTERACTIVE
6790 if (fd == G.interactive_fd) {
6791 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6792 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6793 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6794 return 1; /* "we closed fd" */
6797 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6798 * (1) Redirect in a forked child. No need to save FILEs' fds,
6799 * we aren't going to use them anymore, ok to trash.
6800 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6801 * but how are we doing to restore them?
6802 * "fileno(fd) = new_fd" can't be done.
6807 /* If this one of script's fds? */
6808 if (save_FILEs_on_redirect(fd, avoid_fd))
6809 return 1; /* yes. "we closed fd" */
6811 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6812 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6813 return 0; /* "we did not close fd" */
6816 static void restore_redirects(struct squirrel *sq)
6820 for (i = 0; sq[i].orig_fd >= 0; i++) {
6821 if (sq[i].moved_to >= 0) {
6822 /* We simply die on error */
6823 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6824 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6826 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6827 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6828 close(sq[i].orig_fd);
6834 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6836 restore_redirected_FILEs();
6839 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6840 static void close_saved_fds_and_FILE_fds(void)
6842 if (G_interactive_fd)
6843 close(G_interactive_fd);
6844 close_all_FILE_list();
6848 static int internally_opened_fd(int fd, struct squirrel *sq)
6852 #if ENABLE_HUSH_INTERACTIVE
6853 if (fd == G.interactive_fd)
6856 /* If this one of script's fds? */
6857 if (fd_in_FILEs(fd))
6860 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6861 if (fd == sq[i].moved_to)
6867 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6868 * and stderr if they are redirected. */
6869 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6871 struct redir_struct *redir;
6873 for (redir = prog->redirects; redir; redir = redir->next) {
6877 if (redir->rd_type == REDIRECT_HEREDOC2) {
6878 /* "rd_fd<<HERE" case */
6879 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6880 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6882 debug_printf_parse("set heredoc '%s'\n",
6883 redir->rd_filename);
6884 setup_heredoc(redir);
6888 if (redir->rd_dup == REDIRFD_TO_FILE) {
6889 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6893 if (redir->rd_filename == NULL) {
6896 * "cmd >" (no filename)
6897 * "cmd > <file" (2nd redirect starts too early)
6899 syntax_error("invalid redirect");
6902 mode = redir_table[redir->rd_type].mode;
6903 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6904 newfd = open_or_warn(p, mode);
6907 /* Error message from open_or_warn can be lost
6908 * if stderr has been redirected, but bash
6909 * and ash both lose it as well
6910 * (though zsh doesn't!)
6914 if (newfd == redir->rd_fd && sqp) {
6915 /* open() gave us precisely the fd we wanted.
6916 * This means that this fd was not busy
6917 * (not opened to anywhere).
6918 * Remember to close it on restore:
6920 *sqp = add_squirrel_closed(*sqp, newfd);
6921 debug_printf_redir("redir to previously closed fd %d\n", newfd);
6924 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6925 newfd = redir->rd_dup;
6928 if (newfd == redir->rd_fd)
6931 /* if "N>FILE": move newfd to redir->rd_fd */
6932 /* if "N>&M": dup newfd to redir->rd_fd */
6933 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6935 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6936 if (newfd == REDIRFD_CLOSE) {
6937 /* "N>&-" means "close me" */
6939 /* ^^^ optimization: saving may already
6940 * have closed it. If not... */
6941 close(redir->rd_fd);
6943 /* Sometimes we do another close on restore, getting EBADF.
6944 * Consider "echo 3>FILE 3>&-"
6945 * first redirect remembers "need to close 3",
6946 * and second redirect closes 3! Restore code then closes 3 again.
6949 /* if newfd is a script fd or saved fd, simulate EBADF */
6950 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6952 //bb_perror_msg_and_die("can't duplicate file descriptor");
6953 newfd = -1; /* same effect as code above */
6955 xdup2(newfd, redir->rd_fd);
6956 if (redir->rd_dup == REDIRFD_TO_FILE)
6957 /* "rd_fd > FILE" */
6959 /* else: "rd_fd > rd_dup" */
6965 static char *find_in_path(const char *arg)
6968 const char *PATH = get_local_var_value("PATH");
6974 const char *end = strchrnul(PATH, ':');
6975 int sz = end - PATH; /* must be int! */
6979 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6981 /* We have xxx::yyyy in $PATH,
6982 * it means "use current dir" */
6985 if (access(ret, F_OK) == 0)
6998 static const struct built_in_command *find_builtin_helper(const char *name,
6999 const struct built_in_command *x,
7000 const struct built_in_command *end)
7003 if (strcmp(name, x->b_cmd) != 0) {
7007 debug_printf_exec("found builtin '%s'\n", name);
7012 static const struct built_in_command *find_builtin1(const char *name)
7014 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7016 static const struct built_in_command *find_builtin(const char *name)
7018 const struct built_in_command *x = find_builtin1(name);
7021 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7024 #if ENABLE_HUSH_FUNCTIONS
7025 static struct function **find_function_slot(const char *name)
7027 struct function **funcpp = &G.top_func;
7029 if (strcmp(name, (*funcpp)->name) == 0) {
7032 funcpp = &(*funcpp)->next;
7037 static const struct function *find_function(const char *name)
7039 const struct function *funcp = *find_function_slot(name);
7041 debug_printf_exec("found function '%s'\n", name);
7045 /* Note: takes ownership on name ptr */
7046 static struct function *new_function(char *name)
7048 struct function **funcpp = find_function_slot(name);
7049 struct function *funcp = *funcpp;
7051 if (funcp != NULL) {
7052 struct command *cmd = funcp->parent_cmd;
7053 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7055 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7057 /* Note: if !funcp->body, do not free body_as_string!
7058 * This is a special case of "-F name body" function:
7059 * body_as_string was not malloced! */
7061 free_pipe_list(funcp->body);
7063 free(funcp->body_as_string);
7067 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7068 cmd->argv[0] = funcp->name;
7069 cmd->group = funcp->body;
7071 cmd->group_as_string = funcp->body_as_string;
7075 debug_printf_exec("remembering new function '%s'\n", name);
7076 funcp = *funcpp = xzalloc(sizeof(*funcp));
7077 /*funcp->next = NULL;*/
7084 # if ENABLE_HUSH_UNSET
7085 static void unset_func(const char *name)
7087 struct function **funcpp = find_function_slot(name);
7088 struct function *funcp = *funcpp;
7090 if (funcp != NULL) {
7091 debug_printf_exec("freeing function '%s'\n", funcp->name);
7092 *funcpp = funcp->next;
7093 /* funcp is unlinked now, deleting it.
7094 * Note: if !funcp->body, the function was created by
7095 * "-F name body", do not free ->body_as_string
7096 * and ->name as they were not malloced. */
7098 free_pipe_list(funcp->body);
7101 free(funcp->body_as_string);
7110 #define exec_function(to_free, funcp, argv) \
7111 exec_function(funcp, argv)
7113 static void exec_function(char ***to_free,
7114 const struct function *funcp,
7115 char **argv) NORETURN;
7116 static void exec_function(char ***to_free,
7117 const struct function *funcp,
7123 argv[0] = G.global_argv[0];
7124 G.global_argv = argv;
7125 G.global_argc = n = 1 + string_array_len(argv + 1);
7127 // Example when we are here: "cmd | func"
7128 // func will run with saved-redirect fds open.
7129 // $ f() { echo /proc/self/fd/*; }
7131 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7132 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7135 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7136 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7137 // They are CLOEXEC so external programs won't see them, but
7138 // for "more correctness" we might want to close those extra fds here:
7139 //? close_saved_fds_and_FILE_fds();
7141 /* "we are in function, ok to use return" */
7142 G_flag_return_in_progress = -1;
7143 IF_HUSH_LOCAL(G.func_nest_level++;)
7145 /* On MMU, funcp->body is always non-NULL */
7146 n = run_list(funcp->body);
7150 //? close_saved_fds_and_FILE_fds();
7152 //TODO: check whether "true | func_with_return" works
7154 re_execute_shell(to_free,
7155 funcp->body_as_string,
7162 static int run_function(const struct function *funcp, char **argv)
7168 save_and_replace_G_args(&sv, argv);
7170 /* "we are in function, ok to use return" */
7171 sv_flg = G_flag_return_in_progress;
7172 G_flag_return_in_progress = -1;
7173 IF_HUSH_LOCAL(G.func_nest_level++;)
7175 /* On MMU, funcp->body is always non-NULL */
7178 /* Function defined by -F */
7179 parse_and_run_string(funcp->body_as_string);
7180 rc = G.last_exitcode;
7184 rc = run_list(funcp->body);
7187 # if ENABLE_HUSH_LOCAL
7189 struct variable *var;
7190 struct variable **var_pp;
7192 var_pp = &G.top_var;
7193 while ((var = *var_pp) != NULL) {
7194 if (var->func_nest_level < G.func_nest_level) {
7195 var_pp = &var->next;
7199 if (var->flg_export)
7200 bb_unsetenv(var->varstr);
7201 /* Remove from global list */
7202 *var_pp = var->next;
7208 G.func_nest_level--;
7211 G_flag_return_in_progress = sv_flg;
7213 restore_G_args(&sv, argv);
7217 #endif /* ENABLE_HUSH_FUNCTIONS */
7221 #define exec_builtin(to_free, x, argv) \
7222 exec_builtin(x, argv)
7224 #define exec_builtin(to_free, x, argv) \
7225 exec_builtin(to_free, argv)
7227 static void exec_builtin(char ***to_free,
7228 const struct built_in_command *x,
7229 char **argv) NORETURN;
7230 static void exec_builtin(char ***to_free,
7231 const struct built_in_command *x,
7237 //? close_saved_fds_and_FILE_fds();
7238 rcode = x->b_function(argv);
7243 /* On NOMMU, we must never block!
7244 * Example: { sleep 99 | read line; } & echo Ok
7246 re_execute_shell(to_free,
7255 static void execvp_or_die(char **argv) NORETURN;
7256 static void execvp_or_die(char **argv)
7259 debug_printf_exec("execing '%s'\n", argv[0]);
7260 /* Don't propagate SIG_IGN to the child */
7261 if (SPECIAL_JOBSTOP_SIGS != 0)
7262 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7263 execvp(argv[0], argv);
7265 if (errno == EACCES) e = 126;
7266 if (errno == ENOENT) e = 127;
7267 bb_perror_msg("can't execute '%s'", argv[0]);
7271 #if ENABLE_HUSH_MODE_X
7272 static void dump_cmd_in_x_mode(char **argv)
7274 if (G_x_mode && argv) {
7275 /* We want to output the line in one write op */
7283 len += strlen(argv[n++]) + 1;
7289 p += sprintf(p, " %s", argv[n++]);
7297 # define dump_cmd_in_x_mode(argv) ((void)0)
7301 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7302 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7303 #define pseudo_exec(nommu_save, command, argv_expanded) \
7304 pseudo_exec(command, argv_expanded)
7307 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7309 * Don't exit() here. If you don't exec, use _exit instead.
7310 * The at_exit handlers apparently confuse the calling process,
7311 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7313 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7314 char **argv, int assignment_cnt,
7315 char **argv_expanded) NORETURN;
7316 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7317 char **argv, int assignment_cnt,
7318 char **argv_expanded)
7322 new_env = expand_assignments(argv, assignment_cnt);
7323 dump_cmd_in_x_mode(new_env);
7325 if (!argv[assignment_cnt]) {
7326 /* Case when we are here: ... | var=val | ...
7327 * (note that we do not exit early, i.e., do not optimize out
7328 * expand_assignments(): think about ... | var=`sleep 1` | ...
7330 free_strings(new_env);
7331 _exit(EXIT_SUCCESS);
7335 set_vars_and_save_old(new_env);
7336 free(new_env); /* optional */
7337 /* we can also destroy set_vars_and_save_old's return value,
7340 nommu_save->new_env = new_env;
7341 nommu_save->old_vars = set_vars_and_save_old(new_env);
7344 if (argv_expanded) {
7345 argv = argv_expanded;
7347 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7349 nommu_save->argv = argv;
7352 dump_cmd_in_x_mode(argv);
7354 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7355 if (strchr(argv[0], '/') != NULL)
7359 #if ENABLE_HUSH_FUNCTIONS
7360 /* Check if the command matches any functions (this goes before bltins) */
7362 const struct function *funcp = find_function(argv[0]);
7364 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7369 /* Check if the command matches any of the builtins.
7370 * Depending on context, this might be redundant. But it's
7371 * easier to waste a few CPU cycles than it is to figure out
7372 * if this is one of those cases.
7375 /* On NOMMU, it is more expensive to re-execute shell
7376 * just in order to run echo or test builtin.
7377 * It's better to skip it here and run corresponding
7378 * non-builtin later. */
7379 const struct built_in_command *x;
7380 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7382 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7386 #if ENABLE_FEATURE_SH_STANDALONE
7387 /* Check if the command matches any busybox applets */
7389 int a = find_applet_by_name(argv[0]);
7391 # if BB_MMU /* see above why on NOMMU it is not allowed */
7392 if (APPLET_IS_NOEXEC(a)) {
7393 /* Do not leak open fds from opened script files etc.
7394 * Testcase: interactive "ls -l /proc/self/fd"
7395 * should not show tty fd open.
7397 close_saved_fds_and_FILE_fds();
7398 //FIXME: should also close saved redir fds
7399 /* Without this, "rm -i FILE" can't be ^C'ed: */
7400 switch_off_special_sigs(G.special_sig_mask);
7401 debug_printf_exec("running applet '%s'\n", argv[0]);
7402 run_noexec_applet_and_exit(a, argv[0], argv);
7405 /* Re-exec ourselves */
7406 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7407 /* Don't propagate SIG_IGN to the child */
7408 if (SPECIAL_JOBSTOP_SIGS != 0)
7409 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7410 execv(bb_busybox_exec_path, argv);
7411 /* If they called chroot or otherwise made the binary no longer
7412 * executable, fall through */
7417 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7420 execvp_or_die(argv);
7423 /* Called after [v]fork() in run_pipe
7425 static void pseudo_exec(nommu_save_t *nommu_save,
7426 struct command *command,
7427 char **argv_expanded) NORETURN;
7428 static void pseudo_exec(nommu_save_t *nommu_save,
7429 struct command *command,
7430 char **argv_expanded)
7432 if (command->argv) {
7433 pseudo_exec_argv(nommu_save, command->argv,
7434 command->assignment_cnt, argv_expanded);
7437 if (command->group) {
7438 /* Cases when we are here:
7441 * ... | ( list ) | ...
7442 * ... | { list } | ...
7446 debug_printf_exec("pseudo_exec: run_list\n");
7447 reset_traps_to_defaults();
7448 rcode = run_list(command->group);
7449 /* OK to leak memory by not calling free_pipe_list,
7450 * since this process is about to exit */
7453 re_execute_shell(&nommu_save->argv_from_re_execing,
7454 command->group_as_string,
7461 /* Case when we are here: ... | >file */
7462 debug_printf_exec("pseudo_exec'ed null command\n");
7463 _exit(EXIT_SUCCESS);
7467 static const char *get_cmdtext(struct pipe *pi)
7473 /* This is subtle. ->cmdtext is created only on first backgrounding.
7474 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7475 * On subsequent bg argv is trashed, but we won't use it */
7479 argv = pi->cmds[0].argv;
7481 pi->cmdtext = xzalloc(1);
7486 len += strlen(*argv) + 1;
7490 argv = pi->cmds[0].argv;
7492 p = stpcpy(p, *argv);
7499 static void remove_job_from_table(struct pipe *pi)
7501 struct pipe *prev_pipe;
7503 if (pi == G.job_list) {
7504 G.job_list = pi->next;
7506 prev_pipe = G.job_list;
7507 while (prev_pipe->next != pi)
7508 prev_pipe = prev_pipe->next;
7509 prev_pipe->next = pi->next;
7513 G.last_jobid = G.job_list->jobid;
7516 static void delete_finished_job(struct pipe *pi)
7518 remove_job_from_table(pi);
7522 static void clean_up_last_dead_job(void)
7524 if (G.job_list && !G.job_list->alive_cmds)
7525 delete_finished_job(G.job_list);
7528 static void insert_job_into_table(struct pipe *pi)
7530 struct pipe *job, **jobp;
7533 clean_up_last_dead_job();
7535 /* Find the end of the list, and find next job ID to use */
7538 while ((job = *jobp) != NULL) {
7545 /* Create a new job struct at the end */
7546 job = *jobp = xmemdup(pi, sizeof(*pi));
7548 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7549 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7550 for (i = 0; i < pi->num_cmds; i++) {
7551 job->cmds[i].pid = pi->cmds[i].pid;
7552 /* all other fields are not used and stay zero */
7554 job->cmdtext = xstrdup(get_cmdtext(pi));
7556 if (G_interactive_fd)
7557 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7558 G.last_jobid = job->jobid;
7562 static int job_exited_or_stopped(struct pipe *pi)
7566 if (pi->alive_cmds != pi->stopped_cmds)
7569 /* All processes in fg pipe have exited or stopped */
7573 rcode = pi->cmds[i].cmd_exitcode;
7574 /* usually last process gives overall exitstatus,
7575 * but with "set -o pipefail", last *failed* process does */
7576 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7579 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7583 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7590 dead = WIFEXITED(status) || WIFSIGNALED(status);
7593 if (WIFSTOPPED(status))
7594 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7595 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7596 if (WIFSIGNALED(status))
7597 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7598 childpid, WTERMSIG(status), WEXITSTATUS(status));
7599 if (WIFEXITED(status))
7600 debug_printf_jobs("pid %d exited, exitcode %d\n",
7601 childpid, WEXITSTATUS(status));
7603 /* Were we asked to wait for a fg pipe? */
7605 i = fg_pipe->num_cmds;
7610 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7611 if (fg_pipe->cmds[i].pid != childpid)
7615 fg_pipe->cmds[i].pid = 0;
7616 fg_pipe->alive_cmds--;
7617 ex = WEXITSTATUS(status);
7618 /* bash prints killer signal's name for *last*
7619 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7620 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7622 if (WIFSIGNALED(status)) {
7623 int sig = WTERMSIG(status);
7624 if (i == fg_pipe->num_cmds-1)
7625 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7626 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7627 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7628 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7629 * Maybe we need to use sig | 128? */
7632 fg_pipe->cmds[i].cmd_exitcode = ex;
7634 fg_pipe->stopped_cmds++;
7636 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7637 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7638 rcode = job_exited_or_stopped(fg_pipe);
7640 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7641 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7642 * and "killall -STOP cat" */
7643 if (G_interactive_fd) {
7645 if (fg_pipe->alive_cmds != 0)
7646 insert_job_into_table(fg_pipe);
7650 if (fg_pipe->alive_cmds == 0)
7653 /* There are still running processes in the fg_pipe */
7656 /* It wasn't in fg_pipe, look for process in bg pipes */
7660 /* We were asked to wait for bg or orphaned children */
7661 /* No need to remember exitcode in this case */
7662 for (pi = G.job_list; pi; pi = pi->next) {
7663 for (i = 0; i < pi->num_cmds; i++) {
7664 if (pi->cmds[i].pid == childpid)
7665 goto found_pi_and_prognum;
7668 /* Happens when shell is used as init process (init=/bin/sh) */
7669 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7670 return -1; /* this wasn't a process from fg_pipe */
7672 found_pi_and_prognum:
7675 int rcode = WEXITSTATUS(status);
7676 if (WIFSIGNALED(status))
7677 rcode = 128 + WTERMSIG(status);
7678 pi->cmds[i].cmd_exitcode = rcode;
7679 if (G.last_bg_pid == pi->cmds[i].pid)
7680 G.last_bg_pid_exitcode = rcode;
7681 pi->cmds[i].pid = 0;
7683 if (!pi->alive_cmds) {
7684 if (G_interactive_fd) {
7685 printf(JOB_STATUS_FORMAT, pi->jobid,
7686 "Done", pi->cmdtext);
7687 delete_finished_job(pi);
7690 * bash deletes finished jobs from job table only in interactive mode,
7691 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7692 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7693 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7694 * We only retain one "dead" job, if it's the single job on the list.
7695 * This covers most of real-world scenarios where this is useful.
7697 if (pi != G.job_list)
7698 delete_finished_job(pi);
7706 return -1; /* this wasn't a process from fg_pipe */
7709 /* Check to see if any processes have exited -- if they have,
7710 * figure out why and see if a job has completed.
7712 * If non-NULL fg_pipe: wait for its completion or stop.
7713 * Return its exitcode or zero if stopped.
7715 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7716 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7717 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7718 * or 0 if no children changed status.
7720 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7721 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7722 * or 0 if no children changed status.
7724 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7730 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7732 attributes = WUNTRACED;
7733 if (fg_pipe == NULL)
7734 attributes |= WNOHANG;
7737 #if ENABLE_HUSH_FAST
7738 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7739 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7740 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7741 /* There was neither fork nor SIGCHLD since last waitpid */
7742 /* Avoid doing waitpid syscall if possible */
7743 if (!G.we_have_children) {
7747 if (fg_pipe == NULL) { /* is WNOHANG set? */
7748 /* We have children, but they did not exit
7749 * or stop yet (we saw no SIGCHLD) */
7752 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7756 /* Do we do this right?
7757 * bash-3.00# sleep 20 | false
7759 * [3]+ Stopped sleep 20 | false
7760 * bash-3.00# echo $?
7761 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7762 * [hush 1.14.0: yes we do it right]
7766 #if ENABLE_HUSH_FAST
7768 i = G.count_SIGCHLD;
7770 childpid = waitpid(-1, &status, attributes);
7771 if (childpid <= 0) {
7772 if (childpid && errno != ECHILD)
7773 bb_perror_msg("waitpid");
7774 #if ENABLE_HUSH_FAST
7775 else { /* Until next SIGCHLD, waitpid's are useless */
7776 G.we_have_children = (childpid == 0);
7777 G.handled_SIGCHLD = i;
7778 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7781 /* ECHILD (no children), or 0 (no change in children status) */
7785 rcode = process_wait_result(fg_pipe, childpid, status);
7787 /* fg_pipe exited or stopped */
7790 if (childpid == waitfor_pid) {
7791 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7792 rcode = WEXITSTATUS(status);
7793 if (WIFSIGNALED(status))
7794 rcode = 128 + WTERMSIG(status);
7795 if (WIFSTOPPED(status))
7796 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7797 rcode = 128 + WSTOPSIG(status);
7799 break; /* "wait PID" called us, give it exitcode+1 */
7801 /* This wasn't one of our processes, or */
7802 /* fg_pipe still has running processes, do waitpid again */
7803 } /* while (waitpid succeeds)... */
7809 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7812 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7813 if (G_saved_tty_pgrp) {
7814 /* Job finished, move the shell to the foreground */
7815 p = getpgrp(); /* our process group id */
7816 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7817 tcsetpgrp(G_interactive_fd, p);
7823 /* Start all the jobs, but don't wait for anything to finish.
7826 * Return code is normally -1, when the caller has to wait for children
7827 * to finish to determine the exit status of the pipe. If the pipe
7828 * is a simple builtin command, however, the action is done by the
7829 * time run_pipe returns, and the exit code is provided as the
7832 * Returns -1 only if started some children. IOW: we have to
7833 * mask out retvals of builtins etc with 0xff!
7835 * The only case when we do not need to [v]fork is when the pipe
7836 * is single, non-backgrounded, non-subshell command. Examples:
7837 * cmd ; ... { list } ; ...
7838 * cmd && ... { list } && ...
7839 * cmd || ... { list } || ...
7840 * If it is, then we can run cmd as a builtin, NOFORK,
7841 * or (if SH_STANDALONE) an applet, and we can run the { list }
7842 * with run_list. If it isn't one of these, we fork and exec cmd.
7844 * Cases when we must fork:
7845 * non-single: cmd | cmd
7846 * backgrounded: cmd & { list } &
7847 * subshell: ( list ) [&]
7849 #if !ENABLE_HUSH_MODE_X
7850 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7851 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7853 static int redirect_and_varexp_helper(char ***new_env_p,
7854 struct variable **old_vars_p,
7855 struct command *command,
7856 struct squirrel **sqp,
7857 char **argv_expanded)
7859 /* setup_redirects acts on file descriptors, not FILEs.
7860 * This is perfect for work that comes after exec().
7861 * Is it really safe for inline use? Experimentally,
7862 * things seem to work. */
7863 int rcode = setup_redirects(command, sqp);
7865 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7866 *new_env_p = new_env;
7867 dump_cmd_in_x_mode(new_env);
7868 dump_cmd_in_x_mode(argv_expanded);
7870 *old_vars_p = set_vars_and_save_old(new_env);
7874 static NOINLINE int run_pipe(struct pipe *pi)
7876 static const char *const null_ptr = NULL;
7880 struct command *command;
7881 char **argv_expanded;
7883 struct squirrel *squirrel = NULL;
7886 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7889 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7890 * Result should be 3 lines: q w e, qwe, q w e
7892 G.ifs = get_local_var_value("IFS");
7896 IF_HUSH_JOB(pi->pgrp = -1;)
7897 pi->stopped_cmds = 0;
7898 command = &pi->cmds[0];
7899 argv_expanded = NULL;
7901 if (pi->num_cmds != 1
7902 || pi->followup == PIPE_BG
7903 || command->cmd_type == CMD_SUBSHELL
7910 debug_printf_exec(": group:%p argv:'%s'\n",
7911 command->group, command->argv ? command->argv[0] : "NONE");
7913 if (command->group) {
7914 #if ENABLE_HUSH_FUNCTIONS
7915 if (command->cmd_type == CMD_FUNCDEF) {
7916 /* "executing" func () { list } */
7917 struct function *funcp;
7919 funcp = new_function(command->argv[0]);
7920 /* funcp->name is already set to argv[0] */
7921 funcp->body = command->group;
7923 funcp->body_as_string = command->group_as_string;
7924 command->group_as_string = NULL;
7926 command->group = NULL;
7927 command->argv[0] = NULL;
7928 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7929 funcp->parent_cmd = command;
7930 command->child_func = funcp;
7932 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7934 return EXIT_SUCCESS;
7938 debug_printf("non-subshell group\n");
7939 rcode = 1; /* exitcode if redir failed */
7940 if (setup_redirects(command, &squirrel) == 0) {
7941 debug_printf_exec(": run_list\n");
7942 rcode = run_list(command->group) & 0xff;
7944 restore_redirects(squirrel);
7945 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7947 debug_printf_exec("run_pipe: return %d\n", rcode);
7951 argv = command->argv ? command->argv : (char **) &null_ptr;
7953 const struct built_in_command *x;
7954 #if ENABLE_HUSH_FUNCTIONS
7955 const struct function *funcp;
7959 char **new_env = NULL;
7960 struct variable *old_vars = NULL;
7962 if (argv[command->assignment_cnt] == NULL) {
7963 /* Assignments, but no command */
7964 /* Ensure redirects take effect (that is, create files).
7965 * Try "a=t >file" */
7966 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7967 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
7968 /* Set shell variables */
7972 if (set_local_var(*argv, /*flag:*/ 0)) {
7973 /* assignment to readonly var / putenv error? */
7979 /* Redirect error sets $? to 1. Otherwise,
7980 * if evaluating assignment value set $?, retain it.
7981 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7983 rcode = G.last_exitcode;
7984 /* Exit, _skipping_ variable restoring code: */
7985 goto clean_up_and_ret0;
7987 #else /* Older, bigger, but more correct code */
7989 rcode = setup_redirects(command, &squirrel);
7990 restore_redirects(squirrel);
7991 /* Set shell variables */
7993 bb_putchar_stderr('+');
7995 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7997 fprintf(stderr, " %s", p);
7998 debug_printf_exec("set shell var:'%s'->'%s'\n",
8000 if (set_local_var(p, /*flag:*/ 0)) {
8001 /* assignment to readonly var / putenv error? */
8007 bb_putchar_stderr('\n');
8008 /* Redirect error sets $? to 1. Otherwise,
8009 * if evaluating assignment value set $?, retain it.
8010 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8012 rcode = G.last_exitcode;
8013 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8015 debug_printf_exec("run_pipe: return %d\n", rcode);
8020 /* Expand the rest into (possibly) many strings each */
8022 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8023 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8027 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8030 /* if someone gives us an empty string: `cmd with empty output` */
8031 if (!argv_expanded[0]) {
8032 free(argv_expanded);
8034 return G.last_exitcode;
8037 #if ENABLE_HUSH_FUNCTIONS
8038 /* Check if argv[0] matches any functions (this goes before bltins) */
8039 funcp = find_function(argv_expanded[0]);
8043 x = find_builtin(argv_expanded[0]);
8046 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8047 debug_printf("exec with redirects only\n");
8048 rcode = setup_redirects(command, NULL);
8049 /* rcode=1 can be if redir file can't be opened */
8050 goto clean_up_and_ret1;
8053 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8056 debug_printf_exec(": builtin '%s' '%s'...\n",
8057 x->b_cmd, argv_expanded[1]);
8059 rcode = x->b_function(argv_expanded) & 0xff;
8062 #if ENABLE_HUSH_FUNCTIONS
8064 # if ENABLE_HUSH_LOCAL
8065 struct variable **sv;
8066 sv = G.shadowed_vars_pp;
8067 G.shadowed_vars_pp = &old_vars;
8069 debug_printf_exec(": function '%s' '%s'...\n",
8070 funcp->name, argv_expanded[1]);
8071 rcode = run_function(funcp, argv_expanded) & 0xff;
8072 # if ENABLE_HUSH_LOCAL
8073 G.shadowed_vars_pp = sv;
8079 unset_vars(new_env);
8081 /* clean_up_and_ret0: */
8082 restore_redirects(squirrel);
8084 * Try "usleep 99999999" + ^C + "echo $?"
8085 * with FEATURE_SH_NOFORK=y.
8088 /* It was builtin or nofork.
8089 * if this would be a real fork/execed program,
8090 * it should have died if a fatal sig was received.
8091 * But OTOH, there was no separate process,
8092 * the sig was sent to _shell_, not to non-existing
8094 * Let's just handle ^C only, this one is obvious:
8095 * we aren't ok with exitcode 0 when ^C was pressed
8096 * during builtin/nofork.
8098 if (sigismember(&G.pending_set, SIGINT))
8099 rcode = 128 + SIGINT;
8102 free(argv_expanded);
8103 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8105 debug_printf_exec("run_pipe return %d\n", rcode);
8109 if (ENABLE_FEATURE_SH_NOFORK) {
8110 int n = find_applet_by_name(argv_expanded[0]);
8111 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8112 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8114 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8115 argv_expanded[0], argv_expanded[1]);
8117 * Note: signals (^C) can't interrupt here.
8118 * We remember them and they will be acted upon
8119 * after applet returns.
8120 * This makes applets which can run for a long time
8121 * and/or wait for user input ineligible for NOFORK:
8122 * for example, "yes" or "rm" (rm -i waits for input).
8124 rcode = run_nofork_applet(n, argv_expanded);
8126 goto clean_up_and_ret;
8129 /* It is neither builtin nor applet. We must fork. */
8133 /* NB: argv_expanded may already be created, and that
8134 * might include `cmd` runs! Do not rerun it! We *must*
8135 * use argv_expanded if it's non-NULL */
8137 /* Going to fork a child per each pipe member */
8142 while (cmd_no < pi->num_cmds) {
8143 struct fd_pair pipefds;
8145 volatile nommu_save_t nommu_save;
8146 nommu_save.new_env = NULL;
8147 nommu_save.old_vars = NULL;
8148 nommu_save.argv = NULL;
8149 nommu_save.argv_from_re_execing = NULL;
8151 command = &pi->cmds[cmd_no];
8153 if (command->argv) {
8154 debug_printf_exec(": pipe member '%s' '%s'...\n",
8155 command->argv[0], command->argv[1]);
8157 debug_printf_exec(": pipe member with no argv\n");
8160 /* pipes are inserted between pairs of commands */
8163 if (cmd_no < pi->num_cmds)
8164 xpiped_pair(pipefds);
8166 command->pid = BB_MMU ? fork() : vfork();
8167 if (!command->pid) { /* child */
8169 disable_restore_tty_pgrp_on_exit();
8170 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8172 /* Every child adds itself to new process group
8173 * with pgid == pid_of_first_child_in_pipe */
8174 if (G.run_list_level == 1 && G_interactive_fd) {
8177 if (pgrp < 0) /* true for 1st process only */
8179 if (setpgid(0, pgrp) == 0
8180 && pi->followup != PIPE_BG
8181 && G_saved_tty_pgrp /* we have ctty */
8183 /* We do it in *every* child, not just first,
8185 tcsetpgrp(G_interactive_fd, pgrp);
8189 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8190 /* 1st cmd in backgrounded pipe
8191 * should have its stdin /dev/null'ed */
8193 if (open(bb_dev_null, O_RDONLY))
8194 xopen("/", O_RDONLY);
8196 xmove_fd(next_infd, 0);
8198 xmove_fd(pipefds.wr, 1);
8201 /* Like bash, explicit redirects override pipes,
8202 * and the pipe fd (fd#1) is available for dup'ing:
8203 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8204 * of cmd1 goes into pipe.
8206 if (setup_redirects(command, NULL)) {
8207 /* Happens when redir file can't be opened:
8208 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8210 * hush: can't open '/qwe/rty': No such file or directory
8212 * (echo BAR is not executed, it hits _exit(1) below)
8217 /* Stores to nommu_save list of env vars putenv'ed
8218 * (NOMMU, on MMU we don't need that) */
8219 /* cast away volatility... */
8220 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8221 /* pseudo_exec() does not return */
8224 /* parent or error */
8225 #if ENABLE_HUSH_FAST
8227 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8229 enable_restore_tty_pgrp_on_exit();
8231 /* Clean up after vforked child */
8232 free(nommu_save.argv);
8233 free(nommu_save.argv_from_re_execing);
8234 unset_vars(nommu_save.new_env);
8235 add_vars(nommu_save.old_vars);
8237 free(argv_expanded);
8238 argv_expanded = NULL;
8239 if (command->pid < 0) { /* [v]fork failed */
8240 /* Clearly indicate, was it fork or vfork */
8241 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8245 /* Second and next children need to know pid of first one */
8247 pi->pgrp = command->pid;
8253 if (cmd_no < pi->num_cmds)
8255 /* Pass read (output) pipe end to next iteration */
8256 next_infd = pipefds.rd;
8259 if (!pi->alive_cmds) {
8261 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8266 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8270 /* NB: called by pseudo_exec, and therefore must not modify any
8271 * global data until exec/_exit (we can be a child after vfork!) */
8272 static int run_list(struct pipe *pi)
8274 #if ENABLE_HUSH_CASE
8275 char *case_word = NULL;
8277 #if ENABLE_HUSH_LOOPS
8278 struct pipe *loop_top = NULL;
8279 char **for_lcur = NULL;
8280 char **for_list = NULL;
8282 smallint last_followup;
8284 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8285 smalluint cond_code = 0;
8287 enum { cond_code = 0 };
8290 smallint rword; /* RES_foo */
8291 smallint last_rword; /* ditto */
8294 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8297 #if ENABLE_HUSH_LOOPS
8298 /* Check syntax for "for" */
8301 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8302 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8304 /* current word is FOR or IN (BOLD in comments below) */
8305 if (cpipe->next == NULL) {
8306 syntax_error("malformed for");
8308 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8311 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8312 if (cpipe->next->res_word == RES_DO)
8314 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8315 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8316 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8318 syntax_error("malformed for");
8320 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8327 /* Past this point, all code paths should jump to ret: label
8328 * in order to return, no direct "return" statements please.
8329 * This helps to ensure that no memory is leaked. */
8337 last_rword = RES_XXXX;
8339 last_followup = PIPE_SEQ;
8340 rcode = G.last_exitcode;
8342 /* Go through list of pipes, (maybe) executing them. */
8343 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8345 int sv_errexit_depth;
8349 if (G_flag_return_in_progress == 1)
8352 IF_HAS_KEYWORDS(rword = pi->res_word;)
8353 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8354 rword, cond_code, last_rword);
8356 sv_errexit_depth = G.errexit_depth;
8357 if (IF_HAS_KEYWORDS(rword == RES_IF || rword == RES_ELIF ||)
8358 pi->followup != PIPE_SEQ
8362 #if ENABLE_HUSH_LOOPS
8363 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8364 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8366 /* start of a loop: remember where loop starts */
8371 /* Still in the same "if...", "then..." or "do..." branch? */
8372 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8373 if ((rcode == 0 && last_followup == PIPE_OR)
8374 || (rcode != 0 && last_followup == PIPE_AND)
8376 /* It is "<true> || CMD" or "<false> && CMD"
8377 * and we should not execute CMD */
8378 debug_printf_exec("skipped cmd because of || or &&\n");
8379 last_followup = pi->followup;
8380 goto dont_check_jobs_but_continue;
8383 last_followup = pi->followup;
8384 IF_HAS_KEYWORDS(last_rword = rword;)
8387 if (rword == RES_THEN) {
8388 /* if false; then ... fi has exitcode 0! */
8389 G.last_exitcode = rcode = EXIT_SUCCESS;
8390 /* "if <false> THEN cmd": skip cmd */
8394 if (rword == RES_ELSE || rword == RES_ELIF) {
8395 /* "if <true> then ... ELSE/ELIF cmd":
8396 * skip cmd and all following ones */
8401 #if ENABLE_HUSH_LOOPS
8402 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8404 /* first loop through for */
8406 static const char encoded_dollar_at[] ALIGN1 = {
8407 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8408 }; /* encoded representation of "$@" */
8409 static const char *const encoded_dollar_at_argv[] = {
8410 encoded_dollar_at, NULL
8411 }; /* argv list with one element: "$@" */
8414 vals = (char**)encoded_dollar_at_argv;
8415 if (pi->next->res_word == RES_IN) {
8416 /* if no variable values after "in" we skip "for" */
8417 if (!pi->next->cmds[0].argv) {
8418 G.last_exitcode = rcode = EXIT_SUCCESS;
8419 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8422 vals = pi->next->cmds[0].argv;
8423 } /* else: "for var; do..." -> assume "$@" list */
8424 /* create list of variable values */
8425 debug_print_strings("for_list made from", vals);
8426 for_list = expand_strvec_to_strvec(vals);
8427 for_lcur = for_list;
8428 debug_print_strings("for_list", for_list);
8431 /* "for" loop is over, clean up */
8437 /* Insert next value from for_lcur */
8438 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8439 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8442 if (rword == RES_IN) {
8443 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8445 if (rword == RES_DONE) {
8446 continue; /* "done" has no cmds too */
8449 #if ENABLE_HUSH_CASE
8450 if (rword == RES_CASE) {
8451 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8452 case_word = expand_strvec_to_string(pi->cmds->argv);
8453 unbackslash(case_word);
8456 if (rword == RES_MATCH) {
8459 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8460 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8462 /* all prev words didn't match, does this one match? */
8463 argv = pi->cmds->argv;
8465 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8466 /* TODO: which FNM_xxx flags to use? */
8467 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8468 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8470 if (cond_code == 0) { /* match! we will execute this branch */
8472 case_word = NULL; /* make future "word)" stop */
8479 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8480 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8482 continue; /* not matched yet, skip this pipe */
8484 if (rword == RES_ESAC) {
8485 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8487 /* "case" did not match anything: still set $? (to 0) */
8488 G.last_exitcode = rcode = EXIT_SUCCESS;
8492 /* Just pressing <enter> in shell should check for jobs.
8493 * OTOH, in non-interactive shell this is useless
8494 * and only leads to extra job checks */
8495 if (pi->num_cmds == 0) {
8496 if (G_interactive_fd)
8497 goto check_jobs_and_continue;
8501 /* After analyzing all keywords and conditions, we decided
8502 * to execute this pipe. NB: have to do checkjobs(NULL)
8503 * after run_pipe to collect any background children,
8504 * even if list execution is to be stopped. */
8505 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8506 #if ENABLE_HUSH_LOOPS
8507 G.flag_break_continue = 0;
8509 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8511 /* We ran a builtin, function, or group.
8512 * rcode is already known
8513 * and we don't need to wait for anything. */
8514 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8515 G.last_exitcode = rcode;
8516 check_and_run_traps();
8517 #if ENABLE_HUSH_LOOPS
8518 /* Was it "break" or "continue"? */
8519 if (G.flag_break_continue) {
8520 smallint fbc = G.flag_break_continue;
8521 /* We might fall into outer *loop*,
8522 * don't want to break it too */
8524 G.depth_break_continue--;
8525 if (G.depth_break_continue == 0)
8526 G.flag_break_continue = 0;
8527 /* else: e.g. "continue 2" should *break* once, *then* continue */
8528 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8529 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8530 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8533 /* "continue": simulate end of loop */
8538 if (G_flag_return_in_progress == 1) {
8539 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8542 } else if (pi->followup == PIPE_BG) {
8543 /* What does bash do with attempts to background builtins? */
8544 /* even bash 3.2 doesn't do that well with nested bg:
8545 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8546 * I'm NOT treating inner &'s as jobs */
8548 if (G.run_list_level == 1)
8549 insert_job_into_table(pi);
8551 /* Last command's pid goes to $! */
8552 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8553 G.last_bg_pid_exitcode = 0;
8554 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8555 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8556 rcode = EXIT_SUCCESS;
8560 if (G.run_list_level == 1 && G_interactive_fd) {
8561 /* Waits for completion, then fg's main shell */
8562 rcode = checkjobs_and_fg_shell(pi);
8563 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8567 /* This one just waits for completion */
8568 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8569 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8571 G.last_exitcode = rcode;
8572 check_and_run_traps();
8575 /* Handle "set -e" */
8576 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8577 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8578 if (G.errexit_depth == 0)
8581 G.errexit_depth = sv_errexit_depth;
8583 /* Analyze how result affects subsequent commands */
8585 if (rword == RES_IF || rword == RES_ELIF)
8588 check_jobs_and_continue:
8589 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8590 dont_check_jobs_but_continue: ;
8591 #if ENABLE_HUSH_LOOPS
8592 /* Beware of "while false; true; do ..."! */
8594 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8595 /* check for RES_DONE is needed for "while ...; do \n done" case */
8597 if (rword == RES_WHILE) {
8599 /* "while false; do...done" - exitcode 0 */
8600 G.last_exitcode = rcode = EXIT_SUCCESS;
8601 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8605 if (rword == RES_UNTIL) {
8607 debug_printf_exec(": until expr is true: breaking\n");
8618 #if ENABLE_HUSH_LOOPS
8623 #if ENABLE_HUSH_CASE
8627 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8631 /* Select which version we will use */
8632 static int run_and_free_list(struct pipe *pi)
8635 debug_printf_exec("run_and_free_list entered\n");
8636 if (!G.o_opt[OPT_O_NOEXEC]) {
8637 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8638 rcode = run_list(pi);
8640 /* free_pipe_list has the side effect of clearing memory.
8641 * In the long run that function can be merged with run_list,
8642 * but doing that now would hobble the debugging effort. */
8644 debug_printf_exec("run_and_free_list return %d\n", rcode);
8649 static void install_sighandlers(unsigned mask)
8651 sighandler_t old_handler;
8653 while ((mask >>= 1) != 0) {
8657 old_handler = install_sighandler(sig, pick_sighandler(sig));
8658 /* POSIX allows shell to re-enable SIGCHLD
8659 * even if it was SIG_IGN on entry.
8660 * Therefore we skip IGN check for it:
8664 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8665 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8667 //if (sig == SIGHUP) continue; - TODO?
8668 if (old_handler == SIG_IGN) {
8669 /* oops... restore back to IGN, and record this fact */
8670 install_sighandler(sig, old_handler);
8671 #if ENABLE_HUSH_TRAP
8673 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8675 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8681 /* Called a few times only (or even once if "sh -c") */
8682 static void install_special_sighandlers(void)
8686 /* Which signals are shell-special? */
8687 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8688 if (G_interactive_fd) {
8689 mask |= SPECIAL_INTERACTIVE_SIGS;
8690 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8691 mask |= SPECIAL_JOBSTOP_SIGS;
8693 /* Careful, do not re-install handlers we already installed */
8694 if (G.special_sig_mask != mask) {
8695 unsigned diff = mask & ~G.special_sig_mask;
8696 G.special_sig_mask = mask;
8697 install_sighandlers(diff);
8703 /* Set handlers to restore tty pgrp and exit */
8704 static void install_fatal_sighandlers(void)
8708 /* We will restore tty pgrp on these signals */
8710 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8711 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8712 + (1 << SIGBUS ) * HUSH_DEBUG
8713 + (1 << SIGSEGV) * HUSH_DEBUG
8714 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8716 /* bash 3.2 seems to handle these just like 'fatal' ones */
8719 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8720 * if we aren't interactive... but in this case
8721 * we never want to restore pgrp on exit, and this fn is not called
8723 /*+ (1 << SIGHUP )*/
8724 /*+ (1 << SIGTERM)*/
8725 /*+ (1 << SIGINT )*/
8727 G_fatal_sig_mask = mask;
8729 install_sighandlers(mask);
8733 static int set_mode(int state, char mode, const char *o_opt)
8738 G.o_opt[OPT_O_NOEXEC] = state;
8741 IF_HUSH_MODE_X(G_x_mode = state;)
8745 /* "set -+o" without parameter.
8746 * in bash, set -o produces this output:
8750 * We always use the second form.
8752 const char *p = o_opt_strings;
8755 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8761 idx = index_in_strings(o_opt_strings, o_opt);
8763 G.o_opt[idx] = state;
8767 G.o_opt[OPT_O_ERREXIT] = state;
8770 return EXIT_FAILURE;
8772 return EXIT_SUCCESS;
8775 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8776 int hush_main(int argc, char **argv)
8779 OPT_login = (1 << 0),
8783 unsigned builtin_argc;
8785 struct variable *cur_var;
8786 struct variable *shell_ver;
8789 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8790 G.last_exitcode = EXIT_SUCCESS;
8792 #if ENABLE_HUSH_FAST
8793 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8796 G.argv0_for_re_execing = argv[0];
8798 /* Deal with HUSH_VERSION */
8799 shell_ver = xzalloc(sizeof(*shell_ver));
8800 shell_ver->flg_export = 1;
8801 shell_ver->flg_read_only = 1;
8802 /* Code which handles ${var<op>...} needs writable values for all variables,
8803 * therefore we xstrdup: */
8804 shell_ver->varstr = xstrdup(hush_version_str);
8805 /* Create shell local variables from the values
8806 * currently living in the environment */
8807 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8808 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8809 G.top_var = shell_ver;
8810 cur_var = G.top_var;
8813 char *value = strchr(*e, '=');
8814 if (value) { /* paranoia */
8815 cur_var->next = xzalloc(sizeof(*cur_var));
8816 cur_var = cur_var->next;
8817 cur_var->varstr = *e;
8818 cur_var->max_len = strlen(*e);
8819 cur_var->flg_export = 1;
8823 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8824 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8825 putenv(shell_ver->varstr);
8828 set_pwd_var(SETFLAG_EXPORT);
8830 #if BASH_HOSTNAME_VAR
8831 /* Set (but not export) HOSTNAME unless already set */
8832 if (!get_local_var_value("HOSTNAME")) {
8835 set_local_var_from_halves("HOSTNAME", uts.nodename);
8837 /* bash also exports SHLVL and _,
8838 * and sets (but doesn't export) the following variables:
8840 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8841 * BASH_VERSION='3.2.0(1)-release'
8843 * MACHTYPE=i386-pc-linux-gnu
8845 * PPID=<NNNNN> - we also do it elsewhere
8856 * PIPESTATUS=([0]="0")
8857 * HISTFILE=/<xxx>/.bash_history
8861 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8863 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8874 #if ENABLE_FEATURE_EDITING
8875 G.line_input_state = new_line_input_t(FOR_SHELL);
8878 /* Initialize some more globals to non-zero values */
8879 cmdedit_update_prompt();
8881 die_func = restore_ttypgrp_and__exit;
8883 /* Shell is non-interactive at first. We need to call
8884 * install_special_sighandlers() if we are going to execute "sh <script>",
8885 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8886 * If we later decide that we are interactive, we run install_special_sighandlers()
8887 * in order to intercept (more) signals.
8891 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8892 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8895 opt = getopt(argc, argv, "+c:exinsl"
8898 # if ENABLE_HUSH_FUNCTIONS
8908 * sh ... -c 'script'
8909 * sh ... -c 'script' ARG0 [ARG1...]
8910 * On NOMMU, if builtin_argc != 0,
8911 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8912 * "" needs to be replaced with NULL
8913 * and BARGV vector fed to builtin function.
8914 * Note: the form without ARG0 never happens:
8915 * sh ... -c 'builtin' BARGV... ""
8918 G.root_pid = getpid();
8919 G.root_ppid = getppid();
8921 G.global_argv = argv + optind;
8922 G.global_argc = argc - optind;
8924 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8925 const struct built_in_command *x;
8927 install_special_sighandlers();
8928 x = find_builtin(optarg);
8929 if (x) { /* paranoia */
8930 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8931 G.global_argv += builtin_argc;
8932 G.global_argv[-1] = NULL; /* replace "" */
8934 G.last_exitcode = x->b_function(argv + optind - 1);
8938 if (!G.global_argv[0]) {
8939 /* -c 'script' (no params): prevent empty $0 */
8940 G.global_argv--; /* points to argv[i] of 'script' */
8941 G.global_argv[0] = argv[0];
8943 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8944 install_special_sighandlers();
8945 parse_and_run_string(optarg);
8948 /* Well, we cannot just declare interactiveness,
8949 * we have to have some stuff (ctty, etc) */
8950 /* G_interactive_fd++; */
8953 /* "-s" means "read from stdin", but this is how we always
8954 * operate, so simply do nothing here. */
8960 case '<': /* "big heredoc" support */
8961 full_write1_str(optarg);
8964 unsigned long long empty_trap_mask;
8966 G.root_pid = bb_strtou(optarg, &optarg, 16);
8968 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8970 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8972 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8974 builtin_argc = bb_strtou(optarg, &optarg, 16);
8976 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8977 if (empty_trap_mask != 0) {
8978 IF_HUSH_TRAP(int sig;)
8979 install_special_sighandlers();
8980 # if ENABLE_HUSH_TRAP
8981 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8982 for (sig = 1; sig < NSIG; sig++) {
8983 if (empty_trap_mask & (1LL << sig)) {
8984 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8985 install_sighandler(sig, SIG_IGN);
8990 # if ENABLE_HUSH_LOOPS
8992 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8998 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9000 # if ENABLE_HUSH_FUNCTIONS
9002 struct function *funcp = new_function(optarg);
9003 /* funcp->name is already set to optarg */
9004 /* funcp->body is set to NULL. It's a special case. */
9005 funcp->body_as_string = argv[optind];
9014 if (set_mode(1, opt, NULL) == 0) /* no error */
9018 fprintf(stderr, "Usage: sh [FILE]...\n"
9019 " or: sh -c command [args]...\n\n");
9025 } /* option parsing loop */
9027 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9028 G.global_argc = argc - (optind - 1);
9029 G.global_argv = argv + (optind - 1);
9030 G.global_argv[0] = argv[0];
9033 G.root_pid = getpid();
9034 G.root_ppid = getppid();
9037 /* If we are login shell... */
9038 if (flags & OPT_login) {
9040 debug_printf("sourcing /etc/profile\n");
9041 input = fopen_for_read("/etc/profile");
9042 if (input != NULL) {
9043 remember_FILE(input);
9044 install_special_sighandlers();
9045 parse_and_run_file(input);
9046 fclose_and_forget(input);
9048 /* bash: after sourcing /etc/profile,
9049 * tries to source (in the given order):
9050 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9051 * stopping on first found. --noprofile turns this off.
9052 * bash also sources ~/.bash_logout on exit.
9053 * If called as sh, skips .bash_XXX files.
9057 if (G.global_argv[1]) {
9060 * "bash <script>" (which is never interactive (unless -i?))
9061 * sources $BASH_ENV here (without scanning $PATH).
9062 * If called as sh, does the same but with $ENV.
9063 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9067 debug_printf("running script '%s'\n", G.global_argv[0]);
9068 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9069 input = xfopen_for_read(G.global_argv[0]);
9070 xfunc_error_retval = 1;
9071 remember_FILE(input);
9072 install_special_sighandlers();
9073 parse_and_run_file(input);
9074 #if ENABLE_FEATURE_CLEAN_UP
9075 fclose_and_forget(input);
9080 /* Up to here, shell was non-interactive. Now it may become one.
9081 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9084 /* A shell is interactive if the '-i' flag was given,
9085 * or if all of the following conditions are met:
9087 * no arguments remaining or the -s flag given
9088 * standard input is a terminal
9089 * standard output is a terminal
9090 * Refer to Posix.2, the description of the 'sh' utility.
9093 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9094 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9095 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9096 if (G_saved_tty_pgrp < 0)
9097 G_saved_tty_pgrp = 0;
9099 /* try to dup stdin to high fd#, >= 255 */
9100 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9101 if (G_interactive_fd < 0) {
9102 /* try to dup to any fd */
9103 G_interactive_fd = dup(STDIN_FILENO);
9104 if (G_interactive_fd < 0) {
9106 G_interactive_fd = 0;
9107 G_saved_tty_pgrp = 0;
9110 // TODO: track & disallow any attempts of user
9111 // to (inadvertently) close/redirect G_interactive_fd
9113 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9114 if (G_interactive_fd) {
9115 close_on_exec_on(G_interactive_fd);
9117 if (G_saved_tty_pgrp) {
9118 /* If we were run as 'hush &', sleep until we are
9119 * in the foreground (tty pgrp == our pgrp).
9120 * If we get started under a job aware app (like bash),
9121 * make sure we are now in charge so we don't fight over
9122 * who gets the foreground */
9124 pid_t shell_pgrp = getpgrp();
9125 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9126 if (G_saved_tty_pgrp == shell_pgrp)
9128 /* send TTIN to ourself (should stop us) */
9129 kill(- shell_pgrp, SIGTTIN);
9133 /* Install more signal handlers */
9134 install_special_sighandlers();
9136 if (G_saved_tty_pgrp) {
9137 /* Set other signals to restore saved_tty_pgrp */
9138 install_fatal_sighandlers();
9139 /* Put ourselves in our own process group
9140 * (bash, too, does this only if ctty is available) */
9141 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9142 /* Grab control of the terminal */
9143 tcsetpgrp(G_interactive_fd, getpid());
9145 enable_restore_tty_pgrp_on_exit();
9147 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9149 const char *hp = get_local_var_value("HISTFILE");
9151 hp = get_local_var_value("HOME");
9153 hp = concat_path_file(hp, ".hush_history");
9158 G.line_input_state->hist_file = hp;
9159 //set_local_var(xasprintf("HISTFILE=%s", ...));
9161 # if ENABLE_FEATURE_SH_HISTFILESIZE
9162 hp = get_local_var_value("HISTFILESIZE");
9163 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9168 install_special_sighandlers();
9170 #elif ENABLE_HUSH_INTERACTIVE
9171 /* No job control compiled in, only prompt/line editing */
9172 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9173 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9174 if (G_interactive_fd < 0) {
9175 /* try to dup to any fd */
9176 G_interactive_fd = dup(STDIN_FILENO);
9177 if (G_interactive_fd < 0)
9179 G_interactive_fd = 0;
9182 if (G_interactive_fd) {
9183 close_on_exec_on(G_interactive_fd);
9185 install_special_sighandlers();
9187 /* We have interactiveness code disabled */
9188 install_special_sighandlers();
9191 * if interactive but not a login shell, sources ~/.bashrc
9192 * (--norc turns this off, --rcfile <file> overrides)
9195 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9196 /* note: ash and hush share this string */
9197 printf("\n\n%s %s\n"
9198 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9201 "hush - the humble shell"
9205 parse_and_run_file(stdin);
9208 hush_exit(G.last_exitcode);
9215 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9220 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9221 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9223 int argc = string_array_len(argv);
9224 return applet_main_func(argc, argv);
9227 #if ENABLE_HUSH_TEST || BASH_TEST2
9228 static int FAST_FUNC builtin_test(char **argv)
9230 return run_applet_main(argv, test_main);
9233 #if ENABLE_HUSH_ECHO
9234 static int FAST_FUNC builtin_echo(char **argv)
9236 return run_applet_main(argv, echo_main);
9239 #if ENABLE_HUSH_PRINTF
9240 static int FAST_FUNC builtin_printf(char **argv)
9242 return run_applet_main(argv, printf_main);
9246 #if ENABLE_HUSH_HELP
9247 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9249 const struct built_in_command *x;
9252 "Built-in commands:\n"
9253 "------------------\n");
9254 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9256 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9258 return EXIT_SUCCESS;
9262 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9263 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9265 show_history(G.line_input_state);
9266 return EXIT_SUCCESS;
9270 static char **skip_dash_dash(char **argv)
9273 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9278 static int FAST_FUNC builtin_cd(char **argv)
9282 argv = skip_dash_dash(argv);
9284 if (newdir == NULL) {
9285 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9286 * bash says "bash: cd: HOME not set" and does nothing
9289 const char *home = get_local_var_value("HOME");
9290 newdir = home ? home : "/";
9292 if (chdir(newdir)) {
9293 /* Mimic bash message exactly */
9294 bb_perror_msg("cd: %s", newdir);
9295 return EXIT_FAILURE;
9297 /* Read current dir (get_cwd(1) is inside) and set PWD.
9298 * Note: do not enforce exporting. If PWD was unset or unexported,
9299 * set it again, but do not export. bash does the same.
9301 set_pwd_var(/*flag:*/ 0);
9302 return EXIT_SUCCESS;
9305 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9308 return EXIT_SUCCESS;
9311 static int FAST_FUNC builtin_eval(char **argv)
9313 int rcode = EXIT_SUCCESS;
9315 argv = skip_dash_dash(argv);
9317 char *str = expand_strvec_to_string(argv);
9319 * eval "echo Hi; done" ("done" is syntax error):
9320 * "echo Hi" will not execute too.
9322 parse_and_run_string(str);
9324 rcode = G.last_exitcode;
9329 static int FAST_FUNC builtin_exec(char **argv)
9331 argv = skip_dash_dash(argv);
9332 if (argv[0] == NULL)
9333 return EXIT_SUCCESS; /* bash does this */
9335 /* Careful: we can end up here after [v]fork. Do not restore
9336 * tty pgrp then, only top-level shell process does that */
9337 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9338 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9340 /* Saved-redirect fds, script fds and G_interactive_fd are still
9341 * open here. However, they are all CLOEXEC, and execv below
9342 * closes them. Try interactive "exec ls -l /proc/self/fd",
9343 * it should show no extra open fds in the "ls" process.
9344 * If we'd try to run builtins/NOEXECs, this would need improving.
9346 //close_saved_fds_and_FILE_fds();
9348 /* TODO: if exec fails, bash does NOT exit! We do.
9349 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9350 * and tcsetpgrp, and this is inherently racy.
9352 execvp_or_die(argv);
9355 static int FAST_FUNC builtin_exit(char **argv)
9357 debug_printf_exec("%s()\n", __func__);
9359 /* interactive bash:
9360 * # trap "echo EEE" EXIT
9363 * There are stopped jobs.
9364 * (if there are _stopped_ jobs, running ones don't count)
9367 * EEE (then bash exits)
9369 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9372 /* note: EXIT trap is run by hush_exit */
9373 argv = skip_dash_dash(argv);
9374 if (argv[0] == NULL)
9375 hush_exit(G.last_exitcode);
9376 /* mimic bash: exit 123abc == exit 255 + error msg */
9377 xfunc_error_retval = 255;
9378 /* bash: exit -2 == exit 254, no error msg */
9379 hush_exit(xatoi(argv[0]) & 0xff);
9382 #if ENABLE_HUSH_TYPE
9383 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9384 static int FAST_FUNC builtin_type(char **argv)
9386 int ret = EXIT_SUCCESS;
9392 if (0) {} /* make conditional compile easier below */
9393 /*else if (find_alias(*argv))
9394 type = "an alias";*/
9395 #if ENABLE_HUSH_FUNCTIONS
9396 else if (find_function(*argv))
9397 type = "a function";
9399 else if (find_builtin(*argv))
9400 type = "a shell builtin";
9401 else if ((path = find_in_path(*argv)) != NULL)
9404 bb_error_msg("type: %s: not found", *argv);
9409 printf("%s is %s\n", *argv, type);
9417 #if ENABLE_HUSH_READ
9418 /* Interruptibility of read builtin in bash
9419 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9421 * Empty trap makes read ignore corresponding signal, for any signal.
9424 * - terminates non-interactive shell;
9425 * - interrupts read in interactive shell;
9426 * if it has non-empty trap:
9427 * - executes trap and returns to command prompt in interactive shell;
9428 * - executes trap and returns to read in non-interactive shell;
9430 * - is ignored (does not interrupt) read in interactive shell;
9431 * - terminates non-interactive shell;
9432 * if it has non-empty trap:
9433 * - executes trap and returns to read;
9435 * - terminates shell (regardless of interactivity);
9436 * if it has non-empty trap:
9437 * - executes trap and returns to read;
9438 * SIGCHLD from children:
9439 * - does not interrupt read regardless of interactivity:
9440 * try: sleep 1 & read x; echo $x
9442 static int FAST_FUNC builtin_read(char **argv)
9449 char *opt_d = NULL; /* optimized out if !BASH */
9453 /* "!": do not abort on errors.
9454 * Option string must start with "sr" to match BUILTIN_READ_xxx
9456 read_flags = getopt32(argv,
9458 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9460 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9463 if (read_flags == (uint32_t)-1)
9464 return EXIT_FAILURE;
9466 ifs = get_local_var_value("IFS"); /* can be NULL */
9469 r = shell_builtin_read(set_local_var_from_halves,
9480 if ((uintptr_t)r == 1 && errno == EINTR) {
9481 unsigned sig = check_and_run_traps();
9486 if ((uintptr_t)r > 1) {
9487 bb_error_msg("%s", r);
9488 r = (char*)(uintptr_t)1;
9491 return (uintptr_t)r;
9495 #if ENABLE_HUSH_UMASK
9496 static int FAST_FUNC builtin_umask(char **argv)
9503 argv = skip_dash_dash(argv);
9505 mode_t old_mask = mask;
9507 /* numeric umasks are taken as-is */
9508 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9509 if (!isdigit(argv[0][0]))
9511 mask = bb_parse_mode(argv[0], mask);
9512 if (!isdigit(argv[0][0]))
9514 if ((unsigned)mask > 0777) {
9517 * bash: umask: 'q': invalid symbolic mode operator
9518 * bash: umask: 999: octal number out of range
9520 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9525 printf("%04o\n", (unsigned) mask);
9526 /* fall through and restore mask which we set to 0 */
9530 return !rc; /* rc != 0 - success */
9534 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9535 static void print_escaped(const char *s)
9540 const char *p = strchrnul(s, '\'');
9541 /* print 'xxxx', possibly just '' */
9542 printf("'%.*s'", (int)(p - s), s);
9547 /* s points to '; print "'''...'''" */
9549 do putchar('\''); while (*++s == '\'');
9555 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9556 static int helper_export_local(char **argv, unsigned flags)
9560 char *name_end = strchrnul(name, '=');
9562 /* So far we do not check that name is valid (TODO?) */
9564 if (*name_end == '\0') {
9565 struct variable *var, **vpp;
9567 vpp = get_ptr_to_local_var(name, name_end - name);
9568 var = vpp ? *vpp : NULL;
9570 if (flags & SETFLAG_UNEXPORT) {
9571 /* export -n NAME (without =VALUE) */
9573 var->flg_export = 0;
9574 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9576 } /* else: export -n NOT_EXISTING_VAR: no-op */
9579 if (flags & SETFLAG_EXPORT) {
9580 /* export NAME (without =VALUE) */
9582 var->flg_export = 1;
9583 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9584 putenv(var->varstr);
9588 if (flags & SETFLAG_MAKE_RO) {
9589 /* readonly NAME (without =VALUE) */
9591 var->flg_read_only = 1;
9595 # if ENABLE_HUSH_LOCAL
9596 /* Is this "local" bltin? */
9597 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9598 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9599 if (var && var->func_nest_level == lvl) {
9600 /* "local x=abc; ...; local x" - ignore second local decl */
9605 /* Exporting non-existing variable.
9606 * bash does not put it in environment,
9607 * but remembers that it is exported,
9608 * and does put it in env when it is set later.
9609 * We just set it to "" and export.
9611 /* Or, it's "local NAME" (without =VALUE).
9612 * bash sets the value to "".
9614 /* Or, it's "readonly NAME" (without =VALUE).
9615 * bash remembers NAME and disallows its creation
9618 name = xasprintf("%s=", name);
9620 /* (Un)exporting/making local NAME=VALUE */
9621 name = xstrdup(name);
9623 if (set_local_var(name, flags))
9624 return EXIT_FAILURE;
9626 return EXIT_SUCCESS;
9630 #if ENABLE_HUSH_EXPORT
9631 static int FAST_FUNC builtin_export(char **argv)
9633 unsigned opt_unexport;
9635 #if ENABLE_HUSH_EXPORT_N
9636 /* "!": do not abort on errors */
9637 opt_unexport = getopt32(argv, "!n");
9638 if (opt_unexport == (uint32_t)-1)
9639 return EXIT_FAILURE;
9646 if (argv[0] == NULL) {
9653 /* ash emits: export VAR='VAL'
9654 * bash: declare -x VAR="VAL"
9655 * we follow ash example */
9656 const char *s = *e++;
9657 const char *p = strchr(s, '=');
9659 if (!p) /* wtf? take next variable */
9662 printf("export %.*s", (int)(p - s) + 1, s);
9663 print_escaped(p + 1);
9667 /*fflush_all(); - done after each builtin anyway */
9669 return EXIT_SUCCESS;
9672 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9676 #if ENABLE_HUSH_LOCAL
9677 static int FAST_FUNC builtin_local(char **argv)
9679 if (G.func_nest_level == 0) {
9680 bb_error_msg("%s: not in a function", argv[0]);
9681 return EXIT_FAILURE; /* bash compat */
9684 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9688 #if ENABLE_HUSH_READONLY
9689 static int FAST_FUNC builtin_readonly(char **argv)
9692 if (*argv == NULL) {
9693 /* bash: readonly [-p]: list all readonly VARs
9694 * (-p has no effect in bash)
9697 for (e = G.top_var; e; e = e->next) {
9698 if (e->flg_read_only) {
9699 //TODO: quote value: readonly VAR='VAL'
9700 printf("readonly %s\n", e->varstr);
9703 return EXIT_SUCCESS;
9705 return helper_export_local(argv, SETFLAG_MAKE_RO);
9709 #if ENABLE_HUSH_UNSET
9710 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9711 static int FAST_FUNC builtin_unset(char **argv)
9716 /* "!": do not abort on errors */
9717 /* "+": stop at 1st non-option */
9718 opts = getopt32(argv, "!+vf");
9719 if (opts == (unsigned)-1)
9720 return EXIT_FAILURE;
9722 bb_error_msg("unset: -v and -f are exclusive");
9723 return EXIT_FAILURE;
9729 if (!(opts & 2)) { /* not -f */
9730 if (unset_local_var(*argv)) {
9731 /* unset <nonexistent_var> doesn't fail.
9732 * Error is when one tries to unset RO var.
9733 * Message was printed by unset_local_var. */
9737 # if ENABLE_HUSH_FUNCTIONS
9749 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9750 * built-in 'set' handler
9752 * set [-abCefhmnuvx] [-o option] [argument...]
9753 * set [+abCefhmnuvx] [+o option] [argument...]
9754 * set -- [argument...]
9757 * Implementations shall support the options in both their hyphen and
9758 * plus-sign forms. These options can also be specified as options to sh.
9760 * Write out all variables and their values: set
9761 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9762 * Turn on the -x and -v options: set -xv
9763 * Unset all positional parameters: set --
9764 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9765 * Set the positional parameters to the expansion of x, even if x expands
9766 * with a leading '-' or '+': set -- $x
9768 * So far, we only support "set -- [argument...]" and some of the short names.
9770 static int FAST_FUNC builtin_set(char **argv)
9773 char **pp, **g_argv;
9774 char *arg = *++argv;
9778 for (e = G.top_var; e; e = e->next)
9780 return EXIT_SUCCESS;
9784 if (strcmp(arg, "--") == 0) {
9788 if (arg[0] != '+' && arg[0] != '-')
9790 for (n = 1; arg[n]; ++n) {
9791 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9793 if (arg[n] == 'o' && argv[1])
9796 } while ((arg = *++argv) != NULL);
9797 /* Now argv[0] is 1st argument */
9800 return EXIT_SUCCESS;
9803 /* NB: G.global_argv[0] ($0) is never freed/changed */
9804 g_argv = G.global_argv;
9805 if (G.global_args_malloced) {
9811 G.global_args_malloced = 1;
9812 pp = xzalloc(sizeof(pp[0]) * 2);
9813 pp[0] = g_argv[0]; /* retain $0 */
9816 /* This realloc's G.global_argv */
9817 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9819 G.global_argc = 1 + string_array_len(pp + 1);
9821 return EXIT_SUCCESS;
9823 /* Nothing known, so abort */
9825 bb_error_msg("set: %s: invalid option", arg);
9826 return EXIT_FAILURE;
9830 static int FAST_FUNC builtin_shift(char **argv)
9833 argv = skip_dash_dash(argv);
9835 n = bb_strtou(argv[0], NULL, 10);
9836 if (errno || n < 0) {
9837 /* shared string with ash.c */
9838 bb_error_msg("Illegal number: %s", argv[0]);
9840 * ash aborts in this case.
9841 * bash prints error message and set $? to 1.
9842 * Interestingly, for "shift 99999" bash does not
9843 * print error message, but does set $? to 1
9844 * (and does no shifting at all).
9848 if (n >= 0 && n < G.global_argc) {
9849 if (G_global_args_malloced) {
9852 free(G.global_argv[m++]);
9855 memmove(&G.global_argv[1], &G.global_argv[n+1],
9856 G.global_argc * sizeof(G.global_argv[0]));
9857 return EXIT_SUCCESS;
9859 return EXIT_FAILURE;
9862 static int FAST_FUNC builtin_source(char **argv)
9864 char *arg_path, *filename;
9867 char *args_need_save;
9868 #if ENABLE_HUSH_FUNCTIONS
9872 argv = skip_dash_dash(argv);
9875 /* bash says: "bash: .: filename argument required" */
9876 return 2; /* bash compat */
9879 if (!strchr(filename, '/')) {
9880 arg_path = find_in_path(filename);
9882 filename = arg_path;
9884 input = remember_FILE(fopen_or_warn(filename, "r"));
9887 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9888 /* POSIX: non-interactive shell should abort here,
9889 * not merely fail. So far no one complained :)
9891 return EXIT_FAILURE;
9894 #if ENABLE_HUSH_FUNCTIONS
9895 sv_flg = G_flag_return_in_progress;
9896 /* "we are inside sourced file, ok to use return" */
9897 G_flag_return_in_progress = -1;
9899 args_need_save = argv[1]; /* used as a boolean variable */
9901 save_and_replace_G_args(&sv, argv);
9903 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9904 G.last_exitcode = 0;
9905 parse_and_run_file(input);
9906 fclose_and_forget(input);
9908 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
9909 restore_G_args(&sv, argv);
9910 #if ENABLE_HUSH_FUNCTIONS
9911 G_flag_return_in_progress = sv_flg;
9914 return G.last_exitcode;
9917 #if ENABLE_HUSH_TRAP
9918 static int FAST_FUNC builtin_trap(char **argv)
9924 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9929 /* No args: print all trapped */
9930 for (i = 0; i < NSIG; ++i) {
9933 print_escaped(G_traps[i]);
9934 /* note: bash adds "SIG", but only if invoked
9935 * as "bash". If called as "sh", or if set -o posix,
9936 * then it prints short signal names.
9937 * We are printing short names: */
9938 printf(" %s\n", get_signame(i));
9941 /*fflush_all(); - done after each builtin anyway */
9942 return EXIT_SUCCESS;
9946 /* If first arg is a number: reset all specified signals */
9947 sig = bb_strtou(*argv, NULL, 10);
9953 sighandler_t handler;
9955 sig = get_signum(*argv++);
9958 /* Mimic bash message exactly */
9959 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
9964 G_traps[sig] = xstrdup(new_cmd);
9966 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9967 get_signame(sig), sig, G_traps[sig]);
9969 /* There is no signal for 0 (EXIT) */
9974 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9976 /* We are removing trap handler */
9977 handler = pick_sighandler(sig);
9978 install_sighandler(sig, handler);
9983 if (!argv[1]) { /* no second arg */
9984 bb_error_msg("trap: invalid arguments");
9985 return EXIT_FAILURE;
9988 /* First arg is "-": reset all specified to default */
9989 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9990 /* Everything else: set arg as signal handler
9991 * (includes "" case, which ignores signal) */
9992 if (argv[0][0] == '-') {
9993 if (argv[0][1] == '\0') { /* "-" */
9994 /* new_cmd remains NULL: "reset these sigs" */
9997 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10000 /* else: "-something", no special meaning */
10005 goto process_sig_list;
10009 #if ENABLE_HUSH_JOB
10010 static struct pipe *parse_jobspec(const char *str)
10015 if (sscanf(str, "%%%u", &jobnum) != 1) {
10017 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10019 bb_error_msg("bad argument '%s'", str);
10022 /* It is "%%", "%+" or "%" - current job */
10023 jobnum = G.last_jobid;
10025 bb_error_msg("no current job");
10029 for (pi = G.job_list; pi; pi = pi->next) {
10030 if (pi->jobid == jobnum) {
10034 bb_error_msg("%u: no such job", jobnum);
10038 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10041 const char *status_string;
10043 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10044 for (job = G.job_list; job; job = job->next) {
10045 if (job->alive_cmds == job->stopped_cmds)
10046 status_string = "Stopped";
10048 status_string = "Running";
10050 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10053 clean_up_last_dead_job();
10055 return EXIT_SUCCESS;
10058 /* built-in 'fg' and 'bg' handler */
10059 static int FAST_FUNC builtin_fg_bg(char **argv)
10064 if (!G_interactive_fd)
10065 return EXIT_FAILURE;
10067 /* If they gave us no args, assume they want the last backgrounded task */
10069 for (pi = G.job_list; pi; pi = pi->next) {
10070 if (pi->jobid == G.last_jobid) {
10074 bb_error_msg("%s: no current job", argv[0]);
10075 return EXIT_FAILURE;
10078 pi = parse_jobspec(argv[1]);
10080 return EXIT_FAILURE;
10082 /* TODO: bash prints a string representation
10083 * of job being foregrounded (like "sleep 1 | cat") */
10084 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10085 /* Put the job into the foreground. */
10086 tcsetpgrp(G_interactive_fd, pi->pgrp);
10089 /* Restart the processes in the job */
10090 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10091 for (i = 0; i < pi->num_cmds; i++) {
10092 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10094 pi->stopped_cmds = 0;
10096 i = kill(- pi->pgrp, SIGCONT);
10098 if (errno == ESRCH) {
10099 delete_finished_job(pi);
10100 return EXIT_SUCCESS;
10102 bb_perror_msg("kill (SIGCONT)");
10105 if (argv[0][0] == 'f') {
10106 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10107 return checkjobs_and_fg_shell(pi);
10109 return EXIT_SUCCESS;
10113 #if ENABLE_HUSH_KILL
10114 static int FAST_FUNC builtin_kill(char **argv)
10118 # if ENABLE_HUSH_JOB
10119 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10127 if (argv[i][0] != '%')
10130 * "kill %N" - job kill
10131 * Converting to pgrp / pid kill
10133 pi = parse_jobspec(argv[i]);
10135 /* Eat bad jobspec */
10139 argv[j - 1] = argv[j];
10146 * In jobs started under job control, we signal
10147 * entire process group by kill -PGRP_ID.
10148 * This happens, f.e., in interactive shell.
10150 * Otherwise, we signal each child via
10151 * kill PID1 PID2 PID3.
10153 * sh -c 'sleep 1|sleep 1 & kill %1'
10154 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10155 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10157 n = G_interactive_fd ? 1 : pi->num_cmds;
10158 dst = alloca(n * sizeof(int)*4);
10160 if (G_interactive_fd)
10161 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10162 else for (j = 0; j < n; j++) {
10163 struct command *cmd = &pi->cmds[j];
10164 /* Skip exited members of the job */
10168 * kill_main has matching code to expect
10169 * leading space. Needed to not confuse
10170 * negative pids with "kill -SIGNAL_NO" syntax
10172 dst += sprintf(dst, " %u", (int)cmd->pid);
10175 } while (argv[++i]);
10179 if (argv[1] || ret == 0) {
10180 ret = run_applet_main(argv, kill_main);
10182 /* else: ret = 1, "kill %bad_jobspec" case */
10187 #if ENABLE_HUSH_WAIT
10188 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10189 #if !ENABLE_HUSH_JOB
10190 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10192 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10199 if (!sigisemptyset(&G.pending_set))
10202 /* waitpid is not interruptible by SA_RESTARTed
10203 * signals which we use. Thus, this ugly dance:
10206 /* Make sure possible SIGCHLD is stored in kernel's
10207 * pending signal mask before we call waitpid.
10208 * Or else we may race with SIGCHLD, lose it,
10209 * and get stuck in sigsuspend...
10211 sigfillset(&oldset); /* block all signals, remember old set */
10212 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10214 if (!sigisemptyset(&G.pending_set)) {
10215 /* Crap! we raced with some signal! */
10219 /*errno = 0; - checkjobs does this */
10220 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10221 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10222 debug_printf_exec("checkjobs:%d\n", ret);
10223 #if ENABLE_HUSH_JOB
10224 if (waitfor_pipe) {
10225 int rcode = job_exited_or_stopped(waitfor_pipe);
10226 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10229 sigprocmask(SIG_SETMASK, &oldset, NULL);
10234 /* if ECHILD, there are no children (ret is -1 or 0) */
10235 /* if ret == 0, no children changed state */
10236 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10237 if (errno == ECHILD || ret) {
10239 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10241 sigprocmask(SIG_SETMASK, &oldset, NULL);
10244 /* Wait for SIGCHLD or any other signal */
10245 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10246 /* Note: sigsuspend invokes signal handler */
10247 sigsuspend(&oldset);
10249 sigprocmask(SIG_SETMASK, &oldset, NULL);
10251 /* So, did we get a signal? */
10252 sig = check_and_run_traps();
10253 if (sig /*&& sig != SIGCHLD - always true */) {
10254 /* Do this for any (non-ignored) signal, not only for ^C */
10258 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10263 static int FAST_FUNC builtin_wait(char **argv)
10268 argv = skip_dash_dash(argv);
10269 if (argv[0] == NULL) {
10270 /* Don't care about wait results */
10271 /* Note 1: must wait until there are no more children */
10272 /* Note 2: must be interruptible */
10274 * $ sleep 3 & sleep 6 & wait
10275 * [1] 30934 sleep 3
10276 * [2] 30935 sleep 6
10279 * $ sleep 3 & sleep 6 & wait
10280 * [1] 30936 sleep 3
10281 * [2] 30937 sleep 6
10283 * ^C <-- after ~4 sec from keyboard
10286 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10290 pid_t pid = bb_strtou(*argv, NULL, 10);
10291 if (errno || pid <= 0) {
10292 #if ENABLE_HUSH_JOB
10293 if (argv[0][0] == '%') {
10294 struct pipe *wait_pipe;
10295 ret = 127; /* bash compat for bad jobspecs */
10296 wait_pipe = parse_jobspec(*argv);
10298 ret = job_exited_or_stopped(wait_pipe);
10300 ret = wait_for_child_or_signal(wait_pipe, 0);
10302 /* waiting on "last dead job" removes it */
10303 clean_up_last_dead_job();
10306 /* else: parse_jobspec() already emitted error msg */
10310 /* mimic bash message */
10311 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10312 ret = EXIT_FAILURE;
10313 continue; /* bash checks all argv[] */
10316 /* Do we have such child? */
10317 ret = waitpid(pid, &status, WNOHANG);
10321 if (errno == ECHILD) {
10322 if (pid == G.last_bg_pid) {
10323 /* "wait $!" but last bg task has already exited. Try:
10324 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10325 * In bash it prints exitcode 0, then 3.
10326 * In dash, it is 127.
10328 ret = G.last_bg_pid_exitcode;
10330 /* Example: "wait 1". mimic bash message */
10331 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10335 bb_perror_msg("wait %s", *argv);
10337 continue; /* bash checks all argv[] */
10340 /* Yes, and it still runs */
10341 ret = wait_for_child_or_signal(NULL, pid);
10343 /* Yes, and it just exited */
10344 process_wait_result(NULL, pid, status);
10345 ret = WEXITSTATUS(status);
10346 if (WIFSIGNALED(status))
10347 ret = 128 + WTERMSIG(status);
10355 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10356 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10359 def = bb_strtou(argv[1], NULL, 10);
10360 if (errno || def < def_min || argv[2]) {
10361 bb_error_msg("%s: bad arguments", argv[0]);
10369 #if ENABLE_HUSH_LOOPS
10370 static int FAST_FUNC builtin_break(char **argv)
10373 if (G.depth_of_loop == 0) {
10374 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10375 /* if we came from builtin_continue(), need to undo "= 1" */
10376 G.flag_break_continue = 0;
10377 return EXIT_SUCCESS; /* bash compat */
10379 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10381 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10382 if (depth == UINT_MAX)
10383 G.flag_break_continue = BC_BREAK;
10384 if (G.depth_of_loop < depth)
10385 G.depth_break_continue = G.depth_of_loop;
10387 return EXIT_SUCCESS;
10390 static int FAST_FUNC builtin_continue(char **argv)
10392 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10393 return builtin_break(argv);
10397 #if ENABLE_HUSH_FUNCTIONS
10398 static int FAST_FUNC builtin_return(char **argv)
10402 if (G_flag_return_in_progress != -1) {
10403 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10404 return EXIT_FAILURE; /* bash compat */
10407 G_flag_return_in_progress = 1;
10410 * out of range: wraps around at 256, does not error out
10411 * non-numeric param:
10412 * f() { false; return qwe; }; f; echo $?
10413 * bash: return: qwe: numeric argument required <== we do this
10414 * 255 <== we also do this
10416 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10421 #if ENABLE_HUSH_TIMES
10422 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10424 static const uint8_t times_tbl[] ALIGN1 = {
10425 ' ', offsetof(struct tms, tms_utime),
10426 '\n', offsetof(struct tms, tms_stime),
10427 ' ', offsetof(struct tms, tms_cutime),
10428 '\n', offsetof(struct tms, tms_cstime),
10435 clk_tck = bb_clk_tck();
10440 unsigned sec, frac;
10442 t = *(clock_t *)(((char *) &buf) + p[1]);
10444 frac = t % clk_tck;
10445 printf("%um%u.%03us%c",
10446 sec / 60, sec % 60,
10447 (frac * 1000) / clk_tck,
10452 return EXIT_SUCCESS;
10456 #if ENABLE_HUSH_MEMLEAK
10457 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10462 # ifdef M_TRIM_THRESHOLD
10463 /* Optional. Reduces probability of false positives */
10466 /* Crude attempt to find where "free memory" starts,
10467 * sans fragmentation. */
10469 l = (unsigned long)p;
10472 if (l < (unsigned long)p) l = (unsigned long)p;
10478 struct mallinfo mi = mallinfo();
10479 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10480 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10484 if (!G.memleak_value)
10485 G.memleak_value = l;
10487 l -= G.memleak_value;
10494 /* Exitcode is "how many kilobytes we leaked since 1st call" */