1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
88 //config: hush is a small shell (25k). It handles the normal flow control
89 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
90 //config: case/esac. Redirections, here documents, $((arithmetic))
91 //config: and functions are supported.
93 //config: It will compile and work on no-mmu systems.
95 //config: It does not handle select, aliases, tilde expansion,
96 //config: &>file and >&file redirection of stdout+stderr.
98 //config:config HUSH_BASH_COMPAT
99 //config: bool "bash-compatible extensions"
101 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
103 //config:config HUSH_BRACE_EXPANSION
104 //config: bool "Brace expansion"
106 //config: depends on HUSH_BASH_COMPAT
108 //config: Enable {abc,def} extension.
110 //config:config HUSH_INTERACTIVE
111 //config: bool "Interactive mode"
113 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
115 //config: Enable interactive mode (prompt and command editing).
116 //config: Without this, hush simply reads and executes commands
117 //config: from stdin just like a shell script from a file.
118 //config: No prompt, no PS1/PS2 magic shell variables.
120 //config:config HUSH_SAVEHISTORY
121 //config: bool "Save command history to .hush_history"
123 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
125 //config:config HUSH_JOB
126 //config: bool "Job control"
128 //config: depends on HUSH_INTERACTIVE
130 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
131 //config: command (not entire shell), fg/bg builtins work. Without this option,
132 //config: "cmd &" still works by simply spawning a process and immediately
133 //config: prompting for next command (or executing next command in a script),
134 //config: but no separate process group is formed.
136 //config:config HUSH_TICK
137 //config: bool "Support process substitution"
139 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
141 //config: Enable `command` and $(command).
143 //config:config HUSH_IF
144 //config: bool "Support if/then/elif/else/fi"
146 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
148 //config:config HUSH_LOOPS
149 //config: bool "Support for, while and until loops"
151 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
153 //config:config HUSH_CASE
154 //config: bool "Support case ... esac statement"
156 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
158 //config: Enable case ... esac statement. +400 bytes.
160 //config:config HUSH_FUNCTIONS
161 //config: bool "Support funcname() { commands; } syntax"
163 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
165 //config: Enable support for shell functions. +800 bytes.
167 //config:config HUSH_LOCAL
168 //config: bool "local builtin"
170 //config: depends on HUSH_FUNCTIONS
172 //config: Enable support for local variables in functions.
174 //config:config HUSH_RANDOM_SUPPORT
175 //config: bool "Pseudorandom generator and $RANDOM variable"
177 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
179 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
180 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
182 //config:config HUSH_MODE_X
183 //config: bool "Support 'hush -x' option and 'set -x' command"
185 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
187 //config: This instructs hush to print commands before execution.
188 //config: Adds ~300 bytes.
190 //config:config HUSH_ECHO
191 //config: bool "echo builtin"
193 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
195 //config:config HUSH_PRINTF
196 //config: bool "printf builtin"
198 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
200 //config:config HUSH_HELP
201 //config: bool "help builtin"
203 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
205 //config:config HUSH_EXPORT
206 //config: bool "export builtin"
208 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
210 //config:config HUSH_EXPORT_N
211 //config: bool "Support 'export -n' option"
213 //config: depends on HUSH_EXPORT
215 //config: export -n unexports variables. It is a bash extension.
217 //config:config HUSH_KILL
218 //config: bool "kill builtin (supports kill %jobspec)"
220 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
222 //config:config HUSH_WAIT
223 //config: bool "wait builtin"
225 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227 //config:config HUSH_TRAP
228 //config: bool "trap builtin"
230 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
232 //config:config HUSH_TYPE
233 //config: bool "type builtin"
235 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
237 //config:config HUSH_READ
238 //config: bool "read builtin"
240 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
242 //config:config HUSH_SET
243 //config: bool "set builtin"
245 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
247 //config:config HUSH_UNSET
248 //config: bool "unset builtin"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config:config HUSH_ULIMIT
253 //config: bool "ulimit builtin"
255 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
257 //config:config HUSH_UMASK
258 //config: bool "umask builtin"
260 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
262 //config:config HUSH_MEMLEAK
263 //config: bool "memleak builtin (debugging)"
265 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
268 //config: bool "msh (deprecated: aliased to hush)"
270 //config: select HUSH
272 //config: msh is deprecated and will be removed, please migrate to hush.
274 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
275 //applet:IF_MSH(APPLET_ODDNAME(msh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
276 //applet:IF_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
277 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
279 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
280 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
281 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
282 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
284 /* -i (interactive) and -s (read stdin) are also accepted,
285 * but currently do nothing, therefore aren't shown in help.
286 * NOMMU-specific options are not meant to be used by users,
287 * therefore we don't show them either.
289 //usage:#define hush_trivial_usage
290 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
291 //usage:#define hush_full_usage "\n\n"
292 //usage: "Unix shell interpreter"
294 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
295 || defined(__APPLE__) \
297 # include <malloc.h> /* for malloc_trim */
300 /* #include <dmalloc.h> */
302 # include <fnmatch.h>
304 #include <sys/utsname.h> /* for setting $HOSTNAME */
306 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
308 #include "shell_common.h"
311 #if ENABLE_HUSH_RANDOM_SUPPORT
314 # define CLEAR_RANDOM_T(rnd) ((void)0)
316 #ifndef F_DUPFD_CLOEXEC
317 # define F_DUPFD_CLOEXEC F_DUPFD
320 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
325 #define LEAK_HUNTING 0
326 #define BUILD_AS_NOMMU 0
327 /* Enable/disable sanity checks. Ok to enable in production,
328 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
329 * Keeping 1 for now even in released versions.
332 /* Slightly bigger (+200 bytes), but faster hush.
333 * So far it only enables a trick with counting SIGCHLDs and forks,
334 * which allows us to do fewer waitpid's.
335 * (we can detect a case where neither forks were done nor SIGCHLDs happened
336 * and therefore waitpid will return the same result as last time)
338 #define ENABLE_HUSH_FAST 0
339 /* TODO: implement simplified code for users which do not need ${var%...} ops
340 * So far ${var%...} ops are always enabled:
342 #define ENABLE_HUSH_DOLLAR_OPS 1
347 # undef USE_FOR_NOMMU
350 # define USE_FOR_NOMMU(...) __VA_ARGS__
351 # define USE_FOR_MMU(...)
354 #include "NUM_APPLETS.h"
356 /* STANDALONE does not make sense, and won't compile */
357 # undef CONFIG_FEATURE_SH_STANDALONE
358 # undef ENABLE_FEATURE_SH_STANDALONE
359 # undef IF_FEATURE_SH_STANDALONE
360 # undef IF_NOT_FEATURE_SH_STANDALONE
361 # define ENABLE_FEATURE_SH_STANDALONE 0
362 # define IF_FEATURE_SH_STANDALONE(...)
363 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
366 #if !ENABLE_HUSH_INTERACTIVE
367 # undef ENABLE_FEATURE_EDITING
368 # define ENABLE_FEATURE_EDITING 0
369 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
370 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
371 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
372 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
375 /* Do we support ANY keywords? */
376 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
377 # define HAS_KEYWORDS 1
378 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
379 # define IF_HAS_NO_KEYWORDS(...)
381 # define HAS_KEYWORDS 0
382 # define IF_HAS_KEYWORDS(...)
383 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
386 /* If you comment out one of these below, it will be #defined later
387 * to perform debug printfs to stderr: */
388 #define debug_printf(...) do {} while (0)
389 /* Finer-grained debug switches */
390 #define debug_printf_parse(...) do {} while (0)
391 #define debug_print_tree(a, b) do {} while (0)
392 #define debug_printf_exec(...) do {} while (0)
393 #define debug_printf_env(...) do {} while (0)
394 #define debug_printf_jobs(...) do {} while (0)
395 #define debug_printf_expand(...) do {} while (0)
396 #define debug_printf_varexp(...) do {} while (0)
397 #define debug_printf_glob(...) do {} while (0)
398 #define debug_printf_list(...) do {} while (0)
399 #define debug_printf_subst(...) do {} while (0)
400 #define debug_printf_clean(...) do {} while (0)
402 #define ERR_PTR ((void*)(long)1)
404 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
406 #define _SPECIAL_VARS_STR "_*@$!?#"
407 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
408 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
409 #if ENABLE_HUSH_BASH_COMPAT
410 /* Support / and // replace ops */
411 /* Note that // is stored as \ in "encoded" string representation */
412 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
413 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
414 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
416 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
417 # define VAR_SUBST_OPS "%#:-=+?"
418 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
421 #define SPECIAL_VAR_SYMBOL 3
425 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
427 /* This supports saving pointers malloced in vfork child,
428 * to be freed in the parent.
431 typedef struct nommu_save_t {
433 struct variable *old_vars;
435 char **argv_from_re_execing;
448 #if ENABLE_HUSH_LOOPS
455 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
460 /* three pseudo-keywords support contrived "case" syntax: */
461 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
462 RES_MATCH , /* "word)" */
463 RES_CASE_BODY, /* "this command is inside CASE" */
470 typedef struct o_string {
472 int length; /* position where data is appended */
475 /* At least some part of the string was inside '' or "",
476 * possibly empty one: word"", wo''rd etc. */
477 smallint has_quoted_part;
478 smallint has_empty_slot;
479 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
482 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
484 /* Protect newly added chars against globbing
485 * by prepending \ to *, ?, [, \ */
486 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
489 MAYBE_ASSIGNMENT = 0,
490 DEFINITELY_ASSIGNMENT = 1,
492 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
495 /* Used for initialization: o_string foo = NULL_O_STRING; */
496 #define NULL_O_STRING { NULL }
498 #ifndef debug_printf_parse
499 static const char *const assignment_flag[] = {
501 "DEFINITELY_ASSIGNMENT",
507 typedef struct in_str {
509 #if ENABLE_HUSH_INTERACTIVE
510 smallint promptmode; /* 0: PS1, 1: PS2 */
517 /* The descrip member of this structure is only used to make
518 * debugging output pretty */
519 static const struct {
521 signed char default_fd;
524 { O_RDONLY, 0, "<" },
525 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
526 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
527 { O_CREAT|O_RDWR, 1, "<>" },
528 { O_RDONLY, 0, "<<" },
529 /* Should not be needed. Bogus default_fd helps in debugging */
530 /* { O_RDONLY, 77, "<<" }, */
533 struct redir_struct {
534 struct redir_struct *next;
535 char *rd_filename; /* filename */
536 int rd_fd; /* fd to redirect */
537 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
539 smallint rd_type; /* (enum redir_type) */
540 /* note: for heredocs, rd_filename contains heredoc delimiter,
541 * and subsequently heredoc itself; and rd_dup is a bitmask:
542 * bit 0: do we need to trim leading tabs?
543 * bit 1: is heredoc quoted (<<'delim' syntax) ?
546 typedef enum redir_type {
548 REDIRECT_OVERWRITE = 1,
551 REDIRECT_HEREDOC = 4,
552 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
555 REDIRFD_SYNTAX_ERR = -2,
556 REDIRFD_TO_FILE = -1,
557 /* otherwise, rd_fd is redirected to rd_dup */
559 HEREDOC_SKIPTABS = 1,
565 pid_t pid; /* 0 if exited */
566 int assignment_cnt; /* how many argv[i] are assignments? */
567 smallint cmd_type; /* CMD_xxx */
569 #define CMD_SUBSHELL 1
570 #if ENABLE_HUSH_BASH_COMPAT
571 /* used for "[[ EXPR ]]" */
572 # define CMD_SINGLEWORD_NOGLOB 2
574 #if ENABLE_HUSH_FUNCTIONS
575 # define CMD_FUNCDEF 3
578 smalluint cmd_exitcode;
579 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
582 char *group_as_string;
584 #if ENABLE_HUSH_FUNCTIONS
585 struct function *child_func;
586 /* This field is used to prevent a bug here:
587 * while...do f1() {a;}; f1; f1() {b;}; f1; done
588 * When we execute "f1() {a;}" cmd, we create new function and clear
589 * cmd->group, cmd->group_as_string, cmd->argv[0].
590 * When we execute "f1() {b;}", we notice that f1 exists,
591 * and that its "parent cmd" struct is still "alive",
592 * we put those fields back into cmd->xxx
593 * (struct function has ->parent_cmd ptr to facilitate that).
594 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
595 * Without this trick, loop would execute a;b;b;b;...
596 * instead of correct sequence a;b;a;b;...
597 * When command is freed, it severs the link
598 * (sets ->child_func->parent_cmd to NULL).
601 char **argv; /* command name and arguments */
602 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
603 * and on execution these are substituted with their values.
604 * Substitution can make _several_ words out of one argv[n]!
605 * Example: argv[0]=='.^C*^C.' here: echo .$*.
606 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
608 struct redir_struct *redirects; /* I/O redirections */
610 /* Is there anything in this command at all? */
611 #define IS_NULL_CMD(cmd) \
612 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
616 int num_cmds; /* total number of commands in pipe */
617 int alive_cmds; /* number of commands running (not exited) */
618 int stopped_cmds; /* number of commands alive, but stopped */
620 unsigned jobid; /* job number */
621 pid_t pgrp; /* process group ID for the job */
622 char *cmdtext; /* name of job */
624 struct command *cmds; /* array of commands in pipe */
625 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
626 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
627 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
629 typedef enum pipe_style {
635 /* Is there anything in this pipe at all? */
636 #define IS_NULL_PIPE(pi) \
637 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
639 /* This holds pointers to the various results of parsing */
640 struct parse_context {
641 /* linked list of pipes */
642 struct pipe *list_head;
643 /* last pipe (being constructed right now) */
645 /* last command in pipe (being constructed right now) */
646 struct command *command;
647 /* last redirect in command->redirects list */
648 struct redir_struct *pending_redirect;
654 smallint ctx_inverted; /* "! cmd | cmd" */
656 smallint ctx_dsemicolon; /* ";;" seen */
658 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
660 /* group we are enclosed in:
661 * example: "if pipe1; pipe2; then pipe3; fi"
662 * when we see "if" or "then", we malloc and copy current context,
663 * and make ->stack point to it. then we parse pipeN.
664 * when closing "then" / fi" / whatever is found,
665 * we move list_head into ->stack->command->group,
666 * copy ->stack into current context, and delete ->stack.
667 * (parsing of { list } and ( list ) doesn't use this method)
669 struct parse_context *stack;
673 /* On program start, environ points to initial environment.
674 * putenv adds new pointers into it, unsetenv removes them.
675 * Neither of these (de)allocates the strings.
676 * setenv allocates new strings in malloc space and does putenv,
677 * and thus setenv is unusable (leaky) for shell's purposes */
678 #define setenv(...) setenv_is_leaky_dont_use()
680 struct variable *next;
681 char *varstr; /* points to "name=" portion */
682 #if ENABLE_HUSH_LOCAL
683 unsigned func_nest_level;
685 int max_len; /* if > 0, name is part of initial env; else name is malloced */
686 smallint flg_export; /* putenv should be done on this var */
687 smallint flg_read_only;
695 #if ENABLE_HUSH_FUNCTIONS
697 struct function *next;
699 struct command *parent_cmd;
702 char *body_as_string;
708 /* set -/+o OPT support. (TODO: make it optional)
709 * bash supports the following opts:
720 * interactive-comments on
738 static const char o_opt_strings[] ALIGN1 =
741 #if ENABLE_HUSH_MODE_X
748 #if ENABLE_HUSH_MODE_X
756 struct FILE_list *next;
762 /* "Globals" within this file */
763 /* Sorted roughly by size (smaller offsets == smaller code) */
765 /* interactive_fd != 0 means we are an interactive shell.
766 * If we are, then saved_tty_pgrp can also be != 0, meaning
767 * that controlling tty is available. With saved_tty_pgrp == 0,
768 * job control still works, but terminal signals
769 * (^C, ^Z, ^Y, ^\) won't work at all, and background
770 * process groups can only be created with "cmd &".
771 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
772 * to give tty to the foreground process group,
773 * and will take it back when the group is stopped (^Z)
776 #if ENABLE_HUSH_INTERACTIVE
777 /* 'interactive_fd' is a fd# open to ctty, if we have one
778 * _AND_ if we decided to act interactively */
782 # define G_interactive_fd (G.interactive_fd)
784 # define G_interactive_fd 0
786 #if ENABLE_FEATURE_EDITING
787 line_input_t *line_input_state;
792 #if ENABLE_HUSH_RANDOM_SUPPORT
798 pid_t saved_tty_pgrp;
799 struct pipe *job_list;
800 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
802 # define G_saved_tty_pgrp 0
804 char o_opt[NUM_OPT_O];
805 #if ENABLE_HUSH_MODE_X
806 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
810 smallint flag_SIGINT;
811 #if ENABLE_HUSH_LOOPS
812 smallint flag_break_continue;
814 #if ENABLE_HUSH_FUNCTIONS
815 /* 0: outside of a function (or sourced file)
816 * -1: inside of a function, ok to use return builtin
817 * 1: return is invoked, skip all till end of func
819 smallint flag_return_in_progress;
820 # define G_flag_return_in_progress (G.flag_return_in_progress)
822 # define G_flag_return_in_progress 0
824 smallint exiting; /* used to prevent EXIT trap recursion */
825 /* These four support $?, $#, and $1 */
826 smalluint last_exitcode;
828 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
829 smalluint global_args_malloced;
830 # define G_global_args_malloced (G.global_args_malloced)
832 # define G_global_args_malloced 0
834 /* how many non-NULL argv's we have. NB: $# + 1 */
838 char *argv0_for_re_execing;
840 #if ENABLE_HUSH_LOOPS
841 unsigned depth_break_continue;
842 unsigned depth_of_loop;
846 struct variable *top_var;
847 char **expanded_assignments;
848 #if ENABLE_HUSH_FUNCTIONS
849 struct function *top_func;
850 # if ENABLE_HUSH_LOCAL
851 struct variable **shadowed_vars_pp;
852 unsigned func_nest_level;
855 /* Signal and trap handling */
857 unsigned count_SIGCHLD;
858 unsigned handled_SIGCHLD;
859 smallint we_have_children;
861 struct FILE_list *FILE_list;
862 /* Which signals have non-DFL handler (even with no traps set)?
863 * Set at the start to:
864 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
865 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
866 * The rest is cleared right before execv syscalls.
867 * Other than these two times, never modified.
869 unsigned special_sig_mask;
871 unsigned fatal_sig_mask;
872 # define G_fatal_sig_mask (G.fatal_sig_mask)
874 # define G_fatal_sig_mask 0
877 char **traps; /* char *traps[NSIG] */
878 # define G_traps G.traps
880 # define G_traps ((char**)NULL)
882 sigset_t pending_set;
883 #if ENABLE_HUSH_MEMLEAK
884 unsigned long memleak_value;
890 #if ENABLE_FEATURE_EDITING
891 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
894 #define G (*ptr_to_globals)
895 /* Not #defining name to G.name - this quickly gets unwieldy
896 * (too many defines). Also, I actually prefer to see when a variable
897 * is global, thus "G." prefix is a useful hint */
898 #define INIT_G() do { \
899 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
900 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
901 sigfillset(&G.sa.sa_mask); \
902 G.sa.sa_flags = SA_RESTART; \
906 /* Function prototypes for builtins */
907 static int builtin_cd(char **argv) FAST_FUNC;
909 static int builtin_echo(char **argv) FAST_FUNC;
911 static int builtin_eval(char **argv) FAST_FUNC;
912 static int builtin_exec(char **argv) FAST_FUNC;
913 static int builtin_exit(char **argv) FAST_FUNC;
914 #if ENABLE_HUSH_EXPORT
915 static int builtin_export(char **argv) FAST_FUNC;
918 static int builtin_fg_bg(char **argv) FAST_FUNC;
919 static int builtin_jobs(char **argv) FAST_FUNC;
922 static int builtin_help(char **argv) FAST_FUNC;
924 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
925 static int builtin_history(char **argv) FAST_FUNC;
927 #if ENABLE_HUSH_LOCAL
928 static int builtin_local(char **argv) FAST_FUNC;
930 #if ENABLE_HUSH_MEMLEAK
931 static int builtin_memleak(char **argv) FAST_FUNC;
933 #if ENABLE_HUSH_PRINTF
934 static int builtin_printf(char **argv) FAST_FUNC;
936 static int builtin_pwd(char **argv) FAST_FUNC;
938 static int builtin_read(char **argv) FAST_FUNC;
941 static int builtin_set(char **argv) FAST_FUNC;
943 static int builtin_shift(char **argv) FAST_FUNC;
944 static int builtin_source(char **argv) FAST_FUNC;
945 static int builtin_test(char **argv) FAST_FUNC;
947 static int builtin_trap(char **argv) FAST_FUNC;
950 static int builtin_type(char **argv) FAST_FUNC;
952 static int builtin_true(char **argv) FAST_FUNC;
953 #if ENABLE_HUSH_UMASK
954 static int builtin_umask(char **argv) FAST_FUNC;
956 #if ENABLE_HUSH_UNSET
957 static int builtin_unset(char **argv) FAST_FUNC;
960 static int builtin_kill(char **argv) FAST_FUNC;
963 static int builtin_wait(char **argv) FAST_FUNC;
965 #if ENABLE_HUSH_LOOPS
966 static int builtin_break(char **argv) FAST_FUNC;
967 static int builtin_continue(char **argv) FAST_FUNC;
969 #if ENABLE_HUSH_FUNCTIONS
970 static int builtin_return(char **argv) FAST_FUNC;
973 /* Table of built-in functions. They can be forked or not, depending on
974 * context: within pipes, they fork. As simple commands, they do not.
975 * When used in non-forking context, they can change global variables
976 * in the parent shell process. If forked, of course they cannot.
977 * For example, 'unset foo | whatever' will parse and run, but foo will
978 * still be set at the end. */
979 struct built_in_command {
981 int (*b_function)(char **argv) FAST_FUNC;
984 # define BLTIN(cmd, func, help) { cmd, func, help }
986 # define BLTIN(cmd, func, help) { cmd, func }
990 static const struct built_in_command bltins1[] = {
991 BLTIN("." , builtin_source , "Run commands in a file"),
992 BLTIN(":" , builtin_true , NULL),
994 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
996 #if ENABLE_HUSH_LOOPS
997 BLTIN("break" , builtin_break , "Exit from a loop"),
999 BLTIN("cd" , builtin_cd , "Change directory"),
1000 #if ENABLE_HUSH_LOOPS
1001 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1003 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1004 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1005 BLTIN("exit" , builtin_exit , "Exit"),
1006 #if ENABLE_HUSH_EXPORT
1007 BLTIN("export" , builtin_export , "Set environment variables"),
1010 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
1012 #if ENABLE_HUSH_HELP
1013 BLTIN("help" , builtin_help , NULL),
1015 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1016 BLTIN("history" , builtin_history , "Show command history"),
1019 BLTIN("jobs" , builtin_jobs , "List jobs"),
1021 #if ENABLE_HUSH_KILL
1022 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1024 #if ENABLE_HUSH_LOCAL
1025 BLTIN("local" , builtin_local , "Set local variables"),
1027 #if ENABLE_HUSH_MEMLEAK
1028 BLTIN("memleak" , builtin_memleak , NULL),
1030 #if ENABLE_HUSH_READ
1031 BLTIN("read" , builtin_read , "Input into variable"),
1033 #if ENABLE_HUSH_FUNCTIONS
1034 BLTIN("return" , builtin_return , "Return from a function"),
1037 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
1039 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1040 #if ENABLE_HUSH_BASH_COMPAT
1041 BLTIN("source" , builtin_source , "Run commands in a file"),
1043 #if ENABLE_HUSH_TRAP
1044 BLTIN("trap" , builtin_trap , "Trap signals"),
1046 BLTIN("true" , builtin_true , NULL),
1047 #if ENABLE_HUSH_TYPE
1048 BLTIN("type" , builtin_type , "Show command type"),
1050 #if ENABLE_HUSH_ULIMIT
1051 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1053 #if ENABLE_HUSH_UMASK
1054 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1056 #if ENABLE_HUSH_UNSET
1057 BLTIN("unset" , builtin_unset , "Unset variables"),
1059 #if ENABLE_HUSH_WAIT
1060 BLTIN("wait" , builtin_wait , "Wait for process"),
1063 static const struct built_in_command bltins2[] = {
1064 BLTIN("[" , builtin_test , NULL),
1065 #if ENABLE_HUSH_ECHO
1066 BLTIN("echo" , builtin_echo , NULL),
1068 #if ENABLE_HUSH_PRINTF
1069 BLTIN("printf" , builtin_printf , NULL),
1071 BLTIN("pwd" , builtin_pwd , NULL),
1072 BLTIN("test" , builtin_test , NULL),
1079 /* prevent disasters with G.debug_indent < 0 */
1080 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1081 # define debug_enter() (G.debug_indent++)
1082 # define debug_leave() (G.debug_indent--)
1084 # define indent() ((void)0)
1085 # define debug_enter() ((void)0)
1086 # define debug_leave() ((void)0)
1089 #ifndef debug_printf
1090 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1093 #ifndef debug_printf_parse
1094 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1097 #ifndef debug_printf_exec
1098 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1101 #ifndef debug_printf_env
1102 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1105 #ifndef debug_printf_jobs
1106 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1107 # define DEBUG_JOBS 1
1109 # define DEBUG_JOBS 0
1112 #ifndef debug_printf_expand
1113 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1114 # define DEBUG_EXPAND 1
1116 # define DEBUG_EXPAND 0
1119 #ifndef debug_printf_varexp
1120 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1123 #ifndef debug_printf_glob
1124 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1125 # define DEBUG_GLOB 1
1127 # define DEBUG_GLOB 0
1130 #ifndef debug_printf_list
1131 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1134 #ifndef debug_printf_subst
1135 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1138 #ifndef debug_printf_clean
1139 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1140 # define DEBUG_CLEAN 1
1142 # define DEBUG_CLEAN 0
1146 static void debug_print_strings(const char *prefix, char **vv)
1149 fdprintf(2, "%s:\n", prefix);
1151 fdprintf(2, " '%s'\n", *vv++);
1154 # define debug_print_strings(prefix, vv) ((void)0)
1158 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1161 static void *xxmalloc(int lineno, size_t size)
1163 void *ptr = xmalloc((size + 0xff) & ~0xff);
1164 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1167 static void *xxrealloc(int lineno, void *ptr, size_t size)
1169 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1170 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1173 static char *xxstrdup(int lineno, const char *str)
1175 char *ptr = xstrdup(str);
1176 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1179 static void xxfree(void *ptr)
1181 fdprintf(2, "free %p\n", ptr);
1184 # define xmalloc(s) xxmalloc(__LINE__, s)
1185 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1186 # define xstrdup(s) xxstrdup(__LINE__, s)
1187 # define free(p) xxfree(p)
1191 /* Syntax and runtime errors. They always abort scripts.
1192 * In interactive use they usually discard unparsed and/or unexecuted commands
1193 * and return to the prompt.
1194 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1197 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1198 # define syntax_error(lineno, msg) syntax_error(msg)
1199 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1200 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1201 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1202 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1205 static void die_if_script(unsigned lineno, const char *fmt, ...)
1210 bb_error_msg("hush.c:%u", lineno);
1213 bb_verror_msg(fmt, p, NULL);
1215 if (!G_interactive_fd)
1219 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1222 bb_error_msg("syntax error: %s", msg);
1224 bb_error_msg("syntax error");
1227 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1229 bb_error_msg("syntax error at '%s'", msg);
1232 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1234 bb_error_msg("syntax error: unterminated %s", s);
1237 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1239 char msg[2] = { ch, '\0' };
1240 syntax_error_unterm_str(lineno, msg);
1243 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1249 bb_error_msg("hush.c:%u", lineno);
1251 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1255 # undef die_if_script
1256 # undef syntax_error
1257 # undef syntax_error_at
1258 # undef syntax_error_unterm_ch
1259 # undef syntax_error_unterm_str
1260 # undef syntax_error_unexpected_ch
1262 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1263 # define syntax_error(msg) syntax_error(__LINE__, msg)
1264 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1265 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1266 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1267 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1271 #if ENABLE_HUSH_INTERACTIVE
1272 static void cmdedit_update_prompt(void);
1274 # define cmdedit_update_prompt() ((void)0)
1278 /* Utility functions
1280 /* Replace each \x with x in place, return ptr past NUL. */
1281 static char *unbackslash(char *src)
1283 char *dst = src = strchrnul(src, '\\');
1287 if ((*dst++ = *src++) == '\0')
1293 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1314 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1315 v[count1 + count2] = NULL;
1318 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1322 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1324 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1325 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1328 #define add_strings_to_strings(strings, add, need_to_dup) \
1329 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1332 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1333 static char **add_string_to_strings(char **strings, char *add)
1338 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1341 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1343 char **ptr = add_string_to_strings(strings, add);
1344 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1347 #define add_string_to_strings(strings, add) \
1348 xx_add_string_to_strings(__LINE__, strings, add)
1351 static void free_strings(char **strings)
1366 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1368 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1369 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1371 /* fd was not open? */
1381 /* Manipulating the list of open FILEs */
1382 static FILE *remember_FILE(FILE *fp)
1385 struct FILE_list *n = xmalloc(sizeof(*n));
1386 n->next = G.FILE_list;
1390 close_on_exec_on(n->fd);
1394 static void fclose_and_forget(FILE *fp)
1396 struct FILE_list **pp = &G.FILE_list;
1398 struct FILE_list *cur = *pp;
1399 if (cur->fp == fp) {
1408 static int save_FILEs_on_redirect(int fd)
1410 struct FILE_list *fl = G.FILE_list;
1413 /* We use it only on script files, they are all CLOEXEC */
1414 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1421 static void restore_redirected_FILEs(void)
1423 struct FILE_list *fl = G.FILE_list;
1425 int should_be = fileno(fl->fp);
1426 if (fl->fd != should_be) {
1427 xmove_fd(fl->fd, should_be);
1433 #if ENABLE_FEATURE_SH_STANDALONE
1434 static void close_all_FILE_list(void)
1436 struct FILE_list *fl = G.FILE_list;
1438 /* fclose would also free FILE object.
1439 * It is disastrous if we share memory with a vforked parent.
1440 * I'm not sure we never come here after vfork.
1441 * Therefore just close fd, nothing more.
1443 /*fclose(fl->fp); - unsafe */
1451 /* Helpers for setting new $n and restoring them back
1453 typedef struct save_arg_t {
1457 IF_HUSH_SET(smallint sv_g_malloced;)
1460 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1464 sv->sv_argv0 = argv[0];
1465 sv->sv_g_argv = G.global_argv;
1466 sv->sv_g_argc = G.global_argc;
1467 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1469 argv[0] = G.global_argv[0]; /* retain $0 */
1470 G.global_argv = argv;
1471 IF_HUSH_SET(G.global_args_malloced = 0;)
1479 static void restore_G_args(save_arg_t *sv, char **argv)
1482 if (G.global_args_malloced) {
1483 /* someone ran "set -- arg1 arg2 ...", undo */
1484 char **pp = G.global_argv;
1485 while (*++pp) /* note: does not free $0 */
1487 free(G.global_argv);
1490 argv[0] = sv->sv_argv0;
1491 G.global_argv = sv->sv_g_argv;
1492 G.global_argc = sv->sv_g_argc;
1493 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1497 /* Basic theory of signal handling in shell
1498 * ========================================
1499 * This does not describe what hush does, rather, it is current understanding
1500 * what it _should_ do. If it doesn't, it's a bug.
1501 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1503 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1504 * is finished or backgrounded. It is the same in interactive and
1505 * non-interactive shells, and is the same regardless of whether
1506 * a user trap handler is installed or a shell special one is in effect.
1507 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1508 * backgrounds (i.e. stops) or kills all members of currently running
1511 * Wait builtin is interruptible by signals for which user trap is set
1512 * or by SIGINT in interactive shell.
1514 * Trap handlers will execute even within trap handlers. (right?)
1516 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1517 * except for handlers set to '' (empty string).
1519 * If job control is off, backgrounded commands ("cmd &")
1520 * have SIGINT, SIGQUIT set to SIG_IGN.
1522 * Commands which are run in command substitution ("`cmd`")
1523 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1525 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1526 * by the shell from its parent.
1528 * Signals which differ from SIG_DFL action
1529 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1532 * SIGTERM (interactive): ignore
1533 * SIGHUP (interactive):
1534 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1535 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1536 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1537 * that all pipe members are stopped. Try this in bash:
1538 * while :; do :; done - ^Z does not background it
1539 * (while :; do :; done) - ^Z backgrounds it
1540 * SIGINT (interactive): wait for last pipe, ignore the rest
1541 * of the command line, show prompt. NB: ^C does not send SIGINT
1542 * to interactive shell while shell is waiting for a pipe,
1543 * since shell is bg'ed (is not in foreground process group).
1544 * Example 1: this waits 5 sec, but does not execute ls:
1545 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1546 * Example 2: this does not wait and does not execute ls:
1547 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1548 * Example 3: this does not wait 5 sec, but executes ls:
1549 * "sleep 5; ls -l" + press ^C
1550 * Example 4: this does not wait and does not execute ls:
1551 * "sleep 5 & wait; ls -l" + press ^C
1553 * (What happens to signals which are IGN on shell start?)
1554 * (What happens with signal mask on shell start?)
1556 * Old implementation
1557 * ==================
1558 * We use in-kernel pending signal mask to determine which signals were sent.
1559 * We block all signals which we don't want to take action immediately,
1560 * i.e. we block all signals which need to have special handling as described
1561 * above, and all signals which have traps set.
1562 * After each pipe execution, we extract any pending signals via sigtimedwait()
1565 * unsigned special_sig_mask: a mask of such "special" signals
1566 * sigset_t blocked_set: current blocked signal set
1569 * clear bit in blocked_set unless it is also in special_sig_mask
1570 * "trap 'cmd' SIGxxx":
1571 * set bit in blocked_set (even if 'cmd' is '')
1572 * after [v]fork, if we plan to be a shell:
1573 * unblock signals with special interactive handling
1574 * (child shell is not interactive),
1575 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1576 * after [v]fork, if we plan to exec:
1577 * POSIX says fork clears pending signal mask in child - no need to clear it.
1578 * Restore blocked signal set to one inherited by shell just prior to exec.
1580 * Note: as a result, we do not use signal handlers much. The only uses
1581 * are to count SIGCHLDs
1582 * and to restore tty pgrp on signal-induced exit.
1585 * Standard says "When a subshell is entered, traps that are not being ignored
1586 * are set to the default actions". bash interprets it so that traps which
1587 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1589 * Problem: the above approach makes it unwieldy to catch signals while
1590 * we are in read builtin, or while we read commands from stdin:
1591 * masked signals are not visible!
1593 * New implementation
1594 * ==================
1595 * We record each signal we are interested in by installing signal handler
1596 * for them - a bit like emulating kernel pending signal mask in userspace.
1597 * We are interested in: signals which need to have special handling
1598 * as described above, and all signals which have traps set.
1599 * Signals are recorded in pending_set.
1600 * After each pipe execution, we extract any pending signals
1603 * unsigned special_sig_mask: a mask of shell-special signals.
1604 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1605 * char *traps[sig] if trap for sig is set (even if it's '').
1606 * sigset_t pending_set: set of sigs we received.
1609 * if sig is in special_sig_mask, set handler back to:
1610 * record_pending_signo, or to IGN if it's a tty stop signal
1611 * if sig is in fatal_sig_mask, set handler back to sigexit.
1612 * else: set handler back to SIG_DFL
1613 * "trap 'cmd' SIGxxx":
1614 * set handler to record_pending_signo.
1616 * set handler to SIG_IGN.
1617 * after [v]fork, if we plan to be a shell:
1618 * set signals with special interactive handling to SIG_DFL
1619 * (because child shell is not interactive),
1620 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1621 * after [v]fork, if we plan to exec:
1622 * POSIX says fork clears pending signal mask in child - no need to clear it.
1624 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1625 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1628 * Standard says "When a subshell is entered, traps that are not being ignored
1629 * are set to the default actions". bash interprets it so that traps which
1630 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1633 SPECIAL_INTERACTIVE_SIGS = 0
1638 SPECIAL_JOBSTOP_SIGS = 0
1647 static void record_pending_signo(int sig)
1649 sigaddset(&G.pending_set, sig);
1650 #if ENABLE_HUSH_FAST
1651 if (sig == SIGCHLD) {
1653 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1658 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1660 struct sigaction old_sa;
1662 /* We could use signal() to install handlers... almost:
1663 * except that we need to mask ALL signals while handlers run.
1664 * I saw signal nesting in strace, race window isn't small.
1665 * SA_RESTART is also needed, but in Linux, signal()
1666 * sets SA_RESTART too.
1668 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1669 /* sigfillset(&G.sa.sa_mask); - already done */
1670 /* G.sa.sa_flags = SA_RESTART; - already done */
1671 G.sa.sa_handler = handler;
1672 sigaction(sig, &G.sa, &old_sa);
1673 return old_sa.sa_handler;
1676 static void hush_exit(int exitcode) NORETURN;
1678 static void restore_ttypgrp_and__exit(void) NORETURN;
1679 static void restore_ttypgrp_and__exit(void)
1681 /* xfunc has failed! die die die */
1682 /* no EXIT traps, this is an escape hatch! */
1684 hush_exit(xfunc_error_retval);
1689 /* Needed only on some libc:
1690 * It was observed that on exit(), fgetc'ed buffered data
1691 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1692 * With the net effect that even after fork(), not vfork(),
1693 * exit() in NOEXECed applet in "sh SCRIPT":
1694 * noexec_applet_here
1695 * echo END_OF_SCRIPT
1696 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1697 * This makes "echo END_OF_SCRIPT" executed twice.
1698 * Similar problems can be seen with die_if_script() -> xfunc_die()
1699 * and in `cmd` handling.
1700 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1702 static void fflush_and__exit(void) NORETURN;
1703 static void fflush_and__exit(void)
1706 _exit(xfunc_error_retval);
1709 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1710 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1711 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1712 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1714 /* Restores tty foreground process group, and exits.
1715 * May be called as signal handler for fatal signal
1716 * (will resend signal to itself, producing correct exit state)
1717 * or called directly with -EXITCODE.
1718 * We also call it if xfunc is exiting.
1720 static void sigexit(int sig) NORETURN;
1721 static void sigexit(int sig)
1723 /* Careful: we can end up here after [v]fork. Do not restore
1724 * tty pgrp then, only top-level shell process does that */
1725 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1726 /* Disable all signals: job control, SIGPIPE, etc.
1727 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1729 sigprocmask_allsigs(SIG_BLOCK);
1730 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1733 /* Not a signal, just exit */
1737 kill_myself_with_sig(sig); /* does not return */
1741 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1742 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1746 static sighandler_t pick_sighandler(unsigned sig)
1748 sighandler_t handler = SIG_DFL;
1749 if (sig < sizeof(unsigned)*8) {
1750 unsigned sigmask = (1 << sig);
1754 if (G_fatal_sig_mask & sigmask)
1758 /* sig has special handling? */
1759 if (G.special_sig_mask & sigmask) {
1760 handler = record_pending_signo;
1761 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1762 * in order to ignore them: they will be raised
1763 * in an endless loop when we try to do some
1764 * terminal ioctls! We do have to _ignore_ these.
1766 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1773 /* Restores tty foreground process group, and exits. */
1774 static void hush_exit(int exitcode)
1776 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1777 save_history(G.line_input_state);
1781 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1783 /* argv[0] is unused */
1784 argv[1] = G_traps[0];
1786 G.exiting = 1; /* prevent EXIT trap recursion */
1787 /* Note: G_traps[0] is not cleared!
1788 * "trap" will still show it, if executed
1793 #if ENABLE_FEATURE_CLEAN_UP
1795 struct variable *cur_var;
1796 if (G.cwd != bb_msg_unknown)
1798 cur_var = G.top_var;
1800 struct variable *tmp = cur_var;
1801 if (!cur_var->max_len)
1802 free(cur_var->varstr);
1803 cur_var = cur_var->next;
1811 sigexit(- (exitcode & 0xff));
1818 //TODO: return a mask of ALL handled sigs?
1819 static int check_and_run_traps(void)
1826 if (sigisemptyset(&G.pending_set))
1831 if (sigismember(&G.pending_set, sig)) {
1832 sigdelset(&G.pending_set, sig);
1835 } while (sig < NSIG);
1838 if (G_traps && G_traps[sig]) {
1839 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1840 if (G_traps[sig][0]) {
1841 /* We have user-defined handler */
1842 smalluint save_rcode;
1844 /* argv[0] is unused */
1845 argv[1] = G_traps[sig];
1847 save_rcode = G.last_exitcode;
1849 //FIXME: shouldn't it be set to 128 + sig instead?
1850 G.last_exitcode = save_rcode;
1852 } /* else: "" trap, ignoring signal */
1855 /* not a trap: special action */
1858 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1865 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1866 /* bash is observed to signal whole process groups,
1867 * not individual processes */
1868 for (job = G.job_list; job; job = job->next) {
1871 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1872 if (kill(- job->pgrp, SIGHUP) == 0)
1873 kill(- job->pgrp, SIGCONT);
1878 #if ENABLE_HUSH_FAST
1880 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1882 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1884 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1885 * This simplifies wait builtin a bit.
1889 default: /* ignored: */
1890 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1891 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1893 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1894 * Example: wait is not interrupted by TERM
1895 * in interactive shell, because TERM is ignored.
1904 static const char *get_cwd(int force)
1906 if (force || G.cwd == NULL) {
1907 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1908 * we must not try to free(bb_msg_unknown) */
1909 if (G.cwd == bb_msg_unknown)
1911 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1913 G.cwd = bb_msg_unknown;
1920 * Shell and environment variable support
1922 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1924 struct variable **pp;
1925 struct variable *cur;
1928 while ((cur = *pp) != NULL) {
1929 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1936 static const char* FAST_FUNC get_local_var_value(const char *name)
1938 struct variable **vpp;
1939 unsigned len = strlen(name);
1941 if (G.expanded_assignments) {
1942 char **cpp = G.expanded_assignments;
1945 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1946 return cp + len + 1;
1951 vpp = get_ptr_to_local_var(name, len);
1953 return (*vpp)->varstr + len + 1;
1955 if (strcmp(name, "PPID") == 0)
1956 return utoa(G.root_ppid);
1957 // bash compat: UID? EUID?
1958 #if ENABLE_HUSH_RANDOM_SUPPORT
1959 if (strcmp(name, "RANDOM") == 0)
1960 return utoa(next_random(&G.random_gen));
1965 /* str holds "NAME=VAL" and is expected to be malloced.
1966 * We take ownership of it.
1968 * 0: do not change export flag
1969 * (if creating new variable, flag will be 0)
1970 * 1: set export flag and putenv the variable
1971 * -1: clear export flag and unsetenv the variable
1972 * flg_read_only is set only when we handle -R var=val
1974 #if !BB_MMU && ENABLE_HUSH_LOCAL
1975 /* all params are used */
1976 #elif BB_MMU && ENABLE_HUSH_LOCAL
1977 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1978 set_local_var(str, flg_export, local_lvl)
1979 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1980 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1981 set_local_var(str, flg_export)
1982 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1983 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1984 set_local_var(str, flg_export, flg_read_only)
1986 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1988 struct variable **var_pp;
1989 struct variable *cur;
1990 char *free_me = NULL;
1994 eq_sign = strchr(str, '=');
1995 if (!eq_sign) { /* not expected to ever happen? */
2000 name_len = eq_sign - str + 1; /* including '=' */
2001 var_pp = &G.top_var;
2002 while ((cur = *var_pp) != NULL) {
2003 if (strncmp(cur->varstr, str, name_len) != 0) {
2004 var_pp = &cur->next;
2008 /* We found an existing var with this name */
2009 if (cur->flg_read_only) {
2013 bb_error_msg("%s: readonly variable", str);
2017 if (flg_export == -1) { // "&& cur->flg_export" ?
2018 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2023 #if ENABLE_HUSH_LOCAL
2024 if (cur->func_nest_level < local_lvl) {
2025 /* New variable is declared as local,
2026 * and existing one is global, or local
2027 * from enclosing function.
2028 * Remove and save old one: */
2029 *var_pp = cur->next;
2030 cur->next = *G.shadowed_vars_pp;
2031 *G.shadowed_vars_pp = cur;
2032 /* bash 3.2.33(1) and exported vars:
2034 * # f() { local z=a; env | grep ^z; }
2040 if (cur->flg_export)
2045 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2050 if (cur->max_len != 0) {
2051 if (cur->max_len >= strlen(str)) {
2052 /* This one is from startup env, reuse space */
2053 strcpy(cur->varstr, str);
2058 goto set_str_and_exp;
2060 /* max_len == 0 signifies "malloced" var, which we can
2061 * (and have to) free. But we can't free(cur->varstr) here:
2062 * if cur->flg_export is 1, it is in the environment.
2063 * We should either unsetenv+free, or wait until putenv,
2064 * then putenv(new)+free(old).
2066 free_me = cur->varstr;
2067 goto set_str_and_exp;
2070 /* Not found - create new variable struct */
2071 cur = xzalloc(sizeof(*cur));
2072 #if ENABLE_HUSH_LOCAL
2073 cur->func_nest_level = local_lvl;
2075 cur->next = *var_pp;
2081 cur->flg_read_only = flg_read_only;
2084 if (flg_export == 1)
2085 cur->flg_export = 1;
2086 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2087 cmdedit_update_prompt();
2088 if (cur->flg_export) {
2089 if (flg_export == -1) {
2090 cur->flg_export = 0;
2091 /* unsetenv was already done */
2094 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2095 i = putenv(cur->varstr);
2096 /* only now we can free old exported malloced string */
2105 /* Used at startup and after each cd */
2106 static void set_pwd_var(int exp)
2108 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2109 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2112 static int unset_local_var_len(const char *name, int name_len)
2114 struct variable *cur;
2115 struct variable **var_pp;
2118 return EXIT_SUCCESS;
2119 var_pp = &G.top_var;
2120 while ((cur = *var_pp) != NULL) {
2121 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2122 if (cur->flg_read_only) {
2123 bb_error_msg("%s: readonly variable", name);
2124 return EXIT_FAILURE;
2126 *var_pp = cur->next;
2127 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2128 bb_unsetenv(cur->varstr);
2129 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2130 cmdedit_update_prompt();
2134 return EXIT_SUCCESS;
2136 var_pp = &cur->next;
2138 return EXIT_SUCCESS;
2141 #if ENABLE_HUSH_UNSET
2142 static int unset_local_var(const char *name)
2144 return unset_local_var_len(name, strlen(name));
2148 static void unset_vars(char **strings)
2156 const char *eq = strchrnul(*v, '=');
2157 unset_local_var_len(*v, (int)(eq - *v));
2163 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_BASH_COMPAT || ENABLE_HUSH_READ
2164 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2166 char *var = xasprintf("%s=%s", name, val);
2167 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2173 * Helpers for "var1=val1 var2=val2 cmd" feature
2175 static void add_vars(struct variable *var)
2177 struct variable *next;
2181 var->next = G.top_var;
2183 if (var->flg_export) {
2184 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2185 putenv(var->varstr);
2187 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2193 static struct variable *set_vars_and_save_old(char **strings)
2196 struct variable *old = NULL;
2202 struct variable *var_p;
2203 struct variable **var_pp;
2206 eq = strchr(*s, '=');
2208 var_pp = get_ptr_to_local_var(*s, eq - *s);
2210 /* Remove variable from global linked list */
2212 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2213 *var_pp = var_p->next;
2214 /* Add it to returned list */
2218 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2229 static void reinit_unicode_for_hush(void)
2231 /* Unicode support should be activated even if LANG is set
2232 * _during_ shell execution, not only if it was set when
2233 * shell was started. Therefore, re-check LANG every time:
2235 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2236 || ENABLE_UNICODE_USING_LOCALE
2238 const char *s = get_local_var_value("LC_ALL");
2239 if (!s) s = get_local_var_value("LC_CTYPE");
2240 if (!s) s = get_local_var_value("LANG");
2246 * in_str support (strings, and "strings" read from files).
2249 #if ENABLE_HUSH_INTERACTIVE
2250 /* To test correct lineedit/interactive behavior, type from command line:
2256 * It excercises a lot of corner cases.
2258 static void cmdedit_update_prompt(void)
2260 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2261 G.PS1 = get_local_var_value("PS1");
2264 G.PS2 = get_local_var_value("PS2");
2271 static const char *setup_prompt_string(int promptmode)
2273 const char *prompt_str;
2274 debug_printf("setup_prompt_string %d ", promptmode);
2275 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2276 /* Set up the prompt */
2277 if (promptmode == 0) { /* PS1 */
2279 /* bash uses $PWD value, even if it is set by user.
2280 * It uses current dir only if PWD is unset.
2281 * We always use current dir. */
2282 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2287 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2288 debug_printf("prompt_str '%s'\n", prompt_str);
2291 static int get_user_input(struct in_str *i)
2294 const char *prompt_str;
2296 prompt_str = setup_prompt_string(i->promptmode);
2297 # if ENABLE_FEATURE_EDITING
2299 reinit_unicode_for_hush();
2300 if (G.flag_SIGINT) {
2301 /* There was ^C'ed, make it look prettier: */
2305 /* buglet: SIGINT will not make new prompt to appear _at once_,
2306 * only after <Enter>. (^C works immediately) */
2307 r = read_line_input(G.line_input_state, prompt_str,
2308 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2311 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2313 write(STDOUT_FILENO, "^C", 2);
2316 check_and_run_traps();
2317 if (r != 0 && !G.flag_SIGINT)
2319 /* ^C or SIGINT: repeat */
2320 G.last_exitcode = 128 + SIGINT;
2323 /* EOF/error detected */
2325 i->peek_buf[0] = r = EOF;
2328 i->p = G.user_input_buf;
2329 return (unsigned char)*i->p++;
2333 if (i->last_char == '\0' || i->last_char == '\n') {
2334 /* Why check_and_run_traps here? Try this interactively:
2335 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2336 * $ <[enter], repeatedly...>
2337 * Without check_and_run_traps, handler never runs.
2339 check_and_run_traps();
2340 fputs(prompt_str, stdout);
2343 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2345 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2346 * no ^C masking happens during fgetc, no special code for ^C:
2347 * it generates SIGINT as usual.
2349 check_and_run_traps();
2351 G.last_exitcode = 128 + SIGINT;
2358 /* This is the magic location that prints prompts
2359 * and gets data back from the user */
2360 static int fgetc_interactive(struct in_str *i)
2363 /* If it's interactive stdin, get new line. */
2364 if (G_interactive_fd && i->file == stdin) {
2365 /* Returns first char (or EOF), the rest is in i->p[] */
2366 ch = get_user_input(i);
2367 i->promptmode = 1; /* PS2 */
2369 /* Not stdin: script file, sourced file, etc */
2370 do ch = fgetc(i->file); while (ch == '\0');
2375 static inline int fgetc_interactive(struct in_str *i)
2378 do ch = fgetc(i->file); while (ch == '\0');
2381 #endif /* INTERACTIVE */
2383 static int i_getch(struct in_str *i)
2388 /* string-based in_str */
2389 ch = (unsigned char)*i->p;
2398 /* FILE-based in_str */
2400 #if ENABLE_FEATURE_EDITING
2401 /* This can be stdin, check line editing char[] buffer */
2402 if (i->p && *i->p != '\0') {
2403 ch = (unsigned char)*i->p++;
2407 /* peek_buf[] is an int array, not char. Can contain EOF. */
2408 ch = i->peek_buf[0];
2410 int ch2 = i->peek_buf[1];
2411 i->peek_buf[0] = ch2;
2412 if (ch2 == 0) /* very likely, avoid redundant write */
2418 ch = fgetc_interactive(i);
2420 debug_printf("file_get: got '%c' %d\n", ch, ch);
2425 static int i_peek(struct in_str *i)
2430 /* string-based in_str */
2431 /* Doesn't report EOF on NUL. None of the callers care. */
2432 return (unsigned char)*i->p;
2435 /* FILE-based in_str */
2437 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2438 /* This can be stdin, check line editing char[] buffer */
2439 if (i->p && *i->p != '\0')
2440 return (unsigned char)*i->p;
2442 /* peek_buf[] is an int array, not char. Can contain EOF. */
2443 ch = i->peek_buf[0];
2447 /* Need to get a new char */
2448 ch = fgetc_interactive(i);
2449 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2451 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2452 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2458 i->peek_buf[0] = ch;
2459 /*i->peek_buf[1] = 0; - already is */
2463 /* Only ever called if i_peek() was called, and did not return EOF.
2464 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2465 * not end-of-line. Therefore we never need to read a new editing line here.
2467 static int i_peek2(struct in_str *i)
2471 /* There are two cases when i->p[] buffer exists.
2472 * (1) it's a string in_str.
2473 * (2) It's a file, and we have a saved line editing buffer.
2474 * In both cases, we know that i->p[0] exists and not NUL, and
2475 * the peek2 result is in i->p[1].
2478 return (unsigned char)i->p[1];
2480 /* Now we know it is a file-based in_str. */
2482 /* peek_buf[] is an int array, not char. Can contain EOF. */
2483 /* Is there 2nd char? */
2484 ch = i->peek_buf[1];
2486 /* We did not read it yet, get it now */
2487 do ch = fgetc(i->file); while (ch == '\0');
2488 i->peek_buf[1] = ch;
2491 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2495 static void setup_file_in_str(struct in_str *i, FILE *f)
2497 memset(i, 0, sizeof(*i));
2498 /* i->promptmode = 0; - PS1 (memset did it) */
2503 static void setup_string_in_str(struct in_str *i, const char *s)
2505 memset(i, 0, sizeof(*i));
2506 /* i->promptmode = 0; - PS1 (memset did it) */
2507 /*i->file = NULL */;
2515 #define B_CHUNK (32 * sizeof(char*))
2517 static void o_reset_to_empty_unquoted(o_string *o)
2520 o->has_quoted_part = 0;
2525 static void o_free(o_string *o)
2528 memset(o, 0, sizeof(*o));
2531 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2536 static void o_grow_by(o_string *o, int len)
2538 if (o->length + len > o->maxlen) {
2539 o->maxlen += (2 * len) | (B_CHUNK-1);
2540 o->data = xrealloc(o->data, 1 + o->maxlen);
2544 static void o_addchr(o_string *o, int ch)
2546 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2547 if (o->length < o->maxlen) {
2548 /* likely. avoid o_grow_by() call */
2550 o->data[o->length] = ch;
2552 o->data[o->length] = '\0';
2560 /* Valid only if we know o_string is not empty */
2561 static void o_delchr(o_string *o)
2564 o->data[o->length] = '\0';
2568 static void o_addblock(o_string *o, const char *str, int len)
2571 memcpy(&o->data[o->length], str, len);
2573 o->data[o->length] = '\0';
2576 static void o_addstr(o_string *o, const char *str)
2578 o_addblock(o, str, strlen(str));
2582 static void nommu_addchr(o_string *o, int ch)
2588 # define nommu_addchr(o, str) ((void)0)
2591 static void o_addstr_with_NUL(o_string *o, const char *str)
2593 o_addblock(o, str, strlen(str) + 1);
2597 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2598 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2599 * Apparently, on unquoted $v bash still does globbing
2600 * ("v='*.txt'; echo $v" prints all .txt files),
2601 * but NOT brace expansion! Thus, there should be TWO independent
2602 * quoting mechanisms on $v expansion side: one protects
2603 * $v from brace expansion, and other additionally protects "$v" against globbing.
2604 * We have only second one.
2607 #if ENABLE_HUSH_BRACE_EXPANSION
2608 # define MAYBE_BRACES "{}"
2610 # define MAYBE_BRACES ""
2613 /* My analysis of quoting semantics tells me that state information
2614 * is associated with a destination, not a source.
2616 static void o_addqchr(o_string *o, int ch)
2619 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2624 o->data[o->length] = '\\';
2627 o->data[o->length] = ch;
2629 o->data[o->length] = '\0';
2632 static void o_addQchr(o_string *o, int ch)
2635 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2636 && strchr("*?[\\" MAYBE_BRACES, ch)
2639 o->data[o->length] = '\\';
2643 o->data[o->length] = ch;
2645 o->data[o->length] = '\0';
2648 static void o_addqblock(o_string *o, const char *str, int len)
2653 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2654 if (ordinary_cnt > len) /* paranoia */
2656 o_addblock(o, str, ordinary_cnt);
2657 if (ordinary_cnt == len)
2658 return; /* NUL is already added by o_addblock */
2659 str += ordinary_cnt;
2660 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2664 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2666 o->data[o->length] = '\\';
2670 o->data[o->length] = ch;
2673 o->data[o->length] = '\0';
2676 static void o_addQblock(o_string *o, const char *str, int len)
2678 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2679 o_addblock(o, str, len);
2682 o_addqblock(o, str, len);
2685 static void o_addQstr(o_string *o, const char *str)
2687 o_addQblock(o, str, strlen(str));
2690 /* A special kind of o_string for $VAR and `cmd` expansion.
2691 * It contains char* list[] at the beginning, which is grown in 16 element
2692 * increments. Actual string data starts at the next multiple of 16 * (char*).
2693 * list[i] contains an INDEX (int!) into this string data.
2694 * It means that if list[] needs to grow, data needs to be moved higher up
2695 * but list[i]'s need not be modified.
2696 * NB: remembering how many list[i]'s you have there is crucial.
2697 * o_finalize_list() operation post-processes this structure - calculates
2698 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2700 #if DEBUG_EXPAND || DEBUG_GLOB
2701 static void debug_print_list(const char *prefix, o_string *o, int n)
2703 char **list = (char**)o->data;
2704 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2708 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2709 prefix, list, n, string_start, o->length, o->maxlen,
2710 !!(o->o_expflags & EXP_FLAG_GLOB),
2712 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2715 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2716 o->data + (int)(uintptr_t)list[i] + string_start,
2717 o->data + (int)(uintptr_t)list[i] + string_start);
2721 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2723 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2727 # define debug_print_list(prefix, o, n) ((void)0)
2730 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2731 * in list[n] so that it points past last stored byte so far.
2732 * It returns n+1. */
2733 static int o_save_ptr_helper(o_string *o, int n)
2735 char **list = (char**)o->data;
2739 if (!o->has_empty_slot) {
2740 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2741 string_len = o->length - string_start;
2742 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2743 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2744 /* list[n] points to string_start, make space for 16 more pointers */
2745 o->maxlen += 0x10 * sizeof(list[0]);
2746 o->data = xrealloc(o->data, o->maxlen + 1);
2747 list = (char**)o->data;
2748 memmove(list + n + 0x10, list + n, string_len);
2749 o->length += 0x10 * sizeof(list[0]);
2751 debug_printf_list("list[%d]=%d string_start=%d\n",
2752 n, string_len, string_start);
2755 /* We have empty slot at list[n], reuse without growth */
2756 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2757 string_len = o->length - string_start;
2758 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2759 n, string_len, string_start);
2760 o->has_empty_slot = 0;
2762 o->has_quoted_part = 0;
2763 list[n] = (char*)(uintptr_t)string_len;
2767 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2768 static int o_get_last_ptr(o_string *o, int n)
2770 char **list = (char**)o->data;
2771 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2773 return ((int)(uintptr_t)list[n-1]) + string_start;
2776 #if ENABLE_HUSH_BRACE_EXPANSION
2777 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2778 * first, it processes even {a} (no commas), second,
2779 * I didn't manage to make it return strings when they don't match
2780 * existing files. Need to re-implement it.
2784 static int glob_needed(const char *s)
2793 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2799 /* Return pointer to next closing brace or to comma */
2800 static const char *next_brace_sub(const char *cp)
2804 while (*cp != '\0') {
2811 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2817 return *cp != '\0' ? cp : NULL;
2819 /* Recursive brace globber. Note: may garble pattern[]. */
2820 static int glob_brace(char *pattern, o_string *o, int n)
2822 char *new_pattern_buf;
2829 debug_printf_glob("glob_brace('%s')\n", pattern);
2835 if (*begin == '{') {
2836 /* Find the first sub-pattern and at the same time
2837 * find the rest after the closing brace */
2838 next = next_brace_sub(begin);
2840 /* An illegal expression */
2844 /* "{abc}" with no commas - illegal
2845 * brace expr, disregard and skip it */
2851 if (*begin == '\\' && begin[1] != '\0')
2855 debug_printf_glob("begin:%s\n", begin);
2856 debug_printf_glob("next:%s\n", next);
2858 /* Now find the end of the whole brace expression */
2860 while (*rest != '}') {
2861 rest = next_brace_sub(rest);
2863 /* An illegal expression */
2866 debug_printf_glob("rest:%s\n", rest);
2868 rest_len = strlen(++rest) + 1;
2870 /* We are sure the brace expression is well-formed */
2872 /* Allocate working buffer large enough for our work */
2873 new_pattern_buf = xmalloc(strlen(pattern));
2875 /* We have a brace expression. BEGIN points to the opening {,
2876 * NEXT points past the terminator of the first element, and REST
2877 * points past the final }. We will accumulate result names from
2878 * recursive runs for each brace alternative in the buffer using
2883 /* Construct the new glob expression */
2886 mempcpy(new_pattern_buf,
2887 /* We know the prefix for all sub-patterns */
2888 pattern, begin - pattern),
2892 /* Note: glob_brace() may garble new_pattern_buf[].
2893 * That's why we re-copy prefix every time (1st memcpy above).
2895 n = glob_brace(new_pattern_buf, o, n);
2897 /* We saw the last entry */
2901 next = next_brace_sub(next);
2903 free(new_pattern_buf);
2911 memset(&globdata, 0, sizeof(globdata));
2912 gr = glob(pattern, 0, NULL, &globdata);
2913 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2915 if (gr == GLOB_NOMATCH) {
2916 globfree(&globdata);
2917 /* NB: garbles parameter */
2918 unbackslash(pattern);
2919 o_addstr_with_NUL(o, pattern);
2920 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2921 return o_save_ptr_helper(o, n);
2923 if (gr == GLOB_NOSPACE)
2924 bb_error_msg_and_die(bb_msg_memory_exhausted);
2925 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2926 * but we didn't specify it. Paranoia again. */
2927 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2929 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2930 char **argv = globdata.gl_pathv;
2932 o_addstr_with_NUL(o, *argv);
2933 n = o_save_ptr_helper(o, n);
2939 globfree(&globdata);
2943 /* Performs globbing on last list[],
2944 * saving each result as a new list[].
2946 static int perform_glob(o_string *o, int n)
2948 char *pattern, *copy;
2950 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2952 return o_save_ptr_helper(o, n);
2953 pattern = o->data + o_get_last_ptr(o, n);
2954 debug_printf_glob("glob pattern '%s'\n", pattern);
2955 if (!glob_needed(pattern)) {
2956 /* unbackslash last string in o in place, fix length */
2957 o->length = unbackslash(pattern) - o->data;
2958 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2959 return o_save_ptr_helper(o, n);
2962 copy = xstrdup(pattern);
2963 /* "forget" pattern in o */
2964 o->length = pattern - o->data;
2965 n = glob_brace(copy, o, n);
2968 debug_print_list("perform_glob returning", o, n);
2972 #else /* !HUSH_BRACE_EXPANSION */
2975 static int glob_needed(const char *s)
2984 if (*s == '*' || *s == '[' || *s == '?')
2990 /* Performs globbing on last list[],
2991 * saving each result as a new list[].
2993 static int perform_glob(o_string *o, int n)
2999 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3001 return o_save_ptr_helper(o, n);
3002 pattern = o->data + o_get_last_ptr(o, n);
3003 debug_printf_glob("glob pattern '%s'\n", pattern);
3004 if (!glob_needed(pattern)) {
3006 /* unbackslash last string in o in place, fix length */
3007 o->length = unbackslash(pattern) - o->data;
3008 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3009 return o_save_ptr_helper(o, n);
3012 memset(&globdata, 0, sizeof(globdata));
3013 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3014 * If we glob "*.\*" and don't find anything, we need
3015 * to fall back to using literal "*.*", but GLOB_NOCHECK
3016 * will return "*.\*"!
3018 gr = glob(pattern, 0, NULL, &globdata);
3019 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3021 if (gr == GLOB_NOMATCH) {
3022 globfree(&globdata);
3025 if (gr == GLOB_NOSPACE)
3026 bb_error_msg_and_die(bb_msg_memory_exhausted);
3027 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3028 * but we didn't specify it. Paranoia again. */
3029 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3031 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3032 char **argv = globdata.gl_pathv;
3033 /* "forget" pattern in o */
3034 o->length = pattern - o->data;
3036 o_addstr_with_NUL(o, *argv);
3037 n = o_save_ptr_helper(o, n);
3043 globfree(&globdata);
3045 debug_print_list("perform_glob returning", o, n);
3049 #endif /* !HUSH_BRACE_EXPANSION */
3051 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3052 * Otherwise, just finish current list[] and start new */
3053 static int o_save_ptr(o_string *o, int n)
3055 if (o->o_expflags & EXP_FLAG_GLOB) {
3056 /* If o->has_empty_slot, list[n] was already globbed
3057 * (if it was requested back then when it was filled)
3058 * so don't do that again! */
3059 if (!o->has_empty_slot)
3060 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3062 return o_save_ptr_helper(o, n);
3065 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3066 static char **o_finalize_list(o_string *o, int n)
3071 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3073 debug_print_list("finalized", o, n);
3074 debug_printf_expand("finalized n:%d\n", n);
3075 list = (char**)o->data;
3076 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3080 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3085 static void free_pipe_list(struct pipe *pi);
3087 /* Returns pi->next - next pipe in the list */
3088 static struct pipe *free_pipe(struct pipe *pi)
3093 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3094 for (i = 0; i < pi->num_cmds; i++) {
3095 struct command *command;
3096 struct redir_struct *r, *rnext;
3098 command = &pi->cmds[i];
3099 debug_printf_clean(" command %d:\n", i);
3100 if (command->argv) {
3104 for (a = 0, p = command->argv; *p; a++, p++) {
3105 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3108 free_strings(command->argv);
3109 //command->argv = NULL;
3111 /* not "else if": on syntax error, we may have both! */
3112 if (command->group) {
3113 debug_printf_clean(" begin group (cmd_type:%d)\n",
3115 free_pipe_list(command->group);
3116 debug_printf_clean(" end group\n");
3117 //command->group = NULL;
3119 /* else is crucial here.
3120 * If group != NULL, child_func is meaningless */
3121 #if ENABLE_HUSH_FUNCTIONS
3122 else if (command->child_func) {
3123 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3124 command->child_func->parent_cmd = NULL;
3128 free(command->group_as_string);
3129 //command->group_as_string = NULL;
3131 for (r = command->redirects; r; r = rnext) {
3132 debug_printf_clean(" redirect %d%s",
3133 r->rd_fd, redir_table[r->rd_type].descrip);
3134 /* guard against the case >$FOO, where foo is unset or blank */
3135 if (r->rd_filename) {
3136 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3137 free(r->rd_filename);
3138 //r->rd_filename = NULL;
3140 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3144 //command->redirects = NULL;
3146 free(pi->cmds); /* children are an array, they get freed all at once */
3150 //pi->cmdtext = NULL;
3158 static void free_pipe_list(struct pipe *pi)
3162 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3164 debug_printf_clean("pipe followup code %d\n", pi->followup);
3170 /*** Parsing routines ***/
3172 #ifndef debug_print_tree
3173 static void debug_print_tree(struct pipe *pi, int lvl)
3175 static const char *const PIPE[] = {
3181 static const char *RES[] = {
3182 [RES_NONE ] = "NONE" ,
3185 [RES_THEN ] = "THEN" ,
3186 [RES_ELIF ] = "ELIF" ,
3187 [RES_ELSE ] = "ELSE" ,
3190 # if ENABLE_HUSH_LOOPS
3191 [RES_FOR ] = "FOR" ,
3192 [RES_WHILE] = "WHILE",
3193 [RES_UNTIL] = "UNTIL",
3195 [RES_DONE ] = "DONE" ,
3197 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3200 # if ENABLE_HUSH_CASE
3201 [RES_CASE ] = "CASE" ,
3202 [RES_CASE_IN ] = "CASE_IN" ,
3203 [RES_MATCH] = "MATCH",
3204 [RES_CASE_BODY] = "CASE_BODY",
3205 [RES_ESAC ] = "ESAC" ,
3207 [RES_XXXX ] = "XXXX" ,
3208 [RES_SNTX ] = "SNTX" ,
3210 static const char *const CMDTYPE[] = {
3214 # if ENABLE_HUSH_FUNCTIONS
3223 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3224 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3226 while (prn < pi->num_cmds) {
3227 struct command *command = &pi->cmds[prn];
3228 char **argv = command->argv;
3230 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3232 command->assignment_cnt);
3233 if (command->group) {
3234 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3235 CMDTYPE[command->cmd_type],
3238 , " group_as_string:", command->group_as_string
3243 debug_print_tree(command->group, lvl+1);
3247 if (argv) while (*argv) {
3248 fdprintf(2, " '%s'", *argv);
3258 #endif /* debug_print_tree */
3260 static struct pipe *new_pipe(void)
3263 pi = xzalloc(sizeof(struct pipe));
3264 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3268 /* Command (member of a pipe) is complete, or we start a new pipe
3269 * if ctx->command is NULL.
3270 * No errors possible here.
3272 static int done_command(struct parse_context *ctx)
3274 /* The command is really already in the pipe structure, so
3275 * advance the pipe counter and make a new, null command. */
3276 struct pipe *pi = ctx->pipe;
3277 struct command *command = ctx->command;
3279 #if 0 /* Instead we emit error message at run time */
3280 if (ctx->pending_redirect) {
3281 /* For example, "cmd >" (no filename to redirect to) */
3282 die_if_script("syntax error: %s", "invalid redirect");
3283 ctx->pending_redirect = NULL;
3288 if (IS_NULL_CMD(command)) {
3289 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3293 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3294 //debug_print_tree(ctx->list_head, 20);
3296 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3299 /* Only real trickiness here is that the uncommitted
3300 * command structure is not counted in pi->num_cmds. */
3301 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3302 ctx->command = command = &pi->cmds[pi->num_cmds];
3304 memset(command, 0, sizeof(*command));
3305 return pi->num_cmds; /* used only for 0/nonzero check */
3308 static void done_pipe(struct parse_context *ctx, pipe_style type)
3312 debug_printf_parse("done_pipe entered, followup %d\n", type);
3313 /* Close previous command */
3314 not_null = done_command(ctx);
3315 ctx->pipe->followup = type;
3317 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3318 ctx->ctx_inverted = 0;
3319 ctx->pipe->res_word = ctx->ctx_res_w;
3322 /* Without this check, even just <enter> on command line generates
3323 * tree of three NOPs (!). Which is harmless but annoying.
3324 * IOW: it is safe to do it unconditionally. */
3327 || ctx->ctx_res_w == RES_FI
3329 #if ENABLE_HUSH_LOOPS
3330 || ctx->ctx_res_w == RES_DONE
3331 || ctx->ctx_res_w == RES_FOR
3332 || ctx->ctx_res_w == RES_IN
3334 #if ENABLE_HUSH_CASE
3335 || ctx->ctx_res_w == RES_ESAC
3339 debug_printf_parse("done_pipe: adding new pipe: "
3340 "not_null:%d ctx->ctx_res_w:%d\n",
3341 not_null, ctx->ctx_res_w);
3343 ctx->pipe->next = new_p;
3345 /* RES_THEN, RES_DO etc are "sticky" -
3346 * they remain set for pipes inside if/while.
3347 * This is used to control execution.
3348 * RES_FOR and RES_IN are NOT sticky (needed to support
3349 * cases where variable or value happens to match a keyword):
3351 #if ENABLE_HUSH_LOOPS
3352 if (ctx->ctx_res_w == RES_FOR
3353 || ctx->ctx_res_w == RES_IN)
3354 ctx->ctx_res_w = RES_NONE;
3356 #if ENABLE_HUSH_CASE
3357 if (ctx->ctx_res_w == RES_MATCH)
3358 ctx->ctx_res_w = RES_CASE_BODY;
3359 if (ctx->ctx_res_w == RES_CASE)
3360 ctx->ctx_res_w = RES_CASE_IN;
3362 ctx->command = NULL; /* trick done_command below */
3363 /* Create the memory for command, roughly:
3364 * ctx->pipe->cmds = new struct command;
3365 * ctx->command = &ctx->pipe->cmds[0];
3368 //debug_print_tree(ctx->list_head, 10);
3370 debug_printf_parse("done_pipe return\n");
3373 static void initialize_context(struct parse_context *ctx)
3375 memset(ctx, 0, sizeof(*ctx));
3376 ctx->pipe = ctx->list_head = new_pipe();
3377 /* Create the memory for command, roughly:
3378 * ctx->pipe->cmds = new struct command;
3379 * ctx->command = &ctx->pipe->cmds[0];
3384 /* If a reserved word is found and processed, parse context is modified
3385 * and 1 is returned.
3388 struct reserved_combo {
3391 unsigned char assignment_flag;
3395 FLAG_END = (1 << RES_NONE ),
3397 FLAG_IF = (1 << RES_IF ),
3398 FLAG_THEN = (1 << RES_THEN ),
3399 FLAG_ELIF = (1 << RES_ELIF ),
3400 FLAG_ELSE = (1 << RES_ELSE ),
3401 FLAG_FI = (1 << RES_FI ),
3403 # if ENABLE_HUSH_LOOPS
3404 FLAG_FOR = (1 << RES_FOR ),
3405 FLAG_WHILE = (1 << RES_WHILE),
3406 FLAG_UNTIL = (1 << RES_UNTIL),
3407 FLAG_DO = (1 << RES_DO ),
3408 FLAG_DONE = (1 << RES_DONE ),
3409 FLAG_IN = (1 << RES_IN ),
3411 # if ENABLE_HUSH_CASE
3412 FLAG_MATCH = (1 << RES_MATCH),
3413 FLAG_ESAC = (1 << RES_ESAC ),
3415 FLAG_START = (1 << RES_XXXX ),
3418 static const struct reserved_combo* match_reserved_word(o_string *word)
3420 /* Mostly a list of accepted follow-up reserved words.
3421 * FLAG_END means we are done with the sequence, and are ready
3422 * to turn the compound list into a command.
3423 * FLAG_START means the word must start a new compound list.
3425 static const struct reserved_combo reserved_list[] = {
3427 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3428 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3429 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3430 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3431 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3432 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3434 # if ENABLE_HUSH_LOOPS
3435 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3436 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3437 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3438 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3439 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3440 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3442 # if ENABLE_HUSH_CASE
3443 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3444 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3447 const struct reserved_combo *r;
3449 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3450 if (strcmp(word->data, r->literal) == 0)
3455 /* Return 0: not a keyword, 1: keyword
3457 static int reserved_word(o_string *word, struct parse_context *ctx)
3459 # if ENABLE_HUSH_CASE
3460 static const struct reserved_combo reserved_match = {
3461 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3464 const struct reserved_combo *r;
3466 if (word->has_quoted_part)
3468 r = match_reserved_word(word);
3472 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3473 # if ENABLE_HUSH_CASE
3474 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3475 /* "case word IN ..." - IN part starts first MATCH part */
3476 r = &reserved_match;
3479 if (r->flag == 0) { /* '!' */
3480 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3481 syntax_error("! ! command");
3482 ctx->ctx_res_w = RES_SNTX;
3484 ctx->ctx_inverted = 1;
3487 if (r->flag & FLAG_START) {
3488 struct parse_context *old;
3490 old = xmalloc(sizeof(*old));
3491 debug_printf_parse("push stack %p\n", old);
3492 *old = *ctx; /* physical copy */
3493 initialize_context(ctx);
3495 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3496 syntax_error_at(word->data);
3497 ctx->ctx_res_w = RES_SNTX;
3500 /* "{...} fi" is ok. "{...} if" is not
3502 * if { echo foo; } then { echo bar; } fi */
3503 if (ctx->command->group)
3504 done_pipe(ctx, PIPE_SEQ);
3507 ctx->ctx_res_w = r->res;
3508 ctx->old_flag = r->flag;
3509 word->o_assignment = r->assignment_flag;
3510 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3512 if (ctx->old_flag & FLAG_END) {
3513 struct parse_context *old;
3515 done_pipe(ctx, PIPE_SEQ);
3516 debug_printf_parse("pop stack %p\n", ctx->stack);
3518 old->command->group = ctx->list_head;
3519 old->command->cmd_type = CMD_NORMAL;
3521 /* At this point, the compound command's string is in
3522 * ctx->as_string... except for the leading keyword!
3523 * Consider this example: "echo a | if true; then echo a; fi"
3524 * ctx->as_string will contain "true; then echo a; fi",
3525 * with "if " remaining in old->as_string!
3529 int len = old->as_string.length;
3530 /* Concatenate halves */
3531 o_addstr(&old->as_string, ctx->as_string.data);
3532 o_free_unsafe(&ctx->as_string);
3533 /* Find where leading keyword starts in first half */
3534 str = old->as_string.data + len;
3535 if (str > old->as_string.data)
3536 str--; /* skip whitespace after keyword */
3537 while (str > old->as_string.data && isalpha(str[-1]))
3539 /* Ugh, we're done with this horrid hack */
3540 old->command->group_as_string = xstrdup(str);
3541 debug_printf_parse("pop, remembering as:'%s'\n",
3542 old->command->group_as_string);
3545 *ctx = *old; /* physical copy */
3550 #endif /* HAS_KEYWORDS */
3552 /* Word is complete, look at it and update parsing context.
3553 * Normal return is 0. Syntax errors return 1.
3554 * Note: on return, word is reset, but not o_free'd!
3556 static int done_word(o_string *word, struct parse_context *ctx)
3558 struct command *command = ctx->command;
3560 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3561 if (word->length == 0 && !word->has_quoted_part) {
3562 debug_printf_parse("done_word return 0: true null, ignored\n");
3566 if (ctx->pending_redirect) {
3567 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3568 * only if run as "bash", not "sh" */
3569 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3571 * ...the word that follows the redirection operator
3572 * shall be subjected to tilde expansion, parameter expansion,
3573 * command substitution, arithmetic expansion, and quote
3574 * removal. Pathname expansion shall not be performed
3575 * on the word by a non-interactive shell; an interactive
3576 * shell may perform it, but shall do so only when
3577 * the expansion would result in one word."
3579 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3580 /* Cater for >\file case:
3581 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3582 * Same with heredocs:
3583 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3585 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3586 unbackslash(ctx->pending_redirect->rd_filename);
3587 /* Is it <<"HEREDOC"? */
3588 if (word->has_quoted_part) {
3589 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3592 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3593 ctx->pending_redirect = NULL;
3596 # if ENABLE_HUSH_CASE
3597 if (ctx->ctx_dsemicolon
3598 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3600 /* already done when ctx_dsemicolon was set to 1: */
3601 /* ctx->ctx_res_w = RES_MATCH; */
3602 ctx->ctx_dsemicolon = 0;
3605 if (!command->argv /* if it's the first word... */
3606 # if ENABLE_HUSH_LOOPS
3607 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3608 && ctx->ctx_res_w != RES_IN
3610 # if ENABLE_HUSH_CASE
3611 && ctx->ctx_res_w != RES_CASE
3614 int reserved = reserved_word(word, ctx);
3615 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3617 o_reset_to_empty_unquoted(word);
3618 debug_printf_parse("done_word return %d\n",
3619 (ctx->ctx_res_w == RES_SNTX));
3620 return (ctx->ctx_res_w == RES_SNTX);
3622 # if ENABLE_HUSH_BASH_COMPAT
3623 if (strcmp(word->data, "[[") == 0) {
3624 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3630 if (command->group) {
3631 /* "{ echo foo; } echo bar" - bad */
3632 syntax_error_at(word->data);
3633 debug_printf_parse("done_word return 1: syntax error, "
3634 "groups and arglists don't mix\n");
3638 /* If this word wasn't an assignment, next ones definitely
3639 * can't be assignments. Even if they look like ones. */
3640 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3641 && word->o_assignment != WORD_IS_KEYWORD
3643 word->o_assignment = NOT_ASSIGNMENT;
3645 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3646 command->assignment_cnt++;
3647 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3649 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3650 word->o_assignment = MAYBE_ASSIGNMENT;
3652 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3654 if (word->has_quoted_part
3655 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3656 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3657 /* (otherwise it's known to be not empty and is already safe) */
3659 /* exclude "$@" - it can expand to no word despite "" */
3660 char *p = word->data;
3661 while (p[0] == SPECIAL_VAR_SYMBOL
3662 && (p[1] & 0x7f) == '@'
3663 && p[2] == SPECIAL_VAR_SYMBOL
3668 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3669 debug_print_strings("word appended to argv", command->argv);
3672 #if ENABLE_HUSH_LOOPS
3673 if (ctx->ctx_res_w == RES_FOR) {
3674 if (word->has_quoted_part
3675 || !is_well_formed_var_name(command->argv[0], '\0')
3677 /* bash says just "not a valid identifier" */
3678 syntax_error("not a valid identifier in for");
3681 /* Force FOR to have just one word (variable name) */
3682 /* NB: basically, this makes hush see "for v in ..."
3683 * syntax as if it is "for v; in ...". FOR and IN become
3684 * two pipe structs in parse tree. */
3685 done_pipe(ctx, PIPE_SEQ);
3688 #if ENABLE_HUSH_CASE
3689 /* Force CASE to have just one word */
3690 if (ctx->ctx_res_w == RES_CASE) {
3691 done_pipe(ctx, PIPE_SEQ);
3695 o_reset_to_empty_unquoted(word);
3697 debug_printf_parse("done_word return 0\n");
3702 /* Peek ahead in the input to find out if we have a "&n" construct,
3703 * as in "2>&1", that represents duplicating a file descriptor.
3705 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3706 * REDIRFD_SYNTAX_ERR if syntax error,
3707 * REDIRFD_TO_FILE if no & was seen,
3708 * or the number found.
3711 #define parse_redir_right_fd(as_string, input) \
3712 parse_redir_right_fd(input)
3714 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3720 return REDIRFD_TO_FILE;
3722 ch = i_getch(input); /* get the & */
3723 nommu_addchr(as_string, ch);
3726 ch = i_getch(input);
3727 nommu_addchr(as_string, ch);
3728 return REDIRFD_CLOSE;
3732 while (ch != EOF && isdigit(ch)) {
3733 d = d*10 + (ch-'0');
3735 ch = i_getch(input);
3736 nommu_addchr(as_string, ch);
3741 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3743 bb_error_msg("ambiguous redirect");
3744 return REDIRFD_SYNTAX_ERR;
3747 /* Return code is 0 normal, 1 if a syntax error is detected
3749 static int parse_redirect(struct parse_context *ctx,
3752 struct in_str *input)
3754 struct command *command = ctx->command;
3755 struct redir_struct *redir;
3756 struct redir_struct **redirp;
3759 dup_num = REDIRFD_TO_FILE;
3760 if (style != REDIRECT_HEREDOC) {
3761 /* Check for a '>&1' type redirect */
3762 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3763 if (dup_num == REDIRFD_SYNTAX_ERR)
3766 int ch = i_peek(input);
3767 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3768 if (dup_num) { /* <<-... */
3769 ch = i_getch(input);
3770 nommu_addchr(&ctx->as_string, ch);
3775 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3776 int ch = i_peek(input);
3778 /* >|FILE redirect ("clobbering" >).
3779 * Since we do not support "set -o noclobber" yet,
3780 * >| and > are the same for now. Just eat |.
3782 ch = i_getch(input);
3783 nommu_addchr(&ctx->as_string, ch);
3787 /* Create a new redir_struct and append it to the linked list */
3788 redirp = &command->redirects;
3789 while ((redir = *redirp) != NULL) {
3790 redirp = &(redir->next);
3792 *redirp = redir = xzalloc(sizeof(*redir));
3793 /* redir->next = NULL; */
3794 /* redir->rd_filename = NULL; */
3795 redir->rd_type = style;
3796 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3798 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3799 redir_table[style].descrip);
3801 redir->rd_dup = dup_num;
3802 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3803 /* Erik had a check here that the file descriptor in question
3804 * is legit; I postpone that to "run time"
3805 * A "-" representation of "close me" shows up as a -3 here */
3806 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3807 redir->rd_fd, redir->rd_dup);
3809 #if 0 /* Instead we emit error message at run time */
3810 if (ctx->pending_redirect) {
3811 /* For example, "cmd > <file" */
3812 die_if_script("syntax error: %s", "invalid redirect");
3815 /* Set ctx->pending_redirect, so we know what to do at the
3816 * end of the next parsed word. */
3817 ctx->pending_redirect = redir;
3822 /* If a redirect is immediately preceded by a number, that number is
3823 * supposed to tell which file descriptor to redirect. This routine
3824 * looks for such preceding numbers. In an ideal world this routine
3825 * needs to handle all the following classes of redirects...
3826 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3827 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3828 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3829 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3831 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3833 * ... If n is quoted, the number shall not be recognized as part of
3834 * the redirection expression. For example:
3836 * writes the character 2 into file a"
3837 * We are getting it right by setting ->has_quoted_part on any \<char>
3839 * A -1 return means no valid number was found,
3840 * the caller should use the appropriate default for this redirection.
3842 static int redirect_opt_num(o_string *o)
3846 if (o->data == NULL)
3848 num = bb_strtou(o->data, NULL, 10);
3849 if (errno || num < 0)
3851 o_reset_to_empty_unquoted(o);
3856 #define fetch_till_str(as_string, input, word, skip_tabs) \
3857 fetch_till_str(input, word, skip_tabs)
3859 static char *fetch_till_str(o_string *as_string,
3860 struct in_str *input,
3864 o_string heredoc = NULL_O_STRING;
3866 int prev = 0; /* not \ */
3872 ch = i_getch(input);
3874 nommu_addchr(as_string, ch);
3875 if ((ch == '\n' || ch == EOF)
3876 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3878 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3879 heredoc.data[past_EOL] = '\0';
3880 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3881 return heredoc.data;
3883 while (ch == '\n') {
3884 o_addchr(&heredoc, ch);
3887 past_EOL = heredoc.length;
3889 ch = i_getch(input);
3891 nommu_addchr(as_string, ch);
3892 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3896 o_free_unsafe(&heredoc);
3899 o_addchr(&heredoc, ch);
3900 nommu_addchr(as_string, ch);
3901 if (prev == '\\' && ch == '\\')
3902 /* Correctly handle foo\\<eol> (not a line cont.) */
3903 prev = 0; /* not \ */
3909 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3910 * and load them all. There should be exactly heredoc_cnt of them.
3912 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3914 struct pipe *pi = ctx->list_head;
3916 while (pi && heredoc_cnt) {
3918 struct command *cmd = pi->cmds;
3920 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3922 cmd->argv ? cmd->argv[0] : "NONE");
3923 for (i = 0; i < pi->num_cmds; i++) {
3924 struct redir_struct *redir = cmd->redirects;
3926 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3927 i, cmd->argv ? cmd->argv[0] : "NONE");
3929 if (redir->rd_type == REDIRECT_HEREDOC) {
3932 redir->rd_type = REDIRECT_HEREDOC2;
3933 /* redir->rd_dup is (ab)used to indicate <<- */
3934 p = fetch_till_str(&ctx->as_string, input,
3935 redir->rd_filename, redir->rd_dup);
3937 syntax_error("unexpected EOF in here document");
3940 free(redir->rd_filename);
3941 redir->rd_filename = p;
3944 redir = redir->next;
3951 /* Should be 0. If it isn't, it's a parse error */
3953 bb_error_msg_and_die("heredoc BUG 2");
3959 static int run_list(struct pipe *pi);
3961 #define parse_stream(pstring, input, end_trigger) \
3962 parse_stream(input, end_trigger)
3964 static struct pipe *parse_stream(char **pstring,
3965 struct in_str *input,
3969 #if !ENABLE_HUSH_FUNCTIONS
3970 #define parse_group(dest, ctx, input, ch) \
3971 parse_group(ctx, input, ch)
3973 static int parse_group(o_string *dest, struct parse_context *ctx,
3974 struct in_str *input, int ch)
3976 /* dest contains characters seen prior to ( or {.
3977 * Typically it's empty, but for function defs,
3978 * it contains function name (without '()'). */
3979 struct pipe *pipe_list;
3981 struct command *command = ctx->command;
3983 debug_printf_parse("parse_group entered\n");
3984 #if ENABLE_HUSH_FUNCTIONS
3985 if (ch == '(' && !dest->has_quoted_part) {
3987 if (done_word(dest, ctx))
3990 goto skip; /* (... */
3991 if (command->argv[1]) { /* word word ... (... */
3992 syntax_error_unexpected_ch('(');
3995 /* it is "word(..." or "word (..." */
3997 ch = i_getch(input);
3998 while (ch == ' ' || ch == '\t');
4000 syntax_error_unexpected_ch(ch);
4003 nommu_addchr(&ctx->as_string, ch);
4005 ch = i_getch(input);
4006 while (ch == ' ' || ch == '\t' || ch == '\n');
4008 syntax_error_unexpected_ch(ch);
4011 nommu_addchr(&ctx->as_string, ch);
4012 command->cmd_type = CMD_FUNCDEF;
4017 #if 0 /* Prevented by caller */
4018 if (command->argv /* word [word]{... */
4019 || dest->length /* word{... */
4020 || dest->has_quoted_part /* ""{... */
4023 debug_printf_parse("parse_group return 1: "
4024 "syntax error, groups and arglists don't mix\n");
4029 #if ENABLE_HUSH_FUNCTIONS
4035 command->cmd_type = CMD_SUBSHELL;
4037 /* bash does not allow "{echo...", requires whitespace */
4039 if (ch != ' ' && ch != '\t' && ch != '\n'
4040 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4042 syntax_error_unexpected_ch(ch);
4046 ch = i_getch(input);
4047 nommu_addchr(&ctx->as_string, ch);
4053 # define as_string NULL
4055 char *as_string = NULL;
4057 pipe_list = parse_stream(&as_string, input, endch);
4060 o_addstr(&ctx->as_string, as_string);
4062 /* empty ()/{} or parse error? */
4063 if (!pipe_list || pipe_list == ERR_PTR) {
4064 /* parse_stream already emitted error msg */
4067 debug_printf_parse("parse_group return 1: "
4068 "parse_stream returned %p\n", pipe_list);
4071 command->group = pipe_list;
4073 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4074 command->group_as_string = as_string;
4075 debug_printf_parse("end of group, remembering as:'%s'\n",
4076 command->group_as_string);
4080 debug_printf_parse("parse_group return 0\n");
4082 /* command remains "open", available for possible redirects */
4085 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4090 ch = i_getch(input);
4093 ch2 = i_peek(input);
4096 /* backslash+newline, skip it */
4101 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4109 ch2 = i_peek2(input);
4112 /* backslash+newline, skip it */
4118 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4119 /* Subroutines for copying $(...) and `...` things */
4120 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4122 static int add_till_single_quote(o_string *dest, struct in_str *input)
4125 int ch = i_getch(input);
4127 syntax_error_unterm_ch('\'');
4135 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4136 static int add_till_double_quote(o_string *dest, struct in_str *input)
4139 int ch = i_getch(input);
4141 syntax_error_unterm_ch('"');
4146 if (ch == '\\') { /* \x. Copy both chars. */
4148 ch = i_getch(input);
4152 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4157 //if (ch == '$') ...
4160 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4162 * "Within the backquoted style of command substitution, backslash
4163 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4164 * The search for the matching backquote shall be satisfied by the first
4165 * backquote found without a preceding backslash; during this search,
4166 * if a non-escaped backquote is encountered within a shell comment,
4167 * a here-document, an embedded command substitution of the $(command)
4168 * form, or a quoted string, undefined results occur. A single-quoted
4169 * or double-quoted string that begins, but does not end, within the
4170 * "`...`" sequence produces undefined results."
4172 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4174 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4177 int ch = i_getch(input);
4181 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4182 ch = i_getch(input);
4186 && (!in_dquote || ch != '"')
4188 o_addchr(dest, '\\');
4192 syntax_error_unterm_ch('`');
4198 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4199 * quoting and nested ()s.
4200 * "With the $(command) style of command substitution, all characters
4201 * following the open parenthesis to the matching closing parenthesis
4202 * constitute the command. Any valid shell script can be used for command,
4203 * except a script consisting solely of redirections which produces
4204 * unspecified results."
4206 * echo $(echo '(TEST)' BEST) (TEST) BEST
4207 * echo $(echo 'TEST)' BEST) TEST) BEST
4208 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4210 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4211 * can contain arbitrary constructs, just like $(cmd).
4212 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4213 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4215 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4216 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4219 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4220 # if ENABLE_HUSH_BASH_COMPAT
4221 char end_char2 = end_ch >> 8;
4223 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4226 ch = i_getch(input);
4228 syntax_error_unterm_ch(end_ch);
4231 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4234 /* we look for closing )) of $((EXPR)) */
4235 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4236 i_getch(input); /* eat second ')' */
4241 if (ch == '(' || ch == '{') {
4242 ch = (ch == '(' ? ')' : '}');
4243 if (!add_till_closing_bracket(dest, input, ch))
4249 if (!add_till_single_quote(dest, input))
4255 if (!add_till_double_quote(dest, input))
4261 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4267 /* \x. Copy verbatim. Important for \(, \) */
4268 ch = i_getch(input);
4270 syntax_error_unterm_ch(')');
4275 /* "backslash+newline", ignore both */
4276 o_delchr(dest); /* undo insertion of '\' */
4286 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4288 /* Return code: 0 for OK, 1 for syntax error */
4290 #define parse_dollar(as_string, dest, input, quote_mask) \
4291 parse_dollar(dest, input, quote_mask)
4292 #define as_string NULL
4294 static int parse_dollar(o_string *as_string,
4296 struct in_str *input, unsigned char quote_mask)
4298 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4300 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4302 ch = i_getch(input);
4303 nommu_addchr(as_string, ch);
4305 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4307 debug_printf_parse(": '%c'\n", ch);
4308 o_addchr(dest, ch | quote_mask);
4310 ch = i_peek_and_eat_bkslash_nl(input);
4311 if (!isalnum(ch) && ch != '_') {
4312 /* End of variable name reached */
4315 ch = i_getch(input);
4316 nommu_addchr(as_string, ch);
4318 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4319 } else if (isdigit(ch)) {
4321 ch = i_getch(input);
4322 nommu_addchr(as_string, ch);
4323 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4324 debug_printf_parse(": '%c'\n", ch);
4325 o_addchr(dest, ch | quote_mask);
4326 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4327 } else switch (ch) {
4329 case '!': /* last bg pid */
4330 case '?': /* last exit code */
4331 case '#': /* number of args */
4332 case '*': /* args */
4333 case '@': /* args */
4334 goto make_one_char_var;
4336 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4338 ch = i_getch(input); /* eat '{' */
4339 nommu_addchr(as_string, ch);
4341 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4342 /* It should be ${?}, or ${#var},
4343 * or even ${?+subst} - operator acting on a special variable,
4344 * or the beginning of variable name.
4347 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4350 syntax_error_unterm_str("${name}");
4351 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4354 nommu_addchr(as_string, ch);
4357 /* It's possible to just call add_till_closing_bracket() at this point.
4358 * However, this regresses some of our testsuite cases
4359 * which check invalid constructs like ${%}.
4360 * Oh well... let's check that the var name part is fine... */
4366 debug_printf_parse(": '%c'\n", ch);
4368 ch = i_getch(input);
4369 nommu_addchr(as_string, ch);
4373 if (!isalnum(ch) && ch != '_') {
4375 unsigned char last_ch;
4376 /* handle parameter expansions
4377 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4379 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4380 goto bad_dollar_syntax;
4382 /* Eat everything until closing '}' (or ':') */
4384 if (ENABLE_HUSH_BASH_COMPAT
4386 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4388 /* It's ${var:N[:M]} thing */
4389 end_ch = '}' * 0x100 + ':';
4391 if (ENABLE_HUSH_BASH_COMPAT
4394 /* It's ${var/[/]pattern[/repl]} thing */
4395 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4397 nommu_addchr(as_string, '/');
4400 end_ch = '}' * 0x100 + '/';
4406 #if ENABLE_HUSH_DOLLAR_OPS
4407 last_ch = add_till_closing_bracket(dest, input, end_ch);
4408 if (last_ch == 0) /* error? */
4411 #error Simple code to only allow ${var} is not implemented
4414 o_addstr(as_string, dest->data + pos);
4415 o_addchr(as_string, last_ch);
4418 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4419 /* close the first block: */
4420 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4421 /* while parsing N from ${var:N[:M]}
4422 * or pattern from ${var/[/]pattern[/repl]} */
4423 if ((end_ch & 0xff) == last_ch) {
4424 /* got ':' or '/'- parse the rest */
4429 if (end_ch == '}' * 0x100 + ':') {
4430 /* it's ${var:N} - emulate :999999999 */
4431 o_addstr(dest, "999999999");
4432 } /* else: it's ${var/[/]pattern} */
4437 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4440 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4444 ch = i_getch(input);
4445 nommu_addchr(as_string, ch);
4446 # if ENABLE_FEATURE_SH_MATH
4447 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4448 ch = i_getch(input);
4449 nommu_addchr(as_string, ch);
4450 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4451 o_addchr(dest, /*quote_mask |*/ '+');
4454 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4455 return 0; /* error */
4457 o_addstr(as_string, dest->data + pos);
4458 o_addchr(as_string, ')');
4459 o_addchr(as_string, ')');
4461 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4465 # if ENABLE_HUSH_TICK
4466 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4467 o_addchr(dest, quote_mask | '`');
4470 if (!add_till_closing_bracket(dest, input, ')'))
4471 return 0; /* error */
4473 o_addstr(as_string, dest->data + pos);
4474 o_addchr(as_string, ')');
4476 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4482 ch = i_getch(input);
4483 nommu_addchr(as_string, ch);
4484 ch = i_peek_and_eat_bkslash_nl(input);
4485 if (isalnum(ch)) { /* it's $_name or $_123 */
4490 /* TODO: $_ and $-: */
4491 /* $_ Shell or shell script name; or last argument of last command
4492 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4493 * but in command's env, set to full pathname used to invoke it */
4494 /* $- Option flags set by set builtin or shell options (-i etc) */
4496 o_addQchr(dest, '$');
4498 debug_printf_parse("parse_dollar return 1 (ok)\n");
4504 # if ENABLE_HUSH_BASH_COMPAT
4505 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4506 encode_string(dest, input, dquote_end, process_bkslash)
4508 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4509 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4510 encode_string(dest, input, dquote_end)
4512 #define as_string NULL
4516 # if ENABLE_HUSH_BASH_COMPAT
4517 /* all parameters are needed, no macro tricks */
4519 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4520 encode_string(as_string, dest, input, dquote_end)
4523 static int encode_string(o_string *as_string,
4525 struct in_str *input,
4527 int process_bkslash)
4529 #if !ENABLE_HUSH_BASH_COMPAT
4530 const int process_bkslash = 1;
4536 ch = i_getch(input);
4538 nommu_addchr(as_string, ch);
4539 if (ch == dquote_end) { /* may be only '"' or EOF */
4540 debug_printf_parse("encode_string return 1 (ok)\n");
4543 /* note: can't move it above ch == dquote_end check! */
4545 syntax_error_unterm_ch('"');
4546 return 0; /* error */
4550 next = i_peek(input);
4552 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4553 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4554 if (process_bkslash && ch == '\\') {
4556 syntax_error("\\<eof>");
4560 * "The backslash retains its special meaning [in "..."]
4561 * only when followed by one of the following characters:
4562 * $, `, ", \, or <newline>. A double quote may be quoted
4563 * within double quotes by preceding it with a backslash."
4564 * NB: in (unquoted) heredoc, above does not apply to ",
4565 * therefore we check for it by "next == dquote_end" cond.
4567 if (next == dquote_end || strchr("$`\\\n", next)) {
4568 ch = i_getch(input); /* eat next */
4570 goto again; /* skip \<newline> */
4571 } /* else: ch remains == '\\', and we double it below: */
4572 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4573 nommu_addchr(as_string, ch);
4577 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4578 debug_printf_parse("encode_string return 0: "
4579 "parse_dollar returned 0 (error)\n");
4584 #if ENABLE_HUSH_TICK
4586 //unsigned pos = dest->length;
4587 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4588 o_addchr(dest, 0x80 | '`');
4589 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4590 return 0; /* error */
4591 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4592 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4596 o_addQchr(dest, ch);
4602 * Scan input until EOF or end_trigger char.
4603 * Return a list of pipes to execute, or NULL on EOF
4604 * or if end_trigger character is met.
4605 * On syntax error, exit if shell is not interactive,
4606 * reset parsing machinery and start parsing anew,
4607 * or return ERR_PTR.
4609 static struct pipe *parse_stream(char **pstring,
4610 struct in_str *input,
4613 struct parse_context ctx;
4614 o_string dest = NULL_O_STRING;
4617 /* Single-quote triggers a bypass of the main loop until its mate is
4618 * found. When recursing, quote state is passed in via dest->o_expflags.
4620 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4621 end_trigger ? end_trigger : 'X');
4624 /* If very first arg is "" or '', dest.data may end up NULL.
4625 * Preventing this: */
4626 o_addchr(&dest, '\0');
4629 /* We used to separate words on $IFS here. This was wrong.
4630 * $IFS is used only for word splitting when $var is expanded,
4631 * here we should use blank chars as separators, not $IFS
4634 if (MAYBE_ASSIGNMENT != 0)
4635 dest.o_assignment = MAYBE_ASSIGNMENT;
4636 initialize_context(&ctx);
4639 const char *is_blank;
4640 const char *is_special;
4644 redir_type redir_style;
4646 ch = i_getch(input);
4647 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4648 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4653 syntax_error_unterm_str("here document");
4656 if (end_trigger == ')') {
4657 syntax_error_unterm_ch('(');
4660 if (end_trigger == '}') {
4661 syntax_error_unterm_ch('{');
4665 if (done_word(&dest, &ctx)) {
4669 done_pipe(&ctx, PIPE_SEQ);
4671 /* If we got nothing... */
4672 /* (this makes bare "&" cmd a no-op.
4673 * bash says: "syntax error near unexpected token '&'") */
4674 if (pi->num_cmds == 0
4675 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4681 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4683 *pstring = ctx.as_string.data;
4685 o_free_unsafe(&ctx.as_string);
4688 debug_printf_parse("parse_stream return %p\n", pi);
4691 nommu_addchr(&ctx.as_string, ch);
4695 next = i_peek(input);
4697 is_special = "{}<>;&|()#'" /* special outside of "str" */
4698 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4699 /* Are { and } special here? */
4700 if (ctx.command->argv /* word [word]{... - non-special */
4701 || dest.length /* word{... - non-special */
4702 || dest.has_quoted_part /* ""{... - non-special */
4703 || (next != ';' /* }; - special */
4704 && next != ')' /* }) - special */
4705 && next != '(' /* {( - special */
4706 && next != '&' /* }& and }&& ... - special */
4707 && next != '|' /* }|| ... - special */
4708 && !strchr(defifs, next) /* {word - non-special */
4711 /* They are not special, skip "{}" */
4714 is_special = strchr(is_special, ch);
4715 is_blank = strchr(defifs, ch);
4717 if (!is_special && !is_blank) { /* ordinary char */
4719 o_addQchr(&dest, ch);
4720 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4721 || dest.o_assignment == WORD_IS_KEYWORD)
4723 && is_well_formed_var_name(dest.data, '=')
4725 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4726 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4732 if (done_word(&dest, &ctx)) {
4736 /* Is this a case when newline is simply ignored?
4738 * "cmd | <newline> cmd ..."
4739 * "case ... in <newline> word) ..."
4741 if (IS_NULL_CMD(ctx.command)
4742 && dest.length == 0 && !dest.has_quoted_part
4744 /* This newline can be ignored. But...
4745 * Without check #1, interactive shell
4746 * ignores even bare <newline>,
4747 * and shows the continuation prompt:
4748 * ps1_prompt$ <enter>
4749 * ps2> _ <=== wrong, should be ps1
4750 * Without check #2, "cmd & <newline>"
4751 * is similarly mistreated.
4752 * (BTW, this makes "cmd & cmd"
4753 * and "cmd && cmd" non-orthogonal.
4754 * Really, ask yourself, why
4755 * "cmd && <newline>" doesn't start
4756 * cmd but waits for more input?
4759 struct pipe *pi = ctx.list_head;
4760 if (pi->num_cmds != 0 /* check #1 */
4761 && pi->followup != PIPE_BG /* check #2 */
4766 /* Treat newline as a command separator. */
4767 done_pipe(&ctx, PIPE_SEQ);
4768 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4770 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4775 dest.o_assignment = MAYBE_ASSIGNMENT;
4776 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4778 /* note: if (is_blank) continue;
4779 * will still trigger for us */
4783 /* "cmd}" or "cmd }..." without semicolon or &:
4784 * } is an ordinary char in this case, even inside { cmd; }
4785 * Pathological example: { ""}; } should exec "}" cmd
4788 if (dest.length != 0 /* word} */
4789 || dest.has_quoted_part /* ""} */
4793 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4794 /* Generally, there should be semicolon: "cmd; }"
4795 * However, bash allows to omit it if "cmd" is
4796 * a group. Examples:
4799 * { echo 0 >&2 | { echo 1; } }
4800 * { while false; do :; done }
4801 * { case a in b) ;; esac }
4803 if (ctx.command->group)
4807 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4808 /* Can't be an end of {cmd}, skip the check */
4809 goto skip_end_trigger;
4810 /* else: } does terminate a group */
4813 if (end_trigger && end_trigger == ch
4814 && (ch != ';' || heredoc_cnt == 0)
4815 #if ENABLE_HUSH_CASE
4817 || ctx.ctx_res_w != RES_MATCH
4818 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4823 /* This is technically valid:
4824 * { cat <<HERE; }; echo Ok
4828 * but we don't support this.
4829 * We require heredoc to be in enclosing {}/(),
4832 syntax_error_unterm_str("here document");
4835 if (done_word(&dest, &ctx)) {
4838 done_pipe(&ctx, PIPE_SEQ);
4839 dest.o_assignment = MAYBE_ASSIGNMENT;
4840 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4841 /* Do we sit outside of any if's, loops or case's? */
4843 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4847 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4849 *pstring = ctx.as_string.data;
4851 o_free_unsafe(&ctx.as_string);
4854 debug_printf_parse("parse_stream return %p: "
4855 "end_trigger char found\n",
4857 return ctx.list_head;
4864 /* Catch <, > before deciding whether this word is
4865 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4868 redir_fd = redirect_opt_num(&dest);
4869 if (done_word(&dest, &ctx)) {
4872 redir_style = REDIRECT_OVERWRITE;
4874 redir_style = REDIRECT_APPEND;
4875 ch = i_getch(input);
4876 nommu_addchr(&ctx.as_string, ch);
4879 else if (next == '(') {
4880 syntax_error(">(process) not supported");
4884 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4886 continue; /* back to top of while (1) */
4888 redir_fd = redirect_opt_num(&dest);
4889 if (done_word(&dest, &ctx)) {
4892 redir_style = REDIRECT_INPUT;
4894 redir_style = REDIRECT_HEREDOC;
4896 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4897 ch = i_getch(input);
4898 nommu_addchr(&ctx.as_string, ch);
4899 } else if (next == '>') {
4900 redir_style = REDIRECT_IO;
4901 ch = i_getch(input);
4902 nommu_addchr(&ctx.as_string, ch);
4905 else if (next == '(') {
4906 syntax_error("<(process) not supported");
4910 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4912 continue; /* back to top of while (1) */
4914 if (dest.length == 0 && !dest.has_quoted_part) {
4915 /* skip "#comment" */
4918 if (ch == EOF || ch == '\n')
4921 /* note: we do not add it to &ctx.as_string */
4923 nommu_addchr(&ctx.as_string, '\n');
4924 continue; /* back to top of while (1) */
4929 /* It's "\<newline>" */
4931 /* Remove trailing '\' from ctx.as_string */
4932 ctx.as_string.data[--ctx.as_string.length] = '\0';
4934 ch = i_getch(input); /* eat it */
4935 continue; /* back to top of while (1) */
4940 if (dest.o_assignment == MAYBE_ASSIGNMENT
4941 /* check that we are not in word in "a=1 2>word b=1": */
4942 && !ctx.pending_redirect
4944 /* ch is a special char and thus this word
4945 * cannot be an assignment */
4946 dest.o_assignment = NOT_ASSIGNMENT;
4947 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4950 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4953 case '#': /* non-comment #: "echo a#b" etc */
4954 o_addQchr(&dest, ch);
4958 syntax_error("\\<eof>");
4961 ch = i_getch(input);
4962 /* note: ch != '\n' (that case does not reach this place) */
4963 o_addchr(&dest, '\\');
4964 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4965 o_addchr(&dest, ch);
4966 nommu_addchr(&ctx.as_string, ch);
4967 /* Example: echo Hello \2>file
4968 * we need to know that word 2 is quoted */
4969 dest.has_quoted_part = 1;
4972 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4973 debug_printf_parse("parse_stream parse error: "
4974 "parse_dollar returned 0 (error)\n");
4979 dest.has_quoted_part = 1;
4980 if (next == '\'' && !ctx.pending_redirect) {
4981 insert_empty_quoted_str_marker:
4982 nommu_addchr(&ctx.as_string, next);
4983 i_getch(input); /* eat second ' */
4984 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4985 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4988 ch = i_getch(input);
4990 syntax_error_unterm_ch('\'');
4993 nommu_addchr(&ctx.as_string, ch);
4996 o_addqchr(&dest, ch);
5001 dest.has_quoted_part = 1;
5002 if (next == '"' && !ctx.pending_redirect)
5003 goto insert_empty_quoted_str_marker;
5004 if (dest.o_assignment == NOT_ASSIGNMENT)
5005 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5006 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5008 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5010 #if ENABLE_HUSH_TICK
5012 USE_FOR_NOMMU(unsigned pos;)
5014 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5015 o_addchr(&dest, '`');
5016 USE_FOR_NOMMU(pos = dest.length;)
5017 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5020 o_addstr(&ctx.as_string, dest.data + pos);
5021 o_addchr(&ctx.as_string, '`');
5023 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5024 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5029 #if ENABLE_HUSH_CASE
5032 if (done_word(&dest, &ctx)) {
5035 done_pipe(&ctx, PIPE_SEQ);
5036 #if ENABLE_HUSH_CASE
5037 /* Eat multiple semicolons, detect
5038 * whether it means something special */
5043 ch = i_getch(input);
5044 nommu_addchr(&ctx.as_string, ch);
5045 if (ctx.ctx_res_w == RES_CASE_BODY) {
5046 ctx.ctx_dsemicolon = 1;
5047 ctx.ctx_res_w = RES_MATCH;
5053 /* We just finished a cmd. New one may start
5054 * with an assignment */
5055 dest.o_assignment = MAYBE_ASSIGNMENT;
5056 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5059 if (done_word(&dest, &ctx)) {
5063 ch = i_getch(input);
5064 nommu_addchr(&ctx.as_string, ch);
5065 done_pipe(&ctx, PIPE_AND);
5067 done_pipe(&ctx, PIPE_BG);
5071 if (done_word(&dest, &ctx)) {
5074 #if ENABLE_HUSH_CASE
5075 if (ctx.ctx_res_w == RES_MATCH)
5076 break; /* we are in case's "word | word)" */
5078 if (next == '|') { /* || */
5079 ch = i_getch(input);
5080 nommu_addchr(&ctx.as_string, ch);
5081 done_pipe(&ctx, PIPE_OR);
5083 /* we could pick up a file descriptor choice here
5084 * with redirect_opt_num(), but bash doesn't do it.
5085 * "echo foo 2| cat" yields "foo 2". */
5090 #if ENABLE_HUSH_CASE
5091 /* "case... in [(]word)..." - skip '(' */
5092 if (ctx.ctx_res_w == RES_MATCH
5093 && ctx.command->argv == NULL /* not (word|(... */
5094 && dest.length == 0 /* not word(... */
5095 && dest.has_quoted_part == 0 /* not ""(... */
5101 if (parse_group(&dest, &ctx, input, ch) != 0) {
5106 #if ENABLE_HUSH_CASE
5107 if (ctx.ctx_res_w == RES_MATCH)
5111 /* proper use of this character is caught by end_trigger:
5112 * if we see {, we call parse_group(..., end_trigger='}')
5113 * and it will match } earlier (not here). */
5114 syntax_error_unexpected_ch(ch);
5115 G.last_exitcode = 2;
5119 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5124 G.last_exitcode = 1;
5127 struct parse_context *pctx;
5128 IF_HAS_KEYWORDS(struct parse_context *p2;)
5130 /* Clean up allocated tree.
5131 * Sample for finding leaks on syntax error recovery path.
5132 * Run it from interactive shell, watch pmap `pidof hush`.
5133 * while if false; then false; fi; do break; fi
5134 * Samples to catch leaks at execution:
5135 * while if (true | { true;}); then echo ok; fi; do break; done
5136 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5140 /* Update pipe/command counts,
5141 * otherwise freeing may miss some */
5142 done_pipe(pctx, PIPE_SEQ);
5143 debug_printf_clean("freeing list %p from ctx %p\n",
5144 pctx->list_head, pctx);
5145 debug_print_tree(pctx->list_head, 0);
5146 free_pipe_list(pctx->list_head);
5147 debug_printf_clean("freed list %p\n", pctx->list_head);
5149 o_free_unsafe(&pctx->as_string);
5151 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5155 IF_HAS_KEYWORDS(pctx = p2;)
5156 } while (HAS_KEYWORDS && pctx);
5169 /*** Execution routines ***/
5171 /* Expansion can recurse, need forward decls: */
5172 #if !ENABLE_HUSH_BASH_COMPAT
5173 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5174 #define expand_string_to_string(str, do_unbackslash) \
5175 expand_string_to_string(str)
5177 static char *expand_string_to_string(const char *str, int do_unbackslash);
5178 #if ENABLE_HUSH_TICK
5179 static int process_command_subs(o_string *dest, const char *s);
5182 /* expand_strvec_to_strvec() takes a list of strings, expands
5183 * all variable references within and returns a pointer to
5184 * a list of expanded strings, possibly with larger number
5185 * of strings. (Think VAR="a b"; echo $VAR).
5186 * This new list is allocated as a single malloc block.
5187 * NULL-terminated list of char* pointers is at the beginning of it,
5188 * followed by strings themselves.
5189 * Caller can deallocate entire list by single free(list). */
5191 /* A horde of its helpers come first: */
5193 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5195 while (--len >= 0) {
5198 #if ENABLE_HUSH_BRACE_EXPANSION
5199 if (c == '{' || c == '}') {
5200 /* { -> \{, } -> \} */
5202 /* And now we want to add { or } and continue:
5205 * luckily, just falling throught achieves this.
5211 /* \z -> \\\z; \<eol> -> \\<eol> */
5216 o_addchr(o, *str++);
5222 /* Store given string, finalizing the word and starting new one whenever
5223 * we encounter IFS char(s). This is used for expanding variable values.
5224 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5225 * Return in *ended_with_ifs:
5226 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5228 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5230 int last_is_ifs = 0;
5235 if (!*str) /* EOL - do not finalize word */
5237 word_len = strcspn(str, G.ifs);
5239 /* We have WORD_LEN leading non-IFS chars */
5240 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5241 o_addblock(output, str, word_len);
5243 /* Protect backslashes against globbing up :)
5244 * Example: "v='\*'; echo b$v" prints "b\*"
5245 * (and does not try to glob on "*")
5247 o_addblock_duplicate_backslash(output, str, word_len);
5248 /*/ Why can't we do it easier? */
5249 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5250 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5254 if (!*str) /* EOL - do not finalize word */
5258 /* We know str here points to at least one IFS char */
5260 str += strspn(str, G.ifs); /* skip IFS chars */
5261 if (!*str) /* EOL - do not finalize word */
5264 /* Start new word... but not always! */
5265 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5266 if (output->has_quoted_part
5267 /* Case "v=' a'; echo $v":
5268 * here nothing precedes the space in $v expansion,
5269 * therefore we should not finish the word
5270 * (IOW: if there *is* word to finalize, only then do it):
5272 || (n > 0 && output->data[output->length - 1])
5274 o_addchr(output, '\0');
5275 debug_print_list("expand_on_ifs", output, n);
5276 n = o_save_ptr(output, n);
5281 *ended_with_ifs = last_is_ifs;
5282 debug_print_list("expand_on_ifs[1]", output, n);
5286 /* Helper to expand $((...)) and heredoc body. These act as if
5287 * they are in double quotes, with the exception that they are not :).
5288 * Just the rules are similar: "expand only $var and `cmd`"
5290 * Returns malloced string.
5291 * As an optimization, we return NULL if expansion is not needed.
5293 #if !ENABLE_HUSH_BASH_COMPAT
5294 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5295 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5296 encode_then_expand_string(str)
5298 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5301 struct in_str input;
5302 o_string dest = NULL_O_STRING;
5304 if (!strchr(str, '$')
5305 && !strchr(str, '\\')
5306 #if ENABLE_HUSH_TICK
5307 && !strchr(str, '`')
5313 /* We need to expand. Example:
5314 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5316 setup_string_in_str(&input, str);
5317 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5318 //TODO: error check (encode_string returns 0 on error)?
5319 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5320 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5321 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5322 o_free_unsafe(&dest);
5326 #if ENABLE_FEATURE_SH_MATH
5327 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5329 arith_state_t math_state;
5333 math_state.lookupvar = get_local_var_value;
5334 math_state.setvar = set_local_var_from_halves;
5335 //math_state.endofname = endofname;
5336 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5337 res = arith(&math_state, exp_str ? exp_str : arg);
5340 *errmsg_p = math_state.errmsg;
5341 if (math_state.errmsg)
5342 die_if_script(math_state.errmsg);
5347 #if ENABLE_HUSH_BASH_COMPAT
5348 /* ${var/[/]pattern[/repl]} helpers */
5349 static char *strstr_pattern(char *val, const char *pattern, int *size)
5352 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5353 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5360 /* Optimization: if "*pat" did not match the start of "string",
5361 * we know that "tring", "ring" etc will not match too:
5363 if (pattern[0] == '*')
5368 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5370 char *result = NULL;
5371 unsigned res_len = 0;
5372 unsigned repl_len = strlen(repl);
5376 char *s = strstr_pattern(val, pattern, &size);
5380 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5381 memcpy(result + res_len, val, s - val);
5383 strcpy(result + res_len, repl);
5384 res_len += repl_len;
5385 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5391 if (val[0] && result) {
5392 result = xrealloc(result, res_len + strlen(val) + 1);
5393 strcpy(result + res_len, val);
5394 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5396 debug_printf_varexp("result:'%s'\n", result);
5402 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5404 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5406 const char *val = NULL;
5407 char *to_be_freed = NULL;
5412 char exp_save = exp_save; /* for compiler */
5413 char *exp_saveptr; /* points to expansion operator */
5414 char *exp_word = exp_word; /* for compiler */
5417 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5419 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5421 first_char = arg[0] = arg0 & 0x7f;
5424 if (first_char == '#' /* ${#... */
5425 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5427 /* It must be length operator: ${#var} */
5431 /* Maybe handle parameter expansion */
5432 if (exp_saveptr /* if 2nd char is one of expansion operators */
5433 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5435 /* ${?:0}, ${#[:]%0} etc */
5436 exp_saveptr = var + 1;
5438 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5439 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5441 exp_op = exp_save = *exp_saveptr;
5443 exp_word = exp_saveptr + 1;
5444 if (exp_op == ':') {
5445 exp_op = *exp_word++;
5446 //TODO: try ${var:} and ${var:bogus} in non-bash config
5447 if (ENABLE_HUSH_BASH_COMPAT
5448 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5450 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5455 *exp_saveptr = '\0';
5456 } /* else: it's not an expansion op, but bare ${var} */
5459 /* Look up the variable in question */
5460 if (isdigit(var[0])) {
5461 /* parse_dollar should have vetted var for us */
5462 int n = xatoi_positive(var);
5463 if (n < G.global_argc)
5464 val = G.global_argv[n];
5465 /* else val remains NULL: $N with too big N */
5469 val = utoa(G.root_pid);
5471 case '!': /* bg pid */
5472 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5474 case '?': /* exitcode */
5475 val = utoa(G.last_exitcode);
5477 case '#': /* argc */
5478 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5481 val = get_local_var_value(var);
5485 /* Handle any expansions */
5486 if (exp_op == 'L') {
5487 reinit_unicode_for_hush();
5488 debug_printf_expand("expand: length(%s)=", val);
5489 val = utoa(val ? unicode_strlen(val) : 0);
5490 debug_printf_expand("%s\n", val);
5491 } else if (exp_op) {
5492 if (exp_op == '%' || exp_op == '#') {
5493 /* Standard-mandated substring removal ops:
5494 * ${parameter%word} - remove smallest suffix pattern
5495 * ${parameter%%word} - remove largest suffix pattern
5496 * ${parameter#word} - remove smallest prefix pattern
5497 * ${parameter##word} - remove largest prefix pattern
5499 * Word is expanded to produce a glob pattern.
5500 * Then var's value is matched to it and matching part removed.
5502 if (val && val[0]) {
5506 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5507 if (exp_op == *exp_word) /* ## or %% */
5509 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5511 exp_word = exp_exp_word;
5512 /* HACK ALERT. We depend here on the fact that
5513 * G.global_argv and results of utoa and get_local_var_value
5514 * are actually in writable memory:
5515 * scan_and_match momentarily stores NULs there. */
5517 loc = scan_and_match(t, exp_word, scan_flags);
5518 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5519 // exp_op, t, exp_word, loc);
5521 if (loc) { /* match was found */
5522 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5523 val = loc; /* take right part */
5525 val = to_be_freed = xstrndup(val, loc - val); /* left */
5529 #if ENABLE_HUSH_BASH_COMPAT
5530 else if (exp_op == '/' || exp_op == '\\') {
5531 /* It's ${var/[/]pattern[/repl]} thing.
5532 * Note that in encoded form it has TWO parts:
5533 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5534 * and if // is used, it is encoded as \:
5535 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5537 /* Empty variable always gives nothing: */
5538 // "v=''; echo ${v/*/w}" prints "", not "w"
5539 if (val && val[0]) {
5540 /* pattern uses non-standard expansion.
5541 * repl should be unbackslashed and globbed
5542 * by the usual expansion rules:
5544 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5545 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5546 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5547 * v='a bz'; echo ${v/a*z/\z} prints "z"
5548 * (note that a*z _pattern_ is never globbed!)
5550 char *pattern, *repl, *t;
5551 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5553 pattern = xstrdup(exp_word);
5554 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5555 *p++ = SPECIAL_VAR_SYMBOL;
5557 p = strchr(p, SPECIAL_VAR_SYMBOL);
5559 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5560 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5561 /* HACK ALERT. We depend here on the fact that
5562 * G.global_argv and results of utoa and get_local_var_value
5563 * are actually in writable memory:
5564 * replace_pattern momentarily stores NULs there. */
5566 to_be_freed = replace_pattern(t,
5568 (repl ? repl : exp_word),
5570 if (to_be_freed) /* at least one replace happened */
5577 else if (exp_op == ':') {
5578 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_FEATURE_SH_MATH
5579 /* It's ${var:N[:M]} bashism.
5580 * Note that in encoded form it has TWO parts:
5581 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5586 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5589 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5590 *p++ = SPECIAL_VAR_SYMBOL;
5592 p = strchr(p, SPECIAL_VAR_SYMBOL);
5594 len = expand_and_evaluate_arith(exp_word, &errmsg);
5597 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5598 if (len >= 0) { /* bash compat: len < 0 is illegal */
5599 if (beg < 0) /* bash compat */
5601 debug_printf_varexp("from val:'%s'\n", val);
5602 if (len == 0 || !val || beg >= strlen(val)) {
5606 /* Paranoia. What if user entered 9999999999999
5607 * which fits in arith_t but not int? */
5610 val = to_be_freed = xstrndup(val + beg, len);
5612 debug_printf_varexp("val:'%s'\n", val);
5616 die_if_script("malformed ${%s:...}", var);
5619 } else { /* one of "-=+?" */
5620 /* Standard-mandated substitution ops:
5621 * ${var?word} - indicate error if unset
5622 * If var is unset, word (or a message indicating it is unset
5623 * if word is null) is written to standard error
5624 * and the shell exits with a non-zero exit status.
5625 * Otherwise, the value of var is substituted.
5626 * ${var-word} - use default value
5627 * If var is unset, word is substituted.
5628 * ${var=word} - assign and use default value
5629 * If var is unset, word is assigned to var.
5630 * In all cases, final value of var is substituted.
5631 * ${var+word} - use alternative value
5632 * If var is unset, null is substituted.
5633 * Otherwise, word is substituted.
5635 * Word is subjected to tilde expansion, parameter expansion,
5636 * command substitution, and arithmetic expansion.
5637 * If word is not needed, it is not expanded.
5639 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5640 * but also treat null var as if it is unset.
5642 int use_word = (!val || ((exp_save == ':') && !val[0]));
5644 use_word = !use_word;
5645 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5646 (exp_save == ':') ? "true" : "false", use_word);
5648 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5650 exp_word = to_be_freed;
5651 if (exp_op == '?') {
5652 /* mimic bash message */
5653 die_if_script("%s: %s",
5655 exp_word[0] ? exp_word : "parameter null or not set"
5657 //TODO: how interactive bash aborts expansion mid-command?
5662 if (exp_op == '=') {
5663 /* ${var=[word]} or ${var:=[word]} */
5664 if (isdigit(var[0]) || var[0] == '#') {
5665 /* mimic bash message */
5666 die_if_script("$%s: cannot assign in this way", var);
5669 char *new_var = xasprintf("%s=%s", var, val);
5670 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5674 } /* one of "-=+?" */
5676 *exp_saveptr = exp_save;
5682 *to_be_freed_pp = to_be_freed;
5686 /* Expand all variable references in given string, adding words to list[]
5687 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5688 * to be filled). This routine is extremely tricky: has to deal with
5689 * variables/parameters with whitespace, $* and $@, and constructs like
5690 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5691 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5693 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5694 * expansion of right-hand side of assignment == 1-element expand.
5696 char cant_be_null = 0; /* only bit 0x80 matters */
5697 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5700 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5701 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5702 debug_print_list("expand_vars_to_list", output, n);
5703 n = o_save_ptr(output, n);
5704 debug_print_list("expand_vars_to_list[0]", output, n);
5706 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5708 char *to_be_freed = NULL;
5709 const char *val = NULL;
5710 #if ENABLE_HUSH_TICK
5711 o_string subst_result = NULL_O_STRING;
5713 #if ENABLE_FEATURE_SH_MATH
5714 char arith_buf[sizeof(arith_t)*3 + 2];
5718 o_addchr(output, '\0');
5719 n = o_save_ptr(output, n);
5723 o_addblock(output, arg, p - arg);
5724 debug_print_list("expand_vars_to_list[1]", output, n);
5726 p = strchr(p, SPECIAL_VAR_SYMBOL);
5728 /* Fetch special var name (if it is indeed one of them)
5729 * and quote bit, force the bit on if singleword expansion -
5730 * important for not getting v=$@ expand to many words. */
5731 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5733 /* Is this variable quoted and thus expansion can't be null?
5734 * "$@" is special. Even if quoted, it can still
5735 * expand to nothing (not even an empty string),
5736 * thus it is excluded. */
5737 if ((first_ch & 0x7f) != '@')
5738 cant_be_null |= first_ch;
5740 switch (first_ch & 0x7f) {
5741 /* Highest bit in first_ch indicates that var is double-quoted */
5745 if (!G.global_argv[1])
5748 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5749 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5750 while (G.global_argv[i]) {
5751 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5752 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5753 if (G.global_argv[i++][0] && G.global_argv[i]) {
5754 /* this argv[] is not empty and not last:
5755 * put terminating NUL, start new word */
5756 o_addchr(output, '\0');
5757 debug_print_list("expand_vars_to_list[2]", output, n);
5758 n = o_save_ptr(output, n);
5759 debug_print_list("expand_vars_to_list[3]", output, n);
5763 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5764 * and in this case should treat it like '$*' - see 'else...' below */
5765 if (first_ch == ('@'|0x80) /* quoted $@ */
5766 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5769 o_addQstr(output, G.global_argv[i]);
5770 if (++i >= G.global_argc)
5772 o_addchr(output, '\0');
5773 debug_print_list("expand_vars_to_list[4]", output, n);
5774 n = o_save_ptr(output, n);
5776 } else { /* quoted $* (or v="$@" case): add as one word */
5778 o_addQstr(output, G.global_argv[i]);
5779 if (!G.global_argv[++i])
5782 o_addchr(output, G.ifs[0]);
5784 output->has_quoted_part = 1;
5788 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5789 /* "Empty variable", used to make "" etc to not disappear */
5790 output->has_quoted_part = 1;
5792 cant_be_null = 0x80;
5794 #if ENABLE_HUSH_TICK
5795 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5796 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5798 /* Can't just stuff it into output o_string,
5799 * expanded result may need to be globbed
5800 * and $IFS-splitted */
5801 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5802 G.last_exitcode = process_command_subs(&subst_result, arg);
5803 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5804 val = subst_result.data;
5807 #if ENABLE_FEATURE_SH_MATH
5808 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5811 arg++; /* skip '+' */
5812 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5813 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5814 res = expand_and_evaluate_arith(arg, NULL);
5815 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5816 sprintf(arith_buf, ARITH_FMT, res);
5822 val = expand_one_var(&to_be_freed, arg, &p);
5823 IF_HUSH_TICK(store_val:)
5824 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5825 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5826 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5827 if (val && val[0]) {
5828 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5831 } else { /* quoted $VAR, val will be appended below */
5832 output->has_quoted_part = 1;
5833 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5834 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5837 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5839 if (val && val[0]) {
5840 o_addQstr(output, val);
5844 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5845 * Do the check to avoid writing to a const string. */
5846 if (*p != SPECIAL_VAR_SYMBOL)
5847 *p = SPECIAL_VAR_SYMBOL;
5849 #if ENABLE_HUSH_TICK
5850 o_free(&subst_result);
5853 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5857 o_addchr(output, '\0');
5858 n = o_save_ptr(output, n);
5860 debug_print_list("expand_vars_to_list[a]", output, n);
5861 /* this part is literal, and it was already pre-quoted
5862 * if needed (much earlier), do not use o_addQstr here! */
5863 o_addstr_with_NUL(output, arg);
5864 debug_print_list("expand_vars_to_list[b]", output, n);
5865 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5866 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5869 /* allow to reuse list[n] later without re-growth */
5870 output->has_empty_slot = 1;
5872 o_addchr(output, '\0');
5878 static char **expand_variables(char **argv, unsigned expflags)
5882 o_string output = NULL_O_STRING;
5884 output.o_expflags = expflags;
5888 n = expand_vars_to_list(&output, n, *argv);
5891 debug_print_list("expand_variables", &output, n);
5893 /* output.data (malloced in one block) gets returned in "list" */
5894 list = o_finalize_list(&output, n);
5895 debug_print_strings("expand_variables[1]", list);
5899 static char **expand_strvec_to_strvec(char **argv)
5901 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5904 #if ENABLE_HUSH_BASH_COMPAT
5905 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5907 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5911 /* Used for expansion of right hand of assignments,
5912 * $((...)), heredocs, variable espansion parts.
5914 * NB: should NOT do globbing!
5915 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5917 static char *expand_string_to_string(const char *str, int do_unbackslash)
5919 #if !ENABLE_HUSH_BASH_COMPAT
5920 const int do_unbackslash = 1;
5922 char *argv[2], **list;
5924 debug_printf_expand("string_to_string<='%s'\n", str);
5925 /* This is generally an optimization, but it also
5926 * handles "", which otherwise trips over !list[0] check below.
5927 * (is this ever happens that we actually get str="" here?)
5929 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5930 //TODO: Can use on strings with \ too, just unbackslash() them?
5931 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5932 return xstrdup(str);
5935 argv[0] = (char*)str;
5937 list = expand_variables(argv, do_unbackslash
5938 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5939 : EXP_FLAG_SINGLEWORD
5942 if (!list[0] || list[1])
5943 bb_error_msg_and_die("BUG in varexp2");
5944 /* actually, just move string 2*sizeof(char*) bytes back */
5945 overlapping_strcpy((char*)list, list[0]);
5947 unbackslash((char*)list);
5948 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5952 /* Used for "eval" builtin */
5953 static char* expand_strvec_to_string(char **argv)
5957 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5958 /* Convert all NULs to spaces */
5963 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5964 bb_error_msg_and_die("BUG in varexp3");
5965 /* bash uses ' ' regardless of $IFS contents */
5970 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
5971 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5975 static char **expand_assignments(char **argv, int count)
5980 G.expanded_assignments = p = NULL;
5981 /* Expand assignments into one string each */
5982 for (i = 0; i < count; i++) {
5983 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5985 G.expanded_assignments = NULL;
5990 static void switch_off_special_sigs(unsigned mask)
5993 while ((mask >>= 1) != 0) {
5997 #if ENABLE_HUSH_TRAP
5999 if (G_traps[sig] && !G_traps[sig][0])
6000 /* trap is '', has to remain SIG_IGN */
6003 G_traps[sig] = NULL;
6006 /* We are here only if no trap or trap was not '' */
6007 install_sighandler(sig, SIG_DFL);
6013 void re_execute_shell(char ***to_free, const char *s,
6014 char *g_argv0, char **g_argv,
6015 char **builtin_argv) NORETURN;
6017 static void reset_traps_to_defaults(void)
6019 /* This function is always called in a child shell
6020 * after fork (not vfork, NOMMU doesn't use this function).
6022 IF_HUSH_TRAP(unsigned sig;)
6025 /* Child shells are not interactive.
6026 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6027 * Testcase: (while :; do :; done) + ^Z should background.
6028 * Same goes for SIGTERM, SIGHUP, SIGINT.
6030 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6031 if (!G_traps && !mask)
6032 return; /* already no traps and no special sigs */
6034 /* Switch off special sigs */
6035 switch_off_special_sigs(mask);
6036 # if ENABLE_HUSH_JOB
6037 G_fatal_sig_mask = 0;
6039 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6040 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6041 * remain set in G.special_sig_mask */
6043 # if ENABLE_HUSH_TRAP
6047 /* Reset all sigs to default except ones with empty traps */
6048 for (sig = 0; sig < NSIG; sig++) {
6050 continue; /* no trap: nothing to do */
6051 if (!G_traps[sig][0])
6052 continue; /* empty trap: has to remain SIG_IGN */
6053 /* sig has non-empty trap, reset it: */
6055 G_traps[sig] = NULL;
6056 /* There is no signal for trap 0 (EXIT) */
6059 install_sighandler(sig, pick_sighandler(sig));
6066 static void re_execute_shell(char ***to_free, const char *s,
6067 char *g_argv0, char **g_argv,
6068 char **builtin_argv) NORETURN;
6069 static void re_execute_shell(char ***to_free, const char *s,
6070 char *g_argv0, char **g_argv,
6071 char **builtin_argv)
6073 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6074 /* delims + 2 * (number of bytes in printed hex numbers) */
6075 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6076 char *heredoc_argv[4];
6077 struct variable *cur;
6078 # if ENABLE_HUSH_FUNCTIONS
6079 struct function *funcp;
6083 unsigned long long empty_trap_mask;
6085 if (!g_argv0) { /* heredoc */
6086 argv = heredoc_argv;
6087 argv[0] = (char *) G.argv0_for_re_execing;
6088 argv[1] = (char *) "-<";
6089 argv[2] = (char *) s;
6091 pp = &argv[3]; /* used as pointer to empty environment */
6097 if (pp) while (*pp++)
6100 empty_trap_mask = 0;
6103 for (sig = 1; sig < NSIG; sig++) {
6104 if (G_traps[sig] && !G_traps[sig][0])
6105 empty_trap_mask |= 1LL << sig;
6109 sprintf(param_buf, NOMMU_HACK_FMT
6110 , (unsigned) G.root_pid
6111 , (unsigned) G.root_ppid
6112 , (unsigned) G.last_bg_pid
6113 , (unsigned) G.last_exitcode
6116 IF_HUSH_LOOPS(, G.depth_of_loop)
6118 # undef NOMMU_HACK_FMT
6119 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6120 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6123 for (cur = G.top_var; cur; cur = cur->next) {
6124 if (!cur->flg_export || cur->flg_read_only)
6127 # if ENABLE_HUSH_FUNCTIONS
6128 for (funcp = G.top_func; funcp; funcp = funcp->next)
6134 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6135 *pp++ = (char *) G.argv0_for_re_execing;
6137 for (cur = G.top_var; cur; cur = cur->next) {
6138 if (strcmp(cur->varstr, hush_version_str) == 0)
6140 if (cur->flg_read_only) {
6141 *pp++ = (char *) "-R";
6142 *pp++ = cur->varstr;
6143 } else if (!cur->flg_export) {
6144 *pp++ = (char *) "-V";
6145 *pp++ = cur->varstr;
6148 # if ENABLE_HUSH_FUNCTIONS
6149 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6150 *pp++ = (char *) "-F";
6151 *pp++ = funcp->name;
6152 *pp++ = funcp->body_as_string;
6155 /* We can pass activated traps here. Say, -Tnn:trap_string
6157 * However, POSIX says that subshells reset signals with traps
6159 * I tested bash-3.2 and it not only does that with true subshells
6160 * of the form ( list ), but with any forked children shells.
6161 * I set trap "echo W" WINCH; and then tried:
6163 * { echo 1; sleep 20; echo 2; } &
6164 * while true; do echo 1; sleep 20; echo 2; break; done &
6165 * true | { echo 1; sleep 20; echo 2; } | cat
6167 * In all these cases sending SIGWINCH to the child shell
6168 * did not run the trap. If I add trap "echo V" WINCH;
6169 * _inside_ group (just before echo 1), it works.
6171 * I conclude it means we don't need to pass active traps here.
6173 *pp++ = (char *) "-c";
6176 while (*++builtin_argv)
6177 *pp++ = *builtin_argv;
6178 *pp++ = (char *) "";
6183 /* *pp = NULL; - is already there */
6187 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6188 /* Don't propagate SIG_IGN to the child */
6189 if (SPECIAL_JOBSTOP_SIGS != 0)
6190 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6191 execve(bb_busybox_exec_path, argv, pp);
6192 /* Fallback. Useful for init=/bin/hush usage etc */
6193 if (argv[0][0] == '/')
6194 execve(argv[0], argv, pp);
6195 xfunc_error_retval = 127;
6196 bb_error_msg_and_die("can't re-execute the shell");
6198 #endif /* !BB_MMU */
6201 static int run_and_free_list(struct pipe *pi);
6203 /* Executing from string: eval, sh -c '...'
6204 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6205 * end_trigger controls how often we stop parsing
6206 * NUL: parse all, execute, return
6207 * ';': parse till ';' or newline, execute, repeat till EOF
6209 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6211 /* Why we need empty flag?
6212 * An obscure corner case "false; ``; echo $?":
6213 * empty command in `` should still set $? to 0.
6214 * But we can't just set $? to 0 at the start,
6215 * this breaks "false; echo `echo $?`" case.
6219 struct pipe *pipe_list;
6221 #if ENABLE_HUSH_INTERACTIVE
6222 if (end_trigger == ';')
6223 inp->promptmode = 0; /* PS1 */
6225 pipe_list = parse_stream(NULL, inp, end_trigger);
6226 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6227 /* If we are in "big" script
6228 * (not in `cmd` or something similar)...
6230 if (pipe_list == ERR_PTR && end_trigger == ';') {
6231 /* Discard cached input (rest of line) */
6232 int ch = inp->last_char;
6233 while (ch != EOF && ch != '\n') {
6234 //bb_error_msg("Discarded:'%c'", ch);
6239 /* This stream isn't empty */
6243 if (!pipe_list && empty)
6244 G.last_exitcode = 0;
6247 debug_print_tree(pipe_list, 0);
6248 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6249 run_and_free_list(pipe_list);
6251 if (G_flag_return_in_progress == 1)
6256 static void parse_and_run_string(const char *s)
6258 struct in_str input;
6259 setup_string_in_str(&input, s);
6260 parse_and_run_stream(&input, '\0');
6263 static void parse_and_run_file(FILE *f)
6265 struct in_str input;
6266 setup_file_in_str(&input, f);
6267 parse_and_run_stream(&input, ';');
6270 #if ENABLE_HUSH_TICK
6271 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6276 char **to_free = NULL;
6280 pid = BB_MMU ? xfork() : xvfork();
6281 if (pid == 0) { /* child */
6282 disable_restore_tty_pgrp_on_exit();
6283 /* Process substitution is not considered to be usual
6284 * 'command execution'.
6285 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6292 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6293 close(channel[0]); /* NB: close _first_, then move fd! */
6294 xmove_fd(channel[1], 1);
6295 /* Prevent it from trying to handle ctrl-z etc */
6296 IF_HUSH_JOB(G.run_list_level = 1;)
6297 # if ENABLE_HUSH_TRAP
6298 /* Awful hack for `trap` or $(trap).
6300 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6301 * contains an example where "trap" is executed in a subshell:
6303 * save_traps=$(trap)
6305 * eval "$save_traps"
6307 * Standard does not say that "trap" in subshell shall print
6308 * parent shell's traps. It only says that its output
6309 * must have suitable form, but then, in the above example
6310 * (which is not supposed to be normative), it implies that.
6312 * bash (and probably other shell) does implement it
6313 * (traps are reset to defaults, but "trap" still shows them),
6314 * but as a result, "trap" logic is hopelessly messed up:
6317 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6318 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6319 * # true | trap <--- trap is in subshell - no output (ditto)
6320 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6321 * trap -- 'echo Ho' SIGWINCH
6322 * # echo `(trap)` <--- in subshell in subshell - output
6323 * trap -- 'echo Ho' SIGWINCH
6324 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6325 * trap -- 'echo Ho' SIGWINCH
6327 * The rules when to forget and when to not forget traps
6328 * get really complex and nonsensical.
6330 * Our solution: ONLY bare $(trap) or `trap` is special.
6332 s = skip_whitespace(s);
6333 if (is_prefixed_with(s, "trap")
6334 && skip_whitespace(s + 4)[0] == '\0'
6336 static const char *const argv[] = { NULL, NULL };
6337 builtin_trap((char**)argv);
6338 fflush_all(); /* important */
6343 reset_traps_to_defaults();
6344 parse_and_run_string(s);
6345 _exit(G.last_exitcode);
6347 /* We re-execute after vfork on NOMMU. This makes this script safe:
6348 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6349 * huge=`cat BIG` # was blocking here forever
6352 re_execute_shell(&to_free,
6362 # if ENABLE_HUSH_FAST
6364 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6365 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6366 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6368 enable_restore_tty_pgrp_on_exit();
6373 return remember_FILE(xfdopen_for_read(channel[0]));
6376 /* Return code is exit status of the process that is run. */
6377 static int process_command_subs(o_string *dest, const char *s)
6380 struct in_str pipe_str;
6382 int status, ch, eol_cnt;
6384 fp = generate_stream_from_string(s, &pid);
6386 /* Now send results of command back into original context */
6387 setup_file_in_str(&pipe_str, fp);
6389 while ((ch = i_getch(&pipe_str)) != EOF) {
6395 o_addchr(dest, '\n');
6398 o_addQchr(dest, ch);
6401 debug_printf("done reading from `cmd` pipe, closing it\n");
6402 fclose_and_forget(fp);
6403 /* We need to extract exitcode. Test case
6404 * "true; echo `sleep 1; false` $?"
6406 safe_waitpid(pid, &status, 0);
6407 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6408 return WEXITSTATUS(status);
6410 #endif /* ENABLE_HUSH_TICK */
6413 static void setup_heredoc(struct redir_struct *redir)
6415 struct fd_pair pair;
6418 /* the _body_ of heredoc (misleading field name) */
6419 const char *heredoc = redir->rd_filename;
6426 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6427 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6431 len = strlen(heredoc);
6433 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6435 xmove_fd(pair.rd, redir->rd_fd);
6437 /* Try writing without forking. Newer kernels have
6438 * dynamically growing pipes. Must use non-blocking write! */
6441 written = write(pair.wr, heredoc, len);
6452 ndelay_off(pair.wr);
6454 /* Okay, pipe buffer was not big enough */
6455 /* Note: we must not create a stray child (bastard? :)
6456 * for the unsuspecting parent process. Child creates a grandchild
6457 * and exits before parent execs the process which consumes heredoc
6458 * (that exec happens after we return from this function) */
6465 disable_restore_tty_pgrp_on_exit();
6466 pid = BB_MMU ? xfork() : xvfork();
6470 close(redir->rd_fd); /* read side of the pipe */
6472 full_write(pair.wr, heredoc, len); /* may loop or block */
6475 /* Delegate blocking writes to another process */
6476 xmove_fd(pair.wr, STDOUT_FILENO);
6477 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6481 #if ENABLE_HUSH_FAST
6483 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6485 enable_restore_tty_pgrp_on_exit();
6491 wait(NULL); /* wait till child has died */
6494 /* fd: redirect wants this fd to be used (e.g. 3>file).
6495 * Move all conflicting internally used fds,
6496 * and remember them so that we can restore them later.
6498 static int save_fds_on_redirect(int fd, int squirrel[3])
6501 /* Handle redirects of fds 0,1,2 */
6503 /* If we collide with an already moved stdio fd... */
6504 if (fd == squirrel[0]) {
6505 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6508 if (fd == squirrel[1]) {
6509 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6512 if (fd == squirrel[2]) {
6513 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6516 /* If we are about to redirect stdio fd, and did not yet move it... */
6517 if (fd <= 2 && squirrel[fd] < 0) {
6518 /* We avoid taking stdio fds */
6519 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6520 if (squirrel[fd] < 0 && errno != EBADF)
6522 return 0; /* "we did not close fd" */
6526 #if ENABLE_HUSH_INTERACTIVE
6527 if (fd != 0 && fd == G.interactive_fd) {
6528 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6533 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6534 * (1) Redirect in a forked child. No need to save FILEs' fds,
6535 * we aren't going to use them anymore, ok to trash.
6536 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6537 * but how are we doing to use them?
6538 * "fileno(fd) = new_fd" can't be done.
6543 return save_FILEs_on_redirect(fd);
6546 static void restore_redirects(int squirrel[3])
6549 for (i = 0; i <= 2; i++) {
6552 /* We simply die on error */
6557 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6559 restore_redirected_FILEs();
6562 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6563 * and stderr if they are redirected. */
6564 static int setup_redirects(struct command *prog, int squirrel[])
6567 struct redir_struct *redir;
6569 for (redir = prog->redirects; redir; redir = redir->next) {
6570 if (redir->rd_type == REDIRECT_HEREDOC2) {
6571 /* "rd_fd<<HERE" case */
6572 save_fds_on_redirect(redir->rd_fd, squirrel);
6573 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6575 debug_printf_parse("set heredoc '%s'\n",
6576 redir->rd_filename);
6577 setup_heredoc(redir);
6581 if (redir->rd_dup == REDIRFD_TO_FILE) {
6582 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6584 if (redir->rd_filename == NULL) {
6587 * "cmd >" (no filename)
6588 * "cmd > <file" (2nd redirect starts too early)
6590 die_if_script("syntax error: %s", "invalid redirect");
6593 mode = redir_table[redir->rd_type].mode;
6594 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6595 openfd = open_or_warn(p, mode);
6598 /* Error message from open_or_warn can be lost
6599 * if stderr has been redirected, but bash
6600 * and ash both lose it as well
6601 * (though zsh doesn't!)
6606 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6607 openfd = redir->rd_dup;
6610 if (openfd != redir->rd_fd) {
6611 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6612 if (openfd == REDIRFD_CLOSE) {
6613 /* "rd_fd >&-" means "close me" */
6615 /* ^^^ optimization: saving may already
6616 * have closed it. If not... */
6617 close(redir->rd_fd);
6620 xdup2(openfd, redir->rd_fd);
6621 if (redir->rd_dup == REDIRFD_TO_FILE)
6622 /* "rd_fd > FILE" */
6624 /* else: "rd_fd > rd_dup" */
6631 static char *find_in_path(const char *arg)
6634 const char *PATH = get_local_var_value("PATH");
6640 const char *end = strchrnul(PATH, ':');
6641 int sz = end - PATH; /* must be int! */
6645 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6647 /* We have xxx::yyyy in $PATH,
6648 * it means "use current dir" */
6651 if (access(ret, F_OK) == 0)
6664 static const struct built_in_command *find_builtin_helper(const char *name,
6665 const struct built_in_command *x,
6666 const struct built_in_command *end)
6669 if (strcmp(name, x->b_cmd) != 0) {
6673 debug_printf_exec("found builtin '%s'\n", name);
6678 static const struct built_in_command *find_builtin1(const char *name)
6680 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6682 static const struct built_in_command *find_builtin(const char *name)
6684 const struct built_in_command *x = find_builtin1(name);
6687 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6690 #if ENABLE_HUSH_FUNCTIONS
6691 static struct function **find_function_slot(const char *name)
6693 struct function **funcpp = &G.top_func;
6695 if (strcmp(name, (*funcpp)->name) == 0) {
6698 funcpp = &(*funcpp)->next;
6703 static const struct function *find_function(const char *name)
6705 const struct function *funcp = *find_function_slot(name);
6707 debug_printf_exec("found function '%s'\n", name);
6711 /* Note: takes ownership on name ptr */
6712 static struct function *new_function(char *name)
6714 struct function **funcpp = find_function_slot(name);
6715 struct function *funcp = *funcpp;
6717 if (funcp != NULL) {
6718 struct command *cmd = funcp->parent_cmd;
6719 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6721 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6723 /* Note: if !funcp->body, do not free body_as_string!
6724 * This is a special case of "-F name body" function:
6725 * body_as_string was not malloced! */
6727 free_pipe_list(funcp->body);
6729 free(funcp->body_as_string);
6733 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6734 cmd->argv[0] = funcp->name;
6735 cmd->group = funcp->body;
6737 cmd->group_as_string = funcp->body_as_string;
6741 debug_printf_exec("remembering new function '%s'\n", name);
6742 funcp = *funcpp = xzalloc(sizeof(*funcp));
6743 /*funcp->next = NULL;*/
6750 # if ENABLE_HUSH_UNSET
6751 static void unset_func(const char *name)
6753 struct function **funcpp = find_function_slot(name);
6754 struct function *funcp = *funcpp;
6756 if (funcp != NULL) {
6757 debug_printf_exec("freeing function '%s'\n", funcp->name);
6758 *funcpp = funcp->next;
6759 /* funcp is unlinked now, deleting it.
6760 * Note: if !funcp->body, the function was created by
6761 * "-F name body", do not free ->body_as_string
6762 * and ->name as they were not malloced. */
6764 free_pipe_list(funcp->body);
6767 free(funcp->body_as_string);
6776 #define exec_function(to_free, funcp, argv) \
6777 exec_function(funcp, argv)
6779 static void exec_function(char ***to_free,
6780 const struct function *funcp,
6781 char **argv) NORETURN;
6782 static void exec_function(char ***to_free,
6783 const struct function *funcp,
6789 argv[0] = G.global_argv[0];
6790 G.global_argv = argv;
6794 /* On MMU, funcp->body is always non-NULL */
6795 n = run_list(funcp->body);
6799 re_execute_shell(to_free,
6800 funcp->body_as_string,
6807 static int run_function(const struct function *funcp, char **argv)
6813 save_and_replace_G_args(&sv, argv);
6815 /* "we are in function, ok to use return" */
6816 sv_flg = G_flag_return_in_progress;
6817 G_flag_return_in_progress = -1;
6818 # if ENABLE_HUSH_LOCAL
6819 G.func_nest_level++;
6822 /* On MMU, funcp->body is always non-NULL */
6825 /* Function defined by -F */
6826 parse_and_run_string(funcp->body_as_string);
6827 rc = G.last_exitcode;
6831 rc = run_list(funcp->body);
6834 # if ENABLE_HUSH_LOCAL
6836 struct variable *var;
6837 struct variable **var_pp;
6839 var_pp = &G.top_var;
6840 while ((var = *var_pp) != NULL) {
6841 if (var->func_nest_level < G.func_nest_level) {
6842 var_pp = &var->next;
6846 if (var->flg_export)
6847 bb_unsetenv(var->varstr);
6848 /* Remove from global list */
6849 *var_pp = var->next;
6855 G.func_nest_level--;
6858 G_flag_return_in_progress = sv_flg;
6860 restore_G_args(&sv, argv);
6864 #endif /* ENABLE_HUSH_FUNCTIONS */
6868 #define exec_builtin(to_free, x, argv) \
6869 exec_builtin(x, argv)
6871 #define exec_builtin(to_free, x, argv) \
6872 exec_builtin(to_free, argv)
6874 static void exec_builtin(char ***to_free,
6875 const struct built_in_command *x,
6876 char **argv) NORETURN;
6877 static void exec_builtin(char ***to_free,
6878 const struct built_in_command *x,
6884 rcode = x->b_function(argv);
6889 /* On NOMMU, we must never block!
6890 * Example: { sleep 99 | read line; } & echo Ok
6892 re_execute_shell(to_free,
6901 static void execvp_or_die(char **argv) NORETURN;
6902 static void execvp_or_die(char **argv)
6905 debug_printf_exec("execing '%s'\n", argv[0]);
6906 /* Don't propagate SIG_IGN to the child */
6907 if (SPECIAL_JOBSTOP_SIGS != 0)
6908 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6909 execvp(argv[0], argv);
6911 if (errno == EACCES) e = 126;
6912 if (errno == ENOENT) e = 127;
6913 bb_perror_msg("can't execute '%s'", argv[0]);
6917 #if ENABLE_HUSH_MODE_X
6918 static void dump_cmd_in_x_mode(char **argv)
6920 if (G_x_mode && argv) {
6921 /* We want to output the line in one write op */
6929 len += strlen(argv[n++]) + 1;
6935 p += sprintf(p, " %s", argv[n++]);
6943 # define dump_cmd_in_x_mode(argv) ((void)0)
6947 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6948 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6949 #define pseudo_exec(nommu_save, command, argv_expanded) \
6950 pseudo_exec(command, argv_expanded)
6953 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6955 * Don't exit() here. If you don't exec, use _exit instead.
6956 * The at_exit handlers apparently confuse the calling process,
6957 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6959 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6960 char **argv, int assignment_cnt,
6961 char **argv_expanded) NORETURN;
6962 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6963 char **argv, int assignment_cnt,
6964 char **argv_expanded)
6968 new_env = expand_assignments(argv, assignment_cnt);
6969 dump_cmd_in_x_mode(new_env);
6971 if (!argv[assignment_cnt]) {
6972 /* Case when we are here: ... | var=val | ...
6973 * (note that we do not exit early, i.e., do not optimize out
6974 * expand_assignments(): think about ... | var=`sleep 1` | ...
6976 free_strings(new_env);
6977 _exit(EXIT_SUCCESS);
6981 set_vars_and_save_old(new_env);
6982 free(new_env); /* optional */
6983 /* we can also destroy set_vars_and_save_old's return value,
6986 nommu_save->new_env = new_env;
6987 nommu_save->old_vars = set_vars_and_save_old(new_env);
6990 if (argv_expanded) {
6991 argv = argv_expanded;
6993 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6995 nommu_save->argv = argv;
6998 dump_cmd_in_x_mode(argv);
7000 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7001 if (strchr(argv[0], '/') != NULL)
7005 /* Check if the command matches any of the builtins.
7006 * Depending on context, this might be redundant. But it's
7007 * easier to waste a few CPU cycles than it is to figure out
7008 * if this is one of those cases.
7011 /* On NOMMU, it is more expensive to re-execute shell
7012 * just in order to run echo or test builtin.
7013 * It's better to skip it here and run corresponding
7014 * non-builtin later. */
7015 const struct built_in_command *x;
7016 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7018 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7021 #if ENABLE_HUSH_FUNCTIONS
7022 /* Check if the command matches any functions */
7024 const struct function *funcp = find_function(argv[0]);
7026 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7031 #if ENABLE_FEATURE_SH_STANDALONE
7032 /* Check if the command matches any busybox applets */
7034 int a = find_applet_by_name(argv[0]);
7036 # if BB_MMU /* see above why on NOMMU it is not allowed */
7037 if (APPLET_IS_NOEXEC(a)) {
7038 /* Do not leak open fds from opened script files etc */
7039 close_all_FILE_list();
7040 debug_printf_exec("running applet '%s'\n", argv[0]);
7041 run_applet_no_and_exit(a, argv);
7044 /* Re-exec ourselves */
7045 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7046 /* Don't propagate SIG_IGN to the child */
7047 if (SPECIAL_JOBSTOP_SIGS != 0)
7048 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7049 execv(bb_busybox_exec_path, argv);
7050 /* If they called chroot or otherwise made the binary no longer
7051 * executable, fall through */
7056 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7059 execvp_or_die(argv);
7062 /* Called after [v]fork() in run_pipe
7064 static void pseudo_exec(nommu_save_t *nommu_save,
7065 struct command *command,
7066 char **argv_expanded) NORETURN;
7067 static void pseudo_exec(nommu_save_t *nommu_save,
7068 struct command *command,
7069 char **argv_expanded)
7071 if (command->argv) {
7072 pseudo_exec_argv(nommu_save, command->argv,
7073 command->assignment_cnt, argv_expanded);
7076 if (command->group) {
7077 /* Cases when we are here:
7080 * ... | ( list ) | ...
7081 * ... | { list } | ...
7085 debug_printf_exec("pseudo_exec: run_list\n");
7086 reset_traps_to_defaults();
7087 rcode = run_list(command->group);
7088 /* OK to leak memory by not calling free_pipe_list,
7089 * since this process is about to exit */
7092 re_execute_shell(&nommu_save->argv_from_re_execing,
7093 command->group_as_string,
7100 /* Case when we are here: ... | >file */
7101 debug_printf_exec("pseudo_exec'ed null command\n");
7102 _exit(EXIT_SUCCESS);
7106 static const char *get_cmdtext(struct pipe *pi)
7112 /* This is subtle. ->cmdtext is created only on first backgrounding.
7113 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7114 * On subsequent bg argv is trashed, but we won't use it */
7118 argv = pi->cmds[0].argv;
7120 pi->cmdtext = xzalloc(1);
7125 len += strlen(*argv) + 1;
7129 argv = pi->cmds[0].argv;
7131 p = stpcpy(p, *argv);
7138 static void insert_bg_job(struct pipe *pi)
7140 struct pipe *job, **jobp;
7143 /* Linear search for the ID of the job to use */
7145 for (job = G.job_list; job; job = job->next)
7146 if (job->jobid >= pi->jobid)
7147 pi->jobid = job->jobid + 1;
7149 /* Add job to the list of running jobs */
7151 while ((job = *jobp) != NULL)
7153 job = *jobp = xmalloc(sizeof(*job));
7155 *job = *pi; /* physical copy */
7157 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7158 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7159 for (i = 0; i < pi->num_cmds; i++) {
7160 job->cmds[i].pid = pi->cmds[i].pid;
7161 /* all other fields are not used and stay zero */
7163 job->cmdtext = xstrdup(get_cmdtext(pi));
7165 if (G_interactive_fd)
7166 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7167 G.last_jobid = job->jobid;
7170 static void remove_bg_job(struct pipe *pi)
7172 struct pipe *prev_pipe;
7174 if (pi == G.job_list) {
7175 G.job_list = pi->next;
7177 prev_pipe = G.job_list;
7178 while (prev_pipe->next != pi)
7179 prev_pipe = prev_pipe->next;
7180 prev_pipe->next = pi->next;
7183 G.last_jobid = G.job_list->jobid;
7188 /* Remove a backgrounded job */
7189 static void delete_finished_bg_job(struct pipe *pi)
7196 static int job_exited_or_stopped(struct pipe *pi)
7200 if (pi->alive_cmds != pi->stopped_cmds)
7203 /* All processes in fg pipe have exited or stopped */
7207 rcode = pi->cmds[i].cmd_exitcode;
7208 /* usually last process gives overall exitstatus,
7209 * but with "set -o pipefail", last *failed* process does */
7210 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7213 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7217 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7224 dead = WIFEXITED(status) || WIFSIGNALED(status);
7227 if (WIFSTOPPED(status))
7228 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7229 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7230 if (WIFSIGNALED(status))
7231 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7232 childpid, WTERMSIG(status), WEXITSTATUS(status));
7233 if (WIFEXITED(status))
7234 debug_printf_jobs("pid %d exited, exitcode %d\n",
7235 childpid, WEXITSTATUS(status));
7237 /* Were we asked to wait for a fg pipe? */
7239 i = fg_pipe->num_cmds;
7244 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7245 if (fg_pipe->cmds[i].pid != childpid)
7249 fg_pipe->cmds[i].pid = 0;
7250 fg_pipe->alive_cmds--;
7251 ex = WEXITSTATUS(status);
7252 /* bash prints killer signal's name for *last*
7253 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7254 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7256 if (WIFSIGNALED(status)) {
7257 int sig = WTERMSIG(status);
7258 if (i == fg_pipe->num_cmds-1)
7259 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7260 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7261 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7262 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7263 * Maybe we need to use sig | 128? */
7266 fg_pipe->cmds[i].cmd_exitcode = ex;
7268 fg_pipe->stopped_cmds++;
7270 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7271 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7272 rcode = job_exited_or_stopped(fg_pipe);
7274 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7275 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7276 * and "killall -STOP cat" */
7277 if (G_interactive_fd) {
7279 if (fg_pipe->alive_cmds != 0)
7280 insert_bg_job(fg_pipe);
7284 if (fg_pipe->alive_cmds == 0)
7287 /* There are still running processes in the fg_pipe */
7290 /* It wasnt in fg_pipe, look for process in bg pipes */
7294 /* We were asked to wait for bg or orphaned children */
7295 /* No need to remember exitcode in this case */
7296 for (pi = G.job_list; pi; pi = pi->next) {
7297 for (i = 0; i < pi->num_cmds; i++) {
7298 if (pi->cmds[i].pid == childpid)
7299 goto found_pi_and_prognum;
7302 /* Happens when shell is used as init process (init=/bin/sh) */
7303 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7304 return -1; /* this wasn't a process from fg_pipe */
7306 found_pi_and_prognum:
7309 pi->cmds[i].pid = 0;
7310 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7311 if (WIFSIGNALED(status))
7312 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7314 if (!pi->alive_cmds) {
7315 if (G_interactive_fd)
7316 printf(JOB_STATUS_FORMAT, pi->jobid,
7317 "Done", pi->cmdtext);
7318 delete_finished_bg_job(pi);
7325 return -1; /* this wasn't a process from fg_pipe */
7328 /* Check to see if any processes have exited -- if they have,
7329 * figure out why and see if a job has completed.
7331 * If non-NULL fg_pipe: wait for its completion or stop.
7332 * Return its exitcode or zero if stopped.
7334 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7335 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7336 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7337 * or 0 if no children changed status.
7339 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7340 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7341 * or 0 if no children changed status.
7343 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7349 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7351 attributes = WUNTRACED;
7352 if (fg_pipe == NULL)
7353 attributes |= WNOHANG;
7356 #if ENABLE_HUSH_FAST
7357 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7358 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7359 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7360 /* There was neither fork nor SIGCHLD since last waitpid */
7361 /* Avoid doing waitpid syscall if possible */
7362 if (!G.we_have_children) {
7366 if (fg_pipe == NULL) { /* is WNOHANG set? */
7367 /* We have children, but they did not exit
7368 * or stop yet (we saw no SIGCHLD) */
7371 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7375 /* Do we do this right?
7376 * bash-3.00# sleep 20 | false
7378 * [3]+ Stopped sleep 20 | false
7379 * bash-3.00# echo $?
7380 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7381 * [hush 1.14.0: yes we do it right]
7385 #if ENABLE_HUSH_FAST
7387 i = G.count_SIGCHLD;
7389 childpid = waitpid(-1, &status, attributes);
7390 if (childpid <= 0) {
7391 if (childpid && errno != ECHILD)
7392 bb_perror_msg("waitpid");
7393 #if ENABLE_HUSH_FAST
7394 else { /* Until next SIGCHLD, waitpid's are useless */
7395 G.we_have_children = (childpid == 0);
7396 G.handled_SIGCHLD = i;
7397 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7400 /* ECHILD (no children), or 0 (no change in children status) */
7404 rcode = process_wait_result(fg_pipe, childpid, status);
7406 /* fg_pipe exited or stopped */
7409 if (childpid == waitfor_pid) {
7410 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7411 rcode = WEXITSTATUS(status);
7412 if (WIFSIGNALED(status))
7413 rcode = 128 + WTERMSIG(status);
7414 if (WIFSTOPPED(status))
7415 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7416 rcode = 128 + WSTOPSIG(status);
7418 break; /* "wait PID" called us, give it exitcode+1 */
7420 /* This wasn't one of our processes, or */
7421 /* fg_pipe still has running processes, do waitpid again */
7422 } /* while (waitpid succeeds)... */
7428 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7431 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7432 if (G_saved_tty_pgrp) {
7433 /* Job finished, move the shell to the foreground */
7434 p = getpgrp(); /* our process group id */
7435 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7436 tcsetpgrp(G_interactive_fd, p);
7442 /* Start all the jobs, but don't wait for anything to finish.
7445 * Return code is normally -1, when the caller has to wait for children
7446 * to finish to determine the exit status of the pipe. If the pipe
7447 * is a simple builtin command, however, the action is done by the
7448 * time run_pipe returns, and the exit code is provided as the
7451 * Returns -1 only if started some children. IOW: we have to
7452 * mask out retvals of builtins etc with 0xff!
7454 * The only case when we do not need to [v]fork is when the pipe
7455 * is single, non-backgrounded, non-subshell command. Examples:
7456 * cmd ; ... { list } ; ...
7457 * cmd && ... { list } && ...
7458 * cmd || ... { list } || ...
7459 * If it is, then we can run cmd as a builtin, NOFORK,
7460 * or (if SH_STANDALONE) an applet, and we can run the { list }
7461 * with run_list. If it isn't one of these, we fork and exec cmd.
7463 * Cases when we must fork:
7464 * non-single: cmd | cmd
7465 * backgrounded: cmd & { list } &
7466 * subshell: ( list ) [&]
7468 #if !ENABLE_HUSH_MODE_X
7469 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7470 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7472 static int redirect_and_varexp_helper(char ***new_env_p,
7473 struct variable **old_vars_p,
7474 struct command *command,
7476 char **argv_expanded)
7478 /* setup_redirects acts on file descriptors, not FILEs.
7479 * This is perfect for work that comes after exec().
7480 * Is it really safe for inline use? Experimentally,
7481 * things seem to work. */
7482 int rcode = setup_redirects(command, squirrel);
7484 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7485 *new_env_p = new_env;
7486 dump_cmd_in_x_mode(new_env);
7487 dump_cmd_in_x_mode(argv_expanded);
7489 *old_vars_p = set_vars_and_save_old(new_env);
7493 static NOINLINE int run_pipe(struct pipe *pi)
7495 static const char *const null_ptr = NULL;
7499 struct command *command;
7500 char **argv_expanded;
7502 /* it is not always needed, but we aim to smaller code */
7503 int squirrel[] = { -1, -1, -1 };
7506 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7509 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7510 * Result should be 3 lines: q w e, qwe, q w e
7512 G.ifs = get_local_var_value("IFS");
7516 IF_HUSH_JOB(pi->pgrp = -1;)
7517 pi->stopped_cmds = 0;
7518 command = &pi->cmds[0];
7519 argv_expanded = NULL;
7521 if (pi->num_cmds != 1
7522 || pi->followup == PIPE_BG
7523 || command->cmd_type == CMD_SUBSHELL
7530 debug_printf_exec(": group:%p argv:'%s'\n",
7531 command->group, command->argv ? command->argv[0] : "NONE");
7533 if (command->group) {
7534 #if ENABLE_HUSH_FUNCTIONS
7535 if (command->cmd_type == CMD_FUNCDEF) {
7536 /* "executing" func () { list } */
7537 struct function *funcp;
7539 funcp = new_function(command->argv[0]);
7540 /* funcp->name is already set to argv[0] */
7541 funcp->body = command->group;
7543 funcp->body_as_string = command->group_as_string;
7544 command->group_as_string = NULL;
7546 command->group = NULL;
7547 command->argv[0] = NULL;
7548 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7549 funcp->parent_cmd = command;
7550 command->child_func = funcp;
7552 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7554 return EXIT_SUCCESS;
7558 debug_printf("non-subshell group\n");
7559 rcode = 1; /* exitcode if redir failed */
7560 if (setup_redirects(command, squirrel) == 0) {
7561 debug_printf_exec(": run_list\n");
7562 rcode = run_list(command->group) & 0xff;
7564 restore_redirects(squirrel);
7565 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7567 debug_printf_exec("run_pipe: return %d\n", rcode);
7571 argv = command->argv ? command->argv : (char **) &null_ptr;
7573 const struct built_in_command *x;
7574 #if ENABLE_HUSH_FUNCTIONS
7575 const struct function *funcp;
7579 char **new_env = NULL;
7580 struct variable *old_vars = NULL;
7582 if (argv[command->assignment_cnt] == NULL) {
7583 /* Assignments, but no command */
7584 /* Ensure redirects take effect (that is, create files).
7585 * Try "a=t >file" */
7586 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7587 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7588 /* Set shell variables */
7592 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7593 /* Do we need to flag set_local_var() errors?
7594 * "assignment to readonly var" and "putenv error"
7599 /* Redirect error sets $? to 1. Otherwise,
7600 * if evaluating assignment value set $?, retain it.
7601 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7603 rcode = G.last_exitcode;
7604 /* Exit, _skipping_ variable restoring code: */
7605 goto clean_up_and_ret0;
7607 #else /* Older, bigger, but more correct code */
7609 rcode = setup_redirects(command, squirrel);
7610 restore_redirects(squirrel);
7611 /* Set shell variables */
7613 bb_putchar_stderr('+');
7615 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7617 fprintf(stderr, " %s", p);
7618 debug_printf_exec("set shell var:'%s'->'%s'\n",
7620 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7621 /* Do we need to flag set_local_var() errors?
7622 * "assignment to readonly var" and "putenv error"
7627 bb_putchar_stderr('\n');
7628 /* Redirect error sets $? to 1. Otherwise,
7629 * if evaluating assignment value set $?, retain it.
7630 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7632 rcode = G.last_exitcode;
7633 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7635 debug_printf_exec("run_pipe: return %d\n", rcode);
7640 /* Expand the rest into (possibly) many strings each */
7641 #if ENABLE_HUSH_BASH_COMPAT
7642 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7643 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7647 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7650 /* if someone gives us an empty string: `cmd with empty output` */
7651 if (!argv_expanded[0]) {
7652 free(argv_expanded);
7654 return G.last_exitcode;
7657 x = find_builtin(argv_expanded[0]);
7658 #if ENABLE_HUSH_FUNCTIONS
7661 funcp = find_function(argv_expanded[0]);
7665 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7666 debug_printf("exec with redirects only\n");
7667 rcode = setup_redirects(command, NULL);
7668 /* rcode=1 can be if redir file can't be opened */
7669 goto clean_up_and_ret1;
7672 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7675 debug_printf_exec(": builtin '%s' '%s'...\n",
7676 x->b_cmd, argv_expanded[1]);
7678 rcode = x->b_function(argv_expanded) & 0xff;
7681 #if ENABLE_HUSH_FUNCTIONS
7683 # if ENABLE_HUSH_LOCAL
7684 struct variable **sv;
7685 sv = G.shadowed_vars_pp;
7686 G.shadowed_vars_pp = &old_vars;
7688 debug_printf_exec(": function '%s' '%s'...\n",
7689 funcp->name, argv_expanded[1]);
7690 rcode = run_function(funcp, argv_expanded) & 0xff;
7691 # if ENABLE_HUSH_LOCAL
7692 G.shadowed_vars_pp = sv;
7698 unset_vars(new_env);
7700 /* clean_up_and_ret0: */
7701 restore_redirects(squirrel);
7703 free(argv_expanded);
7704 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7706 debug_printf_exec("run_pipe return %d\n", rcode);
7710 if (ENABLE_FEATURE_SH_NOFORK) {
7711 int n = find_applet_by_name(argv_expanded[0]);
7712 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7713 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7715 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7716 argv_expanded[0], argv_expanded[1]);
7717 rcode = run_nofork_applet(n, argv_expanded);
7719 goto clean_up_and_ret;
7722 /* It is neither builtin nor applet. We must fork. */
7726 /* NB: argv_expanded may already be created, and that
7727 * might include `cmd` runs! Do not rerun it! We *must*
7728 * use argv_expanded if it's non-NULL */
7730 /* Going to fork a child per each pipe member */
7735 while (cmd_no < pi->num_cmds) {
7736 struct fd_pair pipefds;
7738 volatile nommu_save_t nommu_save;
7739 nommu_save.new_env = NULL;
7740 nommu_save.old_vars = NULL;
7741 nommu_save.argv = NULL;
7742 nommu_save.argv_from_re_execing = NULL;
7744 command = &pi->cmds[cmd_no];
7746 if (command->argv) {
7747 debug_printf_exec(": pipe member '%s' '%s'...\n",
7748 command->argv[0], command->argv[1]);
7750 debug_printf_exec(": pipe member with no argv\n");
7753 /* pipes are inserted between pairs of commands */
7756 if (cmd_no < pi->num_cmds)
7757 xpiped_pair(pipefds);
7759 command->pid = BB_MMU ? fork() : vfork();
7760 if (!command->pid) { /* child */
7762 disable_restore_tty_pgrp_on_exit();
7763 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7765 /* Every child adds itself to new process group
7766 * with pgid == pid_of_first_child_in_pipe */
7767 if (G.run_list_level == 1 && G_interactive_fd) {
7770 if (pgrp < 0) /* true for 1st process only */
7772 if (setpgid(0, pgrp) == 0
7773 && pi->followup != PIPE_BG
7774 && G_saved_tty_pgrp /* we have ctty */
7776 /* We do it in *every* child, not just first,
7778 tcsetpgrp(G_interactive_fd, pgrp);
7782 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7783 /* 1st cmd in backgrounded pipe
7784 * should have its stdin /dev/null'ed */
7786 if (open(bb_dev_null, O_RDONLY))
7787 xopen("/", O_RDONLY);
7789 xmove_fd(next_infd, 0);
7791 xmove_fd(pipefds.wr, 1);
7794 /* Like bash, explicit redirects override pipes,
7795 * and the pipe fd (fd#1) is available for dup'ing:
7796 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7797 * of cmd1 goes into pipe.
7799 if (setup_redirects(command, NULL)) {
7800 /* Happens when redir file can't be opened:
7801 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7803 * hush: can't open '/qwe/rty': No such file or directory
7805 * (echo BAR is not executed, it hits _exit(1) below)
7810 /* Stores to nommu_save list of env vars putenv'ed
7811 * (NOMMU, on MMU we don't need that) */
7812 /* cast away volatility... */
7813 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7814 /* pseudo_exec() does not return */
7817 /* parent or error */
7818 #if ENABLE_HUSH_FAST
7820 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7822 enable_restore_tty_pgrp_on_exit();
7824 /* Clean up after vforked child */
7825 free(nommu_save.argv);
7826 free(nommu_save.argv_from_re_execing);
7827 unset_vars(nommu_save.new_env);
7828 add_vars(nommu_save.old_vars);
7830 free(argv_expanded);
7831 argv_expanded = NULL;
7832 if (command->pid < 0) { /* [v]fork failed */
7833 /* Clearly indicate, was it fork or vfork */
7834 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7838 /* Second and next children need to know pid of first one */
7840 pi->pgrp = command->pid;
7846 if (cmd_no < pi->num_cmds)
7848 /* Pass read (output) pipe end to next iteration */
7849 next_infd = pipefds.rd;
7852 if (!pi->alive_cmds) {
7854 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7859 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7863 /* NB: called by pseudo_exec, and therefore must not modify any
7864 * global data until exec/_exit (we can be a child after vfork!) */
7865 static int run_list(struct pipe *pi)
7867 #if ENABLE_HUSH_CASE
7868 char *case_word = NULL;
7870 #if ENABLE_HUSH_LOOPS
7871 struct pipe *loop_top = NULL;
7872 char **for_lcur = NULL;
7873 char **for_list = NULL;
7875 smallint last_followup;
7877 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7878 smalluint cond_code = 0;
7880 enum { cond_code = 0 };
7883 smallint rword; /* RES_foo */
7884 smallint last_rword; /* ditto */
7887 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7890 #if ENABLE_HUSH_LOOPS
7891 /* Check syntax for "for" */
7894 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7895 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7897 /* current word is FOR or IN (BOLD in comments below) */
7898 if (cpipe->next == NULL) {
7899 syntax_error("malformed for");
7901 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7904 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7905 if (cpipe->next->res_word == RES_DO)
7907 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7908 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7909 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7911 syntax_error("malformed for");
7913 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7920 /* Past this point, all code paths should jump to ret: label
7921 * in order to return, no direct "return" statements please.
7922 * This helps to ensure that no memory is leaked. */
7930 last_rword = RES_XXXX;
7932 last_followup = PIPE_SEQ;
7933 rcode = G.last_exitcode;
7935 /* Go through list of pipes, (maybe) executing them. */
7936 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7941 if (G_flag_return_in_progress == 1)
7944 IF_HAS_KEYWORDS(rword = pi->res_word;)
7945 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7946 rword, cond_code, last_rword);
7947 #if ENABLE_HUSH_LOOPS
7948 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7949 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7951 /* start of a loop: remember where loop starts */
7956 /* Still in the same "if...", "then..." or "do..." branch? */
7957 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7958 if ((rcode == 0 && last_followup == PIPE_OR)
7959 || (rcode != 0 && last_followup == PIPE_AND)
7961 /* It is "<true> || CMD" or "<false> && CMD"
7962 * and we should not execute CMD */
7963 debug_printf_exec("skipped cmd because of || or &&\n");
7964 last_followup = pi->followup;
7965 goto dont_check_jobs_but_continue;
7968 last_followup = pi->followup;
7969 IF_HAS_KEYWORDS(last_rword = rword;)
7972 if (rword == RES_THEN) {
7973 /* if false; then ... fi has exitcode 0! */
7974 G.last_exitcode = rcode = EXIT_SUCCESS;
7975 /* "if <false> THEN cmd": skip cmd */
7979 if (rword == RES_ELSE || rword == RES_ELIF) {
7980 /* "if <true> then ... ELSE/ELIF cmd":
7981 * skip cmd and all following ones */
7986 #if ENABLE_HUSH_LOOPS
7987 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7989 /* first loop through for */
7991 static const char encoded_dollar_at[] ALIGN1 = {
7992 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7993 }; /* encoded representation of "$@" */
7994 static const char *const encoded_dollar_at_argv[] = {
7995 encoded_dollar_at, NULL
7996 }; /* argv list with one element: "$@" */
7999 vals = (char**)encoded_dollar_at_argv;
8000 if (pi->next->res_word == RES_IN) {
8001 /* if no variable values after "in" we skip "for" */
8002 if (!pi->next->cmds[0].argv) {
8003 G.last_exitcode = rcode = EXIT_SUCCESS;
8004 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8007 vals = pi->next->cmds[0].argv;
8008 } /* else: "for var; do..." -> assume "$@" list */
8009 /* create list of variable values */
8010 debug_print_strings("for_list made from", vals);
8011 for_list = expand_strvec_to_strvec(vals);
8012 for_lcur = for_list;
8013 debug_print_strings("for_list", for_list);
8016 /* "for" loop is over, clean up */
8022 /* Insert next value from for_lcur */
8023 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8024 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
8027 if (rword == RES_IN) {
8028 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8030 if (rword == RES_DONE) {
8031 continue; /* "done" has no cmds too */
8034 #if ENABLE_HUSH_CASE
8035 if (rword == RES_CASE) {
8036 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8037 case_word = expand_strvec_to_string(pi->cmds->argv);
8040 if (rword == RES_MATCH) {
8043 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8044 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8046 /* all prev words didn't match, does this one match? */
8047 argv = pi->cmds->argv;
8049 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8050 /* TODO: which FNM_xxx flags to use? */
8051 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8053 if (cond_code == 0) { /* match! we will execute this branch */
8055 case_word = NULL; /* make future "word)" stop */
8062 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8063 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8065 continue; /* not matched yet, skip this pipe */
8067 if (rword == RES_ESAC) {
8068 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8070 /* "case" did not match anything: still set $? (to 0) */
8071 G.last_exitcode = rcode = EXIT_SUCCESS;
8075 /* Just pressing <enter> in shell should check for jobs.
8076 * OTOH, in non-interactive shell this is useless
8077 * and only leads to extra job checks */
8078 if (pi->num_cmds == 0) {
8079 if (G_interactive_fd)
8080 goto check_jobs_and_continue;
8084 /* After analyzing all keywords and conditions, we decided
8085 * to execute this pipe. NB: have to do checkjobs(NULL)
8086 * after run_pipe to collect any background children,
8087 * even if list execution is to be stopped. */
8088 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8089 #if ENABLE_HUSH_LOOPS
8090 G.flag_break_continue = 0;
8092 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8094 /* We ran a builtin, function, or group.
8095 * rcode is already known
8096 * and we don't need to wait for anything. */
8097 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8098 G.last_exitcode = rcode;
8099 check_and_run_traps();
8100 #if ENABLE_HUSH_LOOPS
8101 /* Was it "break" or "continue"? */
8102 if (G.flag_break_continue) {
8103 smallint fbc = G.flag_break_continue;
8104 /* We might fall into outer *loop*,
8105 * don't want to break it too */
8107 G.depth_break_continue--;
8108 if (G.depth_break_continue == 0)
8109 G.flag_break_continue = 0;
8110 /* else: e.g. "continue 2" should *break* once, *then* continue */
8111 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8112 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8113 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8116 /* "continue": simulate end of loop */
8121 if (G_flag_return_in_progress == 1) {
8122 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8125 } else if (pi->followup == PIPE_BG) {
8126 /* What does bash do with attempts to background builtins? */
8127 /* even bash 3.2 doesn't do that well with nested bg:
8128 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8129 * I'm NOT treating inner &'s as jobs */
8131 if (G.run_list_level == 1)
8134 /* Last command's pid goes to $! */
8135 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8136 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8137 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
8138 rcode = EXIT_SUCCESS;
8142 if (G.run_list_level == 1 && G_interactive_fd) {
8143 /* Waits for completion, then fg's main shell */
8144 rcode = checkjobs_and_fg_shell(pi);
8145 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8149 /* This one just waits for completion */
8150 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8151 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8153 G.last_exitcode = rcode;
8154 check_and_run_traps();
8157 /* Analyze how result affects subsequent commands */
8159 if (rword == RES_IF || rword == RES_ELIF)
8162 check_jobs_and_continue:
8163 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8164 dont_check_jobs_but_continue: ;
8165 #if ENABLE_HUSH_LOOPS
8166 /* Beware of "while false; true; do ..."! */
8168 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8169 /* check for RES_DONE is needed for "while ...; do \n done" case */
8171 if (rword == RES_WHILE) {
8173 /* "while false; do...done" - exitcode 0 */
8174 G.last_exitcode = rcode = EXIT_SUCCESS;
8175 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8179 if (rword == RES_UNTIL) {
8181 debug_printf_exec(": until expr is true: breaking\n");
8192 #if ENABLE_HUSH_LOOPS
8197 #if ENABLE_HUSH_CASE
8201 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8205 /* Select which version we will use */
8206 static int run_and_free_list(struct pipe *pi)
8209 debug_printf_exec("run_and_free_list entered\n");
8210 if (!G.o_opt[OPT_O_NOEXEC]) {
8211 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8212 rcode = run_list(pi);
8214 /* free_pipe_list has the side effect of clearing memory.
8215 * In the long run that function can be merged with run_list,
8216 * but doing that now would hobble the debugging effort. */
8218 debug_printf_exec("run_and_free_list return %d\n", rcode);
8223 static void install_sighandlers(unsigned mask)
8225 sighandler_t old_handler;
8227 while ((mask >>= 1) != 0) {
8231 old_handler = install_sighandler(sig, pick_sighandler(sig));
8232 /* POSIX allows shell to re-enable SIGCHLD
8233 * even if it was SIG_IGN on entry.
8234 * Therefore we skip IGN check for it:
8238 if (old_handler == SIG_IGN) {
8239 /* oops... restore back to IGN, and record this fact */
8240 install_sighandler(sig, old_handler);
8241 #if ENABLE_HUSH_TRAP
8243 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8245 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8251 /* Called a few times only (or even once if "sh -c") */
8252 static void install_special_sighandlers(void)
8256 /* Which signals are shell-special? */
8257 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8258 if (G_interactive_fd) {
8259 mask |= SPECIAL_INTERACTIVE_SIGS;
8260 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8261 mask |= SPECIAL_JOBSTOP_SIGS;
8263 /* Careful, do not re-install handlers we already installed */
8264 if (G.special_sig_mask != mask) {
8265 unsigned diff = mask & ~G.special_sig_mask;
8266 G.special_sig_mask = mask;
8267 install_sighandlers(diff);
8273 /* Set handlers to restore tty pgrp and exit */
8274 static void install_fatal_sighandlers(void)
8278 /* We will restore tty pgrp on these signals */
8280 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8281 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8282 + (1 << SIGBUS ) * HUSH_DEBUG
8283 + (1 << SIGSEGV) * HUSH_DEBUG
8284 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8286 /* bash 3.2 seems to handle these just like 'fatal' ones */
8289 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8290 * if we aren't interactive... but in this case
8291 * we never want to restore pgrp on exit, and this fn is not called
8293 /*+ (1 << SIGHUP )*/
8294 /*+ (1 << SIGTERM)*/
8295 /*+ (1 << SIGINT )*/
8297 G_fatal_sig_mask = mask;
8299 install_sighandlers(mask);
8303 static int set_mode(int state, char mode, const char *o_opt)
8308 G.o_opt[OPT_O_NOEXEC] = state;
8311 IF_HUSH_MODE_X(G_x_mode = state;)
8315 /* "set -+o" without parameter.
8316 * in bash, set -o produces this output:
8320 * We always use the second form.
8322 const char *p = o_opt_strings;
8325 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8331 idx = index_in_strings(o_opt_strings, o_opt);
8333 G.o_opt[idx] = state;
8337 return EXIT_FAILURE;
8339 return EXIT_SUCCESS;
8342 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8343 int hush_main(int argc, char **argv)
8346 OPT_login = (1 << 0),
8350 unsigned builtin_argc;
8352 struct variable *cur_var;
8353 struct variable *shell_ver;
8356 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8357 G.last_exitcode = EXIT_SUCCESS;
8359 #if ENABLE_HUSH_FAST
8360 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8363 G.argv0_for_re_execing = argv[0];
8365 /* Deal with HUSH_VERSION */
8366 shell_ver = xzalloc(sizeof(*shell_ver));
8367 shell_ver->flg_export = 1;
8368 shell_ver->flg_read_only = 1;
8369 /* Code which handles ${var<op>...} needs writable values for all variables,
8370 * therefore we xstrdup: */
8371 shell_ver->varstr = xstrdup(hush_version_str);
8372 /* Create shell local variables from the values
8373 * currently living in the environment */
8374 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8375 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8376 G.top_var = shell_ver;
8377 cur_var = G.top_var;
8380 char *value = strchr(*e, '=');
8381 if (value) { /* paranoia */
8382 cur_var->next = xzalloc(sizeof(*cur_var));
8383 cur_var = cur_var->next;
8384 cur_var->varstr = *e;
8385 cur_var->max_len = strlen(*e);
8386 cur_var->flg_export = 1;
8390 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8391 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8392 putenv(shell_ver->varstr);
8395 set_pwd_var(/*exp:*/ 1);
8397 #if ENABLE_HUSH_BASH_COMPAT
8398 /* Set (but not export) HOSTNAME unless already set */
8399 if (!get_local_var_value("HOSTNAME")) {
8402 set_local_var_from_halves("HOSTNAME", uts.nodename);
8404 /* bash also exports SHLVL and _,
8405 * and sets (but doesn't export) the following variables:
8407 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8408 * BASH_VERSION='3.2.0(1)-release'
8410 * MACHTYPE=i386-pc-linux-gnu
8412 * PPID=<NNNNN> - we also do it elsewhere
8423 * PIPESTATUS=([0]="0")
8424 * HISTFILE=/<xxx>/.bash_history
8428 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8430 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8441 #if ENABLE_FEATURE_EDITING
8442 G.line_input_state = new_line_input_t(FOR_SHELL);
8445 /* Initialize some more globals to non-zero values */
8446 cmdedit_update_prompt();
8448 die_func = restore_ttypgrp_and__exit;
8450 /* Shell is non-interactive at first. We need to call
8451 * install_special_sighandlers() if we are going to execute "sh <script>",
8452 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8453 * If we later decide that we are interactive, we run install_special_sighandlers()
8454 * in order to intercept (more) signals.
8458 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8459 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8462 opt = getopt(argc, argv, "+c:xinsl"
8465 # if ENABLE_HUSH_FUNCTIONS
8475 * sh ... -c 'script'
8476 * sh ... -c 'script' ARG0 [ARG1...]
8477 * On NOMMU, if builtin_argc != 0,
8478 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8479 * "" needs to be replaced with NULL
8480 * and BARGV vector fed to builtin function.
8481 * Note: the form without ARG0 never happens:
8482 * sh ... -c 'builtin' BARGV... ""
8485 G.root_pid = getpid();
8486 G.root_ppid = getppid();
8488 G.global_argv = argv + optind;
8489 G.global_argc = argc - optind;
8491 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8492 const struct built_in_command *x;
8494 install_special_sighandlers();
8495 x = find_builtin(optarg);
8496 if (x) { /* paranoia */
8497 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8498 G.global_argv += builtin_argc;
8499 G.global_argv[-1] = NULL; /* replace "" */
8501 G.last_exitcode = x->b_function(argv + optind - 1);
8505 if (!G.global_argv[0]) {
8506 /* -c 'script' (no params): prevent empty $0 */
8507 G.global_argv--; /* points to argv[i] of 'script' */
8508 G.global_argv[0] = argv[0];
8510 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8511 install_special_sighandlers();
8512 parse_and_run_string(optarg);
8515 /* Well, we cannot just declare interactiveness,
8516 * we have to have some stuff (ctty, etc) */
8517 /* G_interactive_fd++; */
8520 /* "-s" means "read from stdin", but this is how we always
8521 * operate, so simply do nothing here. */
8527 case '<': /* "big heredoc" support */
8528 full_write1_str(optarg);
8531 unsigned long long empty_trap_mask;
8533 G.root_pid = bb_strtou(optarg, &optarg, 16);
8535 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8537 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8539 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8541 builtin_argc = bb_strtou(optarg, &optarg, 16);
8543 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8544 if (empty_trap_mask != 0) {
8546 install_special_sighandlers();
8547 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8548 for (sig = 1; sig < NSIG; sig++) {
8549 if (empty_trap_mask & (1LL << sig)) {
8550 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8551 install_sighandler(sig, SIG_IGN);
8555 # if ENABLE_HUSH_LOOPS
8557 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8563 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8565 # if ENABLE_HUSH_FUNCTIONS
8567 struct function *funcp = new_function(optarg);
8568 /* funcp->name is already set to optarg */
8569 /* funcp->body is set to NULL. It's a special case. */
8570 funcp->body_as_string = argv[optind];
8578 if (set_mode(1, opt, NULL) == 0) /* no error */
8582 fprintf(stderr, "Usage: sh [FILE]...\n"
8583 " or: sh -c command [args]...\n\n");
8589 } /* option parsing loop */
8591 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8592 G.global_argc = argc - (optind - 1);
8593 G.global_argv = argv + (optind - 1);
8594 G.global_argv[0] = argv[0];
8597 G.root_pid = getpid();
8598 G.root_ppid = getppid();
8601 /* If we are login shell... */
8602 if (flags & OPT_login) {
8604 debug_printf("sourcing /etc/profile\n");
8605 input = fopen_for_read("/etc/profile");
8606 if (input != NULL) {
8607 remember_FILE(input);
8608 install_special_sighandlers();
8609 parse_and_run_file(input);
8610 fclose_and_forget(input);
8612 /* bash: after sourcing /etc/profile,
8613 * tries to source (in the given order):
8614 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8615 * stopping on first found. --noprofile turns this off.
8616 * bash also sources ~/.bash_logout on exit.
8617 * If called as sh, skips .bash_XXX files.
8621 if (G.global_argv[1]) {
8624 * "bash <script>" (which is never interactive (unless -i?))
8625 * sources $BASH_ENV here (without scanning $PATH).
8626 * If called as sh, does the same but with $ENV.
8627 * Also NB, per POSIX, $ENV should undergo parameter expansion.
8631 debug_printf("running script '%s'\n", G.global_argv[0]);
8632 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
8633 input = xfopen_for_read(G.global_argv[0]);
8634 xfunc_error_retval = 1;
8635 remember_FILE(input);
8636 install_special_sighandlers();
8637 parse_and_run_file(input);
8638 #if ENABLE_FEATURE_CLEAN_UP
8639 fclose_and_forget(input);
8644 /* Up to here, shell was non-interactive. Now it may become one.
8645 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8648 /* A shell is interactive if the '-i' flag was given,
8649 * or if all of the following conditions are met:
8651 * no arguments remaining or the -s flag given
8652 * standard input is a terminal
8653 * standard output is a terminal
8654 * Refer to Posix.2, the description of the 'sh' utility.
8657 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8658 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8659 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8660 if (G_saved_tty_pgrp < 0)
8661 G_saved_tty_pgrp = 0;
8663 /* try to dup stdin to high fd#, >= 255 */
8664 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8665 if (G_interactive_fd < 0) {
8666 /* try to dup to any fd */
8667 G_interactive_fd = dup(STDIN_FILENO);
8668 if (G_interactive_fd < 0) {
8670 G_interactive_fd = 0;
8671 G_saved_tty_pgrp = 0;
8674 // TODO: track & disallow any attempts of user
8675 // to (inadvertently) close/redirect G_interactive_fd
8677 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8678 if (G_interactive_fd) {
8679 close_on_exec_on(G_interactive_fd);
8681 if (G_saved_tty_pgrp) {
8682 /* If we were run as 'hush &', sleep until we are
8683 * in the foreground (tty pgrp == our pgrp).
8684 * If we get started under a job aware app (like bash),
8685 * make sure we are now in charge so we don't fight over
8686 * who gets the foreground */
8688 pid_t shell_pgrp = getpgrp();
8689 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8690 if (G_saved_tty_pgrp == shell_pgrp)
8692 /* send TTIN to ourself (should stop us) */
8693 kill(- shell_pgrp, SIGTTIN);
8697 /* Install more signal handlers */
8698 install_special_sighandlers();
8700 if (G_saved_tty_pgrp) {
8701 /* Set other signals to restore saved_tty_pgrp */
8702 install_fatal_sighandlers();
8703 /* Put ourselves in our own process group
8704 * (bash, too, does this only if ctty is available) */
8705 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8706 /* Grab control of the terminal */
8707 tcsetpgrp(G_interactive_fd, getpid());
8709 enable_restore_tty_pgrp_on_exit();
8711 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8713 const char *hp = get_local_var_value("HISTFILE");
8715 hp = get_local_var_value("HOME");
8717 hp = concat_path_file(hp, ".hush_history");
8722 G.line_input_state->hist_file = hp;
8723 //set_local_var(xasprintf("HISTFILE=%s", ...));
8725 # if ENABLE_FEATURE_SH_HISTFILESIZE
8726 hp = get_local_var_value("HISTFILESIZE");
8727 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8732 install_special_sighandlers();
8734 #elif ENABLE_HUSH_INTERACTIVE
8735 /* No job control compiled in, only prompt/line editing */
8736 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8737 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8738 if (G_interactive_fd < 0) {
8739 /* try to dup to any fd */
8740 G_interactive_fd = dup(STDIN_FILENO);
8741 if (G_interactive_fd < 0)
8743 G_interactive_fd = 0;
8746 if (G_interactive_fd) {
8747 close_on_exec_on(G_interactive_fd);
8749 install_special_sighandlers();
8751 /* We have interactiveness code disabled */
8752 install_special_sighandlers();
8755 * if interactive but not a login shell, sources ~/.bashrc
8756 * (--norc turns this off, --rcfile <file> overrides)
8759 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8760 /* note: ash and hush share this string */
8761 printf("\n\n%s %s\n"
8762 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8765 "hush - the humble shell"
8769 parse_and_run_file(stdin);
8772 hush_exit(G.last_exitcode);
8777 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8778 int msh_main(int argc, char **argv)
8780 bb_error_msg("msh is deprecated, please use hush instead");
8781 return hush_main(argc, argv);
8789 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8794 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8801 return applet_main_func(argc, argv - argc);
8804 static int FAST_FUNC builtin_test(char **argv)
8806 return run_applet_main(argv, test_main);
8808 #if ENABLE_HUSH_ECHO
8809 static int FAST_FUNC builtin_echo(char **argv)
8811 return run_applet_main(argv, echo_main);
8814 #if ENABLE_HUSH_PRINTF
8815 static int FAST_FUNC builtin_printf(char **argv)
8817 return run_applet_main(argv, printf_main);
8821 static char **skip_dash_dash(char **argv)
8824 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8829 static int FAST_FUNC builtin_eval(char **argv)
8831 int rcode = EXIT_SUCCESS;
8833 argv = skip_dash_dash(argv);
8835 char *str = expand_strvec_to_string(argv);
8837 * eval "echo Hi; done" ("done" is syntax error):
8838 * "echo Hi" will not execute too.
8840 parse_and_run_string(str);
8842 rcode = G.last_exitcode;
8847 static int FAST_FUNC builtin_cd(char **argv)
8851 argv = skip_dash_dash(argv);
8853 if (newdir == NULL) {
8854 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8855 * bash says "bash: cd: HOME not set" and does nothing
8858 const char *home = get_local_var_value("HOME");
8859 newdir = home ? home : "/";
8861 if (chdir(newdir)) {
8862 /* Mimic bash message exactly */
8863 bb_perror_msg("cd: %s", newdir);
8864 return EXIT_FAILURE;
8866 /* Read current dir (get_cwd(1) is inside) and set PWD.
8867 * Note: do not enforce exporting. If PWD was unset or unexported,
8868 * set it again, but do not export. bash does the same.
8870 set_pwd_var(/*exp:*/ 0);
8871 return EXIT_SUCCESS;
8874 static int FAST_FUNC builtin_exec(char **argv)
8876 argv = skip_dash_dash(argv);
8877 if (argv[0] == NULL)
8878 return EXIT_SUCCESS; /* bash does this */
8880 /* Careful: we can end up here after [v]fork. Do not restore
8881 * tty pgrp then, only top-level shell process does that */
8882 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8883 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8885 /* TODO: if exec fails, bash does NOT exit! We do.
8886 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8887 * and tcsetpgrp, and this is inherently racy.
8889 execvp_or_die(argv);
8892 static int FAST_FUNC builtin_exit(char **argv)
8894 debug_printf_exec("%s()\n", __func__);
8896 /* interactive bash:
8897 * # trap "echo EEE" EXIT
8900 * There are stopped jobs.
8901 * (if there are _stopped_ jobs, running ones don't count)
8904 * EEE (then bash exits)
8906 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8909 /* note: EXIT trap is run by hush_exit */
8910 argv = skip_dash_dash(argv);
8911 if (argv[0] == NULL)
8912 hush_exit(G.last_exitcode);
8913 /* mimic bash: exit 123abc == exit 255 + error msg */
8914 xfunc_error_retval = 255;
8915 /* bash: exit -2 == exit 254, no error msg */
8916 hush_exit(xatoi(argv[0]) & 0xff);
8919 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
8920 static void print_escaped(const char *s)
8925 const char *p = strchrnul(s, '\'');
8926 /* print 'xxxx', possibly just '' */
8927 printf("'%.*s'", (int)(p - s), s);
8932 /* s points to '; print "'''...'''" */
8934 do putchar('\''); while (*++s == '\'');
8940 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL
8941 # if !ENABLE_HUSH_LOCAL
8942 #define helper_export_local(argv, exp, lvl) \
8943 helper_export_local(argv, exp)
8945 static void helper_export_local(char **argv, int exp, int lvl)
8949 char *name_end = strchrnul(name, '=');
8951 /* So far we do not check that name is valid (TODO?) */
8953 if (*name_end == '\0') {
8954 struct variable *var, **vpp;
8956 vpp = get_ptr_to_local_var(name, name_end - name);
8957 var = vpp ? *vpp : NULL;
8959 if (exp == -1) { /* unexporting? */
8960 /* export -n NAME (without =VALUE) */
8962 var->flg_export = 0;
8963 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8965 } /* else: export -n NOT_EXISTING_VAR: no-op */
8968 if (exp == 1) { /* exporting? */
8969 /* export NAME (without =VALUE) */
8971 var->flg_export = 1;
8972 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8973 putenv(var->varstr);
8977 # if ENABLE_HUSH_LOCAL
8978 if (exp == 0 /* local? */
8979 && var && var->func_nest_level == lvl
8981 /* "local x=abc; ...; local x" - ignore second local decl */
8985 /* Exporting non-existing variable.
8986 * bash does not put it in environment,
8987 * but remembers that it is exported,
8988 * and does put it in env when it is set later.
8989 * We just set it to "" and export. */
8990 /* Or, it's "local NAME" (without =VALUE).
8991 * bash sets the value to "". */
8992 name = xasprintf("%s=", name);
8994 /* (Un)exporting/making local NAME=VALUE */
8995 name = xstrdup(name);
8997 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
9002 #if ENABLE_HUSH_EXPORT
9003 static int FAST_FUNC builtin_export(char **argv)
9005 unsigned opt_unexport;
9007 #if ENABLE_HUSH_EXPORT_N
9008 /* "!": do not abort on errors */
9009 opt_unexport = getopt32(argv, "!n");
9010 if (opt_unexport == (uint32_t)-1)
9011 return EXIT_FAILURE;
9018 if (argv[0] == NULL) {
9025 /* ash emits: export VAR='VAL'
9026 * bash: declare -x VAR="VAL"
9027 * we follow ash example */
9028 const char *s = *e++;
9029 const char *p = strchr(s, '=');
9031 if (!p) /* wtf? take next variable */
9034 printf("export %.*s", (int)(p - s) + 1, s);
9035 print_escaped(p + 1);
9039 /*fflush_all(); - done after each builtin anyway */
9041 return EXIT_SUCCESS;
9044 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
9046 return EXIT_SUCCESS;
9050 #if ENABLE_HUSH_LOCAL
9051 static int FAST_FUNC builtin_local(char **argv)
9053 if (G.func_nest_level == 0) {
9054 bb_error_msg("%s: not in a function", argv[0]);
9055 return EXIT_FAILURE; /* bash compat */
9057 helper_export_local(argv, 0, G.func_nest_level);
9058 return EXIT_SUCCESS;
9062 #if ENABLE_HUSH_UNSET
9063 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9064 static int FAST_FUNC builtin_unset(char **argv)
9069 /* "!": do not abort on errors */
9070 /* "+": stop at 1st non-option */
9071 opts = getopt32(argv, "!+vf");
9072 if (opts == (unsigned)-1)
9073 return EXIT_FAILURE;
9075 bb_error_msg("unset: -v and -f are exclusive");
9076 return EXIT_FAILURE;
9082 if (!(opts & 2)) { /* not -f */
9083 if (unset_local_var(*argv)) {
9084 /* unset <nonexistent_var> doesn't fail.
9085 * Error is when one tries to unset RO var.
9086 * Message was printed by unset_local_var. */
9090 # if ENABLE_HUSH_FUNCTIONS
9102 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9103 * built-in 'set' handler
9105 * set [-abCefhmnuvx] [-o option] [argument...]
9106 * set [+abCefhmnuvx] [+o option] [argument...]
9107 * set -- [argument...]
9110 * Implementations shall support the options in both their hyphen and
9111 * plus-sign forms. These options can also be specified as options to sh.
9113 * Write out all variables and their values: set
9114 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9115 * Turn on the -x and -v options: set -xv
9116 * Unset all positional parameters: set --
9117 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9118 * Set the positional parameters to the expansion of x, even if x expands
9119 * with a leading '-' or '+': set -- $x
9121 * So far, we only support "set -- [argument...]" and some of the short names.
9123 static int FAST_FUNC builtin_set(char **argv)
9126 char **pp, **g_argv;
9127 char *arg = *++argv;
9131 for (e = G.top_var; e; e = e->next)
9133 return EXIT_SUCCESS;
9137 if (strcmp(arg, "--") == 0) {
9141 if (arg[0] != '+' && arg[0] != '-')
9143 for (n = 1; arg[n]; ++n) {
9144 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9146 if (arg[n] == 'o' && argv[1])
9149 } while ((arg = *++argv) != NULL);
9150 /* Now argv[0] is 1st argument */
9153 return EXIT_SUCCESS;
9156 /* NB: G.global_argv[0] ($0) is never freed/changed */
9157 g_argv = G.global_argv;
9158 if (G.global_args_malloced) {
9164 G.global_args_malloced = 1;
9165 pp = xzalloc(sizeof(pp[0]) * 2);
9166 pp[0] = g_argv[0]; /* retain $0 */
9169 /* This realloc's G.global_argv */
9170 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9177 return EXIT_SUCCESS;
9179 /* Nothing known, so abort */
9181 bb_error_msg("set: %s: invalid option", arg);
9182 return EXIT_FAILURE;
9186 static int FAST_FUNC builtin_shift(char **argv)
9189 argv = skip_dash_dash(argv);
9193 if (n >= 0 && n < G.global_argc) {
9194 if (G_global_args_malloced) {
9197 free(G.global_argv[m++]);
9200 memmove(&G.global_argv[1], &G.global_argv[n+1],
9201 G.global_argc * sizeof(G.global_argv[0]));
9202 return EXIT_SUCCESS;
9204 return EXIT_FAILURE;
9207 #if ENABLE_HUSH_READ
9208 /* Interruptibility of read builtin in bash
9209 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9211 * Empty trap makes read ignore corresponding signal, for any signal.
9214 * - terminates non-interactive shell;
9215 * - interrupts read in interactive shell;
9216 * if it has non-empty trap:
9217 * - executes trap and returns to command prompt in interactive shell;
9218 * - executes trap and returns to read in non-interactive shell;
9220 * - is ignored (does not interrupt) read in interactive shell;
9221 * - terminates non-interactive shell;
9222 * if it has non-empty trap:
9223 * - executes trap and returns to read;
9225 * - terminates shell (regardless of interactivity);
9226 * if it has non-empty trap:
9227 * - executes trap and returns to read;
9229 static int FAST_FUNC builtin_read(char **argv)
9239 /* "!": do not abort on errors.
9240 * Option string must start with "sr" to match BUILTIN_READ_xxx
9242 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9243 if (read_flags == (uint32_t)-1)
9244 return EXIT_FAILURE;
9246 ifs = get_local_var_value("IFS"); /* can be NULL */
9249 r = shell_builtin_read(set_local_var_from_halves,
9259 if ((uintptr_t)r == 1 && errno == EINTR) {
9260 unsigned sig = check_and_run_traps();
9261 if (sig && sig != SIGINT)
9265 if ((uintptr_t)r > 1) {
9266 bb_error_msg("%s", r);
9267 r = (char*)(uintptr_t)1;
9270 return (uintptr_t)r;
9274 #if ENABLE_HUSH_TRAP
9275 static int FAST_FUNC builtin_trap(char **argv)
9281 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9286 /* No args: print all trapped */
9287 for (i = 0; i < NSIG; ++i) {
9290 print_escaped(G_traps[i]);
9291 /* note: bash adds "SIG", but only if invoked
9292 * as "bash". If called as "sh", or if set -o posix,
9293 * then it prints short signal names.
9294 * We are printing short names: */
9295 printf(" %s\n", get_signame(i));
9298 /*fflush_all(); - done after each builtin anyway */
9299 return EXIT_SUCCESS;
9303 /* If first arg is a number: reset all specified signals */
9304 sig = bb_strtou(*argv, NULL, 10);
9310 sighandler_t handler;
9312 sig = get_signum(*argv++);
9313 if (sig < 0 || sig >= NSIG) {
9315 /* Mimic bash message exactly */
9316 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
9321 G_traps[sig] = xstrdup(new_cmd);
9323 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9324 get_signame(sig), sig, G_traps[sig]);
9326 /* There is no signal for 0 (EXIT) */
9331 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9333 /* We are removing trap handler */
9334 handler = pick_sighandler(sig);
9335 install_sighandler(sig, handler);
9340 if (!argv[1]) { /* no second arg */
9341 bb_error_msg("trap: invalid arguments");
9342 return EXIT_FAILURE;
9345 /* First arg is "-": reset all specified to default */
9346 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9347 /* Everything else: set arg as signal handler
9348 * (includes "" case, which ignores signal) */
9349 if (argv[0][0] == '-') {
9350 if (argv[0][1] == '\0') { /* "-" */
9351 /* new_cmd remains NULL: "reset these sigs" */
9354 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9357 /* else: "-something", no special meaning */
9362 goto process_sig_list;
9366 #if ENABLE_HUSH_TYPE
9367 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9368 static int FAST_FUNC builtin_type(char **argv)
9370 int ret = EXIT_SUCCESS;
9376 if (0) {} /* make conditional compile easier below */
9377 /*else if (find_alias(*argv))
9378 type = "an alias";*/
9379 #if ENABLE_HUSH_FUNCTIONS
9380 else if (find_function(*argv))
9381 type = "a function";
9383 else if (find_builtin(*argv))
9384 type = "a shell builtin";
9385 else if ((path = find_in_path(*argv)) != NULL)
9388 bb_error_msg("type: %s: not found", *argv);
9393 printf("%s is %s\n", *argv, type);
9402 static struct pipe *parse_jobspec(const char *str)
9407 if (sscanf(str, "%%%u", &jobnum) != 1) {
9409 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
9411 bb_error_msg("bad argument '%s'", str);
9414 /* It is "%%", "%+" or "%" - current job */
9415 jobnum = G.last_jobid;
9417 bb_error_msg("no current job");
9421 for (pi = G.job_list; pi; pi = pi->next) {
9422 if (pi->jobid == jobnum) {
9426 bb_error_msg("%u: no such job", jobnum);
9430 /* built-in 'fg' and 'bg' handler */
9431 static int FAST_FUNC builtin_fg_bg(char **argv)
9436 if (!G_interactive_fd)
9437 return EXIT_FAILURE;
9439 /* If they gave us no args, assume they want the last backgrounded task */
9441 for (pi = G.job_list; pi; pi = pi->next) {
9442 if (pi->jobid == G.last_jobid) {
9446 bb_error_msg("%s: no current job", argv[0]);
9447 return EXIT_FAILURE;
9450 pi = parse_jobspec(argv[1]);
9452 return EXIT_FAILURE;
9454 /* TODO: bash prints a string representation
9455 * of job being foregrounded (like "sleep 1 | cat") */
9456 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
9457 /* Put the job into the foreground. */
9458 tcsetpgrp(G_interactive_fd, pi->pgrp);
9461 /* Restart the processes in the job */
9462 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9463 for (i = 0; i < pi->num_cmds; i++) {
9464 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
9466 pi->stopped_cmds = 0;
9468 i = kill(- pi->pgrp, SIGCONT);
9470 if (errno == ESRCH) {
9471 delete_finished_bg_job(pi);
9472 return EXIT_SUCCESS;
9474 bb_perror_msg("kill (SIGCONT)");
9477 if (argv[0][0] == 'f') {
9479 return checkjobs_and_fg_shell(pi);
9481 return EXIT_SUCCESS;
9485 #if ENABLE_HUSH_HELP
9486 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9488 const struct built_in_command *x;
9491 "Built-in commands:\n"
9492 "------------------\n");
9493 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9495 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9497 return EXIT_SUCCESS;
9501 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9502 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9504 show_history(G.line_input_state);
9505 return EXIT_SUCCESS;
9510 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9513 const char *status_string;
9515 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9516 for (job = G.job_list; job; job = job->next) {
9517 if (job->alive_cmds == job->stopped_cmds)
9518 status_string = "Stopped";
9520 status_string = "Running";
9522 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9524 return EXIT_SUCCESS;
9528 #if ENABLE_HUSH_MEMLEAK
9529 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
9534 # ifdef M_TRIM_THRESHOLD
9535 /* Optional. Reduces probability of false positives */
9538 /* Crude attempt to find where "free memory" starts,
9539 * sans fragmentation. */
9541 l = (unsigned long)p;
9544 if (l < (unsigned long)p) l = (unsigned long)p;
9550 struct mallinfo mi = mallinfo();
9551 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9552 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9556 if (!G.memleak_value)
9557 G.memleak_value = l;
9559 l -= G.memleak_value;
9566 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9571 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9574 return EXIT_SUCCESS;
9577 static int FAST_FUNC builtin_source(char **argv)
9579 char *arg_path, *filename;
9582 char *args_need_save;
9583 #if ENABLE_HUSH_FUNCTIONS
9587 argv = skip_dash_dash(argv);
9590 /* bash says: "bash: .: filename argument required" */
9591 return 2; /* bash compat */
9594 if (!strchr(filename, '/')) {
9595 arg_path = find_in_path(filename);
9597 filename = arg_path;
9599 input = remember_FILE(fopen_or_warn(filename, "r"));
9602 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9603 /* POSIX: non-interactive shell should abort here,
9604 * not merely fail. So far no one complained :)
9606 return EXIT_FAILURE;
9609 #if ENABLE_HUSH_FUNCTIONS
9610 sv_flg = G_flag_return_in_progress;
9611 /* "we are inside sourced file, ok to use return" */
9612 G_flag_return_in_progress = -1;
9614 args_need_save = argv[1]; /* used as a boolean variable */
9616 save_and_replace_G_args(&sv, argv);
9618 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9619 G.last_exitcode = 0;
9620 parse_and_run_file(input);
9621 fclose_and_forget(input);
9623 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
9624 restore_G_args(&sv, argv);
9625 #if ENABLE_HUSH_FUNCTIONS
9626 G_flag_return_in_progress = sv_flg;
9629 return G.last_exitcode;
9632 #if ENABLE_HUSH_UMASK
9633 static int FAST_FUNC builtin_umask(char **argv)
9640 argv = skip_dash_dash(argv);
9642 mode_t old_mask = mask;
9644 /* numeric umasks are taken as-is */
9645 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9646 if (!isdigit(argv[0][0]))
9648 mask = bb_parse_mode(argv[0], mask);
9649 if (!isdigit(argv[0][0]))
9651 if ((unsigned)mask > 0777) {
9654 * bash: umask: 'q': invalid symbolic mode operator
9655 * bash: umask: 999: octal number out of range
9657 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9662 printf("%04o\n", (unsigned) mask);
9663 /* fall through and restore mask which we set to 0 */
9667 return !rc; /* rc != 0 - success */
9671 #if ENABLE_HUSH_KILL
9672 static int FAST_FUNC builtin_kill(char **argv)
9676 # if ENABLE_HUSH_JOB
9677 if (argv[1] && strcmp(argv[1], "-l") != 0) {
9685 if (argv[i][0] != '%')
9688 * "kill %N" - job kill
9689 * Converting to pgrp / pid kill
9691 pi = parse_jobspec(argv[i]);
9693 /* Eat bad jobspec */
9697 argv[j - 1] = argv[j];
9704 * In jobs started under job control, we signal
9705 * entire process group by kill -PGRP_ID.
9706 * This happens, f.e., in interactive shell.
9708 * Otherwise, we signal each child via
9709 * kill PID1 PID2 PID3.
9711 * sh -c 'sleep 1|sleep 1 & kill %1'
9712 * sh -c 'true|sleep 2 & sleep 1; kill %1'
9713 * sh -c 'true|sleep 1 & sleep 2; kill %1'
9715 n = G_interactive_fd ? 1 : pi->num_cmds;
9716 dst = alloca(n * sizeof(int)*4);
9718 if (G_interactive_fd)
9719 dst += sprintf(dst, " -%u", (int)pi->pgrp);
9720 else for (j = 0; j < n; j++) {
9721 struct command *cmd = &pi->cmds[j];
9722 /* Skip exited members of the job */
9726 * kill_main has matching code to expect
9727 * leading space. Needed to not confuse
9728 * negative pids with "kill -SIGNAL_NO" syntax
9730 dst += sprintf(dst, " %u", (int)cmd->pid);
9733 } while (argv[++i]);
9737 if (argv[1] || ret == 0) {
9738 ret = run_applet_main(argv, kill_main);
9740 /* else: ret = 1, "kill %bad_jobspec" case */
9745 #if ENABLE_HUSH_WAIT
9746 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9747 #if !ENABLE_HUSH_JOB
9748 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9750 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
9757 if (!sigisemptyset(&G.pending_set))
9760 /* waitpid is not interruptible by SA_RESTARTed
9761 * signals which we use. Thus, this ugly dance:
9764 /* Make sure possible SIGCHLD is stored in kernel's
9765 * pending signal mask before we call waitpid.
9766 * Or else we may race with SIGCHLD, lose it,
9767 * and get stuck in sigsuspend...
9769 sigfillset(&oldset); /* block all signals, remember old set */
9770 sigprocmask(SIG_SETMASK, &oldset, &oldset);
9772 if (!sigisemptyset(&G.pending_set)) {
9773 /* Crap! we raced with some signal! */
9777 /*errno = 0; - checkjobs does this */
9778 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
9779 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
9780 debug_printf_exec("checkjobs:%d\n", ret);
9783 int rcode = job_exited_or_stopped(waitfor_pipe);
9784 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9787 sigprocmask(SIG_SETMASK, &oldset, NULL);
9792 /* if ECHILD, there are no children (ret is -1 or 0) */
9793 /* if ret == 0, no children changed state */
9794 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
9795 if (errno == ECHILD || ret) {
9797 if (ret < 0) /* if ECHILD, may need to fix "ret" */
9799 sigprocmask(SIG_SETMASK, &oldset, NULL);
9802 /* Wait for SIGCHLD or any other signal */
9803 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9804 /* Note: sigsuspend invokes signal handler */
9805 sigsuspend(&oldset);
9807 sigprocmask(SIG_SETMASK, &oldset, NULL);
9809 /* So, did we get a signal? */
9810 sig = check_and_run_traps();
9811 if (sig /*&& sig != SIGCHLD - always true */) {
9815 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9820 static int FAST_FUNC builtin_wait(char **argv)
9825 argv = skip_dash_dash(argv);
9826 if (argv[0] == NULL) {
9827 /* Don't care about wait results */
9828 /* Note 1: must wait until there are no more children */
9829 /* Note 2: must be interruptible */
9831 * $ sleep 3 & sleep 6 & wait
9836 * $ sleep 3 & sleep 6 & wait
9840 * ^C <-- after ~4 sec from keyboard
9843 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
9847 pid_t pid = bb_strtou(*argv, NULL, 10);
9848 if (errno || pid <= 0) {
9850 if (argv[0][0] == '%') {
9851 struct pipe *wait_pipe;
9852 ret = 127; /* bash compat for bad jobspecs */
9853 wait_pipe = parse_jobspec(*argv);
9855 ret = job_exited_or_stopped(wait_pipe);
9857 ret = wait_for_child_or_signal(wait_pipe, 0);
9859 /* else: parse_jobspec() already emitted error msg */
9863 /* mimic bash message */
9864 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9866 continue; /* bash checks all argv[] */
9869 /* Do we have such child? */
9870 ret = waitpid(pid, &status, WNOHANG);
9873 if (errno == ECHILD) {
9874 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9875 /* "wait $!" but last bg task has already exited. Try:
9876 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9877 * In bash it prints exitcode 0, then 3.
9878 * In dash, it is 127.
9880 /* ret = G.last_bg_pid_exitstatus - FIXME */
9882 /* Example: "wait 1". mimic bash message */
9883 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
9887 bb_perror_msg("wait %s", *argv);
9890 continue; /* bash checks all argv[] */
9893 /* Yes, and it still runs */
9894 ret = wait_for_child_or_signal(NULL, pid);
9896 /* Yes, and it just exited */
9897 process_wait_result(NULL, pid, status);
9898 ret = WEXITSTATUS(status);
9899 if (WIFSIGNALED(status))
9900 ret = 128 + WTERMSIG(status);
9908 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9909 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9912 def = bb_strtou(argv[1], NULL, 10);
9913 if (errno || def < def_min || argv[2]) {
9914 bb_error_msg("%s: bad arguments", argv[0]);
9922 #if ENABLE_HUSH_LOOPS
9923 static int FAST_FUNC builtin_break(char **argv)
9926 if (G.depth_of_loop == 0) {
9927 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9928 /* if we came from builtin_continue(), need to undo "= 1" */
9929 G.flag_break_continue = 0;
9930 return EXIT_SUCCESS; /* bash compat */
9932 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9934 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9935 if (depth == UINT_MAX)
9936 G.flag_break_continue = BC_BREAK;
9937 if (G.depth_of_loop < depth)
9938 G.depth_break_continue = G.depth_of_loop;
9940 return EXIT_SUCCESS;
9943 static int FAST_FUNC builtin_continue(char **argv)
9945 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9946 return builtin_break(argv);
9950 #if ENABLE_HUSH_FUNCTIONS
9951 static int FAST_FUNC builtin_return(char **argv)
9955 if (G_flag_return_in_progress != -1) {
9956 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9957 return EXIT_FAILURE; /* bash compat */
9960 G_flag_return_in_progress = 1;
9963 * out of range: wraps around at 256, does not error out
9964 * non-numeric param:
9965 * f() { false; return qwe; }; f; echo $?
9966 * bash: return: qwe: numeric argument required <== we do this
9967 * 255 <== we also do this
9969 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);