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: Enable bash-compatible extensions.
105 //config:config HUSH_BRACE_EXPANSION
106 //config: bool "Brace expansion"
108 //config: depends on HUSH_BASH_COMPAT
110 //config: Enable {abc,def} extension.
112 //config:config HUSH_INTERACTIVE
113 //config: bool "Interactive mode"
115 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
117 //config: Enable interactive mode (prompt and command editing).
118 //config: Without this, hush simply reads and executes commands
119 //config: from stdin just like a shell script from a file.
120 //config: No prompt, no PS1/PS2 magic shell variables.
122 //config:config HUSH_SAVEHISTORY
123 //config: bool "Save command history to .hush_history"
125 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
127 //config: Enable history saving in hush.
129 //config:config HUSH_JOB
130 //config: bool "Job control"
132 //config: depends on HUSH_INTERACTIVE
134 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
135 //config: command (not entire shell), fg/bg builtins work. Without this option,
136 //config: "cmd &" still works by simply spawning a process and immediately
137 //config: prompting for next command (or executing next command in a script),
138 //config: but no separate process group is formed.
140 //config:config HUSH_TICK
141 //config: bool "Process substitution"
143 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
145 //config: Enable process substitution `command` and $(command) in hush.
147 //config:config HUSH_IF
148 //config: bool "Support if/then/elif/else/fi"
150 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
152 //config: Enable if/then/elif/else/fi in hush.
154 //config:config HUSH_LOOPS
155 //config: bool "Support for, while and until loops"
157 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
159 //config: Enable for, while and until loops in hush.
161 //config:config HUSH_CASE
162 //config: bool "Support case ... esac statement"
164 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
166 //config: Enable case ... esac statement in hush. +400 bytes.
168 //config:config HUSH_FUNCTIONS
169 //config: bool "Support funcname() { commands; } syntax"
171 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
173 //config: Enable support for shell functions in hush. +800 bytes.
175 //config:config HUSH_LOCAL
176 //config: bool "local builtin"
178 //config: depends on HUSH_FUNCTIONS
180 //config: Enable support for local variables in functions.
182 //config:config HUSH_RANDOM_SUPPORT
183 //config: bool "Pseudorandom generator and $RANDOM variable"
185 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
187 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
188 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
190 //config:config HUSH_MODE_X
191 //config: bool "Support 'hush -x' option and 'set -x' command"
193 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
195 //config: This instructs hush to print commands before execution.
196 //config: Adds ~300 bytes.
198 //config:config HUSH_EXPORT
199 //config: bool "export builtin"
201 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
203 //config: Enable export builtin in hush.
205 //config:config HUSH_EXPORT_N
206 //config: bool "Support 'export -n' option"
208 //config: depends on HUSH_EXPORT
210 //config: export -n unexports variables. It is a bash extension.
212 //config:config HUSH_HELP
213 //config: bool "help builtin"
215 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
217 //config: Enable help builtin in hush. Code size + ~1 kbyte.
219 //config:config HUSH_PRINTF
220 //config: bool "printf builtin"
222 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
224 //config: Enable printf builtin in hush.
226 //config:config HUSH_KILL
227 //config: bool "kill builtin (for kill %jobspec)"
229 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
231 //config: Enable kill builtin in hush.
233 //config:config HUSH_WAIT
234 //config: bool "wait builtin"
236 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
238 //config: Enable wait builtin in hush.
240 //config:config HUSH_TRAP
241 //config: bool "trap builtin"
243 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
245 //config: Enable trap builtin in hush.
247 //config:config HUSH_ULIMIT
248 //config: bool "ulimit builtin"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config: Enable ulimit builtin in hush.
254 //config:config HUSH_TYPE
255 //config: bool "type builtin"
257 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
259 //config: Enable type builtin in hush.
261 //config:config HUSH_READ
262 //config: bool "read builtin"
264 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266 //config: Enable read builtin in hush.
268 //config:config HUSH_SET
269 //config: bool "set builtin"
271 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
273 //config: Enable set builtin in hush.
275 //config:config HUSH_UNSET
276 //config: bool "unset builtin"
278 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
280 //config: Enable unset builtin in hush.
282 //config:config HUSH_UMASK
283 //config: bool "umask builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config: Enable umask builtin in hush.
289 //config:config HUSH_MEMLEAK
290 //config: bool "memleak builtin (debugging)"
292 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
294 //config: Enable memleak builtin in hush.
297 //config: bool "msh (deprecated: aliased to hush)"
299 //config: select HUSH
301 //config: msh is deprecated and will be removed, please migrate to hush.
303 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
304 //applet:IF_MSH(APPLET_ODDNAME(msh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
305 //applet:IF_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
306 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
308 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
309 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
310 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
311 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
313 /* -i (interactive) and -s (read stdin) are also accepted,
314 * but currently do nothing, therefore aren't shown in help.
315 * NOMMU-specific options are not meant to be used by users,
316 * therefore we don't show them either.
318 //usage:#define hush_trivial_usage
319 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
320 //usage:#define hush_full_usage "\n\n"
321 //usage: "Unix shell interpreter"
323 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
324 || defined(__APPLE__) \
326 # include <malloc.h> /* for malloc_trim */
329 /* #include <dmalloc.h> */
331 # include <fnmatch.h>
333 #include <sys/utsname.h> /* for setting $HOSTNAME */
335 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
337 #include "shell_common.h"
340 #if ENABLE_HUSH_RANDOM_SUPPORT
343 # define CLEAR_RANDOM_T(rnd) ((void)0)
345 #ifndef F_DUPFD_CLOEXEC
346 # define F_DUPFD_CLOEXEC F_DUPFD
349 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
354 #define LEAK_HUNTING 0
355 #define BUILD_AS_NOMMU 0
356 /* Enable/disable sanity checks. Ok to enable in production,
357 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
358 * Keeping 1 for now even in released versions.
361 /* Slightly bigger (+200 bytes), but faster hush.
362 * So far it only enables a trick with counting SIGCHLDs and forks,
363 * which allows us to do fewer waitpid's.
364 * (we can detect a case where neither forks were done nor SIGCHLDs happened
365 * and therefore waitpid will return the same result as last time)
367 #define ENABLE_HUSH_FAST 0
368 /* TODO: implement simplified code for users which do not need ${var%...} ops
369 * So far ${var%...} ops are always enabled:
371 #define ENABLE_HUSH_DOLLAR_OPS 1
376 # undef USE_FOR_NOMMU
379 # define USE_FOR_NOMMU(...) __VA_ARGS__
380 # define USE_FOR_MMU(...)
383 #include "NUM_APPLETS.h"
385 /* STANDALONE does not make sense, and won't compile */
386 # undef CONFIG_FEATURE_SH_STANDALONE
387 # undef ENABLE_FEATURE_SH_STANDALONE
388 # undef IF_FEATURE_SH_STANDALONE
389 # undef IF_NOT_FEATURE_SH_STANDALONE
390 # define ENABLE_FEATURE_SH_STANDALONE 0
391 # define IF_FEATURE_SH_STANDALONE(...)
392 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
395 #if !ENABLE_HUSH_INTERACTIVE
396 # undef ENABLE_FEATURE_EDITING
397 # define ENABLE_FEATURE_EDITING 0
398 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
399 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
400 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
401 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
404 /* Do we support ANY keywords? */
405 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
406 # define HAS_KEYWORDS 1
407 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
408 # define IF_HAS_NO_KEYWORDS(...)
410 # define HAS_KEYWORDS 0
411 # define IF_HAS_KEYWORDS(...)
412 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
415 /* If you comment out one of these below, it will be #defined later
416 * to perform debug printfs to stderr: */
417 #define debug_printf(...) do {} while (0)
418 /* Finer-grained debug switches */
419 #define debug_printf_parse(...) do {} while (0)
420 #define debug_print_tree(a, b) do {} while (0)
421 #define debug_printf_exec(...) do {} while (0)
422 #define debug_printf_env(...) do {} while (0)
423 #define debug_printf_jobs(...) do {} while (0)
424 #define debug_printf_expand(...) do {} while (0)
425 #define debug_printf_varexp(...) do {} while (0)
426 #define debug_printf_glob(...) do {} while (0)
427 #define debug_printf_list(...) do {} while (0)
428 #define debug_printf_subst(...) do {} while (0)
429 #define debug_printf_clean(...) do {} while (0)
431 #define ERR_PTR ((void*)(long)1)
433 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
435 #define _SPECIAL_VARS_STR "_*@$!?#"
436 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
437 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
438 #if ENABLE_HUSH_BASH_COMPAT
439 /* Support / and // replace ops */
440 /* Note that // is stored as \ in "encoded" string representation */
441 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
442 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
443 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
445 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
446 # define VAR_SUBST_OPS "%#:-=+?"
447 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
450 #define SPECIAL_VAR_SYMBOL 3
454 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
456 /* This supports saving pointers malloced in vfork child,
457 * to be freed in the parent.
460 typedef struct nommu_save_t {
462 struct variable *old_vars;
464 char **argv_from_re_execing;
477 #if ENABLE_HUSH_LOOPS
484 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
489 /* three pseudo-keywords support contrived "case" syntax: */
490 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
491 RES_MATCH , /* "word)" */
492 RES_CASE_BODY, /* "this command is inside CASE" */
499 typedef struct o_string {
501 int length; /* position where data is appended */
504 /* At least some part of the string was inside '' or "",
505 * possibly empty one: word"", wo''rd etc. */
506 smallint has_quoted_part;
507 smallint has_empty_slot;
508 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
511 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
513 /* Protect newly added chars against globbing
514 * by prepending \ to *, ?, [, \ */
515 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
518 MAYBE_ASSIGNMENT = 0,
519 DEFINITELY_ASSIGNMENT = 1,
521 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
524 /* Used for initialization: o_string foo = NULL_O_STRING; */
525 #define NULL_O_STRING { NULL }
527 #ifndef debug_printf_parse
528 static const char *const assignment_flag[] = {
530 "DEFINITELY_ASSIGNMENT",
536 typedef struct in_str {
538 #if ENABLE_HUSH_INTERACTIVE
539 smallint promptmode; /* 0: PS1, 1: PS2 */
546 /* The descrip member of this structure is only used to make
547 * debugging output pretty */
548 static const struct {
550 signed char default_fd;
553 { O_RDONLY, 0, "<" },
554 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
555 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
556 { O_CREAT|O_RDWR, 1, "<>" },
557 { O_RDONLY, 0, "<<" },
558 /* Should not be needed. Bogus default_fd helps in debugging */
559 /* { O_RDONLY, 77, "<<" }, */
562 struct redir_struct {
563 struct redir_struct *next;
564 char *rd_filename; /* filename */
565 int rd_fd; /* fd to redirect */
566 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
568 smallint rd_type; /* (enum redir_type) */
569 /* note: for heredocs, rd_filename contains heredoc delimiter,
570 * and subsequently heredoc itself; and rd_dup is a bitmask:
571 * bit 0: do we need to trim leading tabs?
572 * bit 1: is heredoc quoted (<<'delim' syntax) ?
575 typedef enum redir_type {
577 REDIRECT_OVERWRITE = 1,
580 REDIRECT_HEREDOC = 4,
581 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
584 REDIRFD_SYNTAX_ERR = -2,
585 REDIRFD_TO_FILE = -1,
586 /* otherwise, rd_fd is redirected to rd_dup */
588 HEREDOC_SKIPTABS = 1,
594 pid_t pid; /* 0 if exited */
595 int assignment_cnt; /* how many argv[i] are assignments? */
596 smallint cmd_type; /* CMD_xxx */
598 #define CMD_SUBSHELL 1
599 #if ENABLE_HUSH_BASH_COMPAT
600 /* used for "[[ EXPR ]]" */
601 # define CMD_SINGLEWORD_NOGLOB 2
603 #if ENABLE_HUSH_FUNCTIONS
604 # define CMD_FUNCDEF 3
607 smalluint cmd_exitcode;
608 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
611 char *group_as_string;
613 #if ENABLE_HUSH_FUNCTIONS
614 struct function *child_func;
615 /* This field is used to prevent a bug here:
616 * while...do f1() {a;}; f1; f1() {b;}; f1; done
617 * When we execute "f1() {a;}" cmd, we create new function and clear
618 * cmd->group, cmd->group_as_string, cmd->argv[0].
619 * When we execute "f1() {b;}", we notice that f1 exists,
620 * and that its "parent cmd" struct is still "alive",
621 * we put those fields back into cmd->xxx
622 * (struct function has ->parent_cmd ptr to facilitate that).
623 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
624 * Without this trick, loop would execute a;b;b;b;...
625 * instead of correct sequence a;b;a;b;...
626 * When command is freed, it severs the link
627 * (sets ->child_func->parent_cmd to NULL).
630 char **argv; /* command name and arguments */
631 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
632 * and on execution these are substituted with their values.
633 * Substitution can make _several_ words out of one argv[n]!
634 * Example: argv[0]=='.^C*^C.' here: echo .$*.
635 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
637 struct redir_struct *redirects; /* I/O redirections */
639 /* Is there anything in this command at all? */
640 #define IS_NULL_CMD(cmd) \
641 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
645 int num_cmds; /* total number of commands in pipe */
646 int alive_cmds; /* number of commands running (not exited) */
647 int stopped_cmds; /* number of commands alive, but stopped */
649 unsigned jobid; /* job number */
650 pid_t pgrp; /* process group ID for the job */
651 char *cmdtext; /* name of job */
653 struct command *cmds; /* array of commands in pipe */
654 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
655 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
656 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
658 typedef enum pipe_style {
664 /* Is there anything in this pipe at all? */
665 #define IS_NULL_PIPE(pi) \
666 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
668 /* This holds pointers to the various results of parsing */
669 struct parse_context {
670 /* linked list of pipes */
671 struct pipe *list_head;
672 /* last pipe (being constructed right now) */
674 /* last command in pipe (being constructed right now) */
675 struct command *command;
676 /* last redirect in command->redirects list */
677 struct redir_struct *pending_redirect;
683 smallint ctx_inverted; /* "! cmd | cmd" */
685 smallint ctx_dsemicolon; /* ";;" seen */
687 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
689 /* group we are enclosed in:
690 * example: "if pipe1; pipe2; then pipe3; fi"
691 * when we see "if" or "then", we malloc and copy current context,
692 * and make ->stack point to it. then we parse pipeN.
693 * when closing "then" / fi" / whatever is found,
694 * we move list_head into ->stack->command->group,
695 * copy ->stack into current context, and delete ->stack.
696 * (parsing of { list } and ( list ) doesn't use this method)
698 struct parse_context *stack;
702 /* On program start, environ points to initial environment.
703 * putenv adds new pointers into it, unsetenv removes them.
704 * Neither of these (de)allocates the strings.
705 * setenv allocates new strings in malloc space and does putenv,
706 * and thus setenv is unusable (leaky) for shell's purposes */
707 #define setenv(...) setenv_is_leaky_dont_use()
709 struct variable *next;
710 char *varstr; /* points to "name=" portion */
711 #if ENABLE_HUSH_LOCAL
712 unsigned func_nest_level;
714 int max_len; /* if > 0, name is part of initial env; else name is malloced */
715 smallint flg_export; /* putenv should be done on this var */
716 smallint flg_read_only;
724 #if ENABLE_HUSH_FUNCTIONS
726 struct function *next;
728 struct command *parent_cmd;
731 char *body_as_string;
737 /* set -/+o OPT support. (TODO: make it optional)
738 * bash supports the following opts:
749 * interactive-comments on
767 static const char o_opt_strings[] ALIGN1 =
770 #if ENABLE_HUSH_MODE_X
777 #if ENABLE_HUSH_MODE_X
785 struct FILE_list *next;
791 /* "Globals" within this file */
792 /* Sorted roughly by size (smaller offsets == smaller code) */
794 /* interactive_fd != 0 means we are an interactive shell.
795 * If we are, then saved_tty_pgrp can also be != 0, meaning
796 * that controlling tty is available. With saved_tty_pgrp == 0,
797 * job control still works, but terminal signals
798 * (^C, ^Z, ^Y, ^\) won't work at all, and background
799 * process groups can only be created with "cmd &".
800 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
801 * to give tty to the foreground process group,
802 * and will take it back when the group is stopped (^Z)
805 #if ENABLE_HUSH_INTERACTIVE
806 /* 'interactive_fd' is a fd# open to ctty, if we have one
807 * _AND_ if we decided to act interactively */
811 # define G_interactive_fd (G.interactive_fd)
813 # define G_interactive_fd 0
815 #if ENABLE_FEATURE_EDITING
816 line_input_t *line_input_state;
821 #if ENABLE_HUSH_RANDOM_SUPPORT
827 pid_t saved_tty_pgrp;
828 struct pipe *job_list;
829 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
831 # define G_saved_tty_pgrp 0
833 char o_opt[NUM_OPT_O];
834 #if ENABLE_HUSH_MODE_X
835 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
839 smallint flag_SIGINT;
840 #if ENABLE_HUSH_LOOPS
841 smallint flag_break_continue;
843 #if ENABLE_HUSH_FUNCTIONS
844 /* 0: outside of a function (or sourced file)
845 * -1: inside of a function, ok to use return builtin
846 * 1: return is invoked, skip all till end of func
848 smallint flag_return_in_progress;
849 # define G_flag_return_in_progress (G.flag_return_in_progress)
851 # define G_flag_return_in_progress 0
853 smallint exiting; /* used to prevent EXIT trap recursion */
854 /* These four support $?, $#, and $1 */
855 smalluint last_exitcode;
856 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
857 smalluint global_args_malloced;
858 /* how many non-NULL argv's we have. NB: $# + 1 */
862 char *argv0_for_re_execing;
864 #if ENABLE_HUSH_LOOPS
865 unsigned depth_break_continue;
866 unsigned depth_of_loop;
870 struct variable *top_var;
871 char **expanded_assignments;
872 #if ENABLE_HUSH_FUNCTIONS
873 struct function *top_func;
874 # if ENABLE_HUSH_LOCAL
875 struct variable **shadowed_vars_pp;
876 unsigned func_nest_level;
879 /* Signal and trap handling */
881 unsigned count_SIGCHLD;
882 unsigned handled_SIGCHLD;
883 smallint we_have_children;
885 struct FILE_list *FILE_list;
886 /* Which signals have non-DFL handler (even with no traps set)?
887 * Set at the start to:
888 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
889 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
890 * The rest is cleared right before execv syscalls.
891 * Other than these two times, never modified.
893 unsigned special_sig_mask;
895 unsigned fatal_sig_mask;
896 # define G_fatal_sig_mask G.fatal_sig_mask
898 # define G_fatal_sig_mask 0
901 char **traps; /* char *traps[NSIG] */
902 # define G_traps G.traps
904 # define G_traps ((char**)NULL)
906 sigset_t pending_set;
907 #if ENABLE_HUSH_MEMLEAK
908 unsigned long memleak_value;
914 #if ENABLE_FEATURE_EDITING
915 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
918 #define G (*ptr_to_globals)
919 /* Not #defining name to G.name - this quickly gets unwieldy
920 * (too many defines). Also, I actually prefer to see when a variable
921 * is global, thus "G." prefix is a useful hint */
922 #define INIT_G() do { \
923 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
924 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
925 sigfillset(&G.sa.sa_mask); \
926 G.sa.sa_flags = SA_RESTART; \
930 /* Function prototypes for builtins */
931 static int builtin_cd(char **argv) FAST_FUNC;
932 static int builtin_echo(char **argv) FAST_FUNC;
933 static int builtin_eval(char **argv) FAST_FUNC;
934 static int builtin_exec(char **argv) FAST_FUNC;
935 static int builtin_exit(char **argv) FAST_FUNC;
936 #if ENABLE_HUSH_EXPORT
937 static int builtin_export(char **argv) FAST_FUNC;
940 static int builtin_fg_bg(char **argv) FAST_FUNC;
941 static int builtin_jobs(char **argv) FAST_FUNC;
944 static int builtin_help(char **argv) FAST_FUNC;
946 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
947 static int builtin_history(char **argv) FAST_FUNC;
949 #if ENABLE_HUSH_LOCAL
950 static int builtin_local(char **argv) FAST_FUNC;
952 #if ENABLE_HUSH_MEMLEAK
953 static int builtin_memleak(char **argv) FAST_FUNC;
955 #if ENABLE_HUSH_PRINTF
956 static int builtin_printf(char **argv) FAST_FUNC;
958 static int builtin_pwd(char **argv) FAST_FUNC;
960 static int builtin_read(char **argv) FAST_FUNC;
963 static int builtin_set(char **argv) FAST_FUNC;
965 static int builtin_shift(char **argv) FAST_FUNC;
966 static int builtin_source(char **argv) FAST_FUNC;
967 static int builtin_test(char **argv) FAST_FUNC;
969 static int builtin_trap(char **argv) FAST_FUNC;
972 static int builtin_type(char **argv) FAST_FUNC;
974 static int builtin_true(char **argv) FAST_FUNC;
975 #if ENABLE_HUSH_UMASK
976 static int builtin_umask(char **argv) FAST_FUNC;
978 #if ENABLE_HUSH_UNSET
979 static int builtin_unset(char **argv) FAST_FUNC;
982 static int builtin_kill(char **argv) FAST_FUNC;
985 static int builtin_wait(char **argv) FAST_FUNC;
987 #if ENABLE_HUSH_LOOPS
988 static int builtin_break(char **argv) FAST_FUNC;
989 static int builtin_continue(char **argv) FAST_FUNC;
991 #if ENABLE_HUSH_FUNCTIONS
992 static int builtin_return(char **argv) FAST_FUNC;
995 /* Table of built-in functions. They can be forked or not, depending on
996 * context: within pipes, they fork. As simple commands, they do not.
997 * When used in non-forking context, they can change global variables
998 * in the parent shell process. If forked, of course they cannot.
999 * For example, 'unset foo | whatever' will parse and run, but foo will
1000 * still be set at the end. */
1001 struct built_in_command {
1003 int (*b_function)(char **argv) FAST_FUNC;
1004 #if ENABLE_HUSH_HELP
1005 const char *b_descr;
1006 # define BLTIN(cmd, func, help) { cmd, func, help }
1008 # define BLTIN(cmd, func, help) { cmd, func }
1012 static const struct built_in_command bltins1[] = {
1013 BLTIN("." , builtin_source , "Run commands in a file"),
1014 BLTIN(":" , builtin_true , NULL),
1016 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
1018 #if ENABLE_HUSH_LOOPS
1019 BLTIN("break" , builtin_break , "Exit from a loop"),
1021 BLTIN("cd" , builtin_cd , "Change directory"),
1022 #if ENABLE_HUSH_LOOPS
1023 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1025 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1026 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1027 BLTIN("exit" , builtin_exit , "Exit"),
1028 #if ENABLE_HUSH_EXPORT
1029 BLTIN("export" , builtin_export , "Set environment variables"),
1032 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
1034 #if ENABLE_HUSH_HELP
1035 BLTIN("help" , builtin_help , NULL),
1037 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1038 BLTIN("history" , builtin_history , "Show command history"),
1041 BLTIN("jobs" , builtin_jobs , "List jobs"),
1043 #if ENABLE_HUSH_KILL
1044 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1046 #if ENABLE_HUSH_LOCAL
1047 BLTIN("local" , builtin_local , "Set local variables"),
1049 #if ENABLE_HUSH_MEMLEAK
1050 BLTIN("memleak" , builtin_memleak , NULL),
1052 #if ENABLE_HUSH_READ
1053 BLTIN("read" , builtin_read , "Input into variable"),
1055 #if ENABLE_HUSH_FUNCTIONS
1056 BLTIN("return" , builtin_return , "Return from a function"),
1059 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
1061 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1062 #if ENABLE_HUSH_BASH_COMPAT
1063 BLTIN("source" , builtin_source , "Run commands in a file"),
1065 #if ENABLE_HUSH_TRAP
1066 BLTIN("trap" , builtin_trap , "Trap signals"),
1068 BLTIN("true" , builtin_true , NULL),
1069 #if ENABLE_HUSH_TYPE
1070 BLTIN("type" , builtin_type , "Show command type"),
1072 #if ENABLE_HUSH_ULIMIT
1073 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1075 #if ENABLE_HUSH_UMASK
1076 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1078 #if ENABLE_HUSH_UNSET
1079 BLTIN("unset" , builtin_unset , "Unset variables"),
1081 #if ENABLE_HUSH_WAIT
1082 BLTIN("wait" , builtin_wait , "Wait for process"),
1085 /* For now, echo and test are unconditionally enabled.
1086 * Maybe make it configurable? */
1087 static const struct built_in_command bltins2[] = {
1088 BLTIN("[" , builtin_test , NULL),
1089 BLTIN("echo" , builtin_echo , NULL),
1090 #if ENABLE_HUSH_PRINTF
1091 BLTIN("printf" , builtin_printf , NULL),
1093 BLTIN("pwd" , builtin_pwd , NULL),
1094 BLTIN("test" , builtin_test , NULL),
1101 /* prevent disasters with G.debug_indent < 0 */
1102 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1103 # define debug_enter() (G.debug_indent++)
1104 # define debug_leave() (G.debug_indent--)
1106 # define indent() ((void)0)
1107 # define debug_enter() ((void)0)
1108 # define debug_leave() ((void)0)
1111 #ifndef debug_printf
1112 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1115 #ifndef debug_printf_parse
1116 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1119 #ifndef debug_printf_exec
1120 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1123 #ifndef debug_printf_env
1124 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1127 #ifndef debug_printf_jobs
1128 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1129 # define DEBUG_JOBS 1
1131 # define DEBUG_JOBS 0
1134 #ifndef debug_printf_expand
1135 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1136 # define DEBUG_EXPAND 1
1138 # define DEBUG_EXPAND 0
1141 #ifndef debug_printf_varexp
1142 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1145 #ifndef debug_printf_glob
1146 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1147 # define DEBUG_GLOB 1
1149 # define DEBUG_GLOB 0
1152 #ifndef debug_printf_list
1153 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1156 #ifndef debug_printf_subst
1157 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1160 #ifndef debug_printf_clean
1161 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1162 # define DEBUG_CLEAN 1
1164 # define DEBUG_CLEAN 0
1168 static void debug_print_strings(const char *prefix, char **vv)
1171 fdprintf(2, "%s:\n", prefix);
1173 fdprintf(2, " '%s'\n", *vv++);
1176 # define debug_print_strings(prefix, vv) ((void)0)
1180 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1183 static void *xxmalloc(int lineno, size_t size)
1185 void *ptr = xmalloc((size + 0xff) & ~0xff);
1186 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1189 static void *xxrealloc(int lineno, void *ptr, size_t size)
1191 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1192 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1195 static char *xxstrdup(int lineno, const char *str)
1197 char *ptr = xstrdup(str);
1198 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1201 static void xxfree(void *ptr)
1203 fdprintf(2, "free %p\n", ptr);
1206 # define xmalloc(s) xxmalloc(__LINE__, s)
1207 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1208 # define xstrdup(s) xxstrdup(__LINE__, s)
1209 # define free(p) xxfree(p)
1213 /* Syntax and runtime errors. They always abort scripts.
1214 * In interactive use they usually discard unparsed and/or unexecuted commands
1215 * and return to the prompt.
1216 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1219 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1220 # define syntax_error(lineno, msg) syntax_error(msg)
1221 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1222 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1223 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1224 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1227 static void die_if_script(unsigned lineno, const char *fmt, ...)
1232 bb_error_msg("hush.c:%u", lineno);
1235 bb_verror_msg(fmt, p, NULL);
1237 if (!G_interactive_fd)
1241 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1244 bb_error_msg("syntax error: %s", msg);
1246 bb_error_msg("syntax error");
1249 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1251 bb_error_msg("syntax error at '%s'", msg);
1254 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1256 bb_error_msg("syntax error: unterminated %s", s);
1259 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1261 char msg[2] = { ch, '\0' };
1262 syntax_error_unterm_str(lineno, msg);
1265 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1271 bb_error_msg("hush.c:%u", lineno);
1273 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1277 # undef die_if_script
1278 # undef syntax_error
1279 # undef syntax_error_at
1280 # undef syntax_error_unterm_ch
1281 # undef syntax_error_unterm_str
1282 # undef syntax_error_unexpected_ch
1284 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1285 # define syntax_error(msg) syntax_error(__LINE__, msg)
1286 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1287 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1288 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1289 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1293 #if ENABLE_HUSH_INTERACTIVE
1294 static void cmdedit_update_prompt(void);
1296 # define cmdedit_update_prompt() ((void)0)
1300 /* Utility functions
1302 /* Replace each \x with x in place, return ptr past NUL. */
1303 static char *unbackslash(char *src)
1305 char *dst = src = strchrnul(src, '\\');
1309 if ((*dst++ = *src++) == '\0')
1315 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1336 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1337 v[count1 + count2] = NULL;
1340 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1344 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1346 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1347 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1350 #define add_strings_to_strings(strings, add, need_to_dup) \
1351 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1354 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1355 static char **add_string_to_strings(char **strings, char *add)
1360 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1363 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1365 char **ptr = add_string_to_strings(strings, add);
1366 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1369 #define add_string_to_strings(strings, add) \
1370 xx_add_string_to_strings(__LINE__, strings, add)
1373 static void free_strings(char **strings)
1388 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1390 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1391 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1393 /* fd was not open? */
1403 /* Manipulating the list of open FILEs */
1404 static FILE *remember_FILE(FILE *fp)
1407 struct FILE_list *n = xmalloc(sizeof(*n));
1408 n->next = G.FILE_list;
1412 close_on_exec_on(n->fd);
1416 static void fclose_and_forget(FILE *fp)
1418 struct FILE_list **pp = &G.FILE_list;
1420 struct FILE_list *cur = *pp;
1421 if (cur->fp == fp) {
1430 static int save_FILEs_on_redirect(int fd)
1432 struct FILE_list *fl = G.FILE_list;
1435 /* We use it only on script files, they are all CLOEXEC */
1436 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1443 static void restore_redirected_FILEs(void)
1445 struct FILE_list *fl = G.FILE_list;
1447 int should_be = fileno(fl->fp);
1448 if (fl->fd != should_be) {
1449 xmove_fd(fl->fd, should_be);
1455 #if ENABLE_FEATURE_SH_STANDALONE
1456 static void close_all_FILE_list(void)
1458 struct FILE_list *fl = G.FILE_list;
1460 /* fclose would also free FILE object.
1461 * It is disastrous if we share memory with a vforked parent.
1462 * I'm not sure we never come here after vfork.
1463 * Therefore just close fd, nothing more.
1465 /*fclose(fl->fp); - unsafe */
1473 /* Helpers for setting new $n and restoring them back
1475 typedef struct save_arg_t {
1479 smallint sv_g_malloced;
1482 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1486 sv->sv_argv0 = argv[0];
1487 sv->sv_g_argv = G.global_argv;
1488 sv->sv_g_argc = G.global_argc;
1489 sv->sv_g_malloced = G.global_args_malloced;
1491 argv[0] = G.global_argv[0]; /* retain $0 */
1492 G.global_argv = argv;
1493 G.global_args_malloced = 0;
1501 static void restore_G_args(save_arg_t *sv, char **argv)
1505 if (G.global_args_malloced) {
1506 /* someone ran "set -- arg1 arg2 ...", undo */
1508 while (*++pp) /* note: does not free $0 */
1510 free(G.global_argv);
1512 argv[0] = sv->sv_argv0;
1513 G.global_argv = sv->sv_g_argv;
1514 G.global_argc = sv->sv_g_argc;
1515 G.global_args_malloced = sv->sv_g_malloced;
1519 /* Basic theory of signal handling in shell
1520 * ========================================
1521 * This does not describe what hush does, rather, it is current understanding
1522 * what it _should_ do. If it doesn't, it's a bug.
1523 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1525 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1526 * is finished or backgrounded. It is the same in interactive and
1527 * non-interactive shells, and is the same regardless of whether
1528 * a user trap handler is installed or a shell special one is in effect.
1529 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1530 * backgrounds (i.e. stops) or kills all members of currently running
1533 * Wait builtin is interruptible by signals for which user trap is set
1534 * or by SIGINT in interactive shell.
1536 * Trap handlers will execute even within trap handlers. (right?)
1538 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1539 * except for handlers set to '' (empty string).
1541 * If job control is off, backgrounded commands ("cmd &")
1542 * have SIGINT, SIGQUIT set to SIG_IGN.
1544 * Commands which are run in command substitution ("`cmd`")
1545 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1547 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1548 * by the shell from its parent.
1550 * Signals which differ from SIG_DFL action
1551 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1554 * SIGTERM (interactive): ignore
1555 * SIGHUP (interactive):
1556 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1557 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1558 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1559 * that all pipe members are stopped. Try this in bash:
1560 * while :; do :; done - ^Z does not background it
1561 * (while :; do :; done) - ^Z backgrounds it
1562 * SIGINT (interactive): wait for last pipe, ignore the rest
1563 * of the command line, show prompt. NB: ^C does not send SIGINT
1564 * to interactive shell while shell is waiting for a pipe,
1565 * since shell is bg'ed (is not in foreground process group).
1566 * Example 1: this waits 5 sec, but does not execute ls:
1567 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1568 * Example 2: this does not wait and does not execute ls:
1569 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1570 * Example 3: this does not wait 5 sec, but executes ls:
1571 * "sleep 5; ls -l" + press ^C
1572 * Example 4: this does not wait and does not execute ls:
1573 * "sleep 5 & wait; ls -l" + press ^C
1575 * (What happens to signals which are IGN on shell start?)
1576 * (What happens with signal mask on shell start?)
1578 * Old implementation
1579 * ==================
1580 * We use in-kernel pending signal mask to determine which signals were sent.
1581 * We block all signals which we don't want to take action immediately,
1582 * i.e. we block all signals which need to have special handling as described
1583 * above, and all signals which have traps set.
1584 * After each pipe execution, we extract any pending signals via sigtimedwait()
1587 * unsigned special_sig_mask: a mask of such "special" signals
1588 * sigset_t blocked_set: current blocked signal set
1591 * clear bit in blocked_set unless it is also in special_sig_mask
1592 * "trap 'cmd' SIGxxx":
1593 * set bit in blocked_set (even if 'cmd' is '')
1594 * after [v]fork, if we plan to be a shell:
1595 * unblock signals with special interactive handling
1596 * (child shell is not interactive),
1597 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1598 * after [v]fork, if we plan to exec:
1599 * POSIX says fork clears pending signal mask in child - no need to clear it.
1600 * Restore blocked signal set to one inherited by shell just prior to exec.
1602 * Note: as a result, we do not use signal handlers much. The only uses
1603 * are to count SIGCHLDs
1604 * and to restore tty pgrp on signal-induced exit.
1607 * Standard says "When a subshell is entered, traps that are not being ignored
1608 * are set to the default actions". bash interprets it so that traps which
1609 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1611 * Problem: the above approach makes it unwieldy to catch signals while
1612 * we are in read builtin, or while we read commands from stdin:
1613 * masked signals are not visible!
1615 * New implementation
1616 * ==================
1617 * We record each signal we are interested in by installing signal handler
1618 * for them - a bit like emulating kernel pending signal mask in userspace.
1619 * We are interested in: signals which need to have special handling
1620 * as described above, and all signals which have traps set.
1621 * Signals are recorded in pending_set.
1622 * After each pipe execution, we extract any pending signals
1625 * unsigned special_sig_mask: a mask of shell-special signals.
1626 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1627 * char *traps[sig] if trap for sig is set (even if it's '').
1628 * sigset_t pending_set: set of sigs we received.
1631 * if sig is in special_sig_mask, set handler back to:
1632 * record_pending_signo, or to IGN if it's a tty stop signal
1633 * if sig is in fatal_sig_mask, set handler back to sigexit.
1634 * else: set handler back to SIG_DFL
1635 * "trap 'cmd' SIGxxx":
1636 * set handler to record_pending_signo.
1638 * set handler to SIG_IGN.
1639 * after [v]fork, if we plan to be a shell:
1640 * set signals with special interactive handling to SIG_DFL
1641 * (because child shell is not interactive),
1642 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1643 * after [v]fork, if we plan to exec:
1644 * POSIX says fork clears pending signal mask in child - no need to clear it.
1646 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1647 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1650 * Standard says "When a subshell is entered, traps that are not being ignored
1651 * are set to the default actions". bash interprets it so that traps which
1652 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1655 SPECIAL_INTERACTIVE_SIGS = 0
1660 SPECIAL_JOBSTOP_SIGS = 0
1669 static void record_pending_signo(int sig)
1671 sigaddset(&G.pending_set, sig);
1672 #if ENABLE_HUSH_FAST
1673 if (sig == SIGCHLD) {
1675 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1680 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1682 struct sigaction old_sa;
1684 /* We could use signal() to install handlers... almost:
1685 * except that we need to mask ALL signals while handlers run.
1686 * I saw signal nesting in strace, race window isn't small.
1687 * SA_RESTART is also needed, but in Linux, signal()
1688 * sets SA_RESTART too.
1690 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1691 /* sigfillset(&G.sa.sa_mask); - already done */
1692 /* G.sa.sa_flags = SA_RESTART; - already done */
1693 G.sa.sa_handler = handler;
1694 sigaction(sig, &G.sa, &old_sa);
1695 return old_sa.sa_handler;
1698 static void hush_exit(int exitcode) NORETURN;
1700 static void restore_ttypgrp_and__exit(void) NORETURN;
1701 static void restore_ttypgrp_and__exit(void)
1703 /* xfunc has failed! die die die */
1704 /* no EXIT traps, this is an escape hatch! */
1706 hush_exit(xfunc_error_retval);
1711 /* Needed only on some libc:
1712 * It was observed that on exit(), fgetc'ed buffered data
1713 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1714 * With the net effect that even after fork(), not vfork(),
1715 * exit() in NOEXECed applet in "sh SCRIPT":
1716 * noexec_applet_here
1717 * echo END_OF_SCRIPT
1718 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1719 * This makes "echo END_OF_SCRIPT" executed twice.
1720 * Similar problems can be seen with die_if_script() -> xfunc_die()
1721 * and in `cmd` handling.
1722 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1724 static void fflush_and__exit(void) NORETURN;
1725 static void fflush_and__exit(void)
1728 _exit(xfunc_error_retval);
1731 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1732 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1733 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1734 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1736 /* Restores tty foreground process group, and exits.
1737 * May be called as signal handler for fatal signal
1738 * (will resend signal to itself, producing correct exit state)
1739 * or called directly with -EXITCODE.
1740 * We also call it if xfunc is exiting.
1742 static void sigexit(int sig) NORETURN;
1743 static void sigexit(int sig)
1745 /* Careful: we can end up here after [v]fork. Do not restore
1746 * tty pgrp then, only top-level shell process does that */
1747 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1748 /* Disable all signals: job control, SIGPIPE, etc.
1749 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1751 sigprocmask_allsigs(SIG_BLOCK);
1752 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1755 /* Not a signal, just exit */
1759 kill_myself_with_sig(sig); /* does not return */
1763 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1764 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1768 static sighandler_t pick_sighandler(unsigned sig)
1770 sighandler_t handler = SIG_DFL;
1771 if (sig < sizeof(unsigned)*8) {
1772 unsigned sigmask = (1 << sig);
1776 if (G_fatal_sig_mask & sigmask)
1780 /* sig has special handling? */
1781 if (G.special_sig_mask & sigmask) {
1782 handler = record_pending_signo;
1783 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1784 * in order to ignore them: they will be raised
1785 * in an endless loop when we try to do some
1786 * terminal ioctls! We do have to _ignore_ these.
1788 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1795 /* Restores tty foreground process group, and exits. */
1796 static void hush_exit(int exitcode)
1798 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1799 save_history(G.line_input_state);
1803 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1805 /* argv[0] is unused */
1806 argv[1] = G_traps[0];
1808 G.exiting = 1; /* prevent EXIT trap recursion */
1809 /* Note: G_traps[0] is not cleared!
1810 * "trap" will still show it, if executed
1815 #if ENABLE_FEATURE_CLEAN_UP
1817 struct variable *cur_var;
1818 if (G.cwd != bb_msg_unknown)
1820 cur_var = G.top_var;
1822 struct variable *tmp = cur_var;
1823 if (!cur_var->max_len)
1824 free(cur_var->varstr);
1825 cur_var = cur_var->next;
1833 sigexit(- (exitcode & 0xff));
1840 //TODO: return a mask of ALL handled sigs?
1841 static int check_and_run_traps(void)
1848 if (sigisemptyset(&G.pending_set))
1853 if (sigismember(&G.pending_set, sig)) {
1854 sigdelset(&G.pending_set, sig);
1857 } while (sig < NSIG);
1860 if (G_traps && G_traps[sig]) {
1861 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1862 if (G_traps[sig][0]) {
1863 /* We have user-defined handler */
1864 smalluint save_rcode;
1866 /* argv[0] is unused */
1867 argv[1] = G_traps[sig];
1869 save_rcode = G.last_exitcode;
1871 //FIXME: shouldn't it be set to 128 + sig instead?
1872 G.last_exitcode = save_rcode;
1874 } /* else: "" trap, ignoring signal */
1877 /* not a trap: special action */
1880 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1887 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1888 /* bash is observed to signal whole process groups,
1889 * not individual processes */
1890 for (job = G.job_list; job; job = job->next) {
1893 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1894 if (kill(- job->pgrp, SIGHUP) == 0)
1895 kill(- job->pgrp, SIGCONT);
1900 #if ENABLE_HUSH_FAST
1902 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1904 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1906 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1907 * This simplifies wait builtin a bit.
1911 default: /* ignored: */
1912 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1913 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1915 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1916 * Example: wait is not interrupted by TERM
1917 * in interactive shell, because TERM is ignored.
1926 static const char *get_cwd(int force)
1928 if (force || G.cwd == NULL) {
1929 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1930 * we must not try to free(bb_msg_unknown) */
1931 if (G.cwd == bb_msg_unknown)
1933 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1935 G.cwd = bb_msg_unknown;
1942 * Shell and environment variable support
1944 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1946 struct variable **pp;
1947 struct variable *cur;
1950 while ((cur = *pp) != NULL) {
1951 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1958 static const char* FAST_FUNC get_local_var_value(const char *name)
1960 struct variable **vpp;
1961 unsigned len = strlen(name);
1963 if (G.expanded_assignments) {
1964 char **cpp = G.expanded_assignments;
1967 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1968 return cp + len + 1;
1973 vpp = get_ptr_to_local_var(name, len);
1975 return (*vpp)->varstr + len + 1;
1977 if (strcmp(name, "PPID") == 0)
1978 return utoa(G.root_ppid);
1979 // bash compat: UID? EUID?
1980 #if ENABLE_HUSH_RANDOM_SUPPORT
1981 if (strcmp(name, "RANDOM") == 0)
1982 return utoa(next_random(&G.random_gen));
1987 /* str holds "NAME=VAL" and is expected to be malloced.
1988 * We take ownership of it.
1990 * 0: do not change export flag
1991 * (if creating new variable, flag will be 0)
1992 * 1: set export flag and putenv the variable
1993 * -1: clear export flag and unsetenv the variable
1994 * flg_read_only is set only when we handle -R var=val
1996 #if !BB_MMU && ENABLE_HUSH_LOCAL
1997 /* all params are used */
1998 #elif BB_MMU && ENABLE_HUSH_LOCAL
1999 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2000 set_local_var(str, flg_export, local_lvl)
2001 #elif BB_MMU && !ENABLE_HUSH_LOCAL
2002 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2003 set_local_var(str, flg_export)
2004 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
2005 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2006 set_local_var(str, flg_export, flg_read_only)
2008 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
2010 struct variable **var_pp;
2011 struct variable *cur;
2012 char *free_me = NULL;
2016 eq_sign = strchr(str, '=');
2017 if (!eq_sign) { /* not expected to ever happen? */
2022 name_len = eq_sign - str + 1; /* including '=' */
2023 var_pp = &G.top_var;
2024 while ((cur = *var_pp) != NULL) {
2025 if (strncmp(cur->varstr, str, name_len) != 0) {
2026 var_pp = &cur->next;
2030 /* We found an existing var with this name */
2031 if (cur->flg_read_only) {
2035 bb_error_msg("%s: readonly variable", str);
2039 if (flg_export == -1) { // "&& cur->flg_export" ?
2040 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2045 #if ENABLE_HUSH_LOCAL
2046 if (cur->func_nest_level < local_lvl) {
2047 /* New variable is declared as local,
2048 * and existing one is global, or local
2049 * from enclosing function.
2050 * Remove and save old one: */
2051 *var_pp = cur->next;
2052 cur->next = *G.shadowed_vars_pp;
2053 *G.shadowed_vars_pp = cur;
2054 /* bash 3.2.33(1) and exported vars:
2056 * # f() { local z=a; env | grep ^z; }
2062 if (cur->flg_export)
2067 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2072 if (cur->max_len != 0) {
2073 if (cur->max_len >= strlen(str)) {
2074 /* This one is from startup env, reuse space */
2075 strcpy(cur->varstr, str);
2080 goto set_str_and_exp;
2082 /* max_len == 0 signifies "malloced" var, which we can
2083 * (and have to) free. But we can't free(cur->varstr) here:
2084 * if cur->flg_export is 1, it is in the environment.
2085 * We should either unsetenv+free, or wait until putenv,
2086 * then putenv(new)+free(old).
2088 free_me = cur->varstr;
2089 goto set_str_and_exp;
2092 /* Not found - create new variable struct */
2093 cur = xzalloc(sizeof(*cur));
2094 #if ENABLE_HUSH_LOCAL
2095 cur->func_nest_level = local_lvl;
2097 cur->next = *var_pp;
2103 cur->flg_read_only = flg_read_only;
2106 if (flg_export == 1)
2107 cur->flg_export = 1;
2108 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2109 cmdedit_update_prompt();
2110 if (cur->flg_export) {
2111 if (flg_export == -1) {
2112 cur->flg_export = 0;
2113 /* unsetenv was already done */
2116 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2117 i = putenv(cur->varstr);
2118 /* only now we can free old exported malloced string */
2127 /* Used at startup and after each cd */
2128 static void set_pwd_var(int exp)
2130 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2131 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2134 static int unset_local_var_len(const char *name, int name_len)
2136 struct variable *cur;
2137 struct variable **var_pp;
2140 return EXIT_SUCCESS;
2141 var_pp = &G.top_var;
2142 while ((cur = *var_pp) != NULL) {
2143 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2144 if (cur->flg_read_only) {
2145 bb_error_msg("%s: readonly variable", name);
2146 return EXIT_FAILURE;
2148 *var_pp = cur->next;
2149 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2150 bb_unsetenv(cur->varstr);
2151 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2152 cmdedit_update_prompt();
2156 return EXIT_SUCCESS;
2158 var_pp = &cur->next;
2160 return EXIT_SUCCESS;
2163 #if ENABLE_HUSH_UNSET
2164 static int unset_local_var(const char *name)
2166 return unset_local_var_len(name, strlen(name));
2170 static void unset_vars(char **strings)
2178 const char *eq = strchrnul(*v, '=');
2179 unset_local_var_len(*v, (int)(eq - *v));
2185 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_BASH_COMPAT || ENABLE_HUSH_READ
2186 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2188 char *var = xasprintf("%s=%s", name, val);
2189 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2195 * Helpers for "var1=val1 var2=val2 cmd" feature
2197 static void add_vars(struct variable *var)
2199 struct variable *next;
2203 var->next = G.top_var;
2205 if (var->flg_export) {
2206 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2207 putenv(var->varstr);
2209 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2215 static struct variable *set_vars_and_save_old(char **strings)
2218 struct variable *old = NULL;
2224 struct variable *var_p;
2225 struct variable **var_pp;
2228 eq = strchr(*s, '=');
2230 var_pp = get_ptr_to_local_var(*s, eq - *s);
2232 /* Remove variable from global linked list */
2234 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2235 *var_pp = var_p->next;
2236 /* Add it to returned list */
2240 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2251 static void reinit_unicode_for_hush(void)
2253 /* Unicode support should be activated even if LANG is set
2254 * _during_ shell execution, not only if it was set when
2255 * shell was started. Therefore, re-check LANG every time:
2257 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2258 || ENABLE_UNICODE_USING_LOCALE
2260 const char *s = get_local_var_value("LC_ALL");
2261 if (!s) s = get_local_var_value("LC_CTYPE");
2262 if (!s) s = get_local_var_value("LANG");
2268 * in_str support (strings, and "strings" read from files).
2271 #if ENABLE_HUSH_INTERACTIVE
2272 /* To test correct lineedit/interactive behavior, type from command line:
2278 * It excercises a lot of corner cases.
2280 static void cmdedit_update_prompt(void)
2282 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2283 G.PS1 = get_local_var_value("PS1");
2286 G.PS2 = get_local_var_value("PS2");
2293 static const char *setup_prompt_string(int promptmode)
2295 const char *prompt_str;
2296 debug_printf("setup_prompt_string %d ", promptmode);
2297 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2298 /* Set up the prompt */
2299 if (promptmode == 0) { /* PS1 */
2301 /* bash uses $PWD value, even if it is set by user.
2302 * It uses current dir only if PWD is unset.
2303 * We always use current dir. */
2304 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2309 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2310 debug_printf("prompt_str '%s'\n", prompt_str);
2313 static int get_user_input(struct in_str *i)
2316 const char *prompt_str;
2318 prompt_str = setup_prompt_string(i->promptmode);
2319 # if ENABLE_FEATURE_EDITING
2321 reinit_unicode_for_hush();
2322 if (G.flag_SIGINT) {
2323 /* There was ^C'ed, make it look prettier: */
2327 /* buglet: SIGINT will not make new prompt to appear _at once_,
2328 * only after <Enter>. (^C works immediately) */
2329 r = read_line_input(G.line_input_state, prompt_str,
2330 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2333 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2335 write(STDOUT_FILENO, "^C", 2);
2338 check_and_run_traps();
2339 if (r != 0 && !G.flag_SIGINT)
2341 /* ^C or SIGINT: repeat */
2342 G.last_exitcode = 128 + SIGINT;
2345 /* EOF/error detected */
2347 i->peek_buf[0] = r = EOF;
2350 i->p = G.user_input_buf;
2351 return (unsigned char)*i->p++;
2355 if (i->last_char == '\0' || i->last_char == '\n') {
2356 /* Why check_and_run_traps here? Try this interactively:
2357 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2358 * $ <[enter], repeatedly...>
2359 * Without check_and_run_traps, handler never runs.
2361 check_and_run_traps();
2362 fputs(prompt_str, stdout);
2365 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2367 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2368 * no ^C masking happens during fgetc, no special code for ^C:
2369 * it generates SIGINT as usual.
2371 check_and_run_traps();
2373 G.last_exitcode = 128 + SIGINT;
2380 /* This is the magic location that prints prompts
2381 * and gets data back from the user */
2382 static int fgetc_interactive(struct in_str *i)
2385 /* If it's interactive stdin, get new line. */
2386 if (G_interactive_fd && i->file == stdin) {
2387 /* Returns first char (or EOF), the rest is in i->p[] */
2388 ch = get_user_input(i);
2389 i->promptmode = 1; /* PS2 */
2391 /* Not stdin: script file, sourced file, etc */
2392 do ch = fgetc(i->file); while (ch == '\0');
2397 static inline int fgetc_interactive(struct in_str *i)
2400 do ch = fgetc(i->file); while (ch == '\0');
2403 #endif /* INTERACTIVE */
2405 static int i_getch(struct in_str *i)
2410 /* string-based in_str */
2411 ch = (unsigned char)*i->p;
2420 /* FILE-based in_str */
2422 #if ENABLE_FEATURE_EDITING
2423 /* This can be stdin, check line editing char[] buffer */
2424 if (i->p && *i->p != '\0') {
2425 ch = (unsigned char)*i->p++;
2429 /* peek_buf[] is an int array, not char. Can contain EOF. */
2430 ch = i->peek_buf[0];
2432 int ch2 = i->peek_buf[1];
2433 i->peek_buf[0] = ch2;
2434 if (ch2 == 0) /* very likely, avoid redundant write */
2440 ch = fgetc_interactive(i);
2442 debug_printf("file_get: got '%c' %d\n", ch, ch);
2447 static int i_peek(struct in_str *i)
2452 /* string-based in_str */
2453 /* Doesn't report EOF on NUL. None of the callers care. */
2454 return (unsigned char)*i->p;
2457 /* FILE-based in_str */
2459 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2460 /* This can be stdin, check line editing char[] buffer */
2461 if (i->p && *i->p != '\0')
2462 return (unsigned char)*i->p;
2464 /* peek_buf[] is an int array, not char. Can contain EOF. */
2465 ch = i->peek_buf[0];
2469 /* Need to get a new char */
2470 ch = fgetc_interactive(i);
2471 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2473 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2474 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2480 i->peek_buf[0] = ch;
2481 /*i->peek_buf[1] = 0; - already is */
2485 /* Only ever called if i_peek() was called, and did not return EOF.
2486 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2487 * not end-of-line. Therefore we never need to read a new editing line here.
2489 static int i_peek2(struct in_str *i)
2493 /* There are two cases when i->p[] buffer exists.
2494 * (1) it's a string in_str.
2495 * (2) It's a file, and we have a saved line editing buffer.
2496 * In both cases, we know that i->p[0] exists and not NUL, and
2497 * the peek2 result is in i->p[1].
2500 return (unsigned char)i->p[1];
2502 /* Now we know it is a file-based in_str. */
2504 /* peek_buf[] is an int array, not char. Can contain EOF. */
2505 /* Is there 2nd char? */
2506 ch = i->peek_buf[1];
2508 /* We did not read it yet, get it now */
2509 do ch = fgetc(i->file); while (ch == '\0');
2510 i->peek_buf[1] = ch;
2513 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2517 static void setup_file_in_str(struct in_str *i, FILE *f)
2519 memset(i, 0, sizeof(*i));
2520 /* i->promptmode = 0; - PS1 (memset did it) */
2525 static void setup_string_in_str(struct in_str *i, const char *s)
2527 memset(i, 0, sizeof(*i));
2528 /* i->promptmode = 0; - PS1 (memset did it) */
2529 /*i->file = NULL */;
2537 #define B_CHUNK (32 * sizeof(char*))
2539 static void o_reset_to_empty_unquoted(o_string *o)
2542 o->has_quoted_part = 0;
2547 static void o_free(o_string *o)
2550 memset(o, 0, sizeof(*o));
2553 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2558 static void o_grow_by(o_string *o, int len)
2560 if (o->length + len > o->maxlen) {
2561 o->maxlen += (2 * len) | (B_CHUNK-1);
2562 o->data = xrealloc(o->data, 1 + o->maxlen);
2566 static void o_addchr(o_string *o, int ch)
2568 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2569 if (o->length < o->maxlen) {
2570 /* likely. avoid o_grow_by() call */
2572 o->data[o->length] = ch;
2574 o->data[o->length] = '\0';
2582 /* Valid only if we know o_string is not empty */
2583 static void o_delchr(o_string *o)
2586 o->data[o->length] = '\0';
2590 static void o_addblock(o_string *o, const char *str, int len)
2593 memcpy(&o->data[o->length], str, len);
2595 o->data[o->length] = '\0';
2598 static void o_addstr(o_string *o, const char *str)
2600 o_addblock(o, str, strlen(str));
2604 static void nommu_addchr(o_string *o, int ch)
2610 # define nommu_addchr(o, str) ((void)0)
2613 static void o_addstr_with_NUL(o_string *o, const char *str)
2615 o_addblock(o, str, strlen(str) + 1);
2619 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2620 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2621 * Apparently, on unquoted $v bash still does globbing
2622 * ("v='*.txt'; echo $v" prints all .txt files),
2623 * but NOT brace expansion! Thus, there should be TWO independent
2624 * quoting mechanisms on $v expansion side: one protects
2625 * $v from brace expansion, and other additionally protects "$v" against globbing.
2626 * We have only second one.
2629 #if ENABLE_HUSH_BRACE_EXPANSION
2630 # define MAYBE_BRACES "{}"
2632 # define MAYBE_BRACES ""
2635 /* My analysis of quoting semantics tells me that state information
2636 * is associated with a destination, not a source.
2638 static void o_addqchr(o_string *o, int ch)
2641 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2646 o->data[o->length] = '\\';
2649 o->data[o->length] = ch;
2651 o->data[o->length] = '\0';
2654 static void o_addQchr(o_string *o, int ch)
2657 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2658 && strchr("*?[\\" MAYBE_BRACES, ch)
2661 o->data[o->length] = '\\';
2665 o->data[o->length] = ch;
2667 o->data[o->length] = '\0';
2670 static void o_addqblock(o_string *o, const char *str, int len)
2675 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2676 if (ordinary_cnt > len) /* paranoia */
2678 o_addblock(o, str, ordinary_cnt);
2679 if (ordinary_cnt == len)
2680 return; /* NUL is already added by o_addblock */
2681 str += ordinary_cnt;
2682 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2686 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2688 o->data[o->length] = '\\';
2692 o->data[o->length] = ch;
2695 o->data[o->length] = '\0';
2698 static void o_addQblock(o_string *o, const char *str, int len)
2700 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2701 o_addblock(o, str, len);
2704 o_addqblock(o, str, len);
2707 static void o_addQstr(o_string *o, const char *str)
2709 o_addQblock(o, str, strlen(str));
2712 /* A special kind of o_string for $VAR and `cmd` expansion.
2713 * It contains char* list[] at the beginning, which is grown in 16 element
2714 * increments. Actual string data starts at the next multiple of 16 * (char*).
2715 * list[i] contains an INDEX (int!) into this string data.
2716 * It means that if list[] needs to grow, data needs to be moved higher up
2717 * but list[i]'s need not be modified.
2718 * NB: remembering how many list[i]'s you have there is crucial.
2719 * o_finalize_list() operation post-processes this structure - calculates
2720 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2722 #if DEBUG_EXPAND || DEBUG_GLOB
2723 static void debug_print_list(const char *prefix, o_string *o, int n)
2725 char **list = (char**)o->data;
2726 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2730 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2731 prefix, list, n, string_start, o->length, o->maxlen,
2732 !!(o->o_expflags & EXP_FLAG_GLOB),
2734 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2737 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2738 o->data + (int)(uintptr_t)list[i] + string_start,
2739 o->data + (int)(uintptr_t)list[i] + string_start);
2743 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2745 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2749 # define debug_print_list(prefix, o, n) ((void)0)
2752 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2753 * in list[n] so that it points past last stored byte so far.
2754 * It returns n+1. */
2755 static int o_save_ptr_helper(o_string *o, int n)
2757 char **list = (char**)o->data;
2761 if (!o->has_empty_slot) {
2762 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2763 string_len = o->length - string_start;
2764 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2765 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2766 /* list[n] points to string_start, make space for 16 more pointers */
2767 o->maxlen += 0x10 * sizeof(list[0]);
2768 o->data = xrealloc(o->data, o->maxlen + 1);
2769 list = (char**)o->data;
2770 memmove(list + n + 0x10, list + n, string_len);
2771 o->length += 0x10 * sizeof(list[0]);
2773 debug_printf_list("list[%d]=%d string_start=%d\n",
2774 n, string_len, string_start);
2777 /* We have empty slot at list[n], reuse without growth */
2778 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2779 string_len = o->length - string_start;
2780 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2781 n, string_len, string_start);
2782 o->has_empty_slot = 0;
2784 o->has_quoted_part = 0;
2785 list[n] = (char*)(uintptr_t)string_len;
2789 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2790 static int o_get_last_ptr(o_string *o, int n)
2792 char **list = (char**)o->data;
2793 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2795 return ((int)(uintptr_t)list[n-1]) + string_start;
2798 #if ENABLE_HUSH_BRACE_EXPANSION
2799 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2800 * first, it processes even {a} (no commas), second,
2801 * I didn't manage to make it return strings when they don't match
2802 * existing files. Need to re-implement it.
2806 static int glob_needed(const char *s)
2815 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2821 /* Return pointer to next closing brace or to comma */
2822 static const char *next_brace_sub(const char *cp)
2826 while (*cp != '\0') {
2833 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2839 return *cp != '\0' ? cp : NULL;
2841 /* Recursive brace globber. Note: may garble pattern[]. */
2842 static int glob_brace(char *pattern, o_string *o, int n)
2844 char *new_pattern_buf;
2851 debug_printf_glob("glob_brace('%s')\n", pattern);
2857 if (*begin == '{') {
2858 /* Find the first sub-pattern and at the same time
2859 * find the rest after the closing brace */
2860 next = next_brace_sub(begin);
2862 /* An illegal expression */
2866 /* "{abc}" with no commas - illegal
2867 * brace expr, disregard and skip it */
2873 if (*begin == '\\' && begin[1] != '\0')
2877 debug_printf_glob("begin:%s\n", begin);
2878 debug_printf_glob("next:%s\n", next);
2880 /* Now find the end of the whole brace expression */
2882 while (*rest != '}') {
2883 rest = next_brace_sub(rest);
2885 /* An illegal expression */
2888 debug_printf_glob("rest:%s\n", rest);
2890 rest_len = strlen(++rest) + 1;
2892 /* We are sure the brace expression is well-formed */
2894 /* Allocate working buffer large enough for our work */
2895 new_pattern_buf = xmalloc(strlen(pattern));
2897 /* We have a brace expression. BEGIN points to the opening {,
2898 * NEXT points past the terminator of the first element, and REST
2899 * points past the final }. We will accumulate result names from
2900 * recursive runs for each brace alternative in the buffer using
2905 /* Construct the new glob expression */
2908 mempcpy(new_pattern_buf,
2909 /* We know the prefix for all sub-patterns */
2910 pattern, begin - pattern),
2914 /* Note: glob_brace() may garble new_pattern_buf[].
2915 * That's why we re-copy prefix every time (1st memcpy above).
2917 n = glob_brace(new_pattern_buf, o, n);
2919 /* We saw the last entry */
2923 next = next_brace_sub(next);
2925 free(new_pattern_buf);
2933 memset(&globdata, 0, sizeof(globdata));
2934 gr = glob(pattern, 0, NULL, &globdata);
2935 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2937 if (gr == GLOB_NOMATCH) {
2938 globfree(&globdata);
2939 /* NB: garbles parameter */
2940 unbackslash(pattern);
2941 o_addstr_with_NUL(o, pattern);
2942 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2943 return o_save_ptr_helper(o, n);
2945 if (gr == GLOB_NOSPACE)
2946 bb_error_msg_and_die(bb_msg_memory_exhausted);
2947 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2948 * but we didn't specify it. Paranoia again. */
2949 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2951 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2952 char **argv = globdata.gl_pathv;
2954 o_addstr_with_NUL(o, *argv);
2955 n = o_save_ptr_helper(o, n);
2961 globfree(&globdata);
2965 /* Performs globbing on last list[],
2966 * saving each result as a new list[].
2968 static int perform_glob(o_string *o, int n)
2970 char *pattern, *copy;
2972 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2974 return o_save_ptr_helper(o, n);
2975 pattern = o->data + o_get_last_ptr(o, n);
2976 debug_printf_glob("glob pattern '%s'\n", pattern);
2977 if (!glob_needed(pattern)) {
2978 /* unbackslash last string in o in place, fix length */
2979 o->length = unbackslash(pattern) - o->data;
2980 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2981 return o_save_ptr_helper(o, n);
2984 copy = xstrdup(pattern);
2985 /* "forget" pattern in o */
2986 o->length = pattern - o->data;
2987 n = glob_brace(copy, o, n);
2990 debug_print_list("perform_glob returning", o, n);
2994 #else /* !HUSH_BRACE_EXPANSION */
2997 static int glob_needed(const char *s)
3006 if (*s == '*' || *s == '[' || *s == '?')
3012 /* Performs globbing on last list[],
3013 * saving each result as a new list[].
3015 static int perform_glob(o_string *o, int n)
3021 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3023 return o_save_ptr_helper(o, n);
3024 pattern = o->data + o_get_last_ptr(o, n);
3025 debug_printf_glob("glob pattern '%s'\n", pattern);
3026 if (!glob_needed(pattern)) {
3028 /* unbackslash last string in o in place, fix length */
3029 o->length = unbackslash(pattern) - o->data;
3030 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3031 return o_save_ptr_helper(o, n);
3034 memset(&globdata, 0, sizeof(globdata));
3035 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3036 * If we glob "*.\*" and don't find anything, we need
3037 * to fall back to using literal "*.*", but GLOB_NOCHECK
3038 * will return "*.\*"!
3040 gr = glob(pattern, 0, NULL, &globdata);
3041 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3043 if (gr == GLOB_NOMATCH) {
3044 globfree(&globdata);
3047 if (gr == GLOB_NOSPACE)
3048 bb_error_msg_and_die(bb_msg_memory_exhausted);
3049 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3050 * but we didn't specify it. Paranoia again. */
3051 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3053 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3054 char **argv = globdata.gl_pathv;
3055 /* "forget" pattern in o */
3056 o->length = pattern - o->data;
3058 o_addstr_with_NUL(o, *argv);
3059 n = o_save_ptr_helper(o, n);
3065 globfree(&globdata);
3067 debug_print_list("perform_glob returning", o, n);
3071 #endif /* !HUSH_BRACE_EXPANSION */
3073 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3074 * Otherwise, just finish current list[] and start new */
3075 static int o_save_ptr(o_string *o, int n)
3077 if (o->o_expflags & EXP_FLAG_GLOB) {
3078 /* If o->has_empty_slot, list[n] was already globbed
3079 * (if it was requested back then when it was filled)
3080 * so don't do that again! */
3081 if (!o->has_empty_slot)
3082 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3084 return o_save_ptr_helper(o, n);
3087 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3088 static char **o_finalize_list(o_string *o, int n)
3093 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3095 debug_print_list("finalized", o, n);
3096 debug_printf_expand("finalized n:%d\n", n);
3097 list = (char**)o->data;
3098 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3102 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3107 static void free_pipe_list(struct pipe *pi);
3109 /* Returns pi->next - next pipe in the list */
3110 static struct pipe *free_pipe(struct pipe *pi)
3115 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3116 for (i = 0; i < pi->num_cmds; i++) {
3117 struct command *command;
3118 struct redir_struct *r, *rnext;
3120 command = &pi->cmds[i];
3121 debug_printf_clean(" command %d:\n", i);
3122 if (command->argv) {
3126 for (a = 0, p = command->argv; *p; a++, p++) {
3127 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3130 free_strings(command->argv);
3131 //command->argv = NULL;
3133 /* not "else if": on syntax error, we may have both! */
3134 if (command->group) {
3135 debug_printf_clean(" begin group (cmd_type:%d)\n",
3137 free_pipe_list(command->group);
3138 debug_printf_clean(" end group\n");
3139 //command->group = NULL;
3141 /* else is crucial here.
3142 * If group != NULL, child_func is meaningless */
3143 #if ENABLE_HUSH_FUNCTIONS
3144 else if (command->child_func) {
3145 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3146 command->child_func->parent_cmd = NULL;
3150 free(command->group_as_string);
3151 //command->group_as_string = NULL;
3153 for (r = command->redirects; r; r = rnext) {
3154 debug_printf_clean(" redirect %d%s",
3155 r->rd_fd, redir_table[r->rd_type].descrip);
3156 /* guard against the case >$FOO, where foo is unset or blank */
3157 if (r->rd_filename) {
3158 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3159 free(r->rd_filename);
3160 //r->rd_filename = NULL;
3162 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3166 //command->redirects = NULL;
3168 free(pi->cmds); /* children are an array, they get freed all at once */
3172 //pi->cmdtext = NULL;
3180 static void free_pipe_list(struct pipe *pi)
3184 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3186 debug_printf_clean("pipe followup code %d\n", pi->followup);
3192 /*** Parsing routines ***/
3194 #ifndef debug_print_tree
3195 static void debug_print_tree(struct pipe *pi, int lvl)
3197 static const char *const PIPE[] = {
3203 static const char *RES[] = {
3204 [RES_NONE ] = "NONE" ,
3207 [RES_THEN ] = "THEN" ,
3208 [RES_ELIF ] = "ELIF" ,
3209 [RES_ELSE ] = "ELSE" ,
3212 # if ENABLE_HUSH_LOOPS
3213 [RES_FOR ] = "FOR" ,
3214 [RES_WHILE] = "WHILE",
3215 [RES_UNTIL] = "UNTIL",
3217 [RES_DONE ] = "DONE" ,
3219 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3222 # if ENABLE_HUSH_CASE
3223 [RES_CASE ] = "CASE" ,
3224 [RES_CASE_IN ] = "CASE_IN" ,
3225 [RES_MATCH] = "MATCH",
3226 [RES_CASE_BODY] = "CASE_BODY",
3227 [RES_ESAC ] = "ESAC" ,
3229 [RES_XXXX ] = "XXXX" ,
3230 [RES_SNTX ] = "SNTX" ,
3232 static const char *const CMDTYPE[] = {
3236 # if ENABLE_HUSH_FUNCTIONS
3245 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3246 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3248 while (prn < pi->num_cmds) {
3249 struct command *command = &pi->cmds[prn];
3250 char **argv = command->argv;
3252 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3254 command->assignment_cnt);
3255 if (command->group) {
3256 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3257 CMDTYPE[command->cmd_type],
3260 , " group_as_string:", command->group_as_string
3265 debug_print_tree(command->group, lvl+1);
3269 if (argv) while (*argv) {
3270 fdprintf(2, " '%s'", *argv);
3280 #endif /* debug_print_tree */
3282 static struct pipe *new_pipe(void)
3285 pi = xzalloc(sizeof(struct pipe));
3286 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3290 /* Command (member of a pipe) is complete, or we start a new pipe
3291 * if ctx->command is NULL.
3292 * No errors possible here.
3294 static int done_command(struct parse_context *ctx)
3296 /* The command is really already in the pipe structure, so
3297 * advance the pipe counter and make a new, null command. */
3298 struct pipe *pi = ctx->pipe;
3299 struct command *command = ctx->command;
3301 #if 0 /* Instead we emit error message at run time */
3302 if (ctx->pending_redirect) {
3303 /* For example, "cmd >" (no filename to redirect to) */
3304 die_if_script("syntax error: %s", "invalid redirect");
3305 ctx->pending_redirect = NULL;
3310 if (IS_NULL_CMD(command)) {
3311 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3315 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3316 //debug_print_tree(ctx->list_head, 20);
3318 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3321 /* Only real trickiness here is that the uncommitted
3322 * command structure is not counted in pi->num_cmds. */
3323 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3324 ctx->command = command = &pi->cmds[pi->num_cmds];
3326 memset(command, 0, sizeof(*command));
3327 return pi->num_cmds; /* used only for 0/nonzero check */
3330 static void done_pipe(struct parse_context *ctx, pipe_style type)
3334 debug_printf_parse("done_pipe entered, followup %d\n", type);
3335 /* Close previous command */
3336 not_null = done_command(ctx);
3337 ctx->pipe->followup = type;
3339 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3340 ctx->ctx_inverted = 0;
3341 ctx->pipe->res_word = ctx->ctx_res_w;
3344 /* Without this check, even just <enter> on command line generates
3345 * tree of three NOPs (!). Which is harmless but annoying.
3346 * IOW: it is safe to do it unconditionally. */
3349 || ctx->ctx_res_w == RES_FI
3351 #if ENABLE_HUSH_LOOPS
3352 || ctx->ctx_res_w == RES_DONE
3353 || ctx->ctx_res_w == RES_FOR
3354 || ctx->ctx_res_w == RES_IN
3356 #if ENABLE_HUSH_CASE
3357 || ctx->ctx_res_w == RES_ESAC
3361 debug_printf_parse("done_pipe: adding new pipe: "
3362 "not_null:%d ctx->ctx_res_w:%d\n",
3363 not_null, ctx->ctx_res_w);
3365 ctx->pipe->next = new_p;
3367 /* RES_THEN, RES_DO etc are "sticky" -
3368 * they remain set for pipes inside if/while.
3369 * This is used to control execution.
3370 * RES_FOR and RES_IN are NOT sticky (needed to support
3371 * cases where variable or value happens to match a keyword):
3373 #if ENABLE_HUSH_LOOPS
3374 if (ctx->ctx_res_w == RES_FOR
3375 || ctx->ctx_res_w == RES_IN)
3376 ctx->ctx_res_w = RES_NONE;
3378 #if ENABLE_HUSH_CASE
3379 if (ctx->ctx_res_w == RES_MATCH)
3380 ctx->ctx_res_w = RES_CASE_BODY;
3381 if (ctx->ctx_res_w == RES_CASE)
3382 ctx->ctx_res_w = RES_CASE_IN;
3384 ctx->command = NULL; /* trick done_command below */
3385 /* Create the memory for command, roughly:
3386 * ctx->pipe->cmds = new struct command;
3387 * ctx->command = &ctx->pipe->cmds[0];
3390 //debug_print_tree(ctx->list_head, 10);
3392 debug_printf_parse("done_pipe return\n");
3395 static void initialize_context(struct parse_context *ctx)
3397 memset(ctx, 0, sizeof(*ctx));
3398 ctx->pipe = ctx->list_head = new_pipe();
3399 /* Create the memory for command, roughly:
3400 * ctx->pipe->cmds = new struct command;
3401 * ctx->command = &ctx->pipe->cmds[0];
3406 /* If a reserved word is found and processed, parse context is modified
3407 * and 1 is returned.
3410 struct reserved_combo {
3413 unsigned char assignment_flag;
3417 FLAG_END = (1 << RES_NONE ),
3419 FLAG_IF = (1 << RES_IF ),
3420 FLAG_THEN = (1 << RES_THEN ),
3421 FLAG_ELIF = (1 << RES_ELIF ),
3422 FLAG_ELSE = (1 << RES_ELSE ),
3423 FLAG_FI = (1 << RES_FI ),
3425 # if ENABLE_HUSH_LOOPS
3426 FLAG_FOR = (1 << RES_FOR ),
3427 FLAG_WHILE = (1 << RES_WHILE),
3428 FLAG_UNTIL = (1 << RES_UNTIL),
3429 FLAG_DO = (1 << RES_DO ),
3430 FLAG_DONE = (1 << RES_DONE ),
3431 FLAG_IN = (1 << RES_IN ),
3433 # if ENABLE_HUSH_CASE
3434 FLAG_MATCH = (1 << RES_MATCH),
3435 FLAG_ESAC = (1 << RES_ESAC ),
3437 FLAG_START = (1 << RES_XXXX ),
3440 static const struct reserved_combo* match_reserved_word(o_string *word)
3442 /* Mostly a list of accepted follow-up reserved words.
3443 * FLAG_END means we are done with the sequence, and are ready
3444 * to turn the compound list into a command.
3445 * FLAG_START means the word must start a new compound list.
3447 static const struct reserved_combo reserved_list[] = {
3449 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3450 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3451 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3452 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3453 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3454 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3456 # if ENABLE_HUSH_LOOPS
3457 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3458 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3459 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3460 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3461 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3462 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3464 # if ENABLE_HUSH_CASE
3465 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3466 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3469 const struct reserved_combo *r;
3471 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3472 if (strcmp(word->data, r->literal) == 0)
3477 /* Return 0: not a keyword, 1: keyword
3479 static int reserved_word(o_string *word, struct parse_context *ctx)
3481 # if ENABLE_HUSH_CASE
3482 static const struct reserved_combo reserved_match = {
3483 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3486 const struct reserved_combo *r;
3488 if (word->has_quoted_part)
3490 r = match_reserved_word(word);
3494 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3495 # if ENABLE_HUSH_CASE
3496 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3497 /* "case word IN ..." - IN part starts first MATCH part */
3498 r = &reserved_match;
3501 if (r->flag == 0) { /* '!' */
3502 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3503 syntax_error("! ! command");
3504 ctx->ctx_res_w = RES_SNTX;
3506 ctx->ctx_inverted = 1;
3509 if (r->flag & FLAG_START) {
3510 struct parse_context *old;
3512 old = xmalloc(sizeof(*old));
3513 debug_printf_parse("push stack %p\n", old);
3514 *old = *ctx; /* physical copy */
3515 initialize_context(ctx);
3517 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3518 syntax_error_at(word->data);
3519 ctx->ctx_res_w = RES_SNTX;
3522 /* "{...} fi" is ok. "{...} if" is not
3524 * if { echo foo; } then { echo bar; } fi */
3525 if (ctx->command->group)
3526 done_pipe(ctx, PIPE_SEQ);
3529 ctx->ctx_res_w = r->res;
3530 ctx->old_flag = r->flag;
3531 word->o_assignment = r->assignment_flag;
3532 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3534 if (ctx->old_flag & FLAG_END) {
3535 struct parse_context *old;
3537 done_pipe(ctx, PIPE_SEQ);
3538 debug_printf_parse("pop stack %p\n", ctx->stack);
3540 old->command->group = ctx->list_head;
3541 old->command->cmd_type = CMD_NORMAL;
3543 /* At this point, the compound command's string is in
3544 * ctx->as_string... except for the leading keyword!
3545 * Consider this example: "echo a | if true; then echo a; fi"
3546 * ctx->as_string will contain "true; then echo a; fi",
3547 * with "if " remaining in old->as_string!
3551 int len = old->as_string.length;
3552 /* Concatenate halves */
3553 o_addstr(&old->as_string, ctx->as_string.data);
3554 o_free_unsafe(&ctx->as_string);
3555 /* Find where leading keyword starts in first half */
3556 str = old->as_string.data + len;
3557 if (str > old->as_string.data)
3558 str--; /* skip whitespace after keyword */
3559 while (str > old->as_string.data && isalpha(str[-1]))
3561 /* Ugh, we're done with this horrid hack */
3562 old->command->group_as_string = xstrdup(str);
3563 debug_printf_parse("pop, remembering as:'%s'\n",
3564 old->command->group_as_string);
3567 *ctx = *old; /* physical copy */
3572 #endif /* HAS_KEYWORDS */
3574 /* Word is complete, look at it and update parsing context.
3575 * Normal return is 0. Syntax errors return 1.
3576 * Note: on return, word is reset, but not o_free'd!
3578 static int done_word(o_string *word, struct parse_context *ctx)
3580 struct command *command = ctx->command;
3582 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3583 if (word->length == 0 && !word->has_quoted_part) {
3584 debug_printf_parse("done_word return 0: true null, ignored\n");
3588 if (ctx->pending_redirect) {
3589 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3590 * only if run as "bash", not "sh" */
3591 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3593 * ...the word that follows the redirection operator
3594 * shall be subjected to tilde expansion, parameter expansion,
3595 * command substitution, arithmetic expansion, and quote
3596 * removal. Pathname expansion shall not be performed
3597 * on the word by a non-interactive shell; an interactive
3598 * shell may perform it, but shall do so only when
3599 * the expansion would result in one word."
3601 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3602 /* Cater for >\file case:
3603 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3604 * Same with heredocs:
3605 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3607 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3608 unbackslash(ctx->pending_redirect->rd_filename);
3609 /* Is it <<"HEREDOC"? */
3610 if (word->has_quoted_part) {
3611 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3614 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3615 ctx->pending_redirect = NULL;
3618 # if ENABLE_HUSH_CASE
3619 if (ctx->ctx_dsemicolon
3620 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3622 /* already done when ctx_dsemicolon was set to 1: */
3623 /* ctx->ctx_res_w = RES_MATCH; */
3624 ctx->ctx_dsemicolon = 0;
3627 if (!command->argv /* if it's the first word... */
3628 # if ENABLE_HUSH_LOOPS
3629 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3630 && ctx->ctx_res_w != RES_IN
3632 # if ENABLE_HUSH_CASE
3633 && ctx->ctx_res_w != RES_CASE
3636 int reserved = reserved_word(word, ctx);
3637 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3639 o_reset_to_empty_unquoted(word);
3640 debug_printf_parse("done_word return %d\n",
3641 (ctx->ctx_res_w == RES_SNTX));
3642 return (ctx->ctx_res_w == RES_SNTX);
3644 # if ENABLE_HUSH_BASH_COMPAT
3645 if (strcmp(word->data, "[[") == 0) {
3646 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3652 if (command->group) {
3653 /* "{ echo foo; } echo bar" - bad */
3654 syntax_error_at(word->data);
3655 debug_printf_parse("done_word return 1: syntax error, "
3656 "groups and arglists don't mix\n");
3660 /* If this word wasn't an assignment, next ones definitely
3661 * can't be assignments. Even if they look like ones. */
3662 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3663 && word->o_assignment != WORD_IS_KEYWORD
3665 word->o_assignment = NOT_ASSIGNMENT;
3667 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3668 command->assignment_cnt++;
3669 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3671 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3672 word->o_assignment = MAYBE_ASSIGNMENT;
3674 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3676 if (word->has_quoted_part
3677 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3678 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3679 /* (otherwise it's known to be not empty and is already safe) */
3681 /* exclude "$@" - it can expand to no word despite "" */
3682 char *p = word->data;
3683 while (p[0] == SPECIAL_VAR_SYMBOL
3684 && (p[1] & 0x7f) == '@'
3685 && p[2] == SPECIAL_VAR_SYMBOL
3690 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3691 debug_print_strings("word appended to argv", command->argv);
3694 #if ENABLE_HUSH_LOOPS
3695 if (ctx->ctx_res_w == RES_FOR) {
3696 if (word->has_quoted_part
3697 || !is_well_formed_var_name(command->argv[0], '\0')
3699 /* bash says just "not a valid identifier" */
3700 syntax_error("not a valid identifier in for");
3703 /* Force FOR to have just one word (variable name) */
3704 /* NB: basically, this makes hush see "for v in ..."
3705 * syntax as if it is "for v; in ...". FOR and IN become
3706 * two pipe structs in parse tree. */
3707 done_pipe(ctx, PIPE_SEQ);
3710 #if ENABLE_HUSH_CASE
3711 /* Force CASE to have just one word */
3712 if (ctx->ctx_res_w == RES_CASE) {
3713 done_pipe(ctx, PIPE_SEQ);
3717 o_reset_to_empty_unquoted(word);
3719 debug_printf_parse("done_word return 0\n");
3724 /* Peek ahead in the input to find out if we have a "&n" construct,
3725 * as in "2>&1", that represents duplicating a file descriptor.
3727 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3728 * REDIRFD_SYNTAX_ERR if syntax error,
3729 * REDIRFD_TO_FILE if no & was seen,
3730 * or the number found.
3733 #define parse_redir_right_fd(as_string, input) \
3734 parse_redir_right_fd(input)
3736 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3742 return REDIRFD_TO_FILE;
3744 ch = i_getch(input); /* get the & */
3745 nommu_addchr(as_string, ch);
3748 ch = i_getch(input);
3749 nommu_addchr(as_string, ch);
3750 return REDIRFD_CLOSE;
3754 while (ch != EOF && isdigit(ch)) {
3755 d = d*10 + (ch-'0');
3757 ch = i_getch(input);
3758 nommu_addchr(as_string, ch);
3763 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3765 bb_error_msg("ambiguous redirect");
3766 return REDIRFD_SYNTAX_ERR;
3769 /* Return code is 0 normal, 1 if a syntax error is detected
3771 static int parse_redirect(struct parse_context *ctx,
3774 struct in_str *input)
3776 struct command *command = ctx->command;
3777 struct redir_struct *redir;
3778 struct redir_struct **redirp;
3781 dup_num = REDIRFD_TO_FILE;
3782 if (style != REDIRECT_HEREDOC) {
3783 /* Check for a '>&1' type redirect */
3784 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3785 if (dup_num == REDIRFD_SYNTAX_ERR)
3788 int ch = i_peek(input);
3789 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3790 if (dup_num) { /* <<-... */
3791 ch = i_getch(input);
3792 nommu_addchr(&ctx->as_string, ch);
3797 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3798 int ch = i_peek(input);
3800 /* >|FILE redirect ("clobbering" >).
3801 * Since we do not support "set -o noclobber" yet,
3802 * >| and > are the same for now. Just eat |.
3804 ch = i_getch(input);
3805 nommu_addchr(&ctx->as_string, ch);
3809 /* Create a new redir_struct and append it to the linked list */
3810 redirp = &command->redirects;
3811 while ((redir = *redirp) != NULL) {
3812 redirp = &(redir->next);
3814 *redirp = redir = xzalloc(sizeof(*redir));
3815 /* redir->next = NULL; */
3816 /* redir->rd_filename = NULL; */
3817 redir->rd_type = style;
3818 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3820 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3821 redir_table[style].descrip);
3823 redir->rd_dup = dup_num;
3824 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3825 /* Erik had a check here that the file descriptor in question
3826 * is legit; I postpone that to "run time"
3827 * A "-" representation of "close me" shows up as a -3 here */
3828 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3829 redir->rd_fd, redir->rd_dup);
3831 #if 0 /* Instead we emit error message at run time */
3832 if (ctx->pending_redirect) {
3833 /* For example, "cmd > <file" */
3834 die_if_script("syntax error: %s", "invalid redirect");
3837 /* Set ctx->pending_redirect, so we know what to do at the
3838 * end of the next parsed word. */
3839 ctx->pending_redirect = redir;
3844 /* If a redirect is immediately preceded by a number, that number is
3845 * supposed to tell which file descriptor to redirect. This routine
3846 * looks for such preceding numbers. In an ideal world this routine
3847 * needs to handle all the following classes of redirects...
3848 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3849 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3850 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3851 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3853 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3855 * ... If n is quoted, the number shall not be recognized as part of
3856 * the redirection expression. For example:
3858 * writes the character 2 into file a"
3859 * We are getting it right by setting ->has_quoted_part on any \<char>
3861 * A -1 return means no valid number was found,
3862 * the caller should use the appropriate default for this redirection.
3864 static int redirect_opt_num(o_string *o)
3868 if (o->data == NULL)
3870 num = bb_strtou(o->data, NULL, 10);
3871 if (errno || num < 0)
3873 o_reset_to_empty_unquoted(o);
3878 #define fetch_till_str(as_string, input, word, skip_tabs) \
3879 fetch_till_str(input, word, skip_tabs)
3881 static char *fetch_till_str(o_string *as_string,
3882 struct in_str *input,
3886 o_string heredoc = NULL_O_STRING;
3888 int prev = 0; /* not \ */
3894 ch = i_getch(input);
3896 nommu_addchr(as_string, ch);
3897 if ((ch == '\n' || ch == EOF)
3898 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3900 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3901 heredoc.data[past_EOL] = '\0';
3902 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3903 return heredoc.data;
3905 while (ch == '\n') {
3906 o_addchr(&heredoc, ch);
3909 past_EOL = heredoc.length;
3911 ch = i_getch(input);
3913 nommu_addchr(as_string, ch);
3914 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3918 o_free_unsafe(&heredoc);
3921 o_addchr(&heredoc, ch);
3922 nommu_addchr(as_string, ch);
3923 if (prev == '\\' && ch == '\\')
3924 /* Correctly handle foo\\<eol> (not a line cont.) */
3925 prev = 0; /* not \ */
3931 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3932 * and load them all. There should be exactly heredoc_cnt of them.
3934 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3936 struct pipe *pi = ctx->list_head;
3938 while (pi && heredoc_cnt) {
3940 struct command *cmd = pi->cmds;
3942 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3944 cmd->argv ? cmd->argv[0] : "NONE");
3945 for (i = 0; i < pi->num_cmds; i++) {
3946 struct redir_struct *redir = cmd->redirects;
3948 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3949 i, cmd->argv ? cmd->argv[0] : "NONE");
3951 if (redir->rd_type == REDIRECT_HEREDOC) {
3954 redir->rd_type = REDIRECT_HEREDOC2;
3955 /* redir->rd_dup is (ab)used to indicate <<- */
3956 p = fetch_till_str(&ctx->as_string, input,
3957 redir->rd_filename, redir->rd_dup);
3959 syntax_error("unexpected EOF in here document");
3962 free(redir->rd_filename);
3963 redir->rd_filename = p;
3966 redir = redir->next;
3973 /* Should be 0. If it isn't, it's a parse error */
3975 bb_error_msg_and_die("heredoc BUG 2");
3981 static int run_list(struct pipe *pi);
3983 #define parse_stream(pstring, input, end_trigger) \
3984 parse_stream(input, end_trigger)
3986 static struct pipe *parse_stream(char **pstring,
3987 struct in_str *input,
3991 #if !ENABLE_HUSH_FUNCTIONS
3992 #define parse_group(dest, ctx, input, ch) \
3993 parse_group(ctx, input, ch)
3995 static int parse_group(o_string *dest, struct parse_context *ctx,
3996 struct in_str *input, int ch)
3998 /* dest contains characters seen prior to ( or {.
3999 * Typically it's empty, but for function defs,
4000 * it contains function name (without '()'). */
4001 struct pipe *pipe_list;
4003 struct command *command = ctx->command;
4005 debug_printf_parse("parse_group entered\n");
4006 #if ENABLE_HUSH_FUNCTIONS
4007 if (ch == '(' && !dest->has_quoted_part) {
4009 if (done_word(dest, ctx))
4012 goto skip; /* (... */
4013 if (command->argv[1]) { /* word word ... (... */
4014 syntax_error_unexpected_ch('(');
4017 /* it is "word(..." or "word (..." */
4019 ch = i_getch(input);
4020 while (ch == ' ' || ch == '\t');
4022 syntax_error_unexpected_ch(ch);
4025 nommu_addchr(&ctx->as_string, ch);
4027 ch = i_getch(input);
4028 while (ch == ' ' || ch == '\t' || ch == '\n');
4030 syntax_error_unexpected_ch(ch);
4033 nommu_addchr(&ctx->as_string, ch);
4034 command->cmd_type = CMD_FUNCDEF;
4039 #if 0 /* Prevented by caller */
4040 if (command->argv /* word [word]{... */
4041 || dest->length /* word{... */
4042 || dest->has_quoted_part /* ""{... */
4045 debug_printf_parse("parse_group return 1: "
4046 "syntax error, groups and arglists don't mix\n");
4051 #if ENABLE_HUSH_FUNCTIONS
4057 command->cmd_type = CMD_SUBSHELL;
4059 /* bash does not allow "{echo...", requires whitespace */
4061 if (ch != ' ' && ch != '\t' && ch != '\n'
4062 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4064 syntax_error_unexpected_ch(ch);
4068 ch = i_getch(input);
4069 nommu_addchr(&ctx->as_string, ch);
4075 # define as_string NULL
4077 char *as_string = NULL;
4079 pipe_list = parse_stream(&as_string, input, endch);
4082 o_addstr(&ctx->as_string, as_string);
4084 /* empty ()/{} or parse error? */
4085 if (!pipe_list || pipe_list == ERR_PTR) {
4086 /* parse_stream already emitted error msg */
4089 debug_printf_parse("parse_group return 1: "
4090 "parse_stream returned %p\n", pipe_list);
4093 command->group = pipe_list;
4095 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4096 command->group_as_string = as_string;
4097 debug_printf_parse("end of group, remembering as:'%s'\n",
4098 command->group_as_string);
4102 debug_printf_parse("parse_group return 0\n");
4104 /* command remains "open", available for possible redirects */
4107 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4112 ch = i_getch(input);
4115 ch2 = i_peek(input);
4118 /* backslash+newline, skip it */
4123 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4131 ch2 = i_peek2(input);
4134 /* backslash+newline, skip it */
4140 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4141 /* Subroutines for copying $(...) and `...` things */
4142 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4144 static int add_till_single_quote(o_string *dest, struct in_str *input)
4147 int ch = i_getch(input);
4149 syntax_error_unterm_ch('\'');
4157 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4158 static int add_till_double_quote(o_string *dest, struct in_str *input)
4161 int ch = i_getch(input);
4163 syntax_error_unterm_ch('"');
4168 if (ch == '\\') { /* \x. Copy both chars. */
4170 ch = i_getch(input);
4174 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4179 //if (ch == '$') ...
4182 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4184 * "Within the backquoted style of command substitution, backslash
4185 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4186 * The search for the matching backquote shall be satisfied by the first
4187 * backquote found without a preceding backslash; during this search,
4188 * if a non-escaped backquote is encountered within a shell comment,
4189 * a here-document, an embedded command substitution of the $(command)
4190 * form, or a quoted string, undefined results occur. A single-quoted
4191 * or double-quoted string that begins, but does not end, within the
4192 * "`...`" sequence produces undefined results."
4194 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4196 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4199 int ch = i_getch(input);
4203 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4204 ch = i_getch(input);
4208 && (!in_dquote || ch != '"')
4210 o_addchr(dest, '\\');
4214 syntax_error_unterm_ch('`');
4220 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4221 * quoting and nested ()s.
4222 * "With the $(command) style of command substitution, all characters
4223 * following the open parenthesis to the matching closing parenthesis
4224 * constitute the command. Any valid shell script can be used for command,
4225 * except a script consisting solely of redirections which produces
4226 * unspecified results."
4228 * echo $(echo '(TEST)' BEST) (TEST) BEST
4229 * echo $(echo 'TEST)' BEST) TEST) BEST
4230 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4232 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4233 * can contain arbitrary constructs, just like $(cmd).
4234 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4235 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4237 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4238 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4241 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4242 # if ENABLE_HUSH_BASH_COMPAT
4243 char end_char2 = end_ch >> 8;
4245 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4248 ch = i_getch(input);
4250 syntax_error_unterm_ch(end_ch);
4253 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4256 /* we look for closing )) of $((EXPR)) */
4257 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4258 i_getch(input); /* eat second ')' */
4263 if (ch == '(' || ch == '{') {
4264 ch = (ch == '(' ? ')' : '}');
4265 if (!add_till_closing_bracket(dest, input, ch))
4271 if (!add_till_single_quote(dest, input))
4277 if (!add_till_double_quote(dest, input))
4283 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4289 /* \x. Copy verbatim. Important for \(, \) */
4290 ch = i_getch(input);
4292 syntax_error_unterm_ch(')');
4297 /* "backslash+newline", ignore both */
4298 o_delchr(dest); /* undo insertion of '\' */
4308 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4310 /* Return code: 0 for OK, 1 for syntax error */
4312 #define parse_dollar(as_string, dest, input, quote_mask) \
4313 parse_dollar(dest, input, quote_mask)
4314 #define as_string NULL
4316 static int parse_dollar(o_string *as_string,
4318 struct in_str *input, unsigned char quote_mask)
4320 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4322 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4324 ch = i_getch(input);
4325 nommu_addchr(as_string, ch);
4327 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4329 debug_printf_parse(": '%c'\n", ch);
4330 o_addchr(dest, ch | quote_mask);
4332 ch = i_peek_and_eat_bkslash_nl(input);
4333 if (!isalnum(ch) && ch != '_') {
4334 /* End of variable name reached */
4337 ch = i_getch(input);
4338 nommu_addchr(as_string, ch);
4340 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4341 } else if (isdigit(ch)) {
4343 ch = i_getch(input);
4344 nommu_addchr(as_string, ch);
4345 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4346 debug_printf_parse(": '%c'\n", ch);
4347 o_addchr(dest, ch | quote_mask);
4348 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4349 } else switch (ch) {
4351 case '!': /* last bg pid */
4352 case '?': /* last exit code */
4353 case '#': /* number of args */
4354 case '*': /* args */
4355 case '@': /* args */
4356 goto make_one_char_var;
4358 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4360 ch = i_getch(input); /* eat '{' */
4361 nommu_addchr(as_string, ch);
4363 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4364 /* It should be ${?}, or ${#var},
4365 * or even ${?+subst} - operator acting on a special variable,
4366 * or the beginning of variable name.
4369 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4372 syntax_error_unterm_str("${name}");
4373 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4376 nommu_addchr(as_string, ch);
4379 /* It's possible to just call add_till_closing_bracket() at this point.
4380 * However, this regresses some of our testsuite cases
4381 * which check invalid constructs like ${%}.
4382 * Oh well... let's check that the var name part is fine... */
4388 debug_printf_parse(": '%c'\n", ch);
4390 ch = i_getch(input);
4391 nommu_addchr(as_string, ch);
4395 if (!isalnum(ch) && ch != '_') {
4397 unsigned char last_ch;
4398 /* handle parameter expansions
4399 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4401 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4402 goto bad_dollar_syntax;
4404 /* Eat everything until closing '}' (or ':') */
4406 if (ENABLE_HUSH_BASH_COMPAT
4408 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4410 /* It's ${var:N[:M]} thing */
4411 end_ch = '}' * 0x100 + ':';
4413 if (ENABLE_HUSH_BASH_COMPAT
4416 /* It's ${var/[/]pattern[/repl]} thing */
4417 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4419 nommu_addchr(as_string, '/');
4422 end_ch = '}' * 0x100 + '/';
4428 #if ENABLE_HUSH_DOLLAR_OPS
4429 last_ch = add_till_closing_bracket(dest, input, end_ch);
4430 if (last_ch == 0) /* error? */
4433 #error Simple code to only allow ${var} is not implemented
4436 o_addstr(as_string, dest->data + pos);
4437 o_addchr(as_string, last_ch);
4440 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4441 /* close the first block: */
4442 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4443 /* while parsing N from ${var:N[:M]}
4444 * or pattern from ${var/[/]pattern[/repl]} */
4445 if ((end_ch & 0xff) == last_ch) {
4446 /* got ':' or '/'- parse the rest */
4451 if (end_ch == '}' * 0x100 + ':') {
4452 /* it's ${var:N} - emulate :999999999 */
4453 o_addstr(dest, "999999999");
4454 } /* else: it's ${var/[/]pattern} */
4459 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4462 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4466 ch = i_getch(input);
4467 nommu_addchr(as_string, ch);
4468 # if ENABLE_FEATURE_SH_MATH
4469 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4470 ch = i_getch(input);
4471 nommu_addchr(as_string, ch);
4472 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4473 o_addchr(dest, /*quote_mask |*/ '+');
4476 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4477 return 0; /* error */
4479 o_addstr(as_string, dest->data + pos);
4480 o_addchr(as_string, ')');
4481 o_addchr(as_string, ')');
4483 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4487 # if ENABLE_HUSH_TICK
4488 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4489 o_addchr(dest, quote_mask | '`');
4492 if (!add_till_closing_bracket(dest, input, ')'))
4493 return 0; /* error */
4495 o_addstr(as_string, dest->data + pos);
4496 o_addchr(as_string, ')');
4498 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4504 ch = i_getch(input);
4505 nommu_addchr(as_string, ch);
4506 ch = i_peek_and_eat_bkslash_nl(input);
4507 if (isalnum(ch)) { /* it's $_name or $_123 */
4512 /* TODO: $_ and $-: */
4513 /* $_ Shell or shell script name; or last argument of last command
4514 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4515 * but in command's env, set to full pathname used to invoke it */
4516 /* $- Option flags set by set builtin or shell options (-i etc) */
4518 o_addQchr(dest, '$');
4520 debug_printf_parse("parse_dollar return 1 (ok)\n");
4526 # if ENABLE_HUSH_BASH_COMPAT
4527 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4528 encode_string(dest, input, dquote_end, process_bkslash)
4530 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4531 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4532 encode_string(dest, input, dquote_end)
4534 #define as_string NULL
4538 # if ENABLE_HUSH_BASH_COMPAT
4539 /* all parameters are needed, no macro tricks */
4541 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4542 encode_string(as_string, dest, input, dquote_end)
4545 static int encode_string(o_string *as_string,
4547 struct in_str *input,
4549 int process_bkslash)
4551 #if !ENABLE_HUSH_BASH_COMPAT
4552 const int process_bkslash = 1;
4558 ch = i_getch(input);
4560 nommu_addchr(as_string, ch);
4561 if (ch == dquote_end) { /* may be only '"' or EOF */
4562 debug_printf_parse("encode_string return 1 (ok)\n");
4565 /* note: can't move it above ch == dquote_end check! */
4567 syntax_error_unterm_ch('"');
4568 return 0; /* error */
4572 next = i_peek(input);
4574 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4575 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4576 if (process_bkslash && ch == '\\') {
4578 syntax_error("\\<eof>");
4582 * "The backslash retains its special meaning [in "..."]
4583 * only when followed by one of the following characters:
4584 * $, `, ", \, or <newline>. A double quote may be quoted
4585 * within double quotes by preceding it with a backslash."
4586 * NB: in (unquoted) heredoc, above does not apply to ",
4587 * therefore we check for it by "next == dquote_end" cond.
4589 if (next == dquote_end || strchr("$`\\\n", next)) {
4590 ch = i_getch(input); /* eat next */
4592 goto again; /* skip \<newline> */
4593 } /* else: ch remains == '\\', and we double it below: */
4594 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4595 nommu_addchr(as_string, ch);
4599 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4600 debug_printf_parse("encode_string return 0: "
4601 "parse_dollar returned 0 (error)\n");
4606 #if ENABLE_HUSH_TICK
4608 //unsigned pos = dest->length;
4609 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4610 o_addchr(dest, 0x80 | '`');
4611 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4612 return 0; /* error */
4613 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4614 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4618 o_addQchr(dest, ch);
4624 * Scan input until EOF or end_trigger char.
4625 * Return a list of pipes to execute, or NULL on EOF
4626 * or if end_trigger character is met.
4627 * On syntax error, exit if shell is not interactive,
4628 * reset parsing machinery and start parsing anew,
4629 * or return ERR_PTR.
4631 static struct pipe *parse_stream(char **pstring,
4632 struct in_str *input,
4635 struct parse_context ctx;
4636 o_string dest = NULL_O_STRING;
4639 /* Single-quote triggers a bypass of the main loop until its mate is
4640 * found. When recursing, quote state is passed in via dest->o_expflags.
4642 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4643 end_trigger ? end_trigger : 'X');
4646 /* If very first arg is "" or '', dest.data may end up NULL.
4647 * Preventing this: */
4648 o_addchr(&dest, '\0');
4651 /* We used to separate words on $IFS here. This was wrong.
4652 * $IFS is used only for word splitting when $var is expanded,
4653 * here we should use blank chars as separators, not $IFS
4656 if (MAYBE_ASSIGNMENT != 0)
4657 dest.o_assignment = MAYBE_ASSIGNMENT;
4658 initialize_context(&ctx);
4661 const char *is_blank;
4662 const char *is_special;
4666 redir_type redir_style;
4668 ch = i_getch(input);
4669 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4670 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4675 syntax_error_unterm_str("here document");
4678 if (end_trigger == ')') {
4679 syntax_error_unterm_ch('(');
4682 if (end_trigger == '}') {
4683 syntax_error_unterm_ch('{');
4687 if (done_word(&dest, &ctx)) {
4691 done_pipe(&ctx, PIPE_SEQ);
4693 /* If we got nothing... */
4694 /* (this makes bare "&" cmd a no-op.
4695 * bash says: "syntax error near unexpected token '&'") */
4696 if (pi->num_cmds == 0
4697 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4703 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4705 *pstring = ctx.as_string.data;
4707 o_free_unsafe(&ctx.as_string);
4710 debug_printf_parse("parse_stream return %p\n", pi);
4713 nommu_addchr(&ctx.as_string, ch);
4717 next = i_peek(input);
4719 is_special = "{}<>;&|()#'" /* special outside of "str" */
4720 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4721 /* Are { and } special here? */
4722 if (ctx.command->argv /* word [word]{... - non-special */
4723 || dest.length /* word{... - non-special */
4724 || dest.has_quoted_part /* ""{... - non-special */
4725 || (next != ';' /* }; - special */
4726 && next != ')' /* }) - special */
4727 && next != '(' /* {( - special */
4728 && next != '&' /* }& and }&& ... - special */
4729 && next != '|' /* }|| ... - special */
4730 && !strchr(defifs, next) /* {word - non-special */
4733 /* They are not special, skip "{}" */
4736 is_special = strchr(is_special, ch);
4737 is_blank = strchr(defifs, ch);
4739 if (!is_special && !is_blank) { /* ordinary char */
4741 o_addQchr(&dest, ch);
4742 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4743 || dest.o_assignment == WORD_IS_KEYWORD)
4745 && is_well_formed_var_name(dest.data, '=')
4747 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4748 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4754 if (done_word(&dest, &ctx)) {
4758 /* Is this a case when newline is simply ignored?
4760 * "cmd | <newline> cmd ..."
4761 * "case ... in <newline> word) ..."
4763 if (IS_NULL_CMD(ctx.command)
4764 && dest.length == 0 && !dest.has_quoted_part
4766 /* This newline can be ignored. But...
4767 * Without check #1, interactive shell
4768 * ignores even bare <newline>,
4769 * and shows the continuation prompt:
4770 * ps1_prompt$ <enter>
4771 * ps2> _ <=== wrong, should be ps1
4772 * Without check #2, "cmd & <newline>"
4773 * is similarly mistreated.
4774 * (BTW, this makes "cmd & cmd"
4775 * and "cmd && cmd" non-orthogonal.
4776 * Really, ask yourself, why
4777 * "cmd && <newline>" doesn't start
4778 * cmd but waits for more input?
4781 struct pipe *pi = ctx.list_head;
4782 if (pi->num_cmds != 0 /* check #1 */
4783 && pi->followup != PIPE_BG /* check #2 */
4788 /* Treat newline as a command separator. */
4789 done_pipe(&ctx, PIPE_SEQ);
4790 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4792 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4797 dest.o_assignment = MAYBE_ASSIGNMENT;
4798 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4800 /* note: if (is_blank) continue;
4801 * will still trigger for us */
4805 /* "cmd}" or "cmd }..." without semicolon or &:
4806 * } is an ordinary char in this case, even inside { cmd; }
4807 * Pathological example: { ""}; } should exec "}" cmd
4810 if (dest.length != 0 /* word} */
4811 || dest.has_quoted_part /* ""} */
4815 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4816 /* Generally, there should be semicolon: "cmd; }"
4817 * However, bash allows to omit it if "cmd" is
4818 * a group. Examples:
4821 * { echo 0 >&2 | { echo 1; } }
4822 * { while false; do :; done }
4823 * { case a in b) ;; esac }
4825 if (ctx.command->group)
4829 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4830 /* Can't be an end of {cmd}, skip the check */
4831 goto skip_end_trigger;
4832 /* else: } does terminate a group */
4835 if (end_trigger && end_trigger == ch
4836 && (ch != ';' || heredoc_cnt == 0)
4837 #if ENABLE_HUSH_CASE
4839 || ctx.ctx_res_w != RES_MATCH
4840 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4845 /* This is technically valid:
4846 * { cat <<HERE; }; echo Ok
4850 * but we don't support this.
4851 * We require heredoc to be in enclosing {}/(),
4854 syntax_error_unterm_str("here document");
4857 if (done_word(&dest, &ctx)) {
4860 done_pipe(&ctx, PIPE_SEQ);
4861 dest.o_assignment = MAYBE_ASSIGNMENT;
4862 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4863 /* Do we sit outside of any if's, loops or case's? */
4865 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4869 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4871 *pstring = ctx.as_string.data;
4873 o_free_unsafe(&ctx.as_string);
4876 debug_printf_parse("parse_stream return %p: "
4877 "end_trigger char found\n",
4879 return ctx.list_head;
4886 /* Catch <, > before deciding whether this word is
4887 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4890 redir_fd = redirect_opt_num(&dest);
4891 if (done_word(&dest, &ctx)) {
4894 redir_style = REDIRECT_OVERWRITE;
4896 redir_style = REDIRECT_APPEND;
4897 ch = i_getch(input);
4898 nommu_addchr(&ctx.as_string, ch);
4901 else if (next == '(') {
4902 syntax_error(">(process) not supported");
4906 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4908 continue; /* back to top of while (1) */
4910 redir_fd = redirect_opt_num(&dest);
4911 if (done_word(&dest, &ctx)) {
4914 redir_style = REDIRECT_INPUT;
4916 redir_style = REDIRECT_HEREDOC;
4918 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4919 ch = i_getch(input);
4920 nommu_addchr(&ctx.as_string, ch);
4921 } else if (next == '>') {
4922 redir_style = REDIRECT_IO;
4923 ch = i_getch(input);
4924 nommu_addchr(&ctx.as_string, ch);
4927 else if (next == '(') {
4928 syntax_error("<(process) not supported");
4932 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4934 continue; /* back to top of while (1) */
4936 if (dest.length == 0 && !dest.has_quoted_part) {
4937 /* skip "#comment" */
4940 if (ch == EOF || ch == '\n')
4943 /* note: we do not add it to &ctx.as_string */
4945 nommu_addchr(&ctx.as_string, '\n');
4946 continue; /* back to top of while (1) */
4951 /* It's "\<newline>" */
4953 /* Remove trailing '\' from ctx.as_string */
4954 ctx.as_string.data[--ctx.as_string.length] = '\0';
4956 ch = i_getch(input); /* eat it */
4957 continue; /* back to top of while (1) */
4962 if (dest.o_assignment == MAYBE_ASSIGNMENT
4963 /* check that we are not in word in "a=1 2>word b=1": */
4964 && !ctx.pending_redirect
4966 /* ch is a special char and thus this word
4967 * cannot be an assignment */
4968 dest.o_assignment = NOT_ASSIGNMENT;
4969 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4972 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4975 case '#': /* non-comment #: "echo a#b" etc */
4976 o_addQchr(&dest, ch);
4980 syntax_error("\\<eof>");
4983 ch = i_getch(input);
4984 /* note: ch != '\n' (that case does not reach this place) */
4985 o_addchr(&dest, '\\');
4986 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4987 o_addchr(&dest, ch);
4988 nommu_addchr(&ctx.as_string, ch);
4989 /* Example: echo Hello \2>file
4990 * we need to know that word 2 is quoted */
4991 dest.has_quoted_part = 1;
4994 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4995 debug_printf_parse("parse_stream parse error: "
4996 "parse_dollar returned 0 (error)\n");
5001 dest.has_quoted_part = 1;
5002 if (next == '\'' && !ctx.pending_redirect) {
5003 insert_empty_quoted_str_marker:
5004 nommu_addchr(&ctx.as_string, next);
5005 i_getch(input); /* eat second ' */
5006 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5007 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5010 ch = i_getch(input);
5012 syntax_error_unterm_ch('\'');
5015 nommu_addchr(&ctx.as_string, ch);
5018 o_addqchr(&dest, ch);
5023 dest.has_quoted_part = 1;
5024 if (next == '"' && !ctx.pending_redirect)
5025 goto insert_empty_quoted_str_marker;
5026 if (dest.o_assignment == NOT_ASSIGNMENT)
5027 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5028 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5030 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5032 #if ENABLE_HUSH_TICK
5034 USE_FOR_NOMMU(unsigned pos;)
5036 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5037 o_addchr(&dest, '`');
5038 USE_FOR_NOMMU(pos = dest.length;)
5039 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5042 o_addstr(&ctx.as_string, dest.data + pos);
5043 o_addchr(&ctx.as_string, '`');
5045 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5046 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5051 #if ENABLE_HUSH_CASE
5054 if (done_word(&dest, &ctx)) {
5057 done_pipe(&ctx, PIPE_SEQ);
5058 #if ENABLE_HUSH_CASE
5059 /* Eat multiple semicolons, detect
5060 * whether it means something special */
5065 ch = i_getch(input);
5066 nommu_addchr(&ctx.as_string, ch);
5067 if (ctx.ctx_res_w == RES_CASE_BODY) {
5068 ctx.ctx_dsemicolon = 1;
5069 ctx.ctx_res_w = RES_MATCH;
5075 /* We just finished a cmd. New one may start
5076 * with an assignment */
5077 dest.o_assignment = MAYBE_ASSIGNMENT;
5078 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5081 if (done_word(&dest, &ctx)) {
5085 ch = i_getch(input);
5086 nommu_addchr(&ctx.as_string, ch);
5087 done_pipe(&ctx, PIPE_AND);
5089 done_pipe(&ctx, PIPE_BG);
5093 if (done_word(&dest, &ctx)) {
5096 #if ENABLE_HUSH_CASE
5097 if (ctx.ctx_res_w == RES_MATCH)
5098 break; /* we are in case's "word | word)" */
5100 if (next == '|') { /* || */
5101 ch = i_getch(input);
5102 nommu_addchr(&ctx.as_string, ch);
5103 done_pipe(&ctx, PIPE_OR);
5105 /* we could pick up a file descriptor choice here
5106 * with redirect_opt_num(), but bash doesn't do it.
5107 * "echo foo 2| cat" yields "foo 2". */
5112 #if ENABLE_HUSH_CASE
5113 /* "case... in [(]word)..." - skip '(' */
5114 if (ctx.ctx_res_w == RES_MATCH
5115 && ctx.command->argv == NULL /* not (word|(... */
5116 && dest.length == 0 /* not word(... */
5117 && dest.has_quoted_part == 0 /* not ""(... */
5123 if (parse_group(&dest, &ctx, input, ch) != 0) {
5128 #if ENABLE_HUSH_CASE
5129 if (ctx.ctx_res_w == RES_MATCH)
5133 /* proper use of this character is caught by end_trigger:
5134 * if we see {, we call parse_group(..., end_trigger='}')
5135 * and it will match } earlier (not here). */
5136 syntax_error_unexpected_ch(ch);
5137 G.last_exitcode = 2;
5141 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5146 G.last_exitcode = 1;
5149 struct parse_context *pctx;
5150 IF_HAS_KEYWORDS(struct parse_context *p2;)
5152 /* Clean up allocated tree.
5153 * Sample for finding leaks on syntax error recovery path.
5154 * Run it from interactive shell, watch pmap `pidof hush`.
5155 * while if false; then false; fi; do break; fi
5156 * Samples to catch leaks at execution:
5157 * while if (true | { true;}); then echo ok; fi; do break; done
5158 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5162 /* Update pipe/command counts,
5163 * otherwise freeing may miss some */
5164 done_pipe(pctx, PIPE_SEQ);
5165 debug_printf_clean("freeing list %p from ctx %p\n",
5166 pctx->list_head, pctx);
5167 debug_print_tree(pctx->list_head, 0);
5168 free_pipe_list(pctx->list_head);
5169 debug_printf_clean("freed list %p\n", pctx->list_head);
5171 o_free_unsafe(&pctx->as_string);
5173 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5177 IF_HAS_KEYWORDS(pctx = p2;)
5178 } while (HAS_KEYWORDS && pctx);
5191 /*** Execution routines ***/
5193 /* Expansion can recurse, need forward decls: */
5194 #if !ENABLE_HUSH_BASH_COMPAT
5195 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5196 #define expand_string_to_string(str, do_unbackslash) \
5197 expand_string_to_string(str)
5199 static char *expand_string_to_string(const char *str, int do_unbackslash);
5200 #if ENABLE_HUSH_TICK
5201 static int process_command_subs(o_string *dest, const char *s);
5204 /* expand_strvec_to_strvec() takes a list of strings, expands
5205 * all variable references within and returns a pointer to
5206 * a list of expanded strings, possibly with larger number
5207 * of strings. (Think VAR="a b"; echo $VAR).
5208 * This new list is allocated as a single malloc block.
5209 * NULL-terminated list of char* pointers is at the beginning of it,
5210 * followed by strings themselves.
5211 * Caller can deallocate entire list by single free(list). */
5213 /* A horde of its helpers come first: */
5215 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5217 while (--len >= 0) {
5220 #if ENABLE_HUSH_BRACE_EXPANSION
5221 if (c == '{' || c == '}') {
5222 /* { -> \{, } -> \} */
5224 /* And now we want to add { or } and continue:
5227 * luckily, just falling throught achieves this.
5233 /* \z -> \\\z; \<eol> -> \\<eol> */
5238 o_addchr(o, *str++);
5244 /* Store given string, finalizing the word and starting new one whenever
5245 * we encounter IFS char(s). This is used for expanding variable values.
5246 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5247 * Return in *ended_with_ifs:
5248 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5250 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5252 int last_is_ifs = 0;
5257 if (!*str) /* EOL - do not finalize word */
5259 word_len = strcspn(str, G.ifs);
5261 /* We have WORD_LEN leading non-IFS chars */
5262 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5263 o_addblock(output, str, word_len);
5265 /* Protect backslashes against globbing up :)
5266 * Example: "v='\*'; echo b$v" prints "b\*"
5267 * (and does not try to glob on "*")
5269 o_addblock_duplicate_backslash(output, str, word_len);
5270 /*/ Why can't we do it easier? */
5271 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5272 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5276 if (!*str) /* EOL - do not finalize word */
5280 /* We know str here points to at least one IFS char */
5282 str += strspn(str, G.ifs); /* skip IFS chars */
5283 if (!*str) /* EOL - do not finalize word */
5286 /* Start new word... but not always! */
5287 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5288 if (output->has_quoted_part
5289 /* Case "v=' a'; echo $v":
5290 * here nothing precedes the space in $v expansion,
5291 * therefore we should not finish the word
5292 * (IOW: if there *is* word to finalize, only then do it):
5294 || (n > 0 && output->data[output->length - 1])
5296 o_addchr(output, '\0');
5297 debug_print_list("expand_on_ifs", output, n);
5298 n = o_save_ptr(output, n);
5303 *ended_with_ifs = last_is_ifs;
5304 debug_print_list("expand_on_ifs[1]", output, n);
5308 /* Helper to expand $((...)) and heredoc body. These act as if
5309 * they are in double quotes, with the exception that they are not :).
5310 * Just the rules are similar: "expand only $var and `cmd`"
5312 * Returns malloced string.
5313 * As an optimization, we return NULL if expansion is not needed.
5315 #if !ENABLE_HUSH_BASH_COMPAT
5316 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5317 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5318 encode_then_expand_string(str)
5320 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5323 struct in_str input;
5324 o_string dest = NULL_O_STRING;
5326 if (!strchr(str, '$')
5327 && !strchr(str, '\\')
5328 #if ENABLE_HUSH_TICK
5329 && !strchr(str, '`')
5335 /* We need to expand. Example:
5336 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5338 setup_string_in_str(&input, str);
5339 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5340 //TODO: error check (encode_string returns 0 on error)?
5341 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5342 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5343 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5344 o_free_unsafe(&dest);
5348 #if ENABLE_FEATURE_SH_MATH
5349 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5351 arith_state_t math_state;
5355 math_state.lookupvar = get_local_var_value;
5356 math_state.setvar = set_local_var_from_halves;
5357 //math_state.endofname = endofname;
5358 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5359 res = arith(&math_state, exp_str ? exp_str : arg);
5362 *errmsg_p = math_state.errmsg;
5363 if (math_state.errmsg)
5364 die_if_script(math_state.errmsg);
5369 #if ENABLE_HUSH_BASH_COMPAT
5370 /* ${var/[/]pattern[/repl]} helpers */
5371 static char *strstr_pattern(char *val, const char *pattern, int *size)
5374 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5375 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5382 /* Optimization: if "*pat" did not match the start of "string",
5383 * we know that "tring", "ring" etc will not match too:
5385 if (pattern[0] == '*')
5390 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5392 char *result = NULL;
5393 unsigned res_len = 0;
5394 unsigned repl_len = strlen(repl);
5398 char *s = strstr_pattern(val, pattern, &size);
5402 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5403 memcpy(result + res_len, val, s - val);
5405 strcpy(result + res_len, repl);
5406 res_len += repl_len;
5407 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5413 if (val[0] && result) {
5414 result = xrealloc(result, res_len + strlen(val) + 1);
5415 strcpy(result + res_len, val);
5416 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5418 debug_printf_varexp("result:'%s'\n", result);
5424 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5426 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5428 const char *val = NULL;
5429 char *to_be_freed = NULL;
5434 char exp_save = exp_save; /* for compiler */
5435 char *exp_saveptr; /* points to expansion operator */
5436 char *exp_word = exp_word; /* for compiler */
5439 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5441 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5443 first_char = arg[0] = arg0 & 0x7f;
5446 if (first_char == '#' /* ${#... */
5447 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5449 /* It must be length operator: ${#var} */
5453 /* Maybe handle parameter expansion */
5454 if (exp_saveptr /* if 2nd char is one of expansion operators */
5455 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5457 /* ${?:0}, ${#[:]%0} etc */
5458 exp_saveptr = var + 1;
5460 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5461 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5463 exp_op = exp_save = *exp_saveptr;
5465 exp_word = exp_saveptr + 1;
5466 if (exp_op == ':') {
5467 exp_op = *exp_word++;
5468 //TODO: try ${var:} and ${var:bogus} in non-bash config
5469 if (ENABLE_HUSH_BASH_COMPAT
5470 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5472 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5477 *exp_saveptr = '\0';
5478 } /* else: it's not an expansion op, but bare ${var} */
5481 /* Look up the variable in question */
5482 if (isdigit(var[0])) {
5483 /* parse_dollar should have vetted var for us */
5484 int n = xatoi_positive(var);
5485 if (n < G.global_argc)
5486 val = G.global_argv[n];
5487 /* else val remains NULL: $N with too big N */
5491 val = utoa(G.root_pid);
5493 case '!': /* bg pid */
5494 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5496 case '?': /* exitcode */
5497 val = utoa(G.last_exitcode);
5499 case '#': /* argc */
5500 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5503 val = get_local_var_value(var);
5507 /* Handle any expansions */
5508 if (exp_op == 'L') {
5509 reinit_unicode_for_hush();
5510 debug_printf_expand("expand: length(%s)=", val);
5511 val = utoa(val ? unicode_strlen(val) : 0);
5512 debug_printf_expand("%s\n", val);
5513 } else if (exp_op) {
5514 if (exp_op == '%' || exp_op == '#') {
5515 /* Standard-mandated substring removal ops:
5516 * ${parameter%word} - remove smallest suffix pattern
5517 * ${parameter%%word} - remove largest suffix pattern
5518 * ${parameter#word} - remove smallest prefix pattern
5519 * ${parameter##word} - remove largest prefix pattern
5521 * Word is expanded to produce a glob pattern.
5522 * Then var's value is matched to it and matching part removed.
5524 if (val && val[0]) {
5528 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5529 if (exp_op == *exp_word) /* ## or %% */
5531 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5533 exp_word = exp_exp_word;
5534 /* HACK ALERT. We depend here on the fact that
5535 * G.global_argv and results of utoa and get_local_var_value
5536 * are actually in writable memory:
5537 * scan_and_match momentarily stores NULs there. */
5539 loc = scan_and_match(t, exp_word, scan_flags);
5540 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5541 // exp_op, t, exp_word, loc);
5543 if (loc) { /* match was found */
5544 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5545 val = loc; /* take right part */
5547 val = to_be_freed = xstrndup(val, loc - val); /* left */
5551 #if ENABLE_HUSH_BASH_COMPAT
5552 else if (exp_op == '/' || exp_op == '\\') {
5553 /* It's ${var/[/]pattern[/repl]} thing.
5554 * Note that in encoded form it has TWO parts:
5555 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5556 * and if // is used, it is encoded as \:
5557 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5559 /* Empty variable always gives nothing: */
5560 // "v=''; echo ${v/*/w}" prints "", not "w"
5561 if (val && val[0]) {
5562 /* pattern uses non-standard expansion.
5563 * repl should be unbackslashed and globbed
5564 * by the usual expansion rules:
5566 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5567 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5568 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5569 * v='a bz'; echo ${v/a*z/\z} prints "z"
5570 * (note that a*z _pattern_ is never globbed!)
5572 char *pattern, *repl, *t;
5573 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5575 pattern = xstrdup(exp_word);
5576 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5577 *p++ = SPECIAL_VAR_SYMBOL;
5579 p = strchr(p, SPECIAL_VAR_SYMBOL);
5581 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5582 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5583 /* HACK ALERT. We depend here on the fact that
5584 * G.global_argv and results of utoa and get_local_var_value
5585 * are actually in writable memory:
5586 * replace_pattern momentarily stores NULs there. */
5588 to_be_freed = replace_pattern(t,
5590 (repl ? repl : exp_word),
5592 if (to_be_freed) /* at least one replace happened */
5599 else if (exp_op == ':') {
5600 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_FEATURE_SH_MATH
5601 /* It's ${var:N[:M]} bashism.
5602 * Note that in encoded form it has TWO parts:
5603 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5608 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5611 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5612 *p++ = SPECIAL_VAR_SYMBOL;
5614 p = strchr(p, SPECIAL_VAR_SYMBOL);
5616 len = expand_and_evaluate_arith(exp_word, &errmsg);
5619 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5620 if (len >= 0) { /* bash compat: len < 0 is illegal */
5621 if (beg < 0) /* bash compat */
5623 debug_printf_varexp("from val:'%s'\n", val);
5624 if (len == 0 || !val || beg >= strlen(val)) {
5628 /* Paranoia. What if user entered 9999999999999
5629 * which fits in arith_t but not int? */
5632 val = to_be_freed = xstrndup(val + beg, len);
5634 debug_printf_varexp("val:'%s'\n", val);
5638 die_if_script("malformed ${%s:...}", var);
5641 } else { /* one of "-=+?" */
5642 /* Standard-mandated substitution ops:
5643 * ${var?word} - indicate error if unset
5644 * If var is unset, word (or a message indicating it is unset
5645 * if word is null) is written to standard error
5646 * and the shell exits with a non-zero exit status.
5647 * Otherwise, the value of var is substituted.
5648 * ${var-word} - use default value
5649 * If var is unset, word is substituted.
5650 * ${var=word} - assign and use default value
5651 * If var is unset, word is assigned to var.
5652 * In all cases, final value of var is substituted.
5653 * ${var+word} - use alternative value
5654 * If var is unset, null is substituted.
5655 * Otherwise, word is substituted.
5657 * Word is subjected to tilde expansion, parameter expansion,
5658 * command substitution, and arithmetic expansion.
5659 * If word is not needed, it is not expanded.
5661 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5662 * but also treat null var as if it is unset.
5664 int use_word = (!val || ((exp_save == ':') && !val[0]));
5666 use_word = !use_word;
5667 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5668 (exp_save == ':') ? "true" : "false", use_word);
5670 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5672 exp_word = to_be_freed;
5673 if (exp_op == '?') {
5674 /* mimic bash message */
5675 die_if_script("%s: %s",
5677 exp_word[0] ? exp_word : "parameter null or not set"
5679 //TODO: how interactive bash aborts expansion mid-command?
5684 if (exp_op == '=') {
5685 /* ${var=[word]} or ${var:=[word]} */
5686 if (isdigit(var[0]) || var[0] == '#') {
5687 /* mimic bash message */
5688 die_if_script("$%s: cannot assign in this way", var);
5691 char *new_var = xasprintf("%s=%s", var, val);
5692 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5696 } /* one of "-=+?" */
5698 *exp_saveptr = exp_save;
5704 *to_be_freed_pp = to_be_freed;
5708 /* Expand all variable references in given string, adding words to list[]
5709 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5710 * to be filled). This routine is extremely tricky: has to deal with
5711 * variables/parameters with whitespace, $* and $@, and constructs like
5712 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5713 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5715 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5716 * expansion of right-hand side of assignment == 1-element expand.
5718 char cant_be_null = 0; /* only bit 0x80 matters */
5719 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5722 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5723 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5724 debug_print_list("expand_vars_to_list", output, n);
5725 n = o_save_ptr(output, n);
5726 debug_print_list("expand_vars_to_list[0]", output, n);
5728 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5730 char *to_be_freed = NULL;
5731 const char *val = NULL;
5732 #if ENABLE_HUSH_TICK
5733 o_string subst_result = NULL_O_STRING;
5735 #if ENABLE_FEATURE_SH_MATH
5736 char arith_buf[sizeof(arith_t)*3 + 2];
5740 o_addchr(output, '\0');
5741 n = o_save_ptr(output, n);
5745 o_addblock(output, arg, p - arg);
5746 debug_print_list("expand_vars_to_list[1]", output, n);
5748 p = strchr(p, SPECIAL_VAR_SYMBOL);
5750 /* Fetch special var name (if it is indeed one of them)
5751 * and quote bit, force the bit on if singleword expansion -
5752 * important for not getting v=$@ expand to many words. */
5753 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5755 /* Is this variable quoted and thus expansion can't be null?
5756 * "$@" is special. Even if quoted, it can still
5757 * expand to nothing (not even an empty string),
5758 * thus it is excluded. */
5759 if ((first_ch & 0x7f) != '@')
5760 cant_be_null |= first_ch;
5762 switch (first_ch & 0x7f) {
5763 /* Highest bit in first_ch indicates that var is double-quoted */
5767 if (!G.global_argv[1])
5770 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5771 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5772 while (G.global_argv[i]) {
5773 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5774 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5775 if (G.global_argv[i++][0] && G.global_argv[i]) {
5776 /* this argv[] is not empty and not last:
5777 * put terminating NUL, start new word */
5778 o_addchr(output, '\0');
5779 debug_print_list("expand_vars_to_list[2]", output, n);
5780 n = o_save_ptr(output, n);
5781 debug_print_list("expand_vars_to_list[3]", output, n);
5785 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5786 * and in this case should treat it like '$*' - see 'else...' below */
5787 if (first_ch == ('@'|0x80) /* quoted $@ */
5788 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5791 o_addQstr(output, G.global_argv[i]);
5792 if (++i >= G.global_argc)
5794 o_addchr(output, '\0');
5795 debug_print_list("expand_vars_to_list[4]", output, n);
5796 n = o_save_ptr(output, n);
5798 } else { /* quoted $* (or v="$@" case): add as one word */
5800 o_addQstr(output, G.global_argv[i]);
5801 if (!G.global_argv[++i])
5804 o_addchr(output, G.ifs[0]);
5806 output->has_quoted_part = 1;
5810 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5811 /* "Empty variable", used to make "" etc to not disappear */
5812 output->has_quoted_part = 1;
5814 cant_be_null = 0x80;
5816 #if ENABLE_HUSH_TICK
5817 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5818 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5820 /* Can't just stuff it into output o_string,
5821 * expanded result may need to be globbed
5822 * and $IFS-splitted */
5823 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5824 G.last_exitcode = process_command_subs(&subst_result, arg);
5825 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5826 val = subst_result.data;
5829 #if ENABLE_FEATURE_SH_MATH
5830 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5833 arg++; /* skip '+' */
5834 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5835 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5836 res = expand_and_evaluate_arith(arg, NULL);
5837 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5838 sprintf(arith_buf, ARITH_FMT, res);
5844 val = expand_one_var(&to_be_freed, arg, &p);
5845 IF_HUSH_TICK(store_val:)
5846 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5847 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5848 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5849 if (val && val[0]) {
5850 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5853 } else { /* quoted $VAR, val will be appended below */
5854 output->has_quoted_part = 1;
5855 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5856 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5859 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5861 if (val && val[0]) {
5862 o_addQstr(output, val);
5866 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5867 * Do the check to avoid writing to a const string. */
5868 if (*p != SPECIAL_VAR_SYMBOL)
5869 *p = SPECIAL_VAR_SYMBOL;
5871 #if ENABLE_HUSH_TICK
5872 o_free(&subst_result);
5875 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5879 o_addchr(output, '\0');
5880 n = o_save_ptr(output, n);
5882 debug_print_list("expand_vars_to_list[a]", output, n);
5883 /* this part is literal, and it was already pre-quoted
5884 * if needed (much earlier), do not use o_addQstr here! */
5885 o_addstr_with_NUL(output, arg);
5886 debug_print_list("expand_vars_to_list[b]", output, n);
5887 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5888 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5891 /* allow to reuse list[n] later without re-growth */
5892 output->has_empty_slot = 1;
5894 o_addchr(output, '\0');
5900 static char **expand_variables(char **argv, unsigned expflags)
5904 o_string output = NULL_O_STRING;
5906 output.o_expflags = expflags;
5910 n = expand_vars_to_list(&output, n, *argv);
5913 debug_print_list("expand_variables", &output, n);
5915 /* output.data (malloced in one block) gets returned in "list" */
5916 list = o_finalize_list(&output, n);
5917 debug_print_strings("expand_variables[1]", list);
5921 static char **expand_strvec_to_strvec(char **argv)
5923 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5926 #if ENABLE_HUSH_BASH_COMPAT
5927 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5929 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5933 /* Used for expansion of right hand of assignments,
5934 * $((...)), heredocs, variable espansion parts.
5936 * NB: should NOT do globbing!
5937 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5939 static char *expand_string_to_string(const char *str, int do_unbackslash)
5941 #if !ENABLE_HUSH_BASH_COMPAT
5942 const int do_unbackslash = 1;
5944 char *argv[2], **list;
5946 debug_printf_expand("string_to_string<='%s'\n", str);
5947 /* This is generally an optimization, but it also
5948 * handles "", which otherwise trips over !list[0] check below.
5949 * (is this ever happens that we actually get str="" here?)
5951 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5952 //TODO: Can use on strings with \ too, just unbackslash() them?
5953 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5954 return xstrdup(str);
5957 argv[0] = (char*)str;
5959 list = expand_variables(argv, do_unbackslash
5960 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5961 : EXP_FLAG_SINGLEWORD
5964 if (!list[0] || list[1])
5965 bb_error_msg_and_die("BUG in varexp2");
5966 /* actually, just move string 2*sizeof(char*) bytes back */
5967 overlapping_strcpy((char*)list, list[0]);
5969 unbackslash((char*)list);
5970 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5974 /* Used for "eval" builtin */
5975 static char* expand_strvec_to_string(char **argv)
5979 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5980 /* Convert all NULs to spaces */
5985 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5986 bb_error_msg_and_die("BUG in varexp3");
5987 /* bash uses ' ' regardless of $IFS contents */
5992 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
5993 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5997 static char **expand_assignments(char **argv, int count)
6002 G.expanded_assignments = p = NULL;
6003 /* Expand assignments into one string each */
6004 for (i = 0; i < count; i++) {
6005 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6007 G.expanded_assignments = NULL;
6012 static void switch_off_special_sigs(unsigned mask)
6015 while ((mask >>= 1) != 0) {
6019 #if ENABLE_HUSH_TRAP
6021 if (G_traps[sig] && !G_traps[sig][0])
6022 /* trap is '', has to remain SIG_IGN */
6025 G_traps[sig] = NULL;
6028 /* We are here only if no trap or trap was not '' */
6029 install_sighandler(sig, SIG_DFL);
6035 void re_execute_shell(char ***to_free, const char *s,
6036 char *g_argv0, char **g_argv,
6037 char **builtin_argv) NORETURN;
6039 static void reset_traps_to_defaults(void)
6041 /* This function is always called in a child shell
6042 * after fork (not vfork, NOMMU doesn't use this function).
6044 IF_HUSH_TRAP(unsigned sig;)
6047 /* Child shells are not interactive.
6048 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6049 * Testcase: (while :; do :; done) + ^Z should background.
6050 * Same goes for SIGTERM, SIGHUP, SIGINT.
6052 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6053 if (!G_traps && !mask)
6054 return; /* already no traps and no special sigs */
6056 /* Switch off special sigs */
6057 switch_off_special_sigs(mask);
6058 # if ENABLE_HUSH_JOB
6059 G_fatal_sig_mask = 0;
6061 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6062 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6063 * remain set in G.special_sig_mask */
6065 # if ENABLE_HUSH_TRAP
6069 /* Reset all sigs to default except ones with empty traps */
6070 for (sig = 0; sig < NSIG; sig++) {
6072 continue; /* no trap: nothing to do */
6073 if (!G_traps[sig][0])
6074 continue; /* empty trap: has to remain SIG_IGN */
6075 /* sig has non-empty trap, reset it: */
6077 G_traps[sig] = NULL;
6078 /* There is no signal for trap 0 (EXIT) */
6081 install_sighandler(sig, pick_sighandler(sig));
6088 static void re_execute_shell(char ***to_free, const char *s,
6089 char *g_argv0, char **g_argv,
6090 char **builtin_argv) NORETURN;
6091 static void re_execute_shell(char ***to_free, const char *s,
6092 char *g_argv0, char **g_argv,
6093 char **builtin_argv)
6095 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6096 /* delims + 2 * (number of bytes in printed hex numbers) */
6097 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6098 char *heredoc_argv[4];
6099 struct variable *cur;
6100 # if ENABLE_HUSH_FUNCTIONS
6101 struct function *funcp;
6105 unsigned long long empty_trap_mask;
6107 if (!g_argv0) { /* heredoc */
6108 argv = heredoc_argv;
6109 argv[0] = (char *) G.argv0_for_re_execing;
6110 argv[1] = (char *) "-<";
6111 argv[2] = (char *) s;
6113 pp = &argv[3]; /* used as pointer to empty environment */
6119 if (pp) while (*pp++)
6122 empty_trap_mask = 0;
6125 for (sig = 1; sig < NSIG; sig++) {
6126 if (G_traps[sig] && !G_traps[sig][0])
6127 empty_trap_mask |= 1LL << sig;
6131 sprintf(param_buf, NOMMU_HACK_FMT
6132 , (unsigned) G.root_pid
6133 , (unsigned) G.root_ppid
6134 , (unsigned) G.last_bg_pid
6135 , (unsigned) G.last_exitcode
6138 IF_HUSH_LOOPS(, G.depth_of_loop)
6140 # undef NOMMU_HACK_FMT
6141 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6142 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6145 for (cur = G.top_var; cur; cur = cur->next) {
6146 if (!cur->flg_export || cur->flg_read_only)
6149 # if ENABLE_HUSH_FUNCTIONS
6150 for (funcp = G.top_func; funcp; funcp = funcp->next)
6156 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6157 *pp++ = (char *) G.argv0_for_re_execing;
6159 for (cur = G.top_var; cur; cur = cur->next) {
6160 if (strcmp(cur->varstr, hush_version_str) == 0)
6162 if (cur->flg_read_only) {
6163 *pp++ = (char *) "-R";
6164 *pp++ = cur->varstr;
6165 } else if (!cur->flg_export) {
6166 *pp++ = (char *) "-V";
6167 *pp++ = cur->varstr;
6170 # if ENABLE_HUSH_FUNCTIONS
6171 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6172 *pp++ = (char *) "-F";
6173 *pp++ = funcp->name;
6174 *pp++ = funcp->body_as_string;
6177 /* We can pass activated traps here. Say, -Tnn:trap_string
6179 * However, POSIX says that subshells reset signals with traps
6181 * I tested bash-3.2 and it not only does that with true subshells
6182 * of the form ( list ), but with any forked children shells.
6183 * I set trap "echo W" WINCH; and then tried:
6185 * { echo 1; sleep 20; echo 2; } &
6186 * while true; do echo 1; sleep 20; echo 2; break; done &
6187 * true | { echo 1; sleep 20; echo 2; } | cat
6189 * In all these cases sending SIGWINCH to the child shell
6190 * did not run the trap. If I add trap "echo V" WINCH;
6191 * _inside_ group (just before echo 1), it works.
6193 * I conclude it means we don't need to pass active traps here.
6195 *pp++ = (char *) "-c";
6198 while (*++builtin_argv)
6199 *pp++ = *builtin_argv;
6200 *pp++ = (char *) "";
6205 /* *pp = NULL; - is already there */
6209 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6210 /* Don't propagate SIG_IGN to the child */
6211 if (SPECIAL_JOBSTOP_SIGS != 0)
6212 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6213 execve(bb_busybox_exec_path, argv, pp);
6214 /* Fallback. Useful for init=/bin/hush usage etc */
6215 if (argv[0][0] == '/')
6216 execve(argv[0], argv, pp);
6217 xfunc_error_retval = 127;
6218 bb_error_msg_and_die("can't re-execute the shell");
6220 #endif /* !BB_MMU */
6223 static int run_and_free_list(struct pipe *pi);
6225 /* Executing from string: eval, sh -c '...'
6226 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6227 * end_trigger controls how often we stop parsing
6228 * NUL: parse all, execute, return
6229 * ';': parse till ';' or newline, execute, repeat till EOF
6231 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6233 /* Why we need empty flag?
6234 * An obscure corner case "false; ``; echo $?":
6235 * empty command in `` should still set $? to 0.
6236 * But we can't just set $? to 0 at the start,
6237 * this breaks "false; echo `echo $?`" case.
6241 struct pipe *pipe_list;
6243 #if ENABLE_HUSH_INTERACTIVE
6244 if (end_trigger == ';')
6245 inp->promptmode = 0; /* PS1 */
6247 pipe_list = parse_stream(NULL, inp, end_trigger);
6248 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6249 /* If we are in "big" script
6250 * (not in `cmd` or something similar)...
6252 if (pipe_list == ERR_PTR && end_trigger == ';') {
6253 /* Discard cached input (rest of line) */
6254 int ch = inp->last_char;
6255 while (ch != EOF && ch != '\n') {
6256 //bb_error_msg("Discarded:'%c'", ch);
6261 /* This stream isn't empty */
6265 if (!pipe_list && empty)
6266 G.last_exitcode = 0;
6269 debug_print_tree(pipe_list, 0);
6270 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6271 run_and_free_list(pipe_list);
6273 if (G_flag_return_in_progress == 1)
6278 static void parse_and_run_string(const char *s)
6280 struct in_str input;
6281 setup_string_in_str(&input, s);
6282 parse_and_run_stream(&input, '\0');
6285 static void parse_and_run_file(FILE *f)
6287 struct in_str input;
6288 setup_file_in_str(&input, f);
6289 parse_and_run_stream(&input, ';');
6292 #if ENABLE_HUSH_TICK
6293 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6298 char **to_free = NULL;
6302 pid = BB_MMU ? xfork() : xvfork();
6303 if (pid == 0) { /* child */
6304 disable_restore_tty_pgrp_on_exit();
6305 /* Process substitution is not considered to be usual
6306 * 'command execution'.
6307 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6314 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6315 close(channel[0]); /* NB: close _first_, then move fd! */
6316 xmove_fd(channel[1], 1);
6317 /* Prevent it from trying to handle ctrl-z etc */
6318 IF_HUSH_JOB(G.run_list_level = 1;)
6319 # if ENABLE_HUSH_TRAP
6320 /* Awful hack for `trap` or $(trap).
6322 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6323 * contains an example where "trap" is executed in a subshell:
6325 * save_traps=$(trap)
6327 * eval "$save_traps"
6329 * Standard does not say that "trap" in subshell shall print
6330 * parent shell's traps. It only says that its output
6331 * must have suitable form, but then, in the above example
6332 * (which is not supposed to be normative), it implies that.
6334 * bash (and probably other shell) does implement it
6335 * (traps are reset to defaults, but "trap" still shows them),
6336 * but as a result, "trap" logic is hopelessly messed up:
6339 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6340 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6341 * # true | trap <--- trap is in subshell - no output (ditto)
6342 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6343 * trap -- 'echo Ho' SIGWINCH
6344 * # echo `(trap)` <--- in subshell in subshell - output
6345 * trap -- 'echo Ho' SIGWINCH
6346 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6347 * trap -- 'echo Ho' SIGWINCH
6349 * The rules when to forget and when to not forget traps
6350 * get really complex and nonsensical.
6352 * Our solution: ONLY bare $(trap) or `trap` is special.
6354 s = skip_whitespace(s);
6355 if (is_prefixed_with(s, "trap")
6356 && skip_whitespace(s + 4)[0] == '\0'
6358 static const char *const argv[] = { NULL, NULL };
6359 builtin_trap((char**)argv);
6360 fflush_all(); /* important */
6365 reset_traps_to_defaults();
6366 parse_and_run_string(s);
6367 _exit(G.last_exitcode);
6369 /* We re-execute after vfork on NOMMU. This makes this script safe:
6370 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6371 * huge=`cat BIG` # was blocking here forever
6374 re_execute_shell(&to_free,
6384 # if ENABLE_HUSH_FAST
6386 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6387 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6388 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6390 enable_restore_tty_pgrp_on_exit();
6395 return remember_FILE(xfdopen_for_read(channel[0]));
6398 /* Return code is exit status of the process that is run. */
6399 static int process_command_subs(o_string *dest, const char *s)
6402 struct in_str pipe_str;
6404 int status, ch, eol_cnt;
6406 fp = generate_stream_from_string(s, &pid);
6408 /* Now send results of command back into original context */
6409 setup_file_in_str(&pipe_str, fp);
6411 while ((ch = i_getch(&pipe_str)) != EOF) {
6417 o_addchr(dest, '\n');
6420 o_addQchr(dest, ch);
6423 debug_printf("done reading from `cmd` pipe, closing it\n");
6424 fclose_and_forget(fp);
6425 /* We need to extract exitcode. Test case
6426 * "true; echo `sleep 1; false` $?"
6428 safe_waitpid(pid, &status, 0);
6429 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6430 return WEXITSTATUS(status);
6432 #endif /* ENABLE_HUSH_TICK */
6435 static void setup_heredoc(struct redir_struct *redir)
6437 struct fd_pair pair;
6440 /* the _body_ of heredoc (misleading field name) */
6441 const char *heredoc = redir->rd_filename;
6448 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6449 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6453 len = strlen(heredoc);
6455 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6457 xmove_fd(pair.rd, redir->rd_fd);
6459 /* Try writing without forking. Newer kernels have
6460 * dynamically growing pipes. Must use non-blocking write! */
6463 written = write(pair.wr, heredoc, len);
6474 ndelay_off(pair.wr);
6476 /* Okay, pipe buffer was not big enough */
6477 /* Note: we must not create a stray child (bastard? :)
6478 * for the unsuspecting parent process. Child creates a grandchild
6479 * and exits before parent execs the process which consumes heredoc
6480 * (that exec happens after we return from this function) */
6487 disable_restore_tty_pgrp_on_exit();
6488 pid = BB_MMU ? xfork() : xvfork();
6492 close(redir->rd_fd); /* read side of the pipe */
6494 full_write(pair.wr, heredoc, len); /* may loop or block */
6497 /* Delegate blocking writes to another process */
6498 xmove_fd(pair.wr, STDOUT_FILENO);
6499 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6503 #if ENABLE_HUSH_FAST
6505 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6507 enable_restore_tty_pgrp_on_exit();
6513 wait(NULL); /* wait till child has died */
6516 /* fd: redirect wants this fd to be used (e.g. 3>file).
6517 * Move all conflicting internally used fds,
6518 * and remember them so that we can restore them later.
6520 static int save_fds_on_redirect(int fd, int squirrel[3])
6523 /* Handle redirects of fds 0,1,2 */
6525 /* If we collide with an already moved stdio fd... */
6526 if (fd == squirrel[0]) {
6527 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6530 if (fd == squirrel[1]) {
6531 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6534 if (fd == squirrel[2]) {
6535 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6538 /* If we are about to redirect stdio fd, and did not yet move it... */
6539 if (fd <= 2 && squirrel[fd] < 0) {
6540 /* We avoid taking stdio fds */
6541 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6542 if (squirrel[fd] < 0 && errno != EBADF)
6544 return 0; /* "we did not close fd" */
6548 #if ENABLE_HUSH_INTERACTIVE
6549 if (fd != 0 && fd == G.interactive_fd) {
6550 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6555 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6556 * (1) Redirect in a forked child. No need to save FILEs' fds,
6557 * we aren't going to use them anymore, ok to trash.
6558 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6559 * but how are we doing to use them?
6560 * "fileno(fd) = new_fd" can't be done.
6565 return save_FILEs_on_redirect(fd);
6568 static void restore_redirects(int squirrel[3])
6571 for (i = 0; i <= 2; i++) {
6574 /* We simply die on error */
6579 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6581 restore_redirected_FILEs();
6584 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6585 * and stderr if they are redirected. */
6586 static int setup_redirects(struct command *prog, int squirrel[])
6589 struct redir_struct *redir;
6591 for (redir = prog->redirects; redir; redir = redir->next) {
6592 if (redir->rd_type == REDIRECT_HEREDOC2) {
6593 /* "rd_fd<<HERE" case */
6594 save_fds_on_redirect(redir->rd_fd, squirrel);
6595 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6597 debug_printf_parse("set heredoc '%s'\n",
6598 redir->rd_filename);
6599 setup_heredoc(redir);
6603 if (redir->rd_dup == REDIRFD_TO_FILE) {
6604 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6606 if (redir->rd_filename == NULL) {
6609 * "cmd >" (no filename)
6610 * "cmd > <file" (2nd redirect starts too early)
6612 die_if_script("syntax error: %s", "invalid redirect");
6615 mode = redir_table[redir->rd_type].mode;
6616 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6617 openfd = open_or_warn(p, mode);
6620 /* Error message from open_or_warn can be lost
6621 * if stderr has been redirected, but bash
6622 * and ash both lose it as well
6623 * (though zsh doesn't!)
6628 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6629 openfd = redir->rd_dup;
6632 if (openfd != redir->rd_fd) {
6633 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6634 if (openfd == REDIRFD_CLOSE) {
6635 /* "rd_fd >&-" means "close me" */
6637 /* ^^^ optimization: saving may already
6638 * have closed it. If not... */
6639 close(redir->rd_fd);
6642 xdup2(openfd, redir->rd_fd);
6643 if (redir->rd_dup == REDIRFD_TO_FILE)
6644 /* "rd_fd > FILE" */
6646 /* else: "rd_fd > rd_dup" */
6653 static char *find_in_path(const char *arg)
6656 const char *PATH = get_local_var_value("PATH");
6662 const char *end = strchrnul(PATH, ':');
6663 int sz = end - PATH; /* must be int! */
6667 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6669 /* We have xxx::yyyy in $PATH,
6670 * it means "use current dir" */
6673 if (access(ret, F_OK) == 0)
6686 static const struct built_in_command *find_builtin_helper(const char *name,
6687 const struct built_in_command *x,
6688 const struct built_in_command *end)
6691 if (strcmp(name, x->b_cmd) != 0) {
6695 debug_printf_exec("found builtin '%s'\n", name);
6700 static const struct built_in_command *find_builtin1(const char *name)
6702 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6704 static const struct built_in_command *find_builtin(const char *name)
6706 const struct built_in_command *x = find_builtin1(name);
6709 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6712 #if ENABLE_HUSH_FUNCTIONS
6713 static struct function **find_function_slot(const char *name)
6715 struct function **funcpp = &G.top_func;
6717 if (strcmp(name, (*funcpp)->name) == 0) {
6720 funcpp = &(*funcpp)->next;
6725 static const struct function *find_function(const char *name)
6727 const struct function *funcp = *find_function_slot(name);
6729 debug_printf_exec("found function '%s'\n", name);
6733 /* Note: takes ownership on name ptr */
6734 static struct function *new_function(char *name)
6736 struct function **funcpp = find_function_slot(name);
6737 struct function *funcp = *funcpp;
6739 if (funcp != NULL) {
6740 struct command *cmd = funcp->parent_cmd;
6741 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6743 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6745 /* Note: if !funcp->body, do not free body_as_string!
6746 * This is a special case of "-F name body" function:
6747 * body_as_string was not malloced! */
6749 free_pipe_list(funcp->body);
6751 free(funcp->body_as_string);
6755 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6756 cmd->argv[0] = funcp->name;
6757 cmd->group = funcp->body;
6759 cmd->group_as_string = funcp->body_as_string;
6763 debug_printf_exec("remembering new function '%s'\n", name);
6764 funcp = *funcpp = xzalloc(sizeof(*funcp));
6765 /*funcp->next = NULL;*/
6772 # if ENABLE_HUSH_UNSET
6773 static void unset_func(const char *name)
6775 struct function **funcpp = find_function_slot(name);
6776 struct function *funcp = *funcpp;
6778 if (funcp != NULL) {
6779 debug_printf_exec("freeing function '%s'\n", funcp->name);
6780 *funcpp = funcp->next;
6781 /* funcp is unlinked now, deleting it.
6782 * Note: if !funcp->body, the function was created by
6783 * "-F name body", do not free ->body_as_string
6784 * and ->name as they were not malloced. */
6786 free_pipe_list(funcp->body);
6789 free(funcp->body_as_string);
6798 #define exec_function(to_free, funcp, argv) \
6799 exec_function(funcp, argv)
6801 static void exec_function(char ***to_free,
6802 const struct function *funcp,
6803 char **argv) NORETURN;
6804 static void exec_function(char ***to_free,
6805 const struct function *funcp,
6811 argv[0] = G.global_argv[0];
6812 G.global_argv = argv;
6816 /* On MMU, funcp->body is always non-NULL */
6817 n = run_list(funcp->body);
6821 re_execute_shell(to_free,
6822 funcp->body_as_string,
6829 static int run_function(const struct function *funcp, char **argv)
6835 save_and_replace_G_args(&sv, argv);
6837 /* "we are in function, ok to use return" */
6838 sv_flg = G_flag_return_in_progress;
6839 G_flag_return_in_progress = -1;
6840 # if ENABLE_HUSH_LOCAL
6841 G.func_nest_level++;
6844 /* On MMU, funcp->body is always non-NULL */
6847 /* Function defined by -F */
6848 parse_and_run_string(funcp->body_as_string);
6849 rc = G.last_exitcode;
6853 rc = run_list(funcp->body);
6856 # if ENABLE_HUSH_LOCAL
6858 struct variable *var;
6859 struct variable **var_pp;
6861 var_pp = &G.top_var;
6862 while ((var = *var_pp) != NULL) {
6863 if (var->func_nest_level < G.func_nest_level) {
6864 var_pp = &var->next;
6868 if (var->flg_export)
6869 bb_unsetenv(var->varstr);
6870 /* Remove from global list */
6871 *var_pp = var->next;
6877 G.func_nest_level--;
6880 G_flag_return_in_progress = sv_flg;
6882 restore_G_args(&sv, argv);
6886 #endif /* ENABLE_HUSH_FUNCTIONS */
6890 #define exec_builtin(to_free, x, argv) \
6891 exec_builtin(x, argv)
6893 #define exec_builtin(to_free, x, argv) \
6894 exec_builtin(to_free, argv)
6896 static void exec_builtin(char ***to_free,
6897 const struct built_in_command *x,
6898 char **argv) NORETURN;
6899 static void exec_builtin(char ***to_free,
6900 const struct built_in_command *x,
6906 rcode = x->b_function(argv);
6911 /* On NOMMU, we must never block!
6912 * Example: { sleep 99 | read line; } & echo Ok
6914 re_execute_shell(to_free,
6923 static void execvp_or_die(char **argv) NORETURN;
6924 static void execvp_or_die(char **argv)
6927 debug_printf_exec("execing '%s'\n", argv[0]);
6928 /* Don't propagate SIG_IGN to the child */
6929 if (SPECIAL_JOBSTOP_SIGS != 0)
6930 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6931 execvp(argv[0], argv);
6933 if (errno == EACCES) e = 126;
6934 if (errno == ENOENT) e = 127;
6935 bb_perror_msg("can't execute '%s'", argv[0]);
6939 #if ENABLE_HUSH_MODE_X
6940 static void dump_cmd_in_x_mode(char **argv)
6942 if (G_x_mode && argv) {
6943 /* We want to output the line in one write op */
6951 len += strlen(argv[n++]) + 1;
6957 p += sprintf(p, " %s", argv[n++]);
6965 # define dump_cmd_in_x_mode(argv) ((void)0)
6969 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6970 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6971 #define pseudo_exec(nommu_save, command, argv_expanded) \
6972 pseudo_exec(command, argv_expanded)
6975 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6977 * Don't exit() here. If you don't exec, use _exit instead.
6978 * The at_exit handlers apparently confuse the calling process,
6979 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6981 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6982 char **argv, int assignment_cnt,
6983 char **argv_expanded) NORETURN;
6984 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6985 char **argv, int assignment_cnt,
6986 char **argv_expanded)
6990 new_env = expand_assignments(argv, assignment_cnt);
6991 dump_cmd_in_x_mode(new_env);
6993 if (!argv[assignment_cnt]) {
6994 /* Case when we are here: ... | var=val | ...
6995 * (note that we do not exit early, i.e., do not optimize out
6996 * expand_assignments(): think about ... | var=`sleep 1` | ...
6998 free_strings(new_env);
6999 _exit(EXIT_SUCCESS);
7003 set_vars_and_save_old(new_env);
7004 free(new_env); /* optional */
7005 /* we can also destroy set_vars_and_save_old's return value,
7008 nommu_save->new_env = new_env;
7009 nommu_save->old_vars = set_vars_and_save_old(new_env);
7012 if (argv_expanded) {
7013 argv = argv_expanded;
7015 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7017 nommu_save->argv = argv;
7020 dump_cmd_in_x_mode(argv);
7022 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7023 if (strchr(argv[0], '/') != NULL)
7027 /* Check if the command matches any of the builtins.
7028 * Depending on context, this might be redundant. But it's
7029 * easier to waste a few CPU cycles than it is to figure out
7030 * if this is one of those cases.
7033 /* On NOMMU, it is more expensive to re-execute shell
7034 * just in order to run echo or test builtin.
7035 * It's better to skip it here and run corresponding
7036 * non-builtin later. */
7037 const struct built_in_command *x;
7038 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7040 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7043 #if ENABLE_HUSH_FUNCTIONS
7044 /* Check if the command matches any functions */
7046 const struct function *funcp = find_function(argv[0]);
7048 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7053 #if ENABLE_FEATURE_SH_STANDALONE
7054 /* Check if the command matches any busybox applets */
7056 int a = find_applet_by_name(argv[0]);
7058 # if BB_MMU /* see above why on NOMMU it is not allowed */
7059 if (APPLET_IS_NOEXEC(a)) {
7060 /* Do not leak open fds from opened script files etc */
7061 close_all_FILE_list();
7062 debug_printf_exec("running applet '%s'\n", argv[0]);
7063 run_applet_no_and_exit(a, argv);
7066 /* Re-exec ourselves */
7067 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7068 /* Don't propagate SIG_IGN to the child */
7069 if (SPECIAL_JOBSTOP_SIGS != 0)
7070 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7071 execv(bb_busybox_exec_path, argv);
7072 /* If they called chroot or otherwise made the binary no longer
7073 * executable, fall through */
7078 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7081 execvp_or_die(argv);
7084 /* Called after [v]fork() in run_pipe
7086 static void pseudo_exec(nommu_save_t *nommu_save,
7087 struct command *command,
7088 char **argv_expanded) NORETURN;
7089 static void pseudo_exec(nommu_save_t *nommu_save,
7090 struct command *command,
7091 char **argv_expanded)
7093 if (command->argv) {
7094 pseudo_exec_argv(nommu_save, command->argv,
7095 command->assignment_cnt, argv_expanded);
7098 if (command->group) {
7099 /* Cases when we are here:
7102 * ... | ( list ) | ...
7103 * ... | { list } | ...
7107 debug_printf_exec("pseudo_exec: run_list\n");
7108 reset_traps_to_defaults();
7109 rcode = run_list(command->group);
7110 /* OK to leak memory by not calling free_pipe_list,
7111 * since this process is about to exit */
7114 re_execute_shell(&nommu_save->argv_from_re_execing,
7115 command->group_as_string,
7122 /* Case when we are here: ... | >file */
7123 debug_printf_exec("pseudo_exec'ed null command\n");
7124 _exit(EXIT_SUCCESS);
7128 static const char *get_cmdtext(struct pipe *pi)
7134 /* This is subtle. ->cmdtext is created only on first backgrounding.
7135 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7136 * On subsequent bg argv is trashed, but we won't use it */
7140 argv = pi->cmds[0].argv;
7142 pi->cmdtext = xzalloc(1);
7147 len += strlen(*argv) + 1;
7151 argv = pi->cmds[0].argv;
7153 p = stpcpy(p, *argv);
7160 static void insert_bg_job(struct pipe *pi)
7162 struct pipe *job, **jobp;
7165 /* Linear search for the ID of the job to use */
7167 for (job = G.job_list; job; job = job->next)
7168 if (job->jobid >= pi->jobid)
7169 pi->jobid = job->jobid + 1;
7171 /* Add job to the list of running jobs */
7173 while ((job = *jobp) != NULL)
7175 job = *jobp = xmalloc(sizeof(*job));
7177 *job = *pi; /* physical copy */
7179 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7180 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7181 for (i = 0; i < pi->num_cmds; i++) {
7182 job->cmds[i].pid = pi->cmds[i].pid;
7183 /* all other fields are not used and stay zero */
7185 job->cmdtext = xstrdup(get_cmdtext(pi));
7187 if (G_interactive_fd)
7188 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7189 G.last_jobid = job->jobid;
7192 static void remove_bg_job(struct pipe *pi)
7194 struct pipe *prev_pipe;
7196 if (pi == G.job_list) {
7197 G.job_list = pi->next;
7199 prev_pipe = G.job_list;
7200 while (prev_pipe->next != pi)
7201 prev_pipe = prev_pipe->next;
7202 prev_pipe->next = pi->next;
7205 G.last_jobid = G.job_list->jobid;
7210 /* Remove a backgrounded job */
7211 static void delete_finished_bg_job(struct pipe *pi)
7218 static int job_exited_or_stopped(struct pipe *pi)
7222 if (pi->alive_cmds != pi->stopped_cmds)
7225 /* All processes in fg pipe have exited or stopped */
7229 rcode = pi->cmds[i].cmd_exitcode;
7230 /* usually last process gives overall exitstatus,
7231 * but with "set -o pipefail", last *failed* process does */
7232 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7235 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7239 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7246 dead = WIFEXITED(status) || WIFSIGNALED(status);
7249 if (WIFSTOPPED(status))
7250 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7251 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7252 if (WIFSIGNALED(status))
7253 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7254 childpid, WTERMSIG(status), WEXITSTATUS(status));
7255 if (WIFEXITED(status))
7256 debug_printf_jobs("pid %d exited, exitcode %d\n",
7257 childpid, WEXITSTATUS(status));
7259 /* Were we asked to wait for a fg pipe? */
7261 i = fg_pipe->num_cmds;
7266 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7267 if (fg_pipe->cmds[i].pid != childpid)
7271 fg_pipe->cmds[i].pid = 0;
7272 fg_pipe->alive_cmds--;
7273 ex = WEXITSTATUS(status);
7274 /* bash prints killer signal's name for *last*
7275 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7276 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7278 if (WIFSIGNALED(status)) {
7279 int sig = WTERMSIG(status);
7280 if (i == fg_pipe->num_cmds-1)
7281 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7282 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7283 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7284 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7285 * Maybe we need to use sig | 128? */
7288 fg_pipe->cmds[i].cmd_exitcode = ex;
7290 fg_pipe->stopped_cmds++;
7292 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7293 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7294 rcode = job_exited_or_stopped(fg_pipe);
7296 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7297 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7298 * and "killall -STOP cat" */
7299 if (G_interactive_fd) {
7301 if (fg_pipe->alive_cmds != 0)
7302 insert_bg_job(fg_pipe);
7306 if (fg_pipe->alive_cmds == 0)
7309 /* There are still running processes in the fg_pipe */
7312 /* It wasnt in fg_pipe, look for process in bg pipes */
7316 /* We were asked to wait for bg or orphaned children */
7317 /* No need to remember exitcode in this case */
7318 for (pi = G.job_list; pi; pi = pi->next) {
7319 for (i = 0; i < pi->num_cmds; i++) {
7320 if (pi->cmds[i].pid == childpid)
7321 goto found_pi_and_prognum;
7324 /* Happens when shell is used as init process (init=/bin/sh) */
7325 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7326 return -1; /* this wasn't a process from fg_pipe */
7328 found_pi_and_prognum:
7331 pi->cmds[i].pid = 0;
7332 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7333 if (WIFSIGNALED(status))
7334 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7336 if (!pi->alive_cmds) {
7337 if (G_interactive_fd)
7338 printf(JOB_STATUS_FORMAT, pi->jobid,
7339 "Done", pi->cmdtext);
7340 delete_finished_bg_job(pi);
7347 return -1; /* this wasn't a process from fg_pipe */
7350 /* Check to see if any processes have exited -- if they have,
7351 * figure out why and see if a job has completed.
7353 * If non-NULL fg_pipe: wait for its completion or stop.
7354 * Return its exitcode or zero if stopped.
7356 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7357 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7358 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7359 * or 0 if no children changed status.
7361 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7362 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7363 * or 0 if no children changed status.
7365 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7371 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7373 attributes = WUNTRACED;
7374 if (fg_pipe == NULL)
7375 attributes |= WNOHANG;
7378 #if ENABLE_HUSH_FAST
7379 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7380 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7381 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7382 /* There was neither fork nor SIGCHLD since last waitpid */
7383 /* Avoid doing waitpid syscall if possible */
7384 if (!G.we_have_children) {
7388 if (fg_pipe == NULL) { /* is WNOHANG set? */
7389 /* We have children, but they did not exit
7390 * or stop yet (we saw no SIGCHLD) */
7393 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7397 /* Do we do this right?
7398 * bash-3.00# sleep 20 | false
7400 * [3]+ Stopped sleep 20 | false
7401 * bash-3.00# echo $?
7402 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7403 * [hush 1.14.0: yes we do it right]
7407 #if ENABLE_HUSH_FAST
7409 i = G.count_SIGCHLD;
7411 childpid = waitpid(-1, &status, attributes);
7412 if (childpid <= 0) {
7413 if (childpid && errno != ECHILD)
7414 bb_perror_msg("waitpid");
7415 #if ENABLE_HUSH_FAST
7416 else { /* Until next SIGCHLD, waitpid's are useless */
7417 G.we_have_children = (childpid == 0);
7418 G.handled_SIGCHLD = i;
7419 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7422 /* ECHILD (no children), or 0 (no change in children status) */
7426 rcode = process_wait_result(fg_pipe, childpid, status);
7428 /* fg_pipe exited or stopped */
7431 if (childpid == waitfor_pid) {
7432 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7433 rcode = WEXITSTATUS(status);
7434 if (WIFSIGNALED(status))
7435 rcode = 128 + WTERMSIG(status);
7436 if (WIFSTOPPED(status))
7437 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7438 rcode = 128 + WSTOPSIG(status);
7440 break; /* "wait PID" called us, give it exitcode+1 */
7442 /* This wasn't one of our processes, or */
7443 /* fg_pipe still has running processes, do waitpid again */
7444 } /* while (waitpid succeeds)... */
7450 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7453 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7454 if (G_saved_tty_pgrp) {
7455 /* Job finished, move the shell to the foreground */
7456 p = getpgrp(); /* our process group id */
7457 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7458 tcsetpgrp(G_interactive_fd, p);
7464 /* Start all the jobs, but don't wait for anything to finish.
7467 * Return code is normally -1, when the caller has to wait for children
7468 * to finish to determine the exit status of the pipe. If the pipe
7469 * is a simple builtin command, however, the action is done by the
7470 * time run_pipe returns, and the exit code is provided as the
7473 * Returns -1 only if started some children. IOW: we have to
7474 * mask out retvals of builtins etc with 0xff!
7476 * The only case when we do not need to [v]fork is when the pipe
7477 * is single, non-backgrounded, non-subshell command. Examples:
7478 * cmd ; ... { list } ; ...
7479 * cmd && ... { list } && ...
7480 * cmd || ... { list } || ...
7481 * If it is, then we can run cmd as a builtin, NOFORK,
7482 * or (if SH_STANDALONE) an applet, and we can run the { list }
7483 * with run_list. If it isn't one of these, we fork and exec cmd.
7485 * Cases when we must fork:
7486 * non-single: cmd | cmd
7487 * backgrounded: cmd & { list } &
7488 * subshell: ( list ) [&]
7490 #if !ENABLE_HUSH_MODE_X
7491 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7492 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7494 static int redirect_and_varexp_helper(char ***new_env_p,
7495 struct variable **old_vars_p,
7496 struct command *command,
7498 char **argv_expanded)
7500 /* setup_redirects acts on file descriptors, not FILEs.
7501 * This is perfect for work that comes after exec().
7502 * Is it really safe for inline use? Experimentally,
7503 * things seem to work. */
7504 int rcode = setup_redirects(command, squirrel);
7506 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7507 *new_env_p = new_env;
7508 dump_cmd_in_x_mode(new_env);
7509 dump_cmd_in_x_mode(argv_expanded);
7511 *old_vars_p = set_vars_and_save_old(new_env);
7515 static NOINLINE int run_pipe(struct pipe *pi)
7517 static const char *const null_ptr = NULL;
7521 struct command *command;
7522 char **argv_expanded;
7524 /* it is not always needed, but we aim to smaller code */
7525 int squirrel[] = { -1, -1, -1 };
7528 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7531 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7532 * Result should be 3 lines: q w e, qwe, q w e
7534 G.ifs = get_local_var_value("IFS");
7538 IF_HUSH_JOB(pi->pgrp = -1;)
7539 pi->stopped_cmds = 0;
7540 command = &pi->cmds[0];
7541 argv_expanded = NULL;
7543 if (pi->num_cmds != 1
7544 || pi->followup == PIPE_BG
7545 || command->cmd_type == CMD_SUBSHELL
7552 debug_printf_exec(": group:%p argv:'%s'\n",
7553 command->group, command->argv ? command->argv[0] : "NONE");
7555 if (command->group) {
7556 #if ENABLE_HUSH_FUNCTIONS
7557 if (command->cmd_type == CMD_FUNCDEF) {
7558 /* "executing" func () { list } */
7559 struct function *funcp;
7561 funcp = new_function(command->argv[0]);
7562 /* funcp->name is already set to argv[0] */
7563 funcp->body = command->group;
7565 funcp->body_as_string = command->group_as_string;
7566 command->group_as_string = NULL;
7568 command->group = NULL;
7569 command->argv[0] = NULL;
7570 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7571 funcp->parent_cmd = command;
7572 command->child_func = funcp;
7574 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7576 return EXIT_SUCCESS;
7580 debug_printf("non-subshell group\n");
7581 rcode = 1; /* exitcode if redir failed */
7582 if (setup_redirects(command, squirrel) == 0) {
7583 debug_printf_exec(": run_list\n");
7584 rcode = run_list(command->group) & 0xff;
7586 restore_redirects(squirrel);
7587 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7589 debug_printf_exec("run_pipe: return %d\n", rcode);
7593 argv = command->argv ? command->argv : (char **) &null_ptr;
7595 const struct built_in_command *x;
7596 #if ENABLE_HUSH_FUNCTIONS
7597 const struct function *funcp;
7601 char **new_env = NULL;
7602 struct variable *old_vars = NULL;
7604 if (argv[command->assignment_cnt] == NULL) {
7605 /* Assignments, but no command */
7606 /* Ensure redirects take effect (that is, create files).
7607 * Try "a=t >file" */
7608 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7609 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7610 /* Set shell variables */
7614 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7615 /* Do we need to flag set_local_var() errors?
7616 * "assignment to readonly var" and "putenv error"
7621 /* Redirect error sets $? to 1. Otherwise,
7622 * if evaluating assignment value set $?, retain it.
7623 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7625 rcode = G.last_exitcode;
7626 /* Exit, _skipping_ variable restoring code: */
7627 goto clean_up_and_ret0;
7629 #else /* Older, bigger, but more correct code */
7631 rcode = setup_redirects(command, squirrel);
7632 restore_redirects(squirrel);
7633 /* Set shell variables */
7635 bb_putchar_stderr('+');
7637 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7639 fprintf(stderr, " %s", p);
7640 debug_printf_exec("set shell var:'%s'->'%s'\n",
7642 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7643 /* Do we need to flag set_local_var() errors?
7644 * "assignment to readonly var" and "putenv error"
7649 bb_putchar_stderr('\n');
7650 /* Redirect error sets $? to 1. Otherwise,
7651 * if evaluating assignment value set $?, retain it.
7652 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7654 rcode = G.last_exitcode;
7655 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7657 debug_printf_exec("run_pipe: return %d\n", rcode);
7662 /* Expand the rest into (possibly) many strings each */
7663 #if ENABLE_HUSH_BASH_COMPAT
7664 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7665 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7669 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7672 /* if someone gives us an empty string: `cmd with empty output` */
7673 if (!argv_expanded[0]) {
7674 free(argv_expanded);
7676 return G.last_exitcode;
7679 x = find_builtin(argv_expanded[0]);
7680 #if ENABLE_HUSH_FUNCTIONS
7683 funcp = find_function(argv_expanded[0]);
7687 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7688 debug_printf("exec with redirects only\n");
7689 rcode = setup_redirects(command, NULL);
7690 /* rcode=1 can be if redir file can't be opened */
7691 goto clean_up_and_ret1;
7694 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7697 debug_printf_exec(": builtin '%s' '%s'...\n",
7698 x->b_cmd, argv_expanded[1]);
7700 rcode = x->b_function(argv_expanded) & 0xff;
7703 #if ENABLE_HUSH_FUNCTIONS
7705 # if ENABLE_HUSH_LOCAL
7706 struct variable **sv;
7707 sv = G.shadowed_vars_pp;
7708 G.shadowed_vars_pp = &old_vars;
7710 debug_printf_exec(": function '%s' '%s'...\n",
7711 funcp->name, argv_expanded[1]);
7712 rcode = run_function(funcp, argv_expanded) & 0xff;
7713 # if ENABLE_HUSH_LOCAL
7714 G.shadowed_vars_pp = sv;
7720 unset_vars(new_env);
7722 /* clean_up_and_ret0: */
7723 restore_redirects(squirrel);
7725 free(argv_expanded);
7726 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7728 debug_printf_exec("run_pipe return %d\n", rcode);
7732 if (ENABLE_FEATURE_SH_NOFORK) {
7733 int n = find_applet_by_name(argv_expanded[0]);
7734 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7735 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7737 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7738 argv_expanded[0], argv_expanded[1]);
7739 rcode = run_nofork_applet(n, argv_expanded);
7741 goto clean_up_and_ret;
7744 /* It is neither builtin nor applet. We must fork. */
7748 /* NB: argv_expanded may already be created, and that
7749 * might include `cmd` runs! Do not rerun it! We *must*
7750 * use argv_expanded if it's non-NULL */
7752 /* Going to fork a child per each pipe member */
7757 while (cmd_no < pi->num_cmds) {
7758 struct fd_pair pipefds;
7760 volatile nommu_save_t nommu_save;
7761 nommu_save.new_env = NULL;
7762 nommu_save.old_vars = NULL;
7763 nommu_save.argv = NULL;
7764 nommu_save.argv_from_re_execing = NULL;
7766 command = &pi->cmds[cmd_no];
7768 if (command->argv) {
7769 debug_printf_exec(": pipe member '%s' '%s'...\n",
7770 command->argv[0], command->argv[1]);
7772 debug_printf_exec(": pipe member with no argv\n");
7775 /* pipes are inserted between pairs of commands */
7778 if (cmd_no < pi->num_cmds)
7779 xpiped_pair(pipefds);
7781 command->pid = BB_MMU ? fork() : vfork();
7782 if (!command->pid) { /* child */
7784 disable_restore_tty_pgrp_on_exit();
7785 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7787 /* Every child adds itself to new process group
7788 * with pgid == pid_of_first_child_in_pipe */
7789 if (G.run_list_level == 1 && G_interactive_fd) {
7792 if (pgrp < 0) /* true for 1st process only */
7794 if (setpgid(0, pgrp) == 0
7795 && pi->followup != PIPE_BG
7796 && G_saved_tty_pgrp /* we have ctty */
7798 /* We do it in *every* child, not just first,
7800 tcsetpgrp(G_interactive_fd, pgrp);
7804 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7805 /* 1st cmd in backgrounded pipe
7806 * should have its stdin /dev/null'ed */
7808 if (open(bb_dev_null, O_RDONLY))
7809 xopen("/", O_RDONLY);
7811 xmove_fd(next_infd, 0);
7813 xmove_fd(pipefds.wr, 1);
7816 /* Like bash, explicit redirects override pipes,
7817 * and the pipe fd (fd#1) is available for dup'ing:
7818 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7819 * of cmd1 goes into pipe.
7821 if (setup_redirects(command, NULL)) {
7822 /* Happens when redir file can't be opened:
7823 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7825 * hush: can't open '/qwe/rty': No such file or directory
7827 * (echo BAR is not executed, it hits _exit(1) below)
7832 /* Stores to nommu_save list of env vars putenv'ed
7833 * (NOMMU, on MMU we don't need that) */
7834 /* cast away volatility... */
7835 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7836 /* pseudo_exec() does not return */
7839 /* parent or error */
7840 #if ENABLE_HUSH_FAST
7842 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7844 enable_restore_tty_pgrp_on_exit();
7846 /* Clean up after vforked child */
7847 free(nommu_save.argv);
7848 free(nommu_save.argv_from_re_execing);
7849 unset_vars(nommu_save.new_env);
7850 add_vars(nommu_save.old_vars);
7852 free(argv_expanded);
7853 argv_expanded = NULL;
7854 if (command->pid < 0) { /* [v]fork failed */
7855 /* Clearly indicate, was it fork or vfork */
7856 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7860 /* Second and next children need to know pid of first one */
7862 pi->pgrp = command->pid;
7868 if (cmd_no < pi->num_cmds)
7870 /* Pass read (output) pipe end to next iteration */
7871 next_infd = pipefds.rd;
7874 if (!pi->alive_cmds) {
7876 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7881 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7885 /* NB: called by pseudo_exec, and therefore must not modify any
7886 * global data until exec/_exit (we can be a child after vfork!) */
7887 static int run_list(struct pipe *pi)
7889 #if ENABLE_HUSH_CASE
7890 char *case_word = NULL;
7892 #if ENABLE_HUSH_LOOPS
7893 struct pipe *loop_top = NULL;
7894 char **for_lcur = NULL;
7895 char **for_list = NULL;
7897 smallint last_followup;
7899 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7900 smalluint cond_code = 0;
7902 enum { cond_code = 0 };
7905 smallint rword; /* RES_foo */
7906 smallint last_rword; /* ditto */
7909 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7912 #if ENABLE_HUSH_LOOPS
7913 /* Check syntax for "for" */
7916 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7917 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7919 /* current word is FOR or IN (BOLD in comments below) */
7920 if (cpipe->next == NULL) {
7921 syntax_error("malformed for");
7923 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7926 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7927 if (cpipe->next->res_word == RES_DO)
7929 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7930 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7931 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7933 syntax_error("malformed for");
7935 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7942 /* Past this point, all code paths should jump to ret: label
7943 * in order to return, no direct "return" statements please.
7944 * This helps to ensure that no memory is leaked. */
7952 last_rword = RES_XXXX;
7954 last_followup = PIPE_SEQ;
7955 rcode = G.last_exitcode;
7957 /* Go through list of pipes, (maybe) executing them. */
7958 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7963 if (G_flag_return_in_progress == 1)
7966 IF_HAS_KEYWORDS(rword = pi->res_word;)
7967 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7968 rword, cond_code, last_rword);
7969 #if ENABLE_HUSH_LOOPS
7970 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7971 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7973 /* start of a loop: remember where loop starts */
7978 /* Still in the same "if...", "then..." or "do..." branch? */
7979 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7980 if ((rcode == 0 && last_followup == PIPE_OR)
7981 || (rcode != 0 && last_followup == PIPE_AND)
7983 /* It is "<true> || CMD" or "<false> && CMD"
7984 * and we should not execute CMD */
7985 debug_printf_exec("skipped cmd because of || or &&\n");
7986 last_followup = pi->followup;
7987 goto dont_check_jobs_but_continue;
7990 last_followup = pi->followup;
7991 IF_HAS_KEYWORDS(last_rword = rword;)
7994 if (rword == RES_THEN) {
7995 /* if false; then ... fi has exitcode 0! */
7996 G.last_exitcode = rcode = EXIT_SUCCESS;
7997 /* "if <false> THEN cmd": skip cmd */
8001 if (rword == RES_ELSE || rword == RES_ELIF) {
8002 /* "if <true> then ... ELSE/ELIF cmd":
8003 * skip cmd and all following ones */
8008 #if ENABLE_HUSH_LOOPS
8009 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8011 /* first loop through for */
8013 static const char encoded_dollar_at[] ALIGN1 = {
8014 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8015 }; /* encoded representation of "$@" */
8016 static const char *const encoded_dollar_at_argv[] = {
8017 encoded_dollar_at, NULL
8018 }; /* argv list with one element: "$@" */
8021 vals = (char**)encoded_dollar_at_argv;
8022 if (pi->next->res_word == RES_IN) {
8023 /* if no variable values after "in" we skip "for" */
8024 if (!pi->next->cmds[0].argv) {
8025 G.last_exitcode = rcode = EXIT_SUCCESS;
8026 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8029 vals = pi->next->cmds[0].argv;
8030 } /* else: "for var; do..." -> assume "$@" list */
8031 /* create list of variable values */
8032 debug_print_strings("for_list made from", vals);
8033 for_list = expand_strvec_to_strvec(vals);
8034 for_lcur = for_list;
8035 debug_print_strings("for_list", for_list);
8038 /* "for" loop is over, clean up */
8044 /* Insert next value from for_lcur */
8045 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8046 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
8049 if (rword == RES_IN) {
8050 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8052 if (rword == RES_DONE) {
8053 continue; /* "done" has no cmds too */
8056 #if ENABLE_HUSH_CASE
8057 if (rword == RES_CASE) {
8058 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8059 case_word = expand_strvec_to_string(pi->cmds->argv);
8062 if (rword == RES_MATCH) {
8065 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8066 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8068 /* all prev words didn't match, does this one match? */
8069 argv = pi->cmds->argv;
8071 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8072 /* TODO: which FNM_xxx flags to use? */
8073 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8075 if (cond_code == 0) { /* match! we will execute this branch */
8077 case_word = NULL; /* make future "word)" stop */
8084 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8085 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8087 continue; /* not matched yet, skip this pipe */
8089 if (rword == RES_ESAC) {
8090 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8092 /* "case" did not match anything: still set $? (to 0) */
8093 G.last_exitcode = rcode = EXIT_SUCCESS;
8097 /* Just pressing <enter> in shell should check for jobs.
8098 * OTOH, in non-interactive shell this is useless
8099 * and only leads to extra job checks */
8100 if (pi->num_cmds == 0) {
8101 if (G_interactive_fd)
8102 goto check_jobs_and_continue;
8106 /* After analyzing all keywords and conditions, we decided
8107 * to execute this pipe. NB: have to do checkjobs(NULL)
8108 * after run_pipe to collect any background children,
8109 * even if list execution is to be stopped. */
8110 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8111 #if ENABLE_HUSH_LOOPS
8112 G.flag_break_continue = 0;
8114 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8116 /* We ran a builtin, function, or group.
8117 * rcode is already known
8118 * and we don't need to wait for anything. */
8119 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8120 G.last_exitcode = rcode;
8121 check_and_run_traps();
8122 #if ENABLE_HUSH_LOOPS
8123 /* Was it "break" or "continue"? */
8124 if (G.flag_break_continue) {
8125 smallint fbc = G.flag_break_continue;
8126 /* We might fall into outer *loop*,
8127 * don't want to break it too */
8129 G.depth_break_continue--;
8130 if (G.depth_break_continue == 0)
8131 G.flag_break_continue = 0;
8132 /* else: e.g. "continue 2" should *break* once, *then* continue */
8133 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8134 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8135 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8138 /* "continue": simulate end of loop */
8143 if (G_flag_return_in_progress == 1) {
8144 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8147 } else if (pi->followup == PIPE_BG) {
8148 /* What does bash do with attempts to background builtins? */
8149 /* even bash 3.2 doesn't do that well with nested bg:
8150 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8151 * I'm NOT treating inner &'s as jobs */
8153 if (G.run_list_level == 1)
8156 /* Last command's pid goes to $! */
8157 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8158 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8159 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
8160 rcode = EXIT_SUCCESS;
8164 if (G.run_list_level == 1 && G_interactive_fd) {
8165 /* Waits for completion, then fg's main shell */
8166 rcode = checkjobs_and_fg_shell(pi);
8167 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8171 /* This one just waits for completion */
8172 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8173 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8175 G.last_exitcode = rcode;
8176 check_and_run_traps();
8179 /* Analyze how result affects subsequent commands */
8181 if (rword == RES_IF || rword == RES_ELIF)
8184 check_jobs_and_continue:
8185 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8186 dont_check_jobs_but_continue: ;
8187 #if ENABLE_HUSH_LOOPS
8188 /* Beware of "while false; true; do ..."! */
8190 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8191 /* check for RES_DONE is needed for "while ...; do \n done" case */
8193 if (rword == RES_WHILE) {
8195 /* "while false; do...done" - exitcode 0 */
8196 G.last_exitcode = rcode = EXIT_SUCCESS;
8197 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8201 if (rword == RES_UNTIL) {
8203 debug_printf_exec(": until expr is true: breaking\n");
8214 #if ENABLE_HUSH_LOOPS
8219 #if ENABLE_HUSH_CASE
8223 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8227 /* Select which version we will use */
8228 static int run_and_free_list(struct pipe *pi)
8231 debug_printf_exec("run_and_free_list entered\n");
8232 if (!G.o_opt[OPT_O_NOEXEC]) {
8233 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8234 rcode = run_list(pi);
8236 /* free_pipe_list has the side effect of clearing memory.
8237 * In the long run that function can be merged with run_list,
8238 * but doing that now would hobble the debugging effort. */
8240 debug_printf_exec("run_and_free_list return %d\n", rcode);
8245 static void install_sighandlers(unsigned mask)
8247 sighandler_t old_handler;
8249 while ((mask >>= 1) != 0) {
8253 old_handler = install_sighandler(sig, pick_sighandler(sig));
8254 /* POSIX allows shell to re-enable SIGCHLD
8255 * even if it was SIG_IGN on entry.
8256 * Therefore we skip IGN check for it:
8260 if (old_handler == SIG_IGN) {
8261 /* oops... restore back to IGN, and record this fact */
8262 install_sighandler(sig, old_handler);
8263 #if ENABLE_HUSH_TRAP
8265 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8267 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8273 /* Called a few times only (or even once if "sh -c") */
8274 static void install_special_sighandlers(void)
8278 /* Which signals are shell-special? */
8279 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8280 if (G_interactive_fd) {
8281 mask |= SPECIAL_INTERACTIVE_SIGS;
8282 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8283 mask |= SPECIAL_JOBSTOP_SIGS;
8285 /* Careful, do not re-install handlers we already installed */
8286 if (G.special_sig_mask != mask) {
8287 unsigned diff = mask & ~G.special_sig_mask;
8288 G.special_sig_mask = mask;
8289 install_sighandlers(diff);
8295 /* Set handlers to restore tty pgrp and exit */
8296 static void install_fatal_sighandlers(void)
8300 /* We will restore tty pgrp on these signals */
8302 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8303 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8304 + (1 << SIGBUS ) * HUSH_DEBUG
8305 + (1 << SIGSEGV) * HUSH_DEBUG
8306 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8308 /* bash 3.2 seems to handle these just like 'fatal' ones */
8311 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8312 * if we aren't interactive... but in this case
8313 * we never want to restore pgrp on exit, and this fn is not called
8315 /*+ (1 << SIGHUP )*/
8316 /*+ (1 << SIGTERM)*/
8317 /*+ (1 << SIGINT )*/
8319 G_fatal_sig_mask = mask;
8321 install_sighandlers(mask);
8325 static int set_mode(int state, char mode, const char *o_opt)
8330 G.o_opt[OPT_O_NOEXEC] = state;
8333 IF_HUSH_MODE_X(G_x_mode = state;)
8337 /* "set -+o" without parameter.
8338 * in bash, set -o produces this output:
8342 * We always use the second form.
8344 const char *p = o_opt_strings;
8347 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8353 idx = index_in_strings(o_opt_strings, o_opt);
8355 G.o_opt[idx] = state;
8359 return EXIT_FAILURE;
8361 return EXIT_SUCCESS;
8364 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8365 int hush_main(int argc, char **argv)
8368 OPT_login = (1 << 0),
8372 unsigned builtin_argc;
8374 struct variable *cur_var;
8375 struct variable *shell_ver;
8378 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8379 G.last_exitcode = EXIT_SUCCESS;
8381 #if ENABLE_HUSH_FAST
8382 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8385 G.argv0_for_re_execing = argv[0];
8387 /* Deal with HUSH_VERSION */
8388 shell_ver = xzalloc(sizeof(*shell_ver));
8389 shell_ver->flg_export = 1;
8390 shell_ver->flg_read_only = 1;
8391 /* Code which handles ${var<op>...} needs writable values for all variables,
8392 * therefore we xstrdup: */
8393 shell_ver->varstr = xstrdup(hush_version_str);
8394 /* Create shell local variables from the values
8395 * currently living in the environment */
8396 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8397 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8398 G.top_var = shell_ver;
8399 cur_var = G.top_var;
8402 char *value = strchr(*e, '=');
8403 if (value) { /* paranoia */
8404 cur_var->next = xzalloc(sizeof(*cur_var));
8405 cur_var = cur_var->next;
8406 cur_var->varstr = *e;
8407 cur_var->max_len = strlen(*e);
8408 cur_var->flg_export = 1;
8412 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8413 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8414 putenv(shell_ver->varstr);
8417 set_pwd_var(/*exp:*/ 1);
8419 #if ENABLE_HUSH_BASH_COMPAT
8420 /* Set (but not export) HOSTNAME unless already set */
8421 if (!get_local_var_value("HOSTNAME")) {
8424 set_local_var_from_halves("HOSTNAME", uts.nodename);
8426 /* bash also exports SHLVL and _,
8427 * and sets (but doesn't export) the following variables:
8429 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8430 * BASH_VERSION='3.2.0(1)-release'
8432 * MACHTYPE=i386-pc-linux-gnu
8434 * PPID=<NNNNN> - we also do it elsewhere
8445 * PIPESTATUS=([0]="0")
8446 * HISTFILE=/<xxx>/.bash_history
8450 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8452 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8463 #if ENABLE_FEATURE_EDITING
8464 G.line_input_state = new_line_input_t(FOR_SHELL);
8467 /* Initialize some more globals to non-zero values */
8468 cmdedit_update_prompt();
8470 die_func = restore_ttypgrp_and__exit;
8472 /* Shell is non-interactive at first. We need to call
8473 * install_special_sighandlers() if we are going to execute "sh <script>",
8474 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8475 * If we later decide that we are interactive, we run install_special_sighandlers()
8476 * in order to intercept (more) signals.
8480 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8481 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8484 opt = getopt(argc, argv, "+c:xinsl"
8487 # if ENABLE_HUSH_FUNCTIONS
8497 * sh ... -c 'script'
8498 * sh ... -c 'script' ARG0 [ARG1...]
8499 * On NOMMU, if builtin_argc != 0,
8500 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8501 * "" needs to be replaced with NULL
8502 * and BARGV vector fed to builtin function.
8503 * Note: the form without ARG0 never happens:
8504 * sh ... -c 'builtin' BARGV... ""
8507 G.root_pid = getpid();
8508 G.root_ppid = getppid();
8510 G.global_argv = argv + optind;
8511 G.global_argc = argc - optind;
8513 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8514 const struct built_in_command *x;
8516 install_special_sighandlers();
8517 x = find_builtin(optarg);
8518 if (x) { /* paranoia */
8519 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8520 G.global_argv += builtin_argc;
8521 G.global_argv[-1] = NULL; /* replace "" */
8523 G.last_exitcode = x->b_function(argv + optind - 1);
8527 if (!G.global_argv[0]) {
8528 /* -c 'script' (no params): prevent empty $0 */
8529 G.global_argv--; /* points to argv[i] of 'script' */
8530 G.global_argv[0] = argv[0];
8532 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8533 install_special_sighandlers();
8534 parse_and_run_string(optarg);
8537 /* Well, we cannot just declare interactiveness,
8538 * we have to have some stuff (ctty, etc) */
8539 /* G_interactive_fd++; */
8542 /* "-s" means "read from stdin", but this is how we always
8543 * operate, so simply do nothing here. */
8549 case '<': /* "big heredoc" support */
8550 full_write1_str(optarg);
8553 unsigned long long empty_trap_mask;
8555 G.root_pid = bb_strtou(optarg, &optarg, 16);
8557 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8559 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8561 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8563 builtin_argc = bb_strtou(optarg, &optarg, 16);
8565 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8566 if (empty_trap_mask != 0) {
8568 install_special_sighandlers();
8569 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8570 for (sig = 1; sig < NSIG; sig++) {
8571 if (empty_trap_mask & (1LL << sig)) {
8572 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8573 install_sighandler(sig, SIG_IGN);
8577 # if ENABLE_HUSH_LOOPS
8579 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8585 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8587 # if ENABLE_HUSH_FUNCTIONS
8589 struct function *funcp = new_function(optarg);
8590 /* funcp->name is already set to optarg */
8591 /* funcp->body is set to NULL. It's a special case. */
8592 funcp->body_as_string = argv[optind];
8600 if (set_mode(1, opt, NULL) == 0) /* no error */
8604 fprintf(stderr, "Usage: sh [FILE]...\n"
8605 " or: sh -c command [args]...\n\n");
8611 } /* option parsing loop */
8613 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8614 G.global_argc = argc - (optind - 1);
8615 G.global_argv = argv + (optind - 1);
8616 G.global_argv[0] = argv[0];
8619 G.root_pid = getpid();
8620 G.root_ppid = getppid();
8623 /* If we are login shell... */
8624 if (flags & OPT_login) {
8626 debug_printf("sourcing /etc/profile\n");
8627 input = fopen_for_read("/etc/profile");
8628 if (input != NULL) {
8629 remember_FILE(input);
8630 install_special_sighandlers();
8631 parse_and_run_file(input);
8632 fclose_and_forget(input);
8634 /* bash: after sourcing /etc/profile,
8635 * tries to source (in the given order):
8636 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8637 * stopping on first found. --noprofile turns this off.
8638 * bash also sources ~/.bash_logout on exit.
8639 * If called as sh, skips .bash_XXX files.
8643 if (G.global_argv[1]) {
8646 * "bash <script>" (which is never interactive (unless -i?))
8647 * sources $BASH_ENV here (without scanning $PATH).
8648 * If called as sh, does the same but with $ENV.
8649 * Also NB, per POSIX, $ENV should undergo parameter expansion.
8653 debug_printf("running script '%s'\n", G.global_argv[0]);
8654 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
8655 input = xfopen_for_read(G.global_argv[0]);
8656 xfunc_error_retval = 1;
8657 remember_FILE(input);
8658 install_special_sighandlers();
8659 parse_and_run_file(input);
8660 #if ENABLE_FEATURE_CLEAN_UP
8661 fclose_and_forget(input);
8666 /* Up to here, shell was non-interactive. Now it may become one.
8667 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8670 /* A shell is interactive if the '-i' flag was given,
8671 * or if all of the following conditions are met:
8673 * no arguments remaining or the -s flag given
8674 * standard input is a terminal
8675 * standard output is a terminal
8676 * Refer to Posix.2, the description of the 'sh' utility.
8679 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8680 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8681 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8682 if (G_saved_tty_pgrp < 0)
8683 G_saved_tty_pgrp = 0;
8685 /* try to dup stdin to high fd#, >= 255 */
8686 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8687 if (G_interactive_fd < 0) {
8688 /* try to dup to any fd */
8689 G_interactive_fd = dup(STDIN_FILENO);
8690 if (G_interactive_fd < 0) {
8692 G_interactive_fd = 0;
8693 G_saved_tty_pgrp = 0;
8696 // TODO: track & disallow any attempts of user
8697 // to (inadvertently) close/redirect G_interactive_fd
8699 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8700 if (G_interactive_fd) {
8701 close_on_exec_on(G_interactive_fd);
8703 if (G_saved_tty_pgrp) {
8704 /* If we were run as 'hush &', sleep until we are
8705 * in the foreground (tty pgrp == our pgrp).
8706 * If we get started under a job aware app (like bash),
8707 * make sure we are now in charge so we don't fight over
8708 * who gets the foreground */
8710 pid_t shell_pgrp = getpgrp();
8711 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8712 if (G_saved_tty_pgrp == shell_pgrp)
8714 /* send TTIN to ourself (should stop us) */
8715 kill(- shell_pgrp, SIGTTIN);
8719 /* Install more signal handlers */
8720 install_special_sighandlers();
8722 if (G_saved_tty_pgrp) {
8723 /* Set other signals to restore saved_tty_pgrp */
8724 install_fatal_sighandlers();
8725 /* Put ourselves in our own process group
8726 * (bash, too, does this only if ctty is available) */
8727 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8728 /* Grab control of the terminal */
8729 tcsetpgrp(G_interactive_fd, getpid());
8731 enable_restore_tty_pgrp_on_exit();
8733 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8735 const char *hp = get_local_var_value("HISTFILE");
8737 hp = get_local_var_value("HOME");
8739 hp = concat_path_file(hp, ".hush_history");
8744 G.line_input_state->hist_file = hp;
8745 //set_local_var(xasprintf("HISTFILE=%s", ...));
8747 # if ENABLE_FEATURE_SH_HISTFILESIZE
8748 hp = get_local_var_value("HISTFILESIZE");
8749 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8754 install_special_sighandlers();
8756 #elif ENABLE_HUSH_INTERACTIVE
8757 /* No job control compiled in, only prompt/line editing */
8758 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8759 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8760 if (G_interactive_fd < 0) {
8761 /* try to dup to any fd */
8762 G_interactive_fd = dup(STDIN_FILENO);
8763 if (G_interactive_fd < 0)
8765 G_interactive_fd = 0;
8768 if (G_interactive_fd) {
8769 close_on_exec_on(G_interactive_fd);
8771 install_special_sighandlers();
8773 /* We have interactiveness code disabled */
8774 install_special_sighandlers();
8777 * if interactive but not a login shell, sources ~/.bashrc
8778 * (--norc turns this off, --rcfile <file> overrides)
8781 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8782 /* note: ash and hush share this string */
8783 printf("\n\n%s %s\n"
8784 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8787 "hush - the humble shell"
8791 parse_and_run_file(stdin);
8794 hush_exit(G.last_exitcode);
8799 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8800 int msh_main(int argc, char **argv)
8802 bb_error_msg("msh is deprecated, please use hush instead");
8803 return hush_main(argc, argv);
8811 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8816 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8823 return applet_main_func(argc, argv - argc);
8826 static int FAST_FUNC builtin_test(char **argv)
8828 return run_applet_main(argv, test_main);
8831 static int FAST_FUNC builtin_echo(char **argv)
8833 return run_applet_main(argv, echo_main);
8836 #if ENABLE_HUSH_PRINTF
8837 static int FAST_FUNC builtin_printf(char **argv)
8839 return run_applet_main(argv, printf_main);
8843 static char **skip_dash_dash(char **argv)
8846 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8851 static int FAST_FUNC builtin_eval(char **argv)
8853 int rcode = EXIT_SUCCESS;
8855 argv = skip_dash_dash(argv);
8857 char *str = expand_strvec_to_string(argv);
8859 * eval "echo Hi; done" ("done" is syntax error):
8860 * "echo Hi" will not execute too.
8862 parse_and_run_string(str);
8864 rcode = G.last_exitcode;
8869 static int FAST_FUNC builtin_cd(char **argv)
8873 argv = skip_dash_dash(argv);
8875 if (newdir == NULL) {
8876 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8877 * bash says "bash: cd: HOME not set" and does nothing
8880 const char *home = get_local_var_value("HOME");
8881 newdir = home ? home : "/";
8883 if (chdir(newdir)) {
8884 /* Mimic bash message exactly */
8885 bb_perror_msg("cd: %s", newdir);
8886 return EXIT_FAILURE;
8888 /* Read current dir (get_cwd(1) is inside) and set PWD.
8889 * Note: do not enforce exporting. If PWD was unset or unexported,
8890 * set it again, but do not export. bash does the same.
8892 set_pwd_var(/*exp:*/ 0);
8893 return EXIT_SUCCESS;
8896 static int FAST_FUNC builtin_exec(char **argv)
8898 argv = skip_dash_dash(argv);
8899 if (argv[0] == NULL)
8900 return EXIT_SUCCESS; /* bash does this */
8902 /* Careful: we can end up here after [v]fork. Do not restore
8903 * tty pgrp then, only top-level shell process does that */
8904 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8905 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8907 /* TODO: if exec fails, bash does NOT exit! We do.
8908 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8909 * and tcsetpgrp, and this is inherently racy.
8911 execvp_or_die(argv);
8914 static int FAST_FUNC builtin_exit(char **argv)
8916 debug_printf_exec("%s()\n", __func__);
8918 /* interactive bash:
8919 * # trap "echo EEE" EXIT
8922 * There are stopped jobs.
8923 * (if there are _stopped_ jobs, running ones don't count)
8926 * EEE (then bash exits)
8928 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8931 /* note: EXIT trap is run by hush_exit */
8932 argv = skip_dash_dash(argv);
8933 if (argv[0] == NULL)
8934 hush_exit(G.last_exitcode);
8935 /* mimic bash: exit 123abc == exit 255 + error msg */
8936 xfunc_error_retval = 255;
8937 /* bash: exit -2 == exit 254, no error msg */
8938 hush_exit(xatoi(argv[0]) & 0xff);
8941 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
8942 static void print_escaped(const char *s)
8947 const char *p = strchrnul(s, '\'');
8948 /* print 'xxxx', possibly just '' */
8949 printf("'%.*s'", (int)(p - s), s);
8954 /* s points to '; print "'''...'''" */
8956 do putchar('\''); while (*++s == '\'');
8962 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL
8963 # if !ENABLE_HUSH_LOCAL
8964 #define helper_export_local(argv, exp, lvl) \
8965 helper_export_local(argv, exp)
8967 static void helper_export_local(char **argv, int exp, int lvl)
8971 char *name_end = strchrnul(name, '=');
8973 /* So far we do not check that name is valid (TODO?) */
8975 if (*name_end == '\0') {
8976 struct variable *var, **vpp;
8978 vpp = get_ptr_to_local_var(name, name_end - name);
8979 var = vpp ? *vpp : NULL;
8981 if (exp == -1) { /* unexporting? */
8982 /* export -n NAME (without =VALUE) */
8984 var->flg_export = 0;
8985 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8987 } /* else: export -n NOT_EXISTING_VAR: no-op */
8990 if (exp == 1) { /* exporting? */
8991 /* export NAME (without =VALUE) */
8993 var->flg_export = 1;
8994 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8995 putenv(var->varstr);
8999 # if ENABLE_HUSH_LOCAL
9000 if (exp == 0 /* local? */
9001 && var && var->func_nest_level == lvl
9003 /* "local x=abc; ...; local x" - ignore second local decl */
9007 /* Exporting non-existing variable.
9008 * bash does not put it in environment,
9009 * but remembers that it is exported,
9010 * and does put it in env when it is set later.
9011 * We just set it to "" and export. */
9012 /* Or, it's "local NAME" (without =VALUE).
9013 * bash sets the value to "". */
9014 name = xasprintf("%s=", name);
9016 /* (Un)exporting/making local NAME=VALUE */
9017 name = xstrdup(name);
9019 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
9024 #if ENABLE_HUSH_EXPORT
9025 static int FAST_FUNC builtin_export(char **argv)
9027 unsigned opt_unexport;
9029 #if ENABLE_HUSH_EXPORT_N
9030 /* "!": do not abort on errors */
9031 opt_unexport = getopt32(argv, "!n");
9032 if (opt_unexport == (uint32_t)-1)
9033 return EXIT_FAILURE;
9040 if (argv[0] == NULL) {
9047 /* ash emits: export VAR='VAL'
9048 * bash: declare -x VAR="VAL"
9049 * we follow ash example */
9050 const char *s = *e++;
9051 const char *p = strchr(s, '=');
9053 if (!p) /* wtf? take next variable */
9056 printf("export %.*s", (int)(p - s) + 1, s);
9057 print_escaped(p + 1);
9061 /*fflush_all(); - done after each builtin anyway */
9063 return EXIT_SUCCESS;
9066 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
9068 return EXIT_SUCCESS;
9072 #if ENABLE_HUSH_LOCAL
9073 static int FAST_FUNC builtin_local(char **argv)
9075 if (G.func_nest_level == 0) {
9076 bb_error_msg("%s: not in a function", argv[0]);
9077 return EXIT_FAILURE; /* bash compat */
9079 helper_export_local(argv, 0, G.func_nest_level);
9080 return EXIT_SUCCESS;
9084 #if ENABLE_HUSH_UNSET
9085 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9086 static int FAST_FUNC builtin_unset(char **argv)
9091 /* "!": do not abort on errors */
9092 /* "+": stop at 1st non-option */
9093 opts = getopt32(argv, "!+vf");
9094 if (opts == (unsigned)-1)
9095 return EXIT_FAILURE;
9097 bb_error_msg("unset: -v and -f are exclusive");
9098 return EXIT_FAILURE;
9104 if (!(opts & 2)) { /* not -f */
9105 if (unset_local_var(*argv)) {
9106 /* unset <nonexistent_var> doesn't fail.
9107 * Error is when one tries to unset RO var.
9108 * Message was printed by unset_local_var. */
9112 # if ENABLE_HUSH_FUNCTIONS
9124 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9125 * built-in 'set' handler
9127 * set [-abCefhmnuvx] [-o option] [argument...]
9128 * set [+abCefhmnuvx] [+o option] [argument...]
9129 * set -- [argument...]
9132 * Implementations shall support the options in both their hyphen and
9133 * plus-sign forms. These options can also be specified as options to sh.
9135 * Write out all variables and their values: set
9136 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9137 * Turn on the -x and -v options: set -xv
9138 * Unset all positional parameters: set --
9139 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9140 * Set the positional parameters to the expansion of x, even if x expands
9141 * with a leading '-' or '+': set -- $x
9143 * So far, we only support "set -- [argument...]" and some of the short names.
9145 static int FAST_FUNC builtin_set(char **argv)
9148 char **pp, **g_argv;
9149 char *arg = *++argv;
9153 for (e = G.top_var; e; e = e->next)
9155 return EXIT_SUCCESS;
9159 if (strcmp(arg, "--") == 0) {
9163 if (arg[0] != '+' && arg[0] != '-')
9165 for (n = 1; arg[n]; ++n) {
9166 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9168 if (arg[n] == 'o' && argv[1])
9171 } while ((arg = *++argv) != NULL);
9172 /* Now argv[0] is 1st argument */
9175 return EXIT_SUCCESS;
9178 /* NB: G.global_argv[0] ($0) is never freed/changed */
9179 g_argv = G.global_argv;
9180 if (G.global_args_malloced) {
9186 G.global_args_malloced = 1;
9187 pp = xzalloc(sizeof(pp[0]) * 2);
9188 pp[0] = g_argv[0]; /* retain $0 */
9191 /* This realloc's G.global_argv */
9192 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9199 return EXIT_SUCCESS;
9201 /* Nothing known, so abort */
9203 bb_error_msg("set: %s: invalid option", arg);
9204 return EXIT_FAILURE;
9208 static int FAST_FUNC builtin_shift(char **argv)
9211 argv = skip_dash_dash(argv);
9215 if (n >= 0 && n < G.global_argc) {
9216 if (G.global_args_malloced) {
9219 free(G.global_argv[m++]);
9222 memmove(&G.global_argv[1], &G.global_argv[n+1],
9223 G.global_argc * sizeof(G.global_argv[0]));
9224 return EXIT_SUCCESS;
9226 return EXIT_FAILURE;
9229 #if ENABLE_HUSH_READ
9230 /* Interruptibility of read builtin in bash
9231 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9233 * Empty trap makes read ignore corresponding signal, for any signal.
9236 * - terminates non-interactive shell;
9237 * - interrupts read in interactive shell;
9238 * if it has non-empty trap:
9239 * - executes trap and returns to command prompt in interactive shell;
9240 * - executes trap and returns to read in non-interactive shell;
9242 * - is ignored (does not interrupt) read in interactive shell;
9243 * - terminates non-interactive shell;
9244 * if it has non-empty trap:
9245 * - executes trap and returns to read;
9247 * - terminates shell (regardless of interactivity);
9248 * if it has non-empty trap:
9249 * - executes trap and returns to read;
9251 static int FAST_FUNC builtin_read(char **argv)
9261 /* "!": do not abort on errors.
9262 * Option string must start with "sr" to match BUILTIN_READ_xxx
9264 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9265 if (read_flags == (uint32_t)-1)
9266 return EXIT_FAILURE;
9268 ifs = get_local_var_value("IFS"); /* can be NULL */
9271 r = shell_builtin_read(set_local_var_from_halves,
9281 if ((uintptr_t)r == 1 && errno == EINTR) {
9282 unsigned sig = check_and_run_traps();
9283 if (sig && sig != SIGINT)
9287 if ((uintptr_t)r > 1) {
9288 bb_error_msg("%s", r);
9289 r = (char*)(uintptr_t)1;
9292 return (uintptr_t)r;
9296 #if ENABLE_HUSH_TRAP
9297 static int FAST_FUNC builtin_trap(char **argv)
9303 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9308 /* No args: print all trapped */
9309 for (i = 0; i < NSIG; ++i) {
9312 print_escaped(G_traps[i]);
9313 /* note: bash adds "SIG", but only if invoked
9314 * as "bash". If called as "sh", or if set -o posix,
9315 * then it prints short signal names.
9316 * We are printing short names: */
9317 printf(" %s\n", get_signame(i));
9320 /*fflush_all(); - done after each builtin anyway */
9321 return EXIT_SUCCESS;
9325 /* If first arg is a number: reset all specified signals */
9326 sig = bb_strtou(*argv, NULL, 10);
9332 sighandler_t handler;
9334 sig = get_signum(*argv++);
9335 if (sig < 0 || sig >= NSIG) {
9337 /* Mimic bash message exactly */
9338 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
9343 G_traps[sig] = xstrdup(new_cmd);
9345 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9346 get_signame(sig), sig, G_traps[sig]);
9348 /* There is no signal for 0 (EXIT) */
9353 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9355 /* We are removing trap handler */
9356 handler = pick_sighandler(sig);
9357 install_sighandler(sig, handler);
9362 if (!argv[1]) { /* no second arg */
9363 bb_error_msg("trap: invalid arguments");
9364 return EXIT_FAILURE;
9367 /* First arg is "-": reset all specified to default */
9368 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9369 /* Everything else: set arg as signal handler
9370 * (includes "" case, which ignores signal) */
9371 if (argv[0][0] == '-') {
9372 if (argv[0][1] == '\0') { /* "-" */
9373 /* new_cmd remains NULL: "reset these sigs" */
9376 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9379 /* else: "-something", no special meaning */
9384 goto process_sig_list;
9388 #if ENABLE_HUSH_TYPE
9389 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9390 static int FAST_FUNC builtin_type(char **argv)
9392 int ret = EXIT_SUCCESS;
9398 if (0) {} /* make conditional compile easier below */
9399 /*else if (find_alias(*argv))
9400 type = "an alias";*/
9401 #if ENABLE_HUSH_FUNCTIONS
9402 else if (find_function(*argv))
9403 type = "a function";
9405 else if (find_builtin(*argv))
9406 type = "a shell builtin";
9407 else if ((path = find_in_path(*argv)) != NULL)
9410 bb_error_msg("type: %s: not found", *argv);
9415 printf("%s is %s\n", *argv, type);
9424 static struct pipe *parse_jobspec(const char *str)
9429 if (sscanf(str, "%%%u", &jobnum) != 1) {
9431 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
9433 bb_error_msg("bad argument '%s'", str);
9436 /* It is "%%", "%+" or "%" - current job */
9437 jobnum = G.last_jobid;
9439 bb_error_msg("no current job");
9443 for (pi = G.job_list; pi; pi = pi->next) {
9444 if (pi->jobid == jobnum) {
9448 bb_error_msg("%u: no such job", jobnum);
9452 /* built-in 'fg' and 'bg' handler */
9453 static int FAST_FUNC builtin_fg_bg(char **argv)
9458 if (!G_interactive_fd)
9459 return EXIT_FAILURE;
9461 /* If they gave us no args, assume they want the last backgrounded task */
9463 for (pi = G.job_list; pi; pi = pi->next) {
9464 if (pi->jobid == G.last_jobid) {
9468 bb_error_msg("%s: no current job", argv[0]);
9469 return EXIT_FAILURE;
9472 pi = parse_jobspec(argv[1]);
9474 return EXIT_FAILURE;
9476 /* TODO: bash prints a string representation
9477 * of job being foregrounded (like "sleep 1 | cat") */
9478 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
9479 /* Put the job into the foreground. */
9480 tcsetpgrp(G_interactive_fd, pi->pgrp);
9483 /* Restart the processes in the job */
9484 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9485 for (i = 0; i < pi->num_cmds; i++) {
9486 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
9488 pi->stopped_cmds = 0;
9490 i = kill(- pi->pgrp, SIGCONT);
9492 if (errno == ESRCH) {
9493 delete_finished_bg_job(pi);
9494 return EXIT_SUCCESS;
9496 bb_perror_msg("kill (SIGCONT)");
9499 if (argv[0][0] == 'f') {
9501 return checkjobs_and_fg_shell(pi);
9503 return EXIT_SUCCESS;
9507 #if ENABLE_HUSH_HELP
9508 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9510 const struct built_in_command *x;
9513 "Built-in commands:\n"
9514 "------------------\n");
9515 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9517 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9519 return EXIT_SUCCESS;
9523 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9524 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9526 show_history(G.line_input_state);
9527 return EXIT_SUCCESS;
9532 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9535 const char *status_string;
9537 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9538 for (job = G.job_list; job; job = job->next) {
9539 if (job->alive_cmds == job->stopped_cmds)
9540 status_string = "Stopped";
9542 status_string = "Running";
9544 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9546 return EXIT_SUCCESS;
9550 #if ENABLE_HUSH_MEMLEAK
9551 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
9556 # ifdef M_TRIM_THRESHOLD
9557 /* Optional. Reduces probability of false positives */
9560 /* Crude attempt to find where "free memory" starts,
9561 * sans fragmentation. */
9563 l = (unsigned long)p;
9566 if (l < (unsigned long)p) l = (unsigned long)p;
9572 struct mallinfo mi = mallinfo();
9573 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9574 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9578 if (!G.memleak_value)
9579 G.memleak_value = l;
9581 l -= G.memleak_value;
9588 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9593 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9596 return EXIT_SUCCESS;
9599 static int FAST_FUNC builtin_source(char **argv)
9601 char *arg_path, *filename;
9604 #if ENABLE_HUSH_FUNCTIONS
9608 argv = skip_dash_dash(argv);
9611 /* bash says: "bash: .: filename argument required" */
9612 return 2; /* bash compat */
9615 if (!strchr(filename, '/')) {
9616 arg_path = find_in_path(filename);
9618 filename = arg_path;
9620 input = remember_FILE(fopen_or_warn(filename, "r"));
9623 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9624 /* POSIX: non-interactive shell should abort here,
9625 * not merely fail. So far no one complained :)
9627 return EXIT_FAILURE;
9630 #if ENABLE_HUSH_FUNCTIONS
9631 sv_flg = G_flag_return_in_progress;
9632 /* "we are inside sourced file, ok to use return" */
9633 G_flag_return_in_progress = -1;
9636 save_and_replace_G_args(&sv, argv);
9638 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9639 G.last_exitcode = 0;
9640 parse_and_run_file(input);
9641 fclose_and_forget(input);
9644 restore_G_args(&sv, argv);
9645 #if ENABLE_HUSH_FUNCTIONS
9646 G_flag_return_in_progress = sv_flg;
9649 return G.last_exitcode;
9652 #if ENABLE_HUSH_UMASK
9653 static int FAST_FUNC builtin_umask(char **argv)
9660 argv = skip_dash_dash(argv);
9662 mode_t old_mask = mask;
9664 /* numeric umasks are taken as-is */
9665 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9666 if (!isdigit(argv[0][0]))
9668 mask = bb_parse_mode(argv[0], mask);
9669 if (!isdigit(argv[0][0]))
9671 if ((unsigned)mask > 0777) {
9674 * bash: umask: 'q': invalid symbolic mode operator
9675 * bash: umask: 999: octal number out of range
9677 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9682 printf("%04o\n", (unsigned) mask);
9683 /* fall through and restore mask which we set to 0 */
9687 return !rc; /* rc != 0 - success */
9691 #if ENABLE_HUSH_KILL
9692 static int FAST_FUNC builtin_kill(char **argv)
9696 # if ENABLE_HUSH_JOB
9697 if (argv[1] && strcmp(argv[1], "-l") != 0) {
9705 if (argv[i][0] != '%')
9708 * "kill %N" - job kill
9709 * Converting to pgrp / pid kill
9711 pi = parse_jobspec(argv[i]);
9713 /* Eat bad jobspec */
9717 argv[j - 1] = argv[j];
9724 * In jobs started under job control, we signal
9725 * entire process group by kill -PGRP_ID.
9726 * This happens, f.e., in interactive shell.
9728 * Otherwise, we signal each child via
9729 * kill PID1 PID2 PID3.
9731 * sh -c 'sleep 1|sleep 1 & kill %1'
9732 * sh -c 'true|sleep 2 & sleep 1; kill %1'
9733 * sh -c 'true|sleep 1 & sleep 2; kill %1'
9735 n = G_interactive_fd ? 1 : pi->num_cmds;
9736 dst = alloca(n * sizeof(int)*4);
9738 if (G_interactive_fd)
9739 dst += sprintf(dst, " -%u", (int)pi->pgrp);
9740 else for (j = 0; j < n; j++) {
9741 struct command *cmd = &pi->cmds[j];
9742 /* Skip exited members of the job */
9746 * kill_main has matching code to expect
9747 * leading space. Needed to not confuse
9748 * negative pids with "kill -SIGNAL_NO" syntax
9750 dst += sprintf(dst, " %u", (int)cmd->pid);
9753 } while (argv[++i]);
9757 if (argv[1] || ret == 0) {
9758 ret = run_applet_main(argv, kill_main);
9760 /* else: ret = 1, "kill %bad_jobspec" case */
9765 #if ENABLE_HUSH_WAIT
9766 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9767 #if !ENABLE_HUSH_JOB
9768 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9770 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
9777 if (!sigisemptyset(&G.pending_set))
9780 /* waitpid is not interruptible by SA_RESTARTed
9781 * signals which we use. Thus, this ugly dance:
9784 /* Make sure possible SIGCHLD is stored in kernel's
9785 * pending signal mask before we call waitpid.
9786 * Or else we may race with SIGCHLD, lose it,
9787 * and get stuck in sigsuspend...
9789 sigfillset(&oldset); /* block all signals, remember old set */
9790 sigprocmask(SIG_SETMASK, &oldset, &oldset);
9792 if (!sigisemptyset(&G.pending_set)) {
9793 /* Crap! we raced with some signal! */
9797 /*errno = 0; - checkjobs does this */
9798 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
9799 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
9800 debug_printf_exec("checkjobs:%d\n", ret);
9803 int rcode = job_exited_or_stopped(waitfor_pipe);
9804 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9807 sigprocmask(SIG_SETMASK, &oldset, NULL);
9812 /* if ECHILD, there are no children (ret is -1 or 0) */
9813 /* if ret == 0, no children changed state */
9814 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
9815 if (errno == ECHILD || ret) {
9817 if (ret < 0) /* if ECHILD, may need to fix "ret" */
9819 sigprocmask(SIG_SETMASK, &oldset, NULL);
9822 /* Wait for SIGCHLD or any other signal */
9823 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9824 /* Note: sigsuspend invokes signal handler */
9825 sigsuspend(&oldset);
9827 sigprocmask(SIG_SETMASK, &oldset, NULL);
9829 /* So, did we get a signal? */
9830 sig = check_and_run_traps();
9831 if (sig /*&& sig != SIGCHLD - always true */) {
9835 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9840 static int FAST_FUNC builtin_wait(char **argv)
9845 argv = skip_dash_dash(argv);
9846 if (argv[0] == NULL) {
9847 /* Don't care about wait results */
9848 /* Note 1: must wait until there are no more children */
9849 /* Note 2: must be interruptible */
9851 * $ sleep 3 & sleep 6 & wait
9856 * $ sleep 3 & sleep 6 & wait
9860 * ^C <-- after ~4 sec from keyboard
9863 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
9867 pid_t pid = bb_strtou(*argv, NULL, 10);
9868 if (errno || pid <= 0) {
9870 if (argv[0][0] == '%') {
9871 struct pipe *wait_pipe;
9872 ret = 127; /* bash compat for bad jobspecs */
9873 wait_pipe = parse_jobspec(*argv);
9875 ret = job_exited_or_stopped(wait_pipe);
9877 ret = wait_for_child_or_signal(wait_pipe, 0);
9879 /* else: parse_jobspec() already emitted error msg */
9883 /* mimic bash message */
9884 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9886 continue; /* bash checks all argv[] */
9889 /* Do we have such child? */
9890 ret = waitpid(pid, &status, WNOHANG);
9893 if (errno == ECHILD) {
9894 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9895 /* "wait $!" but last bg task has already exited. Try:
9896 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9897 * In bash it prints exitcode 0, then 3.
9898 * In dash, it is 127.
9900 /* ret = G.last_bg_pid_exitstatus - FIXME */
9902 /* Example: "wait 1". mimic bash message */
9903 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
9907 bb_perror_msg("wait %s", *argv);
9910 continue; /* bash checks all argv[] */
9913 /* Yes, and it still runs */
9914 ret = wait_for_child_or_signal(NULL, pid);
9916 /* Yes, and it just exited */
9917 process_wait_result(NULL, pid, status);
9918 ret = WEXITSTATUS(status);
9919 if (WIFSIGNALED(status))
9920 ret = 128 + WTERMSIG(status);
9928 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9929 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9932 def = bb_strtou(argv[1], NULL, 10);
9933 if (errno || def < def_min || argv[2]) {
9934 bb_error_msg("%s: bad arguments", argv[0]);
9942 #if ENABLE_HUSH_LOOPS
9943 static int FAST_FUNC builtin_break(char **argv)
9946 if (G.depth_of_loop == 0) {
9947 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9948 /* if we came from builtin_continue(), need to undo "= 1" */
9949 G.flag_break_continue = 0;
9950 return EXIT_SUCCESS; /* bash compat */
9952 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9954 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9955 if (depth == UINT_MAX)
9956 G.flag_break_continue = BC_BREAK;
9957 if (G.depth_of_loop < depth)
9958 G.depth_break_continue = G.depth_of_loop;
9960 return EXIT_SUCCESS;
9963 static int FAST_FUNC builtin_continue(char **argv)
9965 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9966 return builtin_break(argv);
9970 #if ENABLE_HUSH_FUNCTIONS
9971 static int FAST_FUNC builtin_return(char **argv)
9975 if (G_flag_return_in_progress != -1) {
9976 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9977 return EXIT_FAILURE; /* bash compat */
9980 G_flag_return_in_progress = 1;
9983 * out of range: wraps around at 256, does not error out
9984 * non-numeric param:
9985 * f() { false; return qwe; }; f; echo $?
9986 * bash: return: qwe: numeric argument required <== we do this
9987 * 255 <== we also do this
9989 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);