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:
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 * fc -l[nr] [BEG] [END]: list range of commands in history
62 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
63 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
66 * redirection of stdout+stderr: &> and >&
67 * reserved words: function select
68 * advanced test: [[ ]]
69 * process substitution: <(list) and >(list)
72 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
73 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
74 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
76 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
77 * This is exactly equivalent to let "EXPR".
78 * $[EXPR]: synonym for $((EXPR))
79 * indirect expansion: ${!VAR}
80 * substring op on @: ${@:n:m}
83 * Some builtins mandated by standards:
84 * newgrp [GRP]: not a builtin in bash but a suid binary
85 * which spawns a new shell with new group ID
86 * In bash, export builtin is special, its arguments are assignments
87 * and therefore expansion of them should be "one-word" expansion:
88 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
90 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
91 * ls: cannot access i=a: No such file or directory
92 * ls: cannot access b: No such file or directory
93 * Note1: same applies to local builtin.
94 * Note2: bash 3.2.33(1) does this only if export word itself
96 * $ export i=`echo 'aaa bbb'`; echo "$i"
98 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
102 //config: bool "hush (64 kb)"
105 //config: hush is a small shell. It handles the normal flow control
106 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
107 //config: case/esac. Redirections, here documents, $((arithmetic))
108 //config: and functions are supported.
110 //config: It will compile and work on no-mmu systems.
112 //config: It does not handle select, aliases, tilde expansion,
113 //config: &>file and >&file redirection of stdout+stderr.
115 //config:config HUSH_BASH_COMPAT
116 //config: bool "bash-compatible extensions"
118 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
120 //config:config HUSH_BRACE_EXPANSION
121 //config: bool "Brace expansion"
123 //config: depends on HUSH_BASH_COMPAT
125 //config: Enable {abc,def} extension.
127 //config:config HUSH_INTERACTIVE
128 //config: bool "Interactive mode"
130 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
132 //config: Enable interactive mode (prompt and command editing).
133 //config: Without this, hush simply reads and executes commands
134 //config: from stdin just like a shell script from a file.
135 //config: No prompt, no PS1/PS2 magic shell variables.
137 //config:config HUSH_SAVEHISTORY
138 //config: bool "Save command history to .hush_history"
140 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
142 //config:config HUSH_JOB
143 //config: bool "Job control"
145 //config: depends on HUSH_INTERACTIVE
147 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
148 //config: command (not entire shell), fg/bg builtins work. Without this option,
149 //config: "cmd &" still works by simply spawning a process and immediately
150 //config: prompting for next command (or executing next command in a script),
151 //config: but no separate process group is formed.
153 //config:config HUSH_TICK
154 //config: bool "Support process substitution"
156 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
158 //config: Enable `command` and $(command).
160 //config:config HUSH_IF
161 //config: bool "Support if/then/elif/else/fi"
163 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
165 //config:config HUSH_LOOPS
166 //config: bool "Support for, while and until loops"
168 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
170 //config:config HUSH_CASE
171 //config: bool "Support case ... esac statement"
173 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
175 //config: Enable case ... esac statement. +400 bytes.
177 //config:config HUSH_FUNCTIONS
178 //config: bool "Support funcname() { commands; } syntax"
180 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
182 //config: Enable support for shell functions. +800 bytes.
184 //config:config HUSH_LOCAL
185 //config: bool "local builtin"
187 //config: depends on HUSH_FUNCTIONS
189 //config: Enable support for local variables in functions.
191 //config:config HUSH_RANDOM_SUPPORT
192 //config: bool "Pseudorandom generator and $RANDOM variable"
194 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
196 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
197 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
199 //config:config HUSH_MODE_X
200 //config: bool "Support 'hush -x' option and 'set -x' command"
202 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
204 //config: This instructs hush to print commands before execution.
205 //config: Adds ~300 bytes.
207 //config:config HUSH_ECHO
208 //config: bool "echo builtin"
210 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
212 //config:config HUSH_PRINTF
213 //config: bool "printf builtin"
215 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
217 //config:config HUSH_TEST
218 //config: bool "test builtin"
220 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
222 //config:config HUSH_HELP
223 //config: bool "help builtin"
225 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227 //config:config HUSH_EXPORT
228 //config: bool "export builtin"
230 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
232 //config:config HUSH_EXPORT_N
233 //config: bool "Support 'export -n' option"
235 //config: depends on HUSH_EXPORT
237 //config: export -n unexports variables. It is a bash extension.
239 //config:config HUSH_READONLY
240 //config: bool "readonly builtin"
242 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
244 //config: Enable support for read-only variables.
246 //config:config HUSH_KILL
247 //config: bool "kill builtin (supports kill %jobspec)"
249 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
251 //config:config HUSH_WAIT
252 //config: bool "wait builtin"
254 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
256 //config:config HUSH_TRAP
257 //config: bool "trap builtin"
259 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
261 //config:config HUSH_TYPE
262 //config: bool "type builtin"
264 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266 //config:config HUSH_TIMES
267 //config: bool "times builtin"
269 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
271 //config:config HUSH_READ
272 //config: bool "read builtin"
274 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
276 //config:config HUSH_SET
277 //config: bool "set builtin"
279 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281 //config:config HUSH_UNSET
282 //config: bool "unset builtin"
284 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
286 //config:config HUSH_ULIMIT
287 //config: bool "ulimit builtin"
289 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
291 //config:config HUSH_UMASK
292 //config: bool "umask builtin"
294 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
296 //config:config HUSH_GETOPTS
297 //config: bool "getopts builtin"
299 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
301 //config:config HUSH_MEMLEAK
302 //config: bool "memleak builtin (debugging)"
304 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
306 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
307 // APPLET_ODDNAME:name main location suid_type help
308 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
309 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
311 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
312 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
313 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
314 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
316 /* -i (interactive) and -s (read stdin) are also accepted,
317 * but currently do nothing, therefore aren't shown in help.
318 * NOMMU-specific options are not meant to be used by users,
319 * therefore we don't show them either.
321 //usage:#define hush_trivial_usage
322 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
323 //usage:#define hush_full_usage "\n\n"
324 //usage: "Unix shell interpreter"
326 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
327 || defined(__APPLE__) \
329 # include <malloc.h> /* for malloc_trim */
332 /* #include <dmalloc.h> */
334 # include <fnmatch.h>
336 #include <sys/times.h>
337 #include <sys/utsname.h> /* for setting $HOSTNAME */
339 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
341 #include "shell_common.h"
344 #if ENABLE_HUSH_RANDOM_SUPPORT
347 # define CLEAR_RANDOM_T(rnd) ((void)0)
349 #ifndef F_DUPFD_CLOEXEC
350 # define F_DUPFD_CLOEXEC F_DUPFD
353 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
357 /* So far, all bash compat is controlled by one config option */
358 /* Separate defines document which part of code implements what */
359 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
360 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
361 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
362 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
363 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
364 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
368 #define LEAK_HUNTING 0
369 #define BUILD_AS_NOMMU 0
370 /* Enable/disable sanity checks. Ok to enable in production,
371 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
372 * Keeping 1 for now even in released versions.
375 /* Slightly bigger (+200 bytes), but faster hush.
376 * So far it only enables a trick with counting SIGCHLDs and forks,
377 * which allows us to do fewer waitpid's.
378 * (we can detect a case where neither forks were done nor SIGCHLDs happened
379 * and therefore waitpid will return the same result as last time)
381 #define ENABLE_HUSH_FAST 0
382 /* TODO: implement simplified code for users which do not need ${var%...} ops
383 * So far ${var%...} ops are always enabled:
385 #define ENABLE_HUSH_DOLLAR_OPS 1
390 # undef USE_FOR_NOMMU
393 # define USE_FOR_NOMMU(...) __VA_ARGS__
394 # define USE_FOR_MMU(...)
397 #include "NUM_APPLETS.h"
399 /* STANDALONE does not make sense, and won't compile */
400 # undef CONFIG_FEATURE_SH_STANDALONE
401 # undef ENABLE_FEATURE_SH_STANDALONE
402 # undef IF_FEATURE_SH_STANDALONE
403 # undef IF_NOT_FEATURE_SH_STANDALONE
404 # define ENABLE_FEATURE_SH_STANDALONE 0
405 # define IF_FEATURE_SH_STANDALONE(...)
406 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
409 #if !ENABLE_HUSH_INTERACTIVE
410 # undef ENABLE_FEATURE_EDITING
411 # define ENABLE_FEATURE_EDITING 0
412 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
413 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
414 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
415 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
418 /* Do we support ANY keywords? */
419 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
420 # define HAS_KEYWORDS 1
421 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
422 # define IF_HAS_NO_KEYWORDS(...)
424 # define HAS_KEYWORDS 0
425 # define IF_HAS_KEYWORDS(...)
426 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
429 /* If you comment out one of these below, it will be #defined later
430 * to perform debug printfs to stderr: */
431 #define debug_printf(...) do {} while (0)
432 /* Finer-grained debug switches */
433 #define debug_printf_parse(...) do {} while (0)
434 #define debug_print_tree(a, b) do {} while (0)
435 #define debug_printf_exec(...) do {} while (0)
436 #define debug_printf_env(...) do {} while (0)
437 #define debug_printf_jobs(...) do {} while (0)
438 #define debug_printf_expand(...) do {} while (0)
439 #define debug_printf_varexp(...) do {} while (0)
440 #define debug_printf_glob(...) do {} while (0)
441 #define debug_printf_redir(...) do {} while (0)
442 #define debug_printf_list(...) do {} while (0)
443 #define debug_printf_subst(...) do {} while (0)
444 #define debug_printf_clean(...) do {} while (0)
446 #define ERR_PTR ((void*)(long)1)
448 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
450 #define _SPECIAL_VARS_STR "_*@$!?#"
451 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
452 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
453 #if BASH_PATTERN_SUBST
454 /* Support / and // replace ops */
455 /* Note that // is stored as \ in "encoded" string representation */
456 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
457 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
458 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
460 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
461 # define VAR_SUBST_OPS "%#:-=+?"
462 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
465 #define SPECIAL_VAR_SYMBOL 3
469 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
471 /* This supports saving pointers malloced in vfork child,
472 * to be freed in the parent.
475 typedef struct nommu_save_t {
477 struct variable *old_vars;
479 char **argv_from_re_execing;
492 #if ENABLE_HUSH_LOOPS
499 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
504 /* three pseudo-keywords support contrived "case" syntax: */
505 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
506 RES_MATCH , /* "word)" */
507 RES_CASE_BODY, /* "this command is inside CASE" */
514 typedef struct o_string {
516 int length; /* position where data is appended */
519 /* At least some part of the string was inside '' or "",
520 * possibly empty one: word"", wo''rd etc. */
521 smallint has_quoted_part;
522 smallint has_empty_slot;
523 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
526 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
528 /* Protect newly added chars against globbing
529 * by prepending \ to *, ?, [, \ */
530 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
533 MAYBE_ASSIGNMENT = 0,
534 DEFINITELY_ASSIGNMENT = 1,
536 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
539 /* Used for initialization: o_string foo = NULL_O_STRING; */
540 #define NULL_O_STRING { NULL }
542 #ifndef debug_printf_parse
543 static const char *const assignment_flag[] = {
545 "DEFINITELY_ASSIGNMENT",
551 typedef struct in_str {
553 #if ENABLE_HUSH_INTERACTIVE
554 smallint promptmode; /* 0: PS1, 1: PS2 */
561 /* The descrip member of this structure is only used to make
562 * debugging output pretty */
563 static const struct {
565 signed char default_fd;
568 { O_RDONLY, 0, "<" },
569 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
570 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
571 { O_CREAT|O_RDWR, 1, "<>" },
572 { O_RDONLY, 0, "<<" },
573 /* Should not be needed. Bogus default_fd helps in debugging */
574 /* { O_RDONLY, 77, "<<" }, */
577 struct redir_struct {
578 struct redir_struct *next;
579 char *rd_filename; /* filename */
580 int rd_fd; /* fd to redirect */
581 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
583 smallint rd_type; /* (enum redir_type) */
584 /* note: for heredocs, rd_filename contains heredoc delimiter,
585 * and subsequently heredoc itself; and rd_dup is a bitmask:
586 * bit 0: do we need to trim leading tabs?
587 * bit 1: is heredoc quoted (<<'delim' syntax) ?
590 typedef enum redir_type {
592 REDIRECT_OVERWRITE = 1,
595 REDIRECT_HEREDOC = 4,
596 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
599 REDIRFD_SYNTAX_ERR = -2,
600 REDIRFD_TO_FILE = -1,
601 /* otherwise, rd_fd is redirected to rd_dup */
603 HEREDOC_SKIPTABS = 1,
609 pid_t pid; /* 0 if exited */
610 int assignment_cnt; /* how many argv[i] are assignments? */
611 smallint cmd_type; /* CMD_xxx */
613 #define CMD_SUBSHELL 1
615 /* used for "[[ EXPR ]]" */
616 # define CMD_SINGLEWORD_NOGLOB 2
618 #if ENABLE_HUSH_FUNCTIONS
619 # define CMD_FUNCDEF 3
622 smalluint cmd_exitcode;
623 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
626 char *group_as_string;
628 #if ENABLE_HUSH_FUNCTIONS
629 struct function *child_func;
630 /* This field is used to prevent a bug here:
631 * while...do f1() {a;}; f1; f1() {b;}; f1; done
632 * When we execute "f1() {a;}" cmd, we create new function and clear
633 * cmd->group, cmd->group_as_string, cmd->argv[0].
634 * When we execute "f1() {b;}", we notice that f1 exists,
635 * and that its "parent cmd" struct is still "alive",
636 * we put those fields back into cmd->xxx
637 * (struct function has ->parent_cmd ptr to facilitate that).
638 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
639 * Without this trick, loop would execute a;b;b;b;...
640 * instead of correct sequence a;b;a;b;...
641 * When command is freed, it severs the link
642 * (sets ->child_func->parent_cmd to NULL).
645 char **argv; /* command name and arguments */
646 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
647 * and on execution these are substituted with their values.
648 * Substitution can make _several_ words out of one argv[n]!
649 * Example: argv[0]=='.^C*^C.' here: echo .$*.
650 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
652 struct redir_struct *redirects; /* I/O redirections */
654 /* Is there anything in this command at all? */
655 #define IS_NULL_CMD(cmd) \
656 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
660 int num_cmds; /* total number of commands in pipe */
661 int alive_cmds; /* number of commands running (not exited) */
662 int stopped_cmds; /* number of commands alive, but stopped */
664 unsigned jobid; /* job number */
665 pid_t pgrp; /* process group ID for the job */
666 char *cmdtext; /* name of job */
668 struct command *cmds; /* array of commands in pipe */
669 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
670 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
671 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
673 typedef enum pipe_style {
679 /* Is there anything in this pipe at all? */
680 #define IS_NULL_PIPE(pi) \
681 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
683 /* This holds pointers to the various results of parsing */
684 struct parse_context {
685 /* linked list of pipes */
686 struct pipe *list_head;
687 /* last pipe (being constructed right now) */
689 /* last command in pipe (being constructed right now) */
690 struct command *command;
691 /* last redirect in command->redirects list */
692 struct redir_struct *pending_redirect;
698 smallint ctx_inverted; /* "! cmd | cmd" */
700 smallint ctx_dsemicolon; /* ";;" seen */
702 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
704 /* group we are enclosed in:
705 * example: "if pipe1; pipe2; then pipe3; fi"
706 * when we see "if" or "then", we malloc and copy current context,
707 * and make ->stack point to it. then we parse pipeN.
708 * when closing "then" / fi" / whatever is found,
709 * we move list_head into ->stack->command->group,
710 * copy ->stack into current context, and delete ->stack.
711 * (parsing of { list } and ( list ) doesn't use this method)
713 struct parse_context *stack;
717 /* On program start, environ points to initial environment.
718 * putenv adds new pointers into it, unsetenv removes them.
719 * Neither of these (de)allocates the strings.
720 * setenv allocates new strings in malloc space and does putenv,
721 * and thus setenv is unusable (leaky) for shell's purposes */
722 #define setenv(...) setenv_is_leaky_dont_use()
724 struct variable *next;
725 char *varstr; /* points to "name=" portion */
726 #if ENABLE_HUSH_LOCAL
727 unsigned func_nest_level;
729 int max_len; /* if > 0, name is part of initial env; else name is malloced */
730 smallint flg_export; /* putenv should be done on this var */
731 smallint flg_read_only;
739 #if ENABLE_HUSH_FUNCTIONS
741 struct function *next;
743 struct command *parent_cmd;
746 char *body_as_string;
752 /* set -/+o OPT support. (TODO: make it optional)
753 * bash supports the following opts:
764 * interactive-comments on
782 static const char o_opt_strings[] ALIGN1 =
786 #if ENABLE_HUSH_MODE_X
794 #if ENABLE_HUSH_MODE_X
802 struct FILE_list *next;
808 /* "Globals" within this file */
809 /* Sorted roughly by size (smaller offsets == smaller code) */
811 /* interactive_fd != 0 means we are an interactive shell.
812 * If we are, then saved_tty_pgrp can also be != 0, meaning
813 * that controlling tty is available. With saved_tty_pgrp == 0,
814 * job control still works, but terminal signals
815 * (^C, ^Z, ^Y, ^\) won't work at all, and background
816 * process groups can only be created with "cmd &".
817 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
818 * to give tty to the foreground process group,
819 * and will take it back when the group is stopped (^Z)
822 #if ENABLE_HUSH_INTERACTIVE
823 /* 'interactive_fd' is a fd# open to ctty, if we have one
824 * _AND_ if we decided to act interactively */
828 # define G_interactive_fd (G.interactive_fd)
830 # define G_interactive_fd 0
832 #if ENABLE_FEATURE_EDITING
833 line_input_t *line_input_state;
838 #if ENABLE_HUSH_RANDOM_SUPPORT
844 pid_t saved_tty_pgrp;
845 struct pipe *job_list;
846 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
848 # define G_saved_tty_pgrp 0
850 /* How deeply are we in context where "set -e" is ignored */
852 /* "set -e" rules (do we follow them correctly?):
853 * Exit if pipe, list, or compound command exits with a non-zero status.
854 * Shell does not exit if failed command is part of condition in
855 * if/while, part of && or || list except the last command, any command
856 * in a pipe but the last, or if the command's return value is being
857 * inverted with !. If a compound command other than a subshell returns a
858 * non-zero status because a command failed while -e was being ignored, the
859 * shell does not exit. A trap on ERR, if set, is executed before the shell
860 * exits [ERR is a bashism].
862 * If a compound command or function executes in a context where -e is
863 * ignored, none of the commands executed within are affected by the -e
864 * setting. If a compound command or function sets -e while executing in a
865 * context where -e is ignored, that setting does not have any effect until
866 * the compound command or the command containing the function call completes.
869 char o_opt[NUM_OPT_O];
870 #if ENABLE_HUSH_MODE_X
871 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
875 smallint flag_SIGINT;
876 #if ENABLE_HUSH_LOOPS
877 smallint flag_break_continue;
879 #if ENABLE_HUSH_FUNCTIONS
880 /* 0: outside of a function (or sourced file)
881 * -1: inside of a function, ok to use return builtin
882 * 1: return is invoked, skip all till end of func
884 smallint flag_return_in_progress;
885 # define G_flag_return_in_progress (G.flag_return_in_progress)
887 # define G_flag_return_in_progress 0
889 smallint exiting; /* used to prevent EXIT trap recursion */
890 /* These four support $?, $#, and $1 */
891 smalluint last_exitcode;
892 smalluint last_bg_pid_exitcode;
894 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
895 smalluint global_args_malloced;
896 # define G_global_args_malloced (G.global_args_malloced)
898 # define G_global_args_malloced 0
900 /* how many non-NULL argv's we have. NB: $# + 1 */
904 char *argv0_for_re_execing;
906 #if ENABLE_HUSH_LOOPS
907 unsigned depth_break_continue;
908 unsigned depth_of_loop;
912 struct variable *top_var;
913 char **expanded_assignments;
914 #if ENABLE_HUSH_FUNCTIONS
915 struct function *top_func;
916 # if ENABLE_HUSH_LOCAL
917 struct variable **shadowed_vars_pp;
918 unsigned func_nest_level;
921 /* Signal and trap handling */
923 unsigned count_SIGCHLD;
924 unsigned handled_SIGCHLD;
925 smallint we_have_children;
927 struct FILE_list *FILE_list;
928 /* Which signals have non-DFL handler (even with no traps set)?
929 * Set at the start to:
930 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
931 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
932 * The rest is cleared right before execv syscalls.
933 * Other than these two times, never modified.
935 unsigned special_sig_mask;
937 unsigned fatal_sig_mask;
938 # define G_fatal_sig_mask (G.fatal_sig_mask)
940 # define G_fatal_sig_mask 0
943 char **traps; /* char *traps[NSIG] */
944 # define G_traps G.traps
946 # define G_traps ((char**)NULL)
948 sigset_t pending_set;
949 #if ENABLE_HUSH_MEMLEAK
950 unsigned long memleak_value;
956 #if ENABLE_FEATURE_EDITING
957 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
960 #define G (*ptr_to_globals)
961 /* Not #defining name to G.name - this quickly gets unwieldy
962 * (too many defines). Also, I actually prefer to see when a variable
963 * is global, thus "G." prefix is a useful hint */
964 #define INIT_G() do { \
965 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
966 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
967 sigfillset(&G.sa.sa_mask); \
968 G.sa.sa_flags = SA_RESTART; \
972 /* Function prototypes for builtins */
973 static int builtin_cd(char **argv) FAST_FUNC;
975 static int builtin_echo(char **argv) FAST_FUNC;
977 static int builtin_eval(char **argv) FAST_FUNC;
978 static int builtin_exec(char **argv) FAST_FUNC;
979 static int builtin_exit(char **argv) FAST_FUNC;
980 #if ENABLE_HUSH_EXPORT
981 static int builtin_export(char **argv) FAST_FUNC;
983 #if ENABLE_HUSH_READONLY
984 static int builtin_readonly(char **argv) FAST_FUNC;
987 static int builtin_fg_bg(char **argv) FAST_FUNC;
988 static int builtin_jobs(char **argv) FAST_FUNC;
990 #if ENABLE_HUSH_GETOPTS
991 static int builtin_getopts(char **argv) FAST_FUNC;
994 static int builtin_help(char **argv) FAST_FUNC;
996 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
997 static int builtin_history(char **argv) FAST_FUNC;
999 #if ENABLE_HUSH_LOCAL
1000 static int builtin_local(char **argv) FAST_FUNC;
1002 #if ENABLE_HUSH_MEMLEAK
1003 static int builtin_memleak(char **argv) FAST_FUNC;
1005 #if ENABLE_HUSH_PRINTF
1006 static int builtin_printf(char **argv) FAST_FUNC;
1008 static int builtin_pwd(char **argv) FAST_FUNC;
1009 #if ENABLE_HUSH_READ
1010 static int builtin_read(char **argv) FAST_FUNC;
1013 static int builtin_set(char **argv) FAST_FUNC;
1015 static int builtin_shift(char **argv) FAST_FUNC;
1016 static int builtin_source(char **argv) FAST_FUNC;
1017 #if ENABLE_HUSH_TEST || BASH_TEST2
1018 static int builtin_test(char **argv) FAST_FUNC;
1020 #if ENABLE_HUSH_TRAP
1021 static int builtin_trap(char **argv) FAST_FUNC;
1023 #if ENABLE_HUSH_TYPE
1024 static int builtin_type(char **argv) FAST_FUNC;
1026 #if ENABLE_HUSH_TIMES
1027 static int builtin_times(char **argv) FAST_FUNC;
1029 static int builtin_true(char **argv) FAST_FUNC;
1030 #if ENABLE_HUSH_UMASK
1031 static int builtin_umask(char **argv) FAST_FUNC;
1033 #if ENABLE_HUSH_UNSET
1034 static int builtin_unset(char **argv) FAST_FUNC;
1036 #if ENABLE_HUSH_KILL
1037 static int builtin_kill(char **argv) FAST_FUNC;
1039 #if ENABLE_HUSH_WAIT
1040 static int builtin_wait(char **argv) FAST_FUNC;
1042 #if ENABLE_HUSH_LOOPS
1043 static int builtin_break(char **argv) FAST_FUNC;
1044 static int builtin_continue(char **argv) FAST_FUNC;
1046 #if ENABLE_HUSH_FUNCTIONS
1047 static int builtin_return(char **argv) FAST_FUNC;
1050 /* Table of built-in functions. They can be forked or not, depending on
1051 * context: within pipes, they fork. As simple commands, they do not.
1052 * When used in non-forking context, they can change global variables
1053 * in the parent shell process. If forked, of course they cannot.
1054 * For example, 'unset foo | whatever' will parse and run, but foo will
1055 * still be set at the end. */
1056 struct built_in_command {
1058 int (*b_function)(char **argv) FAST_FUNC;
1059 #if ENABLE_HUSH_HELP
1060 const char *b_descr;
1061 # define BLTIN(cmd, func, help) { cmd, func, help }
1063 # define BLTIN(cmd, func, help) { cmd, func }
1067 static const struct built_in_command bltins1[] = {
1068 BLTIN("." , builtin_source , "Run commands in file"),
1069 BLTIN(":" , builtin_true , NULL),
1071 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1073 #if ENABLE_HUSH_LOOPS
1074 BLTIN("break" , builtin_break , "Exit loop"),
1076 BLTIN("cd" , builtin_cd , "Change directory"),
1077 #if ENABLE_HUSH_LOOPS
1078 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1080 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1081 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1082 BLTIN("exit" , builtin_exit , NULL),
1083 #if ENABLE_HUSH_EXPORT
1084 BLTIN("export" , builtin_export , "Set environment variables"),
1087 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1089 #if ENABLE_HUSH_GETOPTS
1090 BLTIN("getopts" , builtin_getopts , NULL),
1092 #if ENABLE_HUSH_HELP
1093 BLTIN("help" , builtin_help , NULL),
1095 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1096 BLTIN("history" , builtin_history , "Show history"),
1099 BLTIN("jobs" , builtin_jobs , "List jobs"),
1101 #if ENABLE_HUSH_KILL
1102 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1104 #if ENABLE_HUSH_LOCAL
1105 BLTIN("local" , builtin_local , "Set local variables"),
1107 #if ENABLE_HUSH_MEMLEAK
1108 BLTIN("memleak" , builtin_memleak , NULL),
1110 #if ENABLE_HUSH_READ
1111 BLTIN("read" , builtin_read , "Input into variable"),
1113 #if ENABLE_HUSH_READONLY
1114 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1116 #if ENABLE_HUSH_FUNCTIONS
1117 BLTIN("return" , builtin_return , "Return from function"),
1120 BLTIN("set" , builtin_set , "Set positional parameters"),
1122 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1124 BLTIN("source" , builtin_source , NULL),
1126 #if ENABLE_HUSH_TIMES
1127 BLTIN("times" , builtin_times , NULL),
1129 #if ENABLE_HUSH_TRAP
1130 BLTIN("trap" , builtin_trap , "Trap signals"),
1132 BLTIN("true" , builtin_true , NULL),
1133 #if ENABLE_HUSH_TYPE
1134 BLTIN("type" , builtin_type , "Show command type"),
1136 #if ENABLE_HUSH_ULIMIT
1137 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1139 #if ENABLE_HUSH_UMASK
1140 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1142 #if ENABLE_HUSH_UNSET
1143 BLTIN("unset" , builtin_unset , "Unset variables"),
1145 #if ENABLE_HUSH_WAIT
1146 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1149 /* These builtins won't be used if we are on NOMMU and need to re-exec
1150 * (it's cheaper to run an external program in this case):
1152 static const struct built_in_command bltins2[] = {
1153 #if ENABLE_HUSH_TEST
1154 BLTIN("[" , builtin_test , NULL),
1157 BLTIN("[[" , builtin_test , NULL),
1159 #if ENABLE_HUSH_ECHO
1160 BLTIN("echo" , builtin_echo , NULL),
1162 #if ENABLE_HUSH_PRINTF
1163 BLTIN("printf" , builtin_printf , NULL),
1165 BLTIN("pwd" , builtin_pwd , NULL),
1166 #if ENABLE_HUSH_TEST
1167 BLTIN("test" , builtin_test , NULL),
1175 /* prevent disasters with G.debug_indent < 0 */
1176 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1177 # define debug_enter() (G.debug_indent++)
1178 # define debug_leave() (G.debug_indent--)
1180 # define indent() ((void)0)
1181 # define debug_enter() ((void)0)
1182 # define debug_leave() ((void)0)
1185 #ifndef debug_printf
1186 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1189 #ifndef debug_printf_parse
1190 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1193 #ifndef debug_printf_exec
1194 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1197 #ifndef debug_printf_env
1198 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1201 #ifndef debug_printf_jobs
1202 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1203 # define DEBUG_JOBS 1
1205 # define DEBUG_JOBS 0
1208 #ifndef debug_printf_expand
1209 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1210 # define DEBUG_EXPAND 1
1212 # define DEBUG_EXPAND 0
1215 #ifndef debug_printf_varexp
1216 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1219 #ifndef debug_printf_glob
1220 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1221 # define DEBUG_GLOB 1
1223 # define DEBUG_GLOB 0
1226 #ifndef debug_printf_redir
1227 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1230 #ifndef debug_printf_list
1231 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1234 #ifndef debug_printf_subst
1235 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1238 #ifndef debug_printf_clean
1239 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1240 # define DEBUG_CLEAN 1
1242 # define DEBUG_CLEAN 0
1246 static void debug_print_strings(const char *prefix, char **vv)
1249 fdprintf(2, "%s:\n", prefix);
1251 fdprintf(2, " '%s'\n", *vv++);
1254 # define debug_print_strings(prefix, vv) ((void)0)
1258 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1261 static void *xxmalloc(int lineno, size_t size)
1263 void *ptr = xmalloc((size + 0xff) & ~0xff);
1264 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1267 static void *xxrealloc(int lineno, void *ptr, size_t size)
1269 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1270 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1273 static char *xxstrdup(int lineno, const char *str)
1275 char *ptr = xstrdup(str);
1276 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1279 static void xxfree(void *ptr)
1281 fdprintf(2, "free %p\n", ptr);
1284 # define xmalloc(s) xxmalloc(__LINE__, s)
1285 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1286 # define xstrdup(s) xxstrdup(__LINE__, s)
1287 # define free(p) xxfree(p)
1291 /* Syntax and runtime errors. They always abort scripts.
1292 * In interactive use they usually discard unparsed and/or unexecuted commands
1293 * and return to the prompt.
1294 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1297 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1298 # define syntax_error(lineno, msg) syntax_error(msg)
1299 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1300 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1301 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1302 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1305 static void die_if_script(void)
1307 if (!G_interactive_fd) {
1308 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1309 xfunc_error_retval = G.last_exitcode;
1314 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1319 bb_error_msg("hush.c:%u", lineno);
1322 bb_verror_msg(fmt, p, NULL);
1327 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1330 bb_error_msg("syntax error: %s", msg);
1332 bb_error_msg("syntax error");
1336 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1338 bb_error_msg("syntax error at '%s'", msg);
1342 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1344 bb_error_msg("syntax error: unterminated %s", s);
1345 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1349 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1351 char msg[2] = { ch, '\0' };
1352 syntax_error_unterm_str(lineno, msg);
1355 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1361 bb_error_msg("hush.c:%u", lineno);
1363 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1368 # undef msg_and_die_if_script
1369 # undef syntax_error
1370 # undef syntax_error_at
1371 # undef syntax_error_unterm_ch
1372 # undef syntax_error_unterm_str
1373 # undef syntax_error_unexpected_ch
1375 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1376 # define syntax_error(msg) syntax_error(__LINE__, msg)
1377 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1378 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1379 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1380 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1384 #if ENABLE_HUSH_INTERACTIVE
1385 static void cmdedit_update_prompt(void);
1387 # define cmdedit_update_prompt() ((void)0)
1391 /* Utility functions
1393 /* Replace each \x with x in place, return ptr past NUL. */
1394 static char *unbackslash(char *src)
1396 char *dst = src = strchrnul(src, '\\');
1400 if ((*dst++ = *src++) == '\0')
1406 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1427 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1428 v[count1 + count2] = NULL;
1431 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1435 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1437 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1438 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1441 #define add_strings_to_strings(strings, add, need_to_dup) \
1442 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1445 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1446 static char **add_string_to_strings(char **strings, char *add)
1451 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1454 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1456 char **ptr = add_string_to_strings(strings, add);
1457 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1460 #define add_string_to_strings(strings, add) \
1461 xx_add_string_to_strings(__LINE__, strings, add)
1464 static void free_strings(char **strings)
1478 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1482 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1492 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1496 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1502 /* fd was not open? */
1507 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1508 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1514 /* Manipulating the list of open FILEs */
1515 static FILE *remember_FILE(FILE *fp)
1518 struct FILE_list *n = xmalloc(sizeof(*n));
1519 n->next = G.FILE_list;
1523 close_on_exec_on(n->fd);
1527 static void fclose_and_forget(FILE *fp)
1529 struct FILE_list **pp = &G.FILE_list;
1531 struct FILE_list *cur = *pp;
1532 if (cur->fp == fp) {
1541 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1543 struct FILE_list *fl = G.FILE_list;
1546 /* We use it only on script files, they are all CLOEXEC */
1547 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1548 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1555 static void restore_redirected_FILEs(void)
1557 struct FILE_list *fl = G.FILE_list;
1559 int should_be = fileno(fl->fp);
1560 if (fl->fd != should_be) {
1561 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1562 xmove_fd(fl->fd, should_be);
1568 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1569 static void close_all_FILE_list(void)
1571 struct FILE_list *fl = G.FILE_list;
1573 /* fclose would also free FILE object.
1574 * It is disastrous if we share memory with a vforked parent.
1575 * I'm not sure we never come here after vfork.
1576 * Therefore just close fd, nothing more.
1578 /*fclose(fl->fp); - unsafe */
1584 static int fd_in_FILEs(int fd)
1586 struct FILE_list *fl = G.FILE_list;
1596 /* Helpers for setting new $n and restoring them back
1598 typedef struct save_arg_t {
1602 IF_HUSH_SET(smallint sv_g_malloced;)
1605 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1607 sv->sv_argv0 = argv[0];
1608 sv->sv_g_argv = G.global_argv;
1609 sv->sv_g_argc = G.global_argc;
1610 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1612 argv[0] = G.global_argv[0]; /* retain $0 */
1613 G.global_argv = argv;
1614 IF_HUSH_SET(G.global_args_malloced = 0;)
1616 G.global_argc = 1 + string_array_len(argv + 1);
1619 static void restore_G_args(save_arg_t *sv, char **argv)
1622 if (G.global_args_malloced) {
1623 /* someone ran "set -- arg1 arg2 ...", undo */
1624 char **pp = G.global_argv;
1625 while (*++pp) /* note: does not free $0 */
1627 free(G.global_argv);
1630 argv[0] = sv->sv_argv0;
1631 G.global_argv = sv->sv_g_argv;
1632 G.global_argc = sv->sv_g_argc;
1633 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1637 /* Basic theory of signal handling in shell
1638 * ========================================
1639 * This does not describe what hush does, rather, it is current understanding
1640 * what it _should_ do. If it doesn't, it's a bug.
1641 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1643 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1644 * is finished or backgrounded. It is the same in interactive and
1645 * non-interactive shells, and is the same regardless of whether
1646 * a user trap handler is installed or a shell special one is in effect.
1647 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1648 * backgrounds (i.e. stops) or kills all members of currently running
1651 * Wait builtin is interruptible by signals for which user trap is set
1652 * or by SIGINT in interactive shell.
1654 * Trap handlers will execute even within trap handlers. (right?)
1656 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1657 * except for handlers set to '' (empty string).
1659 * If job control is off, backgrounded commands ("cmd &")
1660 * have SIGINT, SIGQUIT set to SIG_IGN.
1662 * Commands which are run in command substitution ("`cmd`")
1663 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1665 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1666 * by the shell from its parent.
1668 * Signals which differ from SIG_DFL action
1669 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1672 * SIGTERM (interactive): ignore
1673 * SIGHUP (interactive):
1674 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1675 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1676 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1677 * that all pipe members are stopped. Try this in bash:
1678 * while :; do :; done - ^Z does not background it
1679 * (while :; do :; done) - ^Z backgrounds it
1680 * SIGINT (interactive): wait for last pipe, ignore the rest
1681 * of the command line, show prompt. NB: ^C does not send SIGINT
1682 * to interactive shell while shell is waiting for a pipe,
1683 * since shell is bg'ed (is not in foreground process group).
1684 * Example 1: this waits 5 sec, but does not execute ls:
1685 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1686 * Example 2: this does not wait and does not execute ls:
1687 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1688 * Example 3: this does not wait 5 sec, but executes ls:
1689 * "sleep 5; ls -l" + press ^C
1690 * Example 4: this does not wait and does not execute ls:
1691 * "sleep 5 & wait; ls -l" + press ^C
1693 * (What happens to signals which are IGN on shell start?)
1694 * (What happens with signal mask on shell start?)
1696 * Old implementation
1697 * ==================
1698 * We use in-kernel pending signal mask to determine which signals were sent.
1699 * We block all signals which we don't want to take action immediately,
1700 * i.e. we block all signals which need to have special handling as described
1701 * above, and all signals which have traps set.
1702 * After each pipe execution, we extract any pending signals via sigtimedwait()
1705 * unsigned special_sig_mask: a mask of such "special" signals
1706 * sigset_t blocked_set: current blocked signal set
1709 * clear bit in blocked_set unless it is also in special_sig_mask
1710 * "trap 'cmd' SIGxxx":
1711 * set bit in blocked_set (even if 'cmd' is '')
1712 * after [v]fork, if we plan to be a shell:
1713 * unblock signals with special interactive handling
1714 * (child shell is not interactive),
1715 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1716 * after [v]fork, if we plan to exec:
1717 * POSIX says fork clears pending signal mask in child - no need to clear it.
1718 * Restore blocked signal set to one inherited by shell just prior to exec.
1720 * Note: as a result, we do not use signal handlers much. The only uses
1721 * are to count SIGCHLDs
1722 * and to restore tty pgrp on signal-induced exit.
1725 * Standard says "When a subshell is entered, traps that are not being ignored
1726 * are set to the default actions". bash interprets it so that traps which
1727 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1729 * Problem: the above approach makes it unwieldy to catch signals while
1730 * we are in read builtin, or while we read commands from stdin:
1731 * masked signals are not visible!
1733 * New implementation
1734 * ==================
1735 * We record each signal we are interested in by installing signal handler
1736 * for them - a bit like emulating kernel pending signal mask in userspace.
1737 * We are interested in: signals which need to have special handling
1738 * as described above, and all signals which have traps set.
1739 * Signals are recorded in pending_set.
1740 * After each pipe execution, we extract any pending signals
1743 * unsigned special_sig_mask: a mask of shell-special signals.
1744 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1745 * char *traps[sig] if trap for sig is set (even if it's '').
1746 * sigset_t pending_set: set of sigs we received.
1749 * if sig is in special_sig_mask, set handler back to:
1750 * record_pending_signo, or to IGN if it's a tty stop signal
1751 * if sig is in fatal_sig_mask, set handler back to sigexit.
1752 * else: set handler back to SIG_DFL
1753 * "trap 'cmd' SIGxxx":
1754 * set handler to record_pending_signo.
1756 * set handler to SIG_IGN.
1757 * after [v]fork, if we plan to be a shell:
1758 * set signals with special interactive handling to SIG_DFL
1759 * (because child shell is not interactive),
1760 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1761 * after [v]fork, if we plan to exec:
1762 * POSIX says fork clears pending signal mask in child - no need to clear it.
1764 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1765 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1768 * Standard says "When a subshell is entered, traps that are not being ignored
1769 * are set to the default actions". bash interprets it so that traps which
1770 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1773 SPECIAL_INTERACTIVE_SIGS = 0
1778 SPECIAL_JOBSTOP_SIGS = 0
1787 static void record_pending_signo(int sig)
1789 sigaddset(&G.pending_set, sig);
1790 #if ENABLE_HUSH_FAST
1791 if (sig == SIGCHLD) {
1793 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1798 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1800 struct sigaction old_sa;
1802 /* We could use signal() to install handlers... almost:
1803 * except that we need to mask ALL signals while handlers run.
1804 * I saw signal nesting in strace, race window isn't small.
1805 * SA_RESTART is also needed, but in Linux, signal()
1806 * sets SA_RESTART too.
1808 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1809 /* sigfillset(&G.sa.sa_mask); - already done */
1810 /* G.sa.sa_flags = SA_RESTART; - already done */
1811 G.sa.sa_handler = handler;
1812 sigaction(sig, &G.sa, &old_sa);
1813 return old_sa.sa_handler;
1816 static void hush_exit(int exitcode) NORETURN;
1818 static void restore_ttypgrp_and__exit(void) NORETURN;
1819 static void restore_ttypgrp_and__exit(void)
1821 /* xfunc has failed! die die die */
1822 /* no EXIT traps, this is an escape hatch! */
1824 hush_exit(xfunc_error_retval);
1829 /* Needed only on some libc:
1830 * It was observed that on exit(), fgetc'ed buffered data
1831 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1832 * With the net effect that even after fork(), not vfork(),
1833 * exit() in NOEXECed applet in "sh SCRIPT":
1834 * noexec_applet_here
1835 * echo END_OF_SCRIPT
1836 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1837 * This makes "echo END_OF_SCRIPT" executed twice.
1838 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1839 * and in `cmd` handling.
1840 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1842 static void fflush_and__exit(void) NORETURN;
1843 static void fflush_and__exit(void)
1846 _exit(xfunc_error_retval);
1849 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1850 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1851 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1852 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1854 /* Restores tty foreground process group, and exits.
1855 * May be called as signal handler for fatal signal
1856 * (will resend signal to itself, producing correct exit state)
1857 * or called directly with -EXITCODE.
1858 * We also call it if xfunc is exiting.
1860 static void sigexit(int sig) NORETURN;
1861 static void sigexit(int sig)
1863 /* Careful: we can end up here after [v]fork. Do not restore
1864 * tty pgrp then, only top-level shell process does that */
1865 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1866 /* Disable all signals: job control, SIGPIPE, etc.
1867 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1869 sigprocmask_allsigs(SIG_BLOCK);
1870 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1873 /* Not a signal, just exit */
1877 kill_myself_with_sig(sig); /* does not return */
1881 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1882 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1886 static sighandler_t pick_sighandler(unsigned sig)
1888 sighandler_t handler = SIG_DFL;
1889 if (sig < sizeof(unsigned)*8) {
1890 unsigned sigmask = (1 << sig);
1894 if (G_fatal_sig_mask & sigmask)
1898 /* sig has special handling? */
1899 if (G.special_sig_mask & sigmask) {
1900 handler = record_pending_signo;
1901 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1902 * in order to ignore them: they will be raised
1903 * in an endless loop when we try to do some
1904 * terminal ioctls! We do have to _ignore_ these.
1906 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1913 /* Restores tty foreground process group, and exits. */
1914 static void hush_exit(int exitcode)
1916 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1917 save_history(G.line_input_state);
1921 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1923 /* argv[0] is unused */
1924 argv[1] = G_traps[0];
1926 G.exiting = 1; /* prevent EXIT trap recursion */
1927 /* Note: G_traps[0] is not cleared!
1928 * "trap" will still show it, if executed
1933 #if ENABLE_FEATURE_CLEAN_UP
1935 struct variable *cur_var;
1936 if (G.cwd != bb_msg_unknown)
1938 cur_var = G.top_var;
1940 struct variable *tmp = cur_var;
1941 if (!cur_var->max_len)
1942 free(cur_var->varstr);
1943 cur_var = cur_var->next;
1951 sigexit(- (exitcode & 0xff));
1958 //TODO: return a mask of ALL handled sigs?
1959 static int check_and_run_traps(void)
1966 if (sigisemptyset(&G.pending_set))
1971 if (sigismember(&G.pending_set, sig)) {
1972 sigdelset(&G.pending_set, sig);
1975 } while (sig < NSIG);
1978 if (G_traps && G_traps[sig]) {
1979 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1980 if (G_traps[sig][0]) {
1981 /* We have user-defined handler */
1982 smalluint save_rcode;
1984 /* argv[0] is unused */
1985 argv[1] = G_traps[sig];
1987 save_rcode = G.last_exitcode;
1989 //FIXME: shouldn't it be set to 128 + sig instead?
1990 G.last_exitcode = save_rcode;
1992 } /* else: "" trap, ignoring signal */
1995 /* not a trap: special action */
1998 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2004 //TODO: why are we doing this? ash and dash don't do this,
2005 //they have no handler for SIGHUP at all,
2006 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2008 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2009 /* bash is observed to signal whole process groups,
2010 * not individual processes */
2011 for (job = G.job_list; job; job = job->next) {
2014 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2015 if (kill(- job->pgrp, SIGHUP) == 0)
2016 kill(- job->pgrp, SIGCONT);
2021 #if ENABLE_HUSH_FAST
2023 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2025 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2027 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2028 * This simplifies wait builtin a bit.
2032 default: /* ignored: */
2033 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2034 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2036 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2037 * Example: wait is not interrupted by TERM
2038 * in interactive shell, because TERM is ignored.
2047 static const char *get_cwd(int force)
2049 if (force || G.cwd == NULL) {
2050 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2051 * we must not try to free(bb_msg_unknown) */
2052 if (G.cwd == bb_msg_unknown)
2054 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2056 G.cwd = bb_msg_unknown;
2063 * Shell and environment variable support
2065 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2067 struct variable **pp;
2068 struct variable *cur;
2071 while ((cur = *pp) != NULL) {
2072 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2079 static const char* FAST_FUNC get_local_var_value(const char *name)
2081 struct variable **vpp;
2082 unsigned len = strlen(name);
2084 if (G.expanded_assignments) {
2085 char **cpp = G.expanded_assignments;
2088 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2089 return cp + len + 1;
2094 vpp = get_ptr_to_local_var(name, len);
2096 return (*vpp)->varstr + len + 1;
2098 if (strcmp(name, "PPID") == 0)
2099 return utoa(G.root_ppid);
2100 // bash compat: UID? EUID?
2101 #if ENABLE_HUSH_RANDOM_SUPPORT
2102 if (strcmp(name, "RANDOM") == 0)
2103 return utoa(next_random(&G.random_gen));
2108 /* str holds "NAME=VAL" and is expected to be malloced.
2109 * We take ownership of it.
2111 #define SETFLAG_EXPORT (1 << 0)
2112 #define SETFLAG_UNEXPORT (1 << 1)
2113 #define SETFLAG_MAKE_RO (1 << 2)
2114 #define SETFLAG_LOCAL_SHIFT 3
2115 static int set_local_var(char *str, unsigned flags)
2117 struct variable **var_pp;
2118 struct variable *cur;
2119 char *free_me = NULL;
2122 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2124 eq_sign = strchr(str, '=');
2125 if (!eq_sign) { /* not expected to ever happen? */
2130 name_len = eq_sign - str + 1; /* including '=' */
2131 var_pp = &G.top_var;
2132 while ((cur = *var_pp) != NULL) {
2133 if (strncmp(cur->varstr, str, name_len) != 0) {
2134 var_pp = &cur->next;
2138 /* We found an existing var with this name */
2139 if (cur->flg_read_only) {
2140 bb_error_msg("%s: readonly variable", str);
2142 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2143 //but export per se succeeds (does put the var in env). We don't mimic that.
2146 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2147 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2152 #if ENABLE_HUSH_LOCAL
2153 if (cur->func_nest_level < local_lvl) {
2154 /* New variable is declared as local,
2155 * and existing one is global, or local
2156 * from enclosing function.
2157 * Remove and save old one: */
2158 *var_pp = cur->next;
2159 cur->next = *G.shadowed_vars_pp;
2160 *G.shadowed_vars_pp = cur;
2161 /* bash 3.2.33(1) and exported vars:
2163 * # f() { local z=a; env | grep ^z; }
2169 if (cur->flg_export)
2170 flags |= SETFLAG_EXPORT;
2174 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2179 if (cur->max_len != 0) {
2180 if (cur->max_len >= strlen(str)) {
2181 /* This one is from startup env, reuse space */
2182 strcpy(cur->varstr, str);
2187 goto set_str_and_exp;
2189 /* max_len == 0 signifies "malloced" var, which we can
2190 * (and have to) free. But we can't free(cur->varstr) here:
2191 * if cur->flg_export is 1, it is in the environment.
2192 * We should either unsetenv+free, or wait until putenv,
2193 * then putenv(new)+free(old).
2195 free_me = cur->varstr;
2196 goto set_str_and_exp;
2199 /* Not found - create new variable struct */
2200 cur = xzalloc(sizeof(*cur));
2201 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2202 cur->next = *var_pp;
2208 #if !BB_MMU || ENABLE_HUSH_READONLY
2209 if (flags & SETFLAG_MAKE_RO) {
2210 cur->flg_read_only = 1;
2213 if (flags & SETFLAG_EXPORT)
2214 cur->flg_export = 1;
2215 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2216 cmdedit_update_prompt();
2217 if (cur->flg_export) {
2218 if (flags & SETFLAG_UNEXPORT) {
2219 cur->flg_export = 0;
2220 /* unsetenv was already done */
2223 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2224 i = putenv(cur->varstr);
2225 /* only now we can free old exported malloced string */
2234 /* Used at startup and after each cd */
2235 static void set_pwd_var(unsigned flag)
2237 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2240 static int unset_local_var_len(const char *name, int name_len)
2242 struct variable *cur;
2243 struct variable **var_pp;
2246 return EXIT_SUCCESS;
2247 var_pp = &G.top_var;
2248 while ((cur = *var_pp) != NULL) {
2249 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2250 if (cur->flg_read_only) {
2251 bb_error_msg("%s: readonly variable", name);
2252 return EXIT_FAILURE;
2254 *var_pp = cur->next;
2255 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2256 bb_unsetenv(cur->varstr);
2257 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2258 cmdedit_update_prompt();
2262 return EXIT_SUCCESS;
2264 var_pp = &cur->next;
2266 return EXIT_SUCCESS;
2269 #if ENABLE_HUSH_UNSET
2270 static int unset_local_var(const char *name)
2272 return unset_local_var_len(name, strlen(name));
2276 static void unset_vars(char **strings)
2284 const char *eq = strchrnul(*v, '=');
2285 unset_local_var_len(*v, (int)(eq - *v));
2291 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ
2292 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2294 char *var = xasprintf("%s=%s", name, val);
2295 set_local_var(var, /*flag:*/ 0);
2301 * Helpers for "var1=val1 var2=val2 cmd" feature
2303 static void add_vars(struct variable *var)
2305 struct variable *next;
2309 var->next = G.top_var;
2311 if (var->flg_export) {
2312 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2313 putenv(var->varstr);
2315 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2321 static struct variable *set_vars_and_save_old(char **strings)
2324 struct variable *old = NULL;
2330 struct variable *var_p;
2331 struct variable **var_pp;
2334 eq = strchr(*s, '=');
2336 var_pp = get_ptr_to_local_var(*s, eq - *s);
2339 if (var_p->flg_read_only) {
2341 bb_error_msg("%s: readonly variable", *s);
2343 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2344 * If VAR is readonly, leaving it in the list
2345 * after asssignment error (msg above)
2346 * causes doubled error message later, on unset.
2348 debug_printf_env("removing/freeing '%s' element\n", *s);
2351 do { *p = p[1]; p++; } while (*p);
2354 /* Remove variable from global linked list */
2355 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2356 *var_pp = var_p->next;
2357 /* Add it to returned list */
2361 set_local_var(*s, SETFLAG_EXPORT);
2373 static void reinit_unicode_for_hush(void)
2375 /* Unicode support should be activated even if LANG is set
2376 * _during_ shell execution, not only if it was set when
2377 * shell was started. Therefore, re-check LANG every time:
2379 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2380 || ENABLE_UNICODE_USING_LOCALE
2382 const char *s = get_local_var_value("LC_ALL");
2383 if (!s) s = get_local_var_value("LC_CTYPE");
2384 if (!s) s = get_local_var_value("LANG");
2390 * in_str support (strings, and "strings" read from files).
2393 #if ENABLE_HUSH_INTERACTIVE
2394 /* To test correct lineedit/interactive behavior, type from command line:
2400 * It exercises a lot of corner cases.
2402 static void cmdedit_update_prompt(void)
2404 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2405 G.PS1 = get_local_var_value("PS1");
2408 G.PS2 = get_local_var_value("PS2");
2415 static const char *setup_prompt_string(int promptmode)
2417 const char *prompt_str;
2418 debug_printf("setup_prompt_string %d ", promptmode);
2419 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2420 /* Set up the prompt */
2421 if (promptmode == 0) { /* PS1 */
2423 /* bash uses $PWD value, even if it is set by user.
2424 * It uses current dir only if PWD is unset.
2425 * We always use current dir. */
2426 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2431 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2432 debug_printf("prompt_str '%s'\n", prompt_str);
2435 static int get_user_input(struct in_str *i)
2438 const char *prompt_str;
2440 prompt_str = setup_prompt_string(i->promptmode);
2441 # if ENABLE_FEATURE_EDITING
2443 reinit_unicode_for_hush();
2444 if (G.flag_SIGINT) {
2445 /* There was ^C'ed, make it look prettier: */
2449 /* buglet: SIGINT will not make new prompt to appear _at once_,
2450 * only after <Enter>. (^C works immediately) */
2451 r = read_line_input(G.line_input_state, prompt_str,
2452 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2454 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2457 check_and_run_traps();
2458 if (r != 0 && !G.flag_SIGINT)
2460 /* ^C or SIGINT: repeat */
2461 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2462 write(STDOUT_FILENO, "^C", 2);
2463 G.last_exitcode = 128 + SIGINT;
2466 /* EOF/error detected */
2468 i->peek_buf[0] = r = EOF;
2471 i->p = G.user_input_buf;
2472 return (unsigned char)*i->p++;
2476 if (i->last_char == '\0' || i->last_char == '\n') {
2477 /* Why check_and_run_traps here? Try this interactively:
2478 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2479 * $ <[enter], repeatedly...>
2480 * Without check_and_run_traps, handler never runs.
2482 check_and_run_traps();
2483 fputs(prompt_str, stdout);
2486 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2488 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2489 * no ^C masking happens during fgetc, no special code for ^C:
2490 * it generates SIGINT as usual.
2492 check_and_run_traps();
2494 G.last_exitcode = 128 + SIGINT;
2501 /* This is the magic location that prints prompts
2502 * and gets data back from the user */
2503 static int fgetc_interactive(struct in_str *i)
2506 /* If it's interactive stdin, get new line. */
2507 if (G_interactive_fd && i->file == stdin) {
2508 /* Returns first char (or EOF), the rest is in i->p[] */
2509 ch = get_user_input(i);
2510 i->promptmode = 1; /* PS2 */
2512 /* Not stdin: script file, sourced file, etc */
2513 do ch = fgetc(i->file); while (ch == '\0');
2518 static inline int fgetc_interactive(struct in_str *i)
2521 do ch = fgetc(i->file); while (ch == '\0');
2524 #endif /* INTERACTIVE */
2526 static int i_getch(struct in_str *i)
2531 /* string-based in_str */
2532 ch = (unsigned char)*i->p;
2541 /* FILE-based in_str */
2543 #if ENABLE_FEATURE_EDITING
2544 /* This can be stdin, check line editing char[] buffer */
2545 if (i->p && *i->p != '\0') {
2546 ch = (unsigned char)*i->p++;
2550 /* peek_buf[] is an int array, not char. Can contain EOF. */
2551 ch = i->peek_buf[0];
2553 int ch2 = i->peek_buf[1];
2554 i->peek_buf[0] = ch2;
2555 if (ch2 == 0) /* very likely, avoid redundant write */
2561 ch = fgetc_interactive(i);
2563 debug_printf("file_get: got '%c' %d\n", ch, ch);
2568 static int i_peek(struct in_str *i)
2573 /* string-based in_str */
2574 /* Doesn't report EOF on NUL. None of the callers care. */
2575 return (unsigned char)*i->p;
2578 /* FILE-based in_str */
2580 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2581 /* This can be stdin, check line editing char[] buffer */
2582 if (i->p && *i->p != '\0')
2583 return (unsigned char)*i->p;
2585 /* peek_buf[] is an int array, not char. Can contain EOF. */
2586 ch = i->peek_buf[0];
2590 /* Need to get a new char */
2591 ch = fgetc_interactive(i);
2592 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2594 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2595 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2601 i->peek_buf[0] = ch;
2602 /*i->peek_buf[1] = 0; - already is */
2606 /* Only ever called if i_peek() was called, and did not return EOF.
2607 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2608 * not end-of-line. Therefore we never need to read a new editing line here.
2610 static int i_peek2(struct in_str *i)
2614 /* There are two cases when i->p[] buffer exists.
2615 * (1) it's a string in_str.
2616 * (2) It's a file, and we have a saved line editing buffer.
2617 * In both cases, we know that i->p[0] exists and not NUL, and
2618 * the peek2 result is in i->p[1].
2621 return (unsigned char)i->p[1];
2623 /* Now we know it is a file-based in_str. */
2625 /* peek_buf[] is an int array, not char. Can contain EOF. */
2626 /* Is there 2nd char? */
2627 ch = i->peek_buf[1];
2629 /* We did not read it yet, get it now */
2630 do ch = fgetc(i->file); while (ch == '\0');
2631 i->peek_buf[1] = ch;
2634 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2638 static void setup_file_in_str(struct in_str *i, FILE *f)
2640 memset(i, 0, sizeof(*i));
2641 /* i->promptmode = 0; - PS1 (memset did it) */
2646 static void setup_string_in_str(struct in_str *i, const char *s)
2648 memset(i, 0, sizeof(*i));
2649 /* i->promptmode = 0; - PS1 (memset did it) */
2650 /*i->file = NULL */;
2658 #define B_CHUNK (32 * sizeof(char*))
2660 static void o_reset_to_empty_unquoted(o_string *o)
2663 o->has_quoted_part = 0;
2668 static void o_free(o_string *o)
2671 memset(o, 0, sizeof(*o));
2674 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2679 static void o_grow_by(o_string *o, int len)
2681 if (o->length + len > o->maxlen) {
2682 o->maxlen += (2 * len) | (B_CHUNK-1);
2683 o->data = xrealloc(o->data, 1 + o->maxlen);
2687 static void o_addchr(o_string *o, int ch)
2689 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2690 if (o->length < o->maxlen) {
2691 /* likely. avoid o_grow_by() call */
2693 o->data[o->length] = ch;
2695 o->data[o->length] = '\0';
2703 /* Valid only if we know o_string is not empty */
2704 static void o_delchr(o_string *o)
2707 o->data[o->length] = '\0';
2711 static void o_addblock(o_string *o, const char *str, int len)
2714 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2718 static void o_addstr(o_string *o, const char *str)
2720 o_addblock(o, str, strlen(str));
2724 static void nommu_addchr(o_string *o, int ch)
2730 # define nommu_addchr(o, str) ((void)0)
2733 static void o_addstr_with_NUL(o_string *o, const char *str)
2735 o_addblock(o, str, strlen(str) + 1);
2739 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2740 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2741 * Apparently, on unquoted $v bash still does globbing
2742 * ("v='*.txt'; echo $v" prints all .txt files),
2743 * but NOT brace expansion! Thus, there should be TWO independent
2744 * quoting mechanisms on $v expansion side: one protects
2745 * $v from brace expansion, and other additionally protects "$v" against globbing.
2746 * We have only second one.
2749 #if ENABLE_HUSH_BRACE_EXPANSION
2750 # define MAYBE_BRACES "{}"
2752 # define MAYBE_BRACES ""
2755 /* My analysis of quoting semantics tells me that state information
2756 * is associated with a destination, not a source.
2758 static void o_addqchr(o_string *o, int ch)
2761 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2766 o->data[o->length] = '\\';
2769 o->data[o->length] = ch;
2771 o->data[o->length] = '\0';
2774 static void o_addQchr(o_string *o, int ch)
2777 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2778 && strchr("*?[\\" MAYBE_BRACES, ch)
2781 o->data[o->length] = '\\';
2785 o->data[o->length] = ch;
2787 o->data[o->length] = '\0';
2790 static void o_addqblock(o_string *o, const char *str, int len)
2795 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2796 if (ordinary_cnt > len) /* paranoia */
2798 o_addblock(o, str, ordinary_cnt);
2799 if (ordinary_cnt == len)
2800 return; /* NUL is already added by o_addblock */
2801 str += ordinary_cnt;
2802 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2806 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2808 o->data[o->length] = '\\';
2812 o->data[o->length] = ch;
2815 o->data[o->length] = '\0';
2818 static void o_addQblock(o_string *o, const char *str, int len)
2820 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2821 o_addblock(o, str, len);
2824 o_addqblock(o, str, len);
2827 static void o_addQstr(o_string *o, const char *str)
2829 o_addQblock(o, str, strlen(str));
2832 /* A special kind of o_string for $VAR and `cmd` expansion.
2833 * It contains char* list[] at the beginning, which is grown in 16 element
2834 * increments. Actual string data starts at the next multiple of 16 * (char*).
2835 * list[i] contains an INDEX (int!) into this string data.
2836 * It means that if list[] needs to grow, data needs to be moved higher up
2837 * but list[i]'s need not be modified.
2838 * NB: remembering how many list[i]'s you have there is crucial.
2839 * o_finalize_list() operation post-processes this structure - calculates
2840 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2842 #if DEBUG_EXPAND || DEBUG_GLOB
2843 static void debug_print_list(const char *prefix, o_string *o, int n)
2845 char **list = (char**)o->data;
2846 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2850 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2851 prefix, list, n, string_start, o->length, o->maxlen,
2852 !!(o->o_expflags & EXP_FLAG_GLOB),
2854 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2857 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2858 o->data + (int)(uintptr_t)list[i] + string_start,
2859 o->data + (int)(uintptr_t)list[i] + string_start);
2863 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2865 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2869 # define debug_print_list(prefix, o, n) ((void)0)
2872 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2873 * in list[n] so that it points past last stored byte so far.
2874 * It returns n+1. */
2875 static int o_save_ptr_helper(o_string *o, int n)
2877 char **list = (char**)o->data;
2881 if (!o->has_empty_slot) {
2882 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2883 string_len = o->length - string_start;
2884 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2885 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2886 /* list[n] points to string_start, make space for 16 more pointers */
2887 o->maxlen += 0x10 * sizeof(list[0]);
2888 o->data = xrealloc(o->data, o->maxlen + 1);
2889 list = (char**)o->data;
2890 memmove(list + n + 0x10, list + n, string_len);
2891 o->length += 0x10 * sizeof(list[0]);
2893 debug_printf_list("list[%d]=%d string_start=%d\n",
2894 n, string_len, string_start);
2897 /* We have empty slot at list[n], reuse without growth */
2898 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2899 string_len = o->length - string_start;
2900 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2901 n, string_len, string_start);
2902 o->has_empty_slot = 0;
2904 o->has_quoted_part = 0;
2905 list[n] = (char*)(uintptr_t)string_len;
2909 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2910 static int o_get_last_ptr(o_string *o, int n)
2912 char **list = (char**)o->data;
2913 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2915 return ((int)(uintptr_t)list[n-1]) + string_start;
2918 #if ENABLE_HUSH_BRACE_EXPANSION
2919 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2920 * first, it processes even {a} (no commas), second,
2921 * I didn't manage to make it return strings when they don't match
2922 * existing files. Need to re-implement it.
2926 static int glob_needed(const char *s)
2935 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2941 /* Return pointer to next closing brace or to comma */
2942 static const char *next_brace_sub(const char *cp)
2946 while (*cp != '\0') {
2953 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2959 return *cp != '\0' ? cp : NULL;
2961 /* Recursive brace globber. Note: may garble pattern[]. */
2962 static int glob_brace(char *pattern, o_string *o, int n)
2964 char *new_pattern_buf;
2971 debug_printf_glob("glob_brace('%s')\n", pattern);
2977 if (*begin == '{') {
2978 /* Find the first sub-pattern and at the same time
2979 * find the rest after the closing brace */
2980 next = next_brace_sub(begin);
2982 /* An illegal expression */
2986 /* "{abc}" with no commas - illegal
2987 * brace expr, disregard and skip it */
2993 if (*begin == '\\' && begin[1] != '\0')
2997 debug_printf_glob("begin:%s\n", begin);
2998 debug_printf_glob("next:%s\n", next);
3000 /* Now find the end of the whole brace expression */
3002 while (*rest != '}') {
3003 rest = next_brace_sub(rest);
3005 /* An illegal expression */
3008 debug_printf_glob("rest:%s\n", rest);
3010 rest_len = strlen(++rest) + 1;
3012 /* We are sure the brace expression is well-formed */
3014 /* Allocate working buffer large enough for our work */
3015 new_pattern_buf = xmalloc(strlen(pattern));
3017 /* We have a brace expression. BEGIN points to the opening {,
3018 * NEXT points past the terminator of the first element, and REST
3019 * points past the final }. We will accumulate result names from
3020 * recursive runs for each brace alternative in the buffer using
3025 /* Construct the new glob expression */
3028 mempcpy(new_pattern_buf,
3029 /* We know the prefix for all sub-patterns */
3030 pattern, begin - pattern),
3034 /* Note: glob_brace() may garble new_pattern_buf[].
3035 * That's why we re-copy prefix every time (1st memcpy above).
3037 n = glob_brace(new_pattern_buf, o, n);
3039 /* We saw the last entry */
3043 next = next_brace_sub(next);
3045 free(new_pattern_buf);
3053 memset(&globdata, 0, sizeof(globdata));
3054 gr = glob(pattern, 0, NULL, &globdata);
3055 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3057 if (gr == GLOB_NOMATCH) {
3058 globfree(&globdata);
3059 /* NB: garbles parameter */
3060 unbackslash(pattern);
3061 o_addstr_with_NUL(o, pattern);
3062 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3063 return o_save_ptr_helper(o, n);
3065 if (gr == GLOB_NOSPACE)
3066 bb_error_msg_and_die(bb_msg_memory_exhausted);
3067 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3068 * but we didn't specify it. Paranoia again. */
3069 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3071 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3072 char **argv = globdata.gl_pathv;
3074 o_addstr_with_NUL(o, *argv);
3075 n = o_save_ptr_helper(o, n);
3081 globfree(&globdata);
3085 /* Performs globbing on last list[],
3086 * saving each result as a new list[].
3088 static int perform_glob(o_string *o, int n)
3090 char *pattern, *copy;
3092 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3094 return o_save_ptr_helper(o, n);
3095 pattern = o->data + o_get_last_ptr(o, n);
3096 debug_printf_glob("glob pattern '%s'\n", pattern);
3097 if (!glob_needed(pattern)) {
3098 /* unbackslash last string in o in place, fix length */
3099 o->length = unbackslash(pattern) - o->data;
3100 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3101 return o_save_ptr_helper(o, n);
3104 copy = xstrdup(pattern);
3105 /* "forget" pattern in o */
3106 o->length = pattern - o->data;
3107 n = glob_brace(copy, o, n);
3110 debug_print_list("perform_glob returning", o, n);
3114 #else /* !HUSH_BRACE_EXPANSION */
3117 static int glob_needed(const char *s)
3126 if (*s == '*' || *s == '[' || *s == '?')
3132 /* Performs globbing on last list[],
3133 * saving each result as a new list[].
3135 static int perform_glob(o_string *o, int n)
3141 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3143 return o_save_ptr_helper(o, n);
3144 pattern = o->data + o_get_last_ptr(o, n);
3145 debug_printf_glob("glob pattern '%s'\n", pattern);
3146 if (!glob_needed(pattern)) {
3148 /* unbackslash last string in o in place, fix length */
3149 o->length = unbackslash(pattern) - o->data;
3150 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3151 return o_save_ptr_helper(o, n);
3154 memset(&globdata, 0, sizeof(globdata));
3155 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3156 * If we glob "*.\*" and don't find anything, we need
3157 * to fall back to using literal "*.*", but GLOB_NOCHECK
3158 * will return "*.\*"!
3160 gr = glob(pattern, 0, NULL, &globdata);
3161 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3163 if (gr == GLOB_NOMATCH) {
3164 globfree(&globdata);
3167 if (gr == GLOB_NOSPACE)
3168 bb_error_msg_and_die(bb_msg_memory_exhausted);
3169 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3170 * but we didn't specify it. Paranoia again. */
3171 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3173 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3174 char **argv = globdata.gl_pathv;
3175 /* "forget" pattern in o */
3176 o->length = pattern - o->data;
3178 o_addstr_with_NUL(o, *argv);
3179 n = o_save_ptr_helper(o, n);
3185 globfree(&globdata);
3187 debug_print_list("perform_glob returning", o, n);
3191 #endif /* !HUSH_BRACE_EXPANSION */
3193 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3194 * Otherwise, just finish current list[] and start new */
3195 static int o_save_ptr(o_string *o, int n)
3197 if (o->o_expflags & EXP_FLAG_GLOB) {
3198 /* If o->has_empty_slot, list[n] was already globbed
3199 * (if it was requested back then when it was filled)
3200 * so don't do that again! */
3201 if (!o->has_empty_slot)
3202 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3204 return o_save_ptr_helper(o, n);
3207 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3208 static char **o_finalize_list(o_string *o, int n)
3213 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3215 debug_print_list("finalized", o, n);
3216 debug_printf_expand("finalized n:%d\n", n);
3217 list = (char**)o->data;
3218 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3222 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3227 static void free_pipe_list(struct pipe *pi);
3229 /* Returns pi->next - next pipe in the list */
3230 static struct pipe *free_pipe(struct pipe *pi)
3235 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3236 for (i = 0; i < pi->num_cmds; i++) {
3237 struct command *command;
3238 struct redir_struct *r, *rnext;
3240 command = &pi->cmds[i];
3241 debug_printf_clean(" command %d:\n", i);
3242 if (command->argv) {
3246 for (a = 0, p = command->argv; *p; a++, p++) {
3247 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3250 free_strings(command->argv);
3251 //command->argv = NULL;
3253 /* not "else if": on syntax error, we may have both! */
3254 if (command->group) {
3255 debug_printf_clean(" begin group (cmd_type:%d)\n",
3257 free_pipe_list(command->group);
3258 debug_printf_clean(" end group\n");
3259 //command->group = NULL;
3261 /* else is crucial here.
3262 * If group != NULL, child_func is meaningless */
3263 #if ENABLE_HUSH_FUNCTIONS
3264 else if (command->child_func) {
3265 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3266 command->child_func->parent_cmd = NULL;
3270 free(command->group_as_string);
3271 //command->group_as_string = NULL;
3273 for (r = command->redirects; r; r = rnext) {
3274 debug_printf_clean(" redirect %d%s",
3275 r->rd_fd, redir_table[r->rd_type].descrip);
3276 /* guard against the case >$FOO, where foo is unset or blank */
3277 if (r->rd_filename) {
3278 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3279 free(r->rd_filename);
3280 //r->rd_filename = NULL;
3282 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3286 //command->redirects = NULL;
3288 free(pi->cmds); /* children are an array, they get freed all at once */
3292 //pi->cmdtext = NULL;
3300 static void free_pipe_list(struct pipe *pi)
3304 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3306 debug_printf_clean("pipe followup code %d\n", pi->followup);
3312 /*** Parsing routines ***/
3314 #ifndef debug_print_tree
3315 static void debug_print_tree(struct pipe *pi, int lvl)
3317 static const char *const PIPE[] = {
3323 static const char *RES[] = {
3324 [RES_NONE ] = "NONE" ,
3327 [RES_THEN ] = "THEN" ,
3328 [RES_ELIF ] = "ELIF" ,
3329 [RES_ELSE ] = "ELSE" ,
3332 # if ENABLE_HUSH_LOOPS
3333 [RES_FOR ] = "FOR" ,
3334 [RES_WHILE] = "WHILE",
3335 [RES_UNTIL] = "UNTIL",
3337 [RES_DONE ] = "DONE" ,
3339 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3342 # if ENABLE_HUSH_CASE
3343 [RES_CASE ] = "CASE" ,
3344 [RES_CASE_IN ] = "CASE_IN" ,
3345 [RES_MATCH] = "MATCH",
3346 [RES_CASE_BODY] = "CASE_BODY",
3347 [RES_ESAC ] = "ESAC" ,
3349 [RES_XXXX ] = "XXXX" ,
3350 [RES_SNTX ] = "SNTX" ,
3352 static const char *const CMDTYPE[] = {
3356 # if ENABLE_HUSH_FUNCTIONS
3365 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3366 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3368 while (prn < pi->num_cmds) {
3369 struct command *command = &pi->cmds[prn];
3370 char **argv = command->argv;
3372 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3374 command->assignment_cnt);
3375 if (command->group) {
3376 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3377 CMDTYPE[command->cmd_type],
3380 , " group_as_string:", command->group_as_string
3385 debug_print_tree(command->group, lvl+1);
3389 if (argv) while (*argv) {
3390 fdprintf(2, " '%s'", *argv);
3400 #endif /* debug_print_tree */
3402 static struct pipe *new_pipe(void)
3405 pi = xzalloc(sizeof(struct pipe));
3406 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3410 /* Command (member of a pipe) is complete, or we start a new pipe
3411 * if ctx->command is NULL.
3412 * No errors possible here.
3414 static int done_command(struct parse_context *ctx)
3416 /* The command is really already in the pipe structure, so
3417 * advance the pipe counter and make a new, null command. */
3418 struct pipe *pi = ctx->pipe;
3419 struct command *command = ctx->command;
3421 #if 0 /* Instead we emit error message at run time */
3422 if (ctx->pending_redirect) {
3423 /* For example, "cmd >" (no filename to redirect to) */
3424 syntax_error("invalid redirect");
3425 ctx->pending_redirect = NULL;
3430 if (IS_NULL_CMD(command)) {
3431 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3435 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3436 //debug_print_tree(ctx->list_head, 20);
3438 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3441 /* Only real trickiness here is that the uncommitted
3442 * command structure is not counted in pi->num_cmds. */
3443 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3444 ctx->command = command = &pi->cmds[pi->num_cmds];
3446 memset(command, 0, sizeof(*command));
3447 return pi->num_cmds; /* used only for 0/nonzero check */
3450 static void done_pipe(struct parse_context *ctx, pipe_style type)
3454 debug_printf_parse("done_pipe entered, followup %d\n", type);
3455 /* Close previous command */
3456 not_null = done_command(ctx);
3458 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3459 ctx->ctx_inverted = 0;
3460 ctx->pipe->res_word = ctx->ctx_res_w;
3462 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3463 /* Necessary since && and || have precedence over &:
3464 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3465 * in a backgrounded subshell.
3468 struct command *command;
3470 /* Is this actually this construct, all pipes end with && or ||? */
3471 pi = ctx->list_head;
3472 while (pi != ctx->pipe) {
3473 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3478 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3479 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3480 pi = xzalloc(sizeof(*pi));
3481 pi->followup = PIPE_BG;
3483 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3484 command = &pi->cmds[0];
3485 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3486 command->cmd_type = CMD_NORMAL;
3487 command->group = ctx->list_head;
3489 command->group_as_string = xstrndup(
3490 ctx->as_string.data,
3491 ctx->as_string.length - 1 /* do not copy last char, "&" */
3494 /* Replace all pipes in ctx with one newly created */
3495 ctx->list_head = ctx->pipe = pi;
3498 ctx->pipe->followup = type;
3501 /* Without this check, even just <enter> on command line generates
3502 * tree of three NOPs (!). Which is harmless but annoying.
3503 * IOW: it is safe to do it unconditionally. */
3506 || ctx->ctx_res_w == RES_FI
3508 #if ENABLE_HUSH_LOOPS
3509 || ctx->ctx_res_w == RES_DONE
3510 || ctx->ctx_res_w == RES_FOR
3511 || ctx->ctx_res_w == RES_IN
3513 #if ENABLE_HUSH_CASE
3514 || ctx->ctx_res_w == RES_ESAC
3518 debug_printf_parse("done_pipe: adding new pipe: "
3519 "not_null:%d ctx->ctx_res_w:%d\n",
3520 not_null, ctx->ctx_res_w);
3522 ctx->pipe->next = new_p;
3524 /* RES_THEN, RES_DO etc are "sticky" -
3525 * they remain set for pipes inside if/while.
3526 * This is used to control execution.
3527 * RES_FOR and RES_IN are NOT sticky (needed to support
3528 * cases where variable or value happens to match a keyword):
3530 #if ENABLE_HUSH_LOOPS
3531 if (ctx->ctx_res_w == RES_FOR
3532 || ctx->ctx_res_w == RES_IN)
3533 ctx->ctx_res_w = RES_NONE;
3535 #if ENABLE_HUSH_CASE
3536 if (ctx->ctx_res_w == RES_MATCH)
3537 ctx->ctx_res_w = RES_CASE_BODY;
3538 if (ctx->ctx_res_w == RES_CASE)
3539 ctx->ctx_res_w = RES_CASE_IN;
3541 ctx->command = NULL; /* trick done_command below */
3542 /* Create the memory for command, roughly:
3543 * ctx->pipe->cmds = new struct command;
3544 * ctx->command = &ctx->pipe->cmds[0];
3547 //debug_print_tree(ctx->list_head, 10);
3549 debug_printf_parse("done_pipe return\n");
3552 static void initialize_context(struct parse_context *ctx)
3554 memset(ctx, 0, sizeof(*ctx));
3555 ctx->pipe = ctx->list_head = new_pipe();
3556 /* Create the memory for command, roughly:
3557 * ctx->pipe->cmds = new struct command;
3558 * ctx->command = &ctx->pipe->cmds[0];
3563 /* If a reserved word is found and processed, parse context is modified
3564 * and 1 is returned.
3567 struct reserved_combo {
3570 unsigned char assignment_flag;
3574 FLAG_END = (1 << RES_NONE ),
3576 FLAG_IF = (1 << RES_IF ),
3577 FLAG_THEN = (1 << RES_THEN ),
3578 FLAG_ELIF = (1 << RES_ELIF ),
3579 FLAG_ELSE = (1 << RES_ELSE ),
3580 FLAG_FI = (1 << RES_FI ),
3582 # if ENABLE_HUSH_LOOPS
3583 FLAG_FOR = (1 << RES_FOR ),
3584 FLAG_WHILE = (1 << RES_WHILE),
3585 FLAG_UNTIL = (1 << RES_UNTIL),
3586 FLAG_DO = (1 << RES_DO ),
3587 FLAG_DONE = (1 << RES_DONE ),
3588 FLAG_IN = (1 << RES_IN ),
3590 # if ENABLE_HUSH_CASE
3591 FLAG_MATCH = (1 << RES_MATCH),
3592 FLAG_ESAC = (1 << RES_ESAC ),
3594 FLAG_START = (1 << RES_XXXX ),
3597 static const struct reserved_combo* match_reserved_word(o_string *word)
3599 /* Mostly a list of accepted follow-up reserved words.
3600 * FLAG_END means we are done with the sequence, and are ready
3601 * to turn the compound list into a command.
3602 * FLAG_START means the word must start a new compound list.
3604 static const struct reserved_combo reserved_list[] = {
3606 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3607 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3608 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3609 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3610 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3611 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3613 # if ENABLE_HUSH_LOOPS
3614 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3615 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3616 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3617 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3618 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3619 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3621 # if ENABLE_HUSH_CASE
3622 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3623 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3626 const struct reserved_combo *r;
3628 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3629 if (strcmp(word->data, r->literal) == 0)
3634 /* Return 0: not a keyword, 1: keyword
3636 static int reserved_word(o_string *word, struct parse_context *ctx)
3638 # if ENABLE_HUSH_CASE
3639 static const struct reserved_combo reserved_match = {
3640 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3643 const struct reserved_combo *r;
3645 if (word->has_quoted_part)
3647 r = match_reserved_word(word);
3651 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3652 # if ENABLE_HUSH_CASE
3653 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3654 /* "case word IN ..." - IN part starts first MATCH part */
3655 r = &reserved_match;
3658 if (r->flag == 0) { /* '!' */
3659 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3660 syntax_error("! ! command");
3661 ctx->ctx_res_w = RES_SNTX;
3663 ctx->ctx_inverted = 1;
3666 if (r->flag & FLAG_START) {
3667 struct parse_context *old;
3669 old = xmemdup(ctx, sizeof(*ctx));
3670 debug_printf_parse("push stack %p\n", old);
3671 initialize_context(ctx);
3673 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3674 syntax_error_at(word->data);
3675 ctx->ctx_res_w = RES_SNTX;
3678 /* "{...} fi" is ok. "{...} if" is not
3680 * if { echo foo; } then { echo bar; } fi */
3681 if (ctx->command->group)
3682 done_pipe(ctx, PIPE_SEQ);
3685 ctx->ctx_res_w = r->res;
3686 ctx->old_flag = r->flag;
3687 word->o_assignment = r->assignment_flag;
3688 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3690 if (ctx->old_flag & FLAG_END) {
3691 struct parse_context *old;
3693 done_pipe(ctx, PIPE_SEQ);
3694 debug_printf_parse("pop stack %p\n", ctx->stack);
3696 old->command->group = ctx->list_head;
3697 old->command->cmd_type = CMD_NORMAL;
3699 /* At this point, the compound command's string is in
3700 * ctx->as_string... except for the leading keyword!
3701 * Consider this example: "echo a | if true; then echo a; fi"
3702 * ctx->as_string will contain "true; then echo a; fi",
3703 * with "if " remaining in old->as_string!
3707 int len = old->as_string.length;
3708 /* Concatenate halves */
3709 o_addstr(&old->as_string, ctx->as_string.data);
3710 o_free_unsafe(&ctx->as_string);
3711 /* Find where leading keyword starts in first half */
3712 str = old->as_string.data + len;
3713 if (str > old->as_string.data)
3714 str--; /* skip whitespace after keyword */
3715 while (str > old->as_string.data && isalpha(str[-1]))
3717 /* Ugh, we're done with this horrid hack */
3718 old->command->group_as_string = xstrdup(str);
3719 debug_printf_parse("pop, remembering as:'%s'\n",
3720 old->command->group_as_string);
3723 *ctx = *old; /* physical copy */
3728 #endif /* HAS_KEYWORDS */
3730 /* Word is complete, look at it and update parsing context.
3731 * Normal return is 0. Syntax errors return 1.
3732 * Note: on return, word is reset, but not o_free'd!
3734 static int done_word(o_string *word, struct parse_context *ctx)
3736 struct command *command = ctx->command;
3738 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3739 if (word->length == 0 && !word->has_quoted_part) {
3740 debug_printf_parse("done_word return 0: true null, ignored\n");
3744 if (ctx->pending_redirect) {
3745 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3746 * only if run as "bash", not "sh" */
3747 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3749 * ...the word that follows the redirection operator
3750 * shall be subjected to tilde expansion, parameter expansion,
3751 * command substitution, arithmetic expansion, and quote
3752 * removal. Pathname expansion shall not be performed
3753 * on the word by a non-interactive shell; an interactive
3754 * shell may perform it, but shall do so only when
3755 * the expansion would result in one word."
3757 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3758 /* Cater for >\file case:
3759 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3760 * Same with heredocs:
3761 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3763 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3764 unbackslash(ctx->pending_redirect->rd_filename);
3765 /* Is it <<"HEREDOC"? */
3766 if (word->has_quoted_part) {
3767 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3770 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3771 ctx->pending_redirect = NULL;
3774 # if ENABLE_HUSH_CASE
3775 if (ctx->ctx_dsemicolon
3776 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3778 /* already done when ctx_dsemicolon was set to 1: */
3779 /* ctx->ctx_res_w = RES_MATCH; */
3780 ctx->ctx_dsemicolon = 0;
3783 if (!command->argv /* if it's the first word... */
3784 # if ENABLE_HUSH_LOOPS
3785 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3786 && ctx->ctx_res_w != RES_IN
3788 # if ENABLE_HUSH_CASE
3789 && ctx->ctx_res_w != RES_CASE
3792 int reserved = reserved_word(word, ctx);
3793 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3795 o_reset_to_empty_unquoted(word);
3796 debug_printf_parse("done_word return %d\n",
3797 (ctx->ctx_res_w == RES_SNTX));
3798 return (ctx->ctx_res_w == RES_SNTX);
3801 if (strcmp(word->data, "[[") == 0) {
3802 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3808 if (command->group) {
3809 /* "{ echo foo; } echo bar" - bad */
3810 syntax_error_at(word->data);
3811 debug_printf_parse("done_word return 1: syntax error, "
3812 "groups and arglists don't mix\n");
3816 /* If this word wasn't an assignment, next ones definitely
3817 * can't be assignments. Even if they look like ones. */
3818 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3819 && word->o_assignment != WORD_IS_KEYWORD
3821 word->o_assignment = NOT_ASSIGNMENT;
3823 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3824 command->assignment_cnt++;
3825 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3827 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3828 word->o_assignment = MAYBE_ASSIGNMENT;
3830 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3832 if (word->has_quoted_part
3833 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3834 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3835 /* (otherwise it's known to be not empty and is already safe) */
3837 /* exclude "$@" - it can expand to no word despite "" */
3838 char *p = word->data;
3839 while (p[0] == SPECIAL_VAR_SYMBOL
3840 && (p[1] & 0x7f) == '@'
3841 && p[2] == SPECIAL_VAR_SYMBOL
3846 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3847 debug_print_strings("word appended to argv", command->argv);
3850 #if ENABLE_HUSH_LOOPS
3851 if (ctx->ctx_res_w == RES_FOR) {
3852 if (word->has_quoted_part
3853 || !is_well_formed_var_name(command->argv[0], '\0')
3855 /* bash says just "not a valid identifier" */
3856 syntax_error("not a valid identifier in for");
3859 /* Force FOR to have just one word (variable name) */
3860 /* NB: basically, this makes hush see "for v in ..."
3861 * syntax as if it is "for v; in ...". FOR and IN become
3862 * two pipe structs in parse tree. */
3863 done_pipe(ctx, PIPE_SEQ);
3866 #if ENABLE_HUSH_CASE
3867 /* Force CASE to have just one word */
3868 if (ctx->ctx_res_w == RES_CASE) {
3869 done_pipe(ctx, PIPE_SEQ);
3873 o_reset_to_empty_unquoted(word);
3875 debug_printf_parse("done_word return 0\n");
3880 /* Peek ahead in the input to find out if we have a "&n" construct,
3881 * as in "2>&1", that represents duplicating a file descriptor.
3883 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3884 * REDIRFD_SYNTAX_ERR if syntax error,
3885 * REDIRFD_TO_FILE if no & was seen,
3886 * or the number found.
3889 #define parse_redir_right_fd(as_string, input) \
3890 parse_redir_right_fd(input)
3892 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3898 return REDIRFD_TO_FILE;
3900 ch = i_getch(input); /* get the & */
3901 nommu_addchr(as_string, ch);
3904 ch = i_getch(input);
3905 nommu_addchr(as_string, ch);
3906 return REDIRFD_CLOSE;
3910 while (ch != EOF && isdigit(ch)) {
3911 d = d*10 + (ch-'0');
3913 ch = i_getch(input);
3914 nommu_addchr(as_string, ch);
3919 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3921 bb_error_msg("ambiguous redirect");
3922 return REDIRFD_SYNTAX_ERR;
3925 /* Return code is 0 normal, 1 if a syntax error is detected
3927 static int parse_redirect(struct parse_context *ctx,
3930 struct in_str *input)
3932 struct command *command = ctx->command;
3933 struct redir_struct *redir;
3934 struct redir_struct **redirp;
3937 dup_num = REDIRFD_TO_FILE;
3938 if (style != REDIRECT_HEREDOC) {
3939 /* Check for a '>&1' type redirect */
3940 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3941 if (dup_num == REDIRFD_SYNTAX_ERR)
3944 int ch = i_peek(input);
3945 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3946 if (dup_num) { /* <<-... */
3947 ch = i_getch(input);
3948 nommu_addchr(&ctx->as_string, ch);
3953 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3954 int ch = i_peek(input);
3956 /* >|FILE redirect ("clobbering" >).
3957 * Since we do not support "set -o noclobber" yet,
3958 * >| and > are the same for now. Just eat |.
3960 ch = i_getch(input);
3961 nommu_addchr(&ctx->as_string, ch);
3965 /* Create a new redir_struct and append it to the linked list */
3966 redirp = &command->redirects;
3967 while ((redir = *redirp) != NULL) {
3968 redirp = &(redir->next);
3970 *redirp = redir = xzalloc(sizeof(*redir));
3971 /* redir->next = NULL; */
3972 /* redir->rd_filename = NULL; */
3973 redir->rd_type = style;
3974 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3976 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3977 redir_table[style].descrip);
3979 redir->rd_dup = dup_num;
3980 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3981 /* Erik had a check here that the file descriptor in question
3982 * is legit; I postpone that to "run time"
3983 * A "-" representation of "close me" shows up as a -3 here */
3984 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3985 redir->rd_fd, redir->rd_dup);
3987 #if 0 /* Instead we emit error message at run time */
3988 if (ctx->pending_redirect) {
3989 /* For example, "cmd > <file" */
3990 syntax_error("invalid redirect");
3993 /* Set ctx->pending_redirect, so we know what to do at the
3994 * end of the next parsed word. */
3995 ctx->pending_redirect = redir;
4000 /* If a redirect is immediately preceded by a number, that number is
4001 * supposed to tell which file descriptor to redirect. This routine
4002 * looks for such preceding numbers. In an ideal world this routine
4003 * needs to handle all the following classes of redirects...
4004 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4005 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4006 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4007 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4009 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4011 * ... If n is quoted, the number shall not be recognized as part of
4012 * the redirection expression. For example:
4014 * writes the character 2 into file a"
4015 * We are getting it right by setting ->has_quoted_part on any \<char>
4017 * A -1 return means no valid number was found,
4018 * the caller should use the appropriate default for this redirection.
4020 static int redirect_opt_num(o_string *o)
4024 if (o->data == NULL)
4026 num = bb_strtou(o->data, NULL, 10);
4027 if (errno || num < 0)
4029 o_reset_to_empty_unquoted(o);
4034 #define fetch_till_str(as_string, input, word, skip_tabs) \
4035 fetch_till_str(input, word, skip_tabs)
4037 static char *fetch_till_str(o_string *as_string,
4038 struct in_str *input,
4042 o_string heredoc = NULL_O_STRING;
4044 int prev = 0; /* not \ */
4050 ch = i_getch(input);
4052 nommu_addchr(as_string, ch);
4053 if (ch == '\n' || ch == EOF) {
4055 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4056 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4057 heredoc.data[past_EOL] = '\0';
4058 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4059 return heredoc.data;
4062 /* This is a new line.
4063 * Remember position and backslash-escaping status.
4065 o_addchr(&heredoc, ch);
4068 past_EOL = heredoc.length;
4069 /* Get 1st char of next line, possibly skipping leading tabs */
4071 ch = i_getch(input);
4073 nommu_addchr(as_string, ch);
4074 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4075 /* If this immediately ended the line,
4076 * go back to end-of-line checks.
4079 goto check_heredoc_end;
4084 o_free_unsafe(&heredoc);
4087 o_addchr(&heredoc, ch);
4088 nommu_addchr(as_string, ch);
4089 if (prev == '\\' && ch == '\\')
4090 /* Correctly handle foo\\<eol> (not a line cont.) */
4091 prev = 0; /* not \ */
4097 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4098 * and load them all. There should be exactly heredoc_cnt of them.
4100 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4102 struct pipe *pi = ctx->list_head;
4104 while (pi && heredoc_cnt) {
4106 struct command *cmd = pi->cmds;
4108 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4110 cmd->argv ? cmd->argv[0] : "NONE");
4111 for (i = 0; i < pi->num_cmds; i++) {
4112 struct redir_struct *redir = cmd->redirects;
4114 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4115 i, cmd->argv ? cmd->argv[0] : "NONE");
4117 if (redir->rd_type == REDIRECT_HEREDOC) {
4120 redir->rd_type = REDIRECT_HEREDOC2;
4121 /* redir->rd_dup is (ab)used to indicate <<- */
4122 p = fetch_till_str(&ctx->as_string, input,
4123 redir->rd_filename, redir->rd_dup);
4125 syntax_error("unexpected EOF in here document");
4128 free(redir->rd_filename);
4129 redir->rd_filename = p;
4132 redir = redir->next;
4139 /* Should be 0. If it isn't, it's a parse error */
4141 bb_error_msg_and_die("heredoc BUG 2");
4147 static int run_list(struct pipe *pi);
4149 #define parse_stream(pstring, input, end_trigger) \
4150 parse_stream(input, end_trigger)
4152 static struct pipe *parse_stream(char **pstring,
4153 struct in_str *input,
4157 #if !ENABLE_HUSH_FUNCTIONS
4158 #define parse_group(dest, ctx, input, ch) \
4159 parse_group(ctx, input, ch)
4161 static int parse_group(o_string *dest, struct parse_context *ctx,
4162 struct in_str *input, int ch)
4164 /* dest contains characters seen prior to ( or {.
4165 * Typically it's empty, but for function defs,
4166 * it contains function name (without '()'). */
4167 struct pipe *pipe_list;
4169 struct command *command = ctx->command;
4171 debug_printf_parse("parse_group entered\n");
4172 #if ENABLE_HUSH_FUNCTIONS
4173 if (ch == '(' && !dest->has_quoted_part) {
4175 if (done_word(dest, ctx))
4178 goto skip; /* (... */
4179 if (command->argv[1]) { /* word word ... (... */
4180 syntax_error_unexpected_ch('(');
4183 /* it is "word(..." or "word (..." */
4185 ch = i_getch(input);
4186 while (ch == ' ' || ch == '\t');
4188 syntax_error_unexpected_ch(ch);
4191 nommu_addchr(&ctx->as_string, ch);
4193 ch = i_getch(input);
4194 while (ch == ' ' || ch == '\t' || ch == '\n');
4196 syntax_error_unexpected_ch(ch);
4199 nommu_addchr(&ctx->as_string, ch);
4200 command->cmd_type = CMD_FUNCDEF;
4205 #if 0 /* Prevented by caller */
4206 if (command->argv /* word [word]{... */
4207 || dest->length /* word{... */
4208 || dest->has_quoted_part /* ""{... */
4211 debug_printf_parse("parse_group return 1: "
4212 "syntax error, groups and arglists don't mix\n");
4217 #if ENABLE_HUSH_FUNCTIONS
4223 command->cmd_type = CMD_SUBSHELL;
4225 /* bash does not allow "{echo...", requires whitespace */
4227 if (ch != ' ' && ch != '\t' && ch != '\n'
4228 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4230 syntax_error_unexpected_ch(ch);
4234 ch = i_getch(input);
4235 nommu_addchr(&ctx->as_string, ch);
4241 # define as_string NULL
4243 char *as_string = NULL;
4245 pipe_list = parse_stream(&as_string, input, endch);
4248 o_addstr(&ctx->as_string, as_string);
4250 /* empty ()/{} or parse error? */
4251 if (!pipe_list || pipe_list == ERR_PTR) {
4252 /* parse_stream already emitted error msg */
4255 debug_printf_parse("parse_group return 1: "
4256 "parse_stream returned %p\n", pipe_list);
4259 command->group = pipe_list;
4261 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4262 command->group_as_string = as_string;
4263 debug_printf_parse("end of group, remembering as:'%s'\n",
4264 command->group_as_string);
4268 debug_printf_parse("parse_group return 0\n");
4270 /* command remains "open", available for possible redirects */
4273 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4278 ch = i_getch(input);
4281 ch2 = i_peek(input);
4284 /* backslash+newline, skip it */
4289 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4297 ch2 = i_peek2(input);
4300 /* backslash+newline, skip it */
4306 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4307 /* Subroutines for copying $(...) and `...` things */
4308 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4310 static int add_till_single_quote(o_string *dest, struct in_str *input)
4313 int ch = i_getch(input);
4315 syntax_error_unterm_ch('\'');
4323 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4324 static int add_till_double_quote(o_string *dest, struct in_str *input)
4327 int ch = i_getch(input);
4329 syntax_error_unterm_ch('"');
4334 if (ch == '\\') { /* \x. Copy both chars. */
4336 ch = i_getch(input);
4340 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4345 //if (ch == '$') ...
4348 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4350 * "Within the backquoted style of command substitution, backslash
4351 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4352 * The search for the matching backquote shall be satisfied by the first
4353 * backquote found without a preceding backslash; during this search,
4354 * if a non-escaped backquote is encountered within a shell comment,
4355 * a here-document, an embedded command substitution of the $(command)
4356 * form, or a quoted string, undefined results occur. A single-quoted
4357 * or double-quoted string that begins, but does not end, within the
4358 * "`...`" sequence produces undefined results."
4360 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4362 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4365 int ch = i_getch(input);
4369 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4370 ch = i_getch(input);
4374 && (!in_dquote || ch != '"')
4376 o_addchr(dest, '\\');
4380 syntax_error_unterm_ch('`');
4386 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4387 * quoting and nested ()s.
4388 * "With the $(command) style of command substitution, all characters
4389 * following the open parenthesis to the matching closing parenthesis
4390 * constitute the command. Any valid shell script can be used for command,
4391 * except a script consisting solely of redirections which produces
4392 * unspecified results."
4394 * echo $(echo '(TEST)' BEST) (TEST) BEST
4395 * echo $(echo 'TEST)' BEST) TEST) BEST
4396 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4398 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4399 * can contain arbitrary constructs, just like $(cmd).
4400 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4401 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4403 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4404 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4407 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4408 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4409 char end_char2 = end_ch >> 8;
4411 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4414 ch = i_getch(input);
4416 syntax_error_unterm_ch(end_ch);
4420 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4426 /* we look for closing )) of $((EXPR)) */
4427 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4428 i_getch(input); /* eat second ')' */
4433 if (ch == '(' || ch == '{') {
4434 ch = (ch == '(' ? ')' : '}');
4435 if (!add_till_closing_bracket(dest, input, ch))
4441 if (!add_till_single_quote(dest, input))
4447 if (!add_till_double_quote(dest, input))
4453 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4459 /* \x. Copy verbatim. Important for \(, \) */
4460 ch = i_getch(input);
4462 syntax_error_unterm_ch(')');
4467 /* "backslash+newline", ignore both */
4468 o_delchr(dest); /* undo insertion of '\' */
4478 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4480 /* Return code: 0 for OK, 1 for syntax error */
4482 #define parse_dollar(as_string, dest, input, quote_mask) \
4483 parse_dollar(dest, input, quote_mask)
4484 #define as_string NULL
4486 static int parse_dollar(o_string *as_string,
4488 struct in_str *input, unsigned char quote_mask)
4490 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4492 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4494 ch = i_getch(input);
4495 nommu_addchr(as_string, ch);
4497 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4499 debug_printf_parse(": '%c'\n", ch);
4500 o_addchr(dest, ch | quote_mask);
4502 ch = i_peek_and_eat_bkslash_nl(input);
4503 if (!isalnum(ch) && ch != '_') {
4504 /* End of variable name reached */
4507 ch = i_getch(input);
4508 nommu_addchr(as_string, ch);
4510 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4511 } else if (isdigit(ch)) {
4513 ch = i_getch(input);
4514 nommu_addchr(as_string, ch);
4515 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4516 debug_printf_parse(": '%c'\n", ch);
4517 o_addchr(dest, ch | quote_mask);
4518 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4519 } else switch (ch) {
4521 case '!': /* last bg pid */
4522 case '?': /* last exit code */
4523 case '#': /* number of args */
4524 case '*': /* args */
4525 case '@': /* args */
4526 goto make_one_char_var;
4530 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4532 ch = i_getch(input); /* eat '{' */
4533 nommu_addchr(as_string, ch);
4535 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4536 /* It should be ${?}, or ${#var},
4537 * or even ${?+subst} - operator acting on a special variable,
4538 * or the beginning of variable name.
4541 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4544 syntax_error_unterm_str("${name}");
4545 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4548 nommu_addchr(as_string, ch);
4552 /* It's possible to just call add_till_closing_bracket() at this point.
4553 * However, this regresses some of our testsuite cases
4554 * which check invalid constructs like ${%}.
4555 * Oh well... let's check that the var name part is fine... */
4561 debug_printf_parse(": '%c'\n", ch);
4563 ch = i_getch(input);
4564 nommu_addchr(as_string, ch);
4568 if (!isalnum(ch) && ch != '_') {
4570 unsigned char last_ch;
4571 /* handle parameter expansions
4572 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4574 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4575 if (len_single_ch != '#'
4576 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4577 || i_peek(input) != '}'
4579 goto bad_dollar_syntax;
4581 /* else: it's "length of C" ${#C} op,
4582 * where C is a single char
4583 * special var name, e.g. ${#!}.
4586 /* Eat everything until closing '}' (or ':') */
4590 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4592 /* It's ${var:N[:M]} thing */
4593 end_ch = '}' * 0x100 + ':';
4595 if (BASH_PATTERN_SUBST
4598 /* It's ${var/[/]pattern[/repl]} thing */
4599 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4601 nommu_addchr(as_string, '/');
4604 end_ch = '}' * 0x100 + '/';
4610 #if ENABLE_HUSH_DOLLAR_OPS
4611 last_ch = add_till_closing_bracket(dest, input, end_ch);
4612 if (last_ch == 0) /* error? */
4615 #error Simple code to only allow ${var} is not implemented
4618 o_addstr(as_string, dest->data + pos);
4619 o_addchr(as_string, last_ch);
4622 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4623 && (end_ch & 0xff00)
4625 /* close the first block: */
4626 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4627 /* while parsing N from ${var:N[:M]}
4628 * or pattern from ${var/[/]pattern[/repl]} */
4629 if ((end_ch & 0xff) == last_ch) {
4630 /* got ':' or '/'- parse the rest */
4635 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4636 /* it's ${var:N} - emulate :999999999 */
4637 o_addstr(dest, "999999999");
4638 } /* else: it's ${var/[/]pattern} */
4642 len_single_ch = 0; /* it can't be ${#C} op */
4644 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4647 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4651 ch = i_getch(input);
4652 nommu_addchr(as_string, ch);
4653 # if ENABLE_FEATURE_SH_MATH
4654 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4655 ch = i_getch(input);
4656 nommu_addchr(as_string, ch);
4657 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4658 o_addchr(dest, /*quote_mask |*/ '+');
4661 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4662 return 0; /* error */
4664 o_addstr(as_string, dest->data + pos);
4665 o_addchr(as_string, ')');
4666 o_addchr(as_string, ')');
4668 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4672 # if ENABLE_HUSH_TICK
4673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4674 o_addchr(dest, quote_mask | '`');
4677 if (!add_till_closing_bracket(dest, input, ')'))
4678 return 0; /* error */
4680 o_addstr(as_string, dest->data + pos);
4681 o_addchr(as_string, ')');
4683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4689 ch = i_getch(input);
4690 nommu_addchr(as_string, ch);
4691 ch = i_peek_and_eat_bkslash_nl(input);
4692 if (isalnum(ch)) { /* it's $_name or $_123 */
4697 /* TODO: $_ and $-: */
4698 /* $_ Shell or shell script name; or last argument of last command
4699 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4700 * but in command's env, set to full pathname used to invoke it */
4701 /* $- Option flags set by set builtin or shell options (-i etc) */
4703 o_addQchr(dest, '$');
4705 debug_printf_parse("parse_dollar return 1 (ok)\n");
4711 # if BASH_PATTERN_SUBST
4712 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4713 encode_string(dest, input, dquote_end, process_bkslash)
4715 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4716 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4717 encode_string(dest, input, dquote_end)
4719 #define as_string NULL
4723 # if BASH_PATTERN_SUBST
4724 /* all parameters are needed, no macro tricks */
4726 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4727 encode_string(as_string, dest, input, dquote_end)
4730 static int encode_string(o_string *as_string,
4732 struct in_str *input,
4734 int process_bkslash)
4736 #if !BASH_PATTERN_SUBST
4737 const int process_bkslash = 1;
4743 ch = i_getch(input);
4745 nommu_addchr(as_string, ch);
4746 if (ch == dquote_end) { /* may be only '"' or EOF */
4747 debug_printf_parse("encode_string return 1 (ok)\n");
4750 /* note: can't move it above ch == dquote_end check! */
4752 syntax_error_unterm_ch('"');
4753 return 0; /* error */
4757 next = i_peek(input);
4759 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4760 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4761 if (process_bkslash && ch == '\\') {
4763 syntax_error("\\<eof>");
4767 * "The backslash retains its special meaning [in "..."]
4768 * only when followed by one of the following characters:
4769 * $, `, ", \, or <newline>. A double quote may be quoted
4770 * within double quotes by preceding it with a backslash."
4771 * NB: in (unquoted) heredoc, above does not apply to ",
4772 * therefore we check for it by "next == dquote_end" cond.
4774 if (next == dquote_end || strchr("$`\\\n", next)) {
4775 ch = i_getch(input); /* eat next */
4777 goto again; /* skip \<newline> */
4778 } /* else: ch remains == '\\', and we double it below: */
4779 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4780 nommu_addchr(as_string, ch);
4784 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4785 debug_printf_parse("encode_string return 0: "
4786 "parse_dollar returned 0 (error)\n");
4791 #if ENABLE_HUSH_TICK
4793 //unsigned pos = dest->length;
4794 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4795 o_addchr(dest, 0x80 | '`');
4796 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4797 return 0; /* error */
4798 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4799 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4803 o_addQchr(dest, ch);
4809 * Scan input until EOF or end_trigger char.
4810 * Return a list of pipes to execute, or NULL on EOF
4811 * or if end_trigger character is met.
4812 * On syntax error, exit if shell is not interactive,
4813 * reset parsing machinery and start parsing anew,
4814 * or return ERR_PTR.
4816 static struct pipe *parse_stream(char **pstring,
4817 struct in_str *input,
4820 struct parse_context ctx;
4821 o_string dest = NULL_O_STRING;
4824 /* Single-quote triggers a bypass of the main loop until its mate is
4825 * found. When recursing, quote state is passed in via dest->o_expflags.
4827 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4828 end_trigger ? end_trigger : 'X');
4831 /* If very first arg is "" or '', dest.data may end up NULL.
4832 * Preventing this: */
4833 o_addchr(&dest, '\0');
4836 /* We used to separate words on $IFS here. This was wrong.
4837 * $IFS is used only for word splitting when $var is expanded,
4838 * here we should use blank chars as separators, not $IFS
4841 if (MAYBE_ASSIGNMENT != 0)
4842 dest.o_assignment = MAYBE_ASSIGNMENT;
4843 initialize_context(&ctx);
4846 const char *is_blank;
4847 const char *is_special;
4851 redir_type redir_style;
4853 ch = i_getch(input);
4854 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4855 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4860 syntax_error_unterm_str("here document");
4863 if (end_trigger == ')') {
4864 syntax_error_unterm_ch('(');
4867 if (end_trigger == '}') {
4868 syntax_error_unterm_ch('{');
4872 if (done_word(&dest, &ctx)) {
4876 done_pipe(&ctx, PIPE_SEQ);
4878 /* If we got nothing... */
4879 /* (this makes bare "&" cmd a no-op.
4880 * bash says: "syntax error near unexpected token '&'") */
4881 if (pi->num_cmds == 0
4882 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4888 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4890 *pstring = ctx.as_string.data;
4892 o_free_unsafe(&ctx.as_string);
4895 debug_printf_parse("parse_stream return %p\n", pi);
4898 nommu_addchr(&ctx.as_string, ch);
4902 next = i_peek(input);
4904 is_special = "{}<>;&|()#'" /* special outside of "str" */
4905 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4906 /* Are { and } special here? */
4907 if (ctx.command->argv /* word [word]{... - non-special */
4908 || dest.length /* word{... - non-special */
4909 || dest.has_quoted_part /* ""{... - non-special */
4910 || (next != ';' /* }; - special */
4911 && next != ')' /* }) - special */
4912 && next != '(' /* {( - special */
4913 && next != '&' /* }& and }&& ... - special */
4914 && next != '|' /* }|| ... - special */
4915 && !strchr(defifs, next) /* {word - non-special */
4918 /* They are not special, skip "{}" */
4921 is_special = strchr(is_special, ch);
4922 is_blank = strchr(defifs, ch);
4924 if (!is_special && !is_blank) { /* ordinary char */
4926 o_addQchr(&dest, ch);
4927 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4928 || dest.o_assignment == WORD_IS_KEYWORD)
4930 && is_well_formed_var_name(dest.data, '=')
4932 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4933 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4939 if (done_word(&dest, &ctx)) {
4943 /* Is this a case when newline is simply ignored?
4945 * "cmd | <newline> cmd ..."
4946 * "case ... in <newline> word) ..."
4948 if (IS_NULL_CMD(ctx.command)
4949 && dest.length == 0 && !dest.has_quoted_part
4951 /* This newline can be ignored. But...
4952 * Without check #1, interactive shell
4953 * ignores even bare <newline>,
4954 * and shows the continuation prompt:
4955 * ps1_prompt$ <enter>
4956 * ps2> _ <=== wrong, should be ps1
4957 * Without check #2, "cmd & <newline>"
4958 * is similarly mistreated.
4959 * (BTW, this makes "cmd & cmd"
4960 * and "cmd && cmd" non-orthogonal.
4961 * Really, ask yourself, why
4962 * "cmd && <newline>" doesn't start
4963 * cmd but waits for more input?
4964 * The only reason is that it might be
4965 * a "cmd1 && <nl> cmd2 &" construct,
4966 * cmd1 may need to run in BG).
4968 struct pipe *pi = ctx.list_head;
4969 if (pi->num_cmds != 0 /* check #1 */
4970 && pi->followup != PIPE_BG /* check #2 */
4975 /* Treat newline as a command separator. */
4976 done_pipe(&ctx, PIPE_SEQ);
4977 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4979 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4984 dest.o_assignment = MAYBE_ASSIGNMENT;
4985 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4987 /* note: if (is_blank) continue;
4988 * will still trigger for us */
4992 /* "cmd}" or "cmd }..." without semicolon or &:
4993 * } is an ordinary char in this case, even inside { cmd; }
4994 * Pathological example: { ""}; } should exec "}" cmd
4997 if (dest.length != 0 /* word} */
4998 || dest.has_quoted_part /* ""} */
5002 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5003 /* Generally, there should be semicolon: "cmd; }"
5004 * However, bash allows to omit it if "cmd" is
5005 * a group. Examples:
5008 * { echo 0 >&2 | { echo 1; } }
5009 * { while false; do :; done }
5010 * { case a in b) ;; esac }
5012 if (ctx.command->group)
5016 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5017 /* Can't be an end of {cmd}, skip the check */
5018 goto skip_end_trigger;
5019 /* else: } does terminate a group */
5022 if (end_trigger && end_trigger == ch
5023 && (ch != ';' || heredoc_cnt == 0)
5024 #if ENABLE_HUSH_CASE
5026 || ctx.ctx_res_w != RES_MATCH
5027 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5032 /* This is technically valid:
5033 * { cat <<HERE; }; echo Ok
5037 * but we don't support this.
5038 * We require heredoc to be in enclosing {}/(),
5041 syntax_error_unterm_str("here document");
5044 if (done_word(&dest, &ctx)) {
5047 done_pipe(&ctx, PIPE_SEQ);
5048 dest.o_assignment = MAYBE_ASSIGNMENT;
5049 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5050 /* Do we sit outside of any if's, loops or case's? */
5052 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5056 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5058 *pstring = ctx.as_string.data;
5060 o_free_unsafe(&ctx.as_string);
5062 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5063 /* Example: bare "{ }", "()" */
5064 G.last_exitcode = 2; /* bash compat */
5065 syntax_error_unexpected_ch(ch);
5068 debug_printf_parse("parse_stream return %p: "
5069 "end_trigger char found\n",
5072 return ctx.list_head;
5079 /* Catch <, > before deciding whether this word is
5080 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5083 redir_fd = redirect_opt_num(&dest);
5084 if (done_word(&dest, &ctx)) {
5087 redir_style = REDIRECT_OVERWRITE;
5089 redir_style = REDIRECT_APPEND;
5090 ch = i_getch(input);
5091 nommu_addchr(&ctx.as_string, ch);
5094 else if (next == '(') {
5095 syntax_error(">(process) not supported");
5099 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5101 continue; /* back to top of while (1) */
5103 redir_fd = redirect_opt_num(&dest);
5104 if (done_word(&dest, &ctx)) {
5107 redir_style = REDIRECT_INPUT;
5109 redir_style = REDIRECT_HEREDOC;
5111 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5112 ch = i_getch(input);
5113 nommu_addchr(&ctx.as_string, ch);
5114 } else if (next == '>') {
5115 redir_style = REDIRECT_IO;
5116 ch = i_getch(input);
5117 nommu_addchr(&ctx.as_string, ch);
5120 else if (next == '(') {
5121 syntax_error("<(process) not supported");
5125 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5127 continue; /* back to top of while (1) */
5129 if (dest.length == 0 && !dest.has_quoted_part) {
5130 /* skip "#comment" */
5133 if (ch == EOF || ch == '\n')
5136 /* note: we do not add it to &ctx.as_string */
5138 nommu_addchr(&ctx.as_string, '\n');
5139 continue; /* back to top of while (1) */
5144 /* It's "\<newline>" */
5146 /* Remove trailing '\' from ctx.as_string */
5147 ctx.as_string.data[--ctx.as_string.length] = '\0';
5149 ch = i_getch(input); /* eat it */
5150 continue; /* back to top of while (1) */
5155 if (dest.o_assignment == MAYBE_ASSIGNMENT
5156 /* check that we are not in word in "a=1 2>word b=1": */
5157 && !ctx.pending_redirect
5159 /* ch is a special char and thus this word
5160 * cannot be an assignment */
5161 dest.o_assignment = NOT_ASSIGNMENT;
5162 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5165 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5168 case '#': /* non-comment #: "echo a#b" etc */
5169 o_addQchr(&dest, ch);
5173 syntax_error("\\<eof>");
5176 ch = i_getch(input);
5177 /* note: ch != '\n' (that case does not reach this place) */
5178 o_addchr(&dest, '\\');
5179 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5180 o_addchr(&dest, ch);
5181 nommu_addchr(&ctx.as_string, ch);
5182 /* Example: echo Hello \2>file
5183 * we need to know that word 2 is quoted */
5184 dest.has_quoted_part = 1;
5187 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5188 debug_printf_parse("parse_stream parse error: "
5189 "parse_dollar returned 0 (error)\n");
5194 dest.has_quoted_part = 1;
5195 if (next == '\'' && !ctx.pending_redirect) {
5196 insert_empty_quoted_str_marker:
5197 nommu_addchr(&ctx.as_string, next);
5198 i_getch(input); /* eat second ' */
5199 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5200 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5203 ch = i_getch(input);
5205 syntax_error_unterm_ch('\'');
5208 nommu_addchr(&ctx.as_string, ch);
5211 o_addqchr(&dest, ch);
5216 dest.has_quoted_part = 1;
5217 if (next == '"' && !ctx.pending_redirect)
5218 goto insert_empty_quoted_str_marker;
5219 if (dest.o_assignment == NOT_ASSIGNMENT)
5220 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5221 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5223 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5225 #if ENABLE_HUSH_TICK
5227 USE_FOR_NOMMU(unsigned pos;)
5229 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5230 o_addchr(&dest, '`');
5231 USE_FOR_NOMMU(pos = dest.length;)
5232 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5235 o_addstr(&ctx.as_string, dest.data + pos);
5236 o_addchr(&ctx.as_string, '`');
5238 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5239 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5244 #if ENABLE_HUSH_CASE
5247 if (done_word(&dest, &ctx)) {
5250 done_pipe(&ctx, PIPE_SEQ);
5251 #if ENABLE_HUSH_CASE
5252 /* Eat multiple semicolons, detect
5253 * whether it means something special */
5258 ch = i_getch(input);
5259 nommu_addchr(&ctx.as_string, ch);
5260 if (ctx.ctx_res_w == RES_CASE_BODY) {
5261 ctx.ctx_dsemicolon = 1;
5262 ctx.ctx_res_w = RES_MATCH;
5268 /* We just finished a cmd. New one may start
5269 * with an assignment */
5270 dest.o_assignment = MAYBE_ASSIGNMENT;
5271 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5274 if (done_word(&dest, &ctx)) {
5278 ch = i_getch(input);
5279 nommu_addchr(&ctx.as_string, ch);
5280 done_pipe(&ctx, PIPE_AND);
5282 done_pipe(&ctx, PIPE_BG);
5286 if (done_word(&dest, &ctx)) {
5289 #if ENABLE_HUSH_CASE
5290 if (ctx.ctx_res_w == RES_MATCH)
5291 break; /* we are in case's "word | word)" */
5293 if (next == '|') { /* || */
5294 ch = i_getch(input);
5295 nommu_addchr(&ctx.as_string, ch);
5296 done_pipe(&ctx, PIPE_OR);
5298 /* we could pick up a file descriptor choice here
5299 * with redirect_opt_num(), but bash doesn't do it.
5300 * "echo foo 2| cat" yields "foo 2". */
5305 #if ENABLE_HUSH_CASE
5306 /* "case... in [(]word)..." - skip '(' */
5307 if (ctx.ctx_res_w == RES_MATCH
5308 && ctx.command->argv == NULL /* not (word|(... */
5309 && dest.length == 0 /* not word(... */
5310 && dest.has_quoted_part == 0 /* not ""(... */
5316 if (parse_group(&dest, &ctx, input, ch) != 0) {
5321 #if ENABLE_HUSH_CASE
5322 if (ctx.ctx_res_w == RES_MATCH)
5326 /* proper use of this character is caught by end_trigger:
5327 * if we see {, we call parse_group(..., end_trigger='}')
5328 * and it will match } earlier (not here). */
5329 G.last_exitcode = 2;
5330 syntax_error_unexpected_ch(ch);
5334 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5339 G.last_exitcode = 1;
5342 struct parse_context *pctx;
5343 IF_HAS_KEYWORDS(struct parse_context *p2;)
5345 /* Clean up allocated tree.
5346 * Sample for finding leaks on syntax error recovery path.
5347 * Run it from interactive shell, watch pmap `pidof hush`.
5348 * while if false; then false; fi; do break; fi
5349 * Samples to catch leaks at execution:
5350 * while if (true | { true;}); then echo ok; fi; do break; done
5351 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5355 /* Update pipe/command counts,
5356 * otherwise freeing may miss some */
5357 done_pipe(pctx, PIPE_SEQ);
5358 debug_printf_clean("freeing list %p from ctx %p\n",
5359 pctx->list_head, pctx);
5360 debug_print_tree(pctx->list_head, 0);
5361 free_pipe_list(pctx->list_head);
5362 debug_printf_clean("freed list %p\n", pctx->list_head);
5364 o_free_unsafe(&pctx->as_string);
5366 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5370 IF_HAS_KEYWORDS(pctx = p2;)
5371 } while (HAS_KEYWORDS && pctx);
5384 /*** Execution routines ***/
5386 /* Expansion can recurse, need forward decls: */
5387 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5388 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5389 #define expand_string_to_string(str, do_unbackslash) \
5390 expand_string_to_string(str)
5392 static char *expand_string_to_string(const char *str, int do_unbackslash);
5393 #if ENABLE_HUSH_TICK
5394 static int process_command_subs(o_string *dest, const char *s);
5397 /* expand_strvec_to_strvec() takes a list of strings, expands
5398 * all variable references within and returns a pointer to
5399 * a list of expanded strings, possibly with larger number
5400 * of strings. (Think VAR="a b"; echo $VAR).
5401 * This new list is allocated as a single malloc block.
5402 * NULL-terminated list of char* pointers is at the beginning of it,
5403 * followed by strings themselves.
5404 * Caller can deallocate entire list by single free(list). */
5406 /* A horde of its helpers come first: */
5408 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5410 while (--len >= 0) {
5413 #if ENABLE_HUSH_BRACE_EXPANSION
5414 if (c == '{' || c == '}') {
5415 /* { -> \{, } -> \} */
5417 /* And now we want to add { or } and continue:
5420 * luckily, just falling through achieves this.
5426 /* \z -> \\\z; \<eol> -> \\<eol> */
5431 o_addchr(o, *str++);
5437 /* Store given string, finalizing the word and starting new one whenever
5438 * we encounter IFS char(s). This is used for expanding variable values.
5439 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5440 * Return in *ended_with_ifs:
5441 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5443 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5445 int last_is_ifs = 0;
5450 if (!*str) /* EOL - do not finalize word */
5452 word_len = strcspn(str, G.ifs);
5454 /* We have WORD_LEN leading non-IFS chars */
5455 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5456 o_addblock(output, str, word_len);
5458 /* Protect backslashes against globbing up :)
5459 * Example: "v='\*'; echo b$v" prints "b\*"
5460 * (and does not try to glob on "*")
5462 o_addblock_duplicate_backslash(output, str, word_len);
5463 /*/ Why can't we do it easier? */
5464 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5465 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5469 if (!*str) /* EOL - do not finalize word */
5473 /* We know str here points to at least one IFS char */
5475 str += strspn(str, G.ifs); /* skip IFS chars */
5476 if (!*str) /* EOL - do not finalize word */
5479 /* Start new word... but not always! */
5480 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5481 if (output->has_quoted_part
5482 /* Case "v=' a'; echo $v":
5483 * here nothing precedes the space in $v expansion,
5484 * therefore we should not finish the word
5485 * (IOW: if there *is* word to finalize, only then do it):
5487 || (n > 0 && output->data[output->length - 1])
5489 o_addchr(output, '\0');
5490 debug_print_list("expand_on_ifs", output, n);
5491 n = o_save_ptr(output, n);
5496 *ended_with_ifs = last_is_ifs;
5497 debug_print_list("expand_on_ifs[1]", output, n);
5501 /* Helper to expand $((...)) and heredoc body. These act as if
5502 * they are in double quotes, with the exception that they are not :).
5503 * Just the rules are similar: "expand only $var and `cmd`"
5505 * Returns malloced string.
5506 * As an optimization, we return NULL if expansion is not needed.
5508 #if !BASH_PATTERN_SUBST
5509 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5510 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5511 encode_then_expand_string(str)
5513 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5515 #if !BASH_PATTERN_SUBST
5516 const int do_unbackslash = 1;
5519 struct in_str input;
5520 o_string dest = NULL_O_STRING;
5522 if (!strchr(str, '$')
5523 && !strchr(str, '\\')
5524 #if ENABLE_HUSH_TICK
5525 && !strchr(str, '`')
5531 /* We need to expand. Example:
5532 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5534 setup_string_in_str(&input, str);
5535 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5536 //TODO: error check (encode_string returns 0 on error)?
5537 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5538 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5539 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5540 o_free_unsafe(&dest);
5544 #if ENABLE_FEATURE_SH_MATH
5545 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5547 arith_state_t math_state;
5551 math_state.lookupvar = get_local_var_value;
5552 math_state.setvar = set_local_var_from_halves;
5553 //math_state.endofname = endofname;
5554 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5555 res = arith(&math_state, exp_str ? exp_str : arg);
5558 *errmsg_p = math_state.errmsg;
5559 if (math_state.errmsg)
5560 msg_and_die_if_script(math_state.errmsg);
5565 #if BASH_PATTERN_SUBST
5566 /* ${var/[/]pattern[/repl]} helpers */
5567 static char *strstr_pattern(char *val, const char *pattern, int *size)
5570 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5571 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5578 /* Optimization: if "*pat" did not match the start of "string",
5579 * we know that "tring", "ring" etc will not match too:
5581 if (pattern[0] == '*')
5586 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5588 char *result = NULL;
5589 unsigned res_len = 0;
5590 unsigned repl_len = strlen(repl);
5594 char *s = strstr_pattern(val, pattern, &size);
5598 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5599 strcpy(mempcpy(result + res_len, val, s - val), repl);
5600 res_len += (s - val) + repl_len;
5601 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5607 if (*val && result) {
5608 result = xrealloc(result, res_len + strlen(val) + 1);
5609 strcpy(result + res_len, val);
5610 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5612 debug_printf_varexp("result:'%s'\n", result);
5615 #endif /* BASH_PATTERN_SUBST */
5618 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5620 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5622 const char *val = NULL;
5623 char *to_be_freed = NULL;
5628 char exp_save = exp_save; /* for compiler */
5629 char *exp_saveptr; /* points to expansion operator */
5630 char *exp_word = exp_word; /* for compiler */
5633 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5635 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5637 first_char = arg[0] = arg0 & 0x7f;
5640 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5641 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5642 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5643 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5645 /* It must be length operator: ${#var} */
5649 /* Maybe handle parameter expansion */
5650 if (exp_saveptr /* if 2nd char is one of expansion operators */
5651 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5653 /* ${?:0}, ${#[:]%0} etc */
5654 exp_saveptr = var + 1;
5656 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5657 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5659 exp_op = exp_save = *exp_saveptr;
5661 exp_word = exp_saveptr + 1;
5662 if (exp_op == ':') {
5663 exp_op = *exp_word++;
5664 //TODO: try ${var:} and ${var:bogus} in non-bash config
5666 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5668 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5673 *exp_saveptr = '\0';
5674 } /* else: it's not an expansion op, but bare ${var} */
5677 /* Look up the variable in question */
5678 if (isdigit(var[0])) {
5679 /* parse_dollar should have vetted var for us */
5680 int n = xatoi_positive(var);
5681 if (n < G.global_argc)
5682 val = G.global_argv[n];
5683 /* else val remains NULL: $N with too big N */
5687 val = utoa(G.root_pid);
5689 case '!': /* bg pid */
5690 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5692 case '?': /* exitcode */
5693 val = utoa(G.last_exitcode);
5695 case '#': /* argc */
5696 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5699 val = get_local_var_value(var);
5703 /* Handle any expansions */
5704 if (exp_op == 'L') {
5705 reinit_unicode_for_hush();
5706 debug_printf_expand("expand: length(%s)=", val);
5707 val = utoa(val ? unicode_strlen(val) : 0);
5708 debug_printf_expand("%s\n", val);
5709 } else if (exp_op) {
5710 if (exp_op == '%' || exp_op == '#') {
5711 /* Standard-mandated substring removal ops:
5712 * ${parameter%word} - remove smallest suffix pattern
5713 * ${parameter%%word} - remove largest suffix pattern
5714 * ${parameter#word} - remove smallest prefix pattern
5715 * ${parameter##word} - remove largest prefix pattern
5717 * Word is expanded to produce a glob pattern.
5718 * Then var's value is matched to it and matching part removed.
5720 if (val && val[0]) {
5724 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5725 if (exp_op == *exp_word) /* ## or %% */
5727 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5729 exp_word = exp_exp_word;
5730 /* HACK ALERT. We depend here on the fact that
5731 * G.global_argv and results of utoa and get_local_var_value
5732 * are actually in writable memory:
5733 * scan_and_match momentarily stores NULs there. */
5735 loc = scan_and_match(t, exp_word, scan_flags);
5736 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5737 // exp_op, t, exp_word, loc);
5739 if (loc) { /* match was found */
5740 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5741 val = loc; /* take right part */
5743 val = to_be_freed = xstrndup(val, loc - val); /* left */
5747 #if BASH_PATTERN_SUBST
5748 else if (exp_op == '/' || exp_op == '\\') {
5749 /* It's ${var/[/]pattern[/repl]} thing.
5750 * Note that in encoded form it has TWO parts:
5751 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5752 * and if // is used, it is encoded as \:
5753 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5755 /* Empty variable always gives nothing: */
5756 // "v=''; echo ${v/*/w}" prints "", not "w"
5757 if (val && val[0]) {
5758 /* pattern uses non-standard expansion.
5759 * repl should be unbackslashed and globbed
5760 * by the usual expansion rules:
5762 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5763 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5764 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5765 * v='a bz'; echo ${v/a*z/\z} prints "z"
5766 * (note that a*z _pattern_ is never globbed!)
5768 char *pattern, *repl, *t;
5769 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5771 pattern = xstrdup(exp_word);
5772 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5773 *p++ = SPECIAL_VAR_SYMBOL;
5775 p = strchr(p, SPECIAL_VAR_SYMBOL);
5777 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5778 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5779 /* HACK ALERT. We depend here on the fact that
5780 * G.global_argv and results of utoa and get_local_var_value
5781 * are actually in writable memory:
5782 * replace_pattern momentarily stores NULs there. */
5784 to_be_freed = replace_pattern(t,
5786 (repl ? repl : exp_word),
5788 if (to_be_freed) /* at least one replace happened */
5794 #endif /* BASH_PATTERN_SUBST */
5795 else if (exp_op == ':') {
5796 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5797 /* It's ${var:N[:M]} bashism.
5798 * Note that in encoded form it has TWO parts:
5799 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5804 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5807 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5808 *p++ = SPECIAL_VAR_SYMBOL;
5810 p = strchr(p, SPECIAL_VAR_SYMBOL);
5812 len = expand_and_evaluate_arith(exp_word, &errmsg);
5815 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5817 /* negative beg counts from the end */
5818 beg = (arith_t)strlen(val) + beg;
5819 if (beg < 0) /* ${v: -999999} is "" */
5822 debug_printf_varexp("from val:'%s'\n", val);
5824 /* in bash, len=-n means strlen()-n */
5825 len = (arith_t)strlen(val) - beg + len;
5826 if (len < 0) /* bash compat */
5827 msg_and_die_if_script("%s: substring expression < 0", var);
5829 if (len <= 0 || !val || beg >= strlen(val)) {
5833 /* Paranoia. What if user entered 9999999999999
5834 * which fits in arith_t but not int? */
5837 val = to_be_freed = xstrndup(val + beg, len);
5839 debug_printf_varexp("val:'%s'\n", val);
5840 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5841 msg_and_die_if_script("malformed ${%s:...}", var);
5844 } else { /* one of "-=+?" */
5845 /* Standard-mandated substitution ops:
5846 * ${var?word} - indicate error if unset
5847 * If var is unset, word (or a message indicating it is unset
5848 * if word is null) is written to standard error
5849 * and the shell exits with a non-zero exit status.
5850 * Otherwise, the value of var is substituted.
5851 * ${var-word} - use default value
5852 * If var is unset, word is substituted.
5853 * ${var=word} - assign and use default value
5854 * If var is unset, word is assigned to var.
5855 * In all cases, final value of var is substituted.
5856 * ${var+word} - use alternative value
5857 * If var is unset, null is substituted.
5858 * Otherwise, word is substituted.
5860 * Word is subjected to tilde expansion, parameter expansion,
5861 * command substitution, and arithmetic expansion.
5862 * If word is not needed, it is not expanded.
5864 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5865 * but also treat null var as if it is unset.
5867 int use_word = (!val || ((exp_save == ':') && !val[0]));
5869 use_word = !use_word;
5870 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5871 (exp_save == ':') ? "true" : "false", use_word);
5873 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5875 exp_word = to_be_freed;
5876 if (exp_op == '?') {
5877 /* mimic bash message */
5878 msg_and_die_if_script("%s: %s",
5882 : "parameter null or not set"
5883 /* ash has more specific messages, a-la: */
5884 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
5886 //TODO: how interactive bash aborts expansion mid-command?
5891 if (exp_op == '=') {
5892 /* ${var=[word]} or ${var:=[word]} */
5893 if (isdigit(var[0]) || var[0] == '#') {
5894 /* mimic bash message */
5895 msg_and_die_if_script("$%s: cannot assign in this way", var);
5898 char *new_var = xasprintf("%s=%s", var, val);
5899 set_local_var(new_var, /*flag:*/ 0);
5903 } /* one of "-=+?" */
5905 *exp_saveptr = exp_save;
5911 *to_be_freed_pp = to_be_freed;
5915 /* Expand all variable references in given string, adding words to list[]
5916 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5917 * to be filled). This routine is extremely tricky: has to deal with
5918 * variables/parameters with whitespace, $* and $@, and constructs like
5919 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5920 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5922 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5923 * expansion of right-hand side of assignment == 1-element expand.
5925 char cant_be_null = 0; /* only bit 0x80 matters */
5926 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5929 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5930 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5931 debug_print_list("expand_vars_to_list", output, n);
5932 n = o_save_ptr(output, n);
5933 debug_print_list("expand_vars_to_list[0]", output, n);
5935 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5937 char *to_be_freed = NULL;
5938 const char *val = NULL;
5939 #if ENABLE_HUSH_TICK
5940 o_string subst_result = NULL_O_STRING;
5942 #if ENABLE_FEATURE_SH_MATH
5943 char arith_buf[sizeof(arith_t)*3 + 2];
5947 o_addchr(output, '\0');
5948 n = o_save_ptr(output, n);
5952 o_addblock(output, arg, p - arg);
5953 debug_print_list("expand_vars_to_list[1]", output, n);
5955 p = strchr(p, SPECIAL_VAR_SYMBOL);
5957 /* Fetch special var name (if it is indeed one of them)
5958 * and quote bit, force the bit on if singleword expansion -
5959 * important for not getting v=$@ expand to many words. */
5960 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5962 /* Is this variable quoted and thus expansion can't be null?
5963 * "$@" is special. Even if quoted, it can still
5964 * expand to nothing (not even an empty string),
5965 * thus it is excluded. */
5966 if ((first_ch & 0x7f) != '@')
5967 cant_be_null |= first_ch;
5969 switch (first_ch & 0x7f) {
5970 /* Highest bit in first_ch indicates that var is double-quoted */
5974 if (!G.global_argv[1])
5977 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5978 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5979 while (G.global_argv[i]) {
5980 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5981 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5982 if (G.global_argv[i++][0] && G.global_argv[i]) {
5983 /* this argv[] is not empty and not last:
5984 * put terminating NUL, start new word */
5985 o_addchr(output, '\0');
5986 debug_print_list("expand_vars_to_list[2]", output, n);
5987 n = o_save_ptr(output, n);
5988 debug_print_list("expand_vars_to_list[3]", output, n);
5992 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5993 * and in this case should treat it like '$*' - see 'else...' below */
5994 if (first_ch == ('@'|0x80) /* quoted $@ */
5995 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5998 o_addQstr(output, G.global_argv[i]);
5999 if (++i >= G.global_argc)
6001 o_addchr(output, '\0');
6002 debug_print_list("expand_vars_to_list[4]", output, n);
6003 n = o_save_ptr(output, n);
6005 } else { /* quoted $* (or v="$@" case): add as one word */
6007 o_addQstr(output, G.global_argv[i]);
6008 if (!G.global_argv[++i])
6011 o_addchr(output, G.ifs[0]);
6013 output->has_quoted_part = 1;
6017 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6018 /* "Empty variable", used to make "" etc to not disappear */
6019 output->has_quoted_part = 1;
6021 cant_be_null = 0x80;
6023 #if ENABLE_HUSH_TICK
6024 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6025 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6027 /* Can't just stuff it into output o_string,
6028 * expanded result may need to be globbed
6030 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6031 G.last_exitcode = process_command_subs(&subst_result, arg);
6032 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6033 val = subst_result.data;
6036 #if ENABLE_FEATURE_SH_MATH
6037 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6040 arg++; /* skip '+' */
6041 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6042 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6043 res = expand_and_evaluate_arith(arg, NULL);
6044 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6045 sprintf(arith_buf, ARITH_FMT, res);
6051 val = expand_one_var(&to_be_freed, arg, &p);
6052 IF_HUSH_TICK(store_val:)
6053 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6054 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6055 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6056 if (val && val[0]) {
6057 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6060 } else { /* quoted $VAR, val will be appended below */
6061 output->has_quoted_part = 1;
6062 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6063 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6066 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6068 if (val && val[0]) {
6069 o_addQstr(output, val);
6073 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6074 * Do the check to avoid writing to a const string. */
6075 if (*p != SPECIAL_VAR_SYMBOL)
6076 *p = SPECIAL_VAR_SYMBOL;
6078 #if ENABLE_HUSH_TICK
6079 o_free(&subst_result);
6082 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6086 o_addchr(output, '\0');
6087 n = o_save_ptr(output, n);
6089 debug_print_list("expand_vars_to_list[a]", output, n);
6090 /* this part is literal, and it was already pre-quoted
6091 * if needed (much earlier), do not use o_addQstr here! */
6092 o_addstr_with_NUL(output, arg);
6093 debug_print_list("expand_vars_to_list[b]", output, n);
6094 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6095 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6098 /* allow to reuse list[n] later without re-growth */
6099 output->has_empty_slot = 1;
6101 o_addchr(output, '\0');
6107 static char **expand_variables(char **argv, unsigned expflags)
6111 o_string output = NULL_O_STRING;
6113 output.o_expflags = expflags;
6117 n = expand_vars_to_list(&output, n, *argv);
6120 debug_print_list("expand_variables", &output, n);
6122 /* output.data (malloced in one block) gets returned in "list" */
6123 list = o_finalize_list(&output, n);
6124 debug_print_strings("expand_variables[1]", list);
6128 static char **expand_strvec_to_strvec(char **argv)
6130 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6134 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6136 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6140 /* Used for expansion of right hand of assignments,
6141 * $((...)), heredocs, variable espansion parts.
6143 * NB: should NOT do globbing!
6144 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6146 static char *expand_string_to_string(const char *str, int do_unbackslash)
6148 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6149 const int do_unbackslash = 1;
6151 char *argv[2], **list;
6153 debug_printf_expand("string_to_string<='%s'\n", str);
6154 /* This is generally an optimization, but it also
6155 * handles "", which otherwise trips over !list[0] check below.
6156 * (is this ever happens that we actually get str="" here?)
6158 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6159 //TODO: Can use on strings with \ too, just unbackslash() them?
6160 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6161 return xstrdup(str);
6164 argv[0] = (char*)str;
6166 list = expand_variables(argv, do_unbackslash
6167 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6168 : EXP_FLAG_SINGLEWORD
6171 if (!list[0] || list[1])
6172 bb_error_msg_and_die("BUG in varexp2");
6173 /* actually, just move string 2*sizeof(char*) bytes back */
6174 overlapping_strcpy((char*)list, list[0]);
6176 unbackslash((char*)list);
6177 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6181 /* Used for "eval" builtin and case string */
6182 static char* expand_strvec_to_string(char **argv)
6186 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6187 /* Convert all NULs to spaces */
6192 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6193 bb_error_msg_and_die("BUG in varexp3");
6194 /* bash uses ' ' regardless of $IFS contents */
6199 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6200 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6204 static char **expand_assignments(char **argv, int count)
6209 G.expanded_assignments = p = NULL;
6210 /* Expand assignments into one string each */
6211 for (i = 0; i < count; i++) {
6212 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6214 G.expanded_assignments = NULL;
6219 static void switch_off_special_sigs(unsigned mask)
6222 while ((mask >>= 1) != 0) {
6226 #if ENABLE_HUSH_TRAP
6228 if (G_traps[sig] && !G_traps[sig][0])
6229 /* trap is '', has to remain SIG_IGN */
6232 G_traps[sig] = NULL;
6235 /* We are here only if no trap or trap was not '' */
6236 install_sighandler(sig, SIG_DFL);
6242 void re_execute_shell(char ***to_free, const char *s,
6243 char *g_argv0, char **g_argv,
6244 char **builtin_argv) NORETURN;
6246 static void reset_traps_to_defaults(void)
6248 /* This function is always called in a child shell
6249 * after fork (not vfork, NOMMU doesn't use this function).
6251 IF_HUSH_TRAP(unsigned sig;)
6254 /* Child shells are not interactive.
6255 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6256 * Testcase: (while :; do :; done) + ^Z should background.
6257 * Same goes for SIGTERM, SIGHUP, SIGINT.
6259 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6260 if (!G_traps && !mask)
6261 return; /* already no traps and no special sigs */
6263 /* Switch off special sigs */
6264 switch_off_special_sigs(mask);
6265 # if ENABLE_HUSH_JOB
6266 G_fatal_sig_mask = 0;
6268 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6269 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6270 * remain set in G.special_sig_mask */
6272 # if ENABLE_HUSH_TRAP
6276 /* Reset all sigs to default except ones with empty traps */
6277 for (sig = 0; sig < NSIG; sig++) {
6279 continue; /* no trap: nothing to do */
6280 if (!G_traps[sig][0])
6281 continue; /* empty trap: has to remain SIG_IGN */
6282 /* sig has non-empty trap, reset it: */
6284 G_traps[sig] = NULL;
6285 /* There is no signal for trap 0 (EXIT) */
6288 install_sighandler(sig, pick_sighandler(sig));
6295 static void re_execute_shell(char ***to_free, const char *s,
6296 char *g_argv0, char **g_argv,
6297 char **builtin_argv) NORETURN;
6298 static void re_execute_shell(char ***to_free, const char *s,
6299 char *g_argv0, char **g_argv,
6300 char **builtin_argv)
6302 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6303 /* delims + 2 * (number of bytes in printed hex numbers) */
6304 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6305 char *heredoc_argv[4];
6306 struct variable *cur;
6307 # if ENABLE_HUSH_FUNCTIONS
6308 struct function *funcp;
6312 unsigned long long empty_trap_mask;
6314 if (!g_argv0) { /* heredoc */
6315 argv = heredoc_argv;
6316 argv[0] = (char *) G.argv0_for_re_execing;
6317 argv[1] = (char *) "-<";
6318 argv[2] = (char *) s;
6320 pp = &argv[3]; /* used as pointer to empty environment */
6326 if (pp) while (*pp++)
6329 empty_trap_mask = 0;
6332 for (sig = 1; sig < NSIG; sig++) {
6333 if (G_traps[sig] && !G_traps[sig][0])
6334 empty_trap_mask |= 1LL << sig;
6338 sprintf(param_buf, NOMMU_HACK_FMT
6339 , (unsigned) G.root_pid
6340 , (unsigned) G.root_ppid
6341 , (unsigned) G.last_bg_pid
6342 , (unsigned) G.last_exitcode
6345 IF_HUSH_LOOPS(, G.depth_of_loop)
6347 # undef NOMMU_HACK_FMT
6348 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6349 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6352 for (cur = G.top_var; cur; cur = cur->next) {
6353 if (!cur->flg_export || cur->flg_read_only)
6356 # if ENABLE_HUSH_FUNCTIONS
6357 for (funcp = G.top_func; funcp; funcp = funcp->next)
6363 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6364 *pp++ = (char *) G.argv0_for_re_execing;
6366 for (cur = G.top_var; cur; cur = cur->next) {
6367 if (strcmp(cur->varstr, hush_version_str) == 0)
6369 if (cur->flg_read_only) {
6370 *pp++ = (char *) "-R";
6371 *pp++ = cur->varstr;
6372 } else if (!cur->flg_export) {
6373 *pp++ = (char *) "-V";
6374 *pp++ = cur->varstr;
6377 # if ENABLE_HUSH_FUNCTIONS
6378 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6379 *pp++ = (char *) "-F";
6380 *pp++ = funcp->name;
6381 *pp++ = funcp->body_as_string;
6384 /* We can pass activated traps here. Say, -Tnn:trap_string
6386 * However, POSIX says that subshells reset signals with traps
6388 * I tested bash-3.2 and it not only does that with true subshells
6389 * of the form ( list ), but with any forked children shells.
6390 * I set trap "echo W" WINCH; and then tried:
6392 * { echo 1; sleep 20; echo 2; } &
6393 * while true; do echo 1; sleep 20; echo 2; break; done &
6394 * true | { echo 1; sleep 20; echo 2; } | cat
6396 * In all these cases sending SIGWINCH to the child shell
6397 * did not run the trap. If I add trap "echo V" WINCH;
6398 * _inside_ group (just before echo 1), it works.
6400 * I conclude it means we don't need to pass active traps here.
6402 *pp++ = (char *) "-c";
6405 while (*++builtin_argv)
6406 *pp++ = *builtin_argv;
6407 *pp++ = (char *) "";
6412 /* *pp = NULL; - is already there */
6416 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6417 /* Don't propagate SIG_IGN to the child */
6418 if (SPECIAL_JOBSTOP_SIGS != 0)
6419 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6420 execve(bb_busybox_exec_path, argv, pp);
6421 /* Fallback. Useful for init=/bin/hush usage etc */
6422 if (argv[0][0] == '/')
6423 execve(argv[0], argv, pp);
6424 xfunc_error_retval = 127;
6425 bb_error_msg_and_die("can't re-execute the shell");
6427 #endif /* !BB_MMU */
6430 static int run_and_free_list(struct pipe *pi);
6432 /* Executing from string: eval, sh -c '...'
6433 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6434 * end_trigger controls how often we stop parsing
6435 * NUL: parse all, execute, return
6436 * ';': parse till ';' or newline, execute, repeat till EOF
6438 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6440 /* Why we need empty flag?
6441 * An obscure corner case "false; ``; echo $?":
6442 * empty command in `` should still set $? to 0.
6443 * But we can't just set $? to 0 at the start,
6444 * this breaks "false; echo `echo $?`" case.
6448 struct pipe *pipe_list;
6450 #if ENABLE_HUSH_INTERACTIVE
6451 if (end_trigger == ';')
6452 inp->promptmode = 0; /* PS1 */
6454 pipe_list = parse_stream(NULL, inp, end_trigger);
6455 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6456 /* If we are in "big" script
6457 * (not in `cmd` or something similar)...
6459 if (pipe_list == ERR_PTR && end_trigger == ';') {
6460 /* Discard cached input (rest of line) */
6461 int ch = inp->last_char;
6462 while (ch != EOF && ch != '\n') {
6463 //bb_error_msg("Discarded:'%c'", ch);
6468 /* This stream isn't empty */
6472 if (!pipe_list && empty)
6473 G.last_exitcode = 0;
6476 debug_print_tree(pipe_list, 0);
6477 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6478 run_and_free_list(pipe_list);
6480 if (G_flag_return_in_progress == 1)
6485 static void parse_and_run_string(const char *s)
6487 struct in_str input;
6488 setup_string_in_str(&input, s);
6489 parse_and_run_stream(&input, '\0');
6492 static void parse_and_run_file(FILE *f)
6494 struct in_str input;
6495 setup_file_in_str(&input, f);
6496 parse_and_run_stream(&input, ';');
6499 #if ENABLE_HUSH_TICK
6500 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6505 char **to_free = NULL;
6509 pid = BB_MMU ? xfork() : xvfork();
6510 if (pid == 0) { /* child */
6511 disable_restore_tty_pgrp_on_exit();
6512 /* Process substitution is not considered to be usual
6513 * 'command execution'.
6514 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6521 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6522 close(channel[0]); /* NB: close _first_, then move fd! */
6523 xmove_fd(channel[1], 1);
6524 /* Prevent it from trying to handle ctrl-z etc */
6525 IF_HUSH_JOB(G.run_list_level = 1;)
6526 # if ENABLE_HUSH_TRAP
6527 /* Awful hack for `trap` or $(trap).
6529 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6530 * contains an example where "trap" is executed in a subshell:
6532 * save_traps=$(trap)
6534 * eval "$save_traps"
6536 * Standard does not say that "trap" in subshell shall print
6537 * parent shell's traps. It only says that its output
6538 * must have suitable form, but then, in the above example
6539 * (which is not supposed to be normative), it implies that.
6541 * bash (and probably other shell) does implement it
6542 * (traps are reset to defaults, but "trap" still shows them),
6543 * but as a result, "trap" logic is hopelessly messed up:
6546 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6547 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6548 * # true | trap <--- trap is in subshell - no output (ditto)
6549 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6550 * trap -- 'echo Ho' SIGWINCH
6551 * # echo `(trap)` <--- in subshell in subshell - output
6552 * trap -- 'echo Ho' SIGWINCH
6553 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6554 * trap -- 'echo Ho' SIGWINCH
6556 * The rules when to forget and when to not forget traps
6557 * get really complex and nonsensical.
6559 * Our solution: ONLY bare $(trap) or `trap` is special.
6561 s = skip_whitespace(s);
6562 if (is_prefixed_with(s, "trap")
6563 && skip_whitespace(s + 4)[0] == '\0'
6565 static const char *const argv[] = { NULL, NULL };
6566 builtin_trap((char**)argv);
6567 fflush_all(); /* important */
6572 reset_traps_to_defaults();
6573 parse_and_run_string(s);
6574 _exit(G.last_exitcode);
6576 /* We re-execute after vfork on NOMMU. This makes this script safe:
6577 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6578 * huge=`cat BIG` # was blocking here forever
6581 re_execute_shell(&to_free,
6591 # if ENABLE_HUSH_FAST
6593 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6594 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6595 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6597 enable_restore_tty_pgrp_on_exit();
6602 return remember_FILE(xfdopen_for_read(channel[0]));
6605 /* Return code is exit status of the process that is run. */
6606 static int process_command_subs(o_string *dest, const char *s)
6609 struct in_str pipe_str;
6611 int status, ch, eol_cnt;
6613 fp = generate_stream_from_string(s, &pid);
6615 /* Now send results of command back into original context */
6616 setup_file_in_str(&pipe_str, fp);
6618 while ((ch = i_getch(&pipe_str)) != EOF) {
6624 o_addchr(dest, '\n');
6627 o_addQchr(dest, ch);
6630 debug_printf("done reading from `cmd` pipe, closing it\n");
6631 fclose_and_forget(fp);
6632 /* We need to extract exitcode. Test case
6633 * "true; echo `sleep 1; false` $?"
6635 safe_waitpid(pid, &status, 0);
6636 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6637 return WEXITSTATUS(status);
6639 #endif /* ENABLE_HUSH_TICK */
6642 static void setup_heredoc(struct redir_struct *redir)
6644 struct fd_pair pair;
6647 /* the _body_ of heredoc (misleading field name) */
6648 const char *heredoc = redir->rd_filename;
6655 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6656 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6660 len = strlen(heredoc);
6662 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6664 xmove_fd(pair.rd, redir->rd_fd);
6666 /* Try writing without forking. Newer kernels have
6667 * dynamically growing pipes. Must use non-blocking write! */
6670 written = write(pair.wr, heredoc, len);
6681 ndelay_off(pair.wr);
6683 /* Okay, pipe buffer was not big enough */
6684 /* Note: we must not create a stray child (bastard? :)
6685 * for the unsuspecting parent process. Child creates a grandchild
6686 * and exits before parent execs the process which consumes heredoc
6687 * (that exec happens after we return from this function) */
6694 disable_restore_tty_pgrp_on_exit();
6695 pid = BB_MMU ? xfork() : xvfork();
6699 close(redir->rd_fd); /* read side of the pipe */
6701 full_write(pair.wr, heredoc, len); /* may loop or block */
6704 /* Delegate blocking writes to another process */
6705 xmove_fd(pair.wr, STDOUT_FILENO);
6706 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6710 #if ENABLE_HUSH_FAST
6712 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6714 enable_restore_tty_pgrp_on_exit();
6720 wait(NULL); /* wait till child has died */
6726 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6727 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6730 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6732 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6733 sq[i].orig_fd = orig;
6734 sq[i].moved_to = moved;
6735 sq[i+1].orig_fd = -1; /* end marker */
6739 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6744 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6745 /* If we collide with an already moved fd... */
6746 if (fd == sq[i].moved_to) {
6747 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6748 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6749 if (sq[i].moved_to < 0) /* what? */
6753 if (fd == sq[i].orig_fd) {
6754 /* Example: echo Hello >/dev/null 1>&2 */
6755 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6760 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6761 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6762 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6763 if (moved_to < 0 && errno != EBADF)
6765 return append_squirrel(sq, i, fd, moved_to);
6768 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6772 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6773 /* If we collide with an already moved fd... */
6774 if (fd == sq[i].orig_fd) {
6776 * "echo 3>FILE 3>&- 3>FILE"
6777 * "echo 3>&- 3>FILE"
6778 * No need for last redirect to insert
6779 * another "need to close 3" indicator.
6781 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6786 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6787 return append_squirrel(sq, i, fd, -1);
6790 /* fd: redirect wants this fd to be used (e.g. 3>file).
6791 * Move all conflicting internally used fds,
6792 * and remember them so that we can restore them later.
6794 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6796 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6799 #if ENABLE_HUSH_INTERACTIVE
6800 if (fd == G.interactive_fd) {
6801 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6802 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6803 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6804 return 1; /* "we closed fd" */
6807 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6808 * (1) Redirect in a forked child. No need to save FILEs' fds,
6809 * we aren't going to use them anymore, ok to trash.
6810 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6811 * but how are we doing to restore them?
6812 * "fileno(fd) = new_fd" can't be done.
6817 /* If this one of script's fds? */
6818 if (save_FILEs_on_redirect(fd, avoid_fd))
6819 return 1; /* yes. "we closed fd" */
6821 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6822 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6823 return 0; /* "we did not close fd" */
6826 static void restore_redirects(struct squirrel *sq)
6830 for (i = 0; sq[i].orig_fd >= 0; i++) {
6831 if (sq[i].moved_to >= 0) {
6832 /* We simply die on error */
6833 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6834 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6836 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6837 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6838 close(sq[i].orig_fd);
6844 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6846 restore_redirected_FILEs();
6849 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6850 static void close_saved_fds_and_FILE_fds(void)
6852 if (G_interactive_fd)
6853 close(G_interactive_fd);
6854 close_all_FILE_list();
6858 static int internally_opened_fd(int fd, struct squirrel *sq)
6862 #if ENABLE_HUSH_INTERACTIVE
6863 if (fd == G.interactive_fd)
6866 /* If this one of script's fds? */
6867 if (fd_in_FILEs(fd))
6870 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6871 if (fd == sq[i].moved_to)
6877 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6878 * and stderr if they are redirected. */
6879 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6881 struct redir_struct *redir;
6883 for (redir = prog->redirects; redir; redir = redir->next) {
6887 if (redir->rd_type == REDIRECT_HEREDOC2) {
6888 /* "rd_fd<<HERE" case */
6889 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6890 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6892 debug_printf_parse("set heredoc '%s'\n",
6893 redir->rd_filename);
6894 setup_heredoc(redir);
6898 if (redir->rd_dup == REDIRFD_TO_FILE) {
6899 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6903 if (redir->rd_filename == NULL) {
6906 * "cmd >" (no filename)
6907 * "cmd > <file" (2nd redirect starts too early)
6909 syntax_error("invalid redirect");
6912 mode = redir_table[redir->rd_type].mode;
6913 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6914 newfd = open_or_warn(p, mode);
6917 /* Error message from open_or_warn can be lost
6918 * if stderr has been redirected, but bash
6919 * and ash both lose it as well
6920 * (though zsh doesn't!)
6924 if (newfd == redir->rd_fd && sqp) {
6925 /* open() gave us precisely the fd we wanted.
6926 * This means that this fd was not busy
6927 * (not opened to anywhere).
6928 * Remember to close it on restore:
6930 *sqp = add_squirrel_closed(*sqp, newfd);
6931 debug_printf_redir("redir to previously closed fd %d\n", newfd);
6934 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6935 newfd = redir->rd_dup;
6938 if (newfd == redir->rd_fd)
6941 /* if "N>FILE": move newfd to redir->rd_fd */
6942 /* if "N>&M": dup newfd to redir->rd_fd */
6943 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6945 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6946 if (newfd == REDIRFD_CLOSE) {
6947 /* "N>&-" means "close me" */
6949 /* ^^^ optimization: saving may already
6950 * have closed it. If not... */
6951 close(redir->rd_fd);
6953 /* Sometimes we do another close on restore, getting EBADF.
6954 * Consider "echo 3>FILE 3>&-"
6955 * first redirect remembers "need to close 3",
6956 * and second redirect closes 3! Restore code then closes 3 again.
6959 /* if newfd is a script fd or saved fd, simulate EBADF */
6960 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6962 //bb_perror_msg_and_die("can't duplicate file descriptor");
6963 newfd = -1; /* same effect as code above */
6965 xdup2(newfd, redir->rd_fd);
6966 if (redir->rd_dup == REDIRFD_TO_FILE)
6967 /* "rd_fd > FILE" */
6969 /* else: "rd_fd > rd_dup" */
6975 static char *find_in_path(const char *arg)
6978 const char *PATH = get_local_var_value("PATH");
6984 const char *end = strchrnul(PATH, ':');
6985 int sz = end - PATH; /* must be int! */
6989 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6991 /* We have xxx::yyyy in $PATH,
6992 * it means "use current dir" */
6995 if (access(ret, F_OK) == 0)
7008 static const struct built_in_command *find_builtin_helper(const char *name,
7009 const struct built_in_command *x,
7010 const struct built_in_command *end)
7013 if (strcmp(name, x->b_cmd) != 0) {
7017 debug_printf_exec("found builtin '%s'\n", name);
7022 static const struct built_in_command *find_builtin1(const char *name)
7024 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7026 static const struct built_in_command *find_builtin(const char *name)
7028 const struct built_in_command *x = find_builtin1(name);
7031 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7034 #if ENABLE_HUSH_FUNCTIONS
7035 static struct function **find_function_slot(const char *name)
7037 struct function **funcpp = &G.top_func;
7039 if (strcmp(name, (*funcpp)->name) == 0) {
7042 funcpp = &(*funcpp)->next;
7047 static const struct function *find_function(const char *name)
7049 const struct function *funcp = *find_function_slot(name);
7051 debug_printf_exec("found function '%s'\n", name);
7055 /* Note: takes ownership on name ptr */
7056 static struct function *new_function(char *name)
7058 struct function **funcpp = find_function_slot(name);
7059 struct function *funcp = *funcpp;
7061 if (funcp != NULL) {
7062 struct command *cmd = funcp->parent_cmd;
7063 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7065 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7067 /* Note: if !funcp->body, do not free body_as_string!
7068 * This is a special case of "-F name body" function:
7069 * body_as_string was not malloced! */
7071 free_pipe_list(funcp->body);
7073 free(funcp->body_as_string);
7077 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7078 cmd->argv[0] = funcp->name;
7079 cmd->group = funcp->body;
7081 cmd->group_as_string = funcp->body_as_string;
7085 debug_printf_exec("remembering new function '%s'\n", name);
7086 funcp = *funcpp = xzalloc(sizeof(*funcp));
7087 /*funcp->next = NULL;*/
7094 # if ENABLE_HUSH_UNSET
7095 static void unset_func(const char *name)
7097 struct function **funcpp = find_function_slot(name);
7098 struct function *funcp = *funcpp;
7100 if (funcp != NULL) {
7101 debug_printf_exec("freeing function '%s'\n", funcp->name);
7102 *funcpp = funcp->next;
7103 /* funcp is unlinked now, deleting it.
7104 * Note: if !funcp->body, the function was created by
7105 * "-F name body", do not free ->body_as_string
7106 * and ->name as they were not malloced. */
7108 free_pipe_list(funcp->body);
7111 free(funcp->body_as_string);
7120 #define exec_function(to_free, funcp, argv) \
7121 exec_function(funcp, argv)
7123 static void exec_function(char ***to_free,
7124 const struct function *funcp,
7125 char **argv) NORETURN;
7126 static void exec_function(char ***to_free,
7127 const struct function *funcp,
7133 argv[0] = G.global_argv[0];
7134 G.global_argv = argv;
7135 G.global_argc = n = 1 + string_array_len(argv + 1);
7137 // Example when we are here: "cmd | func"
7138 // func will run with saved-redirect fds open.
7139 // $ f() { echo /proc/self/fd/*; }
7141 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7142 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7145 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7146 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7147 // They are CLOEXEC so external programs won't see them, but
7148 // for "more correctness" we might want to close those extra fds here:
7149 //? close_saved_fds_and_FILE_fds();
7151 /* "we are in function, ok to use return" */
7152 G_flag_return_in_progress = -1;
7153 IF_HUSH_LOCAL(G.func_nest_level++;)
7155 /* On MMU, funcp->body is always non-NULL */
7156 n = run_list(funcp->body);
7160 //? close_saved_fds_and_FILE_fds();
7162 //TODO: check whether "true | func_with_return" works
7164 re_execute_shell(to_free,
7165 funcp->body_as_string,
7172 static int run_function(const struct function *funcp, char **argv)
7178 save_and_replace_G_args(&sv, argv);
7180 /* "we are in function, ok to use return" */
7181 sv_flg = G_flag_return_in_progress;
7182 G_flag_return_in_progress = -1;
7183 IF_HUSH_LOCAL(G.func_nest_level++;)
7185 /* On MMU, funcp->body is always non-NULL */
7188 /* Function defined by -F */
7189 parse_and_run_string(funcp->body_as_string);
7190 rc = G.last_exitcode;
7194 rc = run_list(funcp->body);
7197 # if ENABLE_HUSH_LOCAL
7199 struct variable *var;
7200 struct variable **var_pp;
7202 var_pp = &G.top_var;
7203 while ((var = *var_pp) != NULL) {
7204 if (var->func_nest_level < G.func_nest_level) {
7205 var_pp = &var->next;
7209 if (var->flg_export)
7210 bb_unsetenv(var->varstr);
7211 /* Remove from global list */
7212 *var_pp = var->next;
7218 G.func_nest_level--;
7221 G_flag_return_in_progress = sv_flg;
7223 restore_G_args(&sv, argv);
7227 #endif /* ENABLE_HUSH_FUNCTIONS */
7231 #define exec_builtin(to_free, x, argv) \
7232 exec_builtin(x, argv)
7234 #define exec_builtin(to_free, x, argv) \
7235 exec_builtin(to_free, argv)
7237 static void exec_builtin(char ***to_free,
7238 const struct built_in_command *x,
7239 char **argv) NORETURN;
7240 static void exec_builtin(char ***to_free,
7241 const struct built_in_command *x,
7247 //? close_saved_fds_and_FILE_fds();
7248 rcode = x->b_function(argv);
7253 /* On NOMMU, we must never block!
7254 * Example: { sleep 99 | read line; } & echo Ok
7256 re_execute_shell(to_free,
7265 static void execvp_or_die(char **argv) NORETURN;
7266 static void execvp_or_die(char **argv)
7269 debug_printf_exec("execing '%s'\n", argv[0]);
7270 /* Don't propagate SIG_IGN to the child */
7271 if (SPECIAL_JOBSTOP_SIGS != 0)
7272 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7273 execvp(argv[0], argv);
7275 if (errno == EACCES) e = 126;
7276 if (errno == ENOENT) e = 127;
7277 bb_perror_msg("can't execute '%s'", argv[0]);
7281 #if ENABLE_HUSH_MODE_X
7282 static void dump_cmd_in_x_mode(char **argv)
7284 if (G_x_mode && argv) {
7285 /* We want to output the line in one write op */
7293 len += strlen(argv[n++]) + 1;
7299 p += sprintf(p, " %s", argv[n++]);
7307 # define dump_cmd_in_x_mode(argv) ((void)0)
7311 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7312 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7313 #define pseudo_exec(nommu_save, command, argv_expanded) \
7314 pseudo_exec(command, argv_expanded)
7317 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7319 * Don't exit() here. If you don't exec, use _exit instead.
7320 * The at_exit handlers apparently confuse the calling process,
7321 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7323 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7324 char **argv, int assignment_cnt,
7325 char **argv_expanded) NORETURN;
7326 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7327 char **argv, int assignment_cnt,
7328 char **argv_expanded)
7332 new_env = expand_assignments(argv, assignment_cnt);
7333 dump_cmd_in_x_mode(new_env);
7335 if (!argv[assignment_cnt]) {
7336 /* Case when we are here: ... | var=val | ...
7337 * (note that we do not exit early, i.e., do not optimize out
7338 * expand_assignments(): think about ... | var=`sleep 1` | ...
7340 free_strings(new_env);
7341 _exit(EXIT_SUCCESS);
7345 set_vars_and_save_old(new_env);
7346 free(new_env); /* optional */
7347 /* we can also destroy set_vars_and_save_old's return value,
7350 nommu_save->new_env = new_env;
7351 nommu_save->old_vars = set_vars_and_save_old(new_env);
7354 if (argv_expanded) {
7355 argv = argv_expanded;
7357 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7359 nommu_save->argv = argv;
7362 dump_cmd_in_x_mode(argv);
7364 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7365 if (strchr(argv[0], '/') != NULL)
7369 #if ENABLE_HUSH_FUNCTIONS
7370 /* Check if the command matches any functions (this goes before bltins) */
7372 const struct function *funcp = find_function(argv[0]);
7374 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7379 /* Check if the command matches any of the builtins.
7380 * Depending on context, this might be redundant. But it's
7381 * easier to waste a few CPU cycles than it is to figure out
7382 * if this is one of those cases.
7385 /* On NOMMU, it is more expensive to re-execute shell
7386 * just in order to run echo or test builtin.
7387 * It's better to skip it here and run corresponding
7388 * non-builtin later. */
7389 const struct built_in_command *x;
7390 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7392 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7396 #if ENABLE_FEATURE_SH_STANDALONE
7397 /* Check if the command matches any busybox applets */
7399 int a = find_applet_by_name(argv[0]);
7401 # if BB_MMU /* see above why on NOMMU it is not allowed */
7402 if (APPLET_IS_NOEXEC(a)) {
7403 /* Do not leak open fds from opened script files etc.
7404 * Testcase: interactive "ls -l /proc/self/fd"
7405 * should not show tty fd open.
7407 close_saved_fds_and_FILE_fds();
7408 //FIXME: should also close saved redir fds
7409 /* Without this, "rm -i FILE" can't be ^C'ed: */
7410 switch_off_special_sigs(G.special_sig_mask);
7411 debug_printf_exec("running applet '%s'\n", argv[0]);
7412 run_noexec_applet_and_exit(a, argv[0], argv);
7415 /* Re-exec ourselves */
7416 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7417 /* Don't propagate SIG_IGN to the child */
7418 if (SPECIAL_JOBSTOP_SIGS != 0)
7419 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7420 execv(bb_busybox_exec_path, argv);
7421 /* If they called chroot or otherwise made the binary no longer
7422 * executable, fall through */
7427 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7430 execvp_or_die(argv);
7433 /* Called after [v]fork() in run_pipe
7435 static void pseudo_exec(nommu_save_t *nommu_save,
7436 struct command *command,
7437 char **argv_expanded) NORETURN;
7438 static void pseudo_exec(nommu_save_t *nommu_save,
7439 struct command *command,
7440 char **argv_expanded)
7442 if (command->argv) {
7443 pseudo_exec_argv(nommu_save, command->argv,
7444 command->assignment_cnt, argv_expanded);
7447 if (command->group) {
7448 /* Cases when we are here:
7451 * ... | ( list ) | ...
7452 * ... | { list } | ...
7456 debug_printf_exec("pseudo_exec: run_list\n");
7457 reset_traps_to_defaults();
7458 rcode = run_list(command->group);
7459 /* OK to leak memory by not calling free_pipe_list,
7460 * since this process is about to exit */
7463 re_execute_shell(&nommu_save->argv_from_re_execing,
7464 command->group_as_string,
7471 /* Case when we are here: ... | >file */
7472 debug_printf_exec("pseudo_exec'ed null command\n");
7473 _exit(EXIT_SUCCESS);
7477 static const char *get_cmdtext(struct pipe *pi)
7483 /* This is subtle. ->cmdtext is created only on first backgrounding.
7484 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7485 * On subsequent bg argv is trashed, but we won't use it */
7489 argv = pi->cmds[0].argv;
7491 pi->cmdtext = xzalloc(1);
7496 len += strlen(*argv) + 1;
7500 argv = pi->cmds[0].argv;
7502 p = stpcpy(p, *argv);
7509 static void remove_job_from_table(struct pipe *pi)
7511 struct pipe *prev_pipe;
7513 if (pi == G.job_list) {
7514 G.job_list = pi->next;
7516 prev_pipe = G.job_list;
7517 while (prev_pipe->next != pi)
7518 prev_pipe = prev_pipe->next;
7519 prev_pipe->next = pi->next;
7523 G.last_jobid = G.job_list->jobid;
7526 static void delete_finished_job(struct pipe *pi)
7528 remove_job_from_table(pi);
7532 static void clean_up_last_dead_job(void)
7534 if (G.job_list && !G.job_list->alive_cmds)
7535 delete_finished_job(G.job_list);
7538 static void insert_job_into_table(struct pipe *pi)
7540 struct pipe *job, **jobp;
7543 clean_up_last_dead_job();
7545 /* Find the end of the list, and find next job ID to use */
7548 while ((job = *jobp) != NULL) {
7555 /* Create a new job struct at the end */
7556 job = *jobp = xmemdup(pi, sizeof(*pi));
7558 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7559 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7560 for (i = 0; i < pi->num_cmds; i++) {
7561 job->cmds[i].pid = pi->cmds[i].pid;
7562 /* all other fields are not used and stay zero */
7564 job->cmdtext = xstrdup(get_cmdtext(pi));
7566 if (G_interactive_fd)
7567 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7568 G.last_jobid = job->jobid;
7572 static int job_exited_or_stopped(struct pipe *pi)
7576 if (pi->alive_cmds != pi->stopped_cmds)
7579 /* All processes in fg pipe have exited or stopped */
7583 rcode = pi->cmds[i].cmd_exitcode;
7584 /* usually last process gives overall exitstatus,
7585 * but with "set -o pipefail", last *failed* process does */
7586 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7589 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7593 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7600 dead = WIFEXITED(status) || WIFSIGNALED(status);
7603 if (WIFSTOPPED(status))
7604 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7605 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7606 if (WIFSIGNALED(status))
7607 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7608 childpid, WTERMSIG(status), WEXITSTATUS(status));
7609 if (WIFEXITED(status))
7610 debug_printf_jobs("pid %d exited, exitcode %d\n",
7611 childpid, WEXITSTATUS(status));
7613 /* Were we asked to wait for a fg pipe? */
7615 i = fg_pipe->num_cmds;
7620 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7621 if (fg_pipe->cmds[i].pid != childpid)
7625 fg_pipe->cmds[i].pid = 0;
7626 fg_pipe->alive_cmds--;
7627 ex = WEXITSTATUS(status);
7628 /* bash prints killer signal's name for *last*
7629 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7630 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7632 if (WIFSIGNALED(status)) {
7633 int sig = WTERMSIG(status);
7634 if (i == fg_pipe->num_cmds-1)
7635 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7636 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7637 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7638 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7639 * Maybe we need to use sig | 128? */
7642 fg_pipe->cmds[i].cmd_exitcode = ex;
7644 fg_pipe->stopped_cmds++;
7646 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7647 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7648 rcode = job_exited_or_stopped(fg_pipe);
7650 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7651 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7652 * and "killall -STOP cat" */
7653 if (G_interactive_fd) {
7655 if (fg_pipe->alive_cmds != 0)
7656 insert_job_into_table(fg_pipe);
7660 if (fg_pipe->alive_cmds == 0)
7663 /* There are still running processes in the fg_pipe */
7666 /* It wasn't in fg_pipe, look for process in bg pipes */
7670 /* We were asked to wait for bg or orphaned children */
7671 /* No need to remember exitcode in this case */
7672 for (pi = G.job_list; pi; pi = pi->next) {
7673 for (i = 0; i < pi->num_cmds; i++) {
7674 if (pi->cmds[i].pid == childpid)
7675 goto found_pi_and_prognum;
7678 /* Happens when shell is used as init process (init=/bin/sh) */
7679 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7680 return -1; /* this wasn't a process from fg_pipe */
7682 found_pi_and_prognum:
7685 int rcode = WEXITSTATUS(status);
7686 if (WIFSIGNALED(status))
7687 rcode = 128 + WTERMSIG(status);
7688 pi->cmds[i].cmd_exitcode = rcode;
7689 if (G.last_bg_pid == pi->cmds[i].pid)
7690 G.last_bg_pid_exitcode = rcode;
7691 pi->cmds[i].pid = 0;
7693 if (!pi->alive_cmds) {
7694 if (G_interactive_fd) {
7695 printf(JOB_STATUS_FORMAT, pi->jobid,
7696 "Done", pi->cmdtext);
7697 delete_finished_job(pi);
7700 * bash deletes finished jobs from job table only in interactive mode,
7701 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7702 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7703 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7704 * We only retain one "dead" job, if it's the single job on the list.
7705 * This covers most of real-world scenarios where this is useful.
7707 if (pi != G.job_list)
7708 delete_finished_job(pi);
7716 return -1; /* this wasn't a process from fg_pipe */
7719 /* Check to see if any processes have exited -- if they have,
7720 * figure out why and see if a job has completed.
7722 * If non-NULL fg_pipe: wait for its completion or stop.
7723 * Return its exitcode or zero if stopped.
7725 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7726 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7727 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7728 * or 0 if no children changed status.
7730 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7731 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7732 * or 0 if no children changed status.
7734 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7740 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7742 attributes = WUNTRACED;
7743 if (fg_pipe == NULL)
7744 attributes |= WNOHANG;
7747 #if ENABLE_HUSH_FAST
7748 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7749 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7750 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7751 /* There was neither fork nor SIGCHLD since last waitpid */
7752 /* Avoid doing waitpid syscall if possible */
7753 if (!G.we_have_children) {
7757 if (fg_pipe == NULL) { /* is WNOHANG set? */
7758 /* We have children, but they did not exit
7759 * or stop yet (we saw no SIGCHLD) */
7762 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7766 /* Do we do this right?
7767 * bash-3.00# sleep 20 | false
7769 * [3]+ Stopped sleep 20 | false
7770 * bash-3.00# echo $?
7771 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7772 * [hush 1.14.0: yes we do it right]
7776 #if ENABLE_HUSH_FAST
7778 i = G.count_SIGCHLD;
7780 childpid = waitpid(-1, &status, attributes);
7781 if (childpid <= 0) {
7782 if (childpid && errno != ECHILD)
7783 bb_perror_msg("waitpid");
7784 #if ENABLE_HUSH_FAST
7785 else { /* Until next SIGCHLD, waitpid's are useless */
7786 G.we_have_children = (childpid == 0);
7787 G.handled_SIGCHLD = i;
7788 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7791 /* ECHILD (no children), or 0 (no change in children status) */
7795 rcode = process_wait_result(fg_pipe, childpid, status);
7797 /* fg_pipe exited or stopped */
7800 if (childpid == waitfor_pid) {
7801 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7802 rcode = WEXITSTATUS(status);
7803 if (WIFSIGNALED(status))
7804 rcode = 128 + WTERMSIG(status);
7805 if (WIFSTOPPED(status))
7806 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7807 rcode = 128 + WSTOPSIG(status);
7809 break; /* "wait PID" called us, give it exitcode+1 */
7811 /* This wasn't one of our processes, or */
7812 /* fg_pipe still has running processes, do waitpid again */
7813 } /* while (waitpid succeeds)... */
7819 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7822 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7823 if (G_saved_tty_pgrp) {
7824 /* Job finished, move the shell to the foreground */
7825 p = getpgrp(); /* our process group id */
7826 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7827 tcsetpgrp(G_interactive_fd, p);
7833 /* Start all the jobs, but don't wait for anything to finish.
7836 * Return code is normally -1, when the caller has to wait for children
7837 * to finish to determine the exit status of the pipe. If the pipe
7838 * is a simple builtin command, however, the action is done by the
7839 * time run_pipe returns, and the exit code is provided as the
7842 * Returns -1 only if started some children. IOW: we have to
7843 * mask out retvals of builtins etc with 0xff!
7845 * The only case when we do not need to [v]fork is when the pipe
7846 * is single, non-backgrounded, non-subshell command. Examples:
7847 * cmd ; ... { list } ; ...
7848 * cmd && ... { list } && ...
7849 * cmd || ... { list } || ...
7850 * If it is, then we can run cmd as a builtin, NOFORK,
7851 * or (if SH_STANDALONE) an applet, and we can run the { list }
7852 * with run_list. If it isn't one of these, we fork and exec cmd.
7854 * Cases when we must fork:
7855 * non-single: cmd | cmd
7856 * backgrounded: cmd & { list } &
7857 * subshell: ( list ) [&]
7859 #if !ENABLE_HUSH_MODE_X
7860 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7861 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7863 static int redirect_and_varexp_helper(char ***new_env_p,
7864 struct variable **old_vars_p,
7865 struct command *command,
7866 struct squirrel **sqp,
7867 char **argv_expanded)
7869 /* setup_redirects acts on file descriptors, not FILEs.
7870 * This is perfect for work that comes after exec().
7871 * Is it really safe for inline use? Experimentally,
7872 * things seem to work. */
7873 int rcode = setup_redirects(command, sqp);
7875 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7876 *new_env_p = new_env;
7877 dump_cmd_in_x_mode(new_env);
7878 dump_cmd_in_x_mode(argv_expanded);
7880 *old_vars_p = set_vars_and_save_old(new_env);
7884 static NOINLINE int run_pipe(struct pipe *pi)
7886 static const char *const null_ptr = NULL;
7890 struct command *command;
7891 char **argv_expanded;
7893 struct squirrel *squirrel = NULL;
7896 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7899 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7900 * Result should be 3 lines: q w e, qwe, q w e
7902 G.ifs = get_local_var_value("IFS");
7906 IF_HUSH_JOB(pi->pgrp = -1;)
7907 pi->stopped_cmds = 0;
7908 command = &pi->cmds[0];
7909 argv_expanded = NULL;
7911 if (pi->num_cmds != 1
7912 || pi->followup == PIPE_BG
7913 || command->cmd_type == CMD_SUBSHELL
7920 debug_printf_exec(": group:%p argv:'%s'\n",
7921 command->group, command->argv ? command->argv[0] : "NONE");
7923 if (command->group) {
7924 #if ENABLE_HUSH_FUNCTIONS
7925 if (command->cmd_type == CMD_FUNCDEF) {
7926 /* "executing" func () { list } */
7927 struct function *funcp;
7929 funcp = new_function(command->argv[0]);
7930 /* funcp->name is already set to argv[0] */
7931 funcp->body = command->group;
7933 funcp->body_as_string = command->group_as_string;
7934 command->group_as_string = NULL;
7936 command->group = NULL;
7937 command->argv[0] = NULL;
7938 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7939 funcp->parent_cmd = command;
7940 command->child_func = funcp;
7942 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7944 return EXIT_SUCCESS;
7948 debug_printf("non-subshell group\n");
7949 rcode = 1; /* exitcode if redir failed */
7950 if (setup_redirects(command, &squirrel) == 0) {
7951 debug_printf_exec(": run_list\n");
7952 rcode = run_list(command->group) & 0xff;
7954 restore_redirects(squirrel);
7955 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7957 debug_printf_exec("run_pipe: return %d\n", rcode);
7961 argv = command->argv ? command->argv : (char **) &null_ptr;
7963 const struct built_in_command *x;
7964 #if ENABLE_HUSH_FUNCTIONS
7965 const struct function *funcp;
7969 char **new_env = NULL;
7970 struct variable *old_vars = NULL;
7972 if (argv[command->assignment_cnt] == NULL) {
7973 /* Assignments, but no command */
7974 /* Ensure redirects take effect (that is, create files).
7975 * Try "a=t >file" */
7976 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7977 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
7978 /* Set shell variables */
7982 if (set_local_var(*argv, /*flag:*/ 0)) {
7983 /* assignment to readonly var / putenv error? */
7989 /* Redirect error sets $? to 1. Otherwise,
7990 * if evaluating assignment value set $?, retain it.
7991 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7993 rcode = G.last_exitcode;
7994 /* Exit, _skipping_ variable restoring code: */
7995 goto clean_up_and_ret0;
7997 #else /* Older, bigger, but more correct code */
7999 rcode = setup_redirects(command, &squirrel);
8000 restore_redirects(squirrel);
8001 /* Set shell variables */
8003 bb_putchar_stderr('+');
8005 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8007 fprintf(stderr, " %s", p);
8008 debug_printf_exec("set shell var:'%s'->'%s'\n",
8010 if (set_local_var(p, /*flag:*/ 0)) {
8011 /* assignment to readonly var / putenv error? */
8017 bb_putchar_stderr('\n');
8018 /* Redirect error sets $? to 1. Otherwise,
8019 * if evaluating assignment value set $?, retain it.
8020 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8022 rcode = G.last_exitcode;
8023 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8025 debug_printf_exec("run_pipe: return %d\n", rcode);
8030 /* Expand the rest into (possibly) many strings each */
8032 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8033 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8037 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8040 /* if someone gives us an empty string: `cmd with empty output` */
8041 if (!argv_expanded[0]) {
8042 free(argv_expanded);
8044 return G.last_exitcode;
8047 #if ENABLE_HUSH_FUNCTIONS
8048 /* Check if argv[0] matches any functions (this goes before bltins) */
8049 funcp = find_function(argv_expanded[0]);
8053 x = find_builtin(argv_expanded[0]);
8056 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8057 debug_printf("exec with redirects only\n");
8058 rcode = setup_redirects(command, NULL);
8059 /* rcode=1 can be if redir file can't be opened */
8060 goto clean_up_and_ret1;
8063 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8066 debug_printf_exec(": builtin '%s' '%s'...\n",
8067 x->b_cmd, argv_expanded[1]);
8069 rcode = x->b_function(argv_expanded) & 0xff;
8072 #if ENABLE_HUSH_FUNCTIONS
8074 # if ENABLE_HUSH_LOCAL
8075 struct variable **sv;
8076 sv = G.shadowed_vars_pp;
8077 G.shadowed_vars_pp = &old_vars;
8079 debug_printf_exec(": function '%s' '%s'...\n",
8080 funcp->name, argv_expanded[1]);
8081 rcode = run_function(funcp, argv_expanded) & 0xff;
8082 # if ENABLE_HUSH_LOCAL
8083 G.shadowed_vars_pp = sv;
8089 unset_vars(new_env);
8091 /* clean_up_and_ret0: */
8092 restore_redirects(squirrel);
8094 * Try "usleep 99999999" + ^C + "echo $?"
8095 * with FEATURE_SH_NOFORK=y.
8098 /* It was builtin or nofork.
8099 * if this would be a real fork/execed program,
8100 * it should have died if a fatal sig was received.
8101 * But OTOH, there was no separate process,
8102 * the sig was sent to _shell_, not to non-existing
8104 * Let's just handle ^C only, this one is obvious:
8105 * we aren't ok with exitcode 0 when ^C was pressed
8106 * during builtin/nofork.
8108 if (sigismember(&G.pending_set, SIGINT))
8109 rcode = 128 + SIGINT;
8112 free(argv_expanded);
8113 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8115 debug_printf_exec("run_pipe return %d\n", rcode);
8119 if (ENABLE_FEATURE_SH_NOFORK) {
8120 int n = find_applet_by_name(argv_expanded[0]);
8121 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8122 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8124 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8125 argv_expanded[0], argv_expanded[1]);
8127 * Note: signals (^C) can't interrupt here.
8128 * We remember them and they will be acted upon
8129 * after applet returns.
8130 * This makes applets which can run for a long time
8131 * and/or wait for user input ineligible for NOFORK:
8132 * for example, "yes" or "rm" (rm -i waits for input).
8134 rcode = run_nofork_applet(n, argv_expanded);
8136 goto clean_up_and_ret;
8139 /* It is neither builtin nor applet. We must fork. */
8143 /* NB: argv_expanded may already be created, and that
8144 * might include `cmd` runs! Do not rerun it! We *must*
8145 * use argv_expanded if it's non-NULL */
8147 /* Going to fork a child per each pipe member */
8152 while (cmd_no < pi->num_cmds) {
8153 struct fd_pair pipefds;
8155 volatile nommu_save_t nommu_save;
8156 nommu_save.new_env = NULL;
8157 nommu_save.old_vars = NULL;
8158 nommu_save.argv = NULL;
8159 nommu_save.argv_from_re_execing = NULL;
8161 command = &pi->cmds[cmd_no];
8163 if (command->argv) {
8164 debug_printf_exec(": pipe member '%s' '%s'...\n",
8165 command->argv[0], command->argv[1]);
8167 debug_printf_exec(": pipe member with no argv\n");
8170 /* pipes are inserted between pairs of commands */
8173 if (cmd_no < pi->num_cmds)
8174 xpiped_pair(pipefds);
8176 command->pid = BB_MMU ? fork() : vfork();
8177 if (!command->pid) { /* child */
8179 disable_restore_tty_pgrp_on_exit();
8180 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8182 /* Every child adds itself to new process group
8183 * with pgid == pid_of_first_child_in_pipe */
8184 if (G.run_list_level == 1 && G_interactive_fd) {
8187 if (pgrp < 0) /* true for 1st process only */
8189 if (setpgid(0, pgrp) == 0
8190 && pi->followup != PIPE_BG
8191 && G_saved_tty_pgrp /* we have ctty */
8193 /* We do it in *every* child, not just first,
8195 tcsetpgrp(G_interactive_fd, pgrp);
8199 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8200 /* 1st cmd in backgrounded pipe
8201 * should have its stdin /dev/null'ed */
8203 if (open(bb_dev_null, O_RDONLY))
8204 xopen("/", O_RDONLY);
8206 xmove_fd(next_infd, 0);
8208 xmove_fd(pipefds.wr, 1);
8211 /* Like bash, explicit redirects override pipes,
8212 * and the pipe fd (fd#1) is available for dup'ing:
8213 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8214 * of cmd1 goes into pipe.
8216 if (setup_redirects(command, NULL)) {
8217 /* Happens when redir file can't be opened:
8218 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8220 * hush: can't open '/qwe/rty': No such file or directory
8222 * (echo BAR is not executed, it hits _exit(1) below)
8227 /* Stores to nommu_save list of env vars putenv'ed
8228 * (NOMMU, on MMU we don't need that) */
8229 /* cast away volatility... */
8230 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8231 /* pseudo_exec() does not return */
8234 /* parent or error */
8235 #if ENABLE_HUSH_FAST
8237 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8239 enable_restore_tty_pgrp_on_exit();
8241 /* Clean up after vforked child */
8242 free(nommu_save.argv);
8243 free(nommu_save.argv_from_re_execing);
8244 unset_vars(nommu_save.new_env);
8245 add_vars(nommu_save.old_vars);
8247 free(argv_expanded);
8248 argv_expanded = NULL;
8249 if (command->pid < 0) { /* [v]fork failed */
8250 /* Clearly indicate, was it fork or vfork */
8251 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8255 /* Second and next children need to know pid of first one */
8257 pi->pgrp = command->pid;
8263 if (cmd_no < pi->num_cmds)
8265 /* Pass read (output) pipe end to next iteration */
8266 next_infd = pipefds.rd;
8269 if (!pi->alive_cmds) {
8271 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8276 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8280 /* NB: called by pseudo_exec, and therefore must not modify any
8281 * global data until exec/_exit (we can be a child after vfork!) */
8282 static int run_list(struct pipe *pi)
8284 #if ENABLE_HUSH_CASE
8285 char *case_word = NULL;
8287 #if ENABLE_HUSH_LOOPS
8288 struct pipe *loop_top = NULL;
8289 char **for_lcur = NULL;
8290 char **for_list = NULL;
8292 smallint last_followup;
8294 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8295 smalluint cond_code = 0;
8297 enum { cond_code = 0 };
8300 smallint rword; /* RES_foo */
8301 smallint last_rword; /* ditto */
8304 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8307 #if ENABLE_HUSH_LOOPS
8308 /* Check syntax for "for" */
8311 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8312 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8314 /* current word is FOR or IN (BOLD in comments below) */
8315 if (cpipe->next == NULL) {
8316 syntax_error("malformed for");
8318 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8321 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8322 if (cpipe->next->res_word == RES_DO)
8324 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8325 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8326 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8328 syntax_error("malformed for");
8330 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8337 /* Past this point, all code paths should jump to ret: label
8338 * in order to return, no direct "return" statements please.
8339 * This helps to ensure that no memory is leaked. */
8347 last_rword = RES_XXXX;
8349 last_followup = PIPE_SEQ;
8350 rcode = G.last_exitcode;
8352 /* Go through list of pipes, (maybe) executing them. */
8353 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8355 int sv_errexit_depth;
8359 if (G_flag_return_in_progress == 1)
8362 IF_HAS_KEYWORDS(rword = pi->res_word;)
8363 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8364 rword, cond_code, last_rword);
8366 sv_errexit_depth = G.errexit_depth;
8367 if (IF_HAS_KEYWORDS(rword == RES_IF || rword == RES_ELIF ||)
8368 pi->followup != PIPE_SEQ
8372 #if ENABLE_HUSH_LOOPS
8373 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8374 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8376 /* start of a loop: remember where loop starts */
8381 /* Still in the same "if...", "then..." or "do..." branch? */
8382 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8383 if ((rcode == 0 && last_followup == PIPE_OR)
8384 || (rcode != 0 && last_followup == PIPE_AND)
8386 /* It is "<true> || CMD" or "<false> && CMD"
8387 * and we should not execute CMD */
8388 debug_printf_exec("skipped cmd because of || or &&\n");
8389 last_followup = pi->followup;
8390 goto dont_check_jobs_but_continue;
8393 last_followup = pi->followup;
8394 IF_HAS_KEYWORDS(last_rword = rword;)
8397 if (rword == RES_THEN) {
8398 /* if false; then ... fi has exitcode 0! */
8399 G.last_exitcode = rcode = EXIT_SUCCESS;
8400 /* "if <false> THEN cmd": skip cmd */
8404 if (rword == RES_ELSE || rword == RES_ELIF) {
8405 /* "if <true> then ... ELSE/ELIF cmd":
8406 * skip cmd and all following ones */
8411 #if ENABLE_HUSH_LOOPS
8412 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8414 /* first loop through for */
8416 static const char encoded_dollar_at[] ALIGN1 = {
8417 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8418 }; /* encoded representation of "$@" */
8419 static const char *const encoded_dollar_at_argv[] = {
8420 encoded_dollar_at, NULL
8421 }; /* argv list with one element: "$@" */
8424 vals = (char**)encoded_dollar_at_argv;
8425 if (pi->next->res_word == RES_IN) {
8426 /* if no variable values after "in" we skip "for" */
8427 if (!pi->next->cmds[0].argv) {
8428 G.last_exitcode = rcode = EXIT_SUCCESS;
8429 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8432 vals = pi->next->cmds[0].argv;
8433 } /* else: "for var; do..." -> assume "$@" list */
8434 /* create list of variable values */
8435 debug_print_strings("for_list made from", vals);
8436 for_list = expand_strvec_to_strvec(vals);
8437 for_lcur = for_list;
8438 debug_print_strings("for_list", for_list);
8441 /* "for" loop is over, clean up */
8447 /* Insert next value from for_lcur */
8448 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8449 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8452 if (rword == RES_IN) {
8453 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8455 if (rword == RES_DONE) {
8456 continue; /* "done" has no cmds too */
8459 #if ENABLE_HUSH_CASE
8460 if (rword == RES_CASE) {
8461 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8462 case_word = expand_strvec_to_string(pi->cmds->argv);
8463 unbackslash(case_word);
8466 if (rword == RES_MATCH) {
8469 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8470 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8472 /* all prev words didn't match, does this one match? */
8473 argv = pi->cmds->argv;
8475 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8476 /* TODO: which FNM_xxx flags to use? */
8477 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8478 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8480 if (cond_code == 0) { /* match! we will execute this branch */
8482 case_word = NULL; /* make future "word)" stop */
8489 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8490 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8492 continue; /* not matched yet, skip this pipe */
8494 if (rword == RES_ESAC) {
8495 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8497 /* "case" did not match anything: still set $? (to 0) */
8498 G.last_exitcode = rcode = EXIT_SUCCESS;
8502 /* Just pressing <enter> in shell should check for jobs.
8503 * OTOH, in non-interactive shell this is useless
8504 * and only leads to extra job checks */
8505 if (pi->num_cmds == 0) {
8506 if (G_interactive_fd)
8507 goto check_jobs_and_continue;
8511 /* After analyzing all keywords and conditions, we decided
8512 * to execute this pipe. NB: have to do checkjobs(NULL)
8513 * after run_pipe to collect any background children,
8514 * even if list execution is to be stopped. */
8515 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8516 #if ENABLE_HUSH_LOOPS
8517 G.flag_break_continue = 0;
8519 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8521 /* We ran a builtin, function, or group.
8522 * rcode is already known
8523 * and we don't need to wait for anything. */
8524 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8525 G.last_exitcode = rcode;
8526 check_and_run_traps();
8527 #if ENABLE_HUSH_LOOPS
8528 /* Was it "break" or "continue"? */
8529 if (G.flag_break_continue) {
8530 smallint fbc = G.flag_break_continue;
8531 /* We might fall into outer *loop*,
8532 * don't want to break it too */
8534 G.depth_break_continue--;
8535 if (G.depth_break_continue == 0)
8536 G.flag_break_continue = 0;
8537 /* else: e.g. "continue 2" should *break* once, *then* continue */
8538 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8539 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8540 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8543 /* "continue": simulate end of loop */
8548 if (G_flag_return_in_progress == 1) {
8549 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8552 } else if (pi->followup == PIPE_BG) {
8553 /* What does bash do with attempts to background builtins? */
8554 /* even bash 3.2 doesn't do that well with nested bg:
8555 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8556 * I'm NOT treating inner &'s as jobs */
8558 if (G.run_list_level == 1)
8559 insert_job_into_table(pi);
8561 /* Last command's pid goes to $! */
8562 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8563 G.last_bg_pid_exitcode = 0;
8564 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8565 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8566 rcode = EXIT_SUCCESS;
8570 if (G.run_list_level == 1 && G_interactive_fd) {
8571 /* Waits for completion, then fg's main shell */
8572 rcode = checkjobs_and_fg_shell(pi);
8573 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8577 /* This one just waits for completion */
8578 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8579 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8581 G.last_exitcode = rcode;
8582 check_and_run_traps();
8585 /* Handle "set -e" */
8586 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8587 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8588 if (G.errexit_depth == 0)
8591 G.errexit_depth = sv_errexit_depth;
8593 /* Analyze how result affects subsequent commands */
8595 if (rword == RES_IF || rword == RES_ELIF)
8598 check_jobs_and_continue:
8599 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8600 dont_check_jobs_but_continue: ;
8601 #if ENABLE_HUSH_LOOPS
8602 /* Beware of "while false; true; do ..."! */
8604 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8605 /* check for RES_DONE is needed for "while ...; do \n done" case */
8607 if (rword == RES_WHILE) {
8609 /* "while false; do...done" - exitcode 0 */
8610 G.last_exitcode = rcode = EXIT_SUCCESS;
8611 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8615 if (rword == RES_UNTIL) {
8617 debug_printf_exec(": until expr is true: breaking\n");
8628 #if ENABLE_HUSH_LOOPS
8633 #if ENABLE_HUSH_CASE
8637 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8641 /* Select which version we will use */
8642 static int run_and_free_list(struct pipe *pi)
8645 debug_printf_exec("run_and_free_list entered\n");
8646 if (!G.o_opt[OPT_O_NOEXEC]) {
8647 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8648 rcode = run_list(pi);
8650 /* free_pipe_list has the side effect of clearing memory.
8651 * In the long run that function can be merged with run_list,
8652 * but doing that now would hobble the debugging effort. */
8654 debug_printf_exec("run_and_free_list return %d\n", rcode);
8659 static void install_sighandlers(unsigned mask)
8661 sighandler_t old_handler;
8663 while ((mask >>= 1) != 0) {
8667 old_handler = install_sighandler(sig, pick_sighandler(sig));
8668 /* POSIX allows shell to re-enable SIGCHLD
8669 * even if it was SIG_IGN on entry.
8670 * Therefore we skip IGN check for it:
8674 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8675 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8677 //if (sig == SIGHUP) continue; - TODO?
8678 if (old_handler == SIG_IGN) {
8679 /* oops... restore back to IGN, and record this fact */
8680 install_sighandler(sig, old_handler);
8681 #if ENABLE_HUSH_TRAP
8683 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8685 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8691 /* Called a few times only (or even once if "sh -c") */
8692 static void install_special_sighandlers(void)
8696 /* Which signals are shell-special? */
8697 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8698 if (G_interactive_fd) {
8699 mask |= SPECIAL_INTERACTIVE_SIGS;
8700 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8701 mask |= SPECIAL_JOBSTOP_SIGS;
8703 /* Careful, do not re-install handlers we already installed */
8704 if (G.special_sig_mask != mask) {
8705 unsigned diff = mask & ~G.special_sig_mask;
8706 G.special_sig_mask = mask;
8707 install_sighandlers(diff);
8713 /* Set handlers to restore tty pgrp and exit */
8714 static void install_fatal_sighandlers(void)
8718 /* We will restore tty pgrp on these signals */
8720 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8721 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8722 + (1 << SIGBUS ) * HUSH_DEBUG
8723 + (1 << SIGSEGV) * HUSH_DEBUG
8724 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8726 /* bash 3.2 seems to handle these just like 'fatal' ones */
8729 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8730 * if we aren't interactive... but in this case
8731 * we never want to restore pgrp on exit, and this fn is not called
8733 /*+ (1 << SIGHUP )*/
8734 /*+ (1 << SIGTERM)*/
8735 /*+ (1 << SIGINT )*/
8737 G_fatal_sig_mask = mask;
8739 install_sighandlers(mask);
8743 static int set_mode(int state, char mode, const char *o_opt)
8748 G.o_opt[OPT_O_NOEXEC] = state;
8751 IF_HUSH_MODE_X(G_x_mode = state;)
8755 /* "set -+o" without parameter.
8756 * in bash, set -o produces this output:
8760 * We always use the second form.
8762 const char *p = o_opt_strings;
8765 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8771 idx = index_in_strings(o_opt_strings, o_opt);
8773 G.o_opt[idx] = state;
8777 G.o_opt[OPT_O_ERREXIT] = state;
8780 return EXIT_FAILURE;
8782 return EXIT_SUCCESS;
8785 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8786 int hush_main(int argc, char **argv)
8789 OPT_login = (1 << 0),
8793 unsigned builtin_argc;
8795 struct variable *cur_var;
8796 struct variable *shell_ver;
8799 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8800 G.last_exitcode = EXIT_SUCCESS;
8802 #if ENABLE_HUSH_FAST
8803 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8806 G.argv0_for_re_execing = argv[0];
8808 /* Deal with HUSH_VERSION */
8809 shell_ver = xzalloc(sizeof(*shell_ver));
8810 shell_ver->flg_export = 1;
8811 shell_ver->flg_read_only = 1;
8812 /* Code which handles ${var<op>...} needs writable values for all variables,
8813 * therefore we xstrdup: */
8814 shell_ver->varstr = xstrdup(hush_version_str);
8815 /* Create shell local variables from the values
8816 * currently living in the environment */
8817 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8818 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8819 G.top_var = shell_ver;
8820 cur_var = G.top_var;
8823 char *value = strchr(*e, '=');
8824 if (value) { /* paranoia */
8825 cur_var->next = xzalloc(sizeof(*cur_var));
8826 cur_var = cur_var->next;
8827 cur_var->varstr = *e;
8828 cur_var->max_len = strlen(*e);
8829 cur_var->flg_export = 1;
8833 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8834 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8835 putenv(shell_ver->varstr);
8838 set_pwd_var(SETFLAG_EXPORT);
8840 #if BASH_HOSTNAME_VAR
8841 /* Set (but not export) HOSTNAME unless already set */
8842 if (!get_local_var_value("HOSTNAME")) {
8845 set_local_var_from_halves("HOSTNAME", uts.nodename);
8847 /* bash also exports SHLVL and _,
8848 * and sets (but doesn't export) the following variables:
8850 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8851 * BASH_VERSION='3.2.0(1)-release'
8853 * MACHTYPE=i386-pc-linux-gnu
8855 * PPID=<NNNNN> - we also do it elsewhere
8866 * PIPESTATUS=([0]="0")
8867 * HISTFILE=/<xxx>/.bash_history
8871 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8873 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8884 #if ENABLE_FEATURE_EDITING
8885 G.line_input_state = new_line_input_t(FOR_SHELL);
8888 /* Initialize some more globals to non-zero values */
8889 cmdedit_update_prompt();
8891 die_func = restore_ttypgrp_and__exit;
8893 /* Shell is non-interactive at first. We need to call
8894 * install_special_sighandlers() if we are going to execute "sh <script>",
8895 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8896 * If we later decide that we are interactive, we run install_special_sighandlers()
8897 * in order to intercept (more) signals.
8901 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8902 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8905 opt = getopt(argc, argv, "+c:exinsl"
8908 # if ENABLE_HUSH_FUNCTIONS
8918 * sh ... -c 'script'
8919 * sh ... -c 'script' ARG0 [ARG1...]
8920 * On NOMMU, if builtin_argc != 0,
8921 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8922 * "" needs to be replaced with NULL
8923 * and BARGV vector fed to builtin function.
8924 * Note: the form without ARG0 never happens:
8925 * sh ... -c 'builtin' BARGV... ""
8928 G.root_pid = getpid();
8929 G.root_ppid = getppid();
8931 G.global_argv = argv + optind;
8932 G.global_argc = argc - optind;
8934 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8935 const struct built_in_command *x;
8937 install_special_sighandlers();
8938 x = find_builtin(optarg);
8939 if (x) { /* paranoia */
8940 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8941 G.global_argv += builtin_argc;
8942 G.global_argv[-1] = NULL; /* replace "" */
8944 G.last_exitcode = x->b_function(argv + optind - 1);
8948 if (!G.global_argv[0]) {
8949 /* -c 'script' (no params): prevent empty $0 */
8950 G.global_argv--; /* points to argv[i] of 'script' */
8951 G.global_argv[0] = argv[0];
8953 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8954 install_special_sighandlers();
8955 parse_and_run_string(optarg);
8958 /* Well, we cannot just declare interactiveness,
8959 * we have to have some stuff (ctty, etc) */
8960 /* G_interactive_fd++; */
8963 /* "-s" means "read from stdin", but this is how we always
8964 * operate, so simply do nothing here. */
8970 case '<': /* "big heredoc" support */
8971 full_write1_str(optarg);
8974 unsigned long long empty_trap_mask;
8976 G.root_pid = bb_strtou(optarg, &optarg, 16);
8978 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8980 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8982 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8984 builtin_argc = bb_strtou(optarg, &optarg, 16);
8986 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8987 if (empty_trap_mask != 0) {
8988 IF_HUSH_TRAP(int sig;)
8989 install_special_sighandlers();
8990 # if ENABLE_HUSH_TRAP
8991 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8992 for (sig = 1; sig < NSIG; sig++) {
8993 if (empty_trap_mask & (1LL << sig)) {
8994 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8995 install_sighandler(sig, SIG_IGN);
9000 # if ENABLE_HUSH_LOOPS
9002 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
9008 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9010 # if ENABLE_HUSH_FUNCTIONS
9012 struct function *funcp = new_function(optarg);
9013 /* funcp->name is already set to optarg */
9014 /* funcp->body is set to NULL. It's a special case. */
9015 funcp->body_as_string = argv[optind];
9024 if (set_mode(1, opt, NULL) == 0) /* no error */
9028 fprintf(stderr, "Usage: sh [FILE]...\n"
9029 " or: sh -c command [args]...\n\n");
9035 } /* option parsing loop */
9037 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9038 G.global_argc = argc - (optind - 1);
9039 G.global_argv = argv + (optind - 1);
9040 G.global_argv[0] = argv[0];
9043 G.root_pid = getpid();
9044 G.root_ppid = getppid();
9047 /* If we are login shell... */
9048 if (flags & OPT_login) {
9050 debug_printf("sourcing /etc/profile\n");
9051 input = fopen_for_read("/etc/profile");
9052 if (input != NULL) {
9053 remember_FILE(input);
9054 install_special_sighandlers();
9055 parse_and_run_file(input);
9056 fclose_and_forget(input);
9058 /* bash: after sourcing /etc/profile,
9059 * tries to source (in the given order):
9060 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9061 * stopping on first found. --noprofile turns this off.
9062 * bash also sources ~/.bash_logout on exit.
9063 * If called as sh, skips .bash_XXX files.
9067 if (G.global_argv[1]) {
9070 * "bash <script>" (which is never interactive (unless -i?))
9071 * sources $BASH_ENV here (without scanning $PATH).
9072 * If called as sh, does the same but with $ENV.
9073 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9077 debug_printf("running script '%s'\n", G.global_argv[0]);
9078 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9079 input = xfopen_for_read(G.global_argv[0]);
9080 xfunc_error_retval = 1;
9081 remember_FILE(input);
9082 install_special_sighandlers();
9083 parse_and_run_file(input);
9084 #if ENABLE_FEATURE_CLEAN_UP
9085 fclose_and_forget(input);
9090 /* Up to here, shell was non-interactive. Now it may become one.
9091 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9094 /* A shell is interactive if the '-i' flag was given,
9095 * or if all of the following conditions are met:
9097 * no arguments remaining or the -s flag given
9098 * standard input is a terminal
9099 * standard output is a terminal
9100 * Refer to Posix.2, the description of the 'sh' utility.
9103 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9104 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9105 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9106 if (G_saved_tty_pgrp < 0)
9107 G_saved_tty_pgrp = 0;
9109 /* try to dup stdin to high fd#, >= 255 */
9110 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9111 if (G_interactive_fd < 0) {
9112 /* try to dup to any fd */
9113 G_interactive_fd = dup(STDIN_FILENO);
9114 if (G_interactive_fd < 0) {
9116 G_interactive_fd = 0;
9117 G_saved_tty_pgrp = 0;
9120 // TODO: track & disallow any attempts of user
9121 // to (inadvertently) close/redirect G_interactive_fd
9123 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9124 if (G_interactive_fd) {
9125 close_on_exec_on(G_interactive_fd);
9127 if (G_saved_tty_pgrp) {
9128 /* If we were run as 'hush &', sleep until we are
9129 * in the foreground (tty pgrp == our pgrp).
9130 * If we get started under a job aware app (like bash),
9131 * make sure we are now in charge so we don't fight over
9132 * who gets the foreground */
9134 pid_t shell_pgrp = getpgrp();
9135 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9136 if (G_saved_tty_pgrp == shell_pgrp)
9138 /* send TTIN to ourself (should stop us) */
9139 kill(- shell_pgrp, SIGTTIN);
9143 /* Install more signal handlers */
9144 install_special_sighandlers();
9146 if (G_saved_tty_pgrp) {
9147 /* Set other signals to restore saved_tty_pgrp */
9148 install_fatal_sighandlers();
9149 /* Put ourselves in our own process group
9150 * (bash, too, does this only if ctty is available) */
9151 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9152 /* Grab control of the terminal */
9153 tcsetpgrp(G_interactive_fd, getpid());
9155 enable_restore_tty_pgrp_on_exit();
9157 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9159 const char *hp = get_local_var_value("HISTFILE");
9161 hp = get_local_var_value("HOME");
9163 hp = concat_path_file(hp, ".hush_history");
9168 G.line_input_state->hist_file = hp;
9169 //set_local_var(xasprintf("HISTFILE=%s", ...));
9171 # if ENABLE_FEATURE_SH_HISTFILESIZE
9172 hp = get_local_var_value("HISTFILESIZE");
9173 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9178 install_special_sighandlers();
9180 #elif ENABLE_HUSH_INTERACTIVE
9181 /* No job control compiled in, only prompt/line editing */
9182 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9183 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9184 if (G_interactive_fd < 0) {
9185 /* try to dup to any fd */
9186 G_interactive_fd = dup(STDIN_FILENO);
9187 if (G_interactive_fd < 0)
9189 G_interactive_fd = 0;
9192 if (G_interactive_fd) {
9193 close_on_exec_on(G_interactive_fd);
9195 install_special_sighandlers();
9197 /* We have interactiveness code disabled */
9198 install_special_sighandlers();
9201 * if interactive but not a login shell, sources ~/.bashrc
9202 * (--norc turns this off, --rcfile <file> overrides)
9205 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9206 /* note: ash and hush share this string */
9207 printf("\n\n%s %s\n"
9208 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9211 "hush - the humble shell"
9215 parse_and_run_file(stdin);
9218 hush_exit(G.last_exitcode);
9225 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9230 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9231 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9233 int argc = string_array_len(argv);
9234 return applet_main_func(argc, argv);
9237 #if ENABLE_HUSH_TEST || BASH_TEST2
9238 static int FAST_FUNC builtin_test(char **argv)
9240 return run_applet_main(argv, test_main);
9243 #if ENABLE_HUSH_ECHO
9244 static int FAST_FUNC builtin_echo(char **argv)
9246 return run_applet_main(argv, echo_main);
9249 #if ENABLE_HUSH_PRINTF
9250 static int FAST_FUNC builtin_printf(char **argv)
9252 return run_applet_main(argv, printf_main);
9256 #if ENABLE_HUSH_HELP
9257 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9259 const struct built_in_command *x;
9262 "Built-in commands:\n"
9263 "------------------\n");
9264 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9266 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9268 return EXIT_SUCCESS;
9272 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9273 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9275 show_history(G.line_input_state);
9276 return EXIT_SUCCESS;
9280 static char **skip_dash_dash(char **argv)
9283 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9288 static int FAST_FUNC builtin_cd(char **argv)
9292 argv = skip_dash_dash(argv);
9294 if (newdir == NULL) {
9295 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9296 * bash says "bash: cd: HOME not set" and does nothing
9299 const char *home = get_local_var_value("HOME");
9300 newdir = home ? home : "/";
9302 if (chdir(newdir)) {
9303 /* Mimic bash message exactly */
9304 bb_perror_msg("cd: %s", newdir);
9305 return EXIT_FAILURE;
9307 /* Read current dir (get_cwd(1) is inside) and set PWD.
9308 * Note: do not enforce exporting. If PWD was unset or unexported,
9309 * set it again, but do not export. bash does the same.
9311 set_pwd_var(/*flag:*/ 0);
9312 return EXIT_SUCCESS;
9315 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9318 return EXIT_SUCCESS;
9321 static int FAST_FUNC builtin_eval(char **argv)
9323 int rcode = EXIT_SUCCESS;
9325 argv = skip_dash_dash(argv);
9327 char *str = expand_strvec_to_string(argv);
9329 * eval "echo Hi; done" ("done" is syntax error):
9330 * "echo Hi" will not execute too.
9332 parse_and_run_string(str);
9334 rcode = G.last_exitcode;
9339 static int FAST_FUNC builtin_exec(char **argv)
9341 argv = skip_dash_dash(argv);
9342 if (argv[0] == NULL)
9343 return EXIT_SUCCESS; /* bash does this */
9345 /* Careful: we can end up here after [v]fork. Do not restore
9346 * tty pgrp then, only top-level shell process does that */
9347 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9348 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9350 /* Saved-redirect fds, script fds and G_interactive_fd are still
9351 * open here. However, they are all CLOEXEC, and execv below
9352 * closes them. Try interactive "exec ls -l /proc/self/fd",
9353 * it should show no extra open fds in the "ls" process.
9354 * If we'd try to run builtins/NOEXECs, this would need improving.
9356 //close_saved_fds_and_FILE_fds();
9358 /* TODO: if exec fails, bash does NOT exit! We do.
9359 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9360 * and tcsetpgrp, and this is inherently racy.
9362 execvp_or_die(argv);
9365 static int FAST_FUNC builtin_exit(char **argv)
9367 debug_printf_exec("%s()\n", __func__);
9369 /* interactive bash:
9370 * # trap "echo EEE" EXIT
9373 * There are stopped jobs.
9374 * (if there are _stopped_ jobs, running ones don't count)
9377 * EEE (then bash exits)
9379 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9382 /* note: EXIT trap is run by hush_exit */
9383 argv = skip_dash_dash(argv);
9384 if (argv[0] == NULL)
9385 hush_exit(G.last_exitcode);
9386 /* mimic bash: exit 123abc == exit 255 + error msg */
9387 xfunc_error_retval = 255;
9388 /* bash: exit -2 == exit 254, no error msg */
9389 hush_exit(xatoi(argv[0]) & 0xff);
9392 #if ENABLE_HUSH_TYPE
9393 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9394 static int FAST_FUNC builtin_type(char **argv)
9396 int ret = EXIT_SUCCESS;
9402 if (0) {} /* make conditional compile easier below */
9403 /*else if (find_alias(*argv))
9404 type = "an alias";*/
9405 #if ENABLE_HUSH_FUNCTIONS
9406 else if (find_function(*argv))
9407 type = "a function";
9409 else if (find_builtin(*argv))
9410 type = "a shell builtin";
9411 else if ((path = find_in_path(*argv)) != NULL)
9414 bb_error_msg("type: %s: not found", *argv);
9419 printf("%s is %s\n", *argv, type);
9427 #if ENABLE_HUSH_READ
9428 /* Interruptibility of read builtin in bash
9429 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9431 * Empty trap makes read ignore corresponding signal, for any signal.
9434 * - terminates non-interactive shell;
9435 * - interrupts read in interactive shell;
9436 * if it has non-empty trap:
9437 * - executes trap and returns to command prompt in interactive shell;
9438 * - executes trap and returns to read in non-interactive shell;
9440 * - is ignored (does not interrupt) read in interactive shell;
9441 * - terminates non-interactive shell;
9442 * if it has non-empty trap:
9443 * - executes trap and returns to read;
9445 * - terminates shell (regardless of interactivity);
9446 * if it has non-empty trap:
9447 * - executes trap and returns to read;
9448 * SIGCHLD from children:
9449 * - does not interrupt read regardless of interactivity:
9450 * try: sleep 1 & read x; echo $x
9452 static int FAST_FUNC builtin_read(char **argv)
9459 char *opt_d = NULL; /* optimized out if !BASH */
9463 /* "!": do not abort on errors.
9464 * Option string must start with "sr" to match BUILTIN_READ_xxx
9466 read_flags = getopt32(argv,
9468 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9470 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9473 if (read_flags == (uint32_t)-1)
9474 return EXIT_FAILURE;
9476 ifs = get_local_var_value("IFS"); /* can be NULL */
9479 r = shell_builtin_read(set_local_var_from_halves,
9490 if ((uintptr_t)r == 1 && errno == EINTR) {
9491 unsigned sig = check_and_run_traps();
9496 if ((uintptr_t)r > 1) {
9497 bb_error_msg("%s", r);
9498 r = (char*)(uintptr_t)1;
9501 return (uintptr_t)r;
9505 #if ENABLE_HUSH_UMASK
9506 static int FAST_FUNC builtin_umask(char **argv)
9513 argv = skip_dash_dash(argv);
9515 mode_t old_mask = mask;
9517 /* numeric umasks are taken as-is */
9518 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9519 if (!isdigit(argv[0][0]))
9521 mask = bb_parse_mode(argv[0], mask);
9522 if (!isdigit(argv[0][0]))
9524 if ((unsigned)mask > 0777) {
9527 * bash: umask: 'q': invalid symbolic mode operator
9528 * bash: umask: 999: octal number out of range
9530 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9535 printf("%04o\n", (unsigned) mask);
9536 /* fall through and restore mask which we set to 0 */
9540 return !rc; /* rc != 0 - success */
9544 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9545 static void print_escaped(const char *s)
9550 const char *p = strchrnul(s, '\'');
9551 /* print 'xxxx', possibly just '' */
9552 printf("'%.*s'", (int)(p - s), s);
9557 /* s points to '; print "'''...'''" */
9559 do putchar('\''); while (*++s == '\'');
9565 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9566 static int helper_export_local(char **argv, unsigned flags)
9570 char *name_end = strchrnul(name, '=');
9572 /* So far we do not check that name is valid (TODO?) */
9574 if (*name_end == '\0') {
9575 struct variable *var, **vpp;
9577 vpp = get_ptr_to_local_var(name, name_end - name);
9578 var = vpp ? *vpp : NULL;
9580 if (flags & SETFLAG_UNEXPORT) {
9581 /* export -n NAME (without =VALUE) */
9583 var->flg_export = 0;
9584 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9586 } /* else: export -n NOT_EXISTING_VAR: no-op */
9589 if (flags & SETFLAG_EXPORT) {
9590 /* export NAME (without =VALUE) */
9592 var->flg_export = 1;
9593 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9594 putenv(var->varstr);
9598 if (flags & SETFLAG_MAKE_RO) {
9599 /* readonly NAME (without =VALUE) */
9601 var->flg_read_only = 1;
9605 # if ENABLE_HUSH_LOCAL
9606 /* Is this "local" bltin? */
9607 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9608 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9609 if (var && var->func_nest_level == lvl) {
9610 /* "local x=abc; ...; local x" - ignore second local decl */
9615 /* Exporting non-existing variable.
9616 * bash does not put it in environment,
9617 * but remembers that it is exported,
9618 * and does put it in env when it is set later.
9619 * We just set it to "" and export.
9621 /* Or, it's "local NAME" (without =VALUE).
9622 * bash sets the value to "".
9624 /* Or, it's "readonly NAME" (without =VALUE).
9625 * bash remembers NAME and disallows its creation
9628 name = xasprintf("%s=", name);
9630 /* (Un)exporting/making local NAME=VALUE */
9631 name = xstrdup(name);
9633 if (set_local_var(name, flags))
9634 return EXIT_FAILURE;
9636 return EXIT_SUCCESS;
9640 #if ENABLE_HUSH_EXPORT
9641 static int FAST_FUNC builtin_export(char **argv)
9643 unsigned opt_unexport;
9645 #if ENABLE_HUSH_EXPORT_N
9646 /* "!": do not abort on errors */
9647 opt_unexport = getopt32(argv, "!n");
9648 if (opt_unexport == (uint32_t)-1)
9649 return EXIT_FAILURE;
9656 if (argv[0] == NULL) {
9663 /* ash emits: export VAR='VAL'
9664 * bash: declare -x VAR="VAL"
9665 * we follow ash example */
9666 const char *s = *e++;
9667 const char *p = strchr(s, '=');
9669 if (!p) /* wtf? take next variable */
9672 printf("export %.*s", (int)(p - s) + 1, s);
9673 print_escaped(p + 1);
9677 /*fflush_all(); - done after each builtin anyway */
9679 return EXIT_SUCCESS;
9682 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9686 #if ENABLE_HUSH_LOCAL
9687 static int FAST_FUNC builtin_local(char **argv)
9689 if (G.func_nest_level == 0) {
9690 bb_error_msg("%s: not in a function", argv[0]);
9691 return EXIT_FAILURE; /* bash compat */
9694 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9698 #if ENABLE_HUSH_READONLY
9699 static int FAST_FUNC builtin_readonly(char **argv)
9702 if (*argv == NULL) {
9703 /* bash: readonly [-p]: list all readonly VARs
9704 * (-p has no effect in bash)
9707 for (e = G.top_var; e; e = e->next) {
9708 if (e->flg_read_only) {
9709 //TODO: quote value: readonly VAR='VAL'
9710 printf("readonly %s\n", e->varstr);
9713 return EXIT_SUCCESS;
9715 return helper_export_local(argv, SETFLAG_MAKE_RO);
9719 #if ENABLE_HUSH_UNSET
9720 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9721 static int FAST_FUNC builtin_unset(char **argv)
9726 /* "!": do not abort on errors */
9727 /* "+": stop at 1st non-option */
9728 opts = getopt32(argv, "!+vf");
9729 if (opts == (unsigned)-1)
9730 return EXIT_FAILURE;
9732 bb_error_msg("unset: -v and -f are exclusive");
9733 return EXIT_FAILURE;
9739 if (!(opts & 2)) { /* not -f */
9740 if (unset_local_var(*argv)) {
9741 /* unset <nonexistent_var> doesn't fail.
9742 * Error is when one tries to unset RO var.
9743 * Message was printed by unset_local_var. */
9747 # if ENABLE_HUSH_FUNCTIONS
9759 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9760 * built-in 'set' handler
9762 * set [-abCefhmnuvx] [-o option] [argument...]
9763 * set [+abCefhmnuvx] [+o option] [argument...]
9764 * set -- [argument...]
9767 * Implementations shall support the options in both their hyphen and
9768 * plus-sign forms. These options can also be specified as options to sh.
9770 * Write out all variables and their values: set
9771 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9772 * Turn on the -x and -v options: set -xv
9773 * Unset all positional parameters: set --
9774 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9775 * Set the positional parameters to the expansion of x, even if x expands
9776 * with a leading '-' or '+': set -- $x
9778 * So far, we only support "set -- [argument...]" and some of the short names.
9780 static int FAST_FUNC builtin_set(char **argv)
9783 char **pp, **g_argv;
9784 char *arg = *++argv;
9788 for (e = G.top_var; e; e = e->next)
9790 return EXIT_SUCCESS;
9794 if (strcmp(arg, "--") == 0) {
9798 if (arg[0] != '+' && arg[0] != '-')
9800 for (n = 1; arg[n]; ++n) {
9801 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9803 if (arg[n] == 'o' && argv[1])
9806 } while ((arg = *++argv) != NULL);
9807 /* Now argv[0] is 1st argument */
9810 return EXIT_SUCCESS;
9813 /* NB: G.global_argv[0] ($0) is never freed/changed */
9814 g_argv = G.global_argv;
9815 if (G.global_args_malloced) {
9821 G.global_args_malloced = 1;
9822 pp = xzalloc(sizeof(pp[0]) * 2);
9823 pp[0] = g_argv[0]; /* retain $0 */
9826 /* This realloc's G.global_argv */
9827 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9829 G.global_argc = 1 + string_array_len(pp + 1);
9831 return EXIT_SUCCESS;
9833 /* Nothing known, so abort */
9835 bb_error_msg("set: %s: invalid option", arg);
9836 return EXIT_FAILURE;
9840 static int FAST_FUNC builtin_shift(char **argv)
9843 argv = skip_dash_dash(argv);
9845 n = bb_strtou(argv[0], NULL, 10);
9846 if (errno || n < 0) {
9847 /* shared string with ash.c */
9848 bb_error_msg("Illegal number: %s", argv[0]);
9850 * ash aborts in this case.
9851 * bash prints error message and set $? to 1.
9852 * Interestingly, for "shift 99999" bash does not
9853 * print error message, but does set $? to 1
9854 * (and does no shifting at all).
9858 if (n >= 0 && n < G.global_argc) {
9859 if (G_global_args_malloced) {
9862 free(G.global_argv[m++]);
9865 memmove(&G.global_argv[1], &G.global_argv[n+1],
9866 G.global_argc * sizeof(G.global_argv[0]));
9867 return EXIT_SUCCESS;
9869 return EXIT_FAILURE;
9872 #if ENABLE_HUSH_GETOPTS
9873 static int FAST_FUNC builtin_getopts(char **argv)
9877 If an invalid option is seen, getopts places ? into VAR and, if
9878 not silent, prints an error message and unsets OPTARG. If
9879 getopts is silent, the option character found is placed in
9880 OPTARG and no diagnostic message is printed.
9882 If a required argument is not found, and getopts is not silent,
9883 a question mark (?) is placed in VAR, OPTARG is unset, and a
9884 diagnostic message is printed. If getopts is silent, then a
9885 colon (:) is placed in VAR and OPTARG is set to the option
9888 Test that VAR is a valid variable name?
9891 const char *cp, *optstring, *var;
9894 optstring = *++argv;
9895 if (!optstring || !(var = *++argv)) {
9896 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
9897 return EXIT_FAILURE;
9900 cp = get_local_var_value("OPTERR");
9901 opterr = cp ? atoi(cp) : 1;
9902 cp = get_local_var_value("OPTIND");
9903 optind = cp ? atoi(cp) : 0;
9906 /* getopts stops on first non-option. Add "+" to force that */
9907 /*if (optstring[0] != '+')*/ {
9908 char *s = alloca(strlen(optstring) + 2);
9909 sprintf(s, "+%s", optstring);
9914 argv[0] = G.global_argv[0]; /* for error messages */
9916 argv = G.global_argv;
9917 c = getopt(string_array_len(argv), argv, optstring);
9918 exitcode = EXIT_SUCCESS;
9919 if (c < 0) { /* -1: end of options */
9920 exitcode = EXIT_FAILURE;
9924 set_local_var_from_halves("OPTARG", optarg);
9926 unset_local_var("OPTARG");
9929 set_local_var_from_halves(var, cbuf);
9930 set_local_var_from_halves("OPTIND", utoa(optind));
9935 static int FAST_FUNC builtin_source(char **argv)
9937 char *arg_path, *filename;
9940 char *args_need_save;
9941 #if ENABLE_HUSH_FUNCTIONS
9945 argv = skip_dash_dash(argv);
9948 /* bash says: "bash: .: filename argument required" */
9949 return 2; /* bash compat */
9952 if (!strchr(filename, '/')) {
9953 arg_path = find_in_path(filename);
9955 filename = arg_path;
9957 input = remember_FILE(fopen_or_warn(filename, "r"));
9960 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9961 /* POSIX: non-interactive shell should abort here,
9962 * not merely fail. So far no one complained :)
9964 return EXIT_FAILURE;
9967 #if ENABLE_HUSH_FUNCTIONS
9968 sv_flg = G_flag_return_in_progress;
9969 /* "we are inside sourced file, ok to use return" */
9970 G_flag_return_in_progress = -1;
9972 args_need_save = argv[1]; /* used as a boolean variable */
9974 save_and_replace_G_args(&sv, argv);
9976 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9977 G.last_exitcode = 0;
9978 parse_and_run_file(input);
9979 fclose_and_forget(input);
9981 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
9982 restore_G_args(&sv, argv);
9983 #if ENABLE_HUSH_FUNCTIONS
9984 G_flag_return_in_progress = sv_flg;
9987 return G.last_exitcode;
9990 #if ENABLE_HUSH_TRAP
9991 static int FAST_FUNC builtin_trap(char **argv)
9997 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10002 /* No args: print all trapped */
10003 for (i = 0; i < NSIG; ++i) {
10005 printf("trap -- ");
10006 print_escaped(G_traps[i]);
10007 /* note: bash adds "SIG", but only if invoked
10008 * as "bash". If called as "sh", or if set -o posix,
10009 * then it prints short signal names.
10010 * We are printing short names: */
10011 printf(" %s\n", get_signame(i));
10014 /*fflush_all(); - done after each builtin anyway */
10015 return EXIT_SUCCESS;
10019 /* If first arg is a number: reset all specified signals */
10020 sig = bb_strtou(*argv, NULL, 10);
10024 ret = EXIT_SUCCESS;
10026 sighandler_t handler;
10028 sig = get_signum(*argv++);
10030 ret = EXIT_FAILURE;
10031 /* Mimic bash message exactly */
10032 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
10036 free(G_traps[sig]);
10037 G_traps[sig] = xstrdup(new_cmd);
10039 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
10040 get_signame(sig), sig, G_traps[sig]);
10042 /* There is no signal for 0 (EXIT) */
10047 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10049 /* We are removing trap handler */
10050 handler = pick_sighandler(sig);
10051 install_sighandler(sig, handler);
10056 if (!argv[1]) { /* no second arg */
10057 bb_error_msg("trap: invalid arguments");
10058 return EXIT_FAILURE;
10061 /* First arg is "-": reset all specified to default */
10062 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10063 /* Everything else: set arg as signal handler
10064 * (includes "" case, which ignores signal) */
10065 if (argv[0][0] == '-') {
10066 if (argv[0][1] == '\0') { /* "-" */
10067 /* new_cmd remains NULL: "reset these sigs" */
10070 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10073 /* else: "-something", no special meaning */
10078 goto process_sig_list;
10082 #if ENABLE_HUSH_JOB
10083 static struct pipe *parse_jobspec(const char *str)
10088 if (sscanf(str, "%%%u", &jobnum) != 1) {
10090 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10092 bb_error_msg("bad argument '%s'", str);
10095 /* It is "%%", "%+" or "%" - current job */
10096 jobnum = G.last_jobid;
10098 bb_error_msg("no current job");
10102 for (pi = G.job_list; pi; pi = pi->next) {
10103 if (pi->jobid == jobnum) {
10107 bb_error_msg("%u: no such job", jobnum);
10111 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10114 const char *status_string;
10116 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10117 for (job = G.job_list; job; job = job->next) {
10118 if (job->alive_cmds == job->stopped_cmds)
10119 status_string = "Stopped";
10121 status_string = "Running";
10123 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10126 clean_up_last_dead_job();
10128 return EXIT_SUCCESS;
10131 /* built-in 'fg' and 'bg' handler */
10132 static int FAST_FUNC builtin_fg_bg(char **argv)
10137 if (!G_interactive_fd)
10138 return EXIT_FAILURE;
10140 /* If they gave us no args, assume they want the last backgrounded task */
10142 for (pi = G.job_list; pi; pi = pi->next) {
10143 if (pi->jobid == G.last_jobid) {
10147 bb_error_msg("%s: no current job", argv[0]);
10148 return EXIT_FAILURE;
10151 pi = parse_jobspec(argv[1]);
10153 return EXIT_FAILURE;
10155 /* TODO: bash prints a string representation
10156 * of job being foregrounded (like "sleep 1 | cat") */
10157 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10158 /* Put the job into the foreground. */
10159 tcsetpgrp(G_interactive_fd, pi->pgrp);
10162 /* Restart the processes in the job */
10163 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10164 for (i = 0; i < pi->num_cmds; i++) {
10165 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10167 pi->stopped_cmds = 0;
10169 i = kill(- pi->pgrp, SIGCONT);
10171 if (errno == ESRCH) {
10172 delete_finished_job(pi);
10173 return EXIT_SUCCESS;
10175 bb_perror_msg("kill (SIGCONT)");
10178 if (argv[0][0] == 'f') {
10179 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10180 return checkjobs_and_fg_shell(pi);
10182 return EXIT_SUCCESS;
10186 #if ENABLE_HUSH_KILL
10187 static int FAST_FUNC builtin_kill(char **argv)
10191 # if ENABLE_HUSH_JOB
10192 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10200 if (argv[i][0] != '%')
10203 * "kill %N" - job kill
10204 * Converting to pgrp / pid kill
10206 pi = parse_jobspec(argv[i]);
10208 /* Eat bad jobspec */
10212 argv[j - 1] = argv[j];
10219 * In jobs started under job control, we signal
10220 * entire process group by kill -PGRP_ID.
10221 * This happens, f.e., in interactive shell.
10223 * Otherwise, we signal each child via
10224 * kill PID1 PID2 PID3.
10226 * sh -c 'sleep 1|sleep 1 & kill %1'
10227 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10228 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10230 n = G_interactive_fd ? 1 : pi->num_cmds;
10231 dst = alloca(n * sizeof(int)*4);
10233 if (G_interactive_fd)
10234 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10235 else for (j = 0; j < n; j++) {
10236 struct command *cmd = &pi->cmds[j];
10237 /* Skip exited members of the job */
10241 * kill_main has matching code to expect
10242 * leading space. Needed to not confuse
10243 * negative pids with "kill -SIGNAL_NO" syntax
10245 dst += sprintf(dst, " %u", (int)cmd->pid);
10248 } while (argv[++i]);
10252 if (argv[1] || ret == 0) {
10253 ret = run_applet_main(argv, kill_main);
10255 /* else: ret = 1, "kill %bad_jobspec" case */
10260 #if ENABLE_HUSH_WAIT
10261 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10262 #if !ENABLE_HUSH_JOB
10263 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10265 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10272 if (!sigisemptyset(&G.pending_set))
10275 /* waitpid is not interruptible by SA_RESTARTed
10276 * signals which we use. Thus, this ugly dance:
10279 /* Make sure possible SIGCHLD is stored in kernel's
10280 * pending signal mask before we call waitpid.
10281 * Or else we may race with SIGCHLD, lose it,
10282 * and get stuck in sigsuspend...
10284 sigfillset(&oldset); /* block all signals, remember old set */
10285 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10287 if (!sigisemptyset(&G.pending_set)) {
10288 /* Crap! we raced with some signal! */
10292 /*errno = 0; - checkjobs does this */
10293 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10294 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10295 debug_printf_exec("checkjobs:%d\n", ret);
10296 #if ENABLE_HUSH_JOB
10297 if (waitfor_pipe) {
10298 int rcode = job_exited_or_stopped(waitfor_pipe);
10299 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10302 sigprocmask(SIG_SETMASK, &oldset, NULL);
10307 /* if ECHILD, there are no children (ret is -1 or 0) */
10308 /* if ret == 0, no children changed state */
10309 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10310 if (errno == ECHILD || ret) {
10312 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10314 sigprocmask(SIG_SETMASK, &oldset, NULL);
10317 /* Wait for SIGCHLD or any other signal */
10318 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10319 /* Note: sigsuspend invokes signal handler */
10320 sigsuspend(&oldset);
10322 sigprocmask(SIG_SETMASK, &oldset, NULL);
10324 /* So, did we get a signal? */
10325 sig = check_and_run_traps();
10326 if (sig /*&& sig != SIGCHLD - always true */) {
10327 /* Do this for any (non-ignored) signal, not only for ^C */
10331 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10336 static int FAST_FUNC builtin_wait(char **argv)
10341 argv = skip_dash_dash(argv);
10342 if (argv[0] == NULL) {
10343 /* Don't care about wait results */
10344 /* Note 1: must wait until there are no more children */
10345 /* Note 2: must be interruptible */
10347 * $ sleep 3 & sleep 6 & wait
10348 * [1] 30934 sleep 3
10349 * [2] 30935 sleep 6
10352 * $ sleep 3 & sleep 6 & wait
10353 * [1] 30936 sleep 3
10354 * [2] 30937 sleep 6
10356 * ^C <-- after ~4 sec from keyboard
10359 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10363 pid_t pid = bb_strtou(*argv, NULL, 10);
10364 if (errno || pid <= 0) {
10365 #if ENABLE_HUSH_JOB
10366 if (argv[0][0] == '%') {
10367 struct pipe *wait_pipe;
10368 ret = 127; /* bash compat for bad jobspecs */
10369 wait_pipe = parse_jobspec(*argv);
10371 ret = job_exited_or_stopped(wait_pipe);
10373 ret = wait_for_child_or_signal(wait_pipe, 0);
10375 /* waiting on "last dead job" removes it */
10376 clean_up_last_dead_job();
10379 /* else: parse_jobspec() already emitted error msg */
10383 /* mimic bash message */
10384 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10385 ret = EXIT_FAILURE;
10386 continue; /* bash checks all argv[] */
10389 /* Do we have such child? */
10390 ret = waitpid(pid, &status, WNOHANG);
10394 if (errno == ECHILD) {
10395 if (pid == G.last_bg_pid) {
10396 /* "wait $!" but last bg task has already exited. Try:
10397 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10398 * In bash it prints exitcode 0, then 3.
10399 * In dash, it is 127.
10401 ret = G.last_bg_pid_exitcode;
10403 /* Example: "wait 1". mimic bash message */
10404 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10408 bb_perror_msg("wait %s", *argv);
10410 continue; /* bash checks all argv[] */
10413 /* Yes, and it still runs */
10414 ret = wait_for_child_or_signal(NULL, pid);
10416 /* Yes, and it just exited */
10417 process_wait_result(NULL, pid, status);
10418 ret = WEXITSTATUS(status);
10419 if (WIFSIGNALED(status))
10420 ret = 128 + WTERMSIG(status);
10428 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10429 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10432 def = bb_strtou(argv[1], NULL, 10);
10433 if (errno || def < def_min || argv[2]) {
10434 bb_error_msg("%s: bad arguments", argv[0]);
10442 #if ENABLE_HUSH_LOOPS
10443 static int FAST_FUNC builtin_break(char **argv)
10446 if (G.depth_of_loop == 0) {
10447 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10448 /* if we came from builtin_continue(), need to undo "= 1" */
10449 G.flag_break_continue = 0;
10450 return EXIT_SUCCESS; /* bash compat */
10452 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10454 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10455 if (depth == UINT_MAX)
10456 G.flag_break_continue = BC_BREAK;
10457 if (G.depth_of_loop < depth)
10458 G.depth_break_continue = G.depth_of_loop;
10460 return EXIT_SUCCESS;
10463 static int FAST_FUNC builtin_continue(char **argv)
10465 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10466 return builtin_break(argv);
10470 #if ENABLE_HUSH_FUNCTIONS
10471 static int FAST_FUNC builtin_return(char **argv)
10475 if (G_flag_return_in_progress != -1) {
10476 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10477 return EXIT_FAILURE; /* bash compat */
10480 G_flag_return_in_progress = 1;
10483 * out of range: wraps around at 256, does not error out
10484 * non-numeric param:
10485 * f() { false; return qwe; }; f; echo $?
10486 * bash: return: qwe: numeric argument required <== we do this
10487 * 255 <== we also do this
10489 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10494 #if ENABLE_HUSH_TIMES
10495 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10497 static const uint8_t times_tbl[] ALIGN1 = {
10498 ' ', offsetof(struct tms, tms_utime),
10499 '\n', offsetof(struct tms, tms_stime),
10500 ' ', offsetof(struct tms, tms_cutime),
10501 '\n', offsetof(struct tms, tms_cstime),
10508 clk_tck = bb_clk_tck();
10513 unsigned sec, frac;
10515 t = *(clock_t *)(((char *) &buf) + p[1]);
10517 frac = t % clk_tck;
10518 printf("%um%u.%03us%c",
10519 sec / 60, sec % 60,
10520 (frac * 1000) / clk_tck,
10525 return EXIT_SUCCESS;
10529 #if ENABLE_HUSH_MEMLEAK
10530 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10535 # ifdef M_TRIM_THRESHOLD
10536 /* Optional. Reduces probability of false positives */
10539 /* Crude attempt to find where "free memory" starts,
10540 * sans fragmentation. */
10542 l = (unsigned long)p;
10545 if (l < (unsigned long)p) l = (unsigned long)p;
10551 struct mallinfo mi = mallinfo();
10552 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10553 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10557 if (!G.memleak_value)
10558 G.memleak_value = l;
10560 l -= G.memleak_value;
10567 /* Exitcode is "how many kilobytes we leaked since 1st call" */