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, times:
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 * times: print getrusage(SELF/CHILDREN).ru_utime/ru_stime
63 * fc -l[nr] [BEG] [END]: list range of commands in history
64 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
65 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
68 * redirection of stdout+stderr: &> and >&
69 * reserved words: function select
70 * advanced test: [[ ]]
71 * process substitution: <(list) and >(list)
74 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
75 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
76 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
78 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
79 * This is exactly equivalent to let "EXPR".
80 * $[EXPR]: synonym for $((EXPR))
81 * indirect expansion: ${!VAR}
82 * substring op on @: ${@:n:m}
85 * Some builtins mandated by standards:
86 * newgrp [GRP]: not a builtin in bash but a suid binary
87 * which spawns a new shell with new group ID
88 * In bash, export builtin is special, its arguments are assignments
89 * and therefore expansion of them should be "one-word" expansion:
90 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
92 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
93 * ls: cannot access i=a: No such file or directory
94 * ls: cannot access b: No such file or directory
95 * Note1: same applies to local builtin.
96 * Note2: bash 3.2.33(1) does this only if export word itself
98 * $ export i=`echo 'aaa bbb'`; echo "$i"
100 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
104 //config: bool "hush (64 kb)"
107 //config: hush is a small shell. It handles the normal flow control
108 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
109 //config: case/esac. Redirections, here documents, $((arithmetic))
110 //config: and functions are supported.
112 //config: It will compile and work on no-mmu systems.
114 //config: It does not handle select, aliases, tilde expansion,
115 //config: &>file and >&file redirection of stdout+stderr.
117 //config:config HUSH_BASH_COMPAT
118 //config: bool "bash-compatible extensions"
120 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
122 //config:config HUSH_BRACE_EXPANSION
123 //config: bool "Brace expansion"
125 //config: depends on HUSH_BASH_COMPAT
127 //config: Enable {abc,def} extension.
129 //config:config HUSH_INTERACTIVE
130 //config: bool "Interactive mode"
132 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
134 //config: Enable interactive mode (prompt and command editing).
135 //config: Without this, hush simply reads and executes commands
136 //config: from stdin just like a shell script from a file.
137 //config: No prompt, no PS1/PS2 magic shell variables.
139 //config:config HUSH_SAVEHISTORY
140 //config: bool "Save command history to .hush_history"
142 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
144 //config:config HUSH_JOB
145 //config: bool "Job control"
147 //config: depends on HUSH_INTERACTIVE
149 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
150 //config: command (not entire shell), fg/bg builtins work. Without this option,
151 //config: "cmd &" still works by simply spawning a process and immediately
152 //config: prompting for next command (or executing next command in a script),
153 //config: but no separate process group is formed.
155 //config:config HUSH_TICK
156 //config: bool "Support process substitution"
158 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
160 //config: Enable `command` and $(command).
162 //config:config HUSH_IF
163 //config: bool "Support if/then/elif/else/fi"
165 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
167 //config:config HUSH_LOOPS
168 //config: bool "Support for, while and until loops"
170 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
172 //config:config HUSH_CASE
173 //config: bool "Support case ... esac statement"
175 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
177 //config: Enable case ... esac statement. +400 bytes.
179 //config:config HUSH_FUNCTIONS
180 //config: bool "Support funcname() { commands; } syntax"
182 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
184 //config: Enable support for shell functions. +800 bytes.
186 //config:config HUSH_LOCAL
187 //config: bool "local builtin"
189 //config: depends on HUSH_FUNCTIONS
191 //config: Enable support for local variables in functions.
193 //config:config HUSH_RANDOM_SUPPORT
194 //config: bool "Pseudorandom generator and $RANDOM variable"
196 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
198 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
199 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
201 //config:config HUSH_MODE_X
202 //config: bool "Support 'hush -x' option and 'set -x' command"
204 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
206 //config: This instructs hush to print commands before execution.
207 //config: Adds ~300 bytes.
209 //config:config HUSH_ECHO
210 //config: bool "echo builtin"
212 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
214 //config:config HUSH_PRINTF
215 //config: bool "printf builtin"
217 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
219 //config:config HUSH_TEST
220 //config: bool "test builtin"
222 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
224 //config:config HUSH_HELP
225 //config: bool "help builtin"
227 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
229 //config:config HUSH_EXPORT
230 //config: bool "export builtin"
232 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
234 //config:config HUSH_EXPORT_N
235 //config: bool "Support 'export -n' option"
237 //config: depends on HUSH_EXPORT
239 //config: export -n unexports variables. It is a bash extension.
241 //config:config HUSH_READONLY
242 //config: bool "readonly builtin"
244 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
246 //config: Enable support for read-only variables.
248 //config:config HUSH_KILL
249 //config: bool "kill builtin (supports kill %jobspec)"
251 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
253 //config:config HUSH_WAIT
254 //config: bool "wait builtin"
256 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
258 //config:config HUSH_TRAP
259 //config: bool "trap builtin"
261 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
263 //config:config HUSH_TYPE
264 //config: bool "type builtin"
266 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
268 //config:config HUSH_READ
269 //config: bool "read builtin"
271 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
273 //config:config HUSH_SET
274 //config: bool "set builtin"
276 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
278 //config:config HUSH_UNSET
279 //config: bool "unset builtin"
281 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
283 //config:config HUSH_ULIMIT
284 //config: bool "ulimit builtin"
286 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
288 //config:config HUSH_UMASK
289 //config: bool "umask builtin"
291 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
293 //config:config HUSH_MEMLEAK
294 //config: bool "memleak builtin (debugging)"
296 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
298 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
299 // APPLET_ODDNAME:name main location suid_type help
300 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
301 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
303 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
304 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
305 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
306 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
308 /* -i (interactive) and -s (read stdin) are also accepted,
309 * but currently do nothing, therefore aren't shown in help.
310 * NOMMU-specific options are not meant to be used by users,
311 * therefore we don't show them either.
313 //usage:#define hush_trivial_usage
314 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
315 //usage:#define hush_full_usage "\n\n"
316 //usage: "Unix shell interpreter"
318 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
319 || defined(__APPLE__) \
321 # include <malloc.h> /* for malloc_trim */
324 /* #include <dmalloc.h> */
326 # include <fnmatch.h>
328 #include <sys/utsname.h> /* for setting $HOSTNAME */
330 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
332 #include "shell_common.h"
335 #if ENABLE_HUSH_RANDOM_SUPPORT
338 # define CLEAR_RANDOM_T(rnd) ((void)0)
340 #ifndef F_DUPFD_CLOEXEC
341 # define F_DUPFD_CLOEXEC F_DUPFD
344 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
348 /* So far, all bash compat is controlled by one config option */
349 /* Separate defines document which part of code implements what */
350 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
351 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
352 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
353 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
354 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
355 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
359 #define LEAK_HUNTING 0
360 #define BUILD_AS_NOMMU 0
361 /* Enable/disable sanity checks. Ok to enable in production,
362 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
363 * Keeping 1 for now even in released versions.
366 /* Slightly bigger (+200 bytes), but faster hush.
367 * So far it only enables a trick with counting SIGCHLDs and forks,
368 * which allows us to do fewer waitpid's.
369 * (we can detect a case where neither forks were done nor SIGCHLDs happened
370 * and therefore waitpid will return the same result as last time)
372 #define ENABLE_HUSH_FAST 0
373 /* TODO: implement simplified code for users which do not need ${var%...} ops
374 * So far ${var%...} ops are always enabled:
376 #define ENABLE_HUSH_DOLLAR_OPS 1
381 # undef USE_FOR_NOMMU
384 # define USE_FOR_NOMMU(...) __VA_ARGS__
385 # define USE_FOR_MMU(...)
388 #include "NUM_APPLETS.h"
390 /* STANDALONE does not make sense, and won't compile */
391 # undef CONFIG_FEATURE_SH_STANDALONE
392 # undef ENABLE_FEATURE_SH_STANDALONE
393 # undef IF_FEATURE_SH_STANDALONE
394 # undef IF_NOT_FEATURE_SH_STANDALONE
395 # define ENABLE_FEATURE_SH_STANDALONE 0
396 # define IF_FEATURE_SH_STANDALONE(...)
397 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
400 #if !ENABLE_HUSH_INTERACTIVE
401 # undef ENABLE_FEATURE_EDITING
402 # define ENABLE_FEATURE_EDITING 0
403 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
404 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
405 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
406 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
409 /* Do we support ANY keywords? */
410 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
411 # define HAS_KEYWORDS 1
412 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
413 # define IF_HAS_NO_KEYWORDS(...)
415 # define HAS_KEYWORDS 0
416 # define IF_HAS_KEYWORDS(...)
417 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
420 /* If you comment out one of these below, it will be #defined later
421 * to perform debug printfs to stderr: */
422 #define debug_printf(...) do {} while (0)
423 /* Finer-grained debug switches */
424 #define debug_printf_parse(...) do {} while (0)
425 #define debug_print_tree(a, b) do {} while (0)
426 #define debug_printf_exec(...) do {} while (0)
427 #define debug_printf_env(...) do {} while (0)
428 #define debug_printf_jobs(...) do {} while (0)
429 #define debug_printf_expand(...) do {} while (0)
430 #define debug_printf_varexp(...) do {} while (0)
431 #define debug_printf_glob(...) do {} while (0)
432 #define debug_printf_redir(...) do {} while (0)
433 #define debug_printf_list(...) do {} while (0)
434 #define debug_printf_subst(...) do {} while (0)
435 #define debug_printf_clean(...) do {} while (0)
437 #define ERR_PTR ((void*)(long)1)
439 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
441 #define _SPECIAL_VARS_STR "_*@$!?#"
442 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
443 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
444 #if BASH_PATTERN_SUBST
445 /* Support / and // replace ops */
446 /* Note that // is stored as \ in "encoded" string representation */
447 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
448 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
449 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
451 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
452 # define VAR_SUBST_OPS "%#:-=+?"
453 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
456 #define SPECIAL_VAR_SYMBOL 3
460 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
462 /* This supports saving pointers malloced in vfork child,
463 * to be freed in the parent.
466 typedef struct nommu_save_t {
468 struct variable *old_vars;
470 char **argv_from_re_execing;
483 #if ENABLE_HUSH_LOOPS
490 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
495 /* three pseudo-keywords support contrived "case" syntax: */
496 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
497 RES_MATCH , /* "word)" */
498 RES_CASE_BODY, /* "this command is inside CASE" */
505 typedef struct o_string {
507 int length; /* position where data is appended */
510 /* At least some part of the string was inside '' or "",
511 * possibly empty one: word"", wo''rd etc. */
512 smallint has_quoted_part;
513 smallint has_empty_slot;
514 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
517 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
519 /* Protect newly added chars against globbing
520 * by prepending \ to *, ?, [, \ */
521 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
524 MAYBE_ASSIGNMENT = 0,
525 DEFINITELY_ASSIGNMENT = 1,
527 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
530 /* Used for initialization: o_string foo = NULL_O_STRING; */
531 #define NULL_O_STRING { NULL }
533 #ifndef debug_printf_parse
534 static const char *const assignment_flag[] = {
536 "DEFINITELY_ASSIGNMENT",
542 typedef struct in_str {
544 #if ENABLE_HUSH_INTERACTIVE
545 smallint promptmode; /* 0: PS1, 1: PS2 */
552 /* The descrip member of this structure is only used to make
553 * debugging output pretty */
554 static const struct {
556 signed char default_fd;
559 { O_RDONLY, 0, "<" },
560 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
561 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
562 { O_CREAT|O_RDWR, 1, "<>" },
563 { O_RDONLY, 0, "<<" },
564 /* Should not be needed. Bogus default_fd helps in debugging */
565 /* { O_RDONLY, 77, "<<" }, */
568 struct redir_struct {
569 struct redir_struct *next;
570 char *rd_filename; /* filename */
571 int rd_fd; /* fd to redirect */
572 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
574 smallint rd_type; /* (enum redir_type) */
575 /* note: for heredocs, rd_filename contains heredoc delimiter,
576 * and subsequently heredoc itself; and rd_dup is a bitmask:
577 * bit 0: do we need to trim leading tabs?
578 * bit 1: is heredoc quoted (<<'delim' syntax) ?
581 typedef enum redir_type {
583 REDIRECT_OVERWRITE = 1,
586 REDIRECT_HEREDOC = 4,
587 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
590 REDIRFD_SYNTAX_ERR = -2,
591 REDIRFD_TO_FILE = -1,
592 /* otherwise, rd_fd is redirected to rd_dup */
594 HEREDOC_SKIPTABS = 1,
600 pid_t pid; /* 0 if exited */
601 int assignment_cnt; /* how many argv[i] are assignments? */
602 smallint cmd_type; /* CMD_xxx */
604 #define CMD_SUBSHELL 1
606 /* used for "[[ EXPR ]]" */
607 # define CMD_SINGLEWORD_NOGLOB 2
609 #if ENABLE_HUSH_FUNCTIONS
610 # define CMD_FUNCDEF 3
613 smalluint cmd_exitcode;
614 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
617 char *group_as_string;
619 #if ENABLE_HUSH_FUNCTIONS
620 struct function *child_func;
621 /* This field is used to prevent a bug here:
622 * while...do f1() {a;}; f1; f1() {b;}; f1; done
623 * When we execute "f1() {a;}" cmd, we create new function and clear
624 * cmd->group, cmd->group_as_string, cmd->argv[0].
625 * When we execute "f1() {b;}", we notice that f1 exists,
626 * and that its "parent cmd" struct is still "alive",
627 * we put those fields back into cmd->xxx
628 * (struct function has ->parent_cmd ptr to facilitate that).
629 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
630 * Without this trick, loop would execute a;b;b;b;...
631 * instead of correct sequence a;b;a;b;...
632 * When command is freed, it severs the link
633 * (sets ->child_func->parent_cmd to NULL).
636 char **argv; /* command name and arguments */
637 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
638 * and on execution these are substituted with their values.
639 * Substitution can make _several_ words out of one argv[n]!
640 * Example: argv[0]=='.^C*^C.' here: echo .$*.
641 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
643 struct redir_struct *redirects; /* I/O redirections */
645 /* Is there anything in this command at all? */
646 #define IS_NULL_CMD(cmd) \
647 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
651 int num_cmds; /* total number of commands in pipe */
652 int alive_cmds; /* number of commands running (not exited) */
653 int stopped_cmds; /* number of commands alive, but stopped */
655 unsigned jobid; /* job number */
656 pid_t pgrp; /* process group ID for the job */
657 char *cmdtext; /* name of job */
659 struct command *cmds; /* array of commands in pipe */
660 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
661 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
662 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
664 typedef enum pipe_style {
670 /* Is there anything in this pipe at all? */
671 #define IS_NULL_PIPE(pi) \
672 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
674 /* This holds pointers to the various results of parsing */
675 struct parse_context {
676 /* linked list of pipes */
677 struct pipe *list_head;
678 /* last pipe (being constructed right now) */
680 /* last command in pipe (being constructed right now) */
681 struct command *command;
682 /* last redirect in command->redirects list */
683 struct redir_struct *pending_redirect;
689 smallint ctx_inverted; /* "! cmd | cmd" */
691 smallint ctx_dsemicolon; /* ";;" seen */
693 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
695 /* group we are enclosed in:
696 * example: "if pipe1; pipe2; then pipe3; fi"
697 * when we see "if" or "then", we malloc and copy current context,
698 * and make ->stack point to it. then we parse pipeN.
699 * when closing "then" / fi" / whatever is found,
700 * we move list_head into ->stack->command->group,
701 * copy ->stack into current context, and delete ->stack.
702 * (parsing of { list } and ( list ) doesn't use this method)
704 struct parse_context *stack;
708 /* On program start, environ points to initial environment.
709 * putenv adds new pointers into it, unsetenv removes them.
710 * Neither of these (de)allocates the strings.
711 * setenv allocates new strings in malloc space and does putenv,
712 * and thus setenv is unusable (leaky) for shell's purposes */
713 #define setenv(...) setenv_is_leaky_dont_use()
715 struct variable *next;
716 char *varstr; /* points to "name=" portion */
717 #if ENABLE_HUSH_LOCAL
718 unsigned func_nest_level;
720 int max_len; /* if > 0, name is part of initial env; else name is malloced */
721 smallint flg_export; /* putenv should be done on this var */
722 smallint flg_read_only;
730 #if ENABLE_HUSH_FUNCTIONS
732 struct function *next;
734 struct command *parent_cmd;
737 char *body_as_string;
743 /* set -/+o OPT support. (TODO: make it optional)
744 * bash supports the following opts:
755 * interactive-comments on
773 static const char o_opt_strings[] ALIGN1 =
777 #if ENABLE_HUSH_MODE_X
785 #if ENABLE_HUSH_MODE_X
793 struct FILE_list *next;
799 /* "Globals" within this file */
800 /* Sorted roughly by size (smaller offsets == smaller code) */
802 /* interactive_fd != 0 means we are an interactive shell.
803 * If we are, then saved_tty_pgrp can also be != 0, meaning
804 * that controlling tty is available. With saved_tty_pgrp == 0,
805 * job control still works, but terminal signals
806 * (^C, ^Z, ^Y, ^\) won't work at all, and background
807 * process groups can only be created with "cmd &".
808 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
809 * to give tty to the foreground process group,
810 * and will take it back when the group is stopped (^Z)
813 #if ENABLE_HUSH_INTERACTIVE
814 /* 'interactive_fd' is a fd# open to ctty, if we have one
815 * _AND_ if we decided to act interactively */
819 # define G_interactive_fd (G.interactive_fd)
821 # define G_interactive_fd 0
823 #if ENABLE_FEATURE_EDITING
824 line_input_t *line_input_state;
829 #if ENABLE_HUSH_RANDOM_SUPPORT
835 pid_t saved_tty_pgrp;
836 struct pipe *job_list;
837 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
839 # define G_saved_tty_pgrp 0
841 /* How deeply are we in context where "set -e" is ignored */
843 /* "set -e" rules (do we follow them correctly?):
844 * Exit if pipe, list, or compound command exits with a non-zero status.
845 * Shell does not exit if failed command is part of condition in
846 * if/while, part of && or || list except the last command, any command
847 * in a pipe but the last, or if the command's return value is being
848 * inverted with !. If a compound command other than a subshell returns a
849 * non-zero status because a command failed while -e was being ignored, the
850 * shell does not exit. A trap on ERR, if set, is executed before the shell
851 * exits [ERR is a bashism].
853 * If a compound command or function executes in a context where -e is
854 * ignored, none of the commands executed within are affected by the -e
855 * setting. If a compound command or function sets -e while executing in a
856 * context where -e is ignored, that setting does not have any effect until
857 * the compound command or the command containing the function call completes.
860 char o_opt[NUM_OPT_O];
861 #if ENABLE_HUSH_MODE_X
862 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
866 smallint flag_SIGINT;
867 #if ENABLE_HUSH_LOOPS
868 smallint flag_break_continue;
870 #if ENABLE_HUSH_FUNCTIONS
871 /* 0: outside of a function (or sourced file)
872 * -1: inside of a function, ok to use return builtin
873 * 1: return is invoked, skip all till end of func
875 smallint flag_return_in_progress;
876 # define G_flag_return_in_progress (G.flag_return_in_progress)
878 # define G_flag_return_in_progress 0
880 smallint exiting; /* used to prevent EXIT trap recursion */
881 /* These four support $?, $#, and $1 */
882 smalluint last_exitcode;
883 smalluint last_bg_pid_exitcode;
885 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
886 smalluint global_args_malloced;
887 # define G_global_args_malloced (G.global_args_malloced)
889 # define G_global_args_malloced 0
891 /* how many non-NULL argv's we have. NB: $# + 1 */
895 char *argv0_for_re_execing;
897 #if ENABLE_HUSH_LOOPS
898 unsigned depth_break_continue;
899 unsigned depth_of_loop;
903 struct variable *top_var;
904 char **expanded_assignments;
905 #if ENABLE_HUSH_FUNCTIONS
906 struct function *top_func;
907 # if ENABLE_HUSH_LOCAL
908 struct variable **shadowed_vars_pp;
909 unsigned func_nest_level;
912 /* Signal and trap handling */
914 unsigned count_SIGCHLD;
915 unsigned handled_SIGCHLD;
916 smallint we_have_children;
918 struct FILE_list *FILE_list;
919 /* Which signals have non-DFL handler (even with no traps set)?
920 * Set at the start to:
921 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
922 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
923 * The rest is cleared right before execv syscalls.
924 * Other than these two times, never modified.
926 unsigned special_sig_mask;
928 unsigned fatal_sig_mask;
929 # define G_fatal_sig_mask (G.fatal_sig_mask)
931 # define G_fatal_sig_mask 0
934 char **traps; /* char *traps[NSIG] */
935 # define G_traps G.traps
937 # define G_traps ((char**)NULL)
939 sigset_t pending_set;
940 #if ENABLE_HUSH_MEMLEAK
941 unsigned long memleak_value;
947 #if ENABLE_FEATURE_EDITING
948 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
951 #define G (*ptr_to_globals)
952 /* Not #defining name to G.name - this quickly gets unwieldy
953 * (too many defines). Also, I actually prefer to see when a variable
954 * is global, thus "G." prefix is a useful hint */
955 #define INIT_G() do { \
956 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
957 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
958 sigfillset(&G.sa.sa_mask); \
959 G.sa.sa_flags = SA_RESTART; \
963 /* Function prototypes for builtins */
964 static int builtin_cd(char **argv) FAST_FUNC;
966 static int builtin_echo(char **argv) FAST_FUNC;
968 static int builtin_eval(char **argv) FAST_FUNC;
969 static int builtin_exec(char **argv) FAST_FUNC;
970 static int builtin_exit(char **argv) FAST_FUNC;
971 #if ENABLE_HUSH_EXPORT
972 static int builtin_export(char **argv) FAST_FUNC;
974 #if ENABLE_HUSH_READONLY
975 static int builtin_readonly(char **argv) FAST_FUNC;
978 static int builtin_fg_bg(char **argv) FAST_FUNC;
979 static int builtin_jobs(char **argv) FAST_FUNC;
982 static int builtin_help(char **argv) FAST_FUNC;
984 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
985 static int builtin_history(char **argv) FAST_FUNC;
987 #if ENABLE_HUSH_LOCAL
988 static int builtin_local(char **argv) FAST_FUNC;
990 #if ENABLE_HUSH_MEMLEAK
991 static int builtin_memleak(char **argv) FAST_FUNC;
993 #if ENABLE_HUSH_PRINTF
994 static int builtin_printf(char **argv) FAST_FUNC;
996 static int builtin_pwd(char **argv) FAST_FUNC;
998 static int builtin_read(char **argv) FAST_FUNC;
1001 static int builtin_set(char **argv) FAST_FUNC;
1003 static int builtin_shift(char **argv) FAST_FUNC;
1004 static int builtin_source(char **argv) FAST_FUNC;
1005 #if ENABLE_HUSH_TEST || BASH_TEST2
1006 static int builtin_test(char **argv) FAST_FUNC;
1008 #if ENABLE_HUSH_TRAP
1009 static int builtin_trap(char **argv) FAST_FUNC;
1011 #if ENABLE_HUSH_TYPE
1012 static int builtin_type(char **argv) FAST_FUNC;
1014 static int builtin_true(char **argv) FAST_FUNC;
1015 #if ENABLE_HUSH_UMASK
1016 static int builtin_umask(char **argv) FAST_FUNC;
1018 #if ENABLE_HUSH_UNSET
1019 static int builtin_unset(char **argv) FAST_FUNC;
1021 #if ENABLE_HUSH_KILL
1022 static int builtin_kill(char **argv) FAST_FUNC;
1024 #if ENABLE_HUSH_WAIT
1025 static int builtin_wait(char **argv) FAST_FUNC;
1027 #if ENABLE_HUSH_LOOPS
1028 static int builtin_break(char **argv) FAST_FUNC;
1029 static int builtin_continue(char **argv) FAST_FUNC;
1031 #if ENABLE_HUSH_FUNCTIONS
1032 static int builtin_return(char **argv) FAST_FUNC;
1035 /* Table of built-in functions. They can be forked or not, depending on
1036 * context: within pipes, they fork. As simple commands, they do not.
1037 * When used in non-forking context, they can change global variables
1038 * in the parent shell process. If forked, of course they cannot.
1039 * For example, 'unset foo | whatever' will parse and run, but foo will
1040 * still be set at the end. */
1041 struct built_in_command {
1043 int (*b_function)(char **argv) FAST_FUNC;
1044 #if ENABLE_HUSH_HELP
1045 const char *b_descr;
1046 # define BLTIN(cmd, func, help) { cmd, func, help }
1048 # define BLTIN(cmd, func, help) { cmd, func }
1052 static const struct built_in_command bltins1[] = {
1053 BLTIN("." , builtin_source , "Run commands in file"),
1054 BLTIN(":" , builtin_true , NULL),
1056 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1058 #if ENABLE_HUSH_LOOPS
1059 BLTIN("break" , builtin_break , "Exit loop"),
1061 BLTIN("cd" , builtin_cd , "Change directory"),
1062 #if ENABLE_HUSH_LOOPS
1063 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1065 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1066 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1067 BLTIN("exit" , builtin_exit , NULL),
1068 #if ENABLE_HUSH_EXPORT
1069 BLTIN("export" , builtin_export , "Set environment variables"),
1072 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1074 #if ENABLE_HUSH_HELP
1075 BLTIN("help" , builtin_help , NULL),
1077 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1078 BLTIN("history" , builtin_history , "Show history"),
1081 BLTIN("jobs" , builtin_jobs , "List jobs"),
1083 #if ENABLE_HUSH_KILL
1084 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1086 #if ENABLE_HUSH_LOCAL
1087 BLTIN("local" , builtin_local , "Set local variables"),
1089 #if ENABLE_HUSH_MEMLEAK
1090 BLTIN("memleak" , builtin_memleak , NULL),
1092 #if ENABLE_HUSH_READ
1093 BLTIN("read" , builtin_read , "Input into variable"),
1095 #if ENABLE_HUSH_READONLY
1096 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1098 #if ENABLE_HUSH_FUNCTIONS
1099 BLTIN("return" , builtin_return , "Return from function"),
1102 BLTIN("set" , builtin_set , "Set positional parameters"),
1104 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1106 BLTIN("source" , builtin_source , NULL),
1108 #if ENABLE_HUSH_TRAP
1109 BLTIN("trap" , builtin_trap , "Trap signals"),
1111 BLTIN("true" , builtin_true , NULL),
1112 #if ENABLE_HUSH_TYPE
1113 BLTIN("type" , builtin_type , "Show command type"),
1115 #if ENABLE_HUSH_ULIMIT
1116 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1118 #if ENABLE_HUSH_UMASK
1119 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1121 #if ENABLE_HUSH_UNSET
1122 BLTIN("unset" , builtin_unset , "Unset variables"),
1124 #if ENABLE_HUSH_WAIT
1125 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1128 /* These builtins won't be used if we are on NOMMU and need to re-exec
1129 * (it's cheaper to run an external program in this case):
1131 static const struct built_in_command bltins2[] = {
1132 #if ENABLE_HUSH_TEST
1133 BLTIN("[" , builtin_test , NULL),
1136 BLTIN("[[" , builtin_test , NULL),
1138 #if ENABLE_HUSH_ECHO
1139 BLTIN("echo" , builtin_echo , NULL),
1141 #if ENABLE_HUSH_PRINTF
1142 BLTIN("printf" , builtin_printf , NULL),
1144 BLTIN("pwd" , builtin_pwd , NULL),
1145 #if ENABLE_HUSH_TEST
1146 BLTIN("test" , builtin_test , NULL),
1154 /* prevent disasters with G.debug_indent < 0 */
1155 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1156 # define debug_enter() (G.debug_indent++)
1157 # define debug_leave() (G.debug_indent--)
1159 # define indent() ((void)0)
1160 # define debug_enter() ((void)0)
1161 # define debug_leave() ((void)0)
1164 #ifndef debug_printf
1165 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1168 #ifndef debug_printf_parse
1169 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1172 #ifndef debug_printf_exec
1173 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1176 #ifndef debug_printf_env
1177 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1180 #ifndef debug_printf_jobs
1181 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1182 # define DEBUG_JOBS 1
1184 # define DEBUG_JOBS 0
1187 #ifndef debug_printf_expand
1188 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1189 # define DEBUG_EXPAND 1
1191 # define DEBUG_EXPAND 0
1194 #ifndef debug_printf_varexp
1195 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1198 #ifndef debug_printf_glob
1199 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1200 # define DEBUG_GLOB 1
1202 # define DEBUG_GLOB 0
1205 #ifndef debug_printf_redir
1206 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1209 #ifndef debug_printf_list
1210 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1213 #ifndef debug_printf_subst
1214 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1217 #ifndef debug_printf_clean
1218 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1219 # define DEBUG_CLEAN 1
1221 # define DEBUG_CLEAN 0
1225 static void debug_print_strings(const char *prefix, char **vv)
1228 fdprintf(2, "%s:\n", prefix);
1230 fdprintf(2, " '%s'\n", *vv++);
1233 # define debug_print_strings(prefix, vv) ((void)0)
1237 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1240 static void *xxmalloc(int lineno, size_t size)
1242 void *ptr = xmalloc((size + 0xff) & ~0xff);
1243 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1246 static void *xxrealloc(int lineno, void *ptr, size_t size)
1248 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1249 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1252 static char *xxstrdup(int lineno, const char *str)
1254 char *ptr = xstrdup(str);
1255 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1258 static void xxfree(void *ptr)
1260 fdprintf(2, "free %p\n", ptr);
1263 # define xmalloc(s) xxmalloc(__LINE__, s)
1264 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1265 # define xstrdup(s) xxstrdup(__LINE__, s)
1266 # define free(p) xxfree(p)
1270 /* Syntax and runtime errors. They always abort scripts.
1271 * In interactive use they usually discard unparsed and/or unexecuted commands
1272 * and return to the prompt.
1273 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1276 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1277 # define syntax_error(lineno, msg) syntax_error(msg)
1278 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1279 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1280 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1281 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1284 static void die_if_script(void)
1286 if (!G_interactive_fd) {
1287 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1288 xfunc_error_retval = G.last_exitcode;
1293 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1298 bb_error_msg("hush.c:%u", lineno);
1301 bb_verror_msg(fmt, p, NULL);
1306 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1309 bb_error_msg("syntax error: %s", msg);
1311 bb_error_msg("syntax error");
1315 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1317 bb_error_msg("syntax error at '%s'", msg);
1321 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1323 bb_error_msg("syntax error: unterminated %s", s);
1324 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1328 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1330 char msg[2] = { ch, '\0' };
1331 syntax_error_unterm_str(lineno, msg);
1334 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1340 bb_error_msg("hush.c:%u", lineno);
1342 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1347 # undef msg_and_die_if_script
1348 # undef syntax_error
1349 # undef syntax_error_at
1350 # undef syntax_error_unterm_ch
1351 # undef syntax_error_unterm_str
1352 # undef syntax_error_unexpected_ch
1354 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1355 # define syntax_error(msg) syntax_error(__LINE__, msg)
1356 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1357 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1358 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1359 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1363 #if ENABLE_HUSH_INTERACTIVE
1364 static void cmdedit_update_prompt(void);
1366 # define cmdedit_update_prompt() ((void)0)
1370 /* Utility functions
1372 /* Replace each \x with x in place, return ptr past NUL. */
1373 static char *unbackslash(char *src)
1375 char *dst = src = strchrnul(src, '\\');
1379 if ((*dst++ = *src++) == '\0')
1385 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1406 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1407 v[count1 + count2] = NULL;
1410 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1414 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1416 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1417 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1420 #define add_strings_to_strings(strings, add, need_to_dup) \
1421 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1424 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1425 static char **add_string_to_strings(char **strings, char *add)
1430 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1433 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1435 char **ptr = add_string_to_strings(strings, add);
1436 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1439 #define add_string_to_strings(strings, add) \
1440 xx_add_string_to_strings(__LINE__, strings, add)
1443 static void free_strings(char **strings)
1457 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1461 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1471 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1475 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1481 /* fd was not open? */
1486 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1487 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1493 /* Manipulating the list of open FILEs */
1494 static FILE *remember_FILE(FILE *fp)
1497 struct FILE_list *n = xmalloc(sizeof(*n));
1498 n->next = G.FILE_list;
1502 close_on_exec_on(n->fd);
1506 static void fclose_and_forget(FILE *fp)
1508 struct FILE_list **pp = &G.FILE_list;
1510 struct FILE_list *cur = *pp;
1511 if (cur->fp == fp) {
1520 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1522 struct FILE_list *fl = G.FILE_list;
1525 /* We use it only on script files, they are all CLOEXEC */
1526 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1527 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1534 static void restore_redirected_FILEs(void)
1536 struct FILE_list *fl = G.FILE_list;
1538 int should_be = fileno(fl->fp);
1539 if (fl->fd != should_be) {
1540 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1541 xmove_fd(fl->fd, should_be);
1547 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1548 static void close_all_FILE_list(void)
1550 struct FILE_list *fl = G.FILE_list;
1552 /* fclose would also free FILE object.
1553 * It is disastrous if we share memory with a vforked parent.
1554 * I'm not sure we never come here after vfork.
1555 * Therefore just close fd, nothing more.
1557 /*fclose(fl->fp); - unsafe */
1563 static int fd_in_FILEs(int fd)
1565 struct FILE_list *fl = G.FILE_list;
1575 /* Helpers for setting new $n and restoring them back
1577 typedef struct save_arg_t {
1581 IF_HUSH_SET(smallint sv_g_malloced;)
1584 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1586 sv->sv_argv0 = argv[0];
1587 sv->sv_g_argv = G.global_argv;
1588 sv->sv_g_argc = G.global_argc;
1589 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1591 argv[0] = G.global_argv[0]; /* retain $0 */
1592 G.global_argv = argv;
1593 IF_HUSH_SET(G.global_args_malloced = 0;)
1595 G.global_argc = 1 + string_array_len(argv + 1);
1598 static void restore_G_args(save_arg_t *sv, char **argv)
1601 if (G.global_args_malloced) {
1602 /* someone ran "set -- arg1 arg2 ...", undo */
1603 char **pp = G.global_argv;
1604 while (*++pp) /* note: does not free $0 */
1606 free(G.global_argv);
1609 argv[0] = sv->sv_argv0;
1610 G.global_argv = sv->sv_g_argv;
1611 G.global_argc = sv->sv_g_argc;
1612 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1616 /* Basic theory of signal handling in shell
1617 * ========================================
1618 * This does not describe what hush does, rather, it is current understanding
1619 * what it _should_ do. If it doesn't, it's a bug.
1620 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1622 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1623 * is finished or backgrounded. It is the same in interactive and
1624 * non-interactive shells, and is the same regardless of whether
1625 * a user trap handler is installed or a shell special one is in effect.
1626 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1627 * backgrounds (i.e. stops) or kills all members of currently running
1630 * Wait builtin is interruptible by signals for which user trap is set
1631 * or by SIGINT in interactive shell.
1633 * Trap handlers will execute even within trap handlers. (right?)
1635 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1636 * except for handlers set to '' (empty string).
1638 * If job control is off, backgrounded commands ("cmd &")
1639 * have SIGINT, SIGQUIT set to SIG_IGN.
1641 * Commands which are run in command substitution ("`cmd`")
1642 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1644 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1645 * by the shell from its parent.
1647 * Signals which differ from SIG_DFL action
1648 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1651 * SIGTERM (interactive): ignore
1652 * SIGHUP (interactive):
1653 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1654 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1655 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1656 * that all pipe members are stopped. Try this in bash:
1657 * while :; do :; done - ^Z does not background it
1658 * (while :; do :; done) - ^Z backgrounds it
1659 * SIGINT (interactive): wait for last pipe, ignore the rest
1660 * of the command line, show prompt. NB: ^C does not send SIGINT
1661 * to interactive shell while shell is waiting for a pipe,
1662 * since shell is bg'ed (is not in foreground process group).
1663 * Example 1: this waits 5 sec, but does not execute ls:
1664 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1665 * Example 2: this does not wait and does not execute ls:
1666 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1667 * Example 3: this does not wait 5 sec, but executes ls:
1668 * "sleep 5; ls -l" + press ^C
1669 * Example 4: this does not wait and does not execute ls:
1670 * "sleep 5 & wait; ls -l" + press ^C
1672 * (What happens to signals which are IGN on shell start?)
1673 * (What happens with signal mask on shell start?)
1675 * Old implementation
1676 * ==================
1677 * We use in-kernel pending signal mask to determine which signals were sent.
1678 * We block all signals which we don't want to take action immediately,
1679 * i.e. we block all signals which need to have special handling as described
1680 * above, and all signals which have traps set.
1681 * After each pipe execution, we extract any pending signals via sigtimedwait()
1684 * unsigned special_sig_mask: a mask of such "special" signals
1685 * sigset_t blocked_set: current blocked signal set
1688 * clear bit in blocked_set unless it is also in special_sig_mask
1689 * "trap 'cmd' SIGxxx":
1690 * set bit in blocked_set (even if 'cmd' is '')
1691 * after [v]fork, if we plan to be a shell:
1692 * unblock signals with special interactive handling
1693 * (child shell is not interactive),
1694 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1695 * after [v]fork, if we plan to exec:
1696 * POSIX says fork clears pending signal mask in child - no need to clear it.
1697 * Restore blocked signal set to one inherited by shell just prior to exec.
1699 * Note: as a result, we do not use signal handlers much. The only uses
1700 * are to count SIGCHLDs
1701 * and to restore tty pgrp on signal-induced exit.
1704 * Standard says "When a subshell is entered, traps that are not being ignored
1705 * are set to the default actions". bash interprets it so that traps which
1706 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1708 * Problem: the above approach makes it unwieldy to catch signals while
1709 * we are in read builtin, or while we read commands from stdin:
1710 * masked signals are not visible!
1712 * New implementation
1713 * ==================
1714 * We record each signal we are interested in by installing signal handler
1715 * for them - a bit like emulating kernel pending signal mask in userspace.
1716 * We are interested in: signals which need to have special handling
1717 * as described above, and all signals which have traps set.
1718 * Signals are recorded in pending_set.
1719 * After each pipe execution, we extract any pending signals
1722 * unsigned special_sig_mask: a mask of shell-special signals.
1723 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1724 * char *traps[sig] if trap for sig is set (even if it's '').
1725 * sigset_t pending_set: set of sigs we received.
1728 * if sig is in special_sig_mask, set handler back to:
1729 * record_pending_signo, or to IGN if it's a tty stop signal
1730 * if sig is in fatal_sig_mask, set handler back to sigexit.
1731 * else: set handler back to SIG_DFL
1732 * "trap 'cmd' SIGxxx":
1733 * set handler to record_pending_signo.
1735 * set handler to SIG_IGN.
1736 * after [v]fork, if we plan to be a shell:
1737 * set signals with special interactive handling to SIG_DFL
1738 * (because child shell is not interactive),
1739 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1740 * after [v]fork, if we plan to exec:
1741 * POSIX says fork clears pending signal mask in child - no need to clear it.
1743 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1744 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1747 * Standard says "When a subshell is entered, traps that are not being ignored
1748 * are set to the default actions". bash interprets it so that traps which
1749 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1752 SPECIAL_INTERACTIVE_SIGS = 0
1757 SPECIAL_JOBSTOP_SIGS = 0
1766 static void record_pending_signo(int sig)
1768 sigaddset(&G.pending_set, sig);
1769 #if ENABLE_HUSH_FAST
1770 if (sig == SIGCHLD) {
1772 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1777 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1779 struct sigaction old_sa;
1781 /* We could use signal() to install handlers... almost:
1782 * except that we need to mask ALL signals while handlers run.
1783 * I saw signal nesting in strace, race window isn't small.
1784 * SA_RESTART is also needed, but in Linux, signal()
1785 * sets SA_RESTART too.
1787 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1788 /* sigfillset(&G.sa.sa_mask); - already done */
1789 /* G.sa.sa_flags = SA_RESTART; - already done */
1790 G.sa.sa_handler = handler;
1791 sigaction(sig, &G.sa, &old_sa);
1792 return old_sa.sa_handler;
1795 static void hush_exit(int exitcode) NORETURN;
1797 static void restore_ttypgrp_and__exit(void) NORETURN;
1798 static void restore_ttypgrp_and__exit(void)
1800 /* xfunc has failed! die die die */
1801 /* no EXIT traps, this is an escape hatch! */
1803 hush_exit(xfunc_error_retval);
1808 /* Needed only on some libc:
1809 * It was observed that on exit(), fgetc'ed buffered data
1810 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1811 * With the net effect that even after fork(), not vfork(),
1812 * exit() in NOEXECed applet in "sh SCRIPT":
1813 * noexec_applet_here
1814 * echo END_OF_SCRIPT
1815 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1816 * This makes "echo END_OF_SCRIPT" executed twice.
1817 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1818 * and in `cmd` handling.
1819 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1821 static void fflush_and__exit(void) NORETURN;
1822 static void fflush_and__exit(void)
1825 _exit(xfunc_error_retval);
1828 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1829 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1830 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1831 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1833 /* Restores tty foreground process group, and exits.
1834 * May be called as signal handler for fatal signal
1835 * (will resend signal to itself, producing correct exit state)
1836 * or called directly with -EXITCODE.
1837 * We also call it if xfunc is exiting.
1839 static void sigexit(int sig) NORETURN;
1840 static void sigexit(int sig)
1842 /* Careful: we can end up here after [v]fork. Do not restore
1843 * tty pgrp then, only top-level shell process does that */
1844 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1845 /* Disable all signals: job control, SIGPIPE, etc.
1846 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1848 sigprocmask_allsigs(SIG_BLOCK);
1849 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1852 /* Not a signal, just exit */
1856 kill_myself_with_sig(sig); /* does not return */
1860 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1861 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1865 static sighandler_t pick_sighandler(unsigned sig)
1867 sighandler_t handler = SIG_DFL;
1868 if (sig < sizeof(unsigned)*8) {
1869 unsigned sigmask = (1 << sig);
1873 if (G_fatal_sig_mask & sigmask)
1877 /* sig has special handling? */
1878 if (G.special_sig_mask & sigmask) {
1879 handler = record_pending_signo;
1880 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1881 * in order to ignore them: they will be raised
1882 * in an endless loop when we try to do some
1883 * terminal ioctls! We do have to _ignore_ these.
1885 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1892 /* Restores tty foreground process group, and exits. */
1893 static void hush_exit(int exitcode)
1895 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1896 save_history(G.line_input_state);
1900 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1902 /* argv[0] is unused */
1903 argv[1] = G_traps[0];
1905 G.exiting = 1; /* prevent EXIT trap recursion */
1906 /* Note: G_traps[0] is not cleared!
1907 * "trap" will still show it, if executed
1912 #if ENABLE_FEATURE_CLEAN_UP
1914 struct variable *cur_var;
1915 if (G.cwd != bb_msg_unknown)
1917 cur_var = G.top_var;
1919 struct variable *tmp = cur_var;
1920 if (!cur_var->max_len)
1921 free(cur_var->varstr);
1922 cur_var = cur_var->next;
1930 sigexit(- (exitcode & 0xff));
1937 //TODO: return a mask of ALL handled sigs?
1938 static int check_and_run_traps(void)
1945 if (sigisemptyset(&G.pending_set))
1950 if (sigismember(&G.pending_set, sig)) {
1951 sigdelset(&G.pending_set, sig);
1954 } while (sig < NSIG);
1957 if (G_traps && G_traps[sig]) {
1958 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1959 if (G_traps[sig][0]) {
1960 /* We have user-defined handler */
1961 smalluint save_rcode;
1963 /* argv[0] is unused */
1964 argv[1] = G_traps[sig];
1966 save_rcode = G.last_exitcode;
1968 //FIXME: shouldn't it be set to 128 + sig instead?
1969 G.last_exitcode = save_rcode;
1971 } /* else: "" trap, ignoring signal */
1974 /* not a trap: special action */
1977 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1983 //TODO: why are we doing this? ash and dash don't do this,
1984 //they have no handler for SIGHUP at all,
1985 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
1987 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1988 /* bash is observed to signal whole process groups,
1989 * not individual processes */
1990 for (job = G.job_list; job; job = job->next) {
1993 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1994 if (kill(- job->pgrp, SIGHUP) == 0)
1995 kill(- job->pgrp, SIGCONT);
2000 #if ENABLE_HUSH_FAST
2002 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2004 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2006 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2007 * This simplifies wait builtin a bit.
2011 default: /* ignored: */
2012 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2013 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2015 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2016 * Example: wait is not interrupted by TERM
2017 * in interactive shell, because TERM is ignored.
2026 static const char *get_cwd(int force)
2028 if (force || G.cwd == NULL) {
2029 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2030 * we must not try to free(bb_msg_unknown) */
2031 if (G.cwd == bb_msg_unknown)
2033 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2035 G.cwd = bb_msg_unknown;
2042 * Shell and environment variable support
2044 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2046 struct variable **pp;
2047 struct variable *cur;
2050 while ((cur = *pp) != NULL) {
2051 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2058 static const char* FAST_FUNC get_local_var_value(const char *name)
2060 struct variable **vpp;
2061 unsigned len = strlen(name);
2063 if (G.expanded_assignments) {
2064 char **cpp = G.expanded_assignments;
2067 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2068 return cp + len + 1;
2073 vpp = get_ptr_to_local_var(name, len);
2075 return (*vpp)->varstr + len + 1;
2077 if (strcmp(name, "PPID") == 0)
2078 return utoa(G.root_ppid);
2079 // bash compat: UID? EUID?
2080 #if ENABLE_HUSH_RANDOM_SUPPORT
2081 if (strcmp(name, "RANDOM") == 0)
2082 return utoa(next_random(&G.random_gen));
2087 /* str holds "NAME=VAL" and is expected to be malloced.
2088 * We take ownership of it.
2090 #define SETFLAG_EXPORT (1 << 0)
2091 #define SETFLAG_UNEXPORT (1 << 1)
2092 #define SETFLAG_MAKE_RO (1 << 2)
2093 #define SETFLAG_LOCAL_SHIFT 3
2094 static int set_local_var(char *str, unsigned flags)
2096 struct variable **var_pp;
2097 struct variable *cur;
2098 char *free_me = NULL;
2101 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2103 eq_sign = strchr(str, '=');
2104 if (!eq_sign) { /* not expected to ever happen? */
2109 name_len = eq_sign - str + 1; /* including '=' */
2110 var_pp = &G.top_var;
2111 while ((cur = *var_pp) != NULL) {
2112 if (strncmp(cur->varstr, str, name_len) != 0) {
2113 var_pp = &cur->next;
2117 /* We found an existing var with this name */
2118 if (cur->flg_read_only) {
2119 bb_error_msg("%s: readonly variable", str);
2121 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2122 //but export per se succeeds (does put the var in env). We don't mimic that.
2125 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2126 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2131 #if ENABLE_HUSH_LOCAL
2132 if (cur->func_nest_level < local_lvl) {
2133 /* New variable is declared as local,
2134 * and existing one is global, or local
2135 * from enclosing function.
2136 * Remove and save old one: */
2137 *var_pp = cur->next;
2138 cur->next = *G.shadowed_vars_pp;
2139 *G.shadowed_vars_pp = cur;
2140 /* bash 3.2.33(1) and exported vars:
2142 * # f() { local z=a; env | grep ^z; }
2148 if (cur->flg_export)
2149 flags |= SETFLAG_EXPORT;
2153 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2158 if (cur->max_len != 0) {
2159 if (cur->max_len >= strlen(str)) {
2160 /* This one is from startup env, reuse space */
2161 strcpy(cur->varstr, str);
2166 goto set_str_and_exp;
2168 /* max_len == 0 signifies "malloced" var, which we can
2169 * (and have to) free. But we can't free(cur->varstr) here:
2170 * if cur->flg_export is 1, it is in the environment.
2171 * We should either unsetenv+free, or wait until putenv,
2172 * then putenv(new)+free(old).
2174 free_me = cur->varstr;
2175 goto set_str_and_exp;
2178 /* Not found - create new variable struct */
2179 cur = xzalloc(sizeof(*cur));
2180 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2181 cur->next = *var_pp;
2187 #if !BB_MMU || ENABLE_HUSH_READONLY
2188 if (flags & SETFLAG_MAKE_RO) {
2189 cur->flg_read_only = 1;
2192 if (flags & SETFLAG_EXPORT)
2193 cur->flg_export = 1;
2194 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2195 cmdedit_update_prompt();
2196 if (cur->flg_export) {
2197 if (flags & SETFLAG_UNEXPORT) {
2198 cur->flg_export = 0;
2199 /* unsetenv was already done */
2202 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2203 i = putenv(cur->varstr);
2204 /* only now we can free old exported malloced string */
2213 /* Used at startup and after each cd */
2214 static void set_pwd_var(unsigned flag)
2216 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2219 static int unset_local_var_len(const char *name, int name_len)
2221 struct variable *cur;
2222 struct variable **var_pp;
2225 return EXIT_SUCCESS;
2226 var_pp = &G.top_var;
2227 while ((cur = *var_pp) != NULL) {
2228 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2229 if (cur->flg_read_only) {
2230 bb_error_msg("%s: readonly variable", name);
2231 return EXIT_FAILURE;
2233 *var_pp = cur->next;
2234 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2235 bb_unsetenv(cur->varstr);
2236 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2237 cmdedit_update_prompt();
2241 return EXIT_SUCCESS;
2243 var_pp = &cur->next;
2245 return EXIT_SUCCESS;
2248 #if ENABLE_HUSH_UNSET
2249 static int unset_local_var(const char *name)
2251 return unset_local_var_len(name, strlen(name));
2255 static void unset_vars(char **strings)
2263 const char *eq = strchrnul(*v, '=');
2264 unset_local_var_len(*v, (int)(eq - *v));
2270 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ
2271 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2273 char *var = xasprintf("%s=%s", name, val);
2274 set_local_var(var, /*flag:*/ 0);
2280 * Helpers for "var1=val1 var2=val2 cmd" feature
2282 static void add_vars(struct variable *var)
2284 struct variable *next;
2288 var->next = G.top_var;
2290 if (var->flg_export) {
2291 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2292 putenv(var->varstr);
2294 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2300 static struct variable *set_vars_and_save_old(char **strings)
2303 struct variable *old = NULL;
2309 struct variable *var_p;
2310 struct variable **var_pp;
2313 eq = strchr(*s, '=');
2315 var_pp = get_ptr_to_local_var(*s, eq - *s);
2318 if (var_p->flg_read_only) {
2320 bb_error_msg("%s: readonly variable", *s);
2322 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2323 * If VAR is readonly, leaving it in the list
2324 * after asssignment error (msg above)
2325 * causes doubled error message later, on unset.
2327 debug_printf_env("removing/freeing '%s' element\n", *s);
2330 do { *p = p[1]; p++; } while (*p);
2333 /* Remove variable from global linked list */
2334 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2335 *var_pp = var_p->next;
2336 /* Add it to returned list */
2340 set_local_var(*s, SETFLAG_EXPORT);
2352 static void reinit_unicode_for_hush(void)
2354 /* Unicode support should be activated even if LANG is set
2355 * _during_ shell execution, not only if it was set when
2356 * shell was started. Therefore, re-check LANG every time:
2358 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2359 || ENABLE_UNICODE_USING_LOCALE
2361 const char *s = get_local_var_value("LC_ALL");
2362 if (!s) s = get_local_var_value("LC_CTYPE");
2363 if (!s) s = get_local_var_value("LANG");
2369 * in_str support (strings, and "strings" read from files).
2372 #if ENABLE_HUSH_INTERACTIVE
2373 /* To test correct lineedit/interactive behavior, type from command line:
2379 * It exercises a lot of corner cases.
2381 static void cmdedit_update_prompt(void)
2383 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2384 G.PS1 = get_local_var_value("PS1");
2387 G.PS2 = get_local_var_value("PS2");
2394 static const char *setup_prompt_string(int promptmode)
2396 const char *prompt_str;
2397 debug_printf("setup_prompt_string %d ", promptmode);
2398 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2399 /* Set up the prompt */
2400 if (promptmode == 0) { /* PS1 */
2402 /* bash uses $PWD value, even if it is set by user.
2403 * It uses current dir only if PWD is unset.
2404 * We always use current dir. */
2405 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2410 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2411 debug_printf("prompt_str '%s'\n", prompt_str);
2414 static int get_user_input(struct in_str *i)
2417 const char *prompt_str;
2419 prompt_str = setup_prompt_string(i->promptmode);
2420 # if ENABLE_FEATURE_EDITING
2422 reinit_unicode_for_hush();
2423 if (G.flag_SIGINT) {
2424 /* There was ^C'ed, make it look prettier: */
2428 /* buglet: SIGINT will not make new prompt to appear _at once_,
2429 * only after <Enter>. (^C works immediately) */
2430 r = read_line_input(G.line_input_state, prompt_str,
2431 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2433 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2436 check_and_run_traps();
2437 if (r != 0 && !G.flag_SIGINT)
2439 /* ^C or SIGINT: repeat */
2440 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2441 write(STDOUT_FILENO, "^C", 2);
2442 G.last_exitcode = 128 + SIGINT;
2445 /* EOF/error detected */
2447 i->peek_buf[0] = r = EOF;
2450 i->p = G.user_input_buf;
2451 return (unsigned char)*i->p++;
2455 if (i->last_char == '\0' || i->last_char == '\n') {
2456 /* Why check_and_run_traps here? Try this interactively:
2457 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2458 * $ <[enter], repeatedly...>
2459 * Without check_and_run_traps, handler never runs.
2461 check_and_run_traps();
2462 fputs(prompt_str, stdout);
2465 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2467 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2468 * no ^C masking happens during fgetc, no special code for ^C:
2469 * it generates SIGINT as usual.
2471 check_and_run_traps();
2473 G.last_exitcode = 128 + SIGINT;
2480 /* This is the magic location that prints prompts
2481 * and gets data back from the user */
2482 static int fgetc_interactive(struct in_str *i)
2485 /* If it's interactive stdin, get new line. */
2486 if (G_interactive_fd && i->file == stdin) {
2487 /* Returns first char (or EOF), the rest is in i->p[] */
2488 ch = get_user_input(i);
2489 i->promptmode = 1; /* PS2 */
2491 /* Not stdin: script file, sourced file, etc */
2492 do ch = fgetc(i->file); while (ch == '\0');
2497 static inline int fgetc_interactive(struct in_str *i)
2500 do ch = fgetc(i->file); while (ch == '\0');
2503 #endif /* INTERACTIVE */
2505 static int i_getch(struct in_str *i)
2510 /* string-based in_str */
2511 ch = (unsigned char)*i->p;
2520 /* FILE-based in_str */
2522 #if ENABLE_FEATURE_EDITING
2523 /* This can be stdin, check line editing char[] buffer */
2524 if (i->p && *i->p != '\0') {
2525 ch = (unsigned char)*i->p++;
2529 /* peek_buf[] is an int array, not char. Can contain EOF. */
2530 ch = i->peek_buf[0];
2532 int ch2 = i->peek_buf[1];
2533 i->peek_buf[0] = ch2;
2534 if (ch2 == 0) /* very likely, avoid redundant write */
2540 ch = fgetc_interactive(i);
2542 debug_printf("file_get: got '%c' %d\n", ch, ch);
2547 static int i_peek(struct in_str *i)
2552 /* string-based in_str */
2553 /* Doesn't report EOF on NUL. None of the callers care. */
2554 return (unsigned char)*i->p;
2557 /* FILE-based in_str */
2559 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2560 /* This can be stdin, check line editing char[] buffer */
2561 if (i->p && *i->p != '\0')
2562 return (unsigned char)*i->p;
2564 /* peek_buf[] is an int array, not char. Can contain EOF. */
2565 ch = i->peek_buf[0];
2569 /* Need to get a new char */
2570 ch = fgetc_interactive(i);
2571 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2573 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2574 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2580 i->peek_buf[0] = ch;
2581 /*i->peek_buf[1] = 0; - already is */
2585 /* Only ever called if i_peek() was called, and did not return EOF.
2586 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2587 * not end-of-line. Therefore we never need to read a new editing line here.
2589 static int i_peek2(struct in_str *i)
2593 /* There are two cases when i->p[] buffer exists.
2594 * (1) it's a string in_str.
2595 * (2) It's a file, and we have a saved line editing buffer.
2596 * In both cases, we know that i->p[0] exists and not NUL, and
2597 * the peek2 result is in i->p[1].
2600 return (unsigned char)i->p[1];
2602 /* Now we know it is a file-based in_str. */
2604 /* peek_buf[] is an int array, not char. Can contain EOF. */
2605 /* Is there 2nd char? */
2606 ch = i->peek_buf[1];
2608 /* We did not read it yet, get it now */
2609 do ch = fgetc(i->file); while (ch == '\0');
2610 i->peek_buf[1] = ch;
2613 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2617 static void setup_file_in_str(struct in_str *i, FILE *f)
2619 memset(i, 0, sizeof(*i));
2620 /* i->promptmode = 0; - PS1 (memset did it) */
2625 static void setup_string_in_str(struct in_str *i, const char *s)
2627 memset(i, 0, sizeof(*i));
2628 /* i->promptmode = 0; - PS1 (memset did it) */
2629 /*i->file = NULL */;
2637 #define B_CHUNK (32 * sizeof(char*))
2639 static void o_reset_to_empty_unquoted(o_string *o)
2642 o->has_quoted_part = 0;
2647 static void o_free(o_string *o)
2650 memset(o, 0, sizeof(*o));
2653 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2658 static void o_grow_by(o_string *o, int len)
2660 if (o->length + len > o->maxlen) {
2661 o->maxlen += (2 * len) | (B_CHUNK-1);
2662 o->data = xrealloc(o->data, 1 + o->maxlen);
2666 static void o_addchr(o_string *o, int ch)
2668 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2669 if (o->length < o->maxlen) {
2670 /* likely. avoid o_grow_by() call */
2672 o->data[o->length] = ch;
2674 o->data[o->length] = '\0';
2682 /* Valid only if we know o_string is not empty */
2683 static void o_delchr(o_string *o)
2686 o->data[o->length] = '\0';
2690 static void o_addblock(o_string *o, const char *str, int len)
2693 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2697 static void o_addstr(o_string *o, const char *str)
2699 o_addblock(o, str, strlen(str));
2703 static void nommu_addchr(o_string *o, int ch)
2709 # define nommu_addchr(o, str) ((void)0)
2712 static void o_addstr_with_NUL(o_string *o, const char *str)
2714 o_addblock(o, str, strlen(str) + 1);
2718 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2719 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2720 * Apparently, on unquoted $v bash still does globbing
2721 * ("v='*.txt'; echo $v" prints all .txt files),
2722 * but NOT brace expansion! Thus, there should be TWO independent
2723 * quoting mechanisms on $v expansion side: one protects
2724 * $v from brace expansion, and other additionally protects "$v" against globbing.
2725 * We have only second one.
2728 #if ENABLE_HUSH_BRACE_EXPANSION
2729 # define MAYBE_BRACES "{}"
2731 # define MAYBE_BRACES ""
2734 /* My analysis of quoting semantics tells me that state information
2735 * is associated with a destination, not a source.
2737 static void o_addqchr(o_string *o, int ch)
2740 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2745 o->data[o->length] = '\\';
2748 o->data[o->length] = ch;
2750 o->data[o->length] = '\0';
2753 static void o_addQchr(o_string *o, int ch)
2756 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2757 && strchr("*?[\\" MAYBE_BRACES, ch)
2760 o->data[o->length] = '\\';
2764 o->data[o->length] = ch;
2766 o->data[o->length] = '\0';
2769 static void o_addqblock(o_string *o, const char *str, int len)
2774 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2775 if (ordinary_cnt > len) /* paranoia */
2777 o_addblock(o, str, ordinary_cnt);
2778 if (ordinary_cnt == len)
2779 return; /* NUL is already added by o_addblock */
2780 str += ordinary_cnt;
2781 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2785 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2787 o->data[o->length] = '\\';
2791 o->data[o->length] = ch;
2794 o->data[o->length] = '\0';
2797 static void o_addQblock(o_string *o, const char *str, int len)
2799 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2800 o_addblock(o, str, len);
2803 o_addqblock(o, str, len);
2806 static void o_addQstr(o_string *o, const char *str)
2808 o_addQblock(o, str, strlen(str));
2811 /* A special kind of o_string for $VAR and `cmd` expansion.
2812 * It contains char* list[] at the beginning, which is grown in 16 element
2813 * increments. Actual string data starts at the next multiple of 16 * (char*).
2814 * list[i] contains an INDEX (int!) into this string data.
2815 * It means that if list[] needs to grow, data needs to be moved higher up
2816 * but list[i]'s need not be modified.
2817 * NB: remembering how many list[i]'s you have there is crucial.
2818 * o_finalize_list() operation post-processes this structure - calculates
2819 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2821 #if DEBUG_EXPAND || DEBUG_GLOB
2822 static void debug_print_list(const char *prefix, o_string *o, int n)
2824 char **list = (char**)o->data;
2825 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2829 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2830 prefix, list, n, string_start, o->length, o->maxlen,
2831 !!(o->o_expflags & EXP_FLAG_GLOB),
2833 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2836 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2837 o->data + (int)(uintptr_t)list[i] + string_start,
2838 o->data + (int)(uintptr_t)list[i] + string_start);
2842 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2844 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2848 # define debug_print_list(prefix, o, n) ((void)0)
2851 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2852 * in list[n] so that it points past last stored byte so far.
2853 * It returns n+1. */
2854 static int o_save_ptr_helper(o_string *o, int n)
2856 char **list = (char**)o->data;
2860 if (!o->has_empty_slot) {
2861 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2862 string_len = o->length - string_start;
2863 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2864 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2865 /* list[n] points to string_start, make space for 16 more pointers */
2866 o->maxlen += 0x10 * sizeof(list[0]);
2867 o->data = xrealloc(o->data, o->maxlen + 1);
2868 list = (char**)o->data;
2869 memmove(list + n + 0x10, list + n, string_len);
2870 o->length += 0x10 * sizeof(list[0]);
2872 debug_printf_list("list[%d]=%d string_start=%d\n",
2873 n, string_len, string_start);
2876 /* We have empty slot at list[n], reuse without growth */
2877 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2878 string_len = o->length - string_start;
2879 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2880 n, string_len, string_start);
2881 o->has_empty_slot = 0;
2883 o->has_quoted_part = 0;
2884 list[n] = (char*)(uintptr_t)string_len;
2888 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2889 static int o_get_last_ptr(o_string *o, int n)
2891 char **list = (char**)o->data;
2892 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2894 return ((int)(uintptr_t)list[n-1]) + string_start;
2897 #if ENABLE_HUSH_BRACE_EXPANSION
2898 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2899 * first, it processes even {a} (no commas), second,
2900 * I didn't manage to make it return strings when they don't match
2901 * existing files. Need to re-implement it.
2905 static int glob_needed(const char *s)
2914 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2920 /* Return pointer to next closing brace or to comma */
2921 static const char *next_brace_sub(const char *cp)
2925 while (*cp != '\0') {
2932 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2938 return *cp != '\0' ? cp : NULL;
2940 /* Recursive brace globber. Note: may garble pattern[]. */
2941 static int glob_brace(char *pattern, o_string *o, int n)
2943 char *new_pattern_buf;
2950 debug_printf_glob("glob_brace('%s')\n", pattern);
2956 if (*begin == '{') {
2957 /* Find the first sub-pattern and at the same time
2958 * find the rest after the closing brace */
2959 next = next_brace_sub(begin);
2961 /* An illegal expression */
2965 /* "{abc}" with no commas - illegal
2966 * brace expr, disregard and skip it */
2972 if (*begin == '\\' && begin[1] != '\0')
2976 debug_printf_glob("begin:%s\n", begin);
2977 debug_printf_glob("next:%s\n", next);
2979 /* Now find the end of the whole brace expression */
2981 while (*rest != '}') {
2982 rest = next_brace_sub(rest);
2984 /* An illegal expression */
2987 debug_printf_glob("rest:%s\n", rest);
2989 rest_len = strlen(++rest) + 1;
2991 /* We are sure the brace expression is well-formed */
2993 /* Allocate working buffer large enough for our work */
2994 new_pattern_buf = xmalloc(strlen(pattern));
2996 /* We have a brace expression. BEGIN points to the opening {,
2997 * NEXT points past the terminator of the first element, and REST
2998 * points past the final }. We will accumulate result names from
2999 * recursive runs for each brace alternative in the buffer using
3004 /* Construct the new glob expression */
3007 mempcpy(new_pattern_buf,
3008 /* We know the prefix for all sub-patterns */
3009 pattern, begin - pattern),
3013 /* Note: glob_brace() may garble new_pattern_buf[].
3014 * That's why we re-copy prefix every time (1st memcpy above).
3016 n = glob_brace(new_pattern_buf, o, n);
3018 /* We saw the last entry */
3022 next = next_brace_sub(next);
3024 free(new_pattern_buf);
3032 memset(&globdata, 0, sizeof(globdata));
3033 gr = glob(pattern, 0, NULL, &globdata);
3034 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3036 if (gr == GLOB_NOMATCH) {
3037 globfree(&globdata);
3038 /* NB: garbles parameter */
3039 unbackslash(pattern);
3040 o_addstr_with_NUL(o, pattern);
3041 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3042 return o_save_ptr_helper(o, n);
3044 if (gr == GLOB_NOSPACE)
3045 bb_error_msg_and_die(bb_msg_memory_exhausted);
3046 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3047 * but we didn't specify it. Paranoia again. */
3048 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3050 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3051 char **argv = globdata.gl_pathv;
3053 o_addstr_with_NUL(o, *argv);
3054 n = o_save_ptr_helper(o, n);
3060 globfree(&globdata);
3064 /* Performs globbing on last list[],
3065 * saving each result as a new list[].
3067 static int perform_glob(o_string *o, int n)
3069 char *pattern, *copy;
3071 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3073 return o_save_ptr_helper(o, n);
3074 pattern = o->data + o_get_last_ptr(o, n);
3075 debug_printf_glob("glob pattern '%s'\n", pattern);
3076 if (!glob_needed(pattern)) {
3077 /* unbackslash last string in o in place, fix length */
3078 o->length = unbackslash(pattern) - o->data;
3079 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3080 return o_save_ptr_helper(o, n);
3083 copy = xstrdup(pattern);
3084 /* "forget" pattern in o */
3085 o->length = pattern - o->data;
3086 n = glob_brace(copy, o, n);
3089 debug_print_list("perform_glob returning", o, n);
3093 #else /* !HUSH_BRACE_EXPANSION */
3096 static int glob_needed(const char *s)
3105 if (*s == '*' || *s == '[' || *s == '?')
3111 /* Performs globbing on last list[],
3112 * saving each result as a new list[].
3114 static int perform_glob(o_string *o, int n)
3120 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3122 return o_save_ptr_helper(o, n);
3123 pattern = o->data + o_get_last_ptr(o, n);
3124 debug_printf_glob("glob pattern '%s'\n", pattern);
3125 if (!glob_needed(pattern)) {
3127 /* unbackslash last string in o in place, fix length */
3128 o->length = unbackslash(pattern) - o->data;
3129 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3130 return o_save_ptr_helper(o, n);
3133 memset(&globdata, 0, sizeof(globdata));
3134 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3135 * If we glob "*.\*" and don't find anything, we need
3136 * to fall back to using literal "*.*", but GLOB_NOCHECK
3137 * will return "*.\*"!
3139 gr = glob(pattern, 0, NULL, &globdata);
3140 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3142 if (gr == GLOB_NOMATCH) {
3143 globfree(&globdata);
3146 if (gr == GLOB_NOSPACE)
3147 bb_error_msg_and_die(bb_msg_memory_exhausted);
3148 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3149 * but we didn't specify it. Paranoia again. */
3150 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3152 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3153 char **argv = globdata.gl_pathv;
3154 /* "forget" pattern in o */
3155 o->length = pattern - o->data;
3157 o_addstr_with_NUL(o, *argv);
3158 n = o_save_ptr_helper(o, n);
3164 globfree(&globdata);
3166 debug_print_list("perform_glob returning", o, n);
3170 #endif /* !HUSH_BRACE_EXPANSION */
3172 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3173 * Otherwise, just finish current list[] and start new */
3174 static int o_save_ptr(o_string *o, int n)
3176 if (o->o_expflags & EXP_FLAG_GLOB) {
3177 /* If o->has_empty_slot, list[n] was already globbed
3178 * (if it was requested back then when it was filled)
3179 * so don't do that again! */
3180 if (!o->has_empty_slot)
3181 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3183 return o_save_ptr_helper(o, n);
3186 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3187 static char **o_finalize_list(o_string *o, int n)
3192 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3194 debug_print_list("finalized", o, n);
3195 debug_printf_expand("finalized n:%d\n", n);
3196 list = (char**)o->data;
3197 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3201 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3206 static void free_pipe_list(struct pipe *pi);
3208 /* Returns pi->next - next pipe in the list */
3209 static struct pipe *free_pipe(struct pipe *pi)
3214 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3215 for (i = 0; i < pi->num_cmds; i++) {
3216 struct command *command;
3217 struct redir_struct *r, *rnext;
3219 command = &pi->cmds[i];
3220 debug_printf_clean(" command %d:\n", i);
3221 if (command->argv) {
3225 for (a = 0, p = command->argv; *p; a++, p++) {
3226 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3229 free_strings(command->argv);
3230 //command->argv = NULL;
3232 /* not "else if": on syntax error, we may have both! */
3233 if (command->group) {
3234 debug_printf_clean(" begin group (cmd_type:%d)\n",
3236 free_pipe_list(command->group);
3237 debug_printf_clean(" end group\n");
3238 //command->group = NULL;
3240 /* else is crucial here.
3241 * If group != NULL, child_func is meaningless */
3242 #if ENABLE_HUSH_FUNCTIONS
3243 else if (command->child_func) {
3244 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3245 command->child_func->parent_cmd = NULL;
3249 free(command->group_as_string);
3250 //command->group_as_string = NULL;
3252 for (r = command->redirects; r; r = rnext) {
3253 debug_printf_clean(" redirect %d%s",
3254 r->rd_fd, redir_table[r->rd_type].descrip);
3255 /* guard against the case >$FOO, where foo is unset or blank */
3256 if (r->rd_filename) {
3257 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3258 free(r->rd_filename);
3259 //r->rd_filename = NULL;
3261 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3265 //command->redirects = NULL;
3267 free(pi->cmds); /* children are an array, they get freed all at once */
3271 //pi->cmdtext = NULL;
3279 static void free_pipe_list(struct pipe *pi)
3283 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3285 debug_printf_clean("pipe followup code %d\n", pi->followup);
3291 /*** Parsing routines ***/
3293 #ifndef debug_print_tree
3294 static void debug_print_tree(struct pipe *pi, int lvl)
3296 static const char *const PIPE[] = {
3302 static const char *RES[] = {
3303 [RES_NONE ] = "NONE" ,
3306 [RES_THEN ] = "THEN" ,
3307 [RES_ELIF ] = "ELIF" ,
3308 [RES_ELSE ] = "ELSE" ,
3311 # if ENABLE_HUSH_LOOPS
3312 [RES_FOR ] = "FOR" ,
3313 [RES_WHILE] = "WHILE",
3314 [RES_UNTIL] = "UNTIL",
3316 [RES_DONE ] = "DONE" ,
3318 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3321 # if ENABLE_HUSH_CASE
3322 [RES_CASE ] = "CASE" ,
3323 [RES_CASE_IN ] = "CASE_IN" ,
3324 [RES_MATCH] = "MATCH",
3325 [RES_CASE_BODY] = "CASE_BODY",
3326 [RES_ESAC ] = "ESAC" ,
3328 [RES_XXXX ] = "XXXX" ,
3329 [RES_SNTX ] = "SNTX" ,
3331 static const char *const CMDTYPE[] = {
3335 # if ENABLE_HUSH_FUNCTIONS
3344 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3345 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3347 while (prn < pi->num_cmds) {
3348 struct command *command = &pi->cmds[prn];
3349 char **argv = command->argv;
3351 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3353 command->assignment_cnt);
3354 if (command->group) {
3355 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3356 CMDTYPE[command->cmd_type],
3359 , " group_as_string:", command->group_as_string
3364 debug_print_tree(command->group, lvl+1);
3368 if (argv) while (*argv) {
3369 fdprintf(2, " '%s'", *argv);
3379 #endif /* debug_print_tree */
3381 static struct pipe *new_pipe(void)
3384 pi = xzalloc(sizeof(struct pipe));
3385 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3389 /* Command (member of a pipe) is complete, or we start a new pipe
3390 * if ctx->command is NULL.
3391 * No errors possible here.
3393 static int done_command(struct parse_context *ctx)
3395 /* The command is really already in the pipe structure, so
3396 * advance the pipe counter and make a new, null command. */
3397 struct pipe *pi = ctx->pipe;
3398 struct command *command = ctx->command;
3400 #if 0 /* Instead we emit error message at run time */
3401 if (ctx->pending_redirect) {
3402 /* For example, "cmd >" (no filename to redirect to) */
3403 syntax_error("invalid redirect");
3404 ctx->pending_redirect = NULL;
3409 if (IS_NULL_CMD(command)) {
3410 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3414 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3415 //debug_print_tree(ctx->list_head, 20);
3417 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3420 /* Only real trickiness here is that the uncommitted
3421 * command structure is not counted in pi->num_cmds. */
3422 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3423 ctx->command = command = &pi->cmds[pi->num_cmds];
3425 memset(command, 0, sizeof(*command));
3426 return pi->num_cmds; /* used only for 0/nonzero check */
3429 static void done_pipe(struct parse_context *ctx, pipe_style type)
3433 debug_printf_parse("done_pipe entered, followup %d\n", type);
3434 /* Close previous command */
3435 not_null = done_command(ctx);
3437 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3438 ctx->ctx_inverted = 0;
3439 ctx->pipe->res_word = ctx->ctx_res_w;
3441 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3442 /* Necessary since && and || have precedence over &:
3443 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3444 * in a backgrounded subshell.
3447 struct command *command;
3449 /* Is this actually this construct, all pipes end with && or ||? */
3450 pi = ctx->list_head;
3451 while (pi != ctx->pipe) {
3452 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3457 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3458 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3459 pi = xzalloc(sizeof(*pi));
3460 pi->followup = PIPE_BG;
3462 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3463 command = &pi->cmds[0];
3464 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3465 command->cmd_type = CMD_NORMAL;
3466 command->group = ctx->list_head;
3468 command->group_as_string = xstrndup(
3469 ctx->as_string.data,
3470 ctx->as_string.length - 1 /* do not copy last char, "&" */
3473 /* Replace all pipes in ctx with one newly created */
3474 ctx->list_head = ctx->pipe = pi;
3477 ctx->pipe->followup = type;
3480 /* Without this check, even just <enter> on command line generates
3481 * tree of three NOPs (!). Which is harmless but annoying.
3482 * IOW: it is safe to do it unconditionally. */
3485 || ctx->ctx_res_w == RES_FI
3487 #if ENABLE_HUSH_LOOPS
3488 || ctx->ctx_res_w == RES_DONE
3489 || ctx->ctx_res_w == RES_FOR
3490 || ctx->ctx_res_w == RES_IN
3492 #if ENABLE_HUSH_CASE
3493 || ctx->ctx_res_w == RES_ESAC
3497 debug_printf_parse("done_pipe: adding new pipe: "
3498 "not_null:%d ctx->ctx_res_w:%d\n",
3499 not_null, ctx->ctx_res_w);
3501 ctx->pipe->next = new_p;
3503 /* RES_THEN, RES_DO etc are "sticky" -
3504 * they remain set for pipes inside if/while.
3505 * This is used to control execution.
3506 * RES_FOR and RES_IN are NOT sticky (needed to support
3507 * cases where variable or value happens to match a keyword):
3509 #if ENABLE_HUSH_LOOPS
3510 if (ctx->ctx_res_w == RES_FOR
3511 || ctx->ctx_res_w == RES_IN)
3512 ctx->ctx_res_w = RES_NONE;
3514 #if ENABLE_HUSH_CASE
3515 if (ctx->ctx_res_w == RES_MATCH)
3516 ctx->ctx_res_w = RES_CASE_BODY;
3517 if (ctx->ctx_res_w == RES_CASE)
3518 ctx->ctx_res_w = RES_CASE_IN;
3520 ctx->command = NULL; /* trick done_command below */
3521 /* Create the memory for command, roughly:
3522 * ctx->pipe->cmds = new struct command;
3523 * ctx->command = &ctx->pipe->cmds[0];
3526 //debug_print_tree(ctx->list_head, 10);
3528 debug_printf_parse("done_pipe return\n");
3531 static void initialize_context(struct parse_context *ctx)
3533 memset(ctx, 0, sizeof(*ctx));
3534 ctx->pipe = ctx->list_head = new_pipe();
3535 /* Create the memory for command, roughly:
3536 * ctx->pipe->cmds = new struct command;
3537 * ctx->command = &ctx->pipe->cmds[0];
3542 /* If a reserved word is found and processed, parse context is modified
3543 * and 1 is returned.
3546 struct reserved_combo {
3549 unsigned char assignment_flag;
3553 FLAG_END = (1 << RES_NONE ),
3555 FLAG_IF = (1 << RES_IF ),
3556 FLAG_THEN = (1 << RES_THEN ),
3557 FLAG_ELIF = (1 << RES_ELIF ),
3558 FLAG_ELSE = (1 << RES_ELSE ),
3559 FLAG_FI = (1 << RES_FI ),
3561 # if ENABLE_HUSH_LOOPS
3562 FLAG_FOR = (1 << RES_FOR ),
3563 FLAG_WHILE = (1 << RES_WHILE),
3564 FLAG_UNTIL = (1 << RES_UNTIL),
3565 FLAG_DO = (1 << RES_DO ),
3566 FLAG_DONE = (1 << RES_DONE ),
3567 FLAG_IN = (1 << RES_IN ),
3569 # if ENABLE_HUSH_CASE
3570 FLAG_MATCH = (1 << RES_MATCH),
3571 FLAG_ESAC = (1 << RES_ESAC ),
3573 FLAG_START = (1 << RES_XXXX ),
3576 static const struct reserved_combo* match_reserved_word(o_string *word)
3578 /* Mostly a list of accepted follow-up reserved words.
3579 * FLAG_END means we are done with the sequence, and are ready
3580 * to turn the compound list into a command.
3581 * FLAG_START means the word must start a new compound list.
3583 static const struct reserved_combo reserved_list[] = {
3585 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3586 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3587 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3588 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3589 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3590 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3592 # if ENABLE_HUSH_LOOPS
3593 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3594 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3595 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3596 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3597 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3598 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3600 # if ENABLE_HUSH_CASE
3601 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3602 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3605 const struct reserved_combo *r;
3607 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3608 if (strcmp(word->data, r->literal) == 0)
3613 /* Return 0: not a keyword, 1: keyword
3615 static int reserved_word(o_string *word, struct parse_context *ctx)
3617 # if ENABLE_HUSH_CASE
3618 static const struct reserved_combo reserved_match = {
3619 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3622 const struct reserved_combo *r;
3624 if (word->has_quoted_part)
3626 r = match_reserved_word(word);
3630 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3631 # if ENABLE_HUSH_CASE
3632 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3633 /* "case word IN ..." - IN part starts first MATCH part */
3634 r = &reserved_match;
3637 if (r->flag == 0) { /* '!' */
3638 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3639 syntax_error("! ! command");
3640 ctx->ctx_res_w = RES_SNTX;
3642 ctx->ctx_inverted = 1;
3645 if (r->flag & FLAG_START) {
3646 struct parse_context *old;
3648 old = xmemdup(ctx, sizeof(*ctx));
3649 debug_printf_parse("push stack %p\n", old);
3650 initialize_context(ctx);
3652 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3653 syntax_error_at(word->data);
3654 ctx->ctx_res_w = RES_SNTX;
3657 /* "{...} fi" is ok. "{...} if" is not
3659 * if { echo foo; } then { echo bar; } fi */
3660 if (ctx->command->group)
3661 done_pipe(ctx, PIPE_SEQ);
3664 ctx->ctx_res_w = r->res;
3665 ctx->old_flag = r->flag;
3666 word->o_assignment = r->assignment_flag;
3667 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3669 if (ctx->old_flag & FLAG_END) {
3670 struct parse_context *old;
3672 done_pipe(ctx, PIPE_SEQ);
3673 debug_printf_parse("pop stack %p\n", ctx->stack);
3675 old->command->group = ctx->list_head;
3676 old->command->cmd_type = CMD_NORMAL;
3678 /* At this point, the compound command's string is in
3679 * ctx->as_string... except for the leading keyword!
3680 * Consider this example: "echo a | if true; then echo a; fi"
3681 * ctx->as_string will contain "true; then echo a; fi",
3682 * with "if " remaining in old->as_string!
3686 int len = old->as_string.length;
3687 /* Concatenate halves */
3688 o_addstr(&old->as_string, ctx->as_string.data);
3689 o_free_unsafe(&ctx->as_string);
3690 /* Find where leading keyword starts in first half */
3691 str = old->as_string.data + len;
3692 if (str > old->as_string.data)
3693 str--; /* skip whitespace after keyword */
3694 while (str > old->as_string.data && isalpha(str[-1]))
3696 /* Ugh, we're done with this horrid hack */
3697 old->command->group_as_string = xstrdup(str);
3698 debug_printf_parse("pop, remembering as:'%s'\n",
3699 old->command->group_as_string);
3702 *ctx = *old; /* physical copy */
3707 #endif /* HAS_KEYWORDS */
3709 /* Word is complete, look at it and update parsing context.
3710 * Normal return is 0. Syntax errors return 1.
3711 * Note: on return, word is reset, but not o_free'd!
3713 static int done_word(o_string *word, struct parse_context *ctx)
3715 struct command *command = ctx->command;
3717 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3718 if (word->length == 0 && !word->has_quoted_part) {
3719 debug_printf_parse("done_word return 0: true null, ignored\n");
3723 if (ctx->pending_redirect) {
3724 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3725 * only if run as "bash", not "sh" */
3726 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3728 * ...the word that follows the redirection operator
3729 * shall be subjected to tilde expansion, parameter expansion,
3730 * command substitution, arithmetic expansion, and quote
3731 * removal. Pathname expansion shall not be performed
3732 * on the word by a non-interactive shell; an interactive
3733 * shell may perform it, but shall do so only when
3734 * the expansion would result in one word."
3736 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3737 /* Cater for >\file case:
3738 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3739 * Same with heredocs:
3740 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3742 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3743 unbackslash(ctx->pending_redirect->rd_filename);
3744 /* Is it <<"HEREDOC"? */
3745 if (word->has_quoted_part) {
3746 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3749 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3750 ctx->pending_redirect = NULL;
3753 # if ENABLE_HUSH_CASE
3754 if (ctx->ctx_dsemicolon
3755 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3757 /* already done when ctx_dsemicolon was set to 1: */
3758 /* ctx->ctx_res_w = RES_MATCH; */
3759 ctx->ctx_dsemicolon = 0;
3762 if (!command->argv /* if it's the first word... */
3763 # if ENABLE_HUSH_LOOPS
3764 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3765 && ctx->ctx_res_w != RES_IN
3767 # if ENABLE_HUSH_CASE
3768 && ctx->ctx_res_w != RES_CASE
3771 int reserved = reserved_word(word, ctx);
3772 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3774 o_reset_to_empty_unquoted(word);
3775 debug_printf_parse("done_word return %d\n",
3776 (ctx->ctx_res_w == RES_SNTX));
3777 return (ctx->ctx_res_w == RES_SNTX);
3780 if (strcmp(word->data, "[[") == 0) {
3781 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3787 if (command->group) {
3788 /* "{ echo foo; } echo bar" - bad */
3789 syntax_error_at(word->data);
3790 debug_printf_parse("done_word return 1: syntax error, "
3791 "groups and arglists don't mix\n");
3795 /* If this word wasn't an assignment, next ones definitely
3796 * can't be assignments. Even if they look like ones. */
3797 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3798 && word->o_assignment != WORD_IS_KEYWORD
3800 word->o_assignment = NOT_ASSIGNMENT;
3802 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3803 command->assignment_cnt++;
3804 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3806 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3807 word->o_assignment = MAYBE_ASSIGNMENT;
3809 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3811 if (word->has_quoted_part
3812 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3813 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3814 /* (otherwise it's known to be not empty and is already safe) */
3816 /* exclude "$@" - it can expand to no word despite "" */
3817 char *p = word->data;
3818 while (p[0] == SPECIAL_VAR_SYMBOL
3819 && (p[1] & 0x7f) == '@'
3820 && p[2] == SPECIAL_VAR_SYMBOL
3825 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3826 debug_print_strings("word appended to argv", command->argv);
3829 #if ENABLE_HUSH_LOOPS
3830 if (ctx->ctx_res_w == RES_FOR) {
3831 if (word->has_quoted_part
3832 || !is_well_formed_var_name(command->argv[0], '\0')
3834 /* bash says just "not a valid identifier" */
3835 syntax_error("not a valid identifier in for");
3838 /* Force FOR to have just one word (variable name) */
3839 /* NB: basically, this makes hush see "for v in ..."
3840 * syntax as if it is "for v; in ...". FOR and IN become
3841 * two pipe structs in parse tree. */
3842 done_pipe(ctx, PIPE_SEQ);
3845 #if ENABLE_HUSH_CASE
3846 /* Force CASE to have just one word */
3847 if (ctx->ctx_res_w == RES_CASE) {
3848 done_pipe(ctx, PIPE_SEQ);
3852 o_reset_to_empty_unquoted(word);
3854 debug_printf_parse("done_word return 0\n");
3859 /* Peek ahead in the input to find out if we have a "&n" construct,
3860 * as in "2>&1", that represents duplicating a file descriptor.
3862 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3863 * REDIRFD_SYNTAX_ERR if syntax error,
3864 * REDIRFD_TO_FILE if no & was seen,
3865 * or the number found.
3868 #define parse_redir_right_fd(as_string, input) \
3869 parse_redir_right_fd(input)
3871 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3877 return REDIRFD_TO_FILE;
3879 ch = i_getch(input); /* get the & */
3880 nommu_addchr(as_string, ch);
3883 ch = i_getch(input);
3884 nommu_addchr(as_string, ch);
3885 return REDIRFD_CLOSE;
3889 while (ch != EOF && isdigit(ch)) {
3890 d = d*10 + (ch-'0');
3892 ch = i_getch(input);
3893 nommu_addchr(as_string, ch);
3898 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3900 bb_error_msg("ambiguous redirect");
3901 return REDIRFD_SYNTAX_ERR;
3904 /* Return code is 0 normal, 1 if a syntax error is detected
3906 static int parse_redirect(struct parse_context *ctx,
3909 struct in_str *input)
3911 struct command *command = ctx->command;
3912 struct redir_struct *redir;
3913 struct redir_struct **redirp;
3916 dup_num = REDIRFD_TO_FILE;
3917 if (style != REDIRECT_HEREDOC) {
3918 /* Check for a '>&1' type redirect */
3919 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3920 if (dup_num == REDIRFD_SYNTAX_ERR)
3923 int ch = i_peek(input);
3924 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3925 if (dup_num) { /* <<-... */
3926 ch = i_getch(input);
3927 nommu_addchr(&ctx->as_string, ch);
3932 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3933 int ch = i_peek(input);
3935 /* >|FILE redirect ("clobbering" >).
3936 * Since we do not support "set -o noclobber" yet,
3937 * >| and > are the same for now. Just eat |.
3939 ch = i_getch(input);
3940 nommu_addchr(&ctx->as_string, ch);
3944 /* Create a new redir_struct and append it to the linked list */
3945 redirp = &command->redirects;
3946 while ((redir = *redirp) != NULL) {
3947 redirp = &(redir->next);
3949 *redirp = redir = xzalloc(sizeof(*redir));
3950 /* redir->next = NULL; */
3951 /* redir->rd_filename = NULL; */
3952 redir->rd_type = style;
3953 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3955 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3956 redir_table[style].descrip);
3958 redir->rd_dup = dup_num;
3959 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3960 /* Erik had a check here that the file descriptor in question
3961 * is legit; I postpone that to "run time"
3962 * A "-" representation of "close me" shows up as a -3 here */
3963 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3964 redir->rd_fd, redir->rd_dup);
3966 #if 0 /* Instead we emit error message at run time */
3967 if (ctx->pending_redirect) {
3968 /* For example, "cmd > <file" */
3969 syntax_error("invalid redirect");
3972 /* Set ctx->pending_redirect, so we know what to do at the
3973 * end of the next parsed word. */
3974 ctx->pending_redirect = redir;
3979 /* If a redirect is immediately preceded by a number, that number is
3980 * supposed to tell which file descriptor to redirect. This routine
3981 * looks for such preceding numbers. In an ideal world this routine
3982 * needs to handle all the following classes of redirects...
3983 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3984 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3985 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3986 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3988 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3990 * ... If n is quoted, the number shall not be recognized as part of
3991 * the redirection expression. For example:
3993 * writes the character 2 into file a"
3994 * We are getting it right by setting ->has_quoted_part on any \<char>
3996 * A -1 return means no valid number was found,
3997 * the caller should use the appropriate default for this redirection.
3999 static int redirect_opt_num(o_string *o)
4003 if (o->data == NULL)
4005 num = bb_strtou(o->data, NULL, 10);
4006 if (errno || num < 0)
4008 o_reset_to_empty_unquoted(o);
4013 #define fetch_till_str(as_string, input, word, skip_tabs) \
4014 fetch_till_str(input, word, skip_tabs)
4016 static char *fetch_till_str(o_string *as_string,
4017 struct in_str *input,
4021 o_string heredoc = NULL_O_STRING;
4023 int prev = 0; /* not \ */
4029 ch = i_getch(input);
4031 nommu_addchr(as_string, ch);
4032 if (ch == '\n' || ch == EOF) {
4034 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4035 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4036 heredoc.data[past_EOL] = '\0';
4037 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4038 return heredoc.data;
4041 /* This is a new line.
4042 * Remember position and backslash-escaping status.
4044 o_addchr(&heredoc, ch);
4047 past_EOL = heredoc.length;
4048 /* Get 1st char of next line, possibly skipping leading tabs */
4050 ch = i_getch(input);
4052 nommu_addchr(as_string, ch);
4053 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4054 /* If this immediately ended the line,
4055 * go back to end-of-line checks.
4058 goto check_heredoc_end;
4063 o_free_unsafe(&heredoc);
4066 o_addchr(&heredoc, ch);
4067 nommu_addchr(as_string, ch);
4068 if (prev == '\\' && ch == '\\')
4069 /* Correctly handle foo\\<eol> (not a line cont.) */
4070 prev = 0; /* not \ */
4076 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4077 * and load them all. There should be exactly heredoc_cnt of them.
4079 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4081 struct pipe *pi = ctx->list_head;
4083 while (pi && heredoc_cnt) {
4085 struct command *cmd = pi->cmds;
4087 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4089 cmd->argv ? cmd->argv[0] : "NONE");
4090 for (i = 0; i < pi->num_cmds; i++) {
4091 struct redir_struct *redir = cmd->redirects;
4093 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4094 i, cmd->argv ? cmd->argv[0] : "NONE");
4096 if (redir->rd_type == REDIRECT_HEREDOC) {
4099 redir->rd_type = REDIRECT_HEREDOC2;
4100 /* redir->rd_dup is (ab)used to indicate <<- */
4101 p = fetch_till_str(&ctx->as_string, input,
4102 redir->rd_filename, redir->rd_dup);
4104 syntax_error("unexpected EOF in here document");
4107 free(redir->rd_filename);
4108 redir->rd_filename = p;
4111 redir = redir->next;
4118 /* Should be 0. If it isn't, it's a parse error */
4120 bb_error_msg_and_die("heredoc BUG 2");
4126 static int run_list(struct pipe *pi);
4128 #define parse_stream(pstring, input, end_trigger) \
4129 parse_stream(input, end_trigger)
4131 static struct pipe *parse_stream(char **pstring,
4132 struct in_str *input,
4136 #if !ENABLE_HUSH_FUNCTIONS
4137 #define parse_group(dest, ctx, input, ch) \
4138 parse_group(ctx, input, ch)
4140 static int parse_group(o_string *dest, struct parse_context *ctx,
4141 struct in_str *input, int ch)
4143 /* dest contains characters seen prior to ( or {.
4144 * Typically it's empty, but for function defs,
4145 * it contains function name (without '()'). */
4146 struct pipe *pipe_list;
4148 struct command *command = ctx->command;
4150 debug_printf_parse("parse_group entered\n");
4151 #if ENABLE_HUSH_FUNCTIONS
4152 if (ch == '(' && !dest->has_quoted_part) {
4154 if (done_word(dest, ctx))
4157 goto skip; /* (... */
4158 if (command->argv[1]) { /* word word ... (... */
4159 syntax_error_unexpected_ch('(');
4162 /* it is "word(..." or "word (..." */
4164 ch = i_getch(input);
4165 while (ch == ' ' || ch == '\t');
4167 syntax_error_unexpected_ch(ch);
4170 nommu_addchr(&ctx->as_string, ch);
4172 ch = i_getch(input);
4173 while (ch == ' ' || ch == '\t' || ch == '\n');
4175 syntax_error_unexpected_ch(ch);
4178 nommu_addchr(&ctx->as_string, ch);
4179 command->cmd_type = CMD_FUNCDEF;
4184 #if 0 /* Prevented by caller */
4185 if (command->argv /* word [word]{... */
4186 || dest->length /* word{... */
4187 || dest->has_quoted_part /* ""{... */
4190 debug_printf_parse("parse_group return 1: "
4191 "syntax error, groups and arglists don't mix\n");
4196 #if ENABLE_HUSH_FUNCTIONS
4202 command->cmd_type = CMD_SUBSHELL;
4204 /* bash does not allow "{echo...", requires whitespace */
4206 if (ch != ' ' && ch != '\t' && ch != '\n'
4207 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4209 syntax_error_unexpected_ch(ch);
4213 ch = i_getch(input);
4214 nommu_addchr(&ctx->as_string, ch);
4220 # define as_string NULL
4222 char *as_string = NULL;
4224 pipe_list = parse_stream(&as_string, input, endch);
4227 o_addstr(&ctx->as_string, as_string);
4229 /* empty ()/{} or parse error? */
4230 if (!pipe_list || pipe_list == ERR_PTR) {
4231 /* parse_stream already emitted error msg */
4234 debug_printf_parse("parse_group return 1: "
4235 "parse_stream returned %p\n", pipe_list);
4238 command->group = pipe_list;
4240 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4241 command->group_as_string = as_string;
4242 debug_printf_parse("end of group, remembering as:'%s'\n",
4243 command->group_as_string);
4247 debug_printf_parse("parse_group return 0\n");
4249 /* command remains "open", available for possible redirects */
4252 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4257 ch = i_getch(input);
4260 ch2 = i_peek(input);
4263 /* backslash+newline, skip it */
4268 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4276 ch2 = i_peek2(input);
4279 /* backslash+newline, skip it */
4285 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4286 /* Subroutines for copying $(...) and `...` things */
4287 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4289 static int add_till_single_quote(o_string *dest, struct in_str *input)
4292 int ch = i_getch(input);
4294 syntax_error_unterm_ch('\'');
4302 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4303 static int add_till_double_quote(o_string *dest, struct in_str *input)
4306 int ch = i_getch(input);
4308 syntax_error_unterm_ch('"');
4313 if (ch == '\\') { /* \x. Copy both chars. */
4315 ch = i_getch(input);
4319 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4324 //if (ch == '$') ...
4327 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4329 * "Within the backquoted style of command substitution, backslash
4330 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4331 * The search for the matching backquote shall be satisfied by the first
4332 * backquote found without a preceding backslash; during this search,
4333 * if a non-escaped backquote is encountered within a shell comment,
4334 * a here-document, an embedded command substitution of the $(command)
4335 * form, or a quoted string, undefined results occur. A single-quoted
4336 * or double-quoted string that begins, but does not end, within the
4337 * "`...`" sequence produces undefined results."
4339 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4341 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4344 int ch = i_getch(input);
4348 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4349 ch = i_getch(input);
4353 && (!in_dquote || ch != '"')
4355 o_addchr(dest, '\\');
4359 syntax_error_unterm_ch('`');
4365 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4366 * quoting and nested ()s.
4367 * "With the $(command) style of command substitution, all characters
4368 * following the open parenthesis to the matching closing parenthesis
4369 * constitute the command. Any valid shell script can be used for command,
4370 * except a script consisting solely of redirections which produces
4371 * unspecified results."
4373 * echo $(echo '(TEST)' BEST) (TEST) BEST
4374 * echo $(echo 'TEST)' BEST) TEST) BEST
4375 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4377 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4378 * can contain arbitrary constructs, just like $(cmd).
4379 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4380 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4382 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4383 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4386 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4387 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4388 char end_char2 = end_ch >> 8;
4390 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4393 ch = i_getch(input);
4395 syntax_error_unterm_ch(end_ch);
4399 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4405 /* we look for closing )) of $((EXPR)) */
4406 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4407 i_getch(input); /* eat second ')' */
4412 if (ch == '(' || ch == '{') {
4413 ch = (ch == '(' ? ')' : '}');
4414 if (!add_till_closing_bracket(dest, input, ch))
4420 if (!add_till_single_quote(dest, input))
4426 if (!add_till_double_quote(dest, input))
4432 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4438 /* \x. Copy verbatim. Important for \(, \) */
4439 ch = i_getch(input);
4441 syntax_error_unterm_ch(')');
4446 /* "backslash+newline", ignore both */
4447 o_delchr(dest); /* undo insertion of '\' */
4457 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4459 /* Return code: 0 for OK, 1 for syntax error */
4461 #define parse_dollar(as_string, dest, input, quote_mask) \
4462 parse_dollar(dest, input, quote_mask)
4463 #define as_string NULL
4465 static int parse_dollar(o_string *as_string,
4467 struct in_str *input, unsigned char quote_mask)
4469 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4471 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4473 ch = i_getch(input);
4474 nommu_addchr(as_string, ch);
4476 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4478 debug_printf_parse(": '%c'\n", ch);
4479 o_addchr(dest, ch | quote_mask);
4481 ch = i_peek_and_eat_bkslash_nl(input);
4482 if (!isalnum(ch) && ch != '_') {
4483 /* End of variable name reached */
4486 ch = i_getch(input);
4487 nommu_addchr(as_string, ch);
4489 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4490 } else if (isdigit(ch)) {
4492 ch = i_getch(input);
4493 nommu_addchr(as_string, ch);
4494 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4495 debug_printf_parse(": '%c'\n", ch);
4496 o_addchr(dest, ch | quote_mask);
4497 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4498 } else switch (ch) {
4500 case '!': /* last bg pid */
4501 case '?': /* last exit code */
4502 case '#': /* number of args */
4503 case '*': /* args */
4504 case '@': /* args */
4505 goto make_one_char_var;
4509 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4511 ch = i_getch(input); /* eat '{' */
4512 nommu_addchr(as_string, ch);
4514 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4515 /* It should be ${?}, or ${#var},
4516 * or even ${?+subst} - operator acting on a special variable,
4517 * or the beginning of variable name.
4520 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4523 syntax_error_unterm_str("${name}");
4524 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4527 nommu_addchr(as_string, ch);
4531 /* It's possible to just call add_till_closing_bracket() at this point.
4532 * However, this regresses some of our testsuite cases
4533 * which check invalid constructs like ${%}.
4534 * Oh well... let's check that the var name part is fine... */
4540 debug_printf_parse(": '%c'\n", ch);
4542 ch = i_getch(input);
4543 nommu_addchr(as_string, ch);
4547 if (!isalnum(ch) && ch != '_') {
4549 unsigned char last_ch;
4550 /* handle parameter expansions
4551 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4553 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4554 if (len_single_ch != '#'
4555 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4556 || i_peek(input) != '}'
4558 goto bad_dollar_syntax;
4560 /* else: it's "length of C" ${#C} op,
4561 * where C is a single char
4562 * special var name, e.g. ${#!}.
4565 /* Eat everything until closing '}' (or ':') */
4569 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4571 /* It's ${var:N[:M]} thing */
4572 end_ch = '}' * 0x100 + ':';
4574 if (BASH_PATTERN_SUBST
4577 /* It's ${var/[/]pattern[/repl]} thing */
4578 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4580 nommu_addchr(as_string, '/');
4583 end_ch = '}' * 0x100 + '/';
4589 #if ENABLE_HUSH_DOLLAR_OPS
4590 last_ch = add_till_closing_bracket(dest, input, end_ch);
4591 if (last_ch == 0) /* error? */
4594 #error Simple code to only allow ${var} is not implemented
4597 o_addstr(as_string, dest->data + pos);
4598 o_addchr(as_string, last_ch);
4601 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4602 && (end_ch & 0xff00)
4604 /* close the first block: */
4605 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4606 /* while parsing N from ${var:N[:M]}
4607 * or pattern from ${var/[/]pattern[/repl]} */
4608 if ((end_ch & 0xff) == last_ch) {
4609 /* got ':' or '/'- parse the rest */
4614 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4615 /* it's ${var:N} - emulate :999999999 */
4616 o_addstr(dest, "999999999");
4617 } /* else: it's ${var/[/]pattern} */
4621 len_single_ch = 0; /* it can't be ${#C} op */
4623 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4626 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4630 ch = i_getch(input);
4631 nommu_addchr(as_string, ch);
4632 # if ENABLE_FEATURE_SH_MATH
4633 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4634 ch = i_getch(input);
4635 nommu_addchr(as_string, ch);
4636 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4637 o_addchr(dest, /*quote_mask |*/ '+');
4640 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4641 return 0; /* error */
4643 o_addstr(as_string, dest->data + pos);
4644 o_addchr(as_string, ')');
4645 o_addchr(as_string, ')');
4647 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4651 # if ENABLE_HUSH_TICK
4652 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4653 o_addchr(dest, quote_mask | '`');
4656 if (!add_till_closing_bracket(dest, input, ')'))
4657 return 0; /* error */
4659 o_addstr(as_string, dest->data + pos);
4660 o_addchr(as_string, ')');
4662 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4668 ch = i_getch(input);
4669 nommu_addchr(as_string, ch);
4670 ch = i_peek_and_eat_bkslash_nl(input);
4671 if (isalnum(ch)) { /* it's $_name or $_123 */
4676 /* TODO: $_ and $-: */
4677 /* $_ Shell or shell script name; or last argument of last command
4678 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4679 * but in command's env, set to full pathname used to invoke it */
4680 /* $- Option flags set by set builtin or shell options (-i etc) */
4682 o_addQchr(dest, '$');
4684 debug_printf_parse("parse_dollar return 1 (ok)\n");
4690 # if BASH_PATTERN_SUBST
4691 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4692 encode_string(dest, input, dquote_end, process_bkslash)
4694 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4695 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4696 encode_string(dest, input, dquote_end)
4698 #define as_string NULL
4702 # if BASH_PATTERN_SUBST
4703 /* all parameters are needed, no macro tricks */
4705 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4706 encode_string(as_string, dest, input, dquote_end)
4709 static int encode_string(o_string *as_string,
4711 struct in_str *input,
4713 int process_bkslash)
4715 #if !BASH_PATTERN_SUBST
4716 const int process_bkslash = 1;
4722 ch = i_getch(input);
4724 nommu_addchr(as_string, ch);
4725 if (ch == dquote_end) { /* may be only '"' or EOF */
4726 debug_printf_parse("encode_string return 1 (ok)\n");
4729 /* note: can't move it above ch == dquote_end check! */
4731 syntax_error_unterm_ch('"');
4732 return 0; /* error */
4736 next = i_peek(input);
4738 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4739 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4740 if (process_bkslash && ch == '\\') {
4742 syntax_error("\\<eof>");
4746 * "The backslash retains its special meaning [in "..."]
4747 * only when followed by one of the following characters:
4748 * $, `, ", \, or <newline>. A double quote may be quoted
4749 * within double quotes by preceding it with a backslash."
4750 * NB: in (unquoted) heredoc, above does not apply to ",
4751 * therefore we check for it by "next == dquote_end" cond.
4753 if (next == dquote_end || strchr("$`\\\n", next)) {
4754 ch = i_getch(input); /* eat next */
4756 goto again; /* skip \<newline> */
4757 } /* else: ch remains == '\\', and we double it below: */
4758 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4759 nommu_addchr(as_string, ch);
4763 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4764 debug_printf_parse("encode_string return 0: "
4765 "parse_dollar returned 0 (error)\n");
4770 #if ENABLE_HUSH_TICK
4772 //unsigned pos = dest->length;
4773 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4774 o_addchr(dest, 0x80 | '`');
4775 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4776 return 0; /* error */
4777 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4778 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4782 o_addQchr(dest, ch);
4788 * Scan input until EOF or end_trigger char.
4789 * Return a list of pipes to execute, or NULL on EOF
4790 * or if end_trigger character is met.
4791 * On syntax error, exit if shell is not interactive,
4792 * reset parsing machinery and start parsing anew,
4793 * or return ERR_PTR.
4795 static struct pipe *parse_stream(char **pstring,
4796 struct in_str *input,
4799 struct parse_context ctx;
4800 o_string dest = NULL_O_STRING;
4803 /* Single-quote triggers a bypass of the main loop until its mate is
4804 * found. When recursing, quote state is passed in via dest->o_expflags.
4806 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4807 end_trigger ? end_trigger : 'X');
4810 /* If very first arg is "" or '', dest.data may end up NULL.
4811 * Preventing this: */
4812 o_addchr(&dest, '\0');
4815 /* We used to separate words on $IFS here. This was wrong.
4816 * $IFS is used only for word splitting when $var is expanded,
4817 * here we should use blank chars as separators, not $IFS
4820 if (MAYBE_ASSIGNMENT != 0)
4821 dest.o_assignment = MAYBE_ASSIGNMENT;
4822 initialize_context(&ctx);
4825 const char *is_blank;
4826 const char *is_special;
4830 redir_type redir_style;
4832 ch = i_getch(input);
4833 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4834 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4839 syntax_error_unterm_str("here document");
4842 if (end_trigger == ')') {
4843 syntax_error_unterm_ch('(');
4846 if (end_trigger == '}') {
4847 syntax_error_unterm_ch('{');
4851 if (done_word(&dest, &ctx)) {
4855 done_pipe(&ctx, PIPE_SEQ);
4857 /* If we got nothing... */
4858 /* (this makes bare "&" cmd a no-op.
4859 * bash says: "syntax error near unexpected token '&'") */
4860 if (pi->num_cmds == 0
4861 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4867 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4869 *pstring = ctx.as_string.data;
4871 o_free_unsafe(&ctx.as_string);
4874 debug_printf_parse("parse_stream return %p\n", pi);
4877 nommu_addchr(&ctx.as_string, ch);
4881 next = i_peek(input);
4883 is_special = "{}<>;&|()#'" /* special outside of "str" */
4884 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4885 /* Are { and } special here? */
4886 if (ctx.command->argv /* word [word]{... - non-special */
4887 || dest.length /* word{... - non-special */
4888 || dest.has_quoted_part /* ""{... - non-special */
4889 || (next != ';' /* }; - special */
4890 && next != ')' /* }) - special */
4891 && next != '(' /* {( - special */
4892 && next != '&' /* }& and }&& ... - special */
4893 && next != '|' /* }|| ... - special */
4894 && !strchr(defifs, next) /* {word - non-special */
4897 /* They are not special, skip "{}" */
4900 is_special = strchr(is_special, ch);
4901 is_blank = strchr(defifs, ch);
4903 if (!is_special && !is_blank) { /* ordinary char */
4905 o_addQchr(&dest, ch);
4906 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4907 || dest.o_assignment == WORD_IS_KEYWORD)
4909 && is_well_formed_var_name(dest.data, '=')
4911 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4912 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4918 if (done_word(&dest, &ctx)) {
4922 /* Is this a case when newline is simply ignored?
4924 * "cmd | <newline> cmd ..."
4925 * "case ... in <newline> word) ..."
4927 if (IS_NULL_CMD(ctx.command)
4928 && dest.length == 0 && !dest.has_quoted_part
4930 /* This newline can be ignored. But...
4931 * Without check #1, interactive shell
4932 * ignores even bare <newline>,
4933 * and shows the continuation prompt:
4934 * ps1_prompt$ <enter>
4935 * ps2> _ <=== wrong, should be ps1
4936 * Without check #2, "cmd & <newline>"
4937 * is similarly mistreated.
4938 * (BTW, this makes "cmd & cmd"
4939 * and "cmd && cmd" non-orthogonal.
4940 * Really, ask yourself, why
4941 * "cmd && <newline>" doesn't start
4942 * cmd but waits for more input?
4943 * The only reason is that it might be
4944 * a "cmd1 && <nl> cmd2 &" construct,
4945 * cmd1 may need to run in BG).
4947 struct pipe *pi = ctx.list_head;
4948 if (pi->num_cmds != 0 /* check #1 */
4949 && pi->followup != PIPE_BG /* check #2 */
4954 /* Treat newline as a command separator. */
4955 done_pipe(&ctx, PIPE_SEQ);
4956 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4958 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4963 dest.o_assignment = MAYBE_ASSIGNMENT;
4964 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4966 /* note: if (is_blank) continue;
4967 * will still trigger for us */
4971 /* "cmd}" or "cmd }..." without semicolon or &:
4972 * } is an ordinary char in this case, even inside { cmd; }
4973 * Pathological example: { ""}; } should exec "}" cmd
4976 if (dest.length != 0 /* word} */
4977 || dest.has_quoted_part /* ""} */
4981 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4982 /* Generally, there should be semicolon: "cmd; }"
4983 * However, bash allows to omit it if "cmd" is
4984 * a group. Examples:
4987 * { echo 0 >&2 | { echo 1; } }
4988 * { while false; do :; done }
4989 * { case a in b) ;; esac }
4991 if (ctx.command->group)
4995 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4996 /* Can't be an end of {cmd}, skip the check */
4997 goto skip_end_trigger;
4998 /* else: } does terminate a group */
5001 if (end_trigger && end_trigger == ch
5002 && (ch != ';' || heredoc_cnt == 0)
5003 #if ENABLE_HUSH_CASE
5005 || ctx.ctx_res_w != RES_MATCH
5006 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5011 /* This is technically valid:
5012 * { cat <<HERE; }; echo Ok
5016 * but we don't support this.
5017 * We require heredoc to be in enclosing {}/(),
5020 syntax_error_unterm_str("here document");
5023 if (done_word(&dest, &ctx)) {
5026 done_pipe(&ctx, PIPE_SEQ);
5027 dest.o_assignment = MAYBE_ASSIGNMENT;
5028 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5029 /* Do we sit outside of any if's, loops or case's? */
5031 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5035 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5037 *pstring = ctx.as_string.data;
5039 o_free_unsafe(&ctx.as_string);
5041 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5042 /* Example: bare "{ }", "()" */
5043 G.last_exitcode = 2; /* bash compat */
5044 syntax_error_unexpected_ch(ch);
5047 debug_printf_parse("parse_stream return %p: "
5048 "end_trigger char found\n",
5051 return ctx.list_head;
5058 /* Catch <, > before deciding whether this word is
5059 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5062 redir_fd = redirect_opt_num(&dest);
5063 if (done_word(&dest, &ctx)) {
5066 redir_style = REDIRECT_OVERWRITE;
5068 redir_style = REDIRECT_APPEND;
5069 ch = i_getch(input);
5070 nommu_addchr(&ctx.as_string, ch);
5073 else if (next == '(') {
5074 syntax_error(">(process) not supported");
5078 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5080 continue; /* back to top of while (1) */
5082 redir_fd = redirect_opt_num(&dest);
5083 if (done_word(&dest, &ctx)) {
5086 redir_style = REDIRECT_INPUT;
5088 redir_style = REDIRECT_HEREDOC;
5090 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5091 ch = i_getch(input);
5092 nommu_addchr(&ctx.as_string, ch);
5093 } else if (next == '>') {
5094 redir_style = REDIRECT_IO;
5095 ch = i_getch(input);
5096 nommu_addchr(&ctx.as_string, ch);
5099 else if (next == '(') {
5100 syntax_error("<(process) not supported");
5104 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5106 continue; /* back to top of while (1) */
5108 if (dest.length == 0 && !dest.has_quoted_part) {
5109 /* skip "#comment" */
5112 if (ch == EOF || ch == '\n')
5115 /* note: we do not add it to &ctx.as_string */
5117 nommu_addchr(&ctx.as_string, '\n');
5118 continue; /* back to top of while (1) */
5123 /* It's "\<newline>" */
5125 /* Remove trailing '\' from ctx.as_string */
5126 ctx.as_string.data[--ctx.as_string.length] = '\0';
5128 ch = i_getch(input); /* eat it */
5129 continue; /* back to top of while (1) */
5134 if (dest.o_assignment == MAYBE_ASSIGNMENT
5135 /* check that we are not in word in "a=1 2>word b=1": */
5136 && !ctx.pending_redirect
5138 /* ch is a special char and thus this word
5139 * cannot be an assignment */
5140 dest.o_assignment = NOT_ASSIGNMENT;
5141 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5144 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5147 case '#': /* non-comment #: "echo a#b" etc */
5148 o_addQchr(&dest, ch);
5152 syntax_error("\\<eof>");
5155 ch = i_getch(input);
5156 /* note: ch != '\n' (that case does not reach this place) */
5157 o_addchr(&dest, '\\');
5158 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5159 o_addchr(&dest, ch);
5160 nommu_addchr(&ctx.as_string, ch);
5161 /* Example: echo Hello \2>file
5162 * we need to know that word 2 is quoted */
5163 dest.has_quoted_part = 1;
5166 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5167 debug_printf_parse("parse_stream parse error: "
5168 "parse_dollar returned 0 (error)\n");
5173 dest.has_quoted_part = 1;
5174 if (next == '\'' && !ctx.pending_redirect) {
5175 insert_empty_quoted_str_marker:
5176 nommu_addchr(&ctx.as_string, next);
5177 i_getch(input); /* eat second ' */
5178 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5179 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5182 ch = i_getch(input);
5184 syntax_error_unterm_ch('\'');
5187 nommu_addchr(&ctx.as_string, ch);
5190 o_addqchr(&dest, ch);
5195 dest.has_quoted_part = 1;
5196 if (next == '"' && !ctx.pending_redirect)
5197 goto insert_empty_quoted_str_marker;
5198 if (dest.o_assignment == NOT_ASSIGNMENT)
5199 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5200 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5202 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5204 #if ENABLE_HUSH_TICK
5206 USE_FOR_NOMMU(unsigned pos;)
5208 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5209 o_addchr(&dest, '`');
5210 USE_FOR_NOMMU(pos = dest.length;)
5211 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5214 o_addstr(&ctx.as_string, dest.data + pos);
5215 o_addchr(&ctx.as_string, '`');
5217 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5218 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5223 #if ENABLE_HUSH_CASE
5226 if (done_word(&dest, &ctx)) {
5229 done_pipe(&ctx, PIPE_SEQ);
5230 #if ENABLE_HUSH_CASE
5231 /* Eat multiple semicolons, detect
5232 * whether it means something special */
5237 ch = i_getch(input);
5238 nommu_addchr(&ctx.as_string, ch);
5239 if (ctx.ctx_res_w == RES_CASE_BODY) {
5240 ctx.ctx_dsemicolon = 1;
5241 ctx.ctx_res_w = RES_MATCH;
5247 /* We just finished a cmd. New one may start
5248 * with an assignment */
5249 dest.o_assignment = MAYBE_ASSIGNMENT;
5250 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5253 if (done_word(&dest, &ctx)) {
5257 ch = i_getch(input);
5258 nommu_addchr(&ctx.as_string, ch);
5259 done_pipe(&ctx, PIPE_AND);
5261 done_pipe(&ctx, PIPE_BG);
5265 if (done_word(&dest, &ctx)) {
5268 #if ENABLE_HUSH_CASE
5269 if (ctx.ctx_res_w == RES_MATCH)
5270 break; /* we are in case's "word | word)" */
5272 if (next == '|') { /* || */
5273 ch = i_getch(input);
5274 nommu_addchr(&ctx.as_string, ch);
5275 done_pipe(&ctx, PIPE_OR);
5277 /* we could pick up a file descriptor choice here
5278 * with redirect_opt_num(), but bash doesn't do it.
5279 * "echo foo 2| cat" yields "foo 2". */
5284 #if ENABLE_HUSH_CASE
5285 /* "case... in [(]word)..." - skip '(' */
5286 if (ctx.ctx_res_w == RES_MATCH
5287 && ctx.command->argv == NULL /* not (word|(... */
5288 && dest.length == 0 /* not word(... */
5289 && dest.has_quoted_part == 0 /* not ""(... */
5295 if (parse_group(&dest, &ctx, input, ch) != 0) {
5300 #if ENABLE_HUSH_CASE
5301 if (ctx.ctx_res_w == RES_MATCH)
5305 /* proper use of this character is caught by end_trigger:
5306 * if we see {, we call parse_group(..., end_trigger='}')
5307 * and it will match } earlier (not here). */
5308 G.last_exitcode = 2;
5309 syntax_error_unexpected_ch(ch);
5313 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5318 G.last_exitcode = 1;
5321 struct parse_context *pctx;
5322 IF_HAS_KEYWORDS(struct parse_context *p2;)
5324 /* Clean up allocated tree.
5325 * Sample for finding leaks on syntax error recovery path.
5326 * Run it from interactive shell, watch pmap `pidof hush`.
5327 * while if false; then false; fi; do break; fi
5328 * Samples to catch leaks at execution:
5329 * while if (true | { true;}); then echo ok; fi; do break; done
5330 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5334 /* Update pipe/command counts,
5335 * otherwise freeing may miss some */
5336 done_pipe(pctx, PIPE_SEQ);
5337 debug_printf_clean("freeing list %p from ctx %p\n",
5338 pctx->list_head, pctx);
5339 debug_print_tree(pctx->list_head, 0);
5340 free_pipe_list(pctx->list_head);
5341 debug_printf_clean("freed list %p\n", pctx->list_head);
5343 o_free_unsafe(&pctx->as_string);
5345 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5349 IF_HAS_KEYWORDS(pctx = p2;)
5350 } while (HAS_KEYWORDS && pctx);
5363 /*** Execution routines ***/
5365 /* Expansion can recurse, need forward decls: */
5366 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5367 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5368 #define expand_string_to_string(str, do_unbackslash) \
5369 expand_string_to_string(str)
5371 static char *expand_string_to_string(const char *str, int do_unbackslash);
5372 #if ENABLE_HUSH_TICK
5373 static int process_command_subs(o_string *dest, const char *s);
5376 /* expand_strvec_to_strvec() takes a list of strings, expands
5377 * all variable references within and returns a pointer to
5378 * a list of expanded strings, possibly with larger number
5379 * of strings. (Think VAR="a b"; echo $VAR).
5380 * This new list is allocated as a single malloc block.
5381 * NULL-terminated list of char* pointers is at the beginning of it,
5382 * followed by strings themselves.
5383 * Caller can deallocate entire list by single free(list). */
5385 /* A horde of its helpers come first: */
5387 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5389 while (--len >= 0) {
5392 #if ENABLE_HUSH_BRACE_EXPANSION
5393 if (c == '{' || c == '}') {
5394 /* { -> \{, } -> \} */
5396 /* And now we want to add { or } and continue:
5399 * luckily, just falling through achieves this.
5405 /* \z -> \\\z; \<eol> -> \\<eol> */
5410 o_addchr(o, *str++);
5416 /* Store given string, finalizing the word and starting new one whenever
5417 * we encounter IFS char(s). This is used for expanding variable values.
5418 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5419 * Return in *ended_with_ifs:
5420 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5422 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5424 int last_is_ifs = 0;
5429 if (!*str) /* EOL - do not finalize word */
5431 word_len = strcspn(str, G.ifs);
5433 /* We have WORD_LEN leading non-IFS chars */
5434 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5435 o_addblock(output, str, word_len);
5437 /* Protect backslashes against globbing up :)
5438 * Example: "v='\*'; echo b$v" prints "b\*"
5439 * (and does not try to glob on "*")
5441 o_addblock_duplicate_backslash(output, str, word_len);
5442 /*/ Why can't we do it easier? */
5443 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5444 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5448 if (!*str) /* EOL - do not finalize word */
5452 /* We know str here points to at least one IFS char */
5454 str += strspn(str, G.ifs); /* skip IFS chars */
5455 if (!*str) /* EOL - do not finalize word */
5458 /* Start new word... but not always! */
5459 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5460 if (output->has_quoted_part
5461 /* Case "v=' a'; echo $v":
5462 * here nothing precedes the space in $v expansion,
5463 * therefore we should not finish the word
5464 * (IOW: if there *is* word to finalize, only then do it):
5466 || (n > 0 && output->data[output->length - 1])
5468 o_addchr(output, '\0');
5469 debug_print_list("expand_on_ifs", output, n);
5470 n = o_save_ptr(output, n);
5475 *ended_with_ifs = last_is_ifs;
5476 debug_print_list("expand_on_ifs[1]", output, n);
5480 /* Helper to expand $((...)) and heredoc body. These act as if
5481 * they are in double quotes, with the exception that they are not :).
5482 * Just the rules are similar: "expand only $var and `cmd`"
5484 * Returns malloced string.
5485 * As an optimization, we return NULL if expansion is not needed.
5487 #if !BASH_PATTERN_SUBST
5488 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5489 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5490 encode_then_expand_string(str)
5492 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5494 #if !BASH_PATTERN_SUBST
5495 const int do_unbackslash = 1;
5498 struct in_str input;
5499 o_string dest = NULL_O_STRING;
5501 if (!strchr(str, '$')
5502 && !strchr(str, '\\')
5503 #if ENABLE_HUSH_TICK
5504 && !strchr(str, '`')
5510 /* We need to expand. Example:
5511 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5513 setup_string_in_str(&input, str);
5514 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5515 //TODO: error check (encode_string returns 0 on error)?
5516 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5517 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5518 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5519 o_free_unsafe(&dest);
5523 #if ENABLE_FEATURE_SH_MATH
5524 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5526 arith_state_t math_state;
5530 math_state.lookupvar = get_local_var_value;
5531 math_state.setvar = set_local_var_from_halves;
5532 //math_state.endofname = endofname;
5533 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5534 res = arith(&math_state, exp_str ? exp_str : arg);
5537 *errmsg_p = math_state.errmsg;
5538 if (math_state.errmsg)
5539 msg_and_die_if_script(math_state.errmsg);
5544 #if BASH_PATTERN_SUBST
5545 /* ${var/[/]pattern[/repl]} helpers */
5546 static char *strstr_pattern(char *val, const char *pattern, int *size)
5549 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5550 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5557 /* Optimization: if "*pat" did not match the start of "string",
5558 * we know that "tring", "ring" etc will not match too:
5560 if (pattern[0] == '*')
5565 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5567 char *result = NULL;
5568 unsigned res_len = 0;
5569 unsigned repl_len = strlen(repl);
5573 char *s = strstr_pattern(val, pattern, &size);
5577 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5578 strcpy(mempcpy(result + res_len, val, s - val), repl);
5579 res_len += (s - val) + repl_len;
5580 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5586 if (*val && result) {
5587 result = xrealloc(result, res_len + strlen(val) + 1);
5588 strcpy(result + res_len, val);
5589 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5591 debug_printf_varexp("result:'%s'\n", result);
5594 #endif /* BASH_PATTERN_SUBST */
5597 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5599 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5601 const char *val = NULL;
5602 char *to_be_freed = NULL;
5607 char exp_save = exp_save; /* for compiler */
5608 char *exp_saveptr; /* points to expansion operator */
5609 char *exp_word = exp_word; /* for compiler */
5612 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5614 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5616 first_char = arg[0] = arg0 & 0x7f;
5619 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5620 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5621 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5622 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5624 /* It must be length operator: ${#var} */
5628 /* Maybe handle parameter expansion */
5629 if (exp_saveptr /* if 2nd char is one of expansion operators */
5630 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5632 /* ${?:0}, ${#[:]%0} etc */
5633 exp_saveptr = var + 1;
5635 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5636 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5638 exp_op = exp_save = *exp_saveptr;
5640 exp_word = exp_saveptr + 1;
5641 if (exp_op == ':') {
5642 exp_op = *exp_word++;
5643 //TODO: try ${var:} and ${var:bogus} in non-bash config
5645 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5647 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5652 *exp_saveptr = '\0';
5653 } /* else: it's not an expansion op, but bare ${var} */
5656 /* Look up the variable in question */
5657 if (isdigit(var[0])) {
5658 /* parse_dollar should have vetted var for us */
5659 int n = xatoi_positive(var);
5660 if (n < G.global_argc)
5661 val = G.global_argv[n];
5662 /* else val remains NULL: $N with too big N */
5666 val = utoa(G.root_pid);
5668 case '!': /* bg pid */
5669 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5671 case '?': /* exitcode */
5672 val = utoa(G.last_exitcode);
5674 case '#': /* argc */
5675 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5678 val = get_local_var_value(var);
5682 /* Handle any expansions */
5683 if (exp_op == 'L') {
5684 reinit_unicode_for_hush();
5685 debug_printf_expand("expand: length(%s)=", val);
5686 val = utoa(val ? unicode_strlen(val) : 0);
5687 debug_printf_expand("%s\n", val);
5688 } else if (exp_op) {
5689 if (exp_op == '%' || exp_op == '#') {
5690 /* Standard-mandated substring removal ops:
5691 * ${parameter%word} - remove smallest suffix pattern
5692 * ${parameter%%word} - remove largest suffix pattern
5693 * ${parameter#word} - remove smallest prefix pattern
5694 * ${parameter##word} - remove largest prefix pattern
5696 * Word is expanded to produce a glob pattern.
5697 * Then var's value is matched to it and matching part removed.
5699 if (val && val[0]) {
5703 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5704 if (exp_op == *exp_word) /* ## or %% */
5706 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5708 exp_word = exp_exp_word;
5709 /* HACK ALERT. We depend here on the fact that
5710 * G.global_argv and results of utoa and get_local_var_value
5711 * are actually in writable memory:
5712 * scan_and_match momentarily stores NULs there. */
5714 loc = scan_and_match(t, exp_word, scan_flags);
5715 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5716 // exp_op, t, exp_word, loc);
5718 if (loc) { /* match was found */
5719 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5720 val = loc; /* take right part */
5722 val = to_be_freed = xstrndup(val, loc - val); /* left */
5726 #if BASH_PATTERN_SUBST
5727 else if (exp_op == '/' || exp_op == '\\') {
5728 /* It's ${var/[/]pattern[/repl]} thing.
5729 * Note that in encoded form it has TWO parts:
5730 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5731 * and if // is used, it is encoded as \:
5732 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5734 /* Empty variable always gives nothing: */
5735 // "v=''; echo ${v/*/w}" prints "", not "w"
5736 if (val && val[0]) {
5737 /* pattern uses non-standard expansion.
5738 * repl should be unbackslashed and globbed
5739 * by the usual expansion rules:
5741 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5742 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5743 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5744 * v='a bz'; echo ${v/a*z/\z} prints "z"
5745 * (note that a*z _pattern_ is never globbed!)
5747 char *pattern, *repl, *t;
5748 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5750 pattern = xstrdup(exp_word);
5751 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5752 *p++ = SPECIAL_VAR_SYMBOL;
5754 p = strchr(p, SPECIAL_VAR_SYMBOL);
5756 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5757 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5758 /* HACK ALERT. We depend here on the fact that
5759 * G.global_argv and results of utoa and get_local_var_value
5760 * are actually in writable memory:
5761 * replace_pattern momentarily stores NULs there. */
5763 to_be_freed = replace_pattern(t,
5765 (repl ? repl : exp_word),
5767 if (to_be_freed) /* at least one replace happened */
5773 #endif /* BASH_PATTERN_SUBST */
5774 else if (exp_op == ':') {
5775 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5776 /* It's ${var:N[:M]} bashism.
5777 * Note that in encoded form it has TWO parts:
5778 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5783 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5786 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5787 *p++ = SPECIAL_VAR_SYMBOL;
5789 p = strchr(p, SPECIAL_VAR_SYMBOL);
5791 len = expand_and_evaluate_arith(exp_word, &errmsg);
5794 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5796 /* negative beg counts from the end */
5797 beg = (arith_t)strlen(val) + beg;
5798 if (beg < 0) /* ${v: -999999} is "" */
5801 debug_printf_varexp("from val:'%s'\n", val);
5803 /* in bash, len=-n means strlen()-n */
5804 len = (arith_t)strlen(val) - beg + len;
5805 if (len < 0) /* bash compat */
5806 msg_and_die_if_script("%s: substring expression < 0", var);
5808 if (len <= 0 || !val || beg >= strlen(val)) {
5812 /* Paranoia. What if user entered 9999999999999
5813 * which fits in arith_t but not int? */
5816 val = to_be_freed = xstrndup(val + beg, len);
5818 debug_printf_varexp("val:'%s'\n", val);
5819 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5820 msg_and_die_if_script("malformed ${%s:...}", var);
5823 } else { /* one of "-=+?" */
5824 /* Standard-mandated substitution ops:
5825 * ${var?word} - indicate error if unset
5826 * If var is unset, word (or a message indicating it is unset
5827 * if word is null) is written to standard error
5828 * and the shell exits with a non-zero exit status.
5829 * Otherwise, the value of var is substituted.
5830 * ${var-word} - use default value
5831 * If var is unset, word is substituted.
5832 * ${var=word} - assign and use default value
5833 * If var is unset, word is assigned to var.
5834 * In all cases, final value of var is substituted.
5835 * ${var+word} - use alternative value
5836 * If var is unset, null is substituted.
5837 * Otherwise, word is substituted.
5839 * Word is subjected to tilde expansion, parameter expansion,
5840 * command substitution, and arithmetic expansion.
5841 * If word is not needed, it is not expanded.
5843 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5844 * but also treat null var as if it is unset.
5846 int use_word = (!val || ((exp_save == ':') && !val[0]));
5848 use_word = !use_word;
5849 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5850 (exp_save == ':') ? "true" : "false", use_word);
5852 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5854 exp_word = to_be_freed;
5855 if (exp_op == '?') {
5856 /* mimic bash message */
5857 msg_and_die_if_script("%s: %s",
5861 : "parameter null or not set"
5862 /* ash has more specific messages, a-la: */
5863 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
5865 //TODO: how interactive bash aborts expansion mid-command?
5870 if (exp_op == '=') {
5871 /* ${var=[word]} or ${var:=[word]} */
5872 if (isdigit(var[0]) || var[0] == '#') {
5873 /* mimic bash message */
5874 msg_and_die_if_script("$%s: cannot assign in this way", var);
5877 char *new_var = xasprintf("%s=%s", var, val);
5878 set_local_var(new_var, /*flag:*/ 0);
5882 } /* one of "-=+?" */
5884 *exp_saveptr = exp_save;
5890 *to_be_freed_pp = to_be_freed;
5894 /* Expand all variable references in given string, adding words to list[]
5895 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5896 * to be filled). This routine is extremely tricky: has to deal with
5897 * variables/parameters with whitespace, $* and $@, and constructs like
5898 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5899 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5901 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5902 * expansion of right-hand side of assignment == 1-element expand.
5904 char cant_be_null = 0; /* only bit 0x80 matters */
5905 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5908 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5909 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5910 debug_print_list("expand_vars_to_list", output, n);
5911 n = o_save_ptr(output, n);
5912 debug_print_list("expand_vars_to_list[0]", output, n);
5914 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5916 char *to_be_freed = NULL;
5917 const char *val = NULL;
5918 #if ENABLE_HUSH_TICK
5919 o_string subst_result = NULL_O_STRING;
5921 #if ENABLE_FEATURE_SH_MATH
5922 char arith_buf[sizeof(arith_t)*3 + 2];
5926 o_addchr(output, '\0');
5927 n = o_save_ptr(output, n);
5931 o_addblock(output, arg, p - arg);
5932 debug_print_list("expand_vars_to_list[1]", output, n);
5934 p = strchr(p, SPECIAL_VAR_SYMBOL);
5936 /* Fetch special var name (if it is indeed one of them)
5937 * and quote bit, force the bit on if singleword expansion -
5938 * important for not getting v=$@ expand to many words. */
5939 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5941 /* Is this variable quoted and thus expansion can't be null?
5942 * "$@" is special. Even if quoted, it can still
5943 * expand to nothing (not even an empty string),
5944 * thus it is excluded. */
5945 if ((first_ch & 0x7f) != '@')
5946 cant_be_null |= first_ch;
5948 switch (first_ch & 0x7f) {
5949 /* Highest bit in first_ch indicates that var is double-quoted */
5953 if (!G.global_argv[1])
5956 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5957 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5958 while (G.global_argv[i]) {
5959 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5960 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5961 if (G.global_argv[i++][0] && G.global_argv[i]) {
5962 /* this argv[] is not empty and not last:
5963 * put terminating NUL, start new word */
5964 o_addchr(output, '\0');
5965 debug_print_list("expand_vars_to_list[2]", output, n);
5966 n = o_save_ptr(output, n);
5967 debug_print_list("expand_vars_to_list[3]", output, n);
5971 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5972 * and in this case should treat it like '$*' - see 'else...' below */
5973 if (first_ch == ('@'|0x80) /* quoted $@ */
5974 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5977 o_addQstr(output, G.global_argv[i]);
5978 if (++i >= G.global_argc)
5980 o_addchr(output, '\0');
5981 debug_print_list("expand_vars_to_list[4]", output, n);
5982 n = o_save_ptr(output, n);
5984 } else { /* quoted $* (or v="$@" case): add as one word */
5986 o_addQstr(output, G.global_argv[i]);
5987 if (!G.global_argv[++i])
5990 o_addchr(output, G.ifs[0]);
5992 output->has_quoted_part = 1;
5996 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5997 /* "Empty variable", used to make "" etc to not disappear */
5998 output->has_quoted_part = 1;
6000 cant_be_null = 0x80;
6002 #if ENABLE_HUSH_TICK
6003 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6004 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6006 /* Can't just stuff it into output o_string,
6007 * expanded result may need to be globbed
6009 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6010 G.last_exitcode = process_command_subs(&subst_result, arg);
6011 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6012 val = subst_result.data;
6015 #if ENABLE_FEATURE_SH_MATH
6016 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6019 arg++; /* skip '+' */
6020 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6021 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6022 res = expand_and_evaluate_arith(arg, NULL);
6023 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6024 sprintf(arith_buf, ARITH_FMT, res);
6030 val = expand_one_var(&to_be_freed, arg, &p);
6031 IF_HUSH_TICK(store_val:)
6032 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6033 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6034 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6035 if (val && val[0]) {
6036 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6039 } else { /* quoted $VAR, val will be appended below */
6040 output->has_quoted_part = 1;
6041 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6042 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6045 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6047 if (val && val[0]) {
6048 o_addQstr(output, val);
6052 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6053 * Do the check to avoid writing to a const string. */
6054 if (*p != SPECIAL_VAR_SYMBOL)
6055 *p = SPECIAL_VAR_SYMBOL;
6057 #if ENABLE_HUSH_TICK
6058 o_free(&subst_result);
6061 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6065 o_addchr(output, '\0');
6066 n = o_save_ptr(output, n);
6068 debug_print_list("expand_vars_to_list[a]", output, n);
6069 /* this part is literal, and it was already pre-quoted
6070 * if needed (much earlier), do not use o_addQstr here! */
6071 o_addstr_with_NUL(output, arg);
6072 debug_print_list("expand_vars_to_list[b]", output, n);
6073 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6074 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6077 /* allow to reuse list[n] later without re-growth */
6078 output->has_empty_slot = 1;
6080 o_addchr(output, '\0');
6086 static char **expand_variables(char **argv, unsigned expflags)
6090 o_string output = NULL_O_STRING;
6092 output.o_expflags = expflags;
6096 n = expand_vars_to_list(&output, n, *argv);
6099 debug_print_list("expand_variables", &output, n);
6101 /* output.data (malloced in one block) gets returned in "list" */
6102 list = o_finalize_list(&output, n);
6103 debug_print_strings("expand_variables[1]", list);
6107 static char **expand_strvec_to_strvec(char **argv)
6109 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6113 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6115 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6119 /* Used for expansion of right hand of assignments,
6120 * $((...)), heredocs, variable espansion parts.
6122 * NB: should NOT do globbing!
6123 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6125 static char *expand_string_to_string(const char *str, int do_unbackslash)
6127 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6128 const int do_unbackslash = 1;
6130 char *argv[2], **list;
6132 debug_printf_expand("string_to_string<='%s'\n", str);
6133 /* This is generally an optimization, but it also
6134 * handles "", which otherwise trips over !list[0] check below.
6135 * (is this ever happens that we actually get str="" here?)
6137 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6138 //TODO: Can use on strings with \ too, just unbackslash() them?
6139 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6140 return xstrdup(str);
6143 argv[0] = (char*)str;
6145 list = expand_variables(argv, do_unbackslash
6146 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6147 : EXP_FLAG_SINGLEWORD
6150 if (!list[0] || list[1])
6151 bb_error_msg_and_die("BUG in varexp2");
6152 /* actually, just move string 2*sizeof(char*) bytes back */
6153 overlapping_strcpy((char*)list, list[0]);
6155 unbackslash((char*)list);
6156 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6160 /* Used for "eval" builtin and case string */
6161 static char* expand_strvec_to_string(char **argv)
6165 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6166 /* Convert all NULs to spaces */
6171 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6172 bb_error_msg_and_die("BUG in varexp3");
6173 /* bash uses ' ' regardless of $IFS contents */
6178 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6179 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6183 static char **expand_assignments(char **argv, int count)
6188 G.expanded_assignments = p = NULL;
6189 /* Expand assignments into one string each */
6190 for (i = 0; i < count; i++) {
6191 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6193 G.expanded_assignments = NULL;
6198 static void switch_off_special_sigs(unsigned mask)
6201 while ((mask >>= 1) != 0) {
6205 #if ENABLE_HUSH_TRAP
6207 if (G_traps[sig] && !G_traps[sig][0])
6208 /* trap is '', has to remain SIG_IGN */
6211 G_traps[sig] = NULL;
6214 /* We are here only if no trap or trap was not '' */
6215 install_sighandler(sig, SIG_DFL);
6221 void re_execute_shell(char ***to_free, const char *s,
6222 char *g_argv0, char **g_argv,
6223 char **builtin_argv) NORETURN;
6225 static void reset_traps_to_defaults(void)
6227 /* This function is always called in a child shell
6228 * after fork (not vfork, NOMMU doesn't use this function).
6230 IF_HUSH_TRAP(unsigned sig;)
6233 /* Child shells are not interactive.
6234 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6235 * Testcase: (while :; do :; done) + ^Z should background.
6236 * Same goes for SIGTERM, SIGHUP, SIGINT.
6238 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6239 if (!G_traps && !mask)
6240 return; /* already no traps and no special sigs */
6242 /* Switch off special sigs */
6243 switch_off_special_sigs(mask);
6244 # if ENABLE_HUSH_JOB
6245 G_fatal_sig_mask = 0;
6247 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6248 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6249 * remain set in G.special_sig_mask */
6251 # if ENABLE_HUSH_TRAP
6255 /* Reset all sigs to default except ones with empty traps */
6256 for (sig = 0; sig < NSIG; sig++) {
6258 continue; /* no trap: nothing to do */
6259 if (!G_traps[sig][0])
6260 continue; /* empty trap: has to remain SIG_IGN */
6261 /* sig has non-empty trap, reset it: */
6263 G_traps[sig] = NULL;
6264 /* There is no signal for trap 0 (EXIT) */
6267 install_sighandler(sig, pick_sighandler(sig));
6274 static void re_execute_shell(char ***to_free, const char *s,
6275 char *g_argv0, char **g_argv,
6276 char **builtin_argv) NORETURN;
6277 static void re_execute_shell(char ***to_free, const char *s,
6278 char *g_argv0, char **g_argv,
6279 char **builtin_argv)
6281 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6282 /* delims + 2 * (number of bytes in printed hex numbers) */
6283 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6284 char *heredoc_argv[4];
6285 struct variable *cur;
6286 # if ENABLE_HUSH_FUNCTIONS
6287 struct function *funcp;
6291 unsigned long long empty_trap_mask;
6293 if (!g_argv0) { /* heredoc */
6294 argv = heredoc_argv;
6295 argv[0] = (char *) G.argv0_for_re_execing;
6296 argv[1] = (char *) "-<";
6297 argv[2] = (char *) s;
6299 pp = &argv[3]; /* used as pointer to empty environment */
6305 if (pp) while (*pp++)
6308 empty_trap_mask = 0;
6311 for (sig = 1; sig < NSIG; sig++) {
6312 if (G_traps[sig] && !G_traps[sig][0])
6313 empty_trap_mask |= 1LL << sig;
6317 sprintf(param_buf, NOMMU_HACK_FMT
6318 , (unsigned) G.root_pid
6319 , (unsigned) G.root_ppid
6320 , (unsigned) G.last_bg_pid
6321 , (unsigned) G.last_exitcode
6324 IF_HUSH_LOOPS(, G.depth_of_loop)
6326 # undef NOMMU_HACK_FMT
6327 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6328 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6331 for (cur = G.top_var; cur; cur = cur->next) {
6332 if (!cur->flg_export || cur->flg_read_only)
6335 # if ENABLE_HUSH_FUNCTIONS
6336 for (funcp = G.top_func; funcp; funcp = funcp->next)
6342 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6343 *pp++ = (char *) G.argv0_for_re_execing;
6345 for (cur = G.top_var; cur; cur = cur->next) {
6346 if (strcmp(cur->varstr, hush_version_str) == 0)
6348 if (cur->flg_read_only) {
6349 *pp++ = (char *) "-R";
6350 *pp++ = cur->varstr;
6351 } else if (!cur->flg_export) {
6352 *pp++ = (char *) "-V";
6353 *pp++ = cur->varstr;
6356 # if ENABLE_HUSH_FUNCTIONS
6357 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6358 *pp++ = (char *) "-F";
6359 *pp++ = funcp->name;
6360 *pp++ = funcp->body_as_string;
6363 /* We can pass activated traps here. Say, -Tnn:trap_string
6365 * However, POSIX says that subshells reset signals with traps
6367 * I tested bash-3.2 and it not only does that with true subshells
6368 * of the form ( list ), but with any forked children shells.
6369 * I set trap "echo W" WINCH; and then tried:
6371 * { echo 1; sleep 20; echo 2; } &
6372 * while true; do echo 1; sleep 20; echo 2; break; done &
6373 * true | { echo 1; sleep 20; echo 2; } | cat
6375 * In all these cases sending SIGWINCH to the child shell
6376 * did not run the trap. If I add trap "echo V" WINCH;
6377 * _inside_ group (just before echo 1), it works.
6379 * I conclude it means we don't need to pass active traps here.
6381 *pp++ = (char *) "-c";
6384 while (*++builtin_argv)
6385 *pp++ = *builtin_argv;
6386 *pp++ = (char *) "";
6391 /* *pp = NULL; - is already there */
6395 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6396 /* Don't propagate SIG_IGN to the child */
6397 if (SPECIAL_JOBSTOP_SIGS != 0)
6398 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6399 execve(bb_busybox_exec_path, argv, pp);
6400 /* Fallback. Useful for init=/bin/hush usage etc */
6401 if (argv[0][0] == '/')
6402 execve(argv[0], argv, pp);
6403 xfunc_error_retval = 127;
6404 bb_error_msg_and_die("can't re-execute the shell");
6406 #endif /* !BB_MMU */
6409 static int run_and_free_list(struct pipe *pi);
6411 /* Executing from string: eval, sh -c '...'
6412 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6413 * end_trigger controls how often we stop parsing
6414 * NUL: parse all, execute, return
6415 * ';': parse till ';' or newline, execute, repeat till EOF
6417 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6419 /* Why we need empty flag?
6420 * An obscure corner case "false; ``; echo $?":
6421 * empty command in `` should still set $? to 0.
6422 * But we can't just set $? to 0 at the start,
6423 * this breaks "false; echo `echo $?`" case.
6427 struct pipe *pipe_list;
6429 #if ENABLE_HUSH_INTERACTIVE
6430 if (end_trigger == ';')
6431 inp->promptmode = 0; /* PS1 */
6433 pipe_list = parse_stream(NULL, inp, end_trigger);
6434 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6435 /* If we are in "big" script
6436 * (not in `cmd` or something similar)...
6438 if (pipe_list == ERR_PTR && end_trigger == ';') {
6439 /* Discard cached input (rest of line) */
6440 int ch = inp->last_char;
6441 while (ch != EOF && ch != '\n') {
6442 //bb_error_msg("Discarded:'%c'", ch);
6447 /* This stream isn't empty */
6451 if (!pipe_list && empty)
6452 G.last_exitcode = 0;
6455 debug_print_tree(pipe_list, 0);
6456 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6457 run_and_free_list(pipe_list);
6459 if (G_flag_return_in_progress == 1)
6464 static void parse_and_run_string(const char *s)
6466 struct in_str input;
6467 setup_string_in_str(&input, s);
6468 parse_and_run_stream(&input, '\0');
6471 static void parse_and_run_file(FILE *f)
6473 struct in_str input;
6474 setup_file_in_str(&input, f);
6475 parse_and_run_stream(&input, ';');
6478 #if ENABLE_HUSH_TICK
6479 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6484 char **to_free = NULL;
6488 pid = BB_MMU ? xfork() : xvfork();
6489 if (pid == 0) { /* child */
6490 disable_restore_tty_pgrp_on_exit();
6491 /* Process substitution is not considered to be usual
6492 * 'command execution'.
6493 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6500 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6501 close(channel[0]); /* NB: close _first_, then move fd! */
6502 xmove_fd(channel[1], 1);
6503 /* Prevent it from trying to handle ctrl-z etc */
6504 IF_HUSH_JOB(G.run_list_level = 1;)
6505 # if ENABLE_HUSH_TRAP
6506 /* Awful hack for `trap` or $(trap).
6508 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6509 * contains an example where "trap" is executed in a subshell:
6511 * save_traps=$(trap)
6513 * eval "$save_traps"
6515 * Standard does not say that "trap" in subshell shall print
6516 * parent shell's traps. It only says that its output
6517 * must have suitable form, but then, in the above example
6518 * (which is not supposed to be normative), it implies that.
6520 * bash (and probably other shell) does implement it
6521 * (traps are reset to defaults, but "trap" still shows them),
6522 * but as a result, "trap" logic is hopelessly messed up:
6525 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6526 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6527 * # true | trap <--- trap is in subshell - no output (ditto)
6528 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6529 * trap -- 'echo Ho' SIGWINCH
6530 * # echo `(trap)` <--- in subshell in subshell - output
6531 * trap -- 'echo Ho' SIGWINCH
6532 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6533 * trap -- 'echo Ho' SIGWINCH
6535 * The rules when to forget and when to not forget traps
6536 * get really complex and nonsensical.
6538 * Our solution: ONLY bare $(trap) or `trap` is special.
6540 s = skip_whitespace(s);
6541 if (is_prefixed_with(s, "trap")
6542 && skip_whitespace(s + 4)[0] == '\0'
6544 static const char *const argv[] = { NULL, NULL };
6545 builtin_trap((char**)argv);
6546 fflush_all(); /* important */
6551 reset_traps_to_defaults();
6552 parse_and_run_string(s);
6553 _exit(G.last_exitcode);
6555 /* We re-execute after vfork on NOMMU. This makes this script safe:
6556 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6557 * huge=`cat BIG` # was blocking here forever
6560 re_execute_shell(&to_free,
6570 # if ENABLE_HUSH_FAST
6572 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6573 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6574 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6576 enable_restore_tty_pgrp_on_exit();
6581 return remember_FILE(xfdopen_for_read(channel[0]));
6584 /* Return code is exit status of the process that is run. */
6585 static int process_command_subs(o_string *dest, const char *s)
6588 struct in_str pipe_str;
6590 int status, ch, eol_cnt;
6592 fp = generate_stream_from_string(s, &pid);
6594 /* Now send results of command back into original context */
6595 setup_file_in_str(&pipe_str, fp);
6597 while ((ch = i_getch(&pipe_str)) != EOF) {
6603 o_addchr(dest, '\n');
6606 o_addQchr(dest, ch);
6609 debug_printf("done reading from `cmd` pipe, closing it\n");
6610 fclose_and_forget(fp);
6611 /* We need to extract exitcode. Test case
6612 * "true; echo `sleep 1; false` $?"
6614 safe_waitpid(pid, &status, 0);
6615 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6616 return WEXITSTATUS(status);
6618 #endif /* ENABLE_HUSH_TICK */
6621 static void setup_heredoc(struct redir_struct *redir)
6623 struct fd_pair pair;
6626 /* the _body_ of heredoc (misleading field name) */
6627 const char *heredoc = redir->rd_filename;
6634 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6635 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6639 len = strlen(heredoc);
6641 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6643 xmove_fd(pair.rd, redir->rd_fd);
6645 /* Try writing without forking. Newer kernels have
6646 * dynamically growing pipes. Must use non-blocking write! */
6649 written = write(pair.wr, heredoc, len);
6660 ndelay_off(pair.wr);
6662 /* Okay, pipe buffer was not big enough */
6663 /* Note: we must not create a stray child (bastard? :)
6664 * for the unsuspecting parent process. Child creates a grandchild
6665 * and exits before parent execs the process which consumes heredoc
6666 * (that exec happens after we return from this function) */
6673 disable_restore_tty_pgrp_on_exit();
6674 pid = BB_MMU ? xfork() : xvfork();
6678 close(redir->rd_fd); /* read side of the pipe */
6680 full_write(pair.wr, heredoc, len); /* may loop or block */
6683 /* Delegate blocking writes to another process */
6684 xmove_fd(pair.wr, STDOUT_FILENO);
6685 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6689 #if ENABLE_HUSH_FAST
6691 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6693 enable_restore_tty_pgrp_on_exit();
6699 wait(NULL); /* wait till child has died */
6705 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6706 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6709 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6711 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6712 sq[i].orig_fd = orig;
6713 sq[i].moved_to = moved;
6714 sq[i+1].orig_fd = -1; /* end marker */
6718 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6723 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6724 /* If we collide with an already moved fd... */
6725 if (fd == sq[i].moved_to) {
6726 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6727 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6728 if (sq[i].moved_to < 0) /* what? */
6732 if (fd == sq[i].orig_fd) {
6733 /* Example: echo Hello >/dev/null 1>&2 */
6734 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6739 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6740 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6741 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6742 if (moved_to < 0 && errno != EBADF)
6744 return append_squirrel(sq, i, fd, moved_to);
6747 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6751 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6752 /* If we collide with an already moved fd... */
6753 if (fd == sq[i].orig_fd) {
6755 * "echo 3>FILE 3>&- 3>FILE"
6756 * "echo 3>&- 3>FILE"
6757 * No need for last redirect to insert
6758 * another "need to close 3" indicator.
6760 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6765 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6766 return append_squirrel(sq, i, fd, -1);
6769 /* fd: redirect wants this fd to be used (e.g. 3>file).
6770 * Move all conflicting internally used fds,
6771 * and remember them so that we can restore them later.
6773 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6775 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6778 #if ENABLE_HUSH_INTERACTIVE
6779 if (fd == G.interactive_fd) {
6780 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6781 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6782 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6783 return 1; /* "we closed fd" */
6786 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6787 * (1) Redirect in a forked child. No need to save FILEs' fds,
6788 * we aren't going to use them anymore, ok to trash.
6789 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6790 * but how are we doing to restore them?
6791 * "fileno(fd) = new_fd" can't be done.
6796 /* If this one of script's fds? */
6797 if (save_FILEs_on_redirect(fd, avoid_fd))
6798 return 1; /* yes. "we closed fd" */
6800 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6801 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6802 return 0; /* "we did not close fd" */
6805 static void restore_redirects(struct squirrel *sq)
6809 for (i = 0; sq[i].orig_fd >= 0; i++) {
6810 if (sq[i].moved_to >= 0) {
6811 /* We simply die on error */
6812 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6813 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6815 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6816 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6817 close(sq[i].orig_fd);
6823 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6825 restore_redirected_FILEs();
6828 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6829 static void close_saved_fds_and_FILE_fds(void)
6831 if (G_interactive_fd)
6832 close(G_interactive_fd);
6833 close_all_FILE_list();
6837 static int internally_opened_fd(int fd, struct squirrel *sq)
6841 #if ENABLE_HUSH_INTERACTIVE
6842 if (fd == G.interactive_fd)
6845 /* If this one of script's fds? */
6846 if (fd_in_FILEs(fd))
6849 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6850 if (fd == sq[i].moved_to)
6856 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6857 * and stderr if they are redirected. */
6858 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6860 struct redir_struct *redir;
6862 for (redir = prog->redirects; redir; redir = redir->next) {
6866 if (redir->rd_type == REDIRECT_HEREDOC2) {
6867 /* "rd_fd<<HERE" case */
6868 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6869 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6871 debug_printf_parse("set heredoc '%s'\n",
6872 redir->rd_filename);
6873 setup_heredoc(redir);
6877 if (redir->rd_dup == REDIRFD_TO_FILE) {
6878 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6882 if (redir->rd_filename == NULL) {
6885 * "cmd >" (no filename)
6886 * "cmd > <file" (2nd redirect starts too early)
6888 syntax_error("invalid redirect");
6891 mode = redir_table[redir->rd_type].mode;
6892 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6893 newfd = open_or_warn(p, mode);
6896 /* Error message from open_or_warn can be lost
6897 * if stderr has been redirected, but bash
6898 * and ash both lose it as well
6899 * (though zsh doesn't!)
6903 if (newfd == redir->rd_fd && sqp) {
6904 /* open() gave us precisely the fd we wanted.
6905 * This means that this fd was not busy
6906 * (not opened to anywhere).
6907 * Remember to close it on restore:
6909 *sqp = add_squirrel_closed(*sqp, newfd);
6910 debug_printf_redir("redir to previously closed fd %d\n", newfd);
6913 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6914 newfd = redir->rd_dup;
6917 if (newfd == redir->rd_fd)
6920 /* if "N>FILE": move newfd to redir->rd_fd */
6921 /* if "N>&M": dup newfd to redir->rd_fd */
6922 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6924 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6925 if (newfd == REDIRFD_CLOSE) {
6926 /* "N>&-" means "close me" */
6928 /* ^^^ optimization: saving may already
6929 * have closed it. If not... */
6930 close(redir->rd_fd);
6932 /* Sometimes we do another close on restore, getting EBADF.
6933 * Consider "echo 3>FILE 3>&-"
6934 * first redirect remembers "need to close 3",
6935 * and second redirect closes 3! Restore code then closes 3 again.
6938 /* if newfd is a script fd or saved fd, simulate EBADF */
6939 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6941 //bb_perror_msg_and_die("can't duplicate file descriptor");
6942 newfd = -1; /* same effect as code above */
6944 xdup2(newfd, redir->rd_fd);
6945 if (redir->rd_dup == REDIRFD_TO_FILE)
6946 /* "rd_fd > FILE" */
6948 /* else: "rd_fd > rd_dup" */
6954 static char *find_in_path(const char *arg)
6957 const char *PATH = get_local_var_value("PATH");
6963 const char *end = strchrnul(PATH, ':');
6964 int sz = end - PATH; /* must be int! */
6968 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6970 /* We have xxx::yyyy in $PATH,
6971 * it means "use current dir" */
6974 if (access(ret, F_OK) == 0)
6987 static const struct built_in_command *find_builtin_helper(const char *name,
6988 const struct built_in_command *x,
6989 const struct built_in_command *end)
6992 if (strcmp(name, x->b_cmd) != 0) {
6996 debug_printf_exec("found builtin '%s'\n", name);
7001 static const struct built_in_command *find_builtin1(const char *name)
7003 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7005 static const struct built_in_command *find_builtin(const char *name)
7007 const struct built_in_command *x = find_builtin1(name);
7010 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7013 #if ENABLE_HUSH_FUNCTIONS
7014 static struct function **find_function_slot(const char *name)
7016 struct function **funcpp = &G.top_func;
7018 if (strcmp(name, (*funcpp)->name) == 0) {
7021 funcpp = &(*funcpp)->next;
7026 static const struct function *find_function(const char *name)
7028 const struct function *funcp = *find_function_slot(name);
7030 debug_printf_exec("found function '%s'\n", name);
7034 /* Note: takes ownership on name ptr */
7035 static struct function *new_function(char *name)
7037 struct function **funcpp = find_function_slot(name);
7038 struct function *funcp = *funcpp;
7040 if (funcp != NULL) {
7041 struct command *cmd = funcp->parent_cmd;
7042 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7044 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7046 /* Note: if !funcp->body, do not free body_as_string!
7047 * This is a special case of "-F name body" function:
7048 * body_as_string was not malloced! */
7050 free_pipe_list(funcp->body);
7052 free(funcp->body_as_string);
7056 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7057 cmd->argv[0] = funcp->name;
7058 cmd->group = funcp->body;
7060 cmd->group_as_string = funcp->body_as_string;
7064 debug_printf_exec("remembering new function '%s'\n", name);
7065 funcp = *funcpp = xzalloc(sizeof(*funcp));
7066 /*funcp->next = NULL;*/
7073 # if ENABLE_HUSH_UNSET
7074 static void unset_func(const char *name)
7076 struct function **funcpp = find_function_slot(name);
7077 struct function *funcp = *funcpp;
7079 if (funcp != NULL) {
7080 debug_printf_exec("freeing function '%s'\n", funcp->name);
7081 *funcpp = funcp->next;
7082 /* funcp is unlinked now, deleting it.
7083 * Note: if !funcp->body, the function was created by
7084 * "-F name body", do not free ->body_as_string
7085 * and ->name as they were not malloced. */
7087 free_pipe_list(funcp->body);
7090 free(funcp->body_as_string);
7099 #define exec_function(to_free, funcp, argv) \
7100 exec_function(funcp, argv)
7102 static void exec_function(char ***to_free,
7103 const struct function *funcp,
7104 char **argv) NORETURN;
7105 static void exec_function(char ***to_free,
7106 const struct function *funcp,
7112 argv[0] = G.global_argv[0];
7113 G.global_argv = argv;
7114 G.global_argc = n = 1 + string_array_len(argv + 1);
7116 // Example when we are here: "cmd | func"
7117 // func will run with saved-redirect fds open.
7118 // $ f() { echo /proc/self/fd/*; }
7120 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7121 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7124 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7125 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7126 // They are CLOEXEC so external programs won't see them, but
7127 // for "more correctness" we might want to close those extra fds here:
7128 //? close_saved_fds_and_FILE_fds();
7130 /* "we are in function, ok to use return" */
7131 G_flag_return_in_progress = -1;
7132 IF_HUSH_LOCAL(G.func_nest_level++;)
7134 /* On MMU, funcp->body is always non-NULL */
7135 n = run_list(funcp->body);
7139 //? close_saved_fds_and_FILE_fds();
7141 //TODO: check whether "true | func_with_return" works
7143 re_execute_shell(to_free,
7144 funcp->body_as_string,
7151 static int run_function(const struct function *funcp, char **argv)
7157 save_and_replace_G_args(&sv, argv);
7159 /* "we are in function, ok to use return" */
7160 sv_flg = G_flag_return_in_progress;
7161 G_flag_return_in_progress = -1;
7162 IF_HUSH_LOCAL(G.func_nest_level++;)
7164 /* On MMU, funcp->body is always non-NULL */
7167 /* Function defined by -F */
7168 parse_and_run_string(funcp->body_as_string);
7169 rc = G.last_exitcode;
7173 rc = run_list(funcp->body);
7176 # if ENABLE_HUSH_LOCAL
7178 struct variable *var;
7179 struct variable **var_pp;
7181 var_pp = &G.top_var;
7182 while ((var = *var_pp) != NULL) {
7183 if (var->func_nest_level < G.func_nest_level) {
7184 var_pp = &var->next;
7188 if (var->flg_export)
7189 bb_unsetenv(var->varstr);
7190 /* Remove from global list */
7191 *var_pp = var->next;
7197 G.func_nest_level--;
7200 G_flag_return_in_progress = sv_flg;
7202 restore_G_args(&sv, argv);
7206 #endif /* ENABLE_HUSH_FUNCTIONS */
7210 #define exec_builtin(to_free, x, argv) \
7211 exec_builtin(x, argv)
7213 #define exec_builtin(to_free, x, argv) \
7214 exec_builtin(to_free, argv)
7216 static void exec_builtin(char ***to_free,
7217 const struct built_in_command *x,
7218 char **argv) NORETURN;
7219 static void exec_builtin(char ***to_free,
7220 const struct built_in_command *x,
7226 //? close_saved_fds_and_FILE_fds();
7227 rcode = x->b_function(argv);
7232 /* On NOMMU, we must never block!
7233 * Example: { sleep 99 | read line; } & echo Ok
7235 re_execute_shell(to_free,
7244 static void execvp_or_die(char **argv) NORETURN;
7245 static void execvp_or_die(char **argv)
7248 debug_printf_exec("execing '%s'\n", argv[0]);
7249 /* Don't propagate SIG_IGN to the child */
7250 if (SPECIAL_JOBSTOP_SIGS != 0)
7251 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7252 execvp(argv[0], argv);
7254 if (errno == EACCES) e = 126;
7255 if (errno == ENOENT) e = 127;
7256 bb_perror_msg("can't execute '%s'", argv[0]);
7260 #if ENABLE_HUSH_MODE_X
7261 static void dump_cmd_in_x_mode(char **argv)
7263 if (G_x_mode && argv) {
7264 /* We want to output the line in one write op */
7272 len += strlen(argv[n++]) + 1;
7278 p += sprintf(p, " %s", argv[n++]);
7286 # define dump_cmd_in_x_mode(argv) ((void)0)
7290 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7291 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7292 #define pseudo_exec(nommu_save, command, argv_expanded) \
7293 pseudo_exec(command, argv_expanded)
7296 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7298 * Don't exit() here. If you don't exec, use _exit instead.
7299 * The at_exit handlers apparently confuse the calling process,
7300 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7302 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7303 char **argv, int assignment_cnt,
7304 char **argv_expanded) NORETURN;
7305 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7306 char **argv, int assignment_cnt,
7307 char **argv_expanded)
7311 new_env = expand_assignments(argv, assignment_cnt);
7312 dump_cmd_in_x_mode(new_env);
7314 if (!argv[assignment_cnt]) {
7315 /* Case when we are here: ... | var=val | ...
7316 * (note that we do not exit early, i.e., do not optimize out
7317 * expand_assignments(): think about ... | var=`sleep 1` | ...
7319 free_strings(new_env);
7320 _exit(EXIT_SUCCESS);
7324 set_vars_and_save_old(new_env);
7325 free(new_env); /* optional */
7326 /* we can also destroy set_vars_and_save_old's return value,
7329 nommu_save->new_env = new_env;
7330 nommu_save->old_vars = set_vars_and_save_old(new_env);
7333 if (argv_expanded) {
7334 argv = argv_expanded;
7336 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7338 nommu_save->argv = argv;
7341 dump_cmd_in_x_mode(argv);
7343 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7344 if (strchr(argv[0], '/') != NULL)
7348 #if ENABLE_HUSH_FUNCTIONS
7349 /* Check if the command matches any functions (this goes before bltins) */
7351 const struct function *funcp = find_function(argv[0]);
7353 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7358 /* Check if the command matches any of the builtins.
7359 * Depending on context, this might be redundant. But it's
7360 * easier to waste a few CPU cycles than it is to figure out
7361 * if this is one of those cases.
7364 /* On NOMMU, it is more expensive to re-execute shell
7365 * just in order to run echo or test builtin.
7366 * It's better to skip it here and run corresponding
7367 * non-builtin later. */
7368 const struct built_in_command *x;
7369 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7371 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7375 #if ENABLE_FEATURE_SH_STANDALONE
7376 /* Check if the command matches any busybox applets */
7378 int a = find_applet_by_name(argv[0]);
7380 # if BB_MMU /* see above why on NOMMU it is not allowed */
7381 if (APPLET_IS_NOEXEC(a)) {
7382 /* Do not leak open fds from opened script files etc.
7383 * Testcase: interactive "ls -l /proc/self/fd"
7384 * should not show tty fd open.
7386 close_saved_fds_and_FILE_fds();
7387 //FIXME: should also close saved redir fds
7388 /* Without this, "rm -i FILE" can't be ^C'ed: */
7389 switch_off_special_sigs(G.special_sig_mask);
7390 debug_printf_exec("running applet '%s'\n", argv[0]);
7391 run_noexec_applet_and_exit(a, argv[0], argv);
7394 /* Re-exec ourselves */
7395 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7396 /* Don't propagate SIG_IGN to the child */
7397 if (SPECIAL_JOBSTOP_SIGS != 0)
7398 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7399 execv(bb_busybox_exec_path, argv);
7400 /* If they called chroot or otherwise made the binary no longer
7401 * executable, fall through */
7406 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7409 execvp_or_die(argv);
7412 /* Called after [v]fork() in run_pipe
7414 static void pseudo_exec(nommu_save_t *nommu_save,
7415 struct command *command,
7416 char **argv_expanded) NORETURN;
7417 static void pseudo_exec(nommu_save_t *nommu_save,
7418 struct command *command,
7419 char **argv_expanded)
7421 if (command->argv) {
7422 pseudo_exec_argv(nommu_save, command->argv,
7423 command->assignment_cnt, argv_expanded);
7426 if (command->group) {
7427 /* Cases when we are here:
7430 * ... | ( list ) | ...
7431 * ... | { list } | ...
7435 debug_printf_exec("pseudo_exec: run_list\n");
7436 reset_traps_to_defaults();
7437 rcode = run_list(command->group);
7438 /* OK to leak memory by not calling free_pipe_list,
7439 * since this process is about to exit */
7442 re_execute_shell(&nommu_save->argv_from_re_execing,
7443 command->group_as_string,
7450 /* Case when we are here: ... | >file */
7451 debug_printf_exec("pseudo_exec'ed null command\n");
7452 _exit(EXIT_SUCCESS);
7456 static const char *get_cmdtext(struct pipe *pi)
7462 /* This is subtle. ->cmdtext is created only on first backgrounding.
7463 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7464 * On subsequent bg argv is trashed, but we won't use it */
7468 argv = pi->cmds[0].argv;
7470 pi->cmdtext = xzalloc(1);
7475 len += strlen(*argv) + 1;
7479 argv = pi->cmds[0].argv;
7481 p = stpcpy(p, *argv);
7488 static void remove_job_from_table(struct pipe *pi)
7490 struct pipe *prev_pipe;
7492 if (pi == G.job_list) {
7493 G.job_list = pi->next;
7495 prev_pipe = G.job_list;
7496 while (prev_pipe->next != pi)
7497 prev_pipe = prev_pipe->next;
7498 prev_pipe->next = pi->next;
7502 G.last_jobid = G.job_list->jobid;
7505 static void delete_finished_job(struct pipe *pi)
7507 remove_job_from_table(pi);
7511 static void clean_up_last_dead_job(void)
7513 if (G.job_list && !G.job_list->alive_cmds)
7514 delete_finished_job(G.job_list);
7517 static void insert_job_into_table(struct pipe *pi)
7519 struct pipe *job, **jobp;
7522 clean_up_last_dead_job();
7524 /* Find the end of the list, and find next job ID to use */
7527 while ((job = *jobp) != NULL) {
7534 /* Create a new job struct at the end */
7535 job = *jobp = xmemdup(pi, sizeof(*pi));
7537 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7538 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7539 for (i = 0; i < pi->num_cmds; i++) {
7540 job->cmds[i].pid = pi->cmds[i].pid;
7541 /* all other fields are not used and stay zero */
7543 job->cmdtext = xstrdup(get_cmdtext(pi));
7545 if (G_interactive_fd)
7546 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7547 G.last_jobid = job->jobid;
7551 static int job_exited_or_stopped(struct pipe *pi)
7555 if (pi->alive_cmds != pi->stopped_cmds)
7558 /* All processes in fg pipe have exited or stopped */
7562 rcode = pi->cmds[i].cmd_exitcode;
7563 /* usually last process gives overall exitstatus,
7564 * but with "set -o pipefail", last *failed* process does */
7565 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7568 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7572 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7579 dead = WIFEXITED(status) || WIFSIGNALED(status);
7582 if (WIFSTOPPED(status))
7583 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7584 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7585 if (WIFSIGNALED(status))
7586 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7587 childpid, WTERMSIG(status), WEXITSTATUS(status));
7588 if (WIFEXITED(status))
7589 debug_printf_jobs("pid %d exited, exitcode %d\n",
7590 childpid, WEXITSTATUS(status));
7592 /* Were we asked to wait for a fg pipe? */
7594 i = fg_pipe->num_cmds;
7599 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7600 if (fg_pipe->cmds[i].pid != childpid)
7604 fg_pipe->cmds[i].pid = 0;
7605 fg_pipe->alive_cmds--;
7606 ex = WEXITSTATUS(status);
7607 /* bash prints killer signal's name for *last*
7608 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7609 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7611 if (WIFSIGNALED(status)) {
7612 int sig = WTERMSIG(status);
7613 if (i == fg_pipe->num_cmds-1)
7614 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7615 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7616 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7617 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7618 * Maybe we need to use sig | 128? */
7621 fg_pipe->cmds[i].cmd_exitcode = ex;
7623 fg_pipe->stopped_cmds++;
7625 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7626 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7627 rcode = job_exited_or_stopped(fg_pipe);
7629 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7630 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7631 * and "killall -STOP cat" */
7632 if (G_interactive_fd) {
7634 if (fg_pipe->alive_cmds != 0)
7635 insert_job_into_table(fg_pipe);
7639 if (fg_pipe->alive_cmds == 0)
7642 /* There are still running processes in the fg_pipe */
7645 /* It wasn't in fg_pipe, look for process in bg pipes */
7649 /* We were asked to wait for bg or orphaned children */
7650 /* No need to remember exitcode in this case */
7651 for (pi = G.job_list; pi; pi = pi->next) {
7652 for (i = 0; i < pi->num_cmds; i++) {
7653 if (pi->cmds[i].pid == childpid)
7654 goto found_pi_and_prognum;
7657 /* Happens when shell is used as init process (init=/bin/sh) */
7658 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7659 return -1; /* this wasn't a process from fg_pipe */
7661 found_pi_and_prognum:
7664 int rcode = WEXITSTATUS(status);
7665 if (WIFSIGNALED(status))
7666 rcode = 128 + WTERMSIG(status);
7667 pi->cmds[i].cmd_exitcode = rcode;
7668 if (G.last_bg_pid == pi->cmds[i].pid)
7669 G.last_bg_pid_exitcode = rcode;
7670 pi->cmds[i].pid = 0;
7672 if (!pi->alive_cmds) {
7673 if (G_interactive_fd) {
7674 printf(JOB_STATUS_FORMAT, pi->jobid,
7675 "Done", pi->cmdtext);
7676 delete_finished_job(pi);
7679 * bash deletes finished jobs from job table only in interactive mode,
7680 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7681 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7682 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7683 * We only retain one "dead" job, if it's the single job on the list.
7684 * This covers most of real-world scenarios where this is useful.
7686 if (pi != G.job_list)
7687 delete_finished_job(pi);
7695 return -1; /* this wasn't a process from fg_pipe */
7698 /* Check to see if any processes have exited -- if they have,
7699 * figure out why and see if a job has completed.
7701 * If non-NULL fg_pipe: wait for its completion or stop.
7702 * Return its exitcode or zero if stopped.
7704 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7705 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7706 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7707 * or 0 if no children changed status.
7709 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7710 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7711 * or 0 if no children changed status.
7713 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7719 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7721 attributes = WUNTRACED;
7722 if (fg_pipe == NULL)
7723 attributes |= WNOHANG;
7726 #if ENABLE_HUSH_FAST
7727 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7728 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7729 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7730 /* There was neither fork nor SIGCHLD since last waitpid */
7731 /* Avoid doing waitpid syscall if possible */
7732 if (!G.we_have_children) {
7736 if (fg_pipe == NULL) { /* is WNOHANG set? */
7737 /* We have children, but they did not exit
7738 * or stop yet (we saw no SIGCHLD) */
7741 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7745 /* Do we do this right?
7746 * bash-3.00# sleep 20 | false
7748 * [3]+ Stopped sleep 20 | false
7749 * bash-3.00# echo $?
7750 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7751 * [hush 1.14.0: yes we do it right]
7755 #if ENABLE_HUSH_FAST
7757 i = G.count_SIGCHLD;
7759 childpid = waitpid(-1, &status, attributes);
7760 if (childpid <= 0) {
7761 if (childpid && errno != ECHILD)
7762 bb_perror_msg("waitpid");
7763 #if ENABLE_HUSH_FAST
7764 else { /* Until next SIGCHLD, waitpid's are useless */
7765 G.we_have_children = (childpid == 0);
7766 G.handled_SIGCHLD = i;
7767 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7770 /* ECHILD (no children), or 0 (no change in children status) */
7774 rcode = process_wait_result(fg_pipe, childpid, status);
7776 /* fg_pipe exited or stopped */
7779 if (childpid == waitfor_pid) {
7780 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7781 rcode = WEXITSTATUS(status);
7782 if (WIFSIGNALED(status))
7783 rcode = 128 + WTERMSIG(status);
7784 if (WIFSTOPPED(status))
7785 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7786 rcode = 128 + WSTOPSIG(status);
7788 break; /* "wait PID" called us, give it exitcode+1 */
7790 /* This wasn't one of our processes, or */
7791 /* fg_pipe still has running processes, do waitpid again */
7792 } /* while (waitpid succeeds)... */
7798 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7801 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7802 if (G_saved_tty_pgrp) {
7803 /* Job finished, move the shell to the foreground */
7804 p = getpgrp(); /* our process group id */
7805 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7806 tcsetpgrp(G_interactive_fd, p);
7812 /* Start all the jobs, but don't wait for anything to finish.
7815 * Return code is normally -1, when the caller has to wait for children
7816 * to finish to determine the exit status of the pipe. If the pipe
7817 * is a simple builtin command, however, the action is done by the
7818 * time run_pipe returns, and the exit code is provided as the
7821 * Returns -1 only if started some children. IOW: we have to
7822 * mask out retvals of builtins etc with 0xff!
7824 * The only case when we do not need to [v]fork is when the pipe
7825 * is single, non-backgrounded, non-subshell command. Examples:
7826 * cmd ; ... { list } ; ...
7827 * cmd && ... { list } && ...
7828 * cmd || ... { list } || ...
7829 * If it is, then we can run cmd as a builtin, NOFORK,
7830 * or (if SH_STANDALONE) an applet, and we can run the { list }
7831 * with run_list. If it isn't one of these, we fork and exec cmd.
7833 * Cases when we must fork:
7834 * non-single: cmd | cmd
7835 * backgrounded: cmd & { list } &
7836 * subshell: ( list ) [&]
7838 #if !ENABLE_HUSH_MODE_X
7839 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7840 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7842 static int redirect_and_varexp_helper(char ***new_env_p,
7843 struct variable **old_vars_p,
7844 struct command *command,
7845 struct squirrel **sqp,
7846 char **argv_expanded)
7848 /* setup_redirects acts on file descriptors, not FILEs.
7849 * This is perfect for work that comes after exec().
7850 * Is it really safe for inline use? Experimentally,
7851 * things seem to work. */
7852 int rcode = setup_redirects(command, sqp);
7854 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7855 *new_env_p = new_env;
7856 dump_cmd_in_x_mode(new_env);
7857 dump_cmd_in_x_mode(argv_expanded);
7859 *old_vars_p = set_vars_and_save_old(new_env);
7863 static NOINLINE int run_pipe(struct pipe *pi)
7865 static const char *const null_ptr = NULL;
7869 struct command *command;
7870 char **argv_expanded;
7872 struct squirrel *squirrel = NULL;
7875 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7878 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7879 * Result should be 3 lines: q w e, qwe, q w e
7881 G.ifs = get_local_var_value("IFS");
7885 IF_HUSH_JOB(pi->pgrp = -1;)
7886 pi->stopped_cmds = 0;
7887 command = &pi->cmds[0];
7888 argv_expanded = NULL;
7890 if (pi->num_cmds != 1
7891 || pi->followup == PIPE_BG
7892 || command->cmd_type == CMD_SUBSHELL
7899 debug_printf_exec(": group:%p argv:'%s'\n",
7900 command->group, command->argv ? command->argv[0] : "NONE");
7902 if (command->group) {
7903 #if ENABLE_HUSH_FUNCTIONS
7904 if (command->cmd_type == CMD_FUNCDEF) {
7905 /* "executing" func () { list } */
7906 struct function *funcp;
7908 funcp = new_function(command->argv[0]);
7909 /* funcp->name is already set to argv[0] */
7910 funcp->body = command->group;
7912 funcp->body_as_string = command->group_as_string;
7913 command->group_as_string = NULL;
7915 command->group = NULL;
7916 command->argv[0] = NULL;
7917 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7918 funcp->parent_cmd = command;
7919 command->child_func = funcp;
7921 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7923 return EXIT_SUCCESS;
7927 debug_printf("non-subshell group\n");
7928 rcode = 1; /* exitcode if redir failed */
7929 if (setup_redirects(command, &squirrel) == 0) {
7930 debug_printf_exec(": run_list\n");
7931 rcode = run_list(command->group) & 0xff;
7933 restore_redirects(squirrel);
7934 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7936 debug_printf_exec("run_pipe: return %d\n", rcode);
7940 argv = command->argv ? command->argv : (char **) &null_ptr;
7942 const struct built_in_command *x;
7943 #if ENABLE_HUSH_FUNCTIONS
7944 const struct function *funcp;
7948 char **new_env = NULL;
7949 struct variable *old_vars = NULL;
7951 if (argv[command->assignment_cnt] == NULL) {
7952 /* Assignments, but no command */
7953 /* Ensure redirects take effect (that is, create files).
7954 * Try "a=t >file" */
7955 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7956 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
7957 /* Set shell variables */
7961 if (set_local_var(*argv, /*flag:*/ 0)) {
7962 /* assignment to readonly var / putenv error? */
7968 /* Redirect error sets $? to 1. Otherwise,
7969 * if evaluating assignment value set $?, retain it.
7970 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7972 rcode = G.last_exitcode;
7973 /* Exit, _skipping_ variable restoring code: */
7974 goto clean_up_and_ret0;
7976 #else /* Older, bigger, but more correct code */
7978 rcode = setup_redirects(command, &squirrel);
7979 restore_redirects(squirrel);
7980 /* Set shell variables */
7982 bb_putchar_stderr('+');
7984 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7986 fprintf(stderr, " %s", p);
7987 debug_printf_exec("set shell var:'%s'->'%s'\n",
7989 if (set_local_var(p, /*flag:*/ 0)) {
7990 /* assignment to readonly var / putenv error? */
7996 bb_putchar_stderr('\n');
7997 /* Redirect error sets $? to 1. Otherwise,
7998 * if evaluating assignment value set $?, retain it.
7999 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8001 rcode = G.last_exitcode;
8002 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8004 debug_printf_exec("run_pipe: return %d\n", rcode);
8009 /* Expand the rest into (possibly) many strings each */
8011 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8012 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8016 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8019 /* if someone gives us an empty string: `cmd with empty output` */
8020 if (!argv_expanded[0]) {
8021 free(argv_expanded);
8023 return G.last_exitcode;
8026 #if ENABLE_HUSH_FUNCTIONS
8027 /* Check if argv[0] matches any functions (this goes before bltins) */
8028 funcp = find_function(argv_expanded[0]);
8032 x = find_builtin(argv_expanded[0]);
8035 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8036 debug_printf("exec with redirects only\n");
8037 rcode = setup_redirects(command, NULL);
8038 /* rcode=1 can be if redir file can't be opened */
8039 goto clean_up_and_ret1;
8042 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8045 debug_printf_exec(": builtin '%s' '%s'...\n",
8046 x->b_cmd, argv_expanded[1]);
8048 rcode = x->b_function(argv_expanded) & 0xff;
8051 #if ENABLE_HUSH_FUNCTIONS
8053 # if ENABLE_HUSH_LOCAL
8054 struct variable **sv;
8055 sv = G.shadowed_vars_pp;
8056 G.shadowed_vars_pp = &old_vars;
8058 debug_printf_exec(": function '%s' '%s'...\n",
8059 funcp->name, argv_expanded[1]);
8060 rcode = run_function(funcp, argv_expanded) & 0xff;
8061 # if ENABLE_HUSH_LOCAL
8062 G.shadowed_vars_pp = sv;
8068 unset_vars(new_env);
8070 /* clean_up_and_ret0: */
8071 restore_redirects(squirrel);
8073 * Try "usleep 99999999" + ^C + "echo $?"
8074 * with FEATURE_SH_NOFORK=y.
8077 /* It was builtin or nofork.
8078 * if this would be a real fork/execed program,
8079 * it should have died if a fatal sig was received.
8080 * But OTOH, there was no separate process,
8081 * the sig was sent to _shell_, not to non-existing
8083 * Let's just handle ^C only, this one is obvious:
8084 * we aren't ok with exitcode 0 when ^C was pressed
8085 * during builtin/nofork.
8087 if (sigismember(&G.pending_set, SIGINT))
8088 rcode = 128 + SIGINT;
8091 free(argv_expanded);
8092 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8094 debug_printf_exec("run_pipe return %d\n", rcode);
8098 if (ENABLE_FEATURE_SH_NOFORK) {
8099 int n = find_applet_by_name(argv_expanded[0]);
8100 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8101 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8103 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8104 argv_expanded[0], argv_expanded[1]);
8106 * Note: signals (^C) can't interrupt here.
8107 * We remember them and they will be acted upon
8108 * after applet returns.
8109 * This makes applets which can run for a long time
8110 * and/or wait for user input ineligible for NOFORK:
8111 * for example, "yes" or "rm" (rm -i waits for input).
8113 rcode = run_nofork_applet(n, argv_expanded);
8115 goto clean_up_and_ret;
8118 /* It is neither builtin nor applet. We must fork. */
8122 /* NB: argv_expanded may already be created, and that
8123 * might include `cmd` runs! Do not rerun it! We *must*
8124 * use argv_expanded if it's non-NULL */
8126 /* Going to fork a child per each pipe member */
8131 while (cmd_no < pi->num_cmds) {
8132 struct fd_pair pipefds;
8134 volatile nommu_save_t nommu_save;
8135 nommu_save.new_env = NULL;
8136 nommu_save.old_vars = NULL;
8137 nommu_save.argv = NULL;
8138 nommu_save.argv_from_re_execing = NULL;
8140 command = &pi->cmds[cmd_no];
8142 if (command->argv) {
8143 debug_printf_exec(": pipe member '%s' '%s'...\n",
8144 command->argv[0], command->argv[1]);
8146 debug_printf_exec(": pipe member with no argv\n");
8149 /* pipes are inserted between pairs of commands */
8152 if (cmd_no < pi->num_cmds)
8153 xpiped_pair(pipefds);
8155 command->pid = BB_MMU ? fork() : vfork();
8156 if (!command->pid) { /* child */
8158 disable_restore_tty_pgrp_on_exit();
8159 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8161 /* Every child adds itself to new process group
8162 * with pgid == pid_of_first_child_in_pipe */
8163 if (G.run_list_level == 1 && G_interactive_fd) {
8166 if (pgrp < 0) /* true for 1st process only */
8168 if (setpgid(0, pgrp) == 0
8169 && pi->followup != PIPE_BG
8170 && G_saved_tty_pgrp /* we have ctty */
8172 /* We do it in *every* child, not just first,
8174 tcsetpgrp(G_interactive_fd, pgrp);
8178 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8179 /* 1st cmd in backgrounded pipe
8180 * should have its stdin /dev/null'ed */
8182 if (open(bb_dev_null, O_RDONLY))
8183 xopen("/", O_RDONLY);
8185 xmove_fd(next_infd, 0);
8187 xmove_fd(pipefds.wr, 1);
8190 /* Like bash, explicit redirects override pipes,
8191 * and the pipe fd (fd#1) is available for dup'ing:
8192 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8193 * of cmd1 goes into pipe.
8195 if (setup_redirects(command, NULL)) {
8196 /* Happens when redir file can't be opened:
8197 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8199 * hush: can't open '/qwe/rty': No such file or directory
8201 * (echo BAR is not executed, it hits _exit(1) below)
8206 /* Stores to nommu_save list of env vars putenv'ed
8207 * (NOMMU, on MMU we don't need that) */
8208 /* cast away volatility... */
8209 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8210 /* pseudo_exec() does not return */
8213 /* parent or error */
8214 #if ENABLE_HUSH_FAST
8216 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8218 enable_restore_tty_pgrp_on_exit();
8220 /* Clean up after vforked child */
8221 free(nommu_save.argv);
8222 free(nommu_save.argv_from_re_execing);
8223 unset_vars(nommu_save.new_env);
8224 add_vars(nommu_save.old_vars);
8226 free(argv_expanded);
8227 argv_expanded = NULL;
8228 if (command->pid < 0) { /* [v]fork failed */
8229 /* Clearly indicate, was it fork or vfork */
8230 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8234 /* Second and next children need to know pid of first one */
8236 pi->pgrp = command->pid;
8242 if (cmd_no < pi->num_cmds)
8244 /* Pass read (output) pipe end to next iteration */
8245 next_infd = pipefds.rd;
8248 if (!pi->alive_cmds) {
8250 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8255 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8259 /* NB: called by pseudo_exec, and therefore must not modify any
8260 * global data until exec/_exit (we can be a child after vfork!) */
8261 static int run_list(struct pipe *pi)
8263 #if ENABLE_HUSH_CASE
8264 char *case_word = NULL;
8266 #if ENABLE_HUSH_LOOPS
8267 struct pipe *loop_top = NULL;
8268 char **for_lcur = NULL;
8269 char **for_list = NULL;
8271 smallint last_followup;
8273 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8274 smalluint cond_code = 0;
8276 enum { cond_code = 0 };
8279 smallint rword; /* RES_foo */
8280 smallint last_rword; /* ditto */
8283 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8286 #if ENABLE_HUSH_LOOPS
8287 /* Check syntax for "for" */
8290 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8291 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8293 /* current word is FOR or IN (BOLD in comments below) */
8294 if (cpipe->next == NULL) {
8295 syntax_error("malformed for");
8297 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8300 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8301 if (cpipe->next->res_word == RES_DO)
8303 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8304 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8305 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8307 syntax_error("malformed for");
8309 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8316 /* Past this point, all code paths should jump to ret: label
8317 * in order to return, no direct "return" statements please.
8318 * This helps to ensure that no memory is leaked. */
8326 last_rword = RES_XXXX;
8328 last_followup = PIPE_SEQ;
8329 rcode = G.last_exitcode;
8331 /* Go through list of pipes, (maybe) executing them. */
8332 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8334 int sv_errexit_depth;
8338 if (G_flag_return_in_progress == 1)
8341 IF_HAS_KEYWORDS(rword = pi->res_word;)
8342 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8343 rword, cond_code, last_rword);
8345 sv_errexit_depth = G.errexit_depth;
8346 if (IF_HAS_KEYWORDS(rword == RES_IF || rword == RES_ELIF ||)
8347 pi->followup != PIPE_SEQ
8351 #if ENABLE_HUSH_LOOPS
8352 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8353 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8355 /* start of a loop: remember where loop starts */
8360 /* Still in the same "if...", "then..." or "do..." branch? */
8361 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8362 if ((rcode == 0 && last_followup == PIPE_OR)
8363 || (rcode != 0 && last_followup == PIPE_AND)
8365 /* It is "<true> || CMD" or "<false> && CMD"
8366 * and we should not execute CMD */
8367 debug_printf_exec("skipped cmd because of || or &&\n");
8368 last_followup = pi->followup;
8369 goto dont_check_jobs_but_continue;
8372 last_followup = pi->followup;
8373 IF_HAS_KEYWORDS(last_rword = rword;)
8376 if (rword == RES_THEN) {
8377 /* if false; then ... fi has exitcode 0! */
8378 G.last_exitcode = rcode = EXIT_SUCCESS;
8379 /* "if <false> THEN cmd": skip cmd */
8383 if (rword == RES_ELSE || rword == RES_ELIF) {
8384 /* "if <true> then ... ELSE/ELIF cmd":
8385 * skip cmd and all following ones */
8390 #if ENABLE_HUSH_LOOPS
8391 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8393 /* first loop through for */
8395 static const char encoded_dollar_at[] ALIGN1 = {
8396 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8397 }; /* encoded representation of "$@" */
8398 static const char *const encoded_dollar_at_argv[] = {
8399 encoded_dollar_at, NULL
8400 }; /* argv list with one element: "$@" */
8403 vals = (char**)encoded_dollar_at_argv;
8404 if (pi->next->res_word == RES_IN) {
8405 /* if no variable values after "in" we skip "for" */
8406 if (!pi->next->cmds[0].argv) {
8407 G.last_exitcode = rcode = EXIT_SUCCESS;
8408 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8411 vals = pi->next->cmds[0].argv;
8412 } /* else: "for var; do..." -> assume "$@" list */
8413 /* create list of variable values */
8414 debug_print_strings("for_list made from", vals);
8415 for_list = expand_strvec_to_strvec(vals);
8416 for_lcur = for_list;
8417 debug_print_strings("for_list", for_list);
8420 /* "for" loop is over, clean up */
8426 /* Insert next value from for_lcur */
8427 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8428 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8431 if (rword == RES_IN) {
8432 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8434 if (rword == RES_DONE) {
8435 continue; /* "done" has no cmds too */
8438 #if ENABLE_HUSH_CASE
8439 if (rword == RES_CASE) {
8440 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8441 case_word = expand_strvec_to_string(pi->cmds->argv);
8442 unbackslash(case_word);
8445 if (rword == RES_MATCH) {
8448 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8449 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8451 /* all prev words didn't match, does this one match? */
8452 argv = pi->cmds->argv;
8454 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8455 /* TODO: which FNM_xxx flags to use? */
8456 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8457 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8459 if (cond_code == 0) { /* match! we will execute this branch */
8461 case_word = NULL; /* make future "word)" stop */
8468 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8469 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8471 continue; /* not matched yet, skip this pipe */
8473 if (rword == RES_ESAC) {
8474 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8476 /* "case" did not match anything: still set $? (to 0) */
8477 G.last_exitcode = rcode = EXIT_SUCCESS;
8481 /* Just pressing <enter> in shell should check for jobs.
8482 * OTOH, in non-interactive shell this is useless
8483 * and only leads to extra job checks */
8484 if (pi->num_cmds == 0) {
8485 if (G_interactive_fd)
8486 goto check_jobs_and_continue;
8490 /* After analyzing all keywords and conditions, we decided
8491 * to execute this pipe. NB: have to do checkjobs(NULL)
8492 * after run_pipe to collect any background children,
8493 * even if list execution is to be stopped. */
8494 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8495 #if ENABLE_HUSH_LOOPS
8496 G.flag_break_continue = 0;
8498 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8500 /* We ran a builtin, function, or group.
8501 * rcode is already known
8502 * and we don't need to wait for anything. */
8503 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8504 G.last_exitcode = rcode;
8505 check_and_run_traps();
8506 #if ENABLE_HUSH_LOOPS
8507 /* Was it "break" or "continue"? */
8508 if (G.flag_break_continue) {
8509 smallint fbc = G.flag_break_continue;
8510 /* We might fall into outer *loop*,
8511 * don't want to break it too */
8513 G.depth_break_continue--;
8514 if (G.depth_break_continue == 0)
8515 G.flag_break_continue = 0;
8516 /* else: e.g. "continue 2" should *break* once, *then* continue */
8517 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8518 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8519 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8522 /* "continue": simulate end of loop */
8527 if (G_flag_return_in_progress == 1) {
8528 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8531 } else if (pi->followup == PIPE_BG) {
8532 /* What does bash do with attempts to background builtins? */
8533 /* even bash 3.2 doesn't do that well with nested bg:
8534 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8535 * I'm NOT treating inner &'s as jobs */
8537 if (G.run_list_level == 1)
8538 insert_job_into_table(pi);
8540 /* Last command's pid goes to $! */
8541 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8542 G.last_bg_pid_exitcode = 0;
8543 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8544 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8545 rcode = EXIT_SUCCESS;
8549 if (G.run_list_level == 1 && G_interactive_fd) {
8550 /* Waits for completion, then fg's main shell */
8551 rcode = checkjobs_and_fg_shell(pi);
8552 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8556 /* This one just waits for completion */
8557 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8558 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8560 G.last_exitcode = rcode;
8561 check_and_run_traps();
8564 /* Handle "set -e" */
8565 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8566 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8567 if (G.errexit_depth == 0)
8570 G.errexit_depth = sv_errexit_depth;
8572 /* Analyze how result affects subsequent commands */
8574 if (rword == RES_IF || rword == RES_ELIF)
8577 check_jobs_and_continue:
8578 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8579 dont_check_jobs_but_continue: ;
8580 #if ENABLE_HUSH_LOOPS
8581 /* Beware of "while false; true; do ..."! */
8583 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8584 /* check for RES_DONE is needed for "while ...; do \n done" case */
8586 if (rword == RES_WHILE) {
8588 /* "while false; do...done" - exitcode 0 */
8589 G.last_exitcode = rcode = EXIT_SUCCESS;
8590 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8594 if (rword == RES_UNTIL) {
8596 debug_printf_exec(": until expr is true: breaking\n");
8607 #if ENABLE_HUSH_LOOPS
8612 #if ENABLE_HUSH_CASE
8616 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8620 /* Select which version we will use */
8621 static int run_and_free_list(struct pipe *pi)
8624 debug_printf_exec("run_and_free_list entered\n");
8625 if (!G.o_opt[OPT_O_NOEXEC]) {
8626 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8627 rcode = run_list(pi);
8629 /* free_pipe_list has the side effect of clearing memory.
8630 * In the long run that function can be merged with run_list,
8631 * but doing that now would hobble the debugging effort. */
8633 debug_printf_exec("run_and_free_list return %d\n", rcode);
8638 static void install_sighandlers(unsigned mask)
8640 sighandler_t old_handler;
8642 while ((mask >>= 1) != 0) {
8646 old_handler = install_sighandler(sig, pick_sighandler(sig));
8647 /* POSIX allows shell to re-enable SIGCHLD
8648 * even if it was SIG_IGN on entry.
8649 * Therefore we skip IGN check for it:
8653 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8654 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8656 //if (sig == SIGHUP) continue; - TODO?
8657 if (old_handler == SIG_IGN) {
8658 /* oops... restore back to IGN, and record this fact */
8659 install_sighandler(sig, old_handler);
8660 #if ENABLE_HUSH_TRAP
8662 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8664 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8670 /* Called a few times only (or even once if "sh -c") */
8671 static void install_special_sighandlers(void)
8675 /* Which signals are shell-special? */
8676 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8677 if (G_interactive_fd) {
8678 mask |= SPECIAL_INTERACTIVE_SIGS;
8679 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8680 mask |= SPECIAL_JOBSTOP_SIGS;
8682 /* Careful, do not re-install handlers we already installed */
8683 if (G.special_sig_mask != mask) {
8684 unsigned diff = mask & ~G.special_sig_mask;
8685 G.special_sig_mask = mask;
8686 install_sighandlers(diff);
8692 /* Set handlers to restore tty pgrp and exit */
8693 static void install_fatal_sighandlers(void)
8697 /* We will restore tty pgrp on these signals */
8699 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8700 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8701 + (1 << SIGBUS ) * HUSH_DEBUG
8702 + (1 << SIGSEGV) * HUSH_DEBUG
8703 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8705 /* bash 3.2 seems to handle these just like 'fatal' ones */
8708 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8709 * if we aren't interactive... but in this case
8710 * we never want to restore pgrp on exit, and this fn is not called
8712 /*+ (1 << SIGHUP )*/
8713 /*+ (1 << SIGTERM)*/
8714 /*+ (1 << SIGINT )*/
8716 G_fatal_sig_mask = mask;
8718 install_sighandlers(mask);
8722 static int set_mode(int state, char mode, const char *o_opt)
8727 G.o_opt[OPT_O_NOEXEC] = state;
8730 IF_HUSH_MODE_X(G_x_mode = state;)
8734 /* "set -+o" without parameter.
8735 * in bash, set -o produces this output:
8739 * We always use the second form.
8741 const char *p = o_opt_strings;
8744 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8750 idx = index_in_strings(o_opt_strings, o_opt);
8752 G.o_opt[idx] = state;
8756 G.o_opt[OPT_O_ERREXIT] = state;
8759 return EXIT_FAILURE;
8761 return EXIT_SUCCESS;
8764 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8765 int hush_main(int argc, char **argv)
8768 OPT_login = (1 << 0),
8772 unsigned builtin_argc;
8774 struct variable *cur_var;
8775 struct variable *shell_ver;
8778 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8779 G.last_exitcode = EXIT_SUCCESS;
8781 #if ENABLE_HUSH_FAST
8782 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8785 G.argv0_for_re_execing = argv[0];
8787 /* Deal with HUSH_VERSION */
8788 shell_ver = xzalloc(sizeof(*shell_ver));
8789 shell_ver->flg_export = 1;
8790 shell_ver->flg_read_only = 1;
8791 /* Code which handles ${var<op>...} needs writable values for all variables,
8792 * therefore we xstrdup: */
8793 shell_ver->varstr = xstrdup(hush_version_str);
8794 /* Create shell local variables from the values
8795 * currently living in the environment */
8796 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8797 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8798 G.top_var = shell_ver;
8799 cur_var = G.top_var;
8802 char *value = strchr(*e, '=');
8803 if (value) { /* paranoia */
8804 cur_var->next = xzalloc(sizeof(*cur_var));
8805 cur_var = cur_var->next;
8806 cur_var->varstr = *e;
8807 cur_var->max_len = strlen(*e);
8808 cur_var->flg_export = 1;
8812 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8813 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8814 putenv(shell_ver->varstr);
8817 set_pwd_var(SETFLAG_EXPORT);
8819 #if BASH_HOSTNAME_VAR
8820 /* Set (but not export) HOSTNAME unless already set */
8821 if (!get_local_var_value("HOSTNAME")) {
8824 set_local_var_from_halves("HOSTNAME", uts.nodename);
8826 /* bash also exports SHLVL and _,
8827 * and sets (but doesn't export) the following variables:
8829 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8830 * BASH_VERSION='3.2.0(1)-release'
8832 * MACHTYPE=i386-pc-linux-gnu
8834 * PPID=<NNNNN> - we also do it elsewhere
8845 * PIPESTATUS=([0]="0")
8846 * HISTFILE=/<xxx>/.bash_history
8850 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8852 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8863 #if ENABLE_FEATURE_EDITING
8864 G.line_input_state = new_line_input_t(FOR_SHELL);
8867 /* Initialize some more globals to non-zero values */
8868 cmdedit_update_prompt();
8870 die_func = restore_ttypgrp_and__exit;
8872 /* Shell is non-interactive at first. We need to call
8873 * install_special_sighandlers() if we are going to execute "sh <script>",
8874 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8875 * If we later decide that we are interactive, we run install_special_sighandlers()
8876 * in order to intercept (more) signals.
8880 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8881 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8884 opt = getopt(argc, argv, "+c:exinsl"
8887 # if ENABLE_HUSH_FUNCTIONS
8897 * sh ... -c 'script'
8898 * sh ... -c 'script' ARG0 [ARG1...]
8899 * On NOMMU, if builtin_argc != 0,
8900 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8901 * "" needs to be replaced with NULL
8902 * and BARGV vector fed to builtin function.
8903 * Note: the form without ARG0 never happens:
8904 * sh ... -c 'builtin' BARGV... ""
8907 G.root_pid = getpid();
8908 G.root_ppid = getppid();
8910 G.global_argv = argv + optind;
8911 G.global_argc = argc - optind;
8913 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8914 const struct built_in_command *x;
8916 install_special_sighandlers();
8917 x = find_builtin(optarg);
8918 if (x) { /* paranoia */
8919 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8920 G.global_argv += builtin_argc;
8921 G.global_argv[-1] = NULL; /* replace "" */
8923 G.last_exitcode = x->b_function(argv + optind - 1);
8927 if (!G.global_argv[0]) {
8928 /* -c 'script' (no params): prevent empty $0 */
8929 G.global_argv--; /* points to argv[i] of 'script' */
8930 G.global_argv[0] = argv[0];
8932 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8933 install_special_sighandlers();
8934 parse_and_run_string(optarg);
8937 /* Well, we cannot just declare interactiveness,
8938 * we have to have some stuff (ctty, etc) */
8939 /* G_interactive_fd++; */
8942 /* "-s" means "read from stdin", but this is how we always
8943 * operate, so simply do nothing here. */
8949 case '<': /* "big heredoc" support */
8950 full_write1_str(optarg);
8953 unsigned long long empty_trap_mask;
8955 G.root_pid = bb_strtou(optarg, &optarg, 16);
8957 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8959 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8961 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8963 builtin_argc = bb_strtou(optarg, &optarg, 16);
8965 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8966 if (empty_trap_mask != 0) {
8967 IF_HUSH_TRAP(int sig;)
8968 install_special_sighandlers();
8969 # if ENABLE_HUSH_TRAP
8970 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8971 for (sig = 1; sig < NSIG; sig++) {
8972 if (empty_trap_mask & (1LL << sig)) {
8973 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8974 install_sighandler(sig, SIG_IGN);
8979 # if ENABLE_HUSH_LOOPS
8981 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8987 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
8989 # if ENABLE_HUSH_FUNCTIONS
8991 struct function *funcp = new_function(optarg);
8992 /* funcp->name is already set to optarg */
8993 /* funcp->body is set to NULL. It's a special case. */
8994 funcp->body_as_string = argv[optind];
9003 if (set_mode(1, opt, NULL) == 0) /* no error */
9007 fprintf(stderr, "Usage: sh [FILE]...\n"
9008 " or: sh -c command [args]...\n\n");
9014 } /* option parsing loop */
9016 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9017 G.global_argc = argc - (optind - 1);
9018 G.global_argv = argv + (optind - 1);
9019 G.global_argv[0] = argv[0];
9022 G.root_pid = getpid();
9023 G.root_ppid = getppid();
9026 /* If we are login shell... */
9027 if (flags & OPT_login) {
9029 debug_printf("sourcing /etc/profile\n");
9030 input = fopen_for_read("/etc/profile");
9031 if (input != NULL) {
9032 remember_FILE(input);
9033 install_special_sighandlers();
9034 parse_and_run_file(input);
9035 fclose_and_forget(input);
9037 /* bash: after sourcing /etc/profile,
9038 * tries to source (in the given order):
9039 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9040 * stopping on first found. --noprofile turns this off.
9041 * bash also sources ~/.bash_logout on exit.
9042 * If called as sh, skips .bash_XXX files.
9046 if (G.global_argv[1]) {
9049 * "bash <script>" (which is never interactive (unless -i?))
9050 * sources $BASH_ENV here (without scanning $PATH).
9051 * If called as sh, does the same but with $ENV.
9052 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9056 debug_printf("running script '%s'\n", G.global_argv[0]);
9057 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9058 input = xfopen_for_read(G.global_argv[0]);
9059 xfunc_error_retval = 1;
9060 remember_FILE(input);
9061 install_special_sighandlers();
9062 parse_and_run_file(input);
9063 #if ENABLE_FEATURE_CLEAN_UP
9064 fclose_and_forget(input);
9069 /* Up to here, shell was non-interactive. Now it may become one.
9070 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9073 /* A shell is interactive if the '-i' flag was given,
9074 * or if all of the following conditions are met:
9076 * no arguments remaining or the -s flag given
9077 * standard input is a terminal
9078 * standard output is a terminal
9079 * Refer to Posix.2, the description of the 'sh' utility.
9082 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9083 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9084 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9085 if (G_saved_tty_pgrp < 0)
9086 G_saved_tty_pgrp = 0;
9088 /* try to dup stdin to high fd#, >= 255 */
9089 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9090 if (G_interactive_fd < 0) {
9091 /* try to dup to any fd */
9092 G_interactive_fd = dup(STDIN_FILENO);
9093 if (G_interactive_fd < 0) {
9095 G_interactive_fd = 0;
9096 G_saved_tty_pgrp = 0;
9099 // TODO: track & disallow any attempts of user
9100 // to (inadvertently) close/redirect G_interactive_fd
9102 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9103 if (G_interactive_fd) {
9104 close_on_exec_on(G_interactive_fd);
9106 if (G_saved_tty_pgrp) {
9107 /* If we were run as 'hush &', sleep until we are
9108 * in the foreground (tty pgrp == our pgrp).
9109 * If we get started under a job aware app (like bash),
9110 * make sure we are now in charge so we don't fight over
9111 * who gets the foreground */
9113 pid_t shell_pgrp = getpgrp();
9114 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9115 if (G_saved_tty_pgrp == shell_pgrp)
9117 /* send TTIN to ourself (should stop us) */
9118 kill(- shell_pgrp, SIGTTIN);
9122 /* Install more signal handlers */
9123 install_special_sighandlers();
9125 if (G_saved_tty_pgrp) {
9126 /* Set other signals to restore saved_tty_pgrp */
9127 install_fatal_sighandlers();
9128 /* Put ourselves in our own process group
9129 * (bash, too, does this only if ctty is available) */
9130 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9131 /* Grab control of the terminal */
9132 tcsetpgrp(G_interactive_fd, getpid());
9134 enable_restore_tty_pgrp_on_exit();
9136 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9138 const char *hp = get_local_var_value("HISTFILE");
9140 hp = get_local_var_value("HOME");
9142 hp = concat_path_file(hp, ".hush_history");
9147 G.line_input_state->hist_file = hp;
9148 //set_local_var(xasprintf("HISTFILE=%s", ...));
9150 # if ENABLE_FEATURE_SH_HISTFILESIZE
9151 hp = get_local_var_value("HISTFILESIZE");
9152 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9157 install_special_sighandlers();
9159 #elif ENABLE_HUSH_INTERACTIVE
9160 /* No job control compiled in, only prompt/line editing */
9161 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9162 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9163 if (G_interactive_fd < 0) {
9164 /* try to dup to any fd */
9165 G_interactive_fd = dup(STDIN_FILENO);
9166 if (G_interactive_fd < 0)
9168 G_interactive_fd = 0;
9171 if (G_interactive_fd) {
9172 close_on_exec_on(G_interactive_fd);
9174 install_special_sighandlers();
9176 /* We have interactiveness code disabled */
9177 install_special_sighandlers();
9180 * if interactive but not a login shell, sources ~/.bashrc
9181 * (--norc turns this off, --rcfile <file> overrides)
9184 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9185 /* note: ash and hush share this string */
9186 printf("\n\n%s %s\n"
9187 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9190 "hush - the humble shell"
9194 parse_and_run_file(stdin);
9197 hush_exit(G.last_exitcode);
9204 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9209 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9210 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9212 int argc = string_array_len(argv);
9213 return applet_main_func(argc, argv);
9216 #if ENABLE_HUSH_TEST || BASH_TEST2
9217 static int FAST_FUNC builtin_test(char **argv)
9219 return run_applet_main(argv, test_main);
9222 #if ENABLE_HUSH_ECHO
9223 static int FAST_FUNC builtin_echo(char **argv)
9225 return run_applet_main(argv, echo_main);
9228 #if ENABLE_HUSH_PRINTF
9229 static int FAST_FUNC builtin_printf(char **argv)
9231 return run_applet_main(argv, printf_main);
9235 #if ENABLE_HUSH_HELP
9236 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9238 const struct built_in_command *x;
9241 "Built-in commands:\n"
9242 "------------------\n");
9243 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9245 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9247 return EXIT_SUCCESS;
9251 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9252 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9254 show_history(G.line_input_state);
9255 return EXIT_SUCCESS;
9259 static char **skip_dash_dash(char **argv)
9262 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9267 static int FAST_FUNC builtin_cd(char **argv)
9271 argv = skip_dash_dash(argv);
9273 if (newdir == NULL) {
9274 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9275 * bash says "bash: cd: HOME not set" and does nothing
9278 const char *home = get_local_var_value("HOME");
9279 newdir = home ? home : "/";
9281 if (chdir(newdir)) {
9282 /* Mimic bash message exactly */
9283 bb_perror_msg("cd: %s", newdir);
9284 return EXIT_FAILURE;
9286 /* Read current dir (get_cwd(1) is inside) and set PWD.
9287 * Note: do not enforce exporting. If PWD was unset or unexported,
9288 * set it again, but do not export. bash does the same.
9290 set_pwd_var(/*flag:*/ 0);
9291 return EXIT_SUCCESS;
9294 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9297 return EXIT_SUCCESS;
9300 static int FAST_FUNC builtin_eval(char **argv)
9302 int rcode = EXIT_SUCCESS;
9304 argv = skip_dash_dash(argv);
9306 char *str = expand_strvec_to_string(argv);
9308 * eval "echo Hi; done" ("done" is syntax error):
9309 * "echo Hi" will not execute too.
9311 parse_and_run_string(str);
9313 rcode = G.last_exitcode;
9318 static int FAST_FUNC builtin_exec(char **argv)
9320 argv = skip_dash_dash(argv);
9321 if (argv[0] == NULL)
9322 return EXIT_SUCCESS; /* bash does this */
9324 /* Careful: we can end up here after [v]fork. Do not restore
9325 * tty pgrp then, only top-level shell process does that */
9326 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9327 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9329 /* Saved-redirect fds, script fds and G_interactive_fd are still
9330 * open here. However, they are all CLOEXEC, and execv below
9331 * closes them. Try interactive "exec ls -l /proc/self/fd",
9332 * it should show no extra open fds in the "ls" process.
9333 * If we'd try to run builtins/NOEXECs, this would need improving.
9335 //close_saved_fds_and_FILE_fds();
9337 /* TODO: if exec fails, bash does NOT exit! We do.
9338 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9339 * and tcsetpgrp, and this is inherently racy.
9341 execvp_or_die(argv);
9344 static int FAST_FUNC builtin_exit(char **argv)
9346 debug_printf_exec("%s()\n", __func__);
9348 /* interactive bash:
9349 * # trap "echo EEE" EXIT
9352 * There are stopped jobs.
9353 * (if there are _stopped_ jobs, running ones don't count)
9356 * EEE (then bash exits)
9358 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9361 /* note: EXIT trap is run by hush_exit */
9362 argv = skip_dash_dash(argv);
9363 if (argv[0] == NULL)
9364 hush_exit(G.last_exitcode);
9365 /* mimic bash: exit 123abc == exit 255 + error msg */
9366 xfunc_error_retval = 255;
9367 /* bash: exit -2 == exit 254, no error msg */
9368 hush_exit(xatoi(argv[0]) & 0xff);
9371 #if ENABLE_HUSH_TYPE
9372 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9373 static int FAST_FUNC builtin_type(char **argv)
9375 int ret = EXIT_SUCCESS;
9381 if (0) {} /* make conditional compile easier below */
9382 /*else if (find_alias(*argv))
9383 type = "an alias";*/
9384 #if ENABLE_HUSH_FUNCTIONS
9385 else if (find_function(*argv))
9386 type = "a function";
9388 else if (find_builtin(*argv))
9389 type = "a shell builtin";
9390 else if ((path = find_in_path(*argv)) != NULL)
9393 bb_error_msg("type: %s: not found", *argv);
9398 printf("%s is %s\n", *argv, type);
9406 #if ENABLE_HUSH_READ
9407 /* Interruptibility of read builtin in bash
9408 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9410 * Empty trap makes read ignore corresponding signal, for any signal.
9413 * - terminates non-interactive shell;
9414 * - interrupts read in interactive shell;
9415 * if it has non-empty trap:
9416 * - executes trap and returns to command prompt in interactive shell;
9417 * - executes trap and returns to read in non-interactive shell;
9419 * - is ignored (does not interrupt) read in interactive shell;
9420 * - terminates non-interactive shell;
9421 * if it has non-empty trap:
9422 * - executes trap and returns to read;
9424 * - terminates shell (regardless of interactivity);
9425 * if it has non-empty trap:
9426 * - executes trap and returns to read;
9427 * SIGCHLD from children:
9428 * - does not interrupt read regardless of interactivity:
9429 * try: sleep 1 & read x; echo $x
9431 static int FAST_FUNC builtin_read(char **argv)
9438 char *opt_d = NULL; /* optimized out if !BASH */
9442 /* "!": do not abort on errors.
9443 * Option string must start with "sr" to match BUILTIN_READ_xxx
9445 read_flags = getopt32(argv,
9447 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9449 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9452 if (read_flags == (uint32_t)-1)
9453 return EXIT_FAILURE;
9455 ifs = get_local_var_value("IFS"); /* can be NULL */
9458 r = shell_builtin_read(set_local_var_from_halves,
9469 if ((uintptr_t)r == 1 && errno == EINTR) {
9470 unsigned sig = check_and_run_traps();
9475 if ((uintptr_t)r > 1) {
9476 bb_error_msg("%s", r);
9477 r = (char*)(uintptr_t)1;
9480 return (uintptr_t)r;
9484 #if ENABLE_HUSH_UMASK
9485 static int FAST_FUNC builtin_umask(char **argv)
9492 argv = skip_dash_dash(argv);
9494 mode_t old_mask = mask;
9496 /* numeric umasks are taken as-is */
9497 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9498 if (!isdigit(argv[0][0]))
9500 mask = bb_parse_mode(argv[0], mask);
9501 if (!isdigit(argv[0][0]))
9503 if ((unsigned)mask > 0777) {
9506 * bash: umask: 'q': invalid symbolic mode operator
9507 * bash: umask: 999: octal number out of range
9509 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9514 printf("%04o\n", (unsigned) mask);
9515 /* fall through and restore mask which we set to 0 */
9519 return !rc; /* rc != 0 - success */
9523 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9524 static void print_escaped(const char *s)
9529 const char *p = strchrnul(s, '\'');
9530 /* print 'xxxx', possibly just '' */
9531 printf("'%.*s'", (int)(p - s), s);
9536 /* s points to '; print "'''...'''" */
9538 do putchar('\''); while (*++s == '\'');
9544 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9545 static int helper_export_local(char **argv, unsigned flags)
9549 char *name_end = strchrnul(name, '=');
9551 /* So far we do not check that name is valid (TODO?) */
9553 if (*name_end == '\0') {
9554 struct variable *var, **vpp;
9556 vpp = get_ptr_to_local_var(name, name_end - name);
9557 var = vpp ? *vpp : NULL;
9559 if (flags & SETFLAG_UNEXPORT) {
9560 /* export -n NAME (without =VALUE) */
9562 var->flg_export = 0;
9563 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9565 } /* else: export -n NOT_EXISTING_VAR: no-op */
9568 if (flags & SETFLAG_EXPORT) {
9569 /* export NAME (without =VALUE) */
9571 var->flg_export = 1;
9572 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9573 putenv(var->varstr);
9577 if (flags & SETFLAG_MAKE_RO) {
9578 /* readonly NAME (without =VALUE) */
9580 var->flg_read_only = 1;
9584 # if ENABLE_HUSH_LOCAL
9585 /* Is this "local" bltin? */
9586 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9587 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9588 if (var && var->func_nest_level == lvl) {
9589 /* "local x=abc; ...; local x" - ignore second local decl */
9594 /* Exporting non-existing variable.
9595 * bash does not put it in environment,
9596 * but remembers that it is exported,
9597 * and does put it in env when it is set later.
9598 * We just set it to "" and export.
9600 /* Or, it's "local NAME" (without =VALUE).
9601 * bash sets the value to "".
9603 /* Or, it's "readonly NAME" (without =VALUE).
9604 * bash remembers NAME and disallows its creation
9607 name = xasprintf("%s=", name);
9609 /* (Un)exporting/making local NAME=VALUE */
9610 name = xstrdup(name);
9612 if (set_local_var(name, flags))
9613 return EXIT_FAILURE;
9615 return EXIT_SUCCESS;
9619 #if ENABLE_HUSH_EXPORT
9620 static int FAST_FUNC builtin_export(char **argv)
9622 unsigned opt_unexport;
9624 #if ENABLE_HUSH_EXPORT_N
9625 /* "!": do not abort on errors */
9626 opt_unexport = getopt32(argv, "!n");
9627 if (opt_unexport == (uint32_t)-1)
9628 return EXIT_FAILURE;
9635 if (argv[0] == NULL) {
9642 /* ash emits: export VAR='VAL'
9643 * bash: declare -x VAR="VAL"
9644 * we follow ash example */
9645 const char *s = *e++;
9646 const char *p = strchr(s, '=');
9648 if (!p) /* wtf? take next variable */
9651 printf("export %.*s", (int)(p - s) + 1, s);
9652 print_escaped(p + 1);
9656 /*fflush_all(); - done after each builtin anyway */
9658 return EXIT_SUCCESS;
9661 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9665 #if ENABLE_HUSH_LOCAL
9666 static int FAST_FUNC builtin_local(char **argv)
9668 if (G.func_nest_level == 0) {
9669 bb_error_msg("%s: not in a function", argv[0]);
9670 return EXIT_FAILURE; /* bash compat */
9673 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9677 #if ENABLE_HUSH_READONLY
9678 static int FAST_FUNC builtin_readonly(char **argv)
9681 if (*argv == NULL) {
9682 /* bash: readonly [-p]: list all readonly VARs
9683 * (-p has no effect in bash)
9686 for (e = G.top_var; e; e = e->next) {
9687 if (e->flg_read_only) {
9688 //TODO: quote value: readonly VAR='VAL'
9689 printf("readonly %s\n", e->varstr);
9692 return EXIT_SUCCESS;
9694 return helper_export_local(argv, SETFLAG_MAKE_RO);
9698 #if ENABLE_HUSH_UNSET
9699 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9700 static int FAST_FUNC builtin_unset(char **argv)
9705 /* "!": do not abort on errors */
9706 /* "+": stop at 1st non-option */
9707 opts = getopt32(argv, "!+vf");
9708 if (opts == (unsigned)-1)
9709 return EXIT_FAILURE;
9711 bb_error_msg("unset: -v and -f are exclusive");
9712 return EXIT_FAILURE;
9718 if (!(opts & 2)) { /* not -f */
9719 if (unset_local_var(*argv)) {
9720 /* unset <nonexistent_var> doesn't fail.
9721 * Error is when one tries to unset RO var.
9722 * Message was printed by unset_local_var. */
9726 # if ENABLE_HUSH_FUNCTIONS
9738 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9739 * built-in 'set' handler
9741 * set [-abCefhmnuvx] [-o option] [argument...]
9742 * set [+abCefhmnuvx] [+o option] [argument...]
9743 * set -- [argument...]
9746 * Implementations shall support the options in both their hyphen and
9747 * plus-sign forms. These options can also be specified as options to sh.
9749 * Write out all variables and their values: set
9750 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9751 * Turn on the -x and -v options: set -xv
9752 * Unset all positional parameters: set --
9753 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9754 * Set the positional parameters to the expansion of x, even if x expands
9755 * with a leading '-' or '+': set -- $x
9757 * So far, we only support "set -- [argument...]" and some of the short names.
9759 static int FAST_FUNC builtin_set(char **argv)
9762 char **pp, **g_argv;
9763 char *arg = *++argv;
9767 for (e = G.top_var; e; e = e->next)
9769 return EXIT_SUCCESS;
9773 if (strcmp(arg, "--") == 0) {
9777 if (arg[0] != '+' && arg[0] != '-')
9779 for (n = 1; arg[n]; ++n) {
9780 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9782 if (arg[n] == 'o' && argv[1])
9785 } while ((arg = *++argv) != NULL);
9786 /* Now argv[0] is 1st argument */
9789 return EXIT_SUCCESS;
9792 /* NB: G.global_argv[0] ($0) is never freed/changed */
9793 g_argv = G.global_argv;
9794 if (G.global_args_malloced) {
9800 G.global_args_malloced = 1;
9801 pp = xzalloc(sizeof(pp[0]) * 2);
9802 pp[0] = g_argv[0]; /* retain $0 */
9805 /* This realloc's G.global_argv */
9806 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9808 G.global_argc = 1 + string_array_len(pp + 1);
9810 return EXIT_SUCCESS;
9812 /* Nothing known, so abort */
9814 bb_error_msg("set: %s: invalid option", arg);
9815 return EXIT_FAILURE;
9819 static int FAST_FUNC builtin_shift(char **argv)
9822 argv = skip_dash_dash(argv);
9824 n = bb_strtou(argv[0], NULL, 10);
9825 if (errno || n < 0) {
9826 /* shared string with ash.c */
9827 bb_error_msg("Illegal number: %s", argv[0]);
9829 * ash aborts in this case.
9830 * bash prints error message and set $? to 1.
9831 * Interestingly, for "shift 99999" bash does not
9832 * print error message, but does set $? to 1
9833 * (and does no shifting at all).
9837 if (n >= 0 && n < G.global_argc) {
9838 if (G_global_args_malloced) {
9841 free(G.global_argv[m++]);
9844 memmove(&G.global_argv[1], &G.global_argv[n+1],
9845 G.global_argc * sizeof(G.global_argv[0]));
9846 return EXIT_SUCCESS;
9848 return EXIT_FAILURE;
9851 static int FAST_FUNC builtin_source(char **argv)
9853 char *arg_path, *filename;
9856 char *args_need_save;
9857 #if ENABLE_HUSH_FUNCTIONS
9861 argv = skip_dash_dash(argv);
9864 /* bash says: "bash: .: filename argument required" */
9865 return 2; /* bash compat */
9868 if (!strchr(filename, '/')) {
9869 arg_path = find_in_path(filename);
9871 filename = arg_path;
9873 input = remember_FILE(fopen_or_warn(filename, "r"));
9876 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9877 /* POSIX: non-interactive shell should abort here,
9878 * not merely fail. So far no one complained :)
9880 return EXIT_FAILURE;
9883 #if ENABLE_HUSH_FUNCTIONS
9884 sv_flg = G_flag_return_in_progress;
9885 /* "we are inside sourced file, ok to use return" */
9886 G_flag_return_in_progress = -1;
9888 args_need_save = argv[1]; /* used as a boolean variable */
9890 save_and_replace_G_args(&sv, argv);
9892 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9893 G.last_exitcode = 0;
9894 parse_and_run_file(input);
9895 fclose_and_forget(input);
9897 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
9898 restore_G_args(&sv, argv);
9899 #if ENABLE_HUSH_FUNCTIONS
9900 G_flag_return_in_progress = sv_flg;
9903 return G.last_exitcode;
9906 #if ENABLE_HUSH_TRAP
9907 static int FAST_FUNC builtin_trap(char **argv)
9913 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9918 /* No args: print all trapped */
9919 for (i = 0; i < NSIG; ++i) {
9922 print_escaped(G_traps[i]);
9923 /* note: bash adds "SIG", but only if invoked
9924 * as "bash". If called as "sh", or if set -o posix,
9925 * then it prints short signal names.
9926 * We are printing short names: */
9927 printf(" %s\n", get_signame(i));
9930 /*fflush_all(); - done after each builtin anyway */
9931 return EXIT_SUCCESS;
9935 /* If first arg is a number: reset all specified signals */
9936 sig = bb_strtou(*argv, NULL, 10);
9942 sighandler_t handler;
9944 sig = get_signum(*argv++);
9947 /* Mimic bash message exactly */
9948 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
9953 G_traps[sig] = xstrdup(new_cmd);
9955 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9956 get_signame(sig), sig, G_traps[sig]);
9958 /* There is no signal for 0 (EXIT) */
9963 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9965 /* We are removing trap handler */
9966 handler = pick_sighandler(sig);
9967 install_sighandler(sig, handler);
9972 if (!argv[1]) { /* no second arg */
9973 bb_error_msg("trap: invalid arguments");
9974 return EXIT_FAILURE;
9977 /* First arg is "-": reset all specified to default */
9978 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9979 /* Everything else: set arg as signal handler
9980 * (includes "" case, which ignores signal) */
9981 if (argv[0][0] == '-') {
9982 if (argv[0][1] == '\0') { /* "-" */
9983 /* new_cmd remains NULL: "reset these sigs" */
9986 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9989 /* else: "-something", no special meaning */
9994 goto process_sig_list;
9999 static struct pipe *parse_jobspec(const char *str)
10004 if (sscanf(str, "%%%u", &jobnum) != 1) {
10006 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10008 bb_error_msg("bad argument '%s'", str);
10011 /* It is "%%", "%+" or "%" - current job */
10012 jobnum = G.last_jobid;
10014 bb_error_msg("no current job");
10018 for (pi = G.job_list; pi; pi = pi->next) {
10019 if (pi->jobid == jobnum) {
10023 bb_error_msg("%u: no such job", jobnum);
10027 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10030 const char *status_string;
10032 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10033 for (job = G.job_list; job; job = job->next) {
10034 if (job->alive_cmds == job->stopped_cmds)
10035 status_string = "Stopped";
10037 status_string = "Running";
10039 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10042 clean_up_last_dead_job();
10044 return EXIT_SUCCESS;
10047 /* built-in 'fg' and 'bg' handler */
10048 static int FAST_FUNC builtin_fg_bg(char **argv)
10053 if (!G_interactive_fd)
10054 return EXIT_FAILURE;
10056 /* If they gave us no args, assume they want the last backgrounded task */
10058 for (pi = G.job_list; pi; pi = pi->next) {
10059 if (pi->jobid == G.last_jobid) {
10063 bb_error_msg("%s: no current job", argv[0]);
10064 return EXIT_FAILURE;
10067 pi = parse_jobspec(argv[1]);
10069 return EXIT_FAILURE;
10071 /* TODO: bash prints a string representation
10072 * of job being foregrounded (like "sleep 1 | cat") */
10073 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10074 /* Put the job into the foreground. */
10075 tcsetpgrp(G_interactive_fd, pi->pgrp);
10078 /* Restart the processes in the job */
10079 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10080 for (i = 0; i < pi->num_cmds; i++) {
10081 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10083 pi->stopped_cmds = 0;
10085 i = kill(- pi->pgrp, SIGCONT);
10087 if (errno == ESRCH) {
10088 delete_finished_job(pi);
10089 return EXIT_SUCCESS;
10091 bb_perror_msg("kill (SIGCONT)");
10094 if (argv[0][0] == 'f') {
10095 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10096 return checkjobs_and_fg_shell(pi);
10098 return EXIT_SUCCESS;
10102 #if ENABLE_HUSH_KILL
10103 static int FAST_FUNC builtin_kill(char **argv)
10107 # if ENABLE_HUSH_JOB
10108 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10116 if (argv[i][0] != '%')
10119 * "kill %N" - job kill
10120 * Converting to pgrp / pid kill
10122 pi = parse_jobspec(argv[i]);
10124 /* Eat bad jobspec */
10128 argv[j - 1] = argv[j];
10135 * In jobs started under job control, we signal
10136 * entire process group by kill -PGRP_ID.
10137 * This happens, f.e., in interactive shell.
10139 * Otherwise, we signal each child via
10140 * kill PID1 PID2 PID3.
10142 * sh -c 'sleep 1|sleep 1 & kill %1'
10143 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10144 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10146 n = G_interactive_fd ? 1 : pi->num_cmds;
10147 dst = alloca(n * sizeof(int)*4);
10149 if (G_interactive_fd)
10150 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10151 else for (j = 0; j < n; j++) {
10152 struct command *cmd = &pi->cmds[j];
10153 /* Skip exited members of the job */
10157 * kill_main has matching code to expect
10158 * leading space. Needed to not confuse
10159 * negative pids with "kill -SIGNAL_NO" syntax
10161 dst += sprintf(dst, " %u", (int)cmd->pid);
10164 } while (argv[++i]);
10168 if (argv[1] || ret == 0) {
10169 ret = run_applet_main(argv, kill_main);
10171 /* else: ret = 1, "kill %bad_jobspec" case */
10176 #if ENABLE_HUSH_WAIT
10177 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10178 #if !ENABLE_HUSH_JOB
10179 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10181 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10188 if (!sigisemptyset(&G.pending_set))
10191 /* waitpid is not interruptible by SA_RESTARTed
10192 * signals which we use. Thus, this ugly dance:
10195 /* Make sure possible SIGCHLD is stored in kernel's
10196 * pending signal mask before we call waitpid.
10197 * Or else we may race with SIGCHLD, lose it,
10198 * and get stuck in sigsuspend...
10200 sigfillset(&oldset); /* block all signals, remember old set */
10201 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10203 if (!sigisemptyset(&G.pending_set)) {
10204 /* Crap! we raced with some signal! */
10208 /*errno = 0; - checkjobs does this */
10209 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10210 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10211 debug_printf_exec("checkjobs:%d\n", ret);
10212 #if ENABLE_HUSH_JOB
10213 if (waitfor_pipe) {
10214 int rcode = job_exited_or_stopped(waitfor_pipe);
10215 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10218 sigprocmask(SIG_SETMASK, &oldset, NULL);
10223 /* if ECHILD, there are no children (ret is -1 or 0) */
10224 /* if ret == 0, no children changed state */
10225 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10226 if (errno == ECHILD || ret) {
10228 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10230 sigprocmask(SIG_SETMASK, &oldset, NULL);
10233 /* Wait for SIGCHLD or any other signal */
10234 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10235 /* Note: sigsuspend invokes signal handler */
10236 sigsuspend(&oldset);
10238 sigprocmask(SIG_SETMASK, &oldset, NULL);
10240 /* So, did we get a signal? */
10241 sig = check_and_run_traps();
10242 if (sig /*&& sig != SIGCHLD - always true */) {
10243 /* Do this for any (non-ignored) signal, not only for ^C */
10247 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10252 static int FAST_FUNC builtin_wait(char **argv)
10257 argv = skip_dash_dash(argv);
10258 if (argv[0] == NULL) {
10259 /* Don't care about wait results */
10260 /* Note 1: must wait until there are no more children */
10261 /* Note 2: must be interruptible */
10263 * $ sleep 3 & sleep 6 & wait
10264 * [1] 30934 sleep 3
10265 * [2] 30935 sleep 6
10268 * $ sleep 3 & sleep 6 & wait
10269 * [1] 30936 sleep 3
10270 * [2] 30937 sleep 6
10272 * ^C <-- after ~4 sec from keyboard
10275 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10279 pid_t pid = bb_strtou(*argv, NULL, 10);
10280 if (errno || pid <= 0) {
10281 #if ENABLE_HUSH_JOB
10282 if (argv[0][0] == '%') {
10283 struct pipe *wait_pipe;
10284 ret = 127; /* bash compat for bad jobspecs */
10285 wait_pipe = parse_jobspec(*argv);
10287 ret = job_exited_or_stopped(wait_pipe);
10289 ret = wait_for_child_or_signal(wait_pipe, 0);
10291 /* waiting on "last dead job" removes it */
10292 clean_up_last_dead_job();
10295 /* else: parse_jobspec() already emitted error msg */
10299 /* mimic bash message */
10300 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10301 ret = EXIT_FAILURE;
10302 continue; /* bash checks all argv[] */
10305 /* Do we have such child? */
10306 ret = waitpid(pid, &status, WNOHANG);
10310 if (errno == ECHILD) {
10311 if (pid == G.last_bg_pid) {
10312 /* "wait $!" but last bg task has already exited. Try:
10313 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10314 * In bash it prints exitcode 0, then 3.
10315 * In dash, it is 127.
10317 ret = G.last_bg_pid_exitcode;
10319 /* Example: "wait 1". mimic bash message */
10320 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10324 bb_perror_msg("wait %s", *argv);
10326 continue; /* bash checks all argv[] */
10329 /* Yes, and it still runs */
10330 ret = wait_for_child_or_signal(NULL, pid);
10332 /* Yes, and it just exited */
10333 process_wait_result(NULL, pid, status);
10334 ret = WEXITSTATUS(status);
10335 if (WIFSIGNALED(status))
10336 ret = 128 + WTERMSIG(status);
10344 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10345 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10348 def = bb_strtou(argv[1], NULL, 10);
10349 if (errno || def < def_min || argv[2]) {
10350 bb_error_msg("%s: bad arguments", argv[0]);
10358 #if ENABLE_HUSH_LOOPS
10359 static int FAST_FUNC builtin_break(char **argv)
10362 if (G.depth_of_loop == 0) {
10363 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10364 /* if we came from builtin_continue(), need to undo "= 1" */
10365 G.flag_break_continue = 0;
10366 return EXIT_SUCCESS; /* bash compat */
10368 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10370 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10371 if (depth == UINT_MAX)
10372 G.flag_break_continue = BC_BREAK;
10373 if (G.depth_of_loop < depth)
10374 G.depth_break_continue = G.depth_of_loop;
10376 return EXIT_SUCCESS;
10379 static int FAST_FUNC builtin_continue(char **argv)
10381 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10382 return builtin_break(argv);
10386 #if ENABLE_HUSH_FUNCTIONS
10387 static int FAST_FUNC builtin_return(char **argv)
10391 if (G_flag_return_in_progress != -1) {
10392 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10393 return EXIT_FAILURE; /* bash compat */
10396 G_flag_return_in_progress = 1;
10399 * out of range: wraps around at 256, does not error out
10400 * non-numeric param:
10401 * f() { false; return qwe; }; f; echo $?
10402 * bash: return: qwe: numeric argument required <== we do this
10403 * 255 <== we also do this
10405 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10410 #if ENABLE_HUSH_MEMLEAK
10411 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10416 # ifdef M_TRIM_THRESHOLD
10417 /* Optional. Reduces probability of false positives */
10420 /* Crude attempt to find where "free memory" starts,
10421 * sans fragmentation. */
10423 l = (unsigned long)p;
10426 if (l < (unsigned long)p) l = (unsigned long)p;
10432 struct mallinfo mi = mallinfo();
10433 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10434 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10438 if (!G.memleak_value)
10439 G.memleak_value = l;
10441 l -= G.memleak_value;
10448 /* Exitcode is "how many kilobytes we leaked since 1st call" */