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_ECHO
199 //config: bool "echo builtin"
201 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
203 //config: Enable echo builtin in hush.
205 //config:config HUSH_PRINTF
206 //config: bool "printf builtin"
208 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
210 //config: Enable printf builtin in hush.
212 //config:config HUSH_EXPORT
213 //config: bool "export builtin"
215 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
217 //config: Enable export builtin in hush.
219 //config:config HUSH_EXPORT_N
220 //config: bool "Support 'export -n' option"
222 //config: depends on HUSH_EXPORT
224 //config: export -n unexports variables. It is a bash extension.
226 //config:config HUSH_HELP
227 //config: bool "help builtin"
229 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
231 //config: Enable help builtin in hush. Code size + ~1 kbyte.
233 //config:config HUSH_KILL
234 //config: bool "kill builtin (for kill %jobspec)"
236 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
238 //config: Enable kill builtin in hush.
240 //config:config HUSH_WAIT
241 //config: bool "wait builtin"
243 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
245 //config: Enable wait builtin in hush.
247 //config:config HUSH_TRAP
248 //config: bool "trap builtin"
250 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
252 //config: Enable trap builtin in hush.
254 //config:config HUSH_ULIMIT
255 //config: bool "ulimit builtin"
257 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
259 //config: Enable ulimit builtin in hush.
261 //config:config HUSH_TYPE
262 //config: bool "type builtin"
264 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266 //config: Enable type builtin in hush.
268 //config:config HUSH_READ
269 //config: bool "read builtin"
271 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
273 //config: Enable read builtin in hush.
275 //config:config HUSH_SET
276 //config: bool "set builtin"
278 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
280 //config: Enable set builtin in hush.
282 //config:config HUSH_UNSET
283 //config: bool "unset builtin"
285 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
287 //config: Enable unset builtin in hush.
289 //config:config HUSH_UMASK
290 //config: bool "umask builtin"
292 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
294 //config: Enable umask builtin in hush.
296 //config:config HUSH_MEMLEAK
297 //config: bool "memleak builtin (debugging)"
299 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
301 //config: Enable memleak builtin in hush.
304 //config: bool "msh (deprecated: aliased to hush)"
306 //config: select HUSH
308 //config: msh is deprecated and will be removed, please migrate to hush.
310 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
311 //applet:IF_MSH(APPLET_ODDNAME(msh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
312 //applet:IF_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
313 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
315 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
316 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
317 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
318 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
320 /* -i (interactive) and -s (read stdin) are also accepted,
321 * but currently do nothing, therefore aren't shown in help.
322 * NOMMU-specific options are not meant to be used by users,
323 * therefore we don't show them either.
325 //usage:#define hush_trivial_usage
326 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
327 //usage:#define hush_full_usage "\n\n"
328 //usage: "Unix shell interpreter"
330 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
331 || defined(__APPLE__) \
333 # include <malloc.h> /* for malloc_trim */
336 /* #include <dmalloc.h> */
338 # include <fnmatch.h>
340 #include <sys/utsname.h> /* for setting $HOSTNAME */
342 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
344 #include "shell_common.h"
347 #if ENABLE_HUSH_RANDOM_SUPPORT
350 # define CLEAR_RANDOM_T(rnd) ((void)0)
352 #ifndef F_DUPFD_CLOEXEC
353 # define F_DUPFD_CLOEXEC F_DUPFD
356 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
361 #define LEAK_HUNTING 0
362 #define BUILD_AS_NOMMU 0
363 /* Enable/disable sanity checks. Ok to enable in production,
364 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
365 * Keeping 1 for now even in released versions.
368 /* Slightly bigger (+200 bytes), but faster hush.
369 * So far it only enables a trick with counting SIGCHLDs and forks,
370 * which allows us to do fewer waitpid's.
371 * (we can detect a case where neither forks were done nor SIGCHLDs happened
372 * and therefore waitpid will return the same result as last time)
374 #define ENABLE_HUSH_FAST 0
375 /* TODO: implement simplified code for users which do not need ${var%...} ops
376 * So far ${var%...} ops are always enabled:
378 #define ENABLE_HUSH_DOLLAR_OPS 1
383 # undef USE_FOR_NOMMU
386 # define USE_FOR_NOMMU(...) __VA_ARGS__
387 # define USE_FOR_MMU(...)
390 #include "NUM_APPLETS.h"
392 /* STANDALONE does not make sense, and won't compile */
393 # undef CONFIG_FEATURE_SH_STANDALONE
394 # undef ENABLE_FEATURE_SH_STANDALONE
395 # undef IF_FEATURE_SH_STANDALONE
396 # undef IF_NOT_FEATURE_SH_STANDALONE
397 # define ENABLE_FEATURE_SH_STANDALONE 0
398 # define IF_FEATURE_SH_STANDALONE(...)
399 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
402 #if !ENABLE_HUSH_INTERACTIVE
403 # undef ENABLE_FEATURE_EDITING
404 # define ENABLE_FEATURE_EDITING 0
405 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
406 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
407 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
408 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
411 /* Do we support ANY keywords? */
412 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
413 # define HAS_KEYWORDS 1
414 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
415 # define IF_HAS_NO_KEYWORDS(...)
417 # define HAS_KEYWORDS 0
418 # define IF_HAS_KEYWORDS(...)
419 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
422 /* If you comment out one of these below, it will be #defined later
423 * to perform debug printfs to stderr: */
424 #define debug_printf(...) do {} while (0)
425 /* Finer-grained debug switches */
426 #define debug_printf_parse(...) do {} while (0)
427 #define debug_print_tree(a, b) do {} while (0)
428 #define debug_printf_exec(...) do {} while (0)
429 #define debug_printf_env(...) do {} while (0)
430 #define debug_printf_jobs(...) do {} while (0)
431 #define debug_printf_expand(...) do {} while (0)
432 #define debug_printf_varexp(...) do {} while (0)
433 #define debug_printf_glob(...) do {} while (0)
434 #define debug_printf_list(...) do {} while (0)
435 #define debug_printf_subst(...) do {} while (0)
436 #define debug_printf_clean(...) do {} while (0)
438 #define ERR_PTR ((void*)(long)1)
440 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
442 #define _SPECIAL_VARS_STR "_*@$!?#"
443 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
444 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
445 #if ENABLE_HUSH_BASH_COMPAT
446 /* Support / and // replace ops */
447 /* Note that // is stored as \ in "encoded" string representation */
448 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
449 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
450 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
452 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
453 # define VAR_SUBST_OPS "%#:-=+?"
454 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
457 #define SPECIAL_VAR_SYMBOL 3
461 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
463 /* This supports saving pointers malloced in vfork child,
464 * to be freed in the parent.
467 typedef struct nommu_save_t {
469 struct variable *old_vars;
471 char **argv_from_re_execing;
484 #if ENABLE_HUSH_LOOPS
491 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
496 /* three pseudo-keywords support contrived "case" syntax: */
497 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
498 RES_MATCH , /* "word)" */
499 RES_CASE_BODY, /* "this command is inside CASE" */
506 typedef struct o_string {
508 int length; /* position where data is appended */
511 /* At least some part of the string was inside '' or "",
512 * possibly empty one: word"", wo''rd etc. */
513 smallint has_quoted_part;
514 smallint has_empty_slot;
515 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
518 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
520 /* Protect newly added chars against globbing
521 * by prepending \ to *, ?, [, \ */
522 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
525 MAYBE_ASSIGNMENT = 0,
526 DEFINITELY_ASSIGNMENT = 1,
528 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
531 /* Used for initialization: o_string foo = NULL_O_STRING; */
532 #define NULL_O_STRING { NULL }
534 #ifndef debug_printf_parse
535 static const char *const assignment_flag[] = {
537 "DEFINITELY_ASSIGNMENT",
543 typedef struct in_str {
545 #if ENABLE_HUSH_INTERACTIVE
546 smallint promptmode; /* 0: PS1, 1: PS2 */
553 /* The descrip member of this structure is only used to make
554 * debugging output pretty */
555 static const struct {
557 signed char default_fd;
560 { O_RDONLY, 0, "<" },
561 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
562 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
563 { O_CREAT|O_RDWR, 1, "<>" },
564 { O_RDONLY, 0, "<<" },
565 /* Should not be needed. Bogus default_fd helps in debugging */
566 /* { O_RDONLY, 77, "<<" }, */
569 struct redir_struct {
570 struct redir_struct *next;
571 char *rd_filename; /* filename */
572 int rd_fd; /* fd to redirect */
573 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
575 smallint rd_type; /* (enum redir_type) */
576 /* note: for heredocs, rd_filename contains heredoc delimiter,
577 * and subsequently heredoc itself; and rd_dup is a bitmask:
578 * bit 0: do we need to trim leading tabs?
579 * bit 1: is heredoc quoted (<<'delim' syntax) ?
582 typedef enum redir_type {
584 REDIRECT_OVERWRITE = 1,
587 REDIRECT_HEREDOC = 4,
588 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
591 REDIRFD_SYNTAX_ERR = -2,
592 REDIRFD_TO_FILE = -1,
593 /* otherwise, rd_fd is redirected to rd_dup */
595 HEREDOC_SKIPTABS = 1,
601 pid_t pid; /* 0 if exited */
602 int assignment_cnt; /* how many argv[i] are assignments? */
603 smallint cmd_type; /* CMD_xxx */
605 #define CMD_SUBSHELL 1
606 #if ENABLE_HUSH_BASH_COMPAT
607 /* used for "[[ EXPR ]]" */
608 # define CMD_SINGLEWORD_NOGLOB 2
610 #if ENABLE_HUSH_FUNCTIONS
611 # define CMD_FUNCDEF 3
614 smalluint cmd_exitcode;
615 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
618 char *group_as_string;
620 #if ENABLE_HUSH_FUNCTIONS
621 struct function *child_func;
622 /* This field is used to prevent a bug here:
623 * while...do f1() {a;}; f1; f1() {b;}; f1; done
624 * When we execute "f1() {a;}" cmd, we create new function and clear
625 * cmd->group, cmd->group_as_string, cmd->argv[0].
626 * When we execute "f1() {b;}", we notice that f1 exists,
627 * and that its "parent cmd" struct is still "alive",
628 * we put those fields back into cmd->xxx
629 * (struct function has ->parent_cmd ptr to facilitate that).
630 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
631 * Without this trick, loop would execute a;b;b;b;...
632 * instead of correct sequence a;b;a;b;...
633 * When command is freed, it severs the link
634 * (sets ->child_func->parent_cmd to NULL).
637 char **argv; /* command name and arguments */
638 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
639 * and on execution these are substituted with their values.
640 * Substitution can make _several_ words out of one argv[n]!
641 * Example: argv[0]=='.^C*^C.' here: echo .$*.
642 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
644 struct redir_struct *redirects; /* I/O redirections */
646 /* Is there anything in this command at all? */
647 #define IS_NULL_CMD(cmd) \
648 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
652 int num_cmds; /* total number of commands in pipe */
653 int alive_cmds; /* number of commands running (not exited) */
654 int stopped_cmds; /* number of commands alive, but stopped */
656 unsigned jobid; /* job number */
657 pid_t pgrp; /* process group ID for the job */
658 char *cmdtext; /* name of job */
660 struct command *cmds; /* array of commands in pipe */
661 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
662 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
663 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
665 typedef enum pipe_style {
671 /* Is there anything in this pipe at all? */
672 #define IS_NULL_PIPE(pi) \
673 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
675 /* This holds pointers to the various results of parsing */
676 struct parse_context {
677 /* linked list of pipes */
678 struct pipe *list_head;
679 /* last pipe (being constructed right now) */
681 /* last command in pipe (being constructed right now) */
682 struct command *command;
683 /* last redirect in command->redirects list */
684 struct redir_struct *pending_redirect;
690 smallint ctx_inverted; /* "! cmd | cmd" */
692 smallint ctx_dsemicolon; /* ";;" seen */
694 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
696 /* group we are enclosed in:
697 * example: "if pipe1; pipe2; then pipe3; fi"
698 * when we see "if" or "then", we malloc and copy current context,
699 * and make ->stack point to it. then we parse pipeN.
700 * when closing "then" / fi" / whatever is found,
701 * we move list_head into ->stack->command->group,
702 * copy ->stack into current context, and delete ->stack.
703 * (parsing of { list } and ( list ) doesn't use this method)
705 struct parse_context *stack;
709 /* On program start, environ points to initial environment.
710 * putenv adds new pointers into it, unsetenv removes them.
711 * Neither of these (de)allocates the strings.
712 * setenv allocates new strings in malloc space and does putenv,
713 * and thus setenv is unusable (leaky) for shell's purposes */
714 #define setenv(...) setenv_is_leaky_dont_use()
716 struct variable *next;
717 char *varstr; /* points to "name=" portion */
718 #if ENABLE_HUSH_LOCAL
719 unsigned func_nest_level;
721 int max_len; /* if > 0, name is part of initial env; else name is malloced */
722 smallint flg_export; /* putenv should be done on this var */
723 smallint flg_read_only;
731 #if ENABLE_HUSH_FUNCTIONS
733 struct function *next;
735 struct command *parent_cmd;
738 char *body_as_string;
744 /* set -/+o OPT support. (TODO: make it optional)
745 * bash supports the following opts:
756 * interactive-comments on
774 static const char o_opt_strings[] ALIGN1 =
777 #if ENABLE_HUSH_MODE_X
784 #if ENABLE_HUSH_MODE_X
792 struct FILE_list *next;
798 /* "Globals" within this file */
799 /* Sorted roughly by size (smaller offsets == smaller code) */
801 /* interactive_fd != 0 means we are an interactive shell.
802 * If we are, then saved_tty_pgrp can also be != 0, meaning
803 * that controlling tty is available. With saved_tty_pgrp == 0,
804 * job control still works, but terminal signals
805 * (^C, ^Z, ^Y, ^\) won't work at all, and background
806 * process groups can only be created with "cmd &".
807 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
808 * to give tty to the foreground process group,
809 * and will take it back when the group is stopped (^Z)
812 #if ENABLE_HUSH_INTERACTIVE
813 /* 'interactive_fd' is a fd# open to ctty, if we have one
814 * _AND_ if we decided to act interactively */
818 # define G_interactive_fd (G.interactive_fd)
820 # define G_interactive_fd 0
822 #if ENABLE_FEATURE_EDITING
823 line_input_t *line_input_state;
828 #if ENABLE_HUSH_RANDOM_SUPPORT
834 pid_t saved_tty_pgrp;
835 struct pipe *job_list;
836 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
838 # define G_saved_tty_pgrp 0
840 char o_opt[NUM_OPT_O];
841 #if ENABLE_HUSH_MODE_X
842 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
846 smallint flag_SIGINT;
847 #if ENABLE_HUSH_LOOPS
848 smallint flag_break_continue;
850 #if ENABLE_HUSH_FUNCTIONS
851 /* 0: outside of a function (or sourced file)
852 * -1: inside of a function, ok to use return builtin
853 * 1: return is invoked, skip all till end of func
855 smallint flag_return_in_progress;
856 # define G_flag_return_in_progress (G.flag_return_in_progress)
858 # define G_flag_return_in_progress 0
860 smallint exiting; /* used to prevent EXIT trap recursion */
861 /* These four support $?, $#, and $1 */
862 smalluint last_exitcode;
864 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
865 smalluint global_args_malloced;
866 # define G_global_args_malloced (G.global_args_malloced)
868 # define G_global_args_malloced 0
870 /* how many non-NULL argv's we have. NB: $# + 1 */
874 char *argv0_for_re_execing;
876 #if ENABLE_HUSH_LOOPS
877 unsigned depth_break_continue;
878 unsigned depth_of_loop;
882 struct variable *top_var;
883 char **expanded_assignments;
884 #if ENABLE_HUSH_FUNCTIONS
885 struct function *top_func;
886 # if ENABLE_HUSH_LOCAL
887 struct variable **shadowed_vars_pp;
888 unsigned func_nest_level;
891 /* Signal and trap handling */
893 unsigned count_SIGCHLD;
894 unsigned handled_SIGCHLD;
895 smallint we_have_children;
897 struct FILE_list *FILE_list;
898 /* Which signals have non-DFL handler (even with no traps set)?
899 * Set at the start to:
900 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
901 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
902 * The rest is cleared right before execv syscalls.
903 * Other than these two times, never modified.
905 unsigned special_sig_mask;
907 unsigned fatal_sig_mask;
908 # define G_fatal_sig_mask (G.fatal_sig_mask)
910 # define G_fatal_sig_mask 0
913 char **traps; /* char *traps[NSIG] */
914 # define G_traps G.traps
916 # define G_traps ((char**)NULL)
918 sigset_t pending_set;
919 #if ENABLE_HUSH_MEMLEAK
920 unsigned long memleak_value;
926 #if ENABLE_FEATURE_EDITING
927 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
930 #define G (*ptr_to_globals)
931 /* Not #defining name to G.name - this quickly gets unwieldy
932 * (too many defines). Also, I actually prefer to see when a variable
933 * is global, thus "G." prefix is a useful hint */
934 #define INIT_G() do { \
935 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
936 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
937 sigfillset(&G.sa.sa_mask); \
938 G.sa.sa_flags = SA_RESTART; \
942 /* Function prototypes for builtins */
943 static int builtin_cd(char **argv) FAST_FUNC;
945 static int builtin_echo(char **argv) FAST_FUNC;
947 static int builtin_eval(char **argv) FAST_FUNC;
948 static int builtin_exec(char **argv) FAST_FUNC;
949 static int builtin_exit(char **argv) FAST_FUNC;
950 #if ENABLE_HUSH_EXPORT
951 static int builtin_export(char **argv) FAST_FUNC;
954 static int builtin_fg_bg(char **argv) FAST_FUNC;
955 static int builtin_jobs(char **argv) FAST_FUNC;
958 static int builtin_help(char **argv) FAST_FUNC;
960 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
961 static int builtin_history(char **argv) FAST_FUNC;
963 #if ENABLE_HUSH_LOCAL
964 static int builtin_local(char **argv) FAST_FUNC;
966 #if ENABLE_HUSH_MEMLEAK
967 static int builtin_memleak(char **argv) FAST_FUNC;
969 #if ENABLE_HUSH_PRINTF
970 static int builtin_printf(char **argv) FAST_FUNC;
972 static int builtin_pwd(char **argv) FAST_FUNC;
974 static int builtin_read(char **argv) FAST_FUNC;
977 static int builtin_set(char **argv) FAST_FUNC;
979 static int builtin_shift(char **argv) FAST_FUNC;
980 static int builtin_source(char **argv) FAST_FUNC;
981 static int builtin_test(char **argv) FAST_FUNC;
983 static int builtin_trap(char **argv) FAST_FUNC;
986 static int builtin_type(char **argv) FAST_FUNC;
988 static int builtin_true(char **argv) FAST_FUNC;
989 #if ENABLE_HUSH_UMASK
990 static int builtin_umask(char **argv) FAST_FUNC;
992 #if ENABLE_HUSH_UNSET
993 static int builtin_unset(char **argv) FAST_FUNC;
996 static int builtin_kill(char **argv) FAST_FUNC;
999 static int builtin_wait(char **argv) FAST_FUNC;
1001 #if ENABLE_HUSH_LOOPS
1002 static int builtin_break(char **argv) FAST_FUNC;
1003 static int builtin_continue(char **argv) FAST_FUNC;
1005 #if ENABLE_HUSH_FUNCTIONS
1006 static int builtin_return(char **argv) FAST_FUNC;
1009 /* Table of built-in functions. They can be forked or not, depending on
1010 * context: within pipes, they fork. As simple commands, they do not.
1011 * When used in non-forking context, they can change global variables
1012 * in the parent shell process. If forked, of course they cannot.
1013 * For example, 'unset foo | whatever' will parse and run, but foo will
1014 * still be set at the end. */
1015 struct built_in_command {
1017 int (*b_function)(char **argv) FAST_FUNC;
1018 #if ENABLE_HUSH_HELP
1019 const char *b_descr;
1020 # define BLTIN(cmd, func, help) { cmd, func, help }
1022 # define BLTIN(cmd, func, help) { cmd, func }
1026 static const struct built_in_command bltins1[] = {
1027 BLTIN("." , builtin_source , "Run commands in a file"),
1028 BLTIN(":" , builtin_true , NULL),
1030 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
1032 #if ENABLE_HUSH_LOOPS
1033 BLTIN("break" , builtin_break , "Exit from a loop"),
1035 BLTIN("cd" , builtin_cd , "Change directory"),
1036 #if ENABLE_HUSH_LOOPS
1037 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1039 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1040 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1041 BLTIN("exit" , builtin_exit , "Exit"),
1042 #if ENABLE_HUSH_EXPORT
1043 BLTIN("export" , builtin_export , "Set environment variables"),
1046 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
1048 #if ENABLE_HUSH_HELP
1049 BLTIN("help" , builtin_help , NULL),
1051 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1052 BLTIN("history" , builtin_history , "Show command history"),
1055 BLTIN("jobs" , builtin_jobs , "List jobs"),
1057 #if ENABLE_HUSH_KILL
1058 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1060 #if ENABLE_HUSH_LOCAL
1061 BLTIN("local" , builtin_local , "Set local variables"),
1063 #if ENABLE_HUSH_MEMLEAK
1064 BLTIN("memleak" , builtin_memleak , NULL),
1066 #if ENABLE_HUSH_READ
1067 BLTIN("read" , builtin_read , "Input into variable"),
1069 #if ENABLE_HUSH_FUNCTIONS
1070 BLTIN("return" , builtin_return , "Return from a function"),
1073 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
1075 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1076 #if ENABLE_HUSH_BASH_COMPAT
1077 BLTIN("source" , builtin_source , "Run commands in a file"),
1079 #if ENABLE_HUSH_TRAP
1080 BLTIN("trap" , builtin_trap , "Trap signals"),
1082 BLTIN("true" , builtin_true , NULL),
1083 #if ENABLE_HUSH_TYPE
1084 BLTIN("type" , builtin_type , "Show command type"),
1086 #if ENABLE_HUSH_ULIMIT
1087 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1089 #if ENABLE_HUSH_UMASK
1090 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1092 #if ENABLE_HUSH_UNSET
1093 BLTIN("unset" , builtin_unset , "Unset variables"),
1095 #if ENABLE_HUSH_WAIT
1096 BLTIN("wait" , builtin_wait , "Wait for process"),
1099 /* For now, echo and test are unconditionally enabled.
1100 * Maybe make it configurable? */
1101 static const struct built_in_command bltins2[] = {
1102 BLTIN("[" , builtin_test , NULL),
1103 #if ENABLE_HUSH_ECHO
1104 BLTIN("echo" , builtin_echo , NULL),
1106 #if ENABLE_HUSH_PRINTF
1107 BLTIN("printf" , builtin_printf , NULL),
1109 BLTIN("pwd" , builtin_pwd , NULL),
1110 BLTIN("test" , builtin_test , NULL),
1117 /* prevent disasters with G.debug_indent < 0 */
1118 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1119 # define debug_enter() (G.debug_indent++)
1120 # define debug_leave() (G.debug_indent--)
1122 # define indent() ((void)0)
1123 # define debug_enter() ((void)0)
1124 # define debug_leave() ((void)0)
1127 #ifndef debug_printf
1128 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1131 #ifndef debug_printf_parse
1132 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1135 #ifndef debug_printf_exec
1136 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1139 #ifndef debug_printf_env
1140 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1143 #ifndef debug_printf_jobs
1144 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1145 # define DEBUG_JOBS 1
1147 # define DEBUG_JOBS 0
1150 #ifndef debug_printf_expand
1151 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1152 # define DEBUG_EXPAND 1
1154 # define DEBUG_EXPAND 0
1157 #ifndef debug_printf_varexp
1158 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1161 #ifndef debug_printf_glob
1162 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1163 # define DEBUG_GLOB 1
1165 # define DEBUG_GLOB 0
1168 #ifndef debug_printf_list
1169 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1172 #ifndef debug_printf_subst
1173 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1176 #ifndef debug_printf_clean
1177 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1178 # define DEBUG_CLEAN 1
1180 # define DEBUG_CLEAN 0
1184 static void debug_print_strings(const char *prefix, char **vv)
1187 fdprintf(2, "%s:\n", prefix);
1189 fdprintf(2, " '%s'\n", *vv++);
1192 # define debug_print_strings(prefix, vv) ((void)0)
1196 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1199 static void *xxmalloc(int lineno, size_t size)
1201 void *ptr = xmalloc((size + 0xff) & ~0xff);
1202 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1205 static void *xxrealloc(int lineno, void *ptr, size_t size)
1207 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1208 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1211 static char *xxstrdup(int lineno, const char *str)
1213 char *ptr = xstrdup(str);
1214 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1217 static void xxfree(void *ptr)
1219 fdprintf(2, "free %p\n", ptr);
1222 # define xmalloc(s) xxmalloc(__LINE__, s)
1223 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1224 # define xstrdup(s) xxstrdup(__LINE__, s)
1225 # define free(p) xxfree(p)
1229 /* Syntax and runtime errors. They always abort scripts.
1230 * In interactive use they usually discard unparsed and/or unexecuted commands
1231 * and return to the prompt.
1232 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1235 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1236 # define syntax_error(lineno, msg) syntax_error(msg)
1237 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1238 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1239 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1240 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1243 static void die_if_script(unsigned lineno, const char *fmt, ...)
1248 bb_error_msg("hush.c:%u", lineno);
1251 bb_verror_msg(fmt, p, NULL);
1253 if (!G_interactive_fd)
1257 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1260 bb_error_msg("syntax error: %s", msg);
1262 bb_error_msg("syntax error");
1265 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1267 bb_error_msg("syntax error at '%s'", msg);
1270 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1272 bb_error_msg("syntax error: unterminated %s", s);
1275 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1277 char msg[2] = { ch, '\0' };
1278 syntax_error_unterm_str(lineno, msg);
1281 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1287 bb_error_msg("hush.c:%u", lineno);
1289 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1293 # undef die_if_script
1294 # undef syntax_error
1295 # undef syntax_error_at
1296 # undef syntax_error_unterm_ch
1297 # undef syntax_error_unterm_str
1298 # undef syntax_error_unexpected_ch
1300 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1301 # define syntax_error(msg) syntax_error(__LINE__, msg)
1302 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1303 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1304 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1305 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1309 #if ENABLE_HUSH_INTERACTIVE
1310 static void cmdedit_update_prompt(void);
1312 # define cmdedit_update_prompt() ((void)0)
1316 /* Utility functions
1318 /* Replace each \x with x in place, return ptr past NUL. */
1319 static char *unbackslash(char *src)
1321 char *dst = src = strchrnul(src, '\\');
1325 if ((*dst++ = *src++) == '\0')
1331 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1352 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1353 v[count1 + count2] = NULL;
1356 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1360 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1362 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1363 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1366 #define add_strings_to_strings(strings, add, need_to_dup) \
1367 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1370 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1371 static char **add_string_to_strings(char **strings, char *add)
1376 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1379 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1381 char **ptr = add_string_to_strings(strings, add);
1382 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1385 #define add_string_to_strings(strings, add) \
1386 xx_add_string_to_strings(__LINE__, strings, add)
1389 static void free_strings(char **strings)
1404 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1406 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1407 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1409 /* fd was not open? */
1419 /* Manipulating the list of open FILEs */
1420 static FILE *remember_FILE(FILE *fp)
1423 struct FILE_list *n = xmalloc(sizeof(*n));
1424 n->next = G.FILE_list;
1428 close_on_exec_on(n->fd);
1432 static void fclose_and_forget(FILE *fp)
1434 struct FILE_list **pp = &G.FILE_list;
1436 struct FILE_list *cur = *pp;
1437 if (cur->fp == fp) {
1446 static int save_FILEs_on_redirect(int fd)
1448 struct FILE_list *fl = G.FILE_list;
1451 /* We use it only on script files, they are all CLOEXEC */
1452 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1459 static void restore_redirected_FILEs(void)
1461 struct FILE_list *fl = G.FILE_list;
1463 int should_be = fileno(fl->fp);
1464 if (fl->fd != should_be) {
1465 xmove_fd(fl->fd, should_be);
1471 #if ENABLE_FEATURE_SH_STANDALONE
1472 static void close_all_FILE_list(void)
1474 struct FILE_list *fl = G.FILE_list;
1476 /* fclose would also free FILE object.
1477 * It is disastrous if we share memory with a vforked parent.
1478 * I'm not sure we never come here after vfork.
1479 * Therefore just close fd, nothing more.
1481 /*fclose(fl->fp); - unsafe */
1489 /* Helpers for setting new $n and restoring them back
1491 typedef struct save_arg_t {
1495 IF_HUSH_SET(smallint sv_g_malloced;)
1498 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1502 sv->sv_argv0 = argv[0];
1503 sv->sv_g_argv = G.global_argv;
1504 sv->sv_g_argc = G.global_argc;
1505 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1507 argv[0] = G.global_argv[0]; /* retain $0 */
1508 G.global_argv = argv;
1509 IF_HUSH_SET(G.global_args_malloced = 0;)
1517 static void restore_G_args(save_arg_t *sv, char **argv)
1520 if (G.global_args_malloced) {
1521 /* someone ran "set -- arg1 arg2 ...", undo */
1522 char **pp = G.global_argv;
1523 while (*++pp) /* note: does not free $0 */
1525 free(G.global_argv);
1528 argv[0] = sv->sv_argv0;
1529 G.global_argv = sv->sv_g_argv;
1530 G.global_argc = sv->sv_g_argc;
1531 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1535 /* Basic theory of signal handling in shell
1536 * ========================================
1537 * This does not describe what hush does, rather, it is current understanding
1538 * what it _should_ do. If it doesn't, it's a bug.
1539 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1541 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1542 * is finished or backgrounded. It is the same in interactive and
1543 * non-interactive shells, and is the same regardless of whether
1544 * a user trap handler is installed or a shell special one is in effect.
1545 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1546 * backgrounds (i.e. stops) or kills all members of currently running
1549 * Wait builtin is interruptible by signals for which user trap is set
1550 * or by SIGINT in interactive shell.
1552 * Trap handlers will execute even within trap handlers. (right?)
1554 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1555 * except for handlers set to '' (empty string).
1557 * If job control is off, backgrounded commands ("cmd &")
1558 * have SIGINT, SIGQUIT set to SIG_IGN.
1560 * Commands which are run in command substitution ("`cmd`")
1561 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1563 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1564 * by the shell from its parent.
1566 * Signals which differ from SIG_DFL action
1567 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1570 * SIGTERM (interactive): ignore
1571 * SIGHUP (interactive):
1572 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1573 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1574 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1575 * that all pipe members are stopped. Try this in bash:
1576 * while :; do :; done - ^Z does not background it
1577 * (while :; do :; done) - ^Z backgrounds it
1578 * SIGINT (interactive): wait for last pipe, ignore the rest
1579 * of the command line, show prompt. NB: ^C does not send SIGINT
1580 * to interactive shell while shell is waiting for a pipe,
1581 * since shell is bg'ed (is not in foreground process group).
1582 * Example 1: this waits 5 sec, but does not execute ls:
1583 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1584 * Example 2: this does not wait and does not execute ls:
1585 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1586 * Example 3: this does not wait 5 sec, but executes ls:
1587 * "sleep 5; ls -l" + press ^C
1588 * Example 4: this does not wait and does not execute ls:
1589 * "sleep 5 & wait; ls -l" + press ^C
1591 * (What happens to signals which are IGN on shell start?)
1592 * (What happens with signal mask on shell start?)
1594 * Old implementation
1595 * ==================
1596 * We use in-kernel pending signal mask to determine which signals were sent.
1597 * We block all signals which we don't want to take action immediately,
1598 * i.e. we block all signals which need to have special handling as described
1599 * above, and all signals which have traps set.
1600 * After each pipe execution, we extract any pending signals via sigtimedwait()
1603 * unsigned special_sig_mask: a mask of such "special" signals
1604 * sigset_t blocked_set: current blocked signal set
1607 * clear bit in blocked_set unless it is also in special_sig_mask
1608 * "trap 'cmd' SIGxxx":
1609 * set bit in blocked_set (even if 'cmd' is '')
1610 * after [v]fork, if we plan to be a shell:
1611 * unblock signals with special interactive handling
1612 * (child shell is not interactive),
1613 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1614 * after [v]fork, if we plan to exec:
1615 * POSIX says fork clears pending signal mask in child - no need to clear it.
1616 * Restore blocked signal set to one inherited by shell just prior to exec.
1618 * Note: as a result, we do not use signal handlers much. The only uses
1619 * are to count SIGCHLDs
1620 * and to restore tty pgrp on signal-induced exit.
1623 * Standard says "When a subshell is entered, traps that are not being ignored
1624 * are set to the default actions". bash interprets it so that traps which
1625 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1627 * Problem: the above approach makes it unwieldy to catch signals while
1628 * we are in read builtin, or while we read commands from stdin:
1629 * masked signals are not visible!
1631 * New implementation
1632 * ==================
1633 * We record each signal we are interested in by installing signal handler
1634 * for them - a bit like emulating kernel pending signal mask in userspace.
1635 * We are interested in: signals which need to have special handling
1636 * as described above, and all signals which have traps set.
1637 * Signals are recorded in pending_set.
1638 * After each pipe execution, we extract any pending signals
1641 * unsigned special_sig_mask: a mask of shell-special signals.
1642 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1643 * char *traps[sig] if trap for sig is set (even if it's '').
1644 * sigset_t pending_set: set of sigs we received.
1647 * if sig is in special_sig_mask, set handler back to:
1648 * record_pending_signo, or to IGN if it's a tty stop signal
1649 * if sig is in fatal_sig_mask, set handler back to sigexit.
1650 * else: set handler back to SIG_DFL
1651 * "trap 'cmd' SIGxxx":
1652 * set handler to record_pending_signo.
1654 * set handler to SIG_IGN.
1655 * after [v]fork, if we plan to be a shell:
1656 * set signals with special interactive handling to SIG_DFL
1657 * (because child shell is not interactive),
1658 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1659 * after [v]fork, if we plan to exec:
1660 * POSIX says fork clears pending signal mask in child - no need to clear it.
1662 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1663 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1666 * Standard says "When a subshell is entered, traps that are not being ignored
1667 * are set to the default actions". bash interprets it so that traps which
1668 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1671 SPECIAL_INTERACTIVE_SIGS = 0
1676 SPECIAL_JOBSTOP_SIGS = 0
1685 static void record_pending_signo(int sig)
1687 sigaddset(&G.pending_set, sig);
1688 #if ENABLE_HUSH_FAST
1689 if (sig == SIGCHLD) {
1691 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1696 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1698 struct sigaction old_sa;
1700 /* We could use signal() to install handlers... almost:
1701 * except that we need to mask ALL signals while handlers run.
1702 * I saw signal nesting in strace, race window isn't small.
1703 * SA_RESTART is also needed, but in Linux, signal()
1704 * sets SA_RESTART too.
1706 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1707 /* sigfillset(&G.sa.sa_mask); - already done */
1708 /* G.sa.sa_flags = SA_RESTART; - already done */
1709 G.sa.sa_handler = handler;
1710 sigaction(sig, &G.sa, &old_sa);
1711 return old_sa.sa_handler;
1714 static void hush_exit(int exitcode) NORETURN;
1716 static void restore_ttypgrp_and__exit(void) NORETURN;
1717 static void restore_ttypgrp_and__exit(void)
1719 /* xfunc has failed! die die die */
1720 /* no EXIT traps, this is an escape hatch! */
1722 hush_exit(xfunc_error_retval);
1727 /* Needed only on some libc:
1728 * It was observed that on exit(), fgetc'ed buffered data
1729 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1730 * With the net effect that even after fork(), not vfork(),
1731 * exit() in NOEXECed applet in "sh SCRIPT":
1732 * noexec_applet_here
1733 * echo END_OF_SCRIPT
1734 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1735 * This makes "echo END_OF_SCRIPT" executed twice.
1736 * Similar problems can be seen with die_if_script() -> xfunc_die()
1737 * and in `cmd` handling.
1738 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1740 static void fflush_and__exit(void) NORETURN;
1741 static void fflush_and__exit(void)
1744 _exit(xfunc_error_retval);
1747 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1748 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1749 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1750 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1752 /* Restores tty foreground process group, and exits.
1753 * May be called as signal handler for fatal signal
1754 * (will resend signal to itself, producing correct exit state)
1755 * or called directly with -EXITCODE.
1756 * We also call it if xfunc is exiting.
1758 static void sigexit(int sig) NORETURN;
1759 static void sigexit(int sig)
1761 /* Careful: we can end up here after [v]fork. Do not restore
1762 * tty pgrp then, only top-level shell process does that */
1763 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1764 /* Disable all signals: job control, SIGPIPE, etc.
1765 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1767 sigprocmask_allsigs(SIG_BLOCK);
1768 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1771 /* Not a signal, just exit */
1775 kill_myself_with_sig(sig); /* does not return */
1779 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1780 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1784 static sighandler_t pick_sighandler(unsigned sig)
1786 sighandler_t handler = SIG_DFL;
1787 if (sig < sizeof(unsigned)*8) {
1788 unsigned sigmask = (1 << sig);
1792 if (G_fatal_sig_mask & sigmask)
1796 /* sig has special handling? */
1797 if (G.special_sig_mask & sigmask) {
1798 handler = record_pending_signo;
1799 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1800 * in order to ignore them: they will be raised
1801 * in an endless loop when we try to do some
1802 * terminal ioctls! We do have to _ignore_ these.
1804 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1811 /* Restores tty foreground process group, and exits. */
1812 static void hush_exit(int exitcode)
1814 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1815 save_history(G.line_input_state);
1819 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1821 /* argv[0] is unused */
1822 argv[1] = G_traps[0];
1824 G.exiting = 1; /* prevent EXIT trap recursion */
1825 /* Note: G_traps[0] is not cleared!
1826 * "trap" will still show it, if executed
1831 #if ENABLE_FEATURE_CLEAN_UP
1833 struct variable *cur_var;
1834 if (G.cwd != bb_msg_unknown)
1836 cur_var = G.top_var;
1838 struct variable *tmp = cur_var;
1839 if (!cur_var->max_len)
1840 free(cur_var->varstr);
1841 cur_var = cur_var->next;
1849 sigexit(- (exitcode & 0xff));
1856 //TODO: return a mask of ALL handled sigs?
1857 static int check_and_run_traps(void)
1864 if (sigisemptyset(&G.pending_set))
1869 if (sigismember(&G.pending_set, sig)) {
1870 sigdelset(&G.pending_set, sig);
1873 } while (sig < NSIG);
1876 if (G_traps && G_traps[sig]) {
1877 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1878 if (G_traps[sig][0]) {
1879 /* We have user-defined handler */
1880 smalluint save_rcode;
1882 /* argv[0] is unused */
1883 argv[1] = G_traps[sig];
1885 save_rcode = G.last_exitcode;
1887 //FIXME: shouldn't it be set to 128 + sig instead?
1888 G.last_exitcode = save_rcode;
1890 } /* else: "" trap, ignoring signal */
1893 /* not a trap: special action */
1896 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1903 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1904 /* bash is observed to signal whole process groups,
1905 * not individual processes */
1906 for (job = G.job_list; job; job = job->next) {
1909 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1910 if (kill(- job->pgrp, SIGHUP) == 0)
1911 kill(- job->pgrp, SIGCONT);
1916 #if ENABLE_HUSH_FAST
1918 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1920 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1922 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1923 * This simplifies wait builtin a bit.
1927 default: /* ignored: */
1928 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1929 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1931 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1932 * Example: wait is not interrupted by TERM
1933 * in interactive shell, because TERM is ignored.
1942 static const char *get_cwd(int force)
1944 if (force || G.cwd == NULL) {
1945 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1946 * we must not try to free(bb_msg_unknown) */
1947 if (G.cwd == bb_msg_unknown)
1949 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1951 G.cwd = bb_msg_unknown;
1958 * Shell and environment variable support
1960 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1962 struct variable **pp;
1963 struct variable *cur;
1966 while ((cur = *pp) != NULL) {
1967 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1974 static const char* FAST_FUNC get_local_var_value(const char *name)
1976 struct variable **vpp;
1977 unsigned len = strlen(name);
1979 if (G.expanded_assignments) {
1980 char **cpp = G.expanded_assignments;
1983 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1984 return cp + len + 1;
1989 vpp = get_ptr_to_local_var(name, len);
1991 return (*vpp)->varstr + len + 1;
1993 if (strcmp(name, "PPID") == 0)
1994 return utoa(G.root_ppid);
1995 // bash compat: UID? EUID?
1996 #if ENABLE_HUSH_RANDOM_SUPPORT
1997 if (strcmp(name, "RANDOM") == 0)
1998 return utoa(next_random(&G.random_gen));
2003 /* str holds "NAME=VAL" and is expected to be malloced.
2004 * We take ownership of it.
2006 * 0: do not change export flag
2007 * (if creating new variable, flag will be 0)
2008 * 1: set export flag and putenv the variable
2009 * -1: clear export flag and unsetenv the variable
2010 * flg_read_only is set only when we handle -R var=val
2012 #if !BB_MMU && ENABLE_HUSH_LOCAL
2013 /* all params are used */
2014 #elif BB_MMU && ENABLE_HUSH_LOCAL
2015 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2016 set_local_var(str, flg_export, local_lvl)
2017 #elif BB_MMU && !ENABLE_HUSH_LOCAL
2018 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2019 set_local_var(str, flg_export)
2020 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
2021 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
2022 set_local_var(str, flg_export, flg_read_only)
2024 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
2026 struct variable **var_pp;
2027 struct variable *cur;
2028 char *free_me = NULL;
2032 eq_sign = strchr(str, '=');
2033 if (!eq_sign) { /* not expected to ever happen? */
2038 name_len = eq_sign - str + 1; /* including '=' */
2039 var_pp = &G.top_var;
2040 while ((cur = *var_pp) != NULL) {
2041 if (strncmp(cur->varstr, str, name_len) != 0) {
2042 var_pp = &cur->next;
2046 /* We found an existing var with this name */
2047 if (cur->flg_read_only) {
2051 bb_error_msg("%s: readonly variable", str);
2055 if (flg_export == -1) { // "&& cur->flg_export" ?
2056 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2061 #if ENABLE_HUSH_LOCAL
2062 if (cur->func_nest_level < local_lvl) {
2063 /* New variable is declared as local,
2064 * and existing one is global, or local
2065 * from enclosing function.
2066 * Remove and save old one: */
2067 *var_pp = cur->next;
2068 cur->next = *G.shadowed_vars_pp;
2069 *G.shadowed_vars_pp = cur;
2070 /* bash 3.2.33(1) and exported vars:
2072 * # f() { local z=a; env | grep ^z; }
2078 if (cur->flg_export)
2083 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2088 if (cur->max_len != 0) {
2089 if (cur->max_len >= strlen(str)) {
2090 /* This one is from startup env, reuse space */
2091 strcpy(cur->varstr, str);
2096 goto set_str_and_exp;
2098 /* max_len == 0 signifies "malloced" var, which we can
2099 * (and have to) free. But we can't free(cur->varstr) here:
2100 * if cur->flg_export is 1, it is in the environment.
2101 * We should either unsetenv+free, or wait until putenv,
2102 * then putenv(new)+free(old).
2104 free_me = cur->varstr;
2105 goto set_str_and_exp;
2108 /* Not found - create new variable struct */
2109 cur = xzalloc(sizeof(*cur));
2110 #if ENABLE_HUSH_LOCAL
2111 cur->func_nest_level = local_lvl;
2113 cur->next = *var_pp;
2119 cur->flg_read_only = flg_read_only;
2122 if (flg_export == 1)
2123 cur->flg_export = 1;
2124 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2125 cmdedit_update_prompt();
2126 if (cur->flg_export) {
2127 if (flg_export == -1) {
2128 cur->flg_export = 0;
2129 /* unsetenv was already done */
2132 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2133 i = putenv(cur->varstr);
2134 /* only now we can free old exported malloced string */
2143 /* Used at startup and after each cd */
2144 static void set_pwd_var(int exp)
2146 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2147 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2150 static int unset_local_var_len(const char *name, int name_len)
2152 struct variable *cur;
2153 struct variable **var_pp;
2156 return EXIT_SUCCESS;
2157 var_pp = &G.top_var;
2158 while ((cur = *var_pp) != NULL) {
2159 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2160 if (cur->flg_read_only) {
2161 bb_error_msg("%s: readonly variable", name);
2162 return EXIT_FAILURE;
2164 *var_pp = cur->next;
2165 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2166 bb_unsetenv(cur->varstr);
2167 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2168 cmdedit_update_prompt();
2172 return EXIT_SUCCESS;
2174 var_pp = &cur->next;
2176 return EXIT_SUCCESS;
2179 #if ENABLE_HUSH_UNSET
2180 static int unset_local_var(const char *name)
2182 return unset_local_var_len(name, strlen(name));
2186 static void unset_vars(char **strings)
2194 const char *eq = strchrnul(*v, '=');
2195 unset_local_var_len(*v, (int)(eq - *v));
2201 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_BASH_COMPAT || ENABLE_HUSH_READ
2202 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2204 char *var = xasprintf("%s=%s", name, val);
2205 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2211 * Helpers for "var1=val1 var2=val2 cmd" feature
2213 static void add_vars(struct variable *var)
2215 struct variable *next;
2219 var->next = G.top_var;
2221 if (var->flg_export) {
2222 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2223 putenv(var->varstr);
2225 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2231 static struct variable *set_vars_and_save_old(char **strings)
2234 struct variable *old = NULL;
2240 struct variable *var_p;
2241 struct variable **var_pp;
2244 eq = strchr(*s, '=');
2246 var_pp = get_ptr_to_local_var(*s, eq - *s);
2248 /* Remove variable from global linked list */
2250 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2251 *var_pp = var_p->next;
2252 /* Add it to returned list */
2256 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2267 static void reinit_unicode_for_hush(void)
2269 /* Unicode support should be activated even if LANG is set
2270 * _during_ shell execution, not only if it was set when
2271 * shell was started. Therefore, re-check LANG every time:
2273 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2274 || ENABLE_UNICODE_USING_LOCALE
2276 const char *s = get_local_var_value("LC_ALL");
2277 if (!s) s = get_local_var_value("LC_CTYPE");
2278 if (!s) s = get_local_var_value("LANG");
2284 * in_str support (strings, and "strings" read from files).
2287 #if ENABLE_HUSH_INTERACTIVE
2288 /* To test correct lineedit/interactive behavior, type from command line:
2294 * It excercises a lot of corner cases.
2296 static void cmdedit_update_prompt(void)
2298 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2299 G.PS1 = get_local_var_value("PS1");
2302 G.PS2 = get_local_var_value("PS2");
2309 static const char *setup_prompt_string(int promptmode)
2311 const char *prompt_str;
2312 debug_printf("setup_prompt_string %d ", promptmode);
2313 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2314 /* Set up the prompt */
2315 if (promptmode == 0) { /* PS1 */
2317 /* bash uses $PWD value, even if it is set by user.
2318 * It uses current dir only if PWD is unset.
2319 * We always use current dir. */
2320 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2325 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2326 debug_printf("prompt_str '%s'\n", prompt_str);
2329 static int get_user_input(struct in_str *i)
2332 const char *prompt_str;
2334 prompt_str = setup_prompt_string(i->promptmode);
2335 # if ENABLE_FEATURE_EDITING
2337 reinit_unicode_for_hush();
2338 if (G.flag_SIGINT) {
2339 /* There was ^C'ed, make it look prettier: */
2343 /* buglet: SIGINT will not make new prompt to appear _at once_,
2344 * only after <Enter>. (^C works immediately) */
2345 r = read_line_input(G.line_input_state, prompt_str,
2346 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2349 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2351 write(STDOUT_FILENO, "^C", 2);
2354 check_and_run_traps();
2355 if (r != 0 && !G.flag_SIGINT)
2357 /* ^C or SIGINT: repeat */
2358 G.last_exitcode = 128 + SIGINT;
2361 /* EOF/error detected */
2363 i->peek_buf[0] = r = EOF;
2366 i->p = G.user_input_buf;
2367 return (unsigned char)*i->p++;
2371 if (i->last_char == '\0' || i->last_char == '\n') {
2372 /* Why check_and_run_traps here? Try this interactively:
2373 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2374 * $ <[enter], repeatedly...>
2375 * Without check_and_run_traps, handler never runs.
2377 check_and_run_traps();
2378 fputs(prompt_str, stdout);
2381 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2383 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2384 * no ^C masking happens during fgetc, no special code for ^C:
2385 * it generates SIGINT as usual.
2387 check_and_run_traps();
2389 G.last_exitcode = 128 + SIGINT;
2396 /* This is the magic location that prints prompts
2397 * and gets data back from the user */
2398 static int fgetc_interactive(struct in_str *i)
2401 /* If it's interactive stdin, get new line. */
2402 if (G_interactive_fd && i->file == stdin) {
2403 /* Returns first char (or EOF), the rest is in i->p[] */
2404 ch = get_user_input(i);
2405 i->promptmode = 1; /* PS2 */
2407 /* Not stdin: script file, sourced file, etc */
2408 do ch = fgetc(i->file); while (ch == '\0');
2413 static inline int fgetc_interactive(struct in_str *i)
2416 do ch = fgetc(i->file); while (ch == '\0');
2419 #endif /* INTERACTIVE */
2421 static int i_getch(struct in_str *i)
2426 /* string-based in_str */
2427 ch = (unsigned char)*i->p;
2436 /* FILE-based in_str */
2438 #if ENABLE_FEATURE_EDITING
2439 /* This can be stdin, check line editing char[] buffer */
2440 if (i->p && *i->p != '\0') {
2441 ch = (unsigned char)*i->p++;
2445 /* peek_buf[] is an int array, not char. Can contain EOF. */
2446 ch = i->peek_buf[0];
2448 int ch2 = i->peek_buf[1];
2449 i->peek_buf[0] = ch2;
2450 if (ch2 == 0) /* very likely, avoid redundant write */
2456 ch = fgetc_interactive(i);
2458 debug_printf("file_get: got '%c' %d\n", ch, ch);
2463 static int i_peek(struct in_str *i)
2468 /* string-based in_str */
2469 /* Doesn't report EOF on NUL. None of the callers care. */
2470 return (unsigned char)*i->p;
2473 /* FILE-based in_str */
2475 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2476 /* This can be stdin, check line editing char[] buffer */
2477 if (i->p && *i->p != '\0')
2478 return (unsigned char)*i->p;
2480 /* peek_buf[] is an int array, not char. Can contain EOF. */
2481 ch = i->peek_buf[0];
2485 /* Need to get a new char */
2486 ch = fgetc_interactive(i);
2487 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2489 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2490 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2496 i->peek_buf[0] = ch;
2497 /*i->peek_buf[1] = 0; - already is */
2501 /* Only ever called if i_peek() was called, and did not return EOF.
2502 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2503 * not end-of-line. Therefore we never need to read a new editing line here.
2505 static int i_peek2(struct in_str *i)
2509 /* There are two cases when i->p[] buffer exists.
2510 * (1) it's a string in_str.
2511 * (2) It's a file, and we have a saved line editing buffer.
2512 * In both cases, we know that i->p[0] exists and not NUL, and
2513 * the peek2 result is in i->p[1].
2516 return (unsigned char)i->p[1];
2518 /* Now we know it is a file-based in_str. */
2520 /* peek_buf[] is an int array, not char. Can contain EOF. */
2521 /* Is there 2nd char? */
2522 ch = i->peek_buf[1];
2524 /* We did not read it yet, get it now */
2525 do ch = fgetc(i->file); while (ch == '\0');
2526 i->peek_buf[1] = ch;
2529 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2533 static void setup_file_in_str(struct in_str *i, FILE *f)
2535 memset(i, 0, sizeof(*i));
2536 /* i->promptmode = 0; - PS1 (memset did it) */
2541 static void setup_string_in_str(struct in_str *i, const char *s)
2543 memset(i, 0, sizeof(*i));
2544 /* i->promptmode = 0; - PS1 (memset did it) */
2545 /*i->file = NULL */;
2553 #define B_CHUNK (32 * sizeof(char*))
2555 static void o_reset_to_empty_unquoted(o_string *o)
2558 o->has_quoted_part = 0;
2563 static void o_free(o_string *o)
2566 memset(o, 0, sizeof(*o));
2569 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2574 static void o_grow_by(o_string *o, int len)
2576 if (o->length + len > o->maxlen) {
2577 o->maxlen += (2 * len) | (B_CHUNK-1);
2578 o->data = xrealloc(o->data, 1 + o->maxlen);
2582 static void o_addchr(o_string *o, int ch)
2584 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2585 if (o->length < o->maxlen) {
2586 /* likely. avoid o_grow_by() call */
2588 o->data[o->length] = ch;
2590 o->data[o->length] = '\0';
2598 /* Valid only if we know o_string is not empty */
2599 static void o_delchr(o_string *o)
2602 o->data[o->length] = '\0';
2606 static void o_addblock(o_string *o, const char *str, int len)
2609 memcpy(&o->data[o->length], str, len);
2611 o->data[o->length] = '\0';
2614 static void o_addstr(o_string *o, const char *str)
2616 o_addblock(o, str, strlen(str));
2620 static void nommu_addchr(o_string *o, int ch)
2626 # define nommu_addchr(o, str) ((void)0)
2629 static void o_addstr_with_NUL(o_string *o, const char *str)
2631 o_addblock(o, str, strlen(str) + 1);
2635 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2636 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2637 * Apparently, on unquoted $v bash still does globbing
2638 * ("v='*.txt'; echo $v" prints all .txt files),
2639 * but NOT brace expansion! Thus, there should be TWO independent
2640 * quoting mechanisms on $v expansion side: one protects
2641 * $v from brace expansion, and other additionally protects "$v" against globbing.
2642 * We have only second one.
2645 #if ENABLE_HUSH_BRACE_EXPANSION
2646 # define MAYBE_BRACES "{}"
2648 # define MAYBE_BRACES ""
2651 /* My analysis of quoting semantics tells me that state information
2652 * is associated with a destination, not a source.
2654 static void o_addqchr(o_string *o, int ch)
2657 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2662 o->data[o->length] = '\\';
2665 o->data[o->length] = ch;
2667 o->data[o->length] = '\0';
2670 static void o_addQchr(o_string *o, int ch)
2673 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2674 && strchr("*?[\\" MAYBE_BRACES, ch)
2677 o->data[o->length] = '\\';
2681 o->data[o->length] = ch;
2683 o->data[o->length] = '\0';
2686 static void o_addqblock(o_string *o, const char *str, int len)
2691 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2692 if (ordinary_cnt > len) /* paranoia */
2694 o_addblock(o, str, ordinary_cnt);
2695 if (ordinary_cnt == len)
2696 return; /* NUL is already added by o_addblock */
2697 str += ordinary_cnt;
2698 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2702 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2704 o->data[o->length] = '\\';
2708 o->data[o->length] = ch;
2711 o->data[o->length] = '\0';
2714 static void o_addQblock(o_string *o, const char *str, int len)
2716 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2717 o_addblock(o, str, len);
2720 o_addqblock(o, str, len);
2723 static void o_addQstr(o_string *o, const char *str)
2725 o_addQblock(o, str, strlen(str));
2728 /* A special kind of o_string for $VAR and `cmd` expansion.
2729 * It contains char* list[] at the beginning, which is grown in 16 element
2730 * increments. Actual string data starts at the next multiple of 16 * (char*).
2731 * list[i] contains an INDEX (int!) into this string data.
2732 * It means that if list[] needs to grow, data needs to be moved higher up
2733 * but list[i]'s need not be modified.
2734 * NB: remembering how many list[i]'s you have there is crucial.
2735 * o_finalize_list() operation post-processes this structure - calculates
2736 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2738 #if DEBUG_EXPAND || DEBUG_GLOB
2739 static void debug_print_list(const char *prefix, o_string *o, int n)
2741 char **list = (char**)o->data;
2742 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2746 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2747 prefix, list, n, string_start, o->length, o->maxlen,
2748 !!(o->o_expflags & EXP_FLAG_GLOB),
2750 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2753 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2754 o->data + (int)(uintptr_t)list[i] + string_start,
2755 o->data + (int)(uintptr_t)list[i] + string_start);
2759 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2761 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2765 # define debug_print_list(prefix, o, n) ((void)0)
2768 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2769 * in list[n] so that it points past last stored byte so far.
2770 * It returns n+1. */
2771 static int o_save_ptr_helper(o_string *o, int n)
2773 char **list = (char**)o->data;
2777 if (!o->has_empty_slot) {
2778 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2779 string_len = o->length - string_start;
2780 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2781 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2782 /* list[n] points to string_start, make space for 16 more pointers */
2783 o->maxlen += 0x10 * sizeof(list[0]);
2784 o->data = xrealloc(o->data, o->maxlen + 1);
2785 list = (char**)o->data;
2786 memmove(list + n + 0x10, list + n, string_len);
2787 o->length += 0x10 * sizeof(list[0]);
2789 debug_printf_list("list[%d]=%d string_start=%d\n",
2790 n, string_len, string_start);
2793 /* We have empty slot at list[n], reuse without growth */
2794 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2795 string_len = o->length - string_start;
2796 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2797 n, string_len, string_start);
2798 o->has_empty_slot = 0;
2800 o->has_quoted_part = 0;
2801 list[n] = (char*)(uintptr_t)string_len;
2805 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2806 static int o_get_last_ptr(o_string *o, int n)
2808 char **list = (char**)o->data;
2809 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2811 return ((int)(uintptr_t)list[n-1]) + string_start;
2814 #if ENABLE_HUSH_BRACE_EXPANSION
2815 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2816 * first, it processes even {a} (no commas), second,
2817 * I didn't manage to make it return strings when they don't match
2818 * existing files. Need to re-implement it.
2822 static int glob_needed(const char *s)
2831 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2837 /* Return pointer to next closing brace or to comma */
2838 static const char *next_brace_sub(const char *cp)
2842 while (*cp != '\0') {
2849 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2855 return *cp != '\0' ? cp : NULL;
2857 /* Recursive brace globber. Note: may garble pattern[]. */
2858 static int glob_brace(char *pattern, o_string *o, int n)
2860 char *new_pattern_buf;
2867 debug_printf_glob("glob_brace('%s')\n", pattern);
2873 if (*begin == '{') {
2874 /* Find the first sub-pattern and at the same time
2875 * find the rest after the closing brace */
2876 next = next_brace_sub(begin);
2878 /* An illegal expression */
2882 /* "{abc}" with no commas - illegal
2883 * brace expr, disregard and skip it */
2889 if (*begin == '\\' && begin[1] != '\0')
2893 debug_printf_glob("begin:%s\n", begin);
2894 debug_printf_glob("next:%s\n", next);
2896 /* Now find the end of the whole brace expression */
2898 while (*rest != '}') {
2899 rest = next_brace_sub(rest);
2901 /* An illegal expression */
2904 debug_printf_glob("rest:%s\n", rest);
2906 rest_len = strlen(++rest) + 1;
2908 /* We are sure the brace expression is well-formed */
2910 /* Allocate working buffer large enough for our work */
2911 new_pattern_buf = xmalloc(strlen(pattern));
2913 /* We have a brace expression. BEGIN points to the opening {,
2914 * NEXT points past the terminator of the first element, and REST
2915 * points past the final }. We will accumulate result names from
2916 * recursive runs for each brace alternative in the buffer using
2921 /* Construct the new glob expression */
2924 mempcpy(new_pattern_buf,
2925 /* We know the prefix for all sub-patterns */
2926 pattern, begin - pattern),
2930 /* Note: glob_brace() may garble new_pattern_buf[].
2931 * That's why we re-copy prefix every time (1st memcpy above).
2933 n = glob_brace(new_pattern_buf, o, n);
2935 /* We saw the last entry */
2939 next = next_brace_sub(next);
2941 free(new_pattern_buf);
2949 memset(&globdata, 0, sizeof(globdata));
2950 gr = glob(pattern, 0, NULL, &globdata);
2951 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2953 if (gr == GLOB_NOMATCH) {
2954 globfree(&globdata);
2955 /* NB: garbles parameter */
2956 unbackslash(pattern);
2957 o_addstr_with_NUL(o, pattern);
2958 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2959 return o_save_ptr_helper(o, n);
2961 if (gr == GLOB_NOSPACE)
2962 bb_error_msg_and_die(bb_msg_memory_exhausted);
2963 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2964 * but we didn't specify it. Paranoia again. */
2965 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2967 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2968 char **argv = globdata.gl_pathv;
2970 o_addstr_with_NUL(o, *argv);
2971 n = o_save_ptr_helper(o, n);
2977 globfree(&globdata);
2981 /* Performs globbing on last list[],
2982 * saving each result as a new list[].
2984 static int perform_glob(o_string *o, int n)
2986 char *pattern, *copy;
2988 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2990 return o_save_ptr_helper(o, n);
2991 pattern = o->data + o_get_last_ptr(o, n);
2992 debug_printf_glob("glob pattern '%s'\n", pattern);
2993 if (!glob_needed(pattern)) {
2994 /* unbackslash last string in o in place, fix length */
2995 o->length = unbackslash(pattern) - o->data;
2996 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2997 return o_save_ptr_helper(o, n);
3000 copy = xstrdup(pattern);
3001 /* "forget" pattern in o */
3002 o->length = pattern - o->data;
3003 n = glob_brace(copy, o, n);
3006 debug_print_list("perform_glob returning", o, n);
3010 #else /* !HUSH_BRACE_EXPANSION */
3013 static int glob_needed(const char *s)
3022 if (*s == '*' || *s == '[' || *s == '?')
3028 /* Performs globbing on last list[],
3029 * saving each result as a new list[].
3031 static int perform_glob(o_string *o, int n)
3037 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3039 return o_save_ptr_helper(o, n);
3040 pattern = o->data + o_get_last_ptr(o, n);
3041 debug_printf_glob("glob pattern '%s'\n", pattern);
3042 if (!glob_needed(pattern)) {
3044 /* unbackslash last string in o in place, fix length */
3045 o->length = unbackslash(pattern) - o->data;
3046 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3047 return o_save_ptr_helper(o, n);
3050 memset(&globdata, 0, sizeof(globdata));
3051 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3052 * If we glob "*.\*" and don't find anything, we need
3053 * to fall back to using literal "*.*", but GLOB_NOCHECK
3054 * will return "*.\*"!
3056 gr = glob(pattern, 0, NULL, &globdata);
3057 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3059 if (gr == GLOB_NOMATCH) {
3060 globfree(&globdata);
3063 if (gr == GLOB_NOSPACE)
3064 bb_error_msg_and_die(bb_msg_memory_exhausted);
3065 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3066 * but we didn't specify it. Paranoia again. */
3067 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3069 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3070 char **argv = globdata.gl_pathv;
3071 /* "forget" pattern in o */
3072 o->length = pattern - o->data;
3074 o_addstr_with_NUL(o, *argv);
3075 n = o_save_ptr_helper(o, n);
3081 globfree(&globdata);
3083 debug_print_list("perform_glob returning", o, n);
3087 #endif /* !HUSH_BRACE_EXPANSION */
3089 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3090 * Otherwise, just finish current list[] and start new */
3091 static int o_save_ptr(o_string *o, int n)
3093 if (o->o_expflags & EXP_FLAG_GLOB) {
3094 /* If o->has_empty_slot, list[n] was already globbed
3095 * (if it was requested back then when it was filled)
3096 * so don't do that again! */
3097 if (!o->has_empty_slot)
3098 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3100 return o_save_ptr_helper(o, n);
3103 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3104 static char **o_finalize_list(o_string *o, int n)
3109 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3111 debug_print_list("finalized", o, n);
3112 debug_printf_expand("finalized n:%d\n", n);
3113 list = (char**)o->data;
3114 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3118 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3123 static void free_pipe_list(struct pipe *pi);
3125 /* Returns pi->next - next pipe in the list */
3126 static struct pipe *free_pipe(struct pipe *pi)
3131 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3132 for (i = 0; i < pi->num_cmds; i++) {
3133 struct command *command;
3134 struct redir_struct *r, *rnext;
3136 command = &pi->cmds[i];
3137 debug_printf_clean(" command %d:\n", i);
3138 if (command->argv) {
3142 for (a = 0, p = command->argv; *p; a++, p++) {
3143 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3146 free_strings(command->argv);
3147 //command->argv = NULL;
3149 /* not "else if": on syntax error, we may have both! */
3150 if (command->group) {
3151 debug_printf_clean(" begin group (cmd_type:%d)\n",
3153 free_pipe_list(command->group);
3154 debug_printf_clean(" end group\n");
3155 //command->group = NULL;
3157 /* else is crucial here.
3158 * If group != NULL, child_func is meaningless */
3159 #if ENABLE_HUSH_FUNCTIONS
3160 else if (command->child_func) {
3161 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3162 command->child_func->parent_cmd = NULL;
3166 free(command->group_as_string);
3167 //command->group_as_string = NULL;
3169 for (r = command->redirects; r; r = rnext) {
3170 debug_printf_clean(" redirect %d%s",
3171 r->rd_fd, redir_table[r->rd_type].descrip);
3172 /* guard against the case >$FOO, where foo is unset or blank */
3173 if (r->rd_filename) {
3174 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3175 free(r->rd_filename);
3176 //r->rd_filename = NULL;
3178 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3182 //command->redirects = NULL;
3184 free(pi->cmds); /* children are an array, they get freed all at once */
3188 //pi->cmdtext = NULL;
3196 static void free_pipe_list(struct pipe *pi)
3200 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3202 debug_printf_clean("pipe followup code %d\n", pi->followup);
3208 /*** Parsing routines ***/
3210 #ifndef debug_print_tree
3211 static void debug_print_tree(struct pipe *pi, int lvl)
3213 static const char *const PIPE[] = {
3219 static const char *RES[] = {
3220 [RES_NONE ] = "NONE" ,
3223 [RES_THEN ] = "THEN" ,
3224 [RES_ELIF ] = "ELIF" ,
3225 [RES_ELSE ] = "ELSE" ,
3228 # if ENABLE_HUSH_LOOPS
3229 [RES_FOR ] = "FOR" ,
3230 [RES_WHILE] = "WHILE",
3231 [RES_UNTIL] = "UNTIL",
3233 [RES_DONE ] = "DONE" ,
3235 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3238 # if ENABLE_HUSH_CASE
3239 [RES_CASE ] = "CASE" ,
3240 [RES_CASE_IN ] = "CASE_IN" ,
3241 [RES_MATCH] = "MATCH",
3242 [RES_CASE_BODY] = "CASE_BODY",
3243 [RES_ESAC ] = "ESAC" ,
3245 [RES_XXXX ] = "XXXX" ,
3246 [RES_SNTX ] = "SNTX" ,
3248 static const char *const CMDTYPE[] = {
3252 # if ENABLE_HUSH_FUNCTIONS
3261 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3262 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3264 while (prn < pi->num_cmds) {
3265 struct command *command = &pi->cmds[prn];
3266 char **argv = command->argv;
3268 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3270 command->assignment_cnt);
3271 if (command->group) {
3272 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3273 CMDTYPE[command->cmd_type],
3276 , " group_as_string:", command->group_as_string
3281 debug_print_tree(command->group, lvl+1);
3285 if (argv) while (*argv) {
3286 fdprintf(2, " '%s'", *argv);
3296 #endif /* debug_print_tree */
3298 static struct pipe *new_pipe(void)
3301 pi = xzalloc(sizeof(struct pipe));
3302 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3306 /* Command (member of a pipe) is complete, or we start a new pipe
3307 * if ctx->command is NULL.
3308 * No errors possible here.
3310 static int done_command(struct parse_context *ctx)
3312 /* The command is really already in the pipe structure, so
3313 * advance the pipe counter and make a new, null command. */
3314 struct pipe *pi = ctx->pipe;
3315 struct command *command = ctx->command;
3317 #if 0 /* Instead we emit error message at run time */
3318 if (ctx->pending_redirect) {
3319 /* For example, "cmd >" (no filename to redirect to) */
3320 die_if_script("syntax error: %s", "invalid redirect");
3321 ctx->pending_redirect = NULL;
3326 if (IS_NULL_CMD(command)) {
3327 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3331 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3332 //debug_print_tree(ctx->list_head, 20);
3334 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3337 /* Only real trickiness here is that the uncommitted
3338 * command structure is not counted in pi->num_cmds. */
3339 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3340 ctx->command = command = &pi->cmds[pi->num_cmds];
3342 memset(command, 0, sizeof(*command));
3343 return pi->num_cmds; /* used only for 0/nonzero check */
3346 static void done_pipe(struct parse_context *ctx, pipe_style type)
3350 debug_printf_parse("done_pipe entered, followup %d\n", type);
3351 /* Close previous command */
3352 not_null = done_command(ctx);
3353 ctx->pipe->followup = type;
3355 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3356 ctx->ctx_inverted = 0;
3357 ctx->pipe->res_word = ctx->ctx_res_w;
3360 /* Without this check, even just <enter> on command line generates
3361 * tree of three NOPs (!). Which is harmless but annoying.
3362 * IOW: it is safe to do it unconditionally. */
3365 || ctx->ctx_res_w == RES_FI
3367 #if ENABLE_HUSH_LOOPS
3368 || ctx->ctx_res_w == RES_DONE
3369 || ctx->ctx_res_w == RES_FOR
3370 || ctx->ctx_res_w == RES_IN
3372 #if ENABLE_HUSH_CASE
3373 || ctx->ctx_res_w == RES_ESAC
3377 debug_printf_parse("done_pipe: adding new pipe: "
3378 "not_null:%d ctx->ctx_res_w:%d\n",
3379 not_null, ctx->ctx_res_w);
3381 ctx->pipe->next = new_p;
3383 /* RES_THEN, RES_DO etc are "sticky" -
3384 * they remain set for pipes inside if/while.
3385 * This is used to control execution.
3386 * RES_FOR and RES_IN are NOT sticky (needed to support
3387 * cases where variable or value happens to match a keyword):
3389 #if ENABLE_HUSH_LOOPS
3390 if (ctx->ctx_res_w == RES_FOR
3391 || ctx->ctx_res_w == RES_IN)
3392 ctx->ctx_res_w = RES_NONE;
3394 #if ENABLE_HUSH_CASE
3395 if (ctx->ctx_res_w == RES_MATCH)
3396 ctx->ctx_res_w = RES_CASE_BODY;
3397 if (ctx->ctx_res_w == RES_CASE)
3398 ctx->ctx_res_w = RES_CASE_IN;
3400 ctx->command = NULL; /* trick done_command below */
3401 /* Create the memory for command, roughly:
3402 * ctx->pipe->cmds = new struct command;
3403 * ctx->command = &ctx->pipe->cmds[0];
3406 //debug_print_tree(ctx->list_head, 10);
3408 debug_printf_parse("done_pipe return\n");
3411 static void initialize_context(struct parse_context *ctx)
3413 memset(ctx, 0, sizeof(*ctx));
3414 ctx->pipe = ctx->list_head = new_pipe();
3415 /* Create the memory for command, roughly:
3416 * ctx->pipe->cmds = new struct command;
3417 * ctx->command = &ctx->pipe->cmds[0];
3422 /* If a reserved word is found and processed, parse context is modified
3423 * and 1 is returned.
3426 struct reserved_combo {
3429 unsigned char assignment_flag;
3433 FLAG_END = (1 << RES_NONE ),
3435 FLAG_IF = (1 << RES_IF ),
3436 FLAG_THEN = (1 << RES_THEN ),
3437 FLAG_ELIF = (1 << RES_ELIF ),
3438 FLAG_ELSE = (1 << RES_ELSE ),
3439 FLAG_FI = (1 << RES_FI ),
3441 # if ENABLE_HUSH_LOOPS
3442 FLAG_FOR = (1 << RES_FOR ),
3443 FLAG_WHILE = (1 << RES_WHILE),
3444 FLAG_UNTIL = (1 << RES_UNTIL),
3445 FLAG_DO = (1 << RES_DO ),
3446 FLAG_DONE = (1 << RES_DONE ),
3447 FLAG_IN = (1 << RES_IN ),
3449 # if ENABLE_HUSH_CASE
3450 FLAG_MATCH = (1 << RES_MATCH),
3451 FLAG_ESAC = (1 << RES_ESAC ),
3453 FLAG_START = (1 << RES_XXXX ),
3456 static const struct reserved_combo* match_reserved_word(o_string *word)
3458 /* Mostly a list of accepted follow-up reserved words.
3459 * FLAG_END means we are done with the sequence, and are ready
3460 * to turn the compound list into a command.
3461 * FLAG_START means the word must start a new compound list.
3463 static const struct reserved_combo reserved_list[] = {
3465 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3466 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3467 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3468 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3469 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3470 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3472 # if ENABLE_HUSH_LOOPS
3473 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3474 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3475 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3476 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3477 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3478 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3480 # if ENABLE_HUSH_CASE
3481 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3482 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3485 const struct reserved_combo *r;
3487 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3488 if (strcmp(word->data, r->literal) == 0)
3493 /* Return 0: not a keyword, 1: keyword
3495 static int reserved_word(o_string *word, struct parse_context *ctx)
3497 # if ENABLE_HUSH_CASE
3498 static const struct reserved_combo reserved_match = {
3499 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3502 const struct reserved_combo *r;
3504 if (word->has_quoted_part)
3506 r = match_reserved_word(word);
3510 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3511 # if ENABLE_HUSH_CASE
3512 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3513 /* "case word IN ..." - IN part starts first MATCH part */
3514 r = &reserved_match;
3517 if (r->flag == 0) { /* '!' */
3518 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3519 syntax_error("! ! command");
3520 ctx->ctx_res_w = RES_SNTX;
3522 ctx->ctx_inverted = 1;
3525 if (r->flag & FLAG_START) {
3526 struct parse_context *old;
3528 old = xmalloc(sizeof(*old));
3529 debug_printf_parse("push stack %p\n", old);
3530 *old = *ctx; /* physical copy */
3531 initialize_context(ctx);
3533 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3534 syntax_error_at(word->data);
3535 ctx->ctx_res_w = RES_SNTX;
3538 /* "{...} fi" is ok. "{...} if" is not
3540 * if { echo foo; } then { echo bar; } fi */
3541 if (ctx->command->group)
3542 done_pipe(ctx, PIPE_SEQ);
3545 ctx->ctx_res_w = r->res;
3546 ctx->old_flag = r->flag;
3547 word->o_assignment = r->assignment_flag;
3548 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3550 if (ctx->old_flag & FLAG_END) {
3551 struct parse_context *old;
3553 done_pipe(ctx, PIPE_SEQ);
3554 debug_printf_parse("pop stack %p\n", ctx->stack);
3556 old->command->group = ctx->list_head;
3557 old->command->cmd_type = CMD_NORMAL;
3559 /* At this point, the compound command's string is in
3560 * ctx->as_string... except for the leading keyword!
3561 * Consider this example: "echo a | if true; then echo a; fi"
3562 * ctx->as_string will contain "true; then echo a; fi",
3563 * with "if " remaining in old->as_string!
3567 int len = old->as_string.length;
3568 /* Concatenate halves */
3569 o_addstr(&old->as_string, ctx->as_string.data);
3570 o_free_unsafe(&ctx->as_string);
3571 /* Find where leading keyword starts in first half */
3572 str = old->as_string.data + len;
3573 if (str > old->as_string.data)
3574 str--; /* skip whitespace after keyword */
3575 while (str > old->as_string.data && isalpha(str[-1]))
3577 /* Ugh, we're done with this horrid hack */
3578 old->command->group_as_string = xstrdup(str);
3579 debug_printf_parse("pop, remembering as:'%s'\n",
3580 old->command->group_as_string);
3583 *ctx = *old; /* physical copy */
3588 #endif /* HAS_KEYWORDS */
3590 /* Word is complete, look at it and update parsing context.
3591 * Normal return is 0. Syntax errors return 1.
3592 * Note: on return, word is reset, but not o_free'd!
3594 static int done_word(o_string *word, struct parse_context *ctx)
3596 struct command *command = ctx->command;
3598 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3599 if (word->length == 0 && !word->has_quoted_part) {
3600 debug_printf_parse("done_word return 0: true null, ignored\n");
3604 if (ctx->pending_redirect) {
3605 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3606 * only if run as "bash", not "sh" */
3607 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3609 * ...the word that follows the redirection operator
3610 * shall be subjected to tilde expansion, parameter expansion,
3611 * command substitution, arithmetic expansion, and quote
3612 * removal. Pathname expansion shall not be performed
3613 * on the word by a non-interactive shell; an interactive
3614 * shell may perform it, but shall do so only when
3615 * the expansion would result in one word."
3617 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3618 /* Cater for >\file case:
3619 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3620 * Same with heredocs:
3621 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3623 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3624 unbackslash(ctx->pending_redirect->rd_filename);
3625 /* Is it <<"HEREDOC"? */
3626 if (word->has_quoted_part) {
3627 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3630 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3631 ctx->pending_redirect = NULL;
3634 # if ENABLE_HUSH_CASE
3635 if (ctx->ctx_dsemicolon
3636 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3638 /* already done when ctx_dsemicolon was set to 1: */
3639 /* ctx->ctx_res_w = RES_MATCH; */
3640 ctx->ctx_dsemicolon = 0;
3643 if (!command->argv /* if it's the first word... */
3644 # if ENABLE_HUSH_LOOPS
3645 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3646 && ctx->ctx_res_w != RES_IN
3648 # if ENABLE_HUSH_CASE
3649 && ctx->ctx_res_w != RES_CASE
3652 int reserved = reserved_word(word, ctx);
3653 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3655 o_reset_to_empty_unquoted(word);
3656 debug_printf_parse("done_word return %d\n",
3657 (ctx->ctx_res_w == RES_SNTX));
3658 return (ctx->ctx_res_w == RES_SNTX);
3660 # if ENABLE_HUSH_BASH_COMPAT
3661 if (strcmp(word->data, "[[") == 0) {
3662 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3668 if (command->group) {
3669 /* "{ echo foo; } echo bar" - bad */
3670 syntax_error_at(word->data);
3671 debug_printf_parse("done_word return 1: syntax error, "
3672 "groups and arglists don't mix\n");
3676 /* If this word wasn't an assignment, next ones definitely
3677 * can't be assignments. Even if they look like ones. */
3678 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3679 && word->o_assignment != WORD_IS_KEYWORD
3681 word->o_assignment = NOT_ASSIGNMENT;
3683 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3684 command->assignment_cnt++;
3685 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3687 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3688 word->o_assignment = MAYBE_ASSIGNMENT;
3690 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3692 if (word->has_quoted_part
3693 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3694 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3695 /* (otherwise it's known to be not empty and is already safe) */
3697 /* exclude "$@" - it can expand to no word despite "" */
3698 char *p = word->data;
3699 while (p[0] == SPECIAL_VAR_SYMBOL
3700 && (p[1] & 0x7f) == '@'
3701 && p[2] == SPECIAL_VAR_SYMBOL
3706 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3707 debug_print_strings("word appended to argv", command->argv);
3710 #if ENABLE_HUSH_LOOPS
3711 if (ctx->ctx_res_w == RES_FOR) {
3712 if (word->has_quoted_part
3713 || !is_well_formed_var_name(command->argv[0], '\0')
3715 /* bash says just "not a valid identifier" */
3716 syntax_error("not a valid identifier in for");
3719 /* Force FOR to have just one word (variable name) */
3720 /* NB: basically, this makes hush see "for v in ..."
3721 * syntax as if it is "for v; in ...". FOR and IN become
3722 * two pipe structs in parse tree. */
3723 done_pipe(ctx, PIPE_SEQ);
3726 #if ENABLE_HUSH_CASE
3727 /* Force CASE to have just one word */
3728 if (ctx->ctx_res_w == RES_CASE) {
3729 done_pipe(ctx, PIPE_SEQ);
3733 o_reset_to_empty_unquoted(word);
3735 debug_printf_parse("done_word return 0\n");
3740 /* Peek ahead in the input to find out if we have a "&n" construct,
3741 * as in "2>&1", that represents duplicating a file descriptor.
3743 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3744 * REDIRFD_SYNTAX_ERR if syntax error,
3745 * REDIRFD_TO_FILE if no & was seen,
3746 * or the number found.
3749 #define parse_redir_right_fd(as_string, input) \
3750 parse_redir_right_fd(input)
3752 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3758 return REDIRFD_TO_FILE;
3760 ch = i_getch(input); /* get the & */
3761 nommu_addchr(as_string, ch);
3764 ch = i_getch(input);
3765 nommu_addchr(as_string, ch);
3766 return REDIRFD_CLOSE;
3770 while (ch != EOF && isdigit(ch)) {
3771 d = d*10 + (ch-'0');
3773 ch = i_getch(input);
3774 nommu_addchr(as_string, ch);
3779 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3781 bb_error_msg("ambiguous redirect");
3782 return REDIRFD_SYNTAX_ERR;
3785 /* Return code is 0 normal, 1 if a syntax error is detected
3787 static int parse_redirect(struct parse_context *ctx,
3790 struct in_str *input)
3792 struct command *command = ctx->command;
3793 struct redir_struct *redir;
3794 struct redir_struct **redirp;
3797 dup_num = REDIRFD_TO_FILE;
3798 if (style != REDIRECT_HEREDOC) {
3799 /* Check for a '>&1' type redirect */
3800 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3801 if (dup_num == REDIRFD_SYNTAX_ERR)
3804 int ch = i_peek(input);
3805 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3806 if (dup_num) { /* <<-... */
3807 ch = i_getch(input);
3808 nommu_addchr(&ctx->as_string, ch);
3813 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3814 int ch = i_peek(input);
3816 /* >|FILE redirect ("clobbering" >).
3817 * Since we do not support "set -o noclobber" yet,
3818 * >| and > are the same for now. Just eat |.
3820 ch = i_getch(input);
3821 nommu_addchr(&ctx->as_string, ch);
3825 /* Create a new redir_struct and append it to the linked list */
3826 redirp = &command->redirects;
3827 while ((redir = *redirp) != NULL) {
3828 redirp = &(redir->next);
3830 *redirp = redir = xzalloc(sizeof(*redir));
3831 /* redir->next = NULL; */
3832 /* redir->rd_filename = NULL; */
3833 redir->rd_type = style;
3834 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3836 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3837 redir_table[style].descrip);
3839 redir->rd_dup = dup_num;
3840 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3841 /* Erik had a check here that the file descriptor in question
3842 * is legit; I postpone that to "run time"
3843 * A "-" representation of "close me" shows up as a -3 here */
3844 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3845 redir->rd_fd, redir->rd_dup);
3847 #if 0 /* Instead we emit error message at run time */
3848 if (ctx->pending_redirect) {
3849 /* For example, "cmd > <file" */
3850 die_if_script("syntax error: %s", "invalid redirect");
3853 /* Set ctx->pending_redirect, so we know what to do at the
3854 * end of the next parsed word. */
3855 ctx->pending_redirect = redir;
3860 /* If a redirect is immediately preceded by a number, that number is
3861 * supposed to tell which file descriptor to redirect. This routine
3862 * looks for such preceding numbers. In an ideal world this routine
3863 * needs to handle all the following classes of redirects...
3864 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3865 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3866 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3867 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3869 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3871 * ... If n is quoted, the number shall not be recognized as part of
3872 * the redirection expression. For example:
3874 * writes the character 2 into file a"
3875 * We are getting it right by setting ->has_quoted_part on any \<char>
3877 * A -1 return means no valid number was found,
3878 * the caller should use the appropriate default for this redirection.
3880 static int redirect_opt_num(o_string *o)
3884 if (o->data == NULL)
3886 num = bb_strtou(o->data, NULL, 10);
3887 if (errno || num < 0)
3889 o_reset_to_empty_unquoted(o);
3894 #define fetch_till_str(as_string, input, word, skip_tabs) \
3895 fetch_till_str(input, word, skip_tabs)
3897 static char *fetch_till_str(o_string *as_string,
3898 struct in_str *input,
3902 o_string heredoc = NULL_O_STRING;
3904 int prev = 0; /* not \ */
3910 ch = i_getch(input);
3912 nommu_addchr(as_string, ch);
3913 if ((ch == '\n' || ch == EOF)
3914 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3916 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3917 heredoc.data[past_EOL] = '\0';
3918 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3919 return heredoc.data;
3921 while (ch == '\n') {
3922 o_addchr(&heredoc, ch);
3925 past_EOL = heredoc.length;
3927 ch = i_getch(input);
3929 nommu_addchr(as_string, ch);
3930 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3934 o_free_unsafe(&heredoc);
3937 o_addchr(&heredoc, ch);
3938 nommu_addchr(as_string, ch);
3939 if (prev == '\\' && ch == '\\')
3940 /* Correctly handle foo\\<eol> (not a line cont.) */
3941 prev = 0; /* not \ */
3947 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3948 * and load them all. There should be exactly heredoc_cnt of them.
3950 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3952 struct pipe *pi = ctx->list_head;
3954 while (pi && heredoc_cnt) {
3956 struct command *cmd = pi->cmds;
3958 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3960 cmd->argv ? cmd->argv[0] : "NONE");
3961 for (i = 0; i < pi->num_cmds; i++) {
3962 struct redir_struct *redir = cmd->redirects;
3964 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3965 i, cmd->argv ? cmd->argv[0] : "NONE");
3967 if (redir->rd_type == REDIRECT_HEREDOC) {
3970 redir->rd_type = REDIRECT_HEREDOC2;
3971 /* redir->rd_dup is (ab)used to indicate <<- */
3972 p = fetch_till_str(&ctx->as_string, input,
3973 redir->rd_filename, redir->rd_dup);
3975 syntax_error("unexpected EOF in here document");
3978 free(redir->rd_filename);
3979 redir->rd_filename = p;
3982 redir = redir->next;
3989 /* Should be 0. If it isn't, it's a parse error */
3991 bb_error_msg_and_die("heredoc BUG 2");
3997 static int run_list(struct pipe *pi);
3999 #define parse_stream(pstring, input, end_trigger) \
4000 parse_stream(input, end_trigger)
4002 static struct pipe *parse_stream(char **pstring,
4003 struct in_str *input,
4007 #if !ENABLE_HUSH_FUNCTIONS
4008 #define parse_group(dest, ctx, input, ch) \
4009 parse_group(ctx, input, ch)
4011 static int parse_group(o_string *dest, struct parse_context *ctx,
4012 struct in_str *input, int ch)
4014 /* dest contains characters seen prior to ( or {.
4015 * Typically it's empty, but for function defs,
4016 * it contains function name (without '()'). */
4017 struct pipe *pipe_list;
4019 struct command *command = ctx->command;
4021 debug_printf_parse("parse_group entered\n");
4022 #if ENABLE_HUSH_FUNCTIONS
4023 if (ch == '(' && !dest->has_quoted_part) {
4025 if (done_word(dest, ctx))
4028 goto skip; /* (... */
4029 if (command->argv[1]) { /* word word ... (... */
4030 syntax_error_unexpected_ch('(');
4033 /* it is "word(..." or "word (..." */
4035 ch = i_getch(input);
4036 while (ch == ' ' || ch == '\t');
4038 syntax_error_unexpected_ch(ch);
4041 nommu_addchr(&ctx->as_string, ch);
4043 ch = i_getch(input);
4044 while (ch == ' ' || ch == '\t' || ch == '\n');
4046 syntax_error_unexpected_ch(ch);
4049 nommu_addchr(&ctx->as_string, ch);
4050 command->cmd_type = CMD_FUNCDEF;
4055 #if 0 /* Prevented by caller */
4056 if (command->argv /* word [word]{... */
4057 || dest->length /* word{... */
4058 || dest->has_quoted_part /* ""{... */
4061 debug_printf_parse("parse_group return 1: "
4062 "syntax error, groups and arglists don't mix\n");
4067 #if ENABLE_HUSH_FUNCTIONS
4073 command->cmd_type = CMD_SUBSHELL;
4075 /* bash does not allow "{echo...", requires whitespace */
4077 if (ch != ' ' && ch != '\t' && ch != '\n'
4078 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4080 syntax_error_unexpected_ch(ch);
4084 ch = i_getch(input);
4085 nommu_addchr(&ctx->as_string, ch);
4091 # define as_string NULL
4093 char *as_string = NULL;
4095 pipe_list = parse_stream(&as_string, input, endch);
4098 o_addstr(&ctx->as_string, as_string);
4100 /* empty ()/{} or parse error? */
4101 if (!pipe_list || pipe_list == ERR_PTR) {
4102 /* parse_stream already emitted error msg */
4105 debug_printf_parse("parse_group return 1: "
4106 "parse_stream returned %p\n", pipe_list);
4109 command->group = pipe_list;
4111 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4112 command->group_as_string = as_string;
4113 debug_printf_parse("end of group, remembering as:'%s'\n",
4114 command->group_as_string);
4118 debug_printf_parse("parse_group return 0\n");
4120 /* command remains "open", available for possible redirects */
4123 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4128 ch = i_getch(input);
4131 ch2 = i_peek(input);
4134 /* backslash+newline, skip it */
4139 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4147 ch2 = i_peek2(input);
4150 /* backslash+newline, skip it */
4156 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4157 /* Subroutines for copying $(...) and `...` things */
4158 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4160 static int add_till_single_quote(o_string *dest, struct in_str *input)
4163 int ch = i_getch(input);
4165 syntax_error_unterm_ch('\'');
4173 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4174 static int add_till_double_quote(o_string *dest, struct in_str *input)
4177 int ch = i_getch(input);
4179 syntax_error_unterm_ch('"');
4184 if (ch == '\\') { /* \x. Copy both chars. */
4186 ch = i_getch(input);
4190 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4195 //if (ch == '$') ...
4198 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4200 * "Within the backquoted style of command substitution, backslash
4201 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4202 * The search for the matching backquote shall be satisfied by the first
4203 * backquote found without a preceding backslash; during this search,
4204 * if a non-escaped backquote is encountered within a shell comment,
4205 * a here-document, an embedded command substitution of the $(command)
4206 * form, or a quoted string, undefined results occur. A single-quoted
4207 * or double-quoted string that begins, but does not end, within the
4208 * "`...`" sequence produces undefined results."
4210 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4212 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4215 int ch = i_getch(input);
4219 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4220 ch = i_getch(input);
4224 && (!in_dquote || ch != '"')
4226 o_addchr(dest, '\\');
4230 syntax_error_unterm_ch('`');
4236 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4237 * quoting and nested ()s.
4238 * "With the $(command) style of command substitution, all characters
4239 * following the open parenthesis to the matching closing parenthesis
4240 * constitute the command. Any valid shell script can be used for command,
4241 * except a script consisting solely of redirections which produces
4242 * unspecified results."
4244 * echo $(echo '(TEST)' BEST) (TEST) BEST
4245 * echo $(echo 'TEST)' BEST) TEST) BEST
4246 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4248 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4249 * can contain arbitrary constructs, just like $(cmd).
4250 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4251 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4253 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4254 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4257 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4258 # if ENABLE_HUSH_BASH_COMPAT
4259 char end_char2 = end_ch >> 8;
4261 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4264 ch = i_getch(input);
4266 syntax_error_unterm_ch(end_ch);
4269 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4272 /* we look for closing )) of $((EXPR)) */
4273 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4274 i_getch(input); /* eat second ')' */
4279 if (ch == '(' || ch == '{') {
4280 ch = (ch == '(' ? ')' : '}');
4281 if (!add_till_closing_bracket(dest, input, ch))
4287 if (!add_till_single_quote(dest, input))
4293 if (!add_till_double_quote(dest, input))
4299 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4305 /* \x. Copy verbatim. Important for \(, \) */
4306 ch = i_getch(input);
4308 syntax_error_unterm_ch(')');
4313 /* "backslash+newline", ignore both */
4314 o_delchr(dest); /* undo insertion of '\' */
4324 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4326 /* Return code: 0 for OK, 1 for syntax error */
4328 #define parse_dollar(as_string, dest, input, quote_mask) \
4329 parse_dollar(dest, input, quote_mask)
4330 #define as_string NULL
4332 static int parse_dollar(o_string *as_string,
4334 struct in_str *input, unsigned char quote_mask)
4336 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4338 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4340 ch = i_getch(input);
4341 nommu_addchr(as_string, ch);
4343 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4345 debug_printf_parse(": '%c'\n", ch);
4346 o_addchr(dest, ch | quote_mask);
4348 ch = i_peek_and_eat_bkslash_nl(input);
4349 if (!isalnum(ch) && ch != '_') {
4350 /* End of variable name reached */
4353 ch = i_getch(input);
4354 nommu_addchr(as_string, ch);
4356 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4357 } else if (isdigit(ch)) {
4359 ch = i_getch(input);
4360 nommu_addchr(as_string, ch);
4361 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4362 debug_printf_parse(": '%c'\n", ch);
4363 o_addchr(dest, ch | quote_mask);
4364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4365 } else switch (ch) {
4367 case '!': /* last bg pid */
4368 case '?': /* last exit code */
4369 case '#': /* number of args */
4370 case '*': /* args */
4371 case '@': /* args */
4372 goto make_one_char_var;
4374 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4376 ch = i_getch(input); /* eat '{' */
4377 nommu_addchr(as_string, ch);
4379 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4380 /* It should be ${?}, or ${#var},
4381 * or even ${?+subst} - operator acting on a special variable,
4382 * or the beginning of variable name.
4385 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4388 syntax_error_unterm_str("${name}");
4389 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4392 nommu_addchr(as_string, ch);
4395 /* It's possible to just call add_till_closing_bracket() at this point.
4396 * However, this regresses some of our testsuite cases
4397 * which check invalid constructs like ${%}.
4398 * Oh well... let's check that the var name part is fine... */
4404 debug_printf_parse(": '%c'\n", ch);
4406 ch = i_getch(input);
4407 nommu_addchr(as_string, ch);
4411 if (!isalnum(ch) && ch != '_') {
4413 unsigned char last_ch;
4414 /* handle parameter expansions
4415 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4417 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4418 goto bad_dollar_syntax;
4420 /* Eat everything until closing '}' (or ':') */
4422 if (ENABLE_HUSH_BASH_COMPAT
4424 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4426 /* It's ${var:N[:M]} thing */
4427 end_ch = '}' * 0x100 + ':';
4429 if (ENABLE_HUSH_BASH_COMPAT
4432 /* It's ${var/[/]pattern[/repl]} thing */
4433 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4435 nommu_addchr(as_string, '/');
4438 end_ch = '}' * 0x100 + '/';
4444 #if ENABLE_HUSH_DOLLAR_OPS
4445 last_ch = add_till_closing_bracket(dest, input, end_ch);
4446 if (last_ch == 0) /* error? */
4449 #error Simple code to only allow ${var} is not implemented
4452 o_addstr(as_string, dest->data + pos);
4453 o_addchr(as_string, last_ch);
4456 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4457 /* close the first block: */
4458 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4459 /* while parsing N from ${var:N[:M]}
4460 * or pattern from ${var/[/]pattern[/repl]} */
4461 if ((end_ch & 0xff) == last_ch) {
4462 /* got ':' or '/'- parse the rest */
4467 if (end_ch == '}' * 0x100 + ':') {
4468 /* it's ${var:N} - emulate :999999999 */
4469 o_addstr(dest, "999999999");
4470 } /* else: it's ${var/[/]pattern} */
4475 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4478 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4482 ch = i_getch(input);
4483 nommu_addchr(as_string, ch);
4484 # if ENABLE_FEATURE_SH_MATH
4485 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4486 ch = i_getch(input);
4487 nommu_addchr(as_string, ch);
4488 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4489 o_addchr(dest, /*quote_mask |*/ '+');
4492 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4493 return 0; /* error */
4495 o_addstr(as_string, dest->data + pos);
4496 o_addchr(as_string, ')');
4497 o_addchr(as_string, ')');
4499 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4503 # if ENABLE_HUSH_TICK
4504 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4505 o_addchr(dest, quote_mask | '`');
4508 if (!add_till_closing_bracket(dest, input, ')'))
4509 return 0; /* error */
4511 o_addstr(as_string, dest->data + pos);
4512 o_addchr(as_string, ')');
4514 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4520 ch = i_getch(input);
4521 nommu_addchr(as_string, ch);
4522 ch = i_peek_and_eat_bkslash_nl(input);
4523 if (isalnum(ch)) { /* it's $_name or $_123 */
4528 /* TODO: $_ and $-: */
4529 /* $_ Shell or shell script name; or last argument of last command
4530 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4531 * but in command's env, set to full pathname used to invoke it */
4532 /* $- Option flags set by set builtin or shell options (-i etc) */
4534 o_addQchr(dest, '$');
4536 debug_printf_parse("parse_dollar return 1 (ok)\n");
4542 # if ENABLE_HUSH_BASH_COMPAT
4543 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4544 encode_string(dest, input, dquote_end, process_bkslash)
4546 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4547 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4548 encode_string(dest, input, dquote_end)
4550 #define as_string NULL
4554 # if ENABLE_HUSH_BASH_COMPAT
4555 /* all parameters are needed, no macro tricks */
4557 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4558 encode_string(as_string, dest, input, dquote_end)
4561 static int encode_string(o_string *as_string,
4563 struct in_str *input,
4565 int process_bkslash)
4567 #if !ENABLE_HUSH_BASH_COMPAT
4568 const int process_bkslash = 1;
4574 ch = i_getch(input);
4576 nommu_addchr(as_string, ch);
4577 if (ch == dquote_end) { /* may be only '"' or EOF */
4578 debug_printf_parse("encode_string return 1 (ok)\n");
4581 /* note: can't move it above ch == dquote_end check! */
4583 syntax_error_unterm_ch('"');
4584 return 0; /* error */
4588 next = i_peek(input);
4590 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4591 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4592 if (process_bkslash && ch == '\\') {
4594 syntax_error("\\<eof>");
4598 * "The backslash retains its special meaning [in "..."]
4599 * only when followed by one of the following characters:
4600 * $, `, ", \, or <newline>. A double quote may be quoted
4601 * within double quotes by preceding it with a backslash."
4602 * NB: in (unquoted) heredoc, above does not apply to ",
4603 * therefore we check for it by "next == dquote_end" cond.
4605 if (next == dquote_end || strchr("$`\\\n", next)) {
4606 ch = i_getch(input); /* eat next */
4608 goto again; /* skip \<newline> */
4609 } /* else: ch remains == '\\', and we double it below: */
4610 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4611 nommu_addchr(as_string, ch);
4615 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4616 debug_printf_parse("encode_string return 0: "
4617 "parse_dollar returned 0 (error)\n");
4622 #if ENABLE_HUSH_TICK
4624 //unsigned pos = dest->length;
4625 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4626 o_addchr(dest, 0x80 | '`');
4627 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4628 return 0; /* error */
4629 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4630 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4634 o_addQchr(dest, ch);
4640 * Scan input until EOF or end_trigger char.
4641 * Return a list of pipes to execute, or NULL on EOF
4642 * or if end_trigger character is met.
4643 * On syntax error, exit if shell is not interactive,
4644 * reset parsing machinery and start parsing anew,
4645 * or return ERR_PTR.
4647 static struct pipe *parse_stream(char **pstring,
4648 struct in_str *input,
4651 struct parse_context ctx;
4652 o_string dest = NULL_O_STRING;
4655 /* Single-quote triggers a bypass of the main loop until its mate is
4656 * found. When recursing, quote state is passed in via dest->o_expflags.
4658 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4659 end_trigger ? end_trigger : 'X');
4662 /* If very first arg is "" or '', dest.data may end up NULL.
4663 * Preventing this: */
4664 o_addchr(&dest, '\0');
4667 /* We used to separate words on $IFS here. This was wrong.
4668 * $IFS is used only for word splitting when $var is expanded,
4669 * here we should use blank chars as separators, not $IFS
4672 if (MAYBE_ASSIGNMENT != 0)
4673 dest.o_assignment = MAYBE_ASSIGNMENT;
4674 initialize_context(&ctx);
4677 const char *is_blank;
4678 const char *is_special;
4682 redir_type redir_style;
4684 ch = i_getch(input);
4685 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4686 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4691 syntax_error_unterm_str("here document");
4694 if (end_trigger == ')') {
4695 syntax_error_unterm_ch('(');
4698 if (end_trigger == '}') {
4699 syntax_error_unterm_ch('{');
4703 if (done_word(&dest, &ctx)) {
4707 done_pipe(&ctx, PIPE_SEQ);
4709 /* If we got nothing... */
4710 /* (this makes bare "&" cmd a no-op.
4711 * bash says: "syntax error near unexpected token '&'") */
4712 if (pi->num_cmds == 0
4713 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4719 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4721 *pstring = ctx.as_string.data;
4723 o_free_unsafe(&ctx.as_string);
4726 debug_printf_parse("parse_stream return %p\n", pi);
4729 nommu_addchr(&ctx.as_string, ch);
4733 next = i_peek(input);
4735 is_special = "{}<>;&|()#'" /* special outside of "str" */
4736 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4737 /* Are { and } special here? */
4738 if (ctx.command->argv /* word [word]{... - non-special */
4739 || dest.length /* word{... - non-special */
4740 || dest.has_quoted_part /* ""{... - non-special */
4741 || (next != ';' /* }; - special */
4742 && next != ')' /* }) - special */
4743 && next != '(' /* {( - special */
4744 && next != '&' /* }& and }&& ... - special */
4745 && next != '|' /* }|| ... - special */
4746 && !strchr(defifs, next) /* {word - non-special */
4749 /* They are not special, skip "{}" */
4752 is_special = strchr(is_special, ch);
4753 is_blank = strchr(defifs, ch);
4755 if (!is_special && !is_blank) { /* ordinary char */
4757 o_addQchr(&dest, ch);
4758 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4759 || dest.o_assignment == WORD_IS_KEYWORD)
4761 && is_well_formed_var_name(dest.data, '=')
4763 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4764 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4770 if (done_word(&dest, &ctx)) {
4774 /* Is this a case when newline is simply ignored?
4776 * "cmd | <newline> cmd ..."
4777 * "case ... in <newline> word) ..."
4779 if (IS_NULL_CMD(ctx.command)
4780 && dest.length == 0 && !dest.has_quoted_part
4782 /* This newline can be ignored. But...
4783 * Without check #1, interactive shell
4784 * ignores even bare <newline>,
4785 * and shows the continuation prompt:
4786 * ps1_prompt$ <enter>
4787 * ps2> _ <=== wrong, should be ps1
4788 * Without check #2, "cmd & <newline>"
4789 * is similarly mistreated.
4790 * (BTW, this makes "cmd & cmd"
4791 * and "cmd && cmd" non-orthogonal.
4792 * Really, ask yourself, why
4793 * "cmd && <newline>" doesn't start
4794 * cmd but waits for more input?
4797 struct pipe *pi = ctx.list_head;
4798 if (pi->num_cmds != 0 /* check #1 */
4799 && pi->followup != PIPE_BG /* check #2 */
4804 /* Treat newline as a command separator. */
4805 done_pipe(&ctx, PIPE_SEQ);
4806 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4808 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4813 dest.o_assignment = MAYBE_ASSIGNMENT;
4814 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4816 /* note: if (is_blank) continue;
4817 * will still trigger for us */
4821 /* "cmd}" or "cmd }..." without semicolon or &:
4822 * } is an ordinary char in this case, even inside { cmd; }
4823 * Pathological example: { ""}; } should exec "}" cmd
4826 if (dest.length != 0 /* word} */
4827 || dest.has_quoted_part /* ""} */
4831 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4832 /* Generally, there should be semicolon: "cmd; }"
4833 * However, bash allows to omit it if "cmd" is
4834 * a group. Examples:
4837 * { echo 0 >&2 | { echo 1; } }
4838 * { while false; do :; done }
4839 * { case a in b) ;; esac }
4841 if (ctx.command->group)
4845 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4846 /* Can't be an end of {cmd}, skip the check */
4847 goto skip_end_trigger;
4848 /* else: } does terminate a group */
4851 if (end_trigger && end_trigger == ch
4852 && (ch != ';' || heredoc_cnt == 0)
4853 #if ENABLE_HUSH_CASE
4855 || ctx.ctx_res_w != RES_MATCH
4856 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4861 /* This is technically valid:
4862 * { cat <<HERE; }; echo Ok
4866 * but we don't support this.
4867 * We require heredoc to be in enclosing {}/(),
4870 syntax_error_unterm_str("here document");
4873 if (done_word(&dest, &ctx)) {
4876 done_pipe(&ctx, PIPE_SEQ);
4877 dest.o_assignment = MAYBE_ASSIGNMENT;
4878 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4879 /* Do we sit outside of any if's, loops or case's? */
4881 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4885 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4887 *pstring = ctx.as_string.data;
4889 o_free_unsafe(&ctx.as_string);
4892 debug_printf_parse("parse_stream return %p: "
4893 "end_trigger char found\n",
4895 return ctx.list_head;
4902 /* Catch <, > before deciding whether this word is
4903 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4906 redir_fd = redirect_opt_num(&dest);
4907 if (done_word(&dest, &ctx)) {
4910 redir_style = REDIRECT_OVERWRITE;
4912 redir_style = REDIRECT_APPEND;
4913 ch = i_getch(input);
4914 nommu_addchr(&ctx.as_string, ch);
4917 else if (next == '(') {
4918 syntax_error(">(process) not supported");
4922 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4924 continue; /* back to top of while (1) */
4926 redir_fd = redirect_opt_num(&dest);
4927 if (done_word(&dest, &ctx)) {
4930 redir_style = REDIRECT_INPUT;
4932 redir_style = REDIRECT_HEREDOC;
4934 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4935 ch = i_getch(input);
4936 nommu_addchr(&ctx.as_string, ch);
4937 } else if (next == '>') {
4938 redir_style = REDIRECT_IO;
4939 ch = i_getch(input);
4940 nommu_addchr(&ctx.as_string, ch);
4943 else if (next == '(') {
4944 syntax_error("<(process) not supported");
4948 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4950 continue; /* back to top of while (1) */
4952 if (dest.length == 0 && !dest.has_quoted_part) {
4953 /* skip "#comment" */
4956 if (ch == EOF || ch == '\n')
4959 /* note: we do not add it to &ctx.as_string */
4961 nommu_addchr(&ctx.as_string, '\n');
4962 continue; /* back to top of while (1) */
4967 /* It's "\<newline>" */
4969 /* Remove trailing '\' from ctx.as_string */
4970 ctx.as_string.data[--ctx.as_string.length] = '\0';
4972 ch = i_getch(input); /* eat it */
4973 continue; /* back to top of while (1) */
4978 if (dest.o_assignment == MAYBE_ASSIGNMENT
4979 /* check that we are not in word in "a=1 2>word b=1": */
4980 && !ctx.pending_redirect
4982 /* ch is a special char and thus this word
4983 * cannot be an assignment */
4984 dest.o_assignment = NOT_ASSIGNMENT;
4985 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4988 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4991 case '#': /* non-comment #: "echo a#b" etc */
4992 o_addQchr(&dest, ch);
4996 syntax_error("\\<eof>");
4999 ch = i_getch(input);
5000 /* note: ch != '\n' (that case does not reach this place) */
5001 o_addchr(&dest, '\\');
5002 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5003 o_addchr(&dest, ch);
5004 nommu_addchr(&ctx.as_string, ch);
5005 /* Example: echo Hello \2>file
5006 * we need to know that word 2 is quoted */
5007 dest.has_quoted_part = 1;
5010 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5011 debug_printf_parse("parse_stream parse error: "
5012 "parse_dollar returned 0 (error)\n");
5017 dest.has_quoted_part = 1;
5018 if (next == '\'' && !ctx.pending_redirect) {
5019 insert_empty_quoted_str_marker:
5020 nommu_addchr(&ctx.as_string, next);
5021 i_getch(input); /* eat second ' */
5022 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5023 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5026 ch = i_getch(input);
5028 syntax_error_unterm_ch('\'');
5031 nommu_addchr(&ctx.as_string, ch);
5034 o_addqchr(&dest, ch);
5039 dest.has_quoted_part = 1;
5040 if (next == '"' && !ctx.pending_redirect)
5041 goto insert_empty_quoted_str_marker;
5042 if (dest.o_assignment == NOT_ASSIGNMENT)
5043 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5044 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5046 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5048 #if ENABLE_HUSH_TICK
5050 USE_FOR_NOMMU(unsigned pos;)
5052 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5053 o_addchr(&dest, '`');
5054 USE_FOR_NOMMU(pos = dest.length;)
5055 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5058 o_addstr(&ctx.as_string, dest.data + pos);
5059 o_addchr(&ctx.as_string, '`');
5061 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5062 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5067 #if ENABLE_HUSH_CASE
5070 if (done_word(&dest, &ctx)) {
5073 done_pipe(&ctx, PIPE_SEQ);
5074 #if ENABLE_HUSH_CASE
5075 /* Eat multiple semicolons, detect
5076 * whether it means something special */
5081 ch = i_getch(input);
5082 nommu_addchr(&ctx.as_string, ch);
5083 if (ctx.ctx_res_w == RES_CASE_BODY) {
5084 ctx.ctx_dsemicolon = 1;
5085 ctx.ctx_res_w = RES_MATCH;
5091 /* We just finished a cmd. New one may start
5092 * with an assignment */
5093 dest.o_assignment = MAYBE_ASSIGNMENT;
5094 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5097 if (done_word(&dest, &ctx)) {
5101 ch = i_getch(input);
5102 nommu_addchr(&ctx.as_string, ch);
5103 done_pipe(&ctx, PIPE_AND);
5105 done_pipe(&ctx, PIPE_BG);
5109 if (done_word(&dest, &ctx)) {
5112 #if ENABLE_HUSH_CASE
5113 if (ctx.ctx_res_w == RES_MATCH)
5114 break; /* we are in case's "word | word)" */
5116 if (next == '|') { /* || */
5117 ch = i_getch(input);
5118 nommu_addchr(&ctx.as_string, ch);
5119 done_pipe(&ctx, PIPE_OR);
5121 /* we could pick up a file descriptor choice here
5122 * with redirect_opt_num(), but bash doesn't do it.
5123 * "echo foo 2| cat" yields "foo 2". */
5128 #if ENABLE_HUSH_CASE
5129 /* "case... in [(]word)..." - skip '(' */
5130 if (ctx.ctx_res_w == RES_MATCH
5131 && ctx.command->argv == NULL /* not (word|(... */
5132 && dest.length == 0 /* not word(... */
5133 && dest.has_quoted_part == 0 /* not ""(... */
5139 if (parse_group(&dest, &ctx, input, ch) != 0) {
5144 #if ENABLE_HUSH_CASE
5145 if (ctx.ctx_res_w == RES_MATCH)
5149 /* proper use of this character is caught by end_trigger:
5150 * if we see {, we call parse_group(..., end_trigger='}')
5151 * and it will match } earlier (not here). */
5152 syntax_error_unexpected_ch(ch);
5153 G.last_exitcode = 2;
5157 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5162 G.last_exitcode = 1;
5165 struct parse_context *pctx;
5166 IF_HAS_KEYWORDS(struct parse_context *p2;)
5168 /* Clean up allocated tree.
5169 * Sample for finding leaks on syntax error recovery path.
5170 * Run it from interactive shell, watch pmap `pidof hush`.
5171 * while if false; then false; fi; do break; fi
5172 * Samples to catch leaks at execution:
5173 * while if (true | { true;}); then echo ok; fi; do break; done
5174 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5178 /* Update pipe/command counts,
5179 * otherwise freeing may miss some */
5180 done_pipe(pctx, PIPE_SEQ);
5181 debug_printf_clean("freeing list %p from ctx %p\n",
5182 pctx->list_head, pctx);
5183 debug_print_tree(pctx->list_head, 0);
5184 free_pipe_list(pctx->list_head);
5185 debug_printf_clean("freed list %p\n", pctx->list_head);
5187 o_free_unsafe(&pctx->as_string);
5189 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5193 IF_HAS_KEYWORDS(pctx = p2;)
5194 } while (HAS_KEYWORDS && pctx);
5207 /*** Execution routines ***/
5209 /* Expansion can recurse, need forward decls: */
5210 #if !ENABLE_HUSH_BASH_COMPAT
5211 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5212 #define expand_string_to_string(str, do_unbackslash) \
5213 expand_string_to_string(str)
5215 static char *expand_string_to_string(const char *str, int do_unbackslash);
5216 #if ENABLE_HUSH_TICK
5217 static int process_command_subs(o_string *dest, const char *s);
5220 /* expand_strvec_to_strvec() takes a list of strings, expands
5221 * all variable references within and returns a pointer to
5222 * a list of expanded strings, possibly with larger number
5223 * of strings. (Think VAR="a b"; echo $VAR).
5224 * This new list is allocated as a single malloc block.
5225 * NULL-terminated list of char* pointers is at the beginning of it,
5226 * followed by strings themselves.
5227 * Caller can deallocate entire list by single free(list). */
5229 /* A horde of its helpers come first: */
5231 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5233 while (--len >= 0) {
5236 #if ENABLE_HUSH_BRACE_EXPANSION
5237 if (c == '{' || c == '}') {
5238 /* { -> \{, } -> \} */
5240 /* And now we want to add { or } and continue:
5243 * luckily, just falling throught achieves this.
5249 /* \z -> \\\z; \<eol> -> \\<eol> */
5254 o_addchr(o, *str++);
5260 /* Store given string, finalizing the word and starting new one whenever
5261 * we encounter IFS char(s). This is used for expanding variable values.
5262 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5263 * Return in *ended_with_ifs:
5264 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5266 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5268 int last_is_ifs = 0;
5273 if (!*str) /* EOL - do not finalize word */
5275 word_len = strcspn(str, G.ifs);
5277 /* We have WORD_LEN leading non-IFS chars */
5278 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5279 o_addblock(output, str, word_len);
5281 /* Protect backslashes against globbing up :)
5282 * Example: "v='\*'; echo b$v" prints "b\*"
5283 * (and does not try to glob on "*")
5285 o_addblock_duplicate_backslash(output, str, word_len);
5286 /*/ Why can't we do it easier? */
5287 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5288 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5292 if (!*str) /* EOL - do not finalize word */
5296 /* We know str here points to at least one IFS char */
5298 str += strspn(str, G.ifs); /* skip IFS chars */
5299 if (!*str) /* EOL - do not finalize word */
5302 /* Start new word... but not always! */
5303 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5304 if (output->has_quoted_part
5305 /* Case "v=' a'; echo $v":
5306 * here nothing precedes the space in $v expansion,
5307 * therefore we should not finish the word
5308 * (IOW: if there *is* word to finalize, only then do it):
5310 || (n > 0 && output->data[output->length - 1])
5312 o_addchr(output, '\0');
5313 debug_print_list("expand_on_ifs", output, n);
5314 n = o_save_ptr(output, n);
5319 *ended_with_ifs = last_is_ifs;
5320 debug_print_list("expand_on_ifs[1]", output, n);
5324 /* Helper to expand $((...)) and heredoc body. These act as if
5325 * they are in double quotes, with the exception that they are not :).
5326 * Just the rules are similar: "expand only $var and `cmd`"
5328 * Returns malloced string.
5329 * As an optimization, we return NULL if expansion is not needed.
5331 #if !ENABLE_HUSH_BASH_COMPAT
5332 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5333 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5334 encode_then_expand_string(str)
5336 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5339 struct in_str input;
5340 o_string dest = NULL_O_STRING;
5342 if (!strchr(str, '$')
5343 && !strchr(str, '\\')
5344 #if ENABLE_HUSH_TICK
5345 && !strchr(str, '`')
5351 /* We need to expand. Example:
5352 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5354 setup_string_in_str(&input, str);
5355 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5356 //TODO: error check (encode_string returns 0 on error)?
5357 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5358 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5359 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5360 o_free_unsafe(&dest);
5364 #if ENABLE_FEATURE_SH_MATH
5365 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5367 arith_state_t math_state;
5371 math_state.lookupvar = get_local_var_value;
5372 math_state.setvar = set_local_var_from_halves;
5373 //math_state.endofname = endofname;
5374 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5375 res = arith(&math_state, exp_str ? exp_str : arg);
5378 *errmsg_p = math_state.errmsg;
5379 if (math_state.errmsg)
5380 die_if_script(math_state.errmsg);
5385 #if ENABLE_HUSH_BASH_COMPAT
5386 /* ${var/[/]pattern[/repl]} helpers */
5387 static char *strstr_pattern(char *val, const char *pattern, int *size)
5390 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5391 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5398 /* Optimization: if "*pat" did not match the start of "string",
5399 * we know that "tring", "ring" etc will not match too:
5401 if (pattern[0] == '*')
5406 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5408 char *result = NULL;
5409 unsigned res_len = 0;
5410 unsigned repl_len = strlen(repl);
5414 char *s = strstr_pattern(val, pattern, &size);
5418 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5419 memcpy(result + res_len, val, s - val);
5421 strcpy(result + res_len, repl);
5422 res_len += repl_len;
5423 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5429 if (val[0] && result) {
5430 result = xrealloc(result, res_len + strlen(val) + 1);
5431 strcpy(result + res_len, val);
5432 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5434 debug_printf_varexp("result:'%s'\n", result);
5440 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5442 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5444 const char *val = NULL;
5445 char *to_be_freed = NULL;
5450 char exp_save = exp_save; /* for compiler */
5451 char *exp_saveptr; /* points to expansion operator */
5452 char *exp_word = exp_word; /* for compiler */
5455 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5457 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5459 first_char = arg[0] = arg0 & 0x7f;
5462 if (first_char == '#' /* ${#... */
5463 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5465 /* It must be length operator: ${#var} */
5469 /* Maybe handle parameter expansion */
5470 if (exp_saveptr /* if 2nd char is one of expansion operators */
5471 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5473 /* ${?:0}, ${#[:]%0} etc */
5474 exp_saveptr = var + 1;
5476 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5477 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5479 exp_op = exp_save = *exp_saveptr;
5481 exp_word = exp_saveptr + 1;
5482 if (exp_op == ':') {
5483 exp_op = *exp_word++;
5484 //TODO: try ${var:} and ${var:bogus} in non-bash config
5485 if (ENABLE_HUSH_BASH_COMPAT
5486 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5488 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5493 *exp_saveptr = '\0';
5494 } /* else: it's not an expansion op, but bare ${var} */
5497 /* Look up the variable in question */
5498 if (isdigit(var[0])) {
5499 /* parse_dollar should have vetted var for us */
5500 int n = xatoi_positive(var);
5501 if (n < G.global_argc)
5502 val = G.global_argv[n];
5503 /* else val remains NULL: $N with too big N */
5507 val = utoa(G.root_pid);
5509 case '!': /* bg pid */
5510 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5512 case '?': /* exitcode */
5513 val = utoa(G.last_exitcode);
5515 case '#': /* argc */
5516 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5519 val = get_local_var_value(var);
5523 /* Handle any expansions */
5524 if (exp_op == 'L') {
5525 reinit_unicode_for_hush();
5526 debug_printf_expand("expand: length(%s)=", val);
5527 val = utoa(val ? unicode_strlen(val) : 0);
5528 debug_printf_expand("%s\n", val);
5529 } else if (exp_op) {
5530 if (exp_op == '%' || exp_op == '#') {
5531 /* Standard-mandated substring removal ops:
5532 * ${parameter%word} - remove smallest suffix pattern
5533 * ${parameter%%word} - remove largest suffix pattern
5534 * ${parameter#word} - remove smallest prefix pattern
5535 * ${parameter##word} - remove largest prefix pattern
5537 * Word is expanded to produce a glob pattern.
5538 * Then var's value is matched to it and matching part removed.
5540 if (val && val[0]) {
5544 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5545 if (exp_op == *exp_word) /* ## or %% */
5547 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5549 exp_word = exp_exp_word;
5550 /* HACK ALERT. We depend here on the fact that
5551 * G.global_argv and results of utoa and get_local_var_value
5552 * are actually in writable memory:
5553 * scan_and_match momentarily stores NULs there. */
5555 loc = scan_and_match(t, exp_word, scan_flags);
5556 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5557 // exp_op, t, exp_word, loc);
5559 if (loc) { /* match was found */
5560 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5561 val = loc; /* take right part */
5563 val = to_be_freed = xstrndup(val, loc - val); /* left */
5567 #if ENABLE_HUSH_BASH_COMPAT
5568 else if (exp_op == '/' || exp_op == '\\') {
5569 /* It's ${var/[/]pattern[/repl]} thing.
5570 * Note that in encoded form it has TWO parts:
5571 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5572 * and if // is used, it is encoded as \:
5573 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5575 /* Empty variable always gives nothing: */
5576 // "v=''; echo ${v/*/w}" prints "", not "w"
5577 if (val && val[0]) {
5578 /* pattern uses non-standard expansion.
5579 * repl should be unbackslashed and globbed
5580 * by the usual expansion rules:
5582 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5583 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5584 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5585 * v='a bz'; echo ${v/a*z/\z} prints "z"
5586 * (note that a*z _pattern_ is never globbed!)
5588 char *pattern, *repl, *t;
5589 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5591 pattern = xstrdup(exp_word);
5592 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5593 *p++ = SPECIAL_VAR_SYMBOL;
5595 p = strchr(p, SPECIAL_VAR_SYMBOL);
5597 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5598 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5599 /* HACK ALERT. We depend here on the fact that
5600 * G.global_argv and results of utoa and get_local_var_value
5601 * are actually in writable memory:
5602 * replace_pattern momentarily stores NULs there. */
5604 to_be_freed = replace_pattern(t,
5606 (repl ? repl : exp_word),
5608 if (to_be_freed) /* at least one replace happened */
5615 else if (exp_op == ':') {
5616 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_FEATURE_SH_MATH
5617 /* It's ${var:N[:M]} bashism.
5618 * Note that in encoded form it has TWO parts:
5619 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5624 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5627 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5628 *p++ = SPECIAL_VAR_SYMBOL;
5630 p = strchr(p, SPECIAL_VAR_SYMBOL);
5632 len = expand_and_evaluate_arith(exp_word, &errmsg);
5635 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5636 if (len >= 0) { /* bash compat: len < 0 is illegal */
5637 if (beg < 0) /* bash compat */
5639 debug_printf_varexp("from val:'%s'\n", val);
5640 if (len == 0 || !val || beg >= strlen(val)) {
5644 /* Paranoia. What if user entered 9999999999999
5645 * which fits in arith_t but not int? */
5648 val = to_be_freed = xstrndup(val + beg, len);
5650 debug_printf_varexp("val:'%s'\n", val);
5654 die_if_script("malformed ${%s:...}", var);
5657 } else { /* one of "-=+?" */
5658 /* Standard-mandated substitution ops:
5659 * ${var?word} - indicate error if unset
5660 * If var is unset, word (or a message indicating it is unset
5661 * if word is null) is written to standard error
5662 * and the shell exits with a non-zero exit status.
5663 * Otherwise, the value of var is substituted.
5664 * ${var-word} - use default value
5665 * If var is unset, word is substituted.
5666 * ${var=word} - assign and use default value
5667 * If var is unset, word is assigned to var.
5668 * In all cases, final value of var is substituted.
5669 * ${var+word} - use alternative value
5670 * If var is unset, null is substituted.
5671 * Otherwise, word is substituted.
5673 * Word is subjected to tilde expansion, parameter expansion,
5674 * command substitution, and arithmetic expansion.
5675 * If word is not needed, it is not expanded.
5677 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5678 * but also treat null var as if it is unset.
5680 int use_word = (!val || ((exp_save == ':') && !val[0]));
5682 use_word = !use_word;
5683 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5684 (exp_save == ':') ? "true" : "false", use_word);
5686 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5688 exp_word = to_be_freed;
5689 if (exp_op == '?') {
5690 /* mimic bash message */
5691 die_if_script("%s: %s",
5693 exp_word[0] ? exp_word : "parameter null or not set"
5695 //TODO: how interactive bash aborts expansion mid-command?
5700 if (exp_op == '=') {
5701 /* ${var=[word]} or ${var:=[word]} */
5702 if (isdigit(var[0]) || var[0] == '#') {
5703 /* mimic bash message */
5704 die_if_script("$%s: cannot assign in this way", var);
5707 char *new_var = xasprintf("%s=%s", var, val);
5708 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5712 } /* one of "-=+?" */
5714 *exp_saveptr = exp_save;
5720 *to_be_freed_pp = to_be_freed;
5724 /* Expand all variable references in given string, adding words to list[]
5725 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5726 * to be filled). This routine is extremely tricky: has to deal with
5727 * variables/parameters with whitespace, $* and $@, and constructs like
5728 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5729 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5731 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5732 * expansion of right-hand side of assignment == 1-element expand.
5734 char cant_be_null = 0; /* only bit 0x80 matters */
5735 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5738 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5739 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5740 debug_print_list("expand_vars_to_list", output, n);
5741 n = o_save_ptr(output, n);
5742 debug_print_list("expand_vars_to_list[0]", output, n);
5744 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5746 char *to_be_freed = NULL;
5747 const char *val = NULL;
5748 #if ENABLE_HUSH_TICK
5749 o_string subst_result = NULL_O_STRING;
5751 #if ENABLE_FEATURE_SH_MATH
5752 char arith_buf[sizeof(arith_t)*3 + 2];
5756 o_addchr(output, '\0');
5757 n = o_save_ptr(output, n);
5761 o_addblock(output, arg, p - arg);
5762 debug_print_list("expand_vars_to_list[1]", output, n);
5764 p = strchr(p, SPECIAL_VAR_SYMBOL);
5766 /* Fetch special var name (if it is indeed one of them)
5767 * and quote bit, force the bit on if singleword expansion -
5768 * important for not getting v=$@ expand to many words. */
5769 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5771 /* Is this variable quoted and thus expansion can't be null?
5772 * "$@" is special. Even if quoted, it can still
5773 * expand to nothing (not even an empty string),
5774 * thus it is excluded. */
5775 if ((first_ch & 0x7f) != '@')
5776 cant_be_null |= first_ch;
5778 switch (first_ch & 0x7f) {
5779 /* Highest bit in first_ch indicates that var is double-quoted */
5783 if (!G.global_argv[1])
5786 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5787 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5788 while (G.global_argv[i]) {
5789 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5790 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5791 if (G.global_argv[i++][0] && G.global_argv[i]) {
5792 /* this argv[] is not empty and not last:
5793 * put terminating NUL, start new word */
5794 o_addchr(output, '\0');
5795 debug_print_list("expand_vars_to_list[2]", output, n);
5796 n = o_save_ptr(output, n);
5797 debug_print_list("expand_vars_to_list[3]", output, n);
5801 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5802 * and in this case should treat it like '$*' - see 'else...' below */
5803 if (first_ch == ('@'|0x80) /* quoted $@ */
5804 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5807 o_addQstr(output, G.global_argv[i]);
5808 if (++i >= G.global_argc)
5810 o_addchr(output, '\0');
5811 debug_print_list("expand_vars_to_list[4]", output, n);
5812 n = o_save_ptr(output, n);
5814 } else { /* quoted $* (or v="$@" case): add as one word */
5816 o_addQstr(output, G.global_argv[i]);
5817 if (!G.global_argv[++i])
5820 o_addchr(output, G.ifs[0]);
5822 output->has_quoted_part = 1;
5826 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5827 /* "Empty variable", used to make "" etc to not disappear */
5828 output->has_quoted_part = 1;
5830 cant_be_null = 0x80;
5832 #if ENABLE_HUSH_TICK
5833 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5834 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5836 /* Can't just stuff it into output o_string,
5837 * expanded result may need to be globbed
5838 * and $IFS-splitted */
5839 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5840 G.last_exitcode = process_command_subs(&subst_result, arg);
5841 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5842 val = subst_result.data;
5845 #if ENABLE_FEATURE_SH_MATH
5846 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5849 arg++; /* skip '+' */
5850 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5851 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5852 res = expand_and_evaluate_arith(arg, NULL);
5853 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5854 sprintf(arith_buf, ARITH_FMT, res);
5860 val = expand_one_var(&to_be_freed, arg, &p);
5861 IF_HUSH_TICK(store_val:)
5862 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5863 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5864 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5865 if (val && val[0]) {
5866 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5869 } else { /* quoted $VAR, val will be appended below */
5870 output->has_quoted_part = 1;
5871 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5872 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5875 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5877 if (val && val[0]) {
5878 o_addQstr(output, val);
5882 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5883 * Do the check to avoid writing to a const string. */
5884 if (*p != SPECIAL_VAR_SYMBOL)
5885 *p = SPECIAL_VAR_SYMBOL;
5887 #if ENABLE_HUSH_TICK
5888 o_free(&subst_result);
5891 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5895 o_addchr(output, '\0');
5896 n = o_save_ptr(output, n);
5898 debug_print_list("expand_vars_to_list[a]", output, n);
5899 /* this part is literal, and it was already pre-quoted
5900 * if needed (much earlier), do not use o_addQstr here! */
5901 o_addstr_with_NUL(output, arg);
5902 debug_print_list("expand_vars_to_list[b]", output, n);
5903 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5904 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5907 /* allow to reuse list[n] later without re-growth */
5908 output->has_empty_slot = 1;
5910 o_addchr(output, '\0');
5916 static char **expand_variables(char **argv, unsigned expflags)
5920 o_string output = NULL_O_STRING;
5922 output.o_expflags = expflags;
5926 n = expand_vars_to_list(&output, n, *argv);
5929 debug_print_list("expand_variables", &output, n);
5931 /* output.data (malloced in one block) gets returned in "list" */
5932 list = o_finalize_list(&output, n);
5933 debug_print_strings("expand_variables[1]", list);
5937 static char **expand_strvec_to_strvec(char **argv)
5939 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5942 #if ENABLE_HUSH_BASH_COMPAT
5943 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5945 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5949 /* Used for expansion of right hand of assignments,
5950 * $((...)), heredocs, variable espansion parts.
5952 * NB: should NOT do globbing!
5953 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5955 static char *expand_string_to_string(const char *str, int do_unbackslash)
5957 #if !ENABLE_HUSH_BASH_COMPAT
5958 const int do_unbackslash = 1;
5960 char *argv[2], **list;
5962 debug_printf_expand("string_to_string<='%s'\n", str);
5963 /* This is generally an optimization, but it also
5964 * handles "", which otherwise trips over !list[0] check below.
5965 * (is this ever happens that we actually get str="" here?)
5967 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5968 //TODO: Can use on strings with \ too, just unbackslash() them?
5969 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5970 return xstrdup(str);
5973 argv[0] = (char*)str;
5975 list = expand_variables(argv, do_unbackslash
5976 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5977 : EXP_FLAG_SINGLEWORD
5980 if (!list[0] || list[1])
5981 bb_error_msg_and_die("BUG in varexp2");
5982 /* actually, just move string 2*sizeof(char*) bytes back */
5983 overlapping_strcpy((char*)list, list[0]);
5985 unbackslash((char*)list);
5986 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5990 /* Used for "eval" builtin */
5991 static char* expand_strvec_to_string(char **argv)
5995 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5996 /* Convert all NULs to spaces */
6001 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6002 bb_error_msg_and_die("BUG in varexp3");
6003 /* bash uses ' ' regardless of $IFS contents */
6008 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6009 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6013 static char **expand_assignments(char **argv, int count)
6018 G.expanded_assignments = p = NULL;
6019 /* Expand assignments into one string each */
6020 for (i = 0; i < count; i++) {
6021 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6023 G.expanded_assignments = NULL;
6028 static void switch_off_special_sigs(unsigned mask)
6031 while ((mask >>= 1) != 0) {
6035 #if ENABLE_HUSH_TRAP
6037 if (G_traps[sig] && !G_traps[sig][0])
6038 /* trap is '', has to remain SIG_IGN */
6041 G_traps[sig] = NULL;
6044 /* We are here only if no trap or trap was not '' */
6045 install_sighandler(sig, SIG_DFL);
6051 void re_execute_shell(char ***to_free, const char *s,
6052 char *g_argv0, char **g_argv,
6053 char **builtin_argv) NORETURN;
6055 static void reset_traps_to_defaults(void)
6057 /* This function is always called in a child shell
6058 * after fork (not vfork, NOMMU doesn't use this function).
6060 IF_HUSH_TRAP(unsigned sig;)
6063 /* Child shells are not interactive.
6064 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6065 * Testcase: (while :; do :; done) + ^Z should background.
6066 * Same goes for SIGTERM, SIGHUP, SIGINT.
6068 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6069 if (!G_traps && !mask)
6070 return; /* already no traps and no special sigs */
6072 /* Switch off special sigs */
6073 switch_off_special_sigs(mask);
6074 # if ENABLE_HUSH_JOB
6075 G_fatal_sig_mask = 0;
6077 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6078 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6079 * remain set in G.special_sig_mask */
6081 # if ENABLE_HUSH_TRAP
6085 /* Reset all sigs to default except ones with empty traps */
6086 for (sig = 0; sig < NSIG; sig++) {
6088 continue; /* no trap: nothing to do */
6089 if (!G_traps[sig][0])
6090 continue; /* empty trap: has to remain SIG_IGN */
6091 /* sig has non-empty trap, reset it: */
6093 G_traps[sig] = NULL;
6094 /* There is no signal for trap 0 (EXIT) */
6097 install_sighandler(sig, pick_sighandler(sig));
6104 static void re_execute_shell(char ***to_free, const char *s,
6105 char *g_argv0, char **g_argv,
6106 char **builtin_argv) NORETURN;
6107 static void re_execute_shell(char ***to_free, const char *s,
6108 char *g_argv0, char **g_argv,
6109 char **builtin_argv)
6111 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6112 /* delims + 2 * (number of bytes in printed hex numbers) */
6113 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6114 char *heredoc_argv[4];
6115 struct variable *cur;
6116 # if ENABLE_HUSH_FUNCTIONS
6117 struct function *funcp;
6121 unsigned long long empty_trap_mask;
6123 if (!g_argv0) { /* heredoc */
6124 argv = heredoc_argv;
6125 argv[0] = (char *) G.argv0_for_re_execing;
6126 argv[1] = (char *) "-<";
6127 argv[2] = (char *) s;
6129 pp = &argv[3]; /* used as pointer to empty environment */
6135 if (pp) while (*pp++)
6138 empty_trap_mask = 0;
6141 for (sig = 1; sig < NSIG; sig++) {
6142 if (G_traps[sig] && !G_traps[sig][0])
6143 empty_trap_mask |= 1LL << sig;
6147 sprintf(param_buf, NOMMU_HACK_FMT
6148 , (unsigned) G.root_pid
6149 , (unsigned) G.root_ppid
6150 , (unsigned) G.last_bg_pid
6151 , (unsigned) G.last_exitcode
6154 IF_HUSH_LOOPS(, G.depth_of_loop)
6156 # undef NOMMU_HACK_FMT
6157 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6158 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6161 for (cur = G.top_var; cur; cur = cur->next) {
6162 if (!cur->flg_export || cur->flg_read_only)
6165 # if ENABLE_HUSH_FUNCTIONS
6166 for (funcp = G.top_func; funcp; funcp = funcp->next)
6172 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6173 *pp++ = (char *) G.argv0_for_re_execing;
6175 for (cur = G.top_var; cur; cur = cur->next) {
6176 if (strcmp(cur->varstr, hush_version_str) == 0)
6178 if (cur->flg_read_only) {
6179 *pp++ = (char *) "-R";
6180 *pp++ = cur->varstr;
6181 } else if (!cur->flg_export) {
6182 *pp++ = (char *) "-V";
6183 *pp++ = cur->varstr;
6186 # if ENABLE_HUSH_FUNCTIONS
6187 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6188 *pp++ = (char *) "-F";
6189 *pp++ = funcp->name;
6190 *pp++ = funcp->body_as_string;
6193 /* We can pass activated traps here. Say, -Tnn:trap_string
6195 * However, POSIX says that subshells reset signals with traps
6197 * I tested bash-3.2 and it not only does that with true subshells
6198 * of the form ( list ), but with any forked children shells.
6199 * I set trap "echo W" WINCH; and then tried:
6201 * { echo 1; sleep 20; echo 2; } &
6202 * while true; do echo 1; sleep 20; echo 2; break; done &
6203 * true | { echo 1; sleep 20; echo 2; } | cat
6205 * In all these cases sending SIGWINCH to the child shell
6206 * did not run the trap. If I add trap "echo V" WINCH;
6207 * _inside_ group (just before echo 1), it works.
6209 * I conclude it means we don't need to pass active traps here.
6211 *pp++ = (char *) "-c";
6214 while (*++builtin_argv)
6215 *pp++ = *builtin_argv;
6216 *pp++ = (char *) "";
6221 /* *pp = NULL; - is already there */
6225 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6226 /* Don't propagate SIG_IGN to the child */
6227 if (SPECIAL_JOBSTOP_SIGS != 0)
6228 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6229 execve(bb_busybox_exec_path, argv, pp);
6230 /* Fallback. Useful for init=/bin/hush usage etc */
6231 if (argv[0][0] == '/')
6232 execve(argv[0], argv, pp);
6233 xfunc_error_retval = 127;
6234 bb_error_msg_and_die("can't re-execute the shell");
6236 #endif /* !BB_MMU */
6239 static int run_and_free_list(struct pipe *pi);
6241 /* Executing from string: eval, sh -c '...'
6242 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6243 * end_trigger controls how often we stop parsing
6244 * NUL: parse all, execute, return
6245 * ';': parse till ';' or newline, execute, repeat till EOF
6247 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6249 /* Why we need empty flag?
6250 * An obscure corner case "false; ``; echo $?":
6251 * empty command in `` should still set $? to 0.
6252 * But we can't just set $? to 0 at the start,
6253 * this breaks "false; echo `echo $?`" case.
6257 struct pipe *pipe_list;
6259 #if ENABLE_HUSH_INTERACTIVE
6260 if (end_trigger == ';')
6261 inp->promptmode = 0; /* PS1 */
6263 pipe_list = parse_stream(NULL, inp, end_trigger);
6264 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6265 /* If we are in "big" script
6266 * (not in `cmd` or something similar)...
6268 if (pipe_list == ERR_PTR && end_trigger == ';') {
6269 /* Discard cached input (rest of line) */
6270 int ch = inp->last_char;
6271 while (ch != EOF && ch != '\n') {
6272 //bb_error_msg("Discarded:'%c'", ch);
6277 /* This stream isn't empty */
6281 if (!pipe_list && empty)
6282 G.last_exitcode = 0;
6285 debug_print_tree(pipe_list, 0);
6286 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6287 run_and_free_list(pipe_list);
6289 if (G_flag_return_in_progress == 1)
6294 static void parse_and_run_string(const char *s)
6296 struct in_str input;
6297 setup_string_in_str(&input, s);
6298 parse_and_run_stream(&input, '\0');
6301 static void parse_and_run_file(FILE *f)
6303 struct in_str input;
6304 setup_file_in_str(&input, f);
6305 parse_and_run_stream(&input, ';');
6308 #if ENABLE_HUSH_TICK
6309 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6314 char **to_free = NULL;
6318 pid = BB_MMU ? xfork() : xvfork();
6319 if (pid == 0) { /* child */
6320 disable_restore_tty_pgrp_on_exit();
6321 /* Process substitution is not considered to be usual
6322 * 'command execution'.
6323 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6330 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6331 close(channel[0]); /* NB: close _first_, then move fd! */
6332 xmove_fd(channel[1], 1);
6333 /* Prevent it from trying to handle ctrl-z etc */
6334 IF_HUSH_JOB(G.run_list_level = 1;)
6335 # if ENABLE_HUSH_TRAP
6336 /* Awful hack for `trap` or $(trap).
6338 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6339 * contains an example where "trap" is executed in a subshell:
6341 * save_traps=$(trap)
6343 * eval "$save_traps"
6345 * Standard does not say that "trap" in subshell shall print
6346 * parent shell's traps. It only says that its output
6347 * must have suitable form, but then, in the above example
6348 * (which is not supposed to be normative), it implies that.
6350 * bash (and probably other shell) does implement it
6351 * (traps are reset to defaults, but "trap" still shows them),
6352 * but as a result, "trap" logic is hopelessly messed up:
6355 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6356 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6357 * # true | trap <--- trap is in subshell - no output (ditto)
6358 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6359 * trap -- 'echo Ho' SIGWINCH
6360 * # echo `(trap)` <--- in subshell in subshell - output
6361 * trap -- 'echo Ho' SIGWINCH
6362 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6363 * trap -- 'echo Ho' SIGWINCH
6365 * The rules when to forget and when to not forget traps
6366 * get really complex and nonsensical.
6368 * Our solution: ONLY bare $(trap) or `trap` is special.
6370 s = skip_whitespace(s);
6371 if (is_prefixed_with(s, "trap")
6372 && skip_whitespace(s + 4)[0] == '\0'
6374 static const char *const argv[] = { NULL, NULL };
6375 builtin_trap((char**)argv);
6376 fflush_all(); /* important */
6381 reset_traps_to_defaults();
6382 parse_and_run_string(s);
6383 _exit(G.last_exitcode);
6385 /* We re-execute after vfork on NOMMU. This makes this script safe:
6386 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6387 * huge=`cat BIG` # was blocking here forever
6390 re_execute_shell(&to_free,
6400 # if ENABLE_HUSH_FAST
6402 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6403 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6404 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6406 enable_restore_tty_pgrp_on_exit();
6411 return remember_FILE(xfdopen_for_read(channel[0]));
6414 /* Return code is exit status of the process that is run. */
6415 static int process_command_subs(o_string *dest, const char *s)
6418 struct in_str pipe_str;
6420 int status, ch, eol_cnt;
6422 fp = generate_stream_from_string(s, &pid);
6424 /* Now send results of command back into original context */
6425 setup_file_in_str(&pipe_str, fp);
6427 while ((ch = i_getch(&pipe_str)) != EOF) {
6433 o_addchr(dest, '\n');
6436 o_addQchr(dest, ch);
6439 debug_printf("done reading from `cmd` pipe, closing it\n");
6440 fclose_and_forget(fp);
6441 /* We need to extract exitcode. Test case
6442 * "true; echo `sleep 1; false` $?"
6444 safe_waitpid(pid, &status, 0);
6445 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6446 return WEXITSTATUS(status);
6448 #endif /* ENABLE_HUSH_TICK */
6451 static void setup_heredoc(struct redir_struct *redir)
6453 struct fd_pair pair;
6456 /* the _body_ of heredoc (misleading field name) */
6457 const char *heredoc = redir->rd_filename;
6464 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6465 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6469 len = strlen(heredoc);
6471 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6473 xmove_fd(pair.rd, redir->rd_fd);
6475 /* Try writing without forking. Newer kernels have
6476 * dynamically growing pipes. Must use non-blocking write! */
6479 written = write(pair.wr, heredoc, len);
6490 ndelay_off(pair.wr);
6492 /* Okay, pipe buffer was not big enough */
6493 /* Note: we must not create a stray child (bastard? :)
6494 * for the unsuspecting parent process. Child creates a grandchild
6495 * and exits before parent execs the process which consumes heredoc
6496 * (that exec happens after we return from this function) */
6503 disable_restore_tty_pgrp_on_exit();
6504 pid = BB_MMU ? xfork() : xvfork();
6508 close(redir->rd_fd); /* read side of the pipe */
6510 full_write(pair.wr, heredoc, len); /* may loop or block */
6513 /* Delegate blocking writes to another process */
6514 xmove_fd(pair.wr, STDOUT_FILENO);
6515 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6519 #if ENABLE_HUSH_FAST
6521 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6523 enable_restore_tty_pgrp_on_exit();
6529 wait(NULL); /* wait till child has died */
6532 /* fd: redirect wants this fd to be used (e.g. 3>file).
6533 * Move all conflicting internally used fds,
6534 * and remember them so that we can restore them later.
6536 static int save_fds_on_redirect(int fd, int squirrel[3])
6539 /* Handle redirects of fds 0,1,2 */
6541 /* If we collide with an already moved stdio fd... */
6542 if (fd == squirrel[0]) {
6543 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6546 if (fd == squirrel[1]) {
6547 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6550 if (fd == squirrel[2]) {
6551 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6554 /* If we are about to redirect stdio fd, and did not yet move it... */
6555 if (fd <= 2 && squirrel[fd] < 0) {
6556 /* We avoid taking stdio fds */
6557 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6558 if (squirrel[fd] < 0 && errno != EBADF)
6560 return 0; /* "we did not close fd" */
6564 #if ENABLE_HUSH_INTERACTIVE
6565 if (fd != 0 && fd == G.interactive_fd) {
6566 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6571 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6572 * (1) Redirect in a forked child. No need to save FILEs' fds,
6573 * we aren't going to use them anymore, ok to trash.
6574 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6575 * but how are we doing to use them?
6576 * "fileno(fd) = new_fd" can't be done.
6581 return save_FILEs_on_redirect(fd);
6584 static void restore_redirects(int squirrel[3])
6587 for (i = 0; i <= 2; i++) {
6590 /* We simply die on error */
6595 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6597 restore_redirected_FILEs();
6600 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6601 * and stderr if they are redirected. */
6602 static int setup_redirects(struct command *prog, int squirrel[])
6605 struct redir_struct *redir;
6607 for (redir = prog->redirects; redir; redir = redir->next) {
6608 if (redir->rd_type == REDIRECT_HEREDOC2) {
6609 /* "rd_fd<<HERE" case */
6610 save_fds_on_redirect(redir->rd_fd, squirrel);
6611 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6613 debug_printf_parse("set heredoc '%s'\n",
6614 redir->rd_filename);
6615 setup_heredoc(redir);
6619 if (redir->rd_dup == REDIRFD_TO_FILE) {
6620 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6622 if (redir->rd_filename == NULL) {
6625 * "cmd >" (no filename)
6626 * "cmd > <file" (2nd redirect starts too early)
6628 die_if_script("syntax error: %s", "invalid redirect");
6631 mode = redir_table[redir->rd_type].mode;
6632 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6633 openfd = open_or_warn(p, mode);
6636 /* Error message from open_or_warn can be lost
6637 * if stderr has been redirected, but bash
6638 * and ash both lose it as well
6639 * (though zsh doesn't!)
6644 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6645 openfd = redir->rd_dup;
6648 if (openfd != redir->rd_fd) {
6649 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6650 if (openfd == REDIRFD_CLOSE) {
6651 /* "rd_fd >&-" means "close me" */
6653 /* ^^^ optimization: saving may already
6654 * have closed it. If not... */
6655 close(redir->rd_fd);
6658 xdup2(openfd, redir->rd_fd);
6659 if (redir->rd_dup == REDIRFD_TO_FILE)
6660 /* "rd_fd > FILE" */
6662 /* else: "rd_fd > rd_dup" */
6669 static char *find_in_path(const char *arg)
6672 const char *PATH = get_local_var_value("PATH");
6678 const char *end = strchrnul(PATH, ':');
6679 int sz = end - PATH; /* must be int! */
6683 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6685 /* We have xxx::yyyy in $PATH,
6686 * it means "use current dir" */
6689 if (access(ret, F_OK) == 0)
6702 static const struct built_in_command *find_builtin_helper(const char *name,
6703 const struct built_in_command *x,
6704 const struct built_in_command *end)
6707 if (strcmp(name, x->b_cmd) != 0) {
6711 debug_printf_exec("found builtin '%s'\n", name);
6716 static const struct built_in_command *find_builtin1(const char *name)
6718 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6720 static const struct built_in_command *find_builtin(const char *name)
6722 const struct built_in_command *x = find_builtin1(name);
6725 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6728 #if ENABLE_HUSH_FUNCTIONS
6729 static struct function **find_function_slot(const char *name)
6731 struct function **funcpp = &G.top_func;
6733 if (strcmp(name, (*funcpp)->name) == 0) {
6736 funcpp = &(*funcpp)->next;
6741 static const struct function *find_function(const char *name)
6743 const struct function *funcp = *find_function_slot(name);
6745 debug_printf_exec("found function '%s'\n", name);
6749 /* Note: takes ownership on name ptr */
6750 static struct function *new_function(char *name)
6752 struct function **funcpp = find_function_slot(name);
6753 struct function *funcp = *funcpp;
6755 if (funcp != NULL) {
6756 struct command *cmd = funcp->parent_cmd;
6757 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6759 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6761 /* Note: if !funcp->body, do not free body_as_string!
6762 * This is a special case of "-F name body" function:
6763 * body_as_string was not malloced! */
6765 free_pipe_list(funcp->body);
6767 free(funcp->body_as_string);
6771 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6772 cmd->argv[0] = funcp->name;
6773 cmd->group = funcp->body;
6775 cmd->group_as_string = funcp->body_as_string;
6779 debug_printf_exec("remembering new function '%s'\n", name);
6780 funcp = *funcpp = xzalloc(sizeof(*funcp));
6781 /*funcp->next = NULL;*/
6788 # if ENABLE_HUSH_UNSET
6789 static void unset_func(const char *name)
6791 struct function **funcpp = find_function_slot(name);
6792 struct function *funcp = *funcpp;
6794 if (funcp != NULL) {
6795 debug_printf_exec("freeing function '%s'\n", funcp->name);
6796 *funcpp = funcp->next;
6797 /* funcp is unlinked now, deleting it.
6798 * Note: if !funcp->body, the function was created by
6799 * "-F name body", do not free ->body_as_string
6800 * and ->name as they were not malloced. */
6802 free_pipe_list(funcp->body);
6805 free(funcp->body_as_string);
6814 #define exec_function(to_free, funcp, argv) \
6815 exec_function(funcp, argv)
6817 static void exec_function(char ***to_free,
6818 const struct function *funcp,
6819 char **argv) NORETURN;
6820 static void exec_function(char ***to_free,
6821 const struct function *funcp,
6827 argv[0] = G.global_argv[0];
6828 G.global_argv = argv;
6832 /* On MMU, funcp->body is always non-NULL */
6833 n = run_list(funcp->body);
6837 re_execute_shell(to_free,
6838 funcp->body_as_string,
6845 static int run_function(const struct function *funcp, char **argv)
6851 save_and_replace_G_args(&sv, argv);
6853 /* "we are in function, ok to use return" */
6854 sv_flg = G_flag_return_in_progress;
6855 G_flag_return_in_progress = -1;
6856 # if ENABLE_HUSH_LOCAL
6857 G.func_nest_level++;
6860 /* On MMU, funcp->body is always non-NULL */
6863 /* Function defined by -F */
6864 parse_and_run_string(funcp->body_as_string);
6865 rc = G.last_exitcode;
6869 rc = run_list(funcp->body);
6872 # if ENABLE_HUSH_LOCAL
6874 struct variable *var;
6875 struct variable **var_pp;
6877 var_pp = &G.top_var;
6878 while ((var = *var_pp) != NULL) {
6879 if (var->func_nest_level < G.func_nest_level) {
6880 var_pp = &var->next;
6884 if (var->flg_export)
6885 bb_unsetenv(var->varstr);
6886 /* Remove from global list */
6887 *var_pp = var->next;
6893 G.func_nest_level--;
6896 G_flag_return_in_progress = sv_flg;
6898 restore_G_args(&sv, argv);
6902 #endif /* ENABLE_HUSH_FUNCTIONS */
6906 #define exec_builtin(to_free, x, argv) \
6907 exec_builtin(x, argv)
6909 #define exec_builtin(to_free, x, argv) \
6910 exec_builtin(to_free, argv)
6912 static void exec_builtin(char ***to_free,
6913 const struct built_in_command *x,
6914 char **argv) NORETURN;
6915 static void exec_builtin(char ***to_free,
6916 const struct built_in_command *x,
6922 rcode = x->b_function(argv);
6927 /* On NOMMU, we must never block!
6928 * Example: { sleep 99 | read line; } & echo Ok
6930 re_execute_shell(to_free,
6939 static void execvp_or_die(char **argv) NORETURN;
6940 static void execvp_or_die(char **argv)
6943 debug_printf_exec("execing '%s'\n", argv[0]);
6944 /* Don't propagate SIG_IGN to the child */
6945 if (SPECIAL_JOBSTOP_SIGS != 0)
6946 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6947 execvp(argv[0], argv);
6949 if (errno == EACCES) e = 126;
6950 if (errno == ENOENT) e = 127;
6951 bb_perror_msg("can't execute '%s'", argv[0]);
6955 #if ENABLE_HUSH_MODE_X
6956 static void dump_cmd_in_x_mode(char **argv)
6958 if (G_x_mode && argv) {
6959 /* We want to output the line in one write op */
6967 len += strlen(argv[n++]) + 1;
6973 p += sprintf(p, " %s", argv[n++]);
6981 # define dump_cmd_in_x_mode(argv) ((void)0)
6985 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6986 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6987 #define pseudo_exec(nommu_save, command, argv_expanded) \
6988 pseudo_exec(command, argv_expanded)
6991 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6993 * Don't exit() here. If you don't exec, use _exit instead.
6994 * The at_exit handlers apparently confuse the calling process,
6995 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6997 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6998 char **argv, int assignment_cnt,
6999 char **argv_expanded) NORETURN;
7000 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7001 char **argv, int assignment_cnt,
7002 char **argv_expanded)
7006 new_env = expand_assignments(argv, assignment_cnt);
7007 dump_cmd_in_x_mode(new_env);
7009 if (!argv[assignment_cnt]) {
7010 /* Case when we are here: ... | var=val | ...
7011 * (note that we do not exit early, i.e., do not optimize out
7012 * expand_assignments(): think about ... | var=`sleep 1` | ...
7014 free_strings(new_env);
7015 _exit(EXIT_SUCCESS);
7019 set_vars_and_save_old(new_env);
7020 free(new_env); /* optional */
7021 /* we can also destroy set_vars_and_save_old's return value,
7024 nommu_save->new_env = new_env;
7025 nommu_save->old_vars = set_vars_and_save_old(new_env);
7028 if (argv_expanded) {
7029 argv = argv_expanded;
7031 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7033 nommu_save->argv = argv;
7036 dump_cmd_in_x_mode(argv);
7038 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7039 if (strchr(argv[0], '/') != NULL)
7043 /* Check if the command matches any of the builtins.
7044 * Depending on context, this might be redundant. But it's
7045 * easier to waste a few CPU cycles than it is to figure out
7046 * if this is one of those cases.
7049 /* On NOMMU, it is more expensive to re-execute shell
7050 * just in order to run echo or test builtin.
7051 * It's better to skip it here and run corresponding
7052 * non-builtin later. */
7053 const struct built_in_command *x;
7054 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7056 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7059 #if ENABLE_HUSH_FUNCTIONS
7060 /* Check if the command matches any functions */
7062 const struct function *funcp = find_function(argv[0]);
7064 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7069 #if ENABLE_FEATURE_SH_STANDALONE
7070 /* Check if the command matches any busybox applets */
7072 int a = find_applet_by_name(argv[0]);
7074 # if BB_MMU /* see above why on NOMMU it is not allowed */
7075 if (APPLET_IS_NOEXEC(a)) {
7076 /* Do not leak open fds from opened script files etc */
7077 close_all_FILE_list();
7078 debug_printf_exec("running applet '%s'\n", argv[0]);
7079 run_applet_no_and_exit(a, argv);
7082 /* Re-exec ourselves */
7083 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7084 /* Don't propagate SIG_IGN to the child */
7085 if (SPECIAL_JOBSTOP_SIGS != 0)
7086 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7087 execv(bb_busybox_exec_path, argv);
7088 /* If they called chroot or otherwise made the binary no longer
7089 * executable, fall through */
7094 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7097 execvp_or_die(argv);
7100 /* Called after [v]fork() in run_pipe
7102 static void pseudo_exec(nommu_save_t *nommu_save,
7103 struct command *command,
7104 char **argv_expanded) NORETURN;
7105 static void pseudo_exec(nommu_save_t *nommu_save,
7106 struct command *command,
7107 char **argv_expanded)
7109 if (command->argv) {
7110 pseudo_exec_argv(nommu_save, command->argv,
7111 command->assignment_cnt, argv_expanded);
7114 if (command->group) {
7115 /* Cases when we are here:
7118 * ... | ( list ) | ...
7119 * ... | { list } | ...
7123 debug_printf_exec("pseudo_exec: run_list\n");
7124 reset_traps_to_defaults();
7125 rcode = run_list(command->group);
7126 /* OK to leak memory by not calling free_pipe_list,
7127 * since this process is about to exit */
7130 re_execute_shell(&nommu_save->argv_from_re_execing,
7131 command->group_as_string,
7138 /* Case when we are here: ... | >file */
7139 debug_printf_exec("pseudo_exec'ed null command\n");
7140 _exit(EXIT_SUCCESS);
7144 static const char *get_cmdtext(struct pipe *pi)
7150 /* This is subtle. ->cmdtext is created only on first backgrounding.
7151 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7152 * On subsequent bg argv is trashed, but we won't use it */
7156 argv = pi->cmds[0].argv;
7158 pi->cmdtext = xzalloc(1);
7163 len += strlen(*argv) + 1;
7167 argv = pi->cmds[0].argv;
7169 p = stpcpy(p, *argv);
7176 static void insert_bg_job(struct pipe *pi)
7178 struct pipe *job, **jobp;
7181 /* Linear search for the ID of the job to use */
7183 for (job = G.job_list; job; job = job->next)
7184 if (job->jobid >= pi->jobid)
7185 pi->jobid = job->jobid + 1;
7187 /* Add job to the list of running jobs */
7189 while ((job = *jobp) != NULL)
7191 job = *jobp = xmalloc(sizeof(*job));
7193 *job = *pi; /* physical copy */
7195 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7196 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7197 for (i = 0; i < pi->num_cmds; i++) {
7198 job->cmds[i].pid = pi->cmds[i].pid;
7199 /* all other fields are not used and stay zero */
7201 job->cmdtext = xstrdup(get_cmdtext(pi));
7203 if (G_interactive_fd)
7204 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7205 G.last_jobid = job->jobid;
7208 static void remove_bg_job(struct pipe *pi)
7210 struct pipe *prev_pipe;
7212 if (pi == G.job_list) {
7213 G.job_list = pi->next;
7215 prev_pipe = G.job_list;
7216 while (prev_pipe->next != pi)
7217 prev_pipe = prev_pipe->next;
7218 prev_pipe->next = pi->next;
7221 G.last_jobid = G.job_list->jobid;
7226 /* Remove a backgrounded job */
7227 static void delete_finished_bg_job(struct pipe *pi)
7234 static int job_exited_or_stopped(struct pipe *pi)
7238 if (pi->alive_cmds != pi->stopped_cmds)
7241 /* All processes in fg pipe have exited or stopped */
7245 rcode = pi->cmds[i].cmd_exitcode;
7246 /* usually last process gives overall exitstatus,
7247 * but with "set -o pipefail", last *failed* process does */
7248 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7251 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7255 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7262 dead = WIFEXITED(status) || WIFSIGNALED(status);
7265 if (WIFSTOPPED(status))
7266 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7267 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7268 if (WIFSIGNALED(status))
7269 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7270 childpid, WTERMSIG(status), WEXITSTATUS(status));
7271 if (WIFEXITED(status))
7272 debug_printf_jobs("pid %d exited, exitcode %d\n",
7273 childpid, WEXITSTATUS(status));
7275 /* Were we asked to wait for a fg pipe? */
7277 i = fg_pipe->num_cmds;
7282 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7283 if (fg_pipe->cmds[i].pid != childpid)
7287 fg_pipe->cmds[i].pid = 0;
7288 fg_pipe->alive_cmds--;
7289 ex = WEXITSTATUS(status);
7290 /* bash prints killer signal's name for *last*
7291 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7292 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7294 if (WIFSIGNALED(status)) {
7295 int sig = WTERMSIG(status);
7296 if (i == fg_pipe->num_cmds-1)
7297 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7298 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7299 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7300 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7301 * Maybe we need to use sig | 128? */
7304 fg_pipe->cmds[i].cmd_exitcode = ex;
7306 fg_pipe->stopped_cmds++;
7308 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7309 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7310 rcode = job_exited_or_stopped(fg_pipe);
7312 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7313 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7314 * and "killall -STOP cat" */
7315 if (G_interactive_fd) {
7317 if (fg_pipe->alive_cmds != 0)
7318 insert_bg_job(fg_pipe);
7322 if (fg_pipe->alive_cmds == 0)
7325 /* There are still running processes in the fg_pipe */
7328 /* It wasnt in fg_pipe, look for process in bg pipes */
7332 /* We were asked to wait for bg or orphaned children */
7333 /* No need to remember exitcode in this case */
7334 for (pi = G.job_list; pi; pi = pi->next) {
7335 for (i = 0; i < pi->num_cmds; i++) {
7336 if (pi->cmds[i].pid == childpid)
7337 goto found_pi_and_prognum;
7340 /* Happens when shell is used as init process (init=/bin/sh) */
7341 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7342 return -1; /* this wasn't a process from fg_pipe */
7344 found_pi_and_prognum:
7347 pi->cmds[i].pid = 0;
7348 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7349 if (WIFSIGNALED(status))
7350 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7352 if (!pi->alive_cmds) {
7353 if (G_interactive_fd)
7354 printf(JOB_STATUS_FORMAT, pi->jobid,
7355 "Done", pi->cmdtext);
7356 delete_finished_bg_job(pi);
7363 return -1; /* this wasn't a process from fg_pipe */
7366 /* Check to see if any processes have exited -- if they have,
7367 * figure out why and see if a job has completed.
7369 * If non-NULL fg_pipe: wait for its completion or stop.
7370 * Return its exitcode or zero if stopped.
7372 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7373 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7374 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7375 * or 0 if no children changed status.
7377 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7378 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7379 * or 0 if no children changed status.
7381 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7387 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7389 attributes = WUNTRACED;
7390 if (fg_pipe == NULL)
7391 attributes |= WNOHANG;
7394 #if ENABLE_HUSH_FAST
7395 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7396 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7397 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7398 /* There was neither fork nor SIGCHLD since last waitpid */
7399 /* Avoid doing waitpid syscall if possible */
7400 if (!G.we_have_children) {
7404 if (fg_pipe == NULL) { /* is WNOHANG set? */
7405 /* We have children, but they did not exit
7406 * or stop yet (we saw no SIGCHLD) */
7409 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7413 /* Do we do this right?
7414 * bash-3.00# sleep 20 | false
7416 * [3]+ Stopped sleep 20 | false
7417 * bash-3.00# echo $?
7418 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7419 * [hush 1.14.0: yes we do it right]
7423 #if ENABLE_HUSH_FAST
7425 i = G.count_SIGCHLD;
7427 childpid = waitpid(-1, &status, attributes);
7428 if (childpid <= 0) {
7429 if (childpid && errno != ECHILD)
7430 bb_perror_msg("waitpid");
7431 #if ENABLE_HUSH_FAST
7432 else { /* Until next SIGCHLD, waitpid's are useless */
7433 G.we_have_children = (childpid == 0);
7434 G.handled_SIGCHLD = i;
7435 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7438 /* ECHILD (no children), or 0 (no change in children status) */
7442 rcode = process_wait_result(fg_pipe, childpid, status);
7444 /* fg_pipe exited or stopped */
7447 if (childpid == waitfor_pid) {
7448 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7449 rcode = WEXITSTATUS(status);
7450 if (WIFSIGNALED(status))
7451 rcode = 128 + WTERMSIG(status);
7452 if (WIFSTOPPED(status))
7453 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7454 rcode = 128 + WSTOPSIG(status);
7456 break; /* "wait PID" called us, give it exitcode+1 */
7458 /* This wasn't one of our processes, or */
7459 /* fg_pipe still has running processes, do waitpid again */
7460 } /* while (waitpid succeeds)... */
7466 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7469 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7470 if (G_saved_tty_pgrp) {
7471 /* Job finished, move the shell to the foreground */
7472 p = getpgrp(); /* our process group id */
7473 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7474 tcsetpgrp(G_interactive_fd, p);
7480 /* Start all the jobs, but don't wait for anything to finish.
7483 * Return code is normally -1, when the caller has to wait for children
7484 * to finish to determine the exit status of the pipe. If the pipe
7485 * is a simple builtin command, however, the action is done by the
7486 * time run_pipe returns, and the exit code is provided as the
7489 * Returns -1 only if started some children. IOW: we have to
7490 * mask out retvals of builtins etc with 0xff!
7492 * The only case when we do not need to [v]fork is when the pipe
7493 * is single, non-backgrounded, non-subshell command. Examples:
7494 * cmd ; ... { list } ; ...
7495 * cmd && ... { list } && ...
7496 * cmd || ... { list } || ...
7497 * If it is, then we can run cmd as a builtin, NOFORK,
7498 * or (if SH_STANDALONE) an applet, and we can run the { list }
7499 * with run_list. If it isn't one of these, we fork and exec cmd.
7501 * Cases when we must fork:
7502 * non-single: cmd | cmd
7503 * backgrounded: cmd & { list } &
7504 * subshell: ( list ) [&]
7506 #if !ENABLE_HUSH_MODE_X
7507 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7508 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7510 static int redirect_and_varexp_helper(char ***new_env_p,
7511 struct variable **old_vars_p,
7512 struct command *command,
7514 char **argv_expanded)
7516 /* setup_redirects acts on file descriptors, not FILEs.
7517 * This is perfect for work that comes after exec().
7518 * Is it really safe for inline use? Experimentally,
7519 * things seem to work. */
7520 int rcode = setup_redirects(command, squirrel);
7522 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7523 *new_env_p = new_env;
7524 dump_cmd_in_x_mode(new_env);
7525 dump_cmd_in_x_mode(argv_expanded);
7527 *old_vars_p = set_vars_and_save_old(new_env);
7531 static NOINLINE int run_pipe(struct pipe *pi)
7533 static const char *const null_ptr = NULL;
7537 struct command *command;
7538 char **argv_expanded;
7540 /* it is not always needed, but we aim to smaller code */
7541 int squirrel[] = { -1, -1, -1 };
7544 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7547 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7548 * Result should be 3 lines: q w e, qwe, q w e
7550 G.ifs = get_local_var_value("IFS");
7554 IF_HUSH_JOB(pi->pgrp = -1;)
7555 pi->stopped_cmds = 0;
7556 command = &pi->cmds[0];
7557 argv_expanded = NULL;
7559 if (pi->num_cmds != 1
7560 || pi->followup == PIPE_BG
7561 || command->cmd_type == CMD_SUBSHELL
7568 debug_printf_exec(": group:%p argv:'%s'\n",
7569 command->group, command->argv ? command->argv[0] : "NONE");
7571 if (command->group) {
7572 #if ENABLE_HUSH_FUNCTIONS
7573 if (command->cmd_type == CMD_FUNCDEF) {
7574 /* "executing" func () { list } */
7575 struct function *funcp;
7577 funcp = new_function(command->argv[0]);
7578 /* funcp->name is already set to argv[0] */
7579 funcp->body = command->group;
7581 funcp->body_as_string = command->group_as_string;
7582 command->group_as_string = NULL;
7584 command->group = NULL;
7585 command->argv[0] = NULL;
7586 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7587 funcp->parent_cmd = command;
7588 command->child_func = funcp;
7590 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7592 return EXIT_SUCCESS;
7596 debug_printf("non-subshell group\n");
7597 rcode = 1; /* exitcode if redir failed */
7598 if (setup_redirects(command, squirrel) == 0) {
7599 debug_printf_exec(": run_list\n");
7600 rcode = run_list(command->group) & 0xff;
7602 restore_redirects(squirrel);
7603 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7605 debug_printf_exec("run_pipe: return %d\n", rcode);
7609 argv = command->argv ? command->argv : (char **) &null_ptr;
7611 const struct built_in_command *x;
7612 #if ENABLE_HUSH_FUNCTIONS
7613 const struct function *funcp;
7617 char **new_env = NULL;
7618 struct variable *old_vars = NULL;
7620 if (argv[command->assignment_cnt] == NULL) {
7621 /* Assignments, but no command */
7622 /* Ensure redirects take effect (that is, create files).
7623 * Try "a=t >file" */
7624 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7625 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7626 /* Set shell variables */
7630 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7631 /* Do we need to flag set_local_var() errors?
7632 * "assignment to readonly var" and "putenv error"
7637 /* Redirect error sets $? to 1. Otherwise,
7638 * if evaluating assignment value set $?, retain it.
7639 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7641 rcode = G.last_exitcode;
7642 /* Exit, _skipping_ variable restoring code: */
7643 goto clean_up_and_ret0;
7645 #else /* Older, bigger, but more correct code */
7647 rcode = setup_redirects(command, squirrel);
7648 restore_redirects(squirrel);
7649 /* Set shell variables */
7651 bb_putchar_stderr('+');
7653 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7655 fprintf(stderr, " %s", p);
7656 debug_printf_exec("set shell var:'%s'->'%s'\n",
7658 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7659 /* Do we need to flag set_local_var() errors?
7660 * "assignment to readonly var" and "putenv error"
7665 bb_putchar_stderr('\n');
7666 /* Redirect error sets $? to 1. Otherwise,
7667 * if evaluating assignment value set $?, retain it.
7668 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7670 rcode = G.last_exitcode;
7671 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7673 debug_printf_exec("run_pipe: return %d\n", rcode);
7678 /* Expand the rest into (possibly) many strings each */
7679 #if ENABLE_HUSH_BASH_COMPAT
7680 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7681 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7685 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7688 /* if someone gives us an empty string: `cmd with empty output` */
7689 if (!argv_expanded[0]) {
7690 free(argv_expanded);
7692 return G.last_exitcode;
7695 x = find_builtin(argv_expanded[0]);
7696 #if ENABLE_HUSH_FUNCTIONS
7699 funcp = find_function(argv_expanded[0]);
7703 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7704 debug_printf("exec with redirects only\n");
7705 rcode = setup_redirects(command, NULL);
7706 /* rcode=1 can be if redir file can't be opened */
7707 goto clean_up_and_ret1;
7710 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7713 debug_printf_exec(": builtin '%s' '%s'...\n",
7714 x->b_cmd, argv_expanded[1]);
7716 rcode = x->b_function(argv_expanded) & 0xff;
7719 #if ENABLE_HUSH_FUNCTIONS
7721 # if ENABLE_HUSH_LOCAL
7722 struct variable **sv;
7723 sv = G.shadowed_vars_pp;
7724 G.shadowed_vars_pp = &old_vars;
7726 debug_printf_exec(": function '%s' '%s'...\n",
7727 funcp->name, argv_expanded[1]);
7728 rcode = run_function(funcp, argv_expanded) & 0xff;
7729 # if ENABLE_HUSH_LOCAL
7730 G.shadowed_vars_pp = sv;
7736 unset_vars(new_env);
7738 /* clean_up_and_ret0: */
7739 restore_redirects(squirrel);
7741 free(argv_expanded);
7742 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7744 debug_printf_exec("run_pipe return %d\n", rcode);
7748 if (ENABLE_FEATURE_SH_NOFORK) {
7749 int n = find_applet_by_name(argv_expanded[0]);
7750 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7751 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7753 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7754 argv_expanded[0], argv_expanded[1]);
7755 rcode = run_nofork_applet(n, argv_expanded);
7757 goto clean_up_and_ret;
7760 /* It is neither builtin nor applet. We must fork. */
7764 /* NB: argv_expanded may already be created, and that
7765 * might include `cmd` runs! Do not rerun it! We *must*
7766 * use argv_expanded if it's non-NULL */
7768 /* Going to fork a child per each pipe member */
7773 while (cmd_no < pi->num_cmds) {
7774 struct fd_pair pipefds;
7776 volatile nommu_save_t nommu_save;
7777 nommu_save.new_env = NULL;
7778 nommu_save.old_vars = NULL;
7779 nommu_save.argv = NULL;
7780 nommu_save.argv_from_re_execing = NULL;
7782 command = &pi->cmds[cmd_no];
7784 if (command->argv) {
7785 debug_printf_exec(": pipe member '%s' '%s'...\n",
7786 command->argv[0], command->argv[1]);
7788 debug_printf_exec(": pipe member with no argv\n");
7791 /* pipes are inserted between pairs of commands */
7794 if (cmd_no < pi->num_cmds)
7795 xpiped_pair(pipefds);
7797 command->pid = BB_MMU ? fork() : vfork();
7798 if (!command->pid) { /* child */
7800 disable_restore_tty_pgrp_on_exit();
7801 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7803 /* Every child adds itself to new process group
7804 * with pgid == pid_of_first_child_in_pipe */
7805 if (G.run_list_level == 1 && G_interactive_fd) {
7808 if (pgrp < 0) /* true for 1st process only */
7810 if (setpgid(0, pgrp) == 0
7811 && pi->followup != PIPE_BG
7812 && G_saved_tty_pgrp /* we have ctty */
7814 /* We do it in *every* child, not just first,
7816 tcsetpgrp(G_interactive_fd, pgrp);
7820 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7821 /* 1st cmd in backgrounded pipe
7822 * should have its stdin /dev/null'ed */
7824 if (open(bb_dev_null, O_RDONLY))
7825 xopen("/", O_RDONLY);
7827 xmove_fd(next_infd, 0);
7829 xmove_fd(pipefds.wr, 1);
7832 /* Like bash, explicit redirects override pipes,
7833 * and the pipe fd (fd#1) is available for dup'ing:
7834 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7835 * of cmd1 goes into pipe.
7837 if (setup_redirects(command, NULL)) {
7838 /* Happens when redir file can't be opened:
7839 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7841 * hush: can't open '/qwe/rty': No such file or directory
7843 * (echo BAR is not executed, it hits _exit(1) below)
7848 /* Stores to nommu_save list of env vars putenv'ed
7849 * (NOMMU, on MMU we don't need that) */
7850 /* cast away volatility... */
7851 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7852 /* pseudo_exec() does not return */
7855 /* parent or error */
7856 #if ENABLE_HUSH_FAST
7858 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7860 enable_restore_tty_pgrp_on_exit();
7862 /* Clean up after vforked child */
7863 free(nommu_save.argv);
7864 free(nommu_save.argv_from_re_execing);
7865 unset_vars(nommu_save.new_env);
7866 add_vars(nommu_save.old_vars);
7868 free(argv_expanded);
7869 argv_expanded = NULL;
7870 if (command->pid < 0) { /* [v]fork failed */
7871 /* Clearly indicate, was it fork or vfork */
7872 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7876 /* Second and next children need to know pid of first one */
7878 pi->pgrp = command->pid;
7884 if (cmd_no < pi->num_cmds)
7886 /* Pass read (output) pipe end to next iteration */
7887 next_infd = pipefds.rd;
7890 if (!pi->alive_cmds) {
7892 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7897 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7901 /* NB: called by pseudo_exec, and therefore must not modify any
7902 * global data until exec/_exit (we can be a child after vfork!) */
7903 static int run_list(struct pipe *pi)
7905 #if ENABLE_HUSH_CASE
7906 char *case_word = NULL;
7908 #if ENABLE_HUSH_LOOPS
7909 struct pipe *loop_top = NULL;
7910 char **for_lcur = NULL;
7911 char **for_list = NULL;
7913 smallint last_followup;
7915 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7916 smalluint cond_code = 0;
7918 enum { cond_code = 0 };
7921 smallint rword; /* RES_foo */
7922 smallint last_rword; /* ditto */
7925 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7928 #if ENABLE_HUSH_LOOPS
7929 /* Check syntax for "for" */
7932 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7933 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7935 /* current word is FOR or IN (BOLD in comments below) */
7936 if (cpipe->next == NULL) {
7937 syntax_error("malformed for");
7939 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7942 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7943 if (cpipe->next->res_word == RES_DO)
7945 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7946 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7947 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7949 syntax_error("malformed for");
7951 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7958 /* Past this point, all code paths should jump to ret: label
7959 * in order to return, no direct "return" statements please.
7960 * This helps to ensure that no memory is leaked. */
7968 last_rword = RES_XXXX;
7970 last_followup = PIPE_SEQ;
7971 rcode = G.last_exitcode;
7973 /* Go through list of pipes, (maybe) executing them. */
7974 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7979 if (G_flag_return_in_progress == 1)
7982 IF_HAS_KEYWORDS(rword = pi->res_word;)
7983 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7984 rword, cond_code, last_rword);
7985 #if ENABLE_HUSH_LOOPS
7986 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7987 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7989 /* start of a loop: remember where loop starts */
7994 /* Still in the same "if...", "then..." or "do..." branch? */
7995 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7996 if ((rcode == 0 && last_followup == PIPE_OR)
7997 || (rcode != 0 && last_followup == PIPE_AND)
7999 /* It is "<true> || CMD" or "<false> && CMD"
8000 * and we should not execute CMD */
8001 debug_printf_exec("skipped cmd because of || or &&\n");
8002 last_followup = pi->followup;
8003 goto dont_check_jobs_but_continue;
8006 last_followup = pi->followup;
8007 IF_HAS_KEYWORDS(last_rword = rword;)
8010 if (rword == RES_THEN) {
8011 /* if false; then ... fi has exitcode 0! */
8012 G.last_exitcode = rcode = EXIT_SUCCESS;
8013 /* "if <false> THEN cmd": skip cmd */
8017 if (rword == RES_ELSE || rword == RES_ELIF) {
8018 /* "if <true> then ... ELSE/ELIF cmd":
8019 * skip cmd and all following ones */
8024 #if ENABLE_HUSH_LOOPS
8025 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8027 /* first loop through for */
8029 static const char encoded_dollar_at[] ALIGN1 = {
8030 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8031 }; /* encoded representation of "$@" */
8032 static const char *const encoded_dollar_at_argv[] = {
8033 encoded_dollar_at, NULL
8034 }; /* argv list with one element: "$@" */
8037 vals = (char**)encoded_dollar_at_argv;
8038 if (pi->next->res_word == RES_IN) {
8039 /* if no variable values after "in" we skip "for" */
8040 if (!pi->next->cmds[0].argv) {
8041 G.last_exitcode = rcode = EXIT_SUCCESS;
8042 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8045 vals = pi->next->cmds[0].argv;
8046 } /* else: "for var; do..." -> assume "$@" list */
8047 /* create list of variable values */
8048 debug_print_strings("for_list made from", vals);
8049 for_list = expand_strvec_to_strvec(vals);
8050 for_lcur = for_list;
8051 debug_print_strings("for_list", for_list);
8054 /* "for" loop is over, clean up */
8060 /* Insert next value from for_lcur */
8061 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8062 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
8065 if (rword == RES_IN) {
8066 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8068 if (rword == RES_DONE) {
8069 continue; /* "done" has no cmds too */
8072 #if ENABLE_HUSH_CASE
8073 if (rword == RES_CASE) {
8074 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8075 case_word = expand_strvec_to_string(pi->cmds->argv);
8078 if (rword == RES_MATCH) {
8081 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8082 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8084 /* all prev words didn't match, does this one match? */
8085 argv = pi->cmds->argv;
8087 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8088 /* TODO: which FNM_xxx flags to use? */
8089 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8091 if (cond_code == 0) { /* match! we will execute this branch */
8093 case_word = NULL; /* make future "word)" stop */
8100 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8101 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8103 continue; /* not matched yet, skip this pipe */
8105 if (rword == RES_ESAC) {
8106 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8108 /* "case" did not match anything: still set $? (to 0) */
8109 G.last_exitcode = rcode = EXIT_SUCCESS;
8113 /* Just pressing <enter> in shell should check for jobs.
8114 * OTOH, in non-interactive shell this is useless
8115 * and only leads to extra job checks */
8116 if (pi->num_cmds == 0) {
8117 if (G_interactive_fd)
8118 goto check_jobs_and_continue;
8122 /* After analyzing all keywords and conditions, we decided
8123 * to execute this pipe. NB: have to do checkjobs(NULL)
8124 * after run_pipe to collect any background children,
8125 * even if list execution is to be stopped. */
8126 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8127 #if ENABLE_HUSH_LOOPS
8128 G.flag_break_continue = 0;
8130 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8132 /* We ran a builtin, function, or group.
8133 * rcode is already known
8134 * and we don't need to wait for anything. */
8135 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8136 G.last_exitcode = rcode;
8137 check_and_run_traps();
8138 #if ENABLE_HUSH_LOOPS
8139 /* Was it "break" or "continue"? */
8140 if (G.flag_break_continue) {
8141 smallint fbc = G.flag_break_continue;
8142 /* We might fall into outer *loop*,
8143 * don't want to break it too */
8145 G.depth_break_continue--;
8146 if (G.depth_break_continue == 0)
8147 G.flag_break_continue = 0;
8148 /* else: e.g. "continue 2" should *break* once, *then* continue */
8149 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8150 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8151 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8154 /* "continue": simulate end of loop */
8159 if (G_flag_return_in_progress == 1) {
8160 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8163 } else if (pi->followup == PIPE_BG) {
8164 /* What does bash do with attempts to background builtins? */
8165 /* even bash 3.2 doesn't do that well with nested bg:
8166 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8167 * I'm NOT treating inner &'s as jobs */
8169 if (G.run_list_level == 1)
8172 /* Last command's pid goes to $! */
8173 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8174 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8175 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
8176 rcode = EXIT_SUCCESS;
8180 if (G.run_list_level == 1 && G_interactive_fd) {
8181 /* Waits for completion, then fg's main shell */
8182 rcode = checkjobs_and_fg_shell(pi);
8183 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8187 /* This one just waits for completion */
8188 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8189 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8191 G.last_exitcode = rcode;
8192 check_and_run_traps();
8195 /* Analyze how result affects subsequent commands */
8197 if (rword == RES_IF || rword == RES_ELIF)
8200 check_jobs_and_continue:
8201 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8202 dont_check_jobs_but_continue: ;
8203 #if ENABLE_HUSH_LOOPS
8204 /* Beware of "while false; true; do ..."! */
8206 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8207 /* check for RES_DONE is needed for "while ...; do \n done" case */
8209 if (rword == RES_WHILE) {
8211 /* "while false; do...done" - exitcode 0 */
8212 G.last_exitcode = rcode = EXIT_SUCCESS;
8213 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8217 if (rword == RES_UNTIL) {
8219 debug_printf_exec(": until expr is true: breaking\n");
8230 #if ENABLE_HUSH_LOOPS
8235 #if ENABLE_HUSH_CASE
8239 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8243 /* Select which version we will use */
8244 static int run_and_free_list(struct pipe *pi)
8247 debug_printf_exec("run_and_free_list entered\n");
8248 if (!G.o_opt[OPT_O_NOEXEC]) {
8249 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8250 rcode = run_list(pi);
8252 /* free_pipe_list has the side effect of clearing memory.
8253 * In the long run that function can be merged with run_list,
8254 * but doing that now would hobble the debugging effort. */
8256 debug_printf_exec("run_and_free_list return %d\n", rcode);
8261 static void install_sighandlers(unsigned mask)
8263 sighandler_t old_handler;
8265 while ((mask >>= 1) != 0) {
8269 old_handler = install_sighandler(sig, pick_sighandler(sig));
8270 /* POSIX allows shell to re-enable SIGCHLD
8271 * even if it was SIG_IGN on entry.
8272 * Therefore we skip IGN check for it:
8276 if (old_handler == SIG_IGN) {
8277 /* oops... restore back to IGN, and record this fact */
8278 install_sighandler(sig, old_handler);
8279 #if ENABLE_HUSH_TRAP
8281 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8283 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8289 /* Called a few times only (or even once if "sh -c") */
8290 static void install_special_sighandlers(void)
8294 /* Which signals are shell-special? */
8295 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8296 if (G_interactive_fd) {
8297 mask |= SPECIAL_INTERACTIVE_SIGS;
8298 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8299 mask |= SPECIAL_JOBSTOP_SIGS;
8301 /* Careful, do not re-install handlers we already installed */
8302 if (G.special_sig_mask != mask) {
8303 unsigned diff = mask & ~G.special_sig_mask;
8304 G.special_sig_mask = mask;
8305 install_sighandlers(diff);
8311 /* Set handlers to restore tty pgrp and exit */
8312 static void install_fatal_sighandlers(void)
8316 /* We will restore tty pgrp on these signals */
8318 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8319 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8320 + (1 << SIGBUS ) * HUSH_DEBUG
8321 + (1 << SIGSEGV) * HUSH_DEBUG
8322 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8324 /* bash 3.2 seems to handle these just like 'fatal' ones */
8327 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8328 * if we aren't interactive... but in this case
8329 * we never want to restore pgrp on exit, and this fn is not called
8331 /*+ (1 << SIGHUP )*/
8332 /*+ (1 << SIGTERM)*/
8333 /*+ (1 << SIGINT )*/
8335 G_fatal_sig_mask = mask;
8337 install_sighandlers(mask);
8341 static int set_mode(int state, char mode, const char *o_opt)
8346 G.o_opt[OPT_O_NOEXEC] = state;
8349 IF_HUSH_MODE_X(G_x_mode = state;)
8353 /* "set -+o" without parameter.
8354 * in bash, set -o produces this output:
8358 * We always use the second form.
8360 const char *p = o_opt_strings;
8363 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8369 idx = index_in_strings(o_opt_strings, o_opt);
8371 G.o_opt[idx] = state;
8375 return EXIT_FAILURE;
8377 return EXIT_SUCCESS;
8380 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8381 int hush_main(int argc, char **argv)
8384 OPT_login = (1 << 0),
8388 unsigned builtin_argc;
8390 struct variable *cur_var;
8391 struct variable *shell_ver;
8394 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8395 G.last_exitcode = EXIT_SUCCESS;
8397 #if ENABLE_HUSH_FAST
8398 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8401 G.argv0_for_re_execing = argv[0];
8403 /* Deal with HUSH_VERSION */
8404 shell_ver = xzalloc(sizeof(*shell_ver));
8405 shell_ver->flg_export = 1;
8406 shell_ver->flg_read_only = 1;
8407 /* Code which handles ${var<op>...} needs writable values for all variables,
8408 * therefore we xstrdup: */
8409 shell_ver->varstr = xstrdup(hush_version_str);
8410 /* Create shell local variables from the values
8411 * currently living in the environment */
8412 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8413 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8414 G.top_var = shell_ver;
8415 cur_var = G.top_var;
8418 char *value = strchr(*e, '=');
8419 if (value) { /* paranoia */
8420 cur_var->next = xzalloc(sizeof(*cur_var));
8421 cur_var = cur_var->next;
8422 cur_var->varstr = *e;
8423 cur_var->max_len = strlen(*e);
8424 cur_var->flg_export = 1;
8428 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8429 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8430 putenv(shell_ver->varstr);
8433 set_pwd_var(/*exp:*/ 1);
8435 #if ENABLE_HUSH_BASH_COMPAT
8436 /* Set (but not export) HOSTNAME unless already set */
8437 if (!get_local_var_value("HOSTNAME")) {
8440 set_local_var_from_halves("HOSTNAME", uts.nodename);
8442 /* bash also exports SHLVL and _,
8443 * and sets (but doesn't export) the following variables:
8445 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8446 * BASH_VERSION='3.2.0(1)-release'
8448 * MACHTYPE=i386-pc-linux-gnu
8450 * PPID=<NNNNN> - we also do it elsewhere
8461 * PIPESTATUS=([0]="0")
8462 * HISTFILE=/<xxx>/.bash_history
8466 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8468 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8479 #if ENABLE_FEATURE_EDITING
8480 G.line_input_state = new_line_input_t(FOR_SHELL);
8483 /* Initialize some more globals to non-zero values */
8484 cmdedit_update_prompt();
8486 die_func = restore_ttypgrp_and__exit;
8488 /* Shell is non-interactive at first. We need to call
8489 * install_special_sighandlers() if we are going to execute "sh <script>",
8490 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8491 * If we later decide that we are interactive, we run install_special_sighandlers()
8492 * in order to intercept (more) signals.
8496 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8497 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8500 opt = getopt(argc, argv, "+c:xinsl"
8503 # if ENABLE_HUSH_FUNCTIONS
8513 * sh ... -c 'script'
8514 * sh ... -c 'script' ARG0 [ARG1...]
8515 * On NOMMU, if builtin_argc != 0,
8516 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8517 * "" needs to be replaced with NULL
8518 * and BARGV vector fed to builtin function.
8519 * Note: the form without ARG0 never happens:
8520 * sh ... -c 'builtin' BARGV... ""
8523 G.root_pid = getpid();
8524 G.root_ppid = getppid();
8526 G.global_argv = argv + optind;
8527 G.global_argc = argc - optind;
8529 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8530 const struct built_in_command *x;
8532 install_special_sighandlers();
8533 x = find_builtin(optarg);
8534 if (x) { /* paranoia */
8535 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8536 G.global_argv += builtin_argc;
8537 G.global_argv[-1] = NULL; /* replace "" */
8539 G.last_exitcode = x->b_function(argv + optind - 1);
8543 if (!G.global_argv[0]) {
8544 /* -c 'script' (no params): prevent empty $0 */
8545 G.global_argv--; /* points to argv[i] of 'script' */
8546 G.global_argv[0] = argv[0];
8548 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8549 install_special_sighandlers();
8550 parse_and_run_string(optarg);
8553 /* Well, we cannot just declare interactiveness,
8554 * we have to have some stuff (ctty, etc) */
8555 /* G_interactive_fd++; */
8558 /* "-s" means "read from stdin", but this is how we always
8559 * operate, so simply do nothing here. */
8565 case '<': /* "big heredoc" support */
8566 full_write1_str(optarg);
8569 unsigned long long empty_trap_mask;
8571 G.root_pid = bb_strtou(optarg, &optarg, 16);
8573 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8575 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8577 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8579 builtin_argc = bb_strtou(optarg, &optarg, 16);
8581 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8582 if (empty_trap_mask != 0) {
8584 install_special_sighandlers();
8585 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8586 for (sig = 1; sig < NSIG; sig++) {
8587 if (empty_trap_mask & (1LL << sig)) {
8588 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8589 install_sighandler(sig, SIG_IGN);
8593 # if ENABLE_HUSH_LOOPS
8595 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8601 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8603 # if ENABLE_HUSH_FUNCTIONS
8605 struct function *funcp = new_function(optarg);
8606 /* funcp->name is already set to optarg */
8607 /* funcp->body is set to NULL. It's a special case. */
8608 funcp->body_as_string = argv[optind];
8616 if (set_mode(1, opt, NULL) == 0) /* no error */
8620 fprintf(stderr, "Usage: sh [FILE]...\n"
8621 " or: sh -c command [args]...\n\n");
8627 } /* option parsing loop */
8629 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8630 G.global_argc = argc - (optind - 1);
8631 G.global_argv = argv + (optind - 1);
8632 G.global_argv[0] = argv[0];
8635 G.root_pid = getpid();
8636 G.root_ppid = getppid();
8639 /* If we are login shell... */
8640 if (flags & OPT_login) {
8642 debug_printf("sourcing /etc/profile\n");
8643 input = fopen_for_read("/etc/profile");
8644 if (input != NULL) {
8645 remember_FILE(input);
8646 install_special_sighandlers();
8647 parse_and_run_file(input);
8648 fclose_and_forget(input);
8650 /* bash: after sourcing /etc/profile,
8651 * tries to source (in the given order):
8652 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8653 * stopping on first found. --noprofile turns this off.
8654 * bash also sources ~/.bash_logout on exit.
8655 * If called as sh, skips .bash_XXX files.
8659 if (G.global_argv[1]) {
8662 * "bash <script>" (which is never interactive (unless -i?))
8663 * sources $BASH_ENV here (without scanning $PATH).
8664 * If called as sh, does the same but with $ENV.
8665 * Also NB, per POSIX, $ENV should undergo parameter expansion.
8669 debug_printf("running script '%s'\n", G.global_argv[0]);
8670 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
8671 input = xfopen_for_read(G.global_argv[0]);
8672 xfunc_error_retval = 1;
8673 remember_FILE(input);
8674 install_special_sighandlers();
8675 parse_and_run_file(input);
8676 #if ENABLE_FEATURE_CLEAN_UP
8677 fclose_and_forget(input);
8682 /* Up to here, shell was non-interactive. Now it may become one.
8683 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8686 /* A shell is interactive if the '-i' flag was given,
8687 * or if all of the following conditions are met:
8689 * no arguments remaining or the -s flag given
8690 * standard input is a terminal
8691 * standard output is a terminal
8692 * Refer to Posix.2, the description of the 'sh' utility.
8695 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8696 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8697 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8698 if (G_saved_tty_pgrp < 0)
8699 G_saved_tty_pgrp = 0;
8701 /* try to dup stdin to high fd#, >= 255 */
8702 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8703 if (G_interactive_fd < 0) {
8704 /* try to dup to any fd */
8705 G_interactive_fd = dup(STDIN_FILENO);
8706 if (G_interactive_fd < 0) {
8708 G_interactive_fd = 0;
8709 G_saved_tty_pgrp = 0;
8712 // TODO: track & disallow any attempts of user
8713 // to (inadvertently) close/redirect G_interactive_fd
8715 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8716 if (G_interactive_fd) {
8717 close_on_exec_on(G_interactive_fd);
8719 if (G_saved_tty_pgrp) {
8720 /* If we were run as 'hush &', sleep until we are
8721 * in the foreground (tty pgrp == our pgrp).
8722 * If we get started under a job aware app (like bash),
8723 * make sure we are now in charge so we don't fight over
8724 * who gets the foreground */
8726 pid_t shell_pgrp = getpgrp();
8727 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8728 if (G_saved_tty_pgrp == shell_pgrp)
8730 /* send TTIN to ourself (should stop us) */
8731 kill(- shell_pgrp, SIGTTIN);
8735 /* Install more signal handlers */
8736 install_special_sighandlers();
8738 if (G_saved_tty_pgrp) {
8739 /* Set other signals to restore saved_tty_pgrp */
8740 install_fatal_sighandlers();
8741 /* Put ourselves in our own process group
8742 * (bash, too, does this only if ctty is available) */
8743 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8744 /* Grab control of the terminal */
8745 tcsetpgrp(G_interactive_fd, getpid());
8747 enable_restore_tty_pgrp_on_exit();
8749 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8751 const char *hp = get_local_var_value("HISTFILE");
8753 hp = get_local_var_value("HOME");
8755 hp = concat_path_file(hp, ".hush_history");
8760 G.line_input_state->hist_file = hp;
8761 //set_local_var(xasprintf("HISTFILE=%s", ...));
8763 # if ENABLE_FEATURE_SH_HISTFILESIZE
8764 hp = get_local_var_value("HISTFILESIZE");
8765 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8770 install_special_sighandlers();
8772 #elif ENABLE_HUSH_INTERACTIVE
8773 /* No job control compiled in, only prompt/line editing */
8774 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8775 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8776 if (G_interactive_fd < 0) {
8777 /* try to dup to any fd */
8778 G_interactive_fd = dup(STDIN_FILENO);
8779 if (G_interactive_fd < 0)
8781 G_interactive_fd = 0;
8784 if (G_interactive_fd) {
8785 close_on_exec_on(G_interactive_fd);
8787 install_special_sighandlers();
8789 /* We have interactiveness code disabled */
8790 install_special_sighandlers();
8793 * if interactive but not a login shell, sources ~/.bashrc
8794 * (--norc turns this off, --rcfile <file> overrides)
8797 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8798 /* note: ash and hush share this string */
8799 printf("\n\n%s %s\n"
8800 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8803 "hush - the humble shell"
8807 parse_and_run_file(stdin);
8810 hush_exit(G.last_exitcode);
8815 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8816 int msh_main(int argc, char **argv)
8818 bb_error_msg("msh is deprecated, please use hush instead");
8819 return hush_main(argc, argv);
8827 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8832 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8839 return applet_main_func(argc, argv - argc);
8842 static int FAST_FUNC builtin_test(char **argv)
8844 return run_applet_main(argv, test_main);
8846 #if ENABLE_HUSH_ECHO
8847 static int FAST_FUNC builtin_echo(char **argv)
8849 return run_applet_main(argv, echo_main);
8852 #if ENABLE_HUSH_PRINTF
8853 static int FAST_FUNC builtin_printf(char **argv)
8855 return run_applet_main(argv, printf_main);
8859 static char **skip_dash_dash(char **argv)
8862 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8867 static int FAST_FUNC builtin_eval(char **argv)
8869 int rcode = EXIT_SUCCESS;
8871 argv = skip_dash_dash(argv);
8873 char *str = expand_strvec_to_string(argv);
8875 * eval "echo Hi; done" ("done" is syntax error):
8876 * "echo Hi" will not execute too.
8878 parse_and_run_string(str);
8880 rcode = G.last_exitcode;
8885 static int FAST_FUNC builtin_cd(char **argv)
8889 argv = skip_dash_dash(argv);
8891 if (newdir == NULL) {
8892 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8893 * bash says "bash: cd: HOME not set" and does nothing
8896 const char *home = get_local_var_value("HOME");
8897 newdir = home ? home : "/";
8899 if (chdir(newdir)) {
8900 /* Mimic bash message exactly */
8901 bb_perror_msg("cd: %s", newdir);
8902 return EXIT_FAILURE;
8904 /* Read current dir (get_cwd(1) is inside) and set PWD.
8905 * Note: do not enforce exporting. If PWD was unset or unexported,
8906 * set it again, but do not export. bash does the same.
8908 set_pwd_var(/*exp:*/ 0);
8909 return EXIT_SUCCESS;
8912 static int FAST_FUNC builtin_exec(char **argv)
8914 argv = skip_dash_dash(argv);
8915 if (argv[0] == NULL)
8916 return EXIT_SUCCESS; /* bash does this */
8918 /* Careful: we can end up here after [v]fork. Do not restore
8919 * tty pgrp then, only top-level shell process does that */
8920 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8921 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8923 /* TODO: if exec fails, bash does NOT exit! We do.
8924 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8925 * and tcsetpgrp, and this is inherently racy.
8927 execvp_or_die(argv);
8930 static int FAST_FUNC builtin_exit(char **argv)
8932 debug_printf_exec("%s()\n", __func__);
8934 /* interactive bash:
8935 * # trap "echo EEE" EXIT
8938 * There are stopped jobs.
8939 * (if there are _stopped_ jobs, running ones don't count)
8942 * EEE (then bash exits)
8944 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8947 /* note: EXIT trap is run by hush_exit */
8948 argv = skip_dash_dash(argv);
8949 if (argv[0] == NULL)
8950 hush_exit(G.last_exitcode);
8951 /* mimic bash: exit 123abc == exit 255 + error msg */
8952 xfunc_error_retval = 255;
8953 /* bash: exit -2 == exit 254, no error msg */
8954 hush_exit(xatoi(argv[0]) & 0xff);
8957 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
8958 static void print_escaped(const char *s)
8963 const char *p = strchrnul(s, '\'');
8964 /* print 'xxxx', possibly just '' */
8965 printf("'%.*s'", (int)(p - s), s);
8970 /* s points to '; print "'''...'''" */
8972 do putchar('\''); while (*++s == '\'');
8978 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL
8979 # if !ENABLE_HUSH_LOCAL
8980 #define helper_export_local(argv, exp, lvl) \
8981 helper_export_local(argv, exp)
8983 static void helper_export_local(char **argv, int exp, int lvl)
8987 char *name_end = strchrnul(name, '=');
8989 /* So far we do not check that name is valid (TODO?) */
8991 if (*name_end == '\0') {
8992 struct variable *var, **vpp;
8994 vpp = get_ptr_to_local_var(name, name_end - name);
8995 var = vpp ? *vpp : NULL;
8997 if (exp == -1) { /* unexporting? */
8998 /* export -n NAME (without =VALUE) */
9000 var->flg_export = 0;
9001 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9003 } /* else: export -n NOT_EXISTING_VAR: no-op */
9006 if (exp == 1) { /* exporting? */
9007 /* export NAME (without =VALUE) */
9009 var->flg_export = 1;
9010 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9011 putenv(var->varstr);
9015 # if ENABLE_HUSH_LOCAL
9016 if (exp == 0 /* local? */
9017 && var && var->func_nest_level == lvl
9019 /* "local x=abc; ...; local x" - ignore second local decl */
9023 /* Exporting non-existing variable.
9024 * bash does not put it in environment,
9025 * but remembers that it is exported,
9026 * and does put it in env when it is set later.
9027 * We just set it to "" and export. */
9028 /* Or, it's "local NAME" (without =VALUE).
9029 * bash sets the value to "". */
9030 name = xasprintf("%s=", name);
9032 /* (Un)exporting/making local NAME=VALUE */
9033 name = xstrdup(name);
9035 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
9040 #if ENABLE_HUSH_EXPORT
9041 static int FAST_FUNC builtin_export(char **argv)
9043 unsigned opt_unexport;
9045 #if ENABLE_HUSH_EXPORT_N
9046 /* "!": do not abort on errors */
9047 opt_unexport = getopt32(argv, "!n");
9048 if (opt_unexport == (uint32_t)-1)
9049 return EXIT_FAILURE;
9056 if (argv[0] == NULL) {
9063 /* ash emits: export VAR='VAL'
9064 * bash: declare -x VAR="VAL"
9065 * we follow ash example */
9066 const char *s = *e++;
9067 const char *p = strchr(s, '=');
9069 if (!p) /* wtf? take next variable */
9072 printf("export %.*s", (int)(p - s) + 1, s);
9073 print_escaped(p + 1);
9077 /*fflush_all(); - done after each builtin anyway */
9079 return EXIT_SUCCESS;
9082 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
9084 return EXIT_SUCCESS;
9088 #if ENABLE_HUSH_LOCAL
9089 static int FAST_FUNC builtin_local(char **argv)
9091 if (G.func_nest_level == 0) {
9092 bb_error_msg("%s: not in a function", argv[0]);
9093 return EXIT_FAILURE; /* bash compat */
9095 helper_export_local(argv, 0, G.func_nest_level);
9096 return EXIT_SUCCESS;
9100 #if ENABLE_HUSH_UNSET
9101 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9102 static int FAST_FUNC builtin_unset(char **argv)
9107 /* "!": do not abort on errors */
9108 /* "+": stop at 1st non-option */
9109 opts = getopt32(argv, "!+vf");
9110 if (opts == (unsigned)-1)
9111 return EXIT_FAILURE;
9113 bb_error_msg("unset: -v and -f are exclusive");
9114 return EXIT_FAILURE;
9120 if (!(opts & 2)) { /* not -f */
9121 if (unset_local_var(*argv)) {
9122 /* unset <nonexistent_var> doesn't fail.
9123 * Error is when one tries to unset RO var.
9124 * Message was printed by unset_local_var. */
9128 # if ENABLE_HUSH_FUNCTIONS
9140 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9141 * built-in 'set' handler
9143 * set [-abCefhmnuvx] [-o option] [argument...]
9144 * set [+abCefhmnuvx] [+o option] [argument...]
9145 * set -- [argument...]
9148 * Implementations shall support the options in both their hyphen and
9149 * plus-sign forms. These options can also be specified as options to sh.
9151 * Write out all variables and their values: set
9152 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9153 * Turn on the -x and -v options: set -xv
9154 * Unset all positional parameters: set --
9155 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9156 * Set the positional parameters to the expansion of x, even if x expands
9157 * with a leading '-' or '+': set -- $x
9159 * So far, we only support "set -- [argument...]" and some of the short names.
9161 static int FAST_FUNC builtin_set(char **argv)
9164 char **pp, **g_argv;
9165 char *arg = *++argv;
9169 for (e = G.top_var; e; e = e->next)
9171 return EXIT_SUCCESS;
9175 if (strcmp(arg, "--") == 0) {
9179 if (arg[0] != '+' && arg[0] != '-')
9181 for (n = 1; arg[n]; ++n) {
9182 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9184 if (arg[n] == 'o' && argv[1])
9187 } while ((arg = *++argv) != NULL);
9188 /* Now argv[0] is 1st argument */
9191 return EXIT_SUCCESS;
9194 /* NB: G.global_argv[0] ($0) is never freed/changed */
9195 g_argv = G.global_argv;
9196 if (G.global_args_malloced) {
9202 G.global_args_malloced = 1;
9203 pp = xzalloc(sizeof(pp[0]) * 2);
9204 pp[0] = g_argv[0]; /* retain $0 */
9207 /* This realloc's G.global_argv */
9208 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9215 return EXIT_SUCCESS;
9217 /* Nothing known, so abort */
9219 bb_error_msg("set: %s: invalid option", arg);
9220 return EXIT_FAILURE;
9224 static int FAST_FUNC builtin_shift(char **argv)
9227 argv = skip_dash_dash(argv);
9231 if (n >= 0 && n < G.global_argc) {
9232 if (G_global_args_malloced) {
9235 free(G.global_argv[m++]);
9238 memmove(&G.global_argv[1], &G.global_argv[n+1],
9239 G.global_argc * sizeof(G.global_argv[0]));
9240 return EXIT_SUCCESS;
9242 return EXIT_FAILURE;
9245 #if ENABLE_HUSH_READ
9246 /* Interruptibility of read builtin in bash
9247 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9249 * Empty trap makes read ignore corresponding signal, for any signal.
9252 * - terminates non-interactive shell;
9253 * - interrupts read in interactive shell;
9254 * if it has non-empty trap:
9255 * - executes trap and returns to command prompt in interactive shell;
9256 * - executes trap and returns to read in non-interactive shell;
9258 * - is ignored (does not interrupt) read in interactive shell;
9259 * - terminates non-interactive shell;
9260 * if it has non-empty trap:
9261 * - executes trap and returns to read;
9263 * - terminates shell (regardless of interactivity);
9264 * if it has non-empty trap:
9265 * - executes trap and returns to read;
9267 static int FAST_FUNC builtin_read(char **argv)
9277 /* "!": do not abort on errors.
9278 * Option string must start with "sr" to match BUILTIN_READ_xxx
9280 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9281 if (read_flags == (uint32_t)-1)
9282 return EXIT_FAILURE;
9284 ifs = get_local_var_value("IFS"); /* can be NULL */
9287 r = shell_builtin_read(set_local_var_from_halves,
9297 if ((uintptr_t)r == 1 && errno == EINTR) {
9298 unsigned sig = check_and_run_traps();
9299 if (sig && sig != SIGINT)
9303 if ((uintptr_t)r > 1) {
9304 bb_error_msg("%s", r);
9305 r = (char*)(uintptr_t)1;
9308 return (uintptr_t)r;
9312 #if ENABLE_HUSH_TRAP
9313 static int FAST_FUNC builtin_trap(char **argv)
9319 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9324 /* No args: print all trapped */
9325 for (i = 0; i < NSIG; ++i) {
9328 print_escaped(G_traps[i]);
9329 /* note: bash adds "SIG", but only if invoked
9330 * as "bash". If called as "sh", or if set -o posix,
9331 * then it prints short signal names.
9332 * We are printing short names: */
9333 printf(" %s\n", get_signame(i));
9336 /*fflush_all(); - done after each builtin anyway */
9337 return EXIT_SUCCESS;
9341 /* If first arg is a number: reset all specified signals */
9342 sig = bb_strtou(*argv, NULL, 10);
9348 sighandler_t handler;
9350 sig = get_signum(*argv++);
9351 if (sig < 0 || sig >= NSIG) {
9353 /* Mimic bash message exactly */
9354 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
9359 G_traps[sig] = xstrdup(new_cmd);
9361 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
9362 get_signame(sig), sig, G_traps[sig]);
9364 /* There is no signal for 0 (EXIT) */
9369 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9371 /* We are removing trap handler */
9372 handler = pick_sighandler(sig);
9373 install_sighandler(sig, handler);
9378 if (!argv[1]) { /* no second arg */
9379 bb_error_msg("trap: invalid arguments");
9380 return EXIT_FAILURE;
9383 /* First arg is "-": reset all specified to default */
9384 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9385 /* Everything else: set arg as signal handler
9386 * (includes "" case, which ignores signal) */
9387 if (argv[0][0] == '-') {
9388 if (argv[0][1] == '\0') { /* "-" */
9389 /* new_cmd remains NULL: "reset these sigs" */
9392 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9395 /* else: "-something", no special meaning */
9400 goto process_sig_list;
9404 #if ENABLE_HUSH_TYPE
9405 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9406 static int FAST_FUNC builtin_type(char **argv)
9408 int ret = EXIT_SUCCESS;
9414 if (0) {} /* make conditional compile easier below */
9415 /*else if (find_alias(*argv))
9416 type = "an alias";*/
9417 #if ENABLE_HUSH_FUNCTIONS
9418 else if (find_function(*argv))
9419 type = "a function";
9421 else if (find_builtin(*argv))
9422 type = "a shell builtin";
9423 else if ((path = find_in_path(*argv)) != NULL)
9426 bb_error_msg("type: %s: not found", *argv);
9431 printf("%s is %s\n", *argv, type);
9440 static struct pipe *parse_jobspec(const char *str)
9445 if (sscanf(str, "%%%u", &jobnum) != 1) {
9447 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
9449 bb_error_msg("bad argument '%s'", str);
9452 /* It is "%%", "%+" or "%" - current job */
9453 jobnum = G.last_jobid;
9455 bb_error_msg("no current job");
9459 for (pi = G.job_list; pi; pi = pi->next) {
9460 if (pi->jobid == jobnum) {
9464 bb_error_msg("%u: no such job", jobnum);
9468 /* built-in 'fg' and 'bg' handler */
9469 static int FAST_FUNC builtin_fg_bg(char **argv)
9474 if (!G_interactive_fd)
9475 return EXIT_FAILURE;
9477 /* If they gave us no args, assume they want the last backgrounded task */
9479 for (pi = G.job_list; pi; pi = pi->next) {
9480 if (pi->jobid == G.last_jobid) {
9484 bb_error_msg("%s: no current job", argv[0]);
9485 return EXIT_FAILURE;
9488 pi = parse_jobspec(argv[1]);
9490 return EXIT_FAILURE;
9492 /* TODO: bash prints a string representation
9493 * of job being foregrounded (like "sleep 1 | cat") */
9494 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
9495 /* Put the job into the foreground. */
9496 tcsetpgrp(G_interactive_fd, pi->pgrp);
9499 /* Restart the processes in the job */
9500 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9501 for (i = 0; i < pi->num_cmds; i++) {
9502 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
9504 pi->stopped_cmds = 0;
9506 i = kill(- pi->pgrp, SIGCONT);
9508 if (errno == ESRCH) {
9509 delete_finished_bg_job(pi);
9510 return EXIT_SUCCESS;
9512 bb_perror_msg("kill (SIGCONT)");
9515 if (argv[0][0] == 'f') {
9517 return checkjobs_and_fg_shell(pi);
9519 return EXIT_SUCCESS;
9523 #if ENABLE_HUSH_HELP
9524 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9526 const struct built_in_command *x;
9529 "Built-in commands:\n"
9530 "------------------\n");
9531 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9533 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9535 return EXIT_SUCCESS;
9539 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9540 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9542 show_history(G.line_input_state);
9543 return EXIT_SUCCESS;
9548 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9551 const char *status_string;
9553 checkjobs(NULL, 0 /*(no pid to wait for)*/);
9554 for (job = G.job_list; job; job = job->next) {
9555 if (job->alive_cmds == job->stopped_cmds)
9556 status_string = "Stopped";
9558 status_string = "Running";
9560 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9562 return EXIT_SUCCESS;
9566 #if ENABLE_HUSH_MEMLEAK
9567 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
9572 # ifdef M_TRIM_THRESHOLD
9573 /* Optional. Reduces probability of false positives */
9576 /* Crude attempt to find where "free memory" starts,
9577 * sans fragmentation. */
9579 l = (unsigned long)p;
9582 if (l < (unsigned long)p) l = (unsigned long)p;
9588 struct mallinfo mi = mallinfo();
9589 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9590 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9594 if (!G.memleak_value)
9595 G.memleak_value = l;
9597 l -= G.memleak_value;
9604 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9609 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9612 return EXIT_SUCCESS;
9615 static int FAST_FUNC builtin_source(char **argv)
9617 char *arg_path, *filename;
9620 char *args_need_save;
9621 #if ENABLE_HUSH_FUNCTIONS
9625 argv = skip_dash_dash(argv);
9628 /* bash says: "bash: .: filename argument required" */
9629 return 2; /* bash compat */
9632 if (!strchr(filename, '/')) {
9633 arg_path = find_in_path(filename);
9635 filename = arg_path;
9637 input = remember_FILE(fopen_or_warn(filename, "r"));
9640 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9641 /* POSIX: non-interactive shell should abort here,
9642 * not merely fail. So far no one complained :)
9644 return EXIT_FAILURE;
9647 #if ENABLE_HUSH_FUNCTIONS
9648 sv_flg = G_flag_return_in_progress;
9649 /* "we are inside sourced file, ok to use return" */
9650 G_flag_return_in_progress = -1;
9652 args_need_save = argv[1]; /* used as a boolean variable */
9654 save_and_replace_G_args(&sv, argv);
9656 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9657 G.last_exitcode = 0;
9658 parse_and_run_file(input);
9659 fclose_and_forget(input);
9661 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
9662 restore_G_args(&sv, argv);
9663 #if ENABLE_HUSH_FUNCTIONS
9664 G_flag_return_in_progress = sv_flg;
9667 return G.last_exitcode;
9670 #if ENABLE_HUSH_UMASK
9671 static int FAST_FUNC builtin_umask(char **argv)
9678 argv = skip_dash_dash(argv);
9680 mode_t old_mask = mask;
9682 /* numeric umasks are taken as-is */
9683 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9684 if (!isdigit(argv[0][0]))
9686 mask = bb_parse_mode(argv[0], mask);
9687 if (!isdigit(argv[0][0]))
9689 if ((unsigned)mask > 0777) {
9692 * bash: umask: 'q': invalid symbolic mode operator
9693 * bash: umask: 999: octal number out of range
9695 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9700 printf("%04o\n", (unsigned) mask);
9701 /* fall through and restore mask which we set to 0 */
9705 return !rc; /* rc != 0 - success */
9709 #if ENABLE_HUSH_KILL
9710 static int FAST_FUNC builtin_kill(char **argv)
9714 # if ENABLE_HUSH_JOB
9715 if (argv[1] && strcmp(argv[1], "-l") != 0) {
9723 if (argv[i][0] != '%')
9726 * "kill %N" - job kill
9727 * Converting to pgrp / pid kill
9729 pi = parse_jobspec(argv[i]);
9731 /* Eat bad jobspec */
9735 argv[j - 1] = argv[j];
9742 * In jobs started under job control, we signal
9743 * entire process group by kill -PGRP_ID.
9744 * This happens, f.e., in interactive shell.
9746 * Otherwise, we signal each child via
9747 * kill PID1 PID2 PID3.
9749 * sh -c 'sleep 1|sleep 1 & kill %1'
9750 * sh -c 'true|sleep 2 & sleep 1; kill %1'
9751 * sh -c 'true|sleep 1 & sleep 2; kill %1'
9753 n = G_interactive_fd ? 1 : pi->num_cmds;
9754 dst = alloca(n * sizeof(int)*4);
9756 if (G_interactive_fd)
9757 dst += sprintf(dst, " -%u", (int)pi->pgrp);
9758 else for (j = 0; j < n; j++) {
9759 struct command *cmd = &pi->cmds[j];
9760 /* Skip exited members of the job */
9764 * kill_main has matching code to expect
9765 * leading space. Needed to not confuse
9766 * negative pids with "kill -SIGNAL_NO" syntax
9768 dst += sprintf(dst, " %u", (int)cmd->pid);
9771 } while (argv[++i]);
9775 if (argv[1] || ret == 0) {
9776 ret = run_applet_main(argv, kill_main);
9778 /* else: ret = 1, "kill %bad_jobspec" case */
9783 #if ENABLE_HUSH_WAIT
9784 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9785 #if !ENABLE_HUSH_JOB
9786 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9788 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
9795 if (!sigisemptyset(&G.pending_set))
9798 /* waitpid is not interruptible by SA_RESTARTed
9799 * signals which we use. Thus, this ugly dance:
9802 /* Make sure possible SIGCHLD is stored in kernel's
9803 * pending signal mask before we call waitpid.
9804 * Or else we may race with SIGCHLD, lose it,
9805 * and get stuck in sigsuspend...
9807 sigfillset(&oldset); /* block all signals, remember old set */
9808 sigprocmask(SIG_SETMASK, &oldset, &oldset);
9810 if (!sigisemptyset(&G.pending_set)) {
9811 /* Crap! we raced with some signal! */
9815 /*errno = 0; - checkjobs does this */
9816 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
9817 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
9818 debug_printf_exec("checkjobs:%d\n", ret);
9821 int rcode = job_exited_or_stopped(waitfor_pipe);
9822 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9825 sigprocmask(SIG_SETMASK, &oldset, NULL);
9830 /* if ECHILD, there are no children (ret is -1 or 0) */
9831 /* if ret == 0, no children changed state */
9832 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
9833 if (errno == ECHILD || ret) {
9835 if (ret < 0) /* if ECHILD, may need to fix "ret" */
9837 sigprocmask(SIG_SETMASK, &oldset, NULL);
9840 /* Wait for SIGCHLD or any other signal */
9841 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9842 /* Note: sigsuspend invokes signal handler */
9843 sigsuspend(&oldset);
9845 sigprocmask(SIG_SETMASK, &oldset, NULL);
9847 /* So, did we get a signal? */
9848 sig = check_and_run_traps();
9849 if (sig /*&& sig != SIGCHLD - always true */) {
9853 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9858 static int FAST_FUNC builtin_wait(char **argv)
9863 argv = skip_dash_dash(argv);
9864 if (argv[0] == NULL) {
9865 /* Don't care about wait results */
9866 /* Note 1: must wait until there are no more children */
9867 /* Note 2: must be interruptible */
9869 * $ sleep 3 & sleep 6 & wait
9874 * $ sleep 3 & sleep 6 & wait
9878 * ^C <-- after ~4 sec from keyboard
9881 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
9885 pid_t pid = bb_strtou(*argv, NULL, 10);
9886 if (errno || pid <= 0) {
9888 if (argv[0][0] == '%') {
9889 struct pipe *wait_pipe;
9890 ret = 127; /* bash compat for bad jobspecs */
9891 wait_pipe = parse_jobspec(*argv);
9893 ret = job_exited_or_stopped(wait_pipe);
9895 ret = wait_for_child_or_signal(wait_pipe, 0);
9897 /* else: parse_jobspec() already emitted error msg */
9901 /* mimic bash message */
9902 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9904 continue; /* bash checks all argv[] */
9907 /* Do we have such child? */
9908 ret = waitpid(pid, &status, WNOHANG);
9911 if (errno == ECHILD) {
9912 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9913 /* "wait $!" but last bg task has already exited. Try:
9914 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9915 * In bash it prints exitcode 0, then 3.
9916 * In dash, it is 127.
9918 /* ret = G.last_bg_pid_exitstatus - FIXME */
9920 /* Example: "wait 1". mimic bash message */
9921 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
9925 bb_perror_msg("wait %s", *argv);
9928 continue; /* bash checks all argv[] */
9931 /* Yes, and it still runs */
9932 ret = wait_for_child_or_signal(NULL, pid);
9934 /* Yes, and it just exited */
9935 process_wait_result(NULL, pid, status);
9936 ret = WEXITSTATUS(status);
9937 if (WIFSIGNALED(status))
9938 ret = 128 + WTERMSIG(status);
9946 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9947 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9950 def = bb_strtou(argv[1], NULL, 10);
9951 if (errno || def < def_min || argv[2]) {
9952 bb_error_msg("%s: bad arguments", argv[0]);
9960 #if ENABLE_HUSH_LOOPS
9961 static int FAST_FUNC builtin_break(char **argv)
9964 if (G.depth_of_loop == 0) {
9965 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9966 /* if we came from builtin_continue(), need to undo "= 1" */
9967 G.flag_break_continue = 0;
9968 return EXIT_SUCCESS; /* bash compat */
9970 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9972 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9973 if (depth == UINT_MAX)
9974 G.flag_break_continue = BC_BREAK;
9975 if (G.depth_of_loop < depth)
9976 G.depth_break_continue = G.depth_of_loop;
9978 return EXIT_SUCCESS;
9981 static int FAST_FUNC builtin_continue(char **argv)
9983 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9984 return builtin_break(argv);
9988 #if ENABLE_HUSH_FUNCTIONS
9989 static int FAST_FUNC builtin_return(char **argv)
9993 if (G_flag_return_in_progress != -1) {
9994 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9995 return EXIT_FAILURE; /* bash compat */
9998 G_flag_return_in_progress = 1;
10001 * out of range: wraps around at 256, does not error out
10002 * non-numeric param:
10003 * f() { false; return qwe; }; f; echo $?
10004 * bash: return: qwe: numeric argument required <== we do this
10005 * 255 <== we also do this
10007 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);