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>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
94 #if ENABLE_HUSH_RANDOM_SUPPORT
97 # define CLEAR_RANDOM_T(rnd) ((void)0)
100 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
103 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_LASH(APPLET(lash, _BB_DIR_BIN, _BB_SUID_DROP))
106 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
107 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
109 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
110 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
113 //config: bool "hush"
116 //config: hush is a small shell (25k). It handles the normal flow control
117 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
118 //config: case/esac. Redirections, here documents, $((arithmetic))
119 //config: and functions are supported.
121 //config: It will compile and work on no-mmu systems.
123 //config: It does not handle select, aliases, brace expansion,
124 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
126 //config:config HUSH_BASH_COMPAT
127 //config: bool "bash-compatible extensions"
129 //config: depends on HUSH
131 //config: Enable bash-compatible extensions.
133 //config:config HUSH_HELP
134 //config: bool "help builtin"
136 //config: depends on HUSH
138 //config: Enable help builtin in hush. Code size + ~1 kbyte.
140 //config:config HUSH_INTERACTIVE
141 //config: bool "Interactive mode"
143 //config: depends on HUSH
145 //config: Enable interactive mode (prompt and command editing).
146 //config: Without this, hush simply reads and executes commands
147 //config: from stdin just like a shell script from a file.
148 //config: No prompt, no PS1/PS2 magic shell variables.
150 //config:config HUSH_JOB
151 //config: bool "Job control"
153 //config: depends on HUSH_INTERACTIVE
155 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
156 //config: command (not entire shell), fg/bg builtins work. Without this option,
157 //config: "cmd &" still works by simply spawning a process and immediately
158 //config: prompting for next command (or executing next command in a script),
159 //config: but no separate process group is formed.
161 //config:config HUSH_TICK
162 //config: bool "Process substitution"
164 //config: depends on HUSH
166 //config: Enable process substitution `command` and $(command) in hush.
168 //config:config HUSH_IF
169 //config: bool "Support if/then/elif/else/fi"
171 //config: depends on HUSH
173 //config: Enable if/then/elif/else/fi in hush.
175 //config:config HUSH_LOOPS
176 //config: bool "Support for, while and until loops"
178 //config: depends on HUSH
180 //config: Enable for, while and until loops in hush.
182 //config:config HUSH_CASE
183 //config: bool "Support case ... esac statement"
185 //config: depends on HUSH
187 //config: Enable case ... esac statement in hush. +400 bytes.
189 //config:config HUSH_FUNCTIONS
190 //config: bool "Support funcname() { commands; } syntax"
192 //config: depends on HUSH
194 //config: Enable support for shell functions in hush. +800 bytes.
196 //config:config HUSH_LOCAL
197 //config: bool "Support local builtin"
199 //config: depends on HUSH_FUNCTIONS
201 //config: Enable support for local variables in functions.
203 //config:config HUSH_RANDOM_SUPPORT
204 //config: bool "Pseudorandom generator and $RANDOM variable"
206 //config: depends on HUSH
208 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
209 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
211 //config:config HUSH_EXPORT_N
212 //config: bool "Support 'export -n' option"
214 //config: depends on HUSH
216 //config: export -n unexports variables. It is a bash extension.
218 //config:config HUSH_MODE_X
219 //config: bool "Support 'hush -x' option and 'set -x' command"
221 //config: depends on HUSH
223 //config: This instructs hush to print commands before execution.
224 //config: Adds ~300 bytes.
227 //config: bool "lash (deprecated: aliased to hush)"
229 //config: select HUSH
231 //config: lash is deprecated and will be removed, please migrate to hush.
234 //config: bool "msh (deprecated: aliased to hush)"
236 //config: select HUSH
238 //config: msh is deprecated and will be removed, please migrate to hush.
241 //usage:#define hush_trivial_usage NOUSAGE_STR
242 //usage:#define hush_full_usage ""
243 //usage:#define lash_trivial_usage NOUSAGE_STR
244 //usage:#define lash_full_usage ""
245 //usage:#define msh_trivial_usage NOUSAGE_STR
246 //usage:#define msh_full_usage ""
250 #define LEAK_HUNTING 0
251 #define BUILD_AS_NOMMU 0
252 /* Enable/disable sanity checks. Ok to enable in production,
253 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
254 * Keeping 1 for now even in released versions.
257 /* Slightly bigger (+200 bytes), but faster hush.
258 * So far it only enables a trick with counting SIGCHLDs and forks,
259 * which allows us to do fewer waitpid's.
260 * (we can detect a case where neither forks were done nor SIGCHLDs happened
261 * and therefore waitpid will return the same result as last time)
263 #define ENABLE_HUSH_FAST 0
264 /* TODO: implement simplified code for users which do not need ${var%...} ops
265 * So far ${var%...} ops are always enabled:
267 #define ENABLE_HUSH_DOLLAR_OPS 1
272 # undef USE_FOR_NOMMU
275 # define USE_FOR_NOMMU(...) __VA_ARGS__
276 # define USE_FOR_MMU(...)
279 #include "NUM_APPLETS.h"
281 /* STANDALONE does not make sense, and won't compile */
282 # undef CONFIG_FEATURE_SH_STANDALONE
283 # undef ENABLE_FEATURE_SH_STANDALONE
284 # undef IF_FEATURE_SH_STANDALONE
285 # undef IF_NOT_FEATURE_SH_STANDALONE
286 # define ENABLE_FEATURE_SH_STANDALONE 0
287 # define IF_FEATURE_SH_STANDALONE(...)
288 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
291 #if !ENABLE_HUSH_INTERACTIVE
292 # undef ENABLE_FEATURE_EDITING
293 # define ENABLE_FEATURE_EDITING 0
294 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
295 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
298 /* Do we support ANY keywords? */
299 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
300 # define HAS_KEYWORDS 1
301 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
302 # define IF_HAS_NO_KEYWORDS(...)
304 # define HAS_KEYWORDS 0
305 # define IF_HAS_KEYWORDS(...)
306 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
309 /* If you comment out one of these below, it will be #defined later
310 * to perform debug printfs to stderr: */
311 #define debug_printf(...) do {} while (0)
312 /* Finer-grained debug switches */
313 #define debug_printf_parse(...) do {} while (0)
314 #define debug_print_tree(a, b) do {} while (0)
315 #define debug_printf_exec(...) do {} while (0)
316 #define debug_printf_env(...) do {} while (0)
317 #define debug_printf_jobs(...) do {} while (0)
318 #define debug_printf_expand(...) do {} while (0)
319 #define debug_printf_varexp(...) do {} while (0)
320 #define debug_printf_glob(...) do {} while (0)
321 #define debug_printf_list(...) do {} while (0)
322 #define debug_printf_subst(...) do {} while (0)
323 #define debug_printf_clean(...) do {} while (0)
325 #define ERR_PTR ((void*)(long)1)
327 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
329 #define _SPECIAL_VARS_STR "_*@$!?#"
330 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
331 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
332 #if ENABLE_HUSH_BASH_COMPAT
333 /* Support / and // replace ops */
334 /* Note that // is stored as \ in "encoded" string representation */
335 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
336 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
337 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
339 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
340 # define VAR_SUBST_OPS "%#:-=+?"
341 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
344 #define SPECIAL_VAR_SYMBOL 3
348 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
350 /* This supports saving pointers malloced in vfork child,
351 * to be freed in the parent.
354 typedef struct nommu_save_t {
356 struct variable *old_vars;
358 char **argv_from_re_execing;
362 typedef enum reserved_style {
371 #if ENABLE_HUSH_LOOPS
378 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
383 /* three pseudo-keywords support contrived "case" syntax: */
384 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
385 RES_MATCH , /* "word)" */
386 RES_CASE_BODY, /* "this command is inside CASE" */
393 typedef struct o_string {
395 int length; /* position where data is appended */
397 /* Protect newly added chars against globbing
398 * (by prepending \ to *, ?, [, \) */
401 /* At least some part of the string was inside '' or "",
402 * possibly empty one: word"", wo''rd etc. */
403 smallint has_quoted_part;
404 smallint has_empty_slot;
405 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
408 MAYBE_ASSIGNMENT = 0,
409 DEFINITELY_ASSIGNMENT = 1,
411 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
413 /* Used for initialization: o_string foo = NULL_O_STRING; */
414 #define NULL_O_STRING { NULL }
416 /* I can almost use ordinary FILE*. Is open_memstream() universally
417 * available? Where is it documented? */
418 typedef struct in_str {
420 /* eof_flag=1: last char in ->p is really an EOF */
421 char eof_flag; /* meaningless if ->p == NULL */
423 #if ENABLE_HUSH_INTERACTIVE
425 smallint promptmode; /* 0: PS1, 1: PS2 */
428 int (*get) (struct in_str *) FAST_FUNC;
429 int (*peek) (struct in_str *) FAST_FUNC;
431 #define i_getch(input) ((input)->get(input))
432 #define i_peek(input) ((input)->peek(input))
434 /* The descrip member of this structure is only used to make
435 * debugging output pretty */
436 static const struct {
438 signed char default_fd;
441 { O_RDONLY, 0, "<" },
442 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
443 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
444 { O_CREAT|O_RDWR, 1, "<>" },
445 { O_RDONLY, 0, "<<" },
446 /* Should not be needed. Bogus default_fd helps in debugging */
447 /* { O_RDONLY, 77, "<<" }, */
450 struct redir_struct {
451 struct redir_struct *next;
452 char *rd_filename; /* filename */
453 int rd_fd; /* fd to redirect */
454 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
456 smallint rd_type; /* (enum redir_type) */
457 /* note: for heredocs, rd_filename contains heredoc delimiter,
458 * and subsequently heredoc itself; and rd_dup is a bitmask:
459 * bit 0: do we need to trim leading tabs?
460 * bit 1: is heredoc quoted (<<'delim' syntax) ?
463 typedef enum redir_type {
465 REDIRECT_OVERWRITE = 1,
468 REDIRECT_HEREDOC = 4,
469 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
472 REDIRFD_SYNTAX_ERR = -2,
473 REDIRFD_TO_FILE = -1,
474 /* otherwise, rd_fd is redirected to rd_dup */
476 HEREDOC_SKIPTABS = 1,
482 pid_t pid; /* 0 if exited */
483 int assignment_cnt; /* how many argv[i] are assignments? */
484 smallint is_stopped; /* is the command currently running? */
485 smallint cmd_type; /* CMD_xxx */
487 #define CMD_SUBSHELL 1
489 /* used for "[[ EXPR ]]" */
490 #if ENABLE_HUSH_BASH_COMPAT
491 # define CMD_SINGLEWORD_NOGLOB 2
494 /* used for "export noglob=* glob* a=`echo a b`" */
495 //#define CMD_SINGLEWORD_NOGLOB_COND 3
496 // It is hard to implement correctly, it adds significant amounts of tricky code,
497 // and all this is only useful for really obscure export statements
498 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
499 // guards the code which implements it, but I have doubts it works
500 // in all cases (especially with mixed globbed/non-globbed arguments)
502 #if ENABLE_HUSH_FUNCTIONS
503 # define CMD_FUNCDEF 3
506 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
509 char *group_as_string;
511 #if ENABLE_HUSH_FUNCTIONS
512 struct function *child_func;
513 /* This field is used to prevent a bug here:
514 * while...do f1() {a;}; f1; f1() {b;}; f1; done
515 * When we execute "f1() {a;}" cmd, we create new function and clear
516 * cmd->group, cmd->group_as_string, cmd->argv[0].
517 * When we execute "f1() {b;}", we notice that f1 exists,
518 * and that its "parent cmd" struct is still "alive",
519 * we put those fields back into cmd->xxx
520 * (struct function has ->parent_cmd ptr to facilitate that).
521 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
522 * Without this trick, loop would execute a;b;b;b;...
523 * instead of correct sequence a;b;a;b;...
524 * When command is freed, it severs the link
525 * (sets ->child_func->parent_cmd to NULL).
528 char **argv; /* command name and arguments */
529 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
530 * and on execution these are substituted with their values.
531 * Substitution can make _several_ words out of one argv[n]!
532 * Example: argv[0]=='.^C*^C.' here: echo .$*.
533 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
535 struct redir_struct *redirects; /* I/O redirections */
537 /* Is there anything in this command at all? */
538 #define IS_NULL_CMD(cmd) \
539 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
544 int num_cmds; /* total number of commands in pipe */
545 int alive_cmds; /* number of commands running (not exited) */
546 int stopped_cmds; /* number of commands alive, but stopped */
548 int jobid; /* job number */
549 pid_t pgrp; /* process group ID for the job */
550 char *cmdtext; /* name of job */
552 struct command *cmds; /* array of commands in pipe */
553 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
554 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
555 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
557 typedef enum pipe_style {
563 /* Is there anything in this pipe at all? */
564 #define IS_NULL_PIPE(pi) \
565 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
567 /* This holds pointers to the various results of parsing */
568 struct parse_context {
569 /* linked list of pipes */
570 struct pipe *list_head;
571 /* last pipe (being constructed right now) */
573 /* last command in pipe (being constructed right now) */
574 struct command *command;
575 /* last redirect in command->redirects list */
576 struct redir_struct *pending_redirect;
582 smallint ctx_inverted; /* "! cmd | cmd" */
584 smallint ctx_dsemicolon; /* ";;" seen */
586 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
588 /* group we are enclosed in:
589 * example: "if pipe1; pipe2; then pipe3; fi"
590 * when we see "if" or "then", we malloc and copy current context,
591 * and make ->stack point to it. then we parse pipeN.
592 * when closing "then" / fi" / whatever is found,
593 * we move list_head into ->stack->command->group,
594 * copy ->stack into current context, and delete ->stack.
595 * (parsing of { list } and ( list ) doesn't use this method)
597 struct parse_context *stack;
601 /* On program start, environ points to initial environment.
602 * putenv adds new pointers into it, unsetenv removes them.
603 * Neither of these (de)allocates the strings.
604 * setenv allocates new strings in malloc space and does putenv,
605 * and thus setenv is unusable (leaky) for shell's purposes */
606 #define setenv(...) setenv_is_leaky_dont_use()
608 struct variable *next;
609 char *varstr; /* points to "name=" portion */
610 #if ENABLE_HUSH_LOCAL
611 unsigned func_nest_level;
613 int max_len; /* if > 0, name is part of initial env; else name is malloced */
614 smallint flg_export; /* putenv should be done on this var */
615 smallint flg_read_only;
623 #if ENABLE_HUSH_FUNCTIONS
625 struct function *next;
627 struct command *parent_cmd;
630 char *body_as_string;
636 /* "Globals" within this file */
637 /* Sorted roughly by size (smaller offsets == smaller code) */
639 /* interactive_fd != 0 means we are an interactive shell.
640 * If we are, then saved_tty_pgrp can also be != 0, meaning
641 * that controlling tty is available. With saved_tty_pgrp == 0,
642 * job control still works, but terminal signals
643 * (^C, ^Z, ^Y, ^\) won't work at all, and background
644 * process groups can only be created with "cmd &".
645 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
646 * to give tty to the foreground process group,
647 * and will take it back when the group is stopped (^Z)
650 #if ENABLE_HUSH_INTERACTIVE
651 /* 'interactive_fd' is a fd# open to ctty, if we have one
652 * _AND_ if we decided to act interactively */
656 # define G_interactive_fd (G.interactive_fd)
658 # define G_interactive_fd 0
660 #if ENABLE_FEATURE_EDITING
661 line_input_t *line_input_state;
666 #if ENABLE_HUSH_RANDOM_SUPPORT
672 pid_t saved_tty_pgrp;
673 struct pipe *job_list;
674 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
676 # define G_saved_tty_pgrp 0
678 smallint flag_SIGINT;
679 #if ENABLE_HUSH_LOOPS
680 smallint flag_break_continue;
682 #if ENABLE_HUSH_FUNCTIONS
683 /* 0: outside of a function (or sourced file)
684 * -1: inside of a function, ok to use return builtin
685 * 1: return is invoked, skip all till end of func
687 smallint flag_return_in_progress;
690 #if ENABLE_HUSH_MODE_X
692 # define G_x_mode (G.x_mode)
696 smallint exiting; /* used to prevent EXIT trap recursion */
697 /* These four support $?, $#, and $1 */
698 smalluint last_exitcode;
699 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
700 smalluint global_args_malloced;
701 smalluint inherited_set_is_saved;
702 /* how many non-NULL argv's we have. NB: $# + 1 */
706 char *argv0_for_re_execing;
708 #if ENABLE_HUSH_LOOPS
709 unsigned depth_break_continue;
710 unsigned depth_of_loop;
714 struct variable *top_var; /* = &G.shell_ver (set in main()) */
715 struct variable shell_ver;
716 char **expanded_assignments;
717 #if ENABLE_HUSH_FUNCTIONS
718 struct function *top_func;
719 # if ENABLE_HUSH_LOCAL
720 struct variable **shadowed_vars_pp;
721 unsigned func_nest_level;
724 /* Signal and trap handling */
726 unsigned count_SIGCHLD;
727 unsigned handled_SIGCHLD;
728 smallint we_have_children;
730 /* which signals have non-DFL handler (even with no traps set)? */
731 unsigned non_DFL_mask;
732 char **traps; /* char *traps[NSIG] */
733 sigset_t blocked_set;
734 sigset_t inherited_set;
736 unsigned long memleak_value;
739 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
741 #define G (*ptr_to_globals)
742 /* Not #defining name to G.name - this quickly gets unwieldy
743 * (too many defines). Also, I actually prefer to see when a variable
744 * is global, thus "G." prefix is a useful hint */
745 #define INIT_G() do { \
746 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
750 /* Function prototypes for builtins */
751 static int builtin_cd(char **argv) FAST_FUNC;
752 static int builtin_echo(char **argv) FAST_FUNC;
753 static int builtin_eval(char **argv) FAST_FUNC;
754 static int builtin_exec(char **argv) FAST_FUNC;
755 static int builtin_exit(char **argv) FAST_FUNC;
756 static int builtin_export(char **argv) FAST_FUNC;
758 static int builtin_fg_bg(char **argv) FAST_FUNC;
759 static int builtin_jobs(char **argv) FAST_FUNC;
762 static int builtin_help(char **argv) FAST_FUNC;
764 #if ENABLE_HUSH_LOCAL
765 static int builtin_local(char **argv) FAST_FUNC;
768 static int builtin_memleak(char **argv) FAST_FUNC;
771 static int builtin_printf(char **argv) FAST_FUNC;
773 static int builtin_pwd(char **argv) FAST_FUNC;
774 static int builtin_read(char **argv) FAST_FUNC;
775 static int builtin_set(char **argv) FAST_FUNC;
776 static int builtin_shift(char **argv) FAST_FUNC;
777 static int builtin_source(char **argv) FAST_FUNC;
778 static int builtin_test(char **argv) FAST_FUNC;
779 static int builtin_trap(char **argv) FAST_FUNC;
780 static int builtin_type(char **argv) FAST_FUNC;
781 static int builtin_true(char **argv) FAST_FUNC;
782 static int builtin_umask(char **argv) FAST_FUNC;
783 static int builtin_unset(char **argv) FAST_FUNC;
784 static int builtin_wait(char **argv) FAST_FUNC;
785 #if ENABLE_HUSH_LOOPS
786 static int builtin_break(char **argv) FAST_FUNC;
787 static int builtin_continue(char **argv) FAST_FUNC;
789 #if ENABLE_HUSH_FUNCTIONS
790 static int builtin_return(char **argv) FAST_FUNC;
793 /* Table of built-in functions. They can be forked or not, depending on
794 * context: within pipes, they fork. As simple commands, they do not.
795 * When used in non-forking context, they can change global variables
796 * in the parent shell process. If forked, of course they cannot.
797 * For example, 'unset foo | whatever' will parse and run, but foo will
798 * still be set at the end. */
799 struct built_in_command {
801 int (*b_function)(char **argv) FAST_FUNC;
804 # define BLTIN(cmd, func, help) { cmd, func, help }
806 # define BLTIN(cmd, func, help) { cmd, func }
810 static const struct built_in_command bltins1[] = {
811 BLTIN("." , builtin_source , "Run commands in a file"),
812 BLTIN(":" , builtin_true , NULL),
814 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
816 #if ENABLE_HUSH_LOOPS
817 BLTIN("break" , builtin_break , "Exit from a loop"),
819 BLTIN("cd" , builtin_cd , "Change directory"),
820 #if ENABLE_HUSH_LOOPS
821 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
823 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
824 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
825 BLTIN("exit" , builtin_exit , "Exit"),
826 BLTIN("export" , builtin_export , "Set environment variables"),
828 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
831 BLTIN("help" , builtin_help , NULL),
834 BLTIN("jobs" , builtin_jobs , "List jobs"),
836 #if ENABLE_HUSH_LOCAL
837 BLTIN("local" , builtin_local , "Set local variables"),
840 BLTIN("memleak" , builtin_memleak , NULL),
842 BLTIN("read" , builtin_read , "Input into variable"),
843 #if ENABLE_HUSH_FUNCTIONS
844 BLTIN("return" , builtin_return , "Return from a function"),
846 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
847 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
848 #if ENABLE_HUSH_BASH_COMPAT
849 BLTIN("source" , builtin_source , "Run commands in a file"),
851 BLTIN("trap" , builtin_trap , "Trap signals"),
852 BLTIN("type" , builtin_type , "Show command type"),
853 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
854 BLTIN("umask" , builtin_umask , "Set file creation mask"),
855 BLTIN("unset" , builtin_unset , "Unset variables"),
856 BLTIN("wait" , builtin_wait , "Wait for process"),
858 /* For now, echo and test are unconditionally enabled.
859 * Maybe make it configurable? */
860 static const struct built_in_command bltins2[] = {
861 BLTIN("[" , builtin_test , NULL),
862 BLTIN("echo" , builtin_echo , NULL),
864 BLTIN("printf" , builtin_printf , NULL),
866 BLTIN("pwd" , builtin_pwd , NULL),
867 BLTIN("test" , builtin_test , NULL),
874 /* prevent disasters with G.debug_indent < 0 */
875 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
876 # define debug_enter() (G.debug_indent++)
877 # define debug_leave() (G.debug_indent--)
879 # define indent() ((void)0)
880 # define debug_enter() ((void)0)
881 # define debug_leave() ((void)0)
885 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
888 #ifndef debug_printf_parse
889 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
892 #ifndef debug_printf_exec
893 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
896 #ifndef debug_printf_env
897 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
900 #ifndef debug_printf_jobs
901 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
902 # define DEBUG_JOBS 1
904 # define DEBUG_JOBS 0
907 #ifndef debug_printf_expand
908 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
909 # define DEBUG_EXPAND 1
911 # define DEBUG_EXPAND 0
914 #ifndef debug_printf_varexp
915 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
918 #ifndef debug_printf_glob
919 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
920 # define DEBUG_GLOB 1
922 # define DEBUG_GLOB 0
925 #ifndef debug_printf_list
926 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
929 #ifndef debug_printf_subst
930 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
933 #ifndef debug_printf_clean
934 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
935 # define DEBUG_CLEAN 1
937 # define DEBUG_CLEAN 0
941 static void debug_print_strings(const char *prefix, char **vv)
944 fprintf(stderr, "%s:\n", prefix);
946 fprintf(stderr, " '%s'\n", *vv++);
949 # define debug_print_strings(prefix, vv) ((void)0)
953 /* Leak hunting. Use hush_leaktool.sh for post-processing.
956 static void *xxmalloc(int lineno, size_t size)
958 void *ptr = xmalloc((size + 0xff) & ~0xff);
959 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
962 static void *xxrealloc(int lineno, void *ptr, size_t size)
964 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
965 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
968 static char *xxstrdup(int lineno, const char *str)
970 char *ptr = xstrdup(str);
971 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
974 static void xxfree(void *ptr)
976 fdprintf(2, "free %p\n", ptr);
979 # define xmalloc(s) xxmalloc(__LINE__, s)
980 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
981 # define xstrdup(s) xxstrdup(__LINE__, s)
982 # define free(p) xxfree(p)
986 /* Syntax and runtime errors. They always abort scripts.
987 * In interactive use they usually discard unparsed and/or unexecuted commands
988 * and return to the prompt.
989 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
992 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
993 # define syntax_error(lineno, msg) syntax_error(msg)
994 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
995 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
996 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
997 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1000 static void die_if_script(unsigned lineno, const char *fmt, ...)
1005 bb_error_msg("hush.c:%u", lineno);
1008 bb_verror_msg(fmt, p, NULL);
1010 if (!G_interactive_fd)
1014 static void syntax_error(unsigned lineno, const char *msg)
1017 die_if_script(lineno, "syntax error: %s", msg);
1019 die_if_script(lineno, "syntax error", NULL);
1022 static void syntax_error_at(unsigned lineno, const char *msg)
1024 die_if_script(lineno, "syntax error at '%s'", msg);
1027 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1029 die_if_script(lineno, "syntax error: unterminated %s", s);
1032 /* It so happens that all such cases are totally fatal
1033 * even if shell is interactive: EOF while looking for closing
1034 * delimiter. There is nowhere to read stuff from after that,
1035 * it's EOF! The only choice is to terminate.
1037 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1038 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1040 char msg[2] = { ch, '\0' };
1041 syntax_error_unterm_str(lineno, msg);
1045 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1050 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1054 # undef die_if_script
1055 # undef syntax_error
1056 # undef syntax_error_at
1057 # undef syntax_error_unterm_ch
1058 # undef syntax_error_unterm_str
1059 # undef syntax_error_unexpected_ch
1061 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1062 # define syntax_error(msg) syntax_error(__LINE__, msg)
1063 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1064 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1065 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1066 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1070 #if ENABLE_HUSH_INTERACTIVE
1071 static void cmdedit_update_prompt(void);
1073 # define cmdedit_update_prompt() ((void)0)
1077 /* Utility functions
1079 /* Replace each \x with x in place, return ptr past NUL. */
1080 static char *unbackslash(char *src)
1082 char *dst = src = strchrnul(src, '\\');
1086 if ((*dst++ = *src++) == '\0')
1092 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1113 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1114 v[count1 + count2] = NULL;
1117 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1121 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1123 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1124 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1127 #define add_strings_to_strings(strings, add, need_to_dup) \
1128 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1131 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1132 static char **add_string_to_strings(char **strings, char *add)
1137 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1140 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1142 char **ptr = add_string_to_strings(strings, add);
1143 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1146 #define add_string_to_strings(strings, add) \
1147 xx_add_string_to_strings(__LINE__, strings, add)
1150 static void free_strings(char **strings)
1165 /* Helpers for setting new $n and restoring them back
1167 typedef struct save_arg_t {
1171 smallint sv_g_malloced;
1174 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1178 sv->sv_argv0 = argv[0];
1179 sv->sv_g_argv = G.global_argv;
1180 sv->sv_g_argc = G.global_argc;
1181 sv->sv_g_malloced = G.global_args_malloced;
1183 argv[0] = G.global_argv[0]; /* retain $0 */
1184 G.global_argv = argv;
1185 G.global_args_malloced = 0;
1193 static void restore_G_args(save_arg_t *sv, char **argv)
1197 if (G.global_args_malloced) {
1198 /* someone ran "set -- arg1 arg2 ...", undo */
1200 while (*++pp) /* note: does not free $0 */
1202 free(G.global_argv);
1204 argv[0] = sv->sv_argv0;
1205 G.global_argv = sv->sv_g_argv;
1206 G.global_argc = sv->sv_g_argc;
1207 G.global_args_malloced = sv->sv_g_malloced;
1211 /* Basic theory of signal handling in shell
1212 * ========================================
1213 * This does not describe what hush does, rather, it is current understanding
1214 * what it _should_ do. If it doesn't, it's a bug.
1215 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1217 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1218 * is finished or backgrounded. It is the same in interactive and
1219 * non-interactive shells, and is the same regardless of whether
1220 * a user trap handler is installed or a shell special one is in effect.
1221 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1222 * backgrounds (i.e. stops) or kills all members of currently running
1225 * Wait builtin in interruptible by signals for which user trap is set
1226 * or by SIGINT in interactive shell.
1228 * Trap handlers will execute even within trap handlers. (right?)
1230 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1231 * except for handlers set to '' (empty string).
1233 * If job control is off, backgrounded commands ("cmd &")
1234 * have SIGINT, SIGQUIT set to SIG_IGN.
1236 * Commands which are run in command substitution ("`cmd`")
1237 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1239 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1240 * by the shell from its parent.
1242 * Signals which differ from SIG_DFL action
1243 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1246 * SIGTERM (interactive): ignore
1247 * SIGHUP (interactive):
1248 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1249 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1250 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1251 * that all pipe members are stopped. Try this in bash:
1252 * while :; do :; done - ^Z does not background it
1253 * (while :; do :; done) - ^Z backgrounds it
1254 * SIGINT (interactive): wait for last pipe, ignore the rest
1255 * of the command line, show prompt. NB: ^C does not send SIGINT
1256 * to interactive shell while shell is waiting for a pipe,
1257 * since shell is bg'ed (is not in foreground process group).
1258 * Example 1: this waits 5 sec, but does not execute ls:
1259 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1260 * Example 2: this does not wait and does not execute ls:
1261 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1262 * Example 3: this does not wait 5 sec, but executes ls:
1263 * "sleep 5; ls -l" + press ^C
1265 * (What happens to signals which are IGN on shell start?)
1266 * (What happens with signal mask on shell start?)
1268 * Implementation in hush
1269 * ======================
1270 * We use in-kernel pending signal mask to determine which signals were sent.
1271 * We block all signals which we don't want to take action immediately,
1272 * i.e. we block all signals which need to have special handling as described
1273 * above, and all signals which have traps set.
1274 * After each pipe execution, we extract any pending signals via sigtimedwait()
1277 * unsigned non_DFL_mask: a mask of such "special" signals
1278 * sigset_t blocked_set: current blocked signal set
1281 * clear bit in blocked_set unless it is also in non_DFL_mask
1282 * "trap 'cmd' SIGxxx":
1283 * set bit in blocked_set (even if 'cmd' is '')
1284 * after [v]fork, if we plan to be a shell:
1285 * unblock signals with special interactive handling
1286 * (child shell is not interactive),
1287 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1288 * after [v]fork, if we plan to exec:
1289 * POSIX says fork clears pending signal mask in child - no need to clear it.
1290 * Restore blocked signal set to one inherited by shell just prior to exec.
1292 * Note: as a result, we do not use signal handlers much. The only uses
1293 * are to count SIGCHLDs
1294 * and to restore tty pgrp on signal-induced exit.
1297 * Standard says "When a subshell is entered, traps that are not being ignored
1298 * are set to the default actions". bash interprets it so that traps which
1299 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1302 SPECIAL_INTERACTIVE_SIGS = 0
1307 SPECIAL_JOB_SIGS = 0
1315 #if ENABLE_HUSH_FAST
1316 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1319 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1325 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1326 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1327 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1328 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1330 /* Restores tty foreground process group, and exits.
1331 * May be called as signal handler for fatal signal
1332 * (will resend signal to itself, producing correct exit state)
1333 * or called directly with -EXITCODE.
1334 * We also call it if xfunc is exiting. */
1335 static void sigexit(int sig) NORETURN;
1336 static void sigexit(int sig)
1338 /* Disable all signals: job control, SIGPIPE, etc. */
1339 sigprocmask_allsigs(SIG_BLOCK);
1341 /* Careful: we can end up here after [v]fork. Do not restore
1342 * tty pgrp then, only top-level shell process does that */
1343 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1344 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1346 /* Not a signal, just exit */
1350 kill_myself_with_sig(sig); /* does not return */
1354 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1355 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1359 /* Restores tty foreground process group, and exits. */
1360 static void hush_exit(int exitcode) NORETURN;
1361 static void hush_exit(int exitcode)
1363 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1364 /* Prevent recursion:
1365 * trap "echo Hi; exit" EXIT; exit
1367 char *argv[] = { NULL, G.traps[0], NULL };
1376 sigexit(- (exitcode & 0xff));
1382 static int check_and_run_traps(int sig)
1384 static const struct timespec zero_timespec;
1385 smalluint save_rcode;
1391 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1396 if (G.traps && G.traps[sig]) {
1397 if (G.traps[sig][0]) {
1398 /* We have user-defined handler */
1399 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1400 save_rcode = G.last_exitcode;
1403 G.last_exitcode = save_rcode;
1404 } /* else: "" trap, ignoring signal */
1407 /* not a trap: special action */
1409 #if ENABLE_HUSH_FAST
1412 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1416 /* Builtin was ^C'ed, make it look prettier: */
1423 /* bash is observed to signal whole process groups,
1424 * not individual processes */
1425 for (job = G.job_list; job; job = job->next) {
1428 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1429 if (kill(- job->pgrp, SIGHUP) == 0)
1430 kill(- job->pgrp, SIGCONT);
1435 default: /* ignored: */
1436 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1444 static const char *get_cwd(int force)
1446 if (force || G.cwd == NULL) {
1447 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1448 * we must not try to free(bb_msg_unknown) */
1449 if (G.cwd == bb_msg_unknown)
1451 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1453 G.cwd = bb_msg_unknown;
1460 * Shell and environment variable support
1462 static struct variable **get_ptr_to_local_var(const char *name)
1464 struct variable **pp;
1465 struct variable *cur;
1470 while ((cur = *pp) != NULL) {
1471 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1478 static struct variable *get_local_var(const char *name)
1480 struct variable **pp = get_ptr_to_local_var(name);
1486 static const char* FAST_FUNC get_local_var_value(const char *name)
1488 struct variable **vpp;
1490 if (G.expanded_assignments) {
1491 char **cpp = G.expanded_assignments;
1492 int len = strlen(name);
1495 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1496 return cp + len + 1;
1501 vpp = get_ptr_to_local_var(name);
1503 return strchr((*vpp)->varstr, '=') + 1;
1505 if (strcmp(name, "PPID") == 0)
1506 return utoa(G.root_ppid);
1507 // bash compat: UID? EUID?
1508 #if ENABLE_HUSH_RANDOM_SUPPORT
1509 if (strcmp(name, "RANDOM") == 0) {
1510 return utoa(next_random(&G.random_gen));
1516 /* str holds "NAME=VAL" and is expected to be malloced.
1517 * We take ownership of it.
1519 * 0: do not change export flag
1520 * (if creating new variable, flag will be 0)
1521 * 1: set export flag and putenv the variable
1522 * -1: clear export flag and unsetenv the variable
1523 * flg_read_only is set only when we handle -R var=val
1525 #if !BB_MMU && ENABLE_HUSH_LOCAL
1526 /* all params are used */
1527 #elif BB_MMU && ENABLE_HUSH_LOCAL
1528 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1529 set_local_var(str, flg_export, local_lvl)
1530 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1531 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1532 set_local_var(str, flg_export)
1533 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1534 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1535 set_local_var(str, flg_export, flg_read_only)
1537 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1539 struct variable **var_pp;
1540 struct variable *cur;
1544 eq_sign = strchr(str, '=');
1545 if (!eq_sign) { /* not expected to ever happen? */
1550 name_len = eq_sign - str + 1; /* including '=' */
1551 var_pp = &G.top_var;
1552 while ((cur = *var_pp) != NULL) {
1553 if (strncmp(cur->varstr, str, name_len) != 0) {
1554 var_pp = &cur->next;
1557 /* We found an existing var with this name */
1558 if (cur->flg_read_only) {
1562 bb_error_msg("%s: readonly variable", str);
1566 if (flg_export == -1) { // "&& cur->flg_export" ?
1567 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1572 #if ENABLE_HUSH_LOCAL
1573 if (cur->func_nest_level < local_lvl) {
1574 /* New variable is declared as local,
1575 * and existing one is global, or local
1576 * from enclosing function.
1577 * Remove and save old one: */
1578 *var_pp = cur->next;
1579 cur->next = *G.shadowed_vars_pp;
1580 *G.shadowed_vars_pp = cur;
1581 /* bash 3.2.33(1) and exported vars:
1583 * # f() { local z=a; env | grep ^z; }
1589 if (cur->flg_export)
1594 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1599 if (cur->max_len != 0) {
1600 if (cur->max_len >= strlen(str)) {
1601 /* This one is from startup env, reuse space */
1602 strcpy(cur->varstr, str);
1606 /* max_len == 0 signifies "malloced" var, which we can
1607 * (and has to) free */
1611 goto set_str_and_exp;
1614 /* Not found - create new variable struct */
1615 cur = xzalloc(sizeof(*cur));
1616 #if ENABLE_HUSH_LOCAL
1617 cur->func_nest_level = local_lvl;
1619 cur->next = *var_pp;
1625 cur->flg_read_only = flg_read_only;
1628 if (flg_export == 1)
1629 cur->flg_export = 1;
1630 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1631 cmdedit_update_prompt();
1632 if (cur->flg_export) {
1633 if (flg_export == -1) {
1634 cur->flg_export = 0;
1635 /* unsetenv was already done */
1637 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1638 return putenv(cur->varstr);
1644 /* Used at startup and after each cd */
1645 static void set_pwd_var(int exp)
1647 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1648 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1651 static int unset_local_var_len(const char *name, int name_len)
1653 struct variable *cur;
1654 struct variable **var_pp;
1657 return EXIT_SUCCESS;
1658 var_pp = &G.top_var;
1659 while ((cur = *var_pp) != NULL) {
1660 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1661 if (cur->flg_read_only) {
1662 bb_error_msg("%s: readonly variable", name);
1663 return EXIT_FAILURE;
1665 *var_pp = cur->next;
1666 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1667 bb_unsetenv(cur->varstr);
1668 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1669 cmdedit_update_prompt();
1673 return EXIT_SUCCESS;
1675 var_pp = &cur->next;
1677 return EXIT_SUCCESS;
1680 static int unset_local_var(const char *name)
1682 return unset_local_var_len(name, strlen(name));
1685 static void unset_vars(char **strings)
1693 const char *eq = strchrnul(*v, '=');
1694 unset_local_var_len(*v, (int)(eq - *v));
1700 #if ENABLE_SH_MATH_SUPPORT
1701 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1702 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1703 static char* FAST_FUNC endofname(const char *name)
1711 if (!is_in_name(*p))
1718 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1720 char *var = xasprintf("%s=%s", name, val);
1721 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1726 * Helpers for "var1=val1 var2=val2 cmd" feature
1728 static void add_vars(struct variable *var)
1730 struct variable *next;
1734 var->next = G.top_var;
1736 if (var->flg_export) {
1737 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1738 putenv(var->varstr);
1740 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1746 static struct variable *set_vars_and_save_old(char **strings)
1749 struct variable *old = NULL;
1755 struct variable *var_p;
1756 struct variable **var_pp;
1759 eq = strchr(*s, '=');
1762 var_pp = get_ptr_to_local_var(*s);
1765 /* Remove variable from global linked list */
1767 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1768 *var_pp = var_p->next;
1769 /* Add it to returned list */
1773 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1784 static int FAST_FUNC static_get(struct in_str *i)
1794 static int FAST_FUNC static_peek(struct in_str *i)
1799 #if ENABLE_HUSH_INTERACTIVE
1801 static void cmdedit_update_prompt(void)
1803 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1804 G.PS1 = get_local_var_value("PS1");
1807 G.PS2 = get_local_var_value("PS2");
1815 static const char* setup_prompt_string(int promptmode)
1817 const char *prompt_str;
1818 debug_printf("setup_prompt_string %d ", promptmode);
1819 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1820 /* Set up the prompt */
1821 if (promptmode == 0) { /* PS1 */
1823 /* bash uses $PWD value, even if it is set by user.
1824 * It uses current dir only if PWD is unset.
1825 * We always use current dir. */
1826 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1831 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1832 debug_printf("result '%s'\n", prompt_str);
1836 static void get_user_input(struct in_str *i)
1839 const char *prompt_str;
1841 prompt_str = setup_prompt_string(i->promptmode);
1842 # if ENABLE_FEATURE_EDITING
1843 /* Enable command line editing only while a command line
1844 * is actually being read */
1847 /* buglet: SIGINT will not make new prompt to appear _at once_,
1848 * only after <Enter>. (^C will work) */
1849 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1850 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1851 check_and_run_traps(0);
1852 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1853 i->eof_flag = (r < 0);
1854 if (i->eof_flag) { /* EOF/error detected */
1855 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1856 G.user_input_buf[1] = '\0';
1861 fputs(prompt_str, stdout);
1863 G.user_input_buf[0] = r = fgetc(i->file);
1864 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1865 //do we need check_and_run_traps(0)? (maybe only if stdin)
1866 } while (G.flag_SIGINT);
1867 i->eof_flag = (r == EOF);
1869 i->p = G.user_input_buf;
1872 #endif /* INTERACTIVE */
1874 /* This is the magic location that prints prompts
1875 * and gets data back from the user */
1876 static int FAST_FUNC file_get(struct in_str *i)
1880 /* If there is data waiting, eat it up */
1881 if (i->p && *i->p) {
1882 #if ENABLE_HUSH_INTERACTIVE
1886 if (i->eof_flag && !*i->p)
1888 /* note: ch is never NUL */
1890 /* need to double check i->file because we might be doing something
1891 * more complicated by now, like sourcing or substituting. */
1892 #if ENABLE_HUSH_INTERACTIVE
1893 if (G_interactive_fd && i->promptme && i->file == stdin) {
1896 } while (!*i->p); /* need non-empty line */
1897 i->promptmode = 1; /* PS2 */
1902 do ch = fgetc(i->file); while (ch == '\0');
1904 debug_printf("file_get: got '%c' %d\n", ch, ch);
1905 #if ENABLE_HUSH_INTERACTIVE
1912 /* All callers guarantee this routine will never
1913 * be used right after a newline, so prompting is not needed.
1915 static int FAST_FUNC file_peek(struct in_str *i)
1918 if (i->p && *i->p) {
1919 if (i->eof_flag && !i->p[1])
1922 /* note: ch is never NUL */
1924 do ch = fgetc(i->file); while (ch == '\0');
1925 i->eof_flag = (ch == EOF);
1926 i->peek_buf[0] = ch;
1927 i->peek_buf[1] = '\0';
1929 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1933 static void setup_file_in_str(struct in_str *i, FILE *f)
1935 i->peek = file_peek;
1937 #if ENABLE_HUSH_INTERACTIVE
1939 i->promptmode = 0; /* PS1 */
1945 static void setup_string_in_str(struct in_str *i, const char *s)
1947 i->peek = static_peek;
1948 i->get = static_get;
1949 #if ENABLE_HUSH_INTERACTIVE
1951 i->promptmode = 0; /* PS1 */
1961 #define B_CHUNK (32 * sizeof(char*))
1963 static void o_reset_to_empty_unquoted(o_string *o)
1966 o->has_quoted_part = 0;
1971 static void o_free(o_string *o)
1974 memset(o, 0, sizeof(*o));
1977 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1982 static void o_grow_by(o_string *o, int len)
1984 if (o->length + len > o->maxlen) {
1985 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1986 o->data = xrealloc(o->data, 1 + o->maxlen);
1990 static void o_addchr(o_string *o, int ch)
1992 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1994 o->data[o->length] = ch;
1996 o->data[o->length] = '\0';
1999 static void o_addblock(o_string *o, const char *str, int len)
2002 memcpy(&o->data[o->length], str, len);
2004 o->data[o->length] = '\0';
2007 static void o_addstr(o_string *o, const char *str)
2009 o_addblock(o, str, strlen(str));
2013 static void nommu_addchr(o_string *o, int ch)
2019 # define nommu_addchr(o, str) ((void)0)
2022 static void o_addstr_with_NUL(o_string *o, const char *str)
2024 o_addblock(o, str, strlen(str) + 1);
2027 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2039 #undef HUSH_BRACE_EXP
2041 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2042 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2043 * Apparently, on unquoted $v bash still does globbing
2044 * ("v='*.txt'; echo $v" prints all .txt files),
2045 * but NOT brace expansion! Thus, there should be TWO independent
2046 * quoting mechanisms on $v expansion side: one protects
2047 * $v from brace expansion, and other additionally protects "$v" against globbing.
2048 * We have only second one.
2051 #ifdef HUSH_BRACE_EXP
2052 # define MAYBE_BRACES "{}"
2054 # define MAYBE_BRACES ""
2057 /* My analysis of quoting semantics tells me that state information
2058 * is associated with a destination, not a source.
2060 static void o_addqchr(o_string *o, int ch)
2063 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2068 o->data[o->length] = '\\';
2071 o->data[o->length] = ch;
2073 o->data[o->length] = '\0';
2076 static void o_addQchr(o_string *o, int ch)
2079 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2081 o->data[o->length] = '\\';
2085 o->data[o->length] = ch;
2087 o->data[o->length] = '\0';
2090 static void o_addQblock(o_string *o, const char *str, int len)
2093 o_addblock(o, str, len);
2099 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2100 if (ordinary_cnt > len) /* paranoia */
2102 o_addblock(o, str, ordinary_cnt);
2103 if (ordinary_cnt == len)
2105 str += ordinary_cnt;
2106 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2110 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2112 o->data[o->length] = '\\';
2116 o->data[o->length] = ch;
2118 o->data[o->length] = '\0';
2122 static void o_addQstr(o_string *o, const char *str)
2124 o_addQblock(o, str, strlen(str));
2127 /* A special kind of o_string for $VAR and `cmd` expansion.
2128 * It contains char* list[] at the beginning, which is grown in 16 element
2129 * increments. Actual string data starts at the next multiple of 16 * (char*).
2130 * list[i] contains an INDEX (int!) into this string data.
2131 * It means that if list[] needs to grow, data needs to be moved higher up
2132 * but list[i]'s need not be modified.
2133 * NB: remembering how many list[i]'s you have there is crucial.
2134 * o_finalize_list() operation post-processes this structure - calculates
2135 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2137 #if DEBUG_EXPAND || DEBUG_GLOB
2138 static void debug_print_list(const char *prefix, o_string *o, int n)
2140 char **list = (char**)o->data;
2141 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2145 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2146 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->has_quoted_part, o->o_escape);
2149 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2150 o->data + (int)list[i] + string_start,
2151 o->data + (int)list[i] + string_start);
2155 const char *p = o->data + (int)list[n - 1] + string_start;
2157 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2161 # define debug_print_list(prefix, o, n) ((void)0)
2164 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2165 * in list[n] so that it points past last stored byte so far.
2166 * It returns n+1. */
2167 static int o_save_ptr_helper(o_string *o, int n)
2169 char **list = (char**)o->data;
2173 if (!o->has_empty_slot) {
2174 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2175 string_len = o->length - string_start;
2176 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2177 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2178 /* list[n] points to string_start, make space for 16 more pointers */
2179 o->maxlen += 0x10 * sizeof(list[0]);
2180 o->data = xrealloc(o->data, o->maxlen + 1);
2181 list = (char**)o->data;
2182 memmove(list + n + 0x10, list + n, string_len);
2183 o->length += 0x10 * sizeof(list[0]);
2185 debug_printf_list("list[%d]=%d string_start=%d\n",
2186 n, string_len, string_start);
2189 /* We have empty slot at list[n], reuse without growth */
2190 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2191 string_len = o->length - string_start;
2192 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2193 n, string_len, string_start);
2194 o->has_empty_slot = 0;
2196 list[n] = (char*)(ptrdiff_t)string_len;
2200 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2201 static int o_get_last_ptr(o_string *o, int n)
2203 char **list = (char**)o->data;
2204 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2206 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2209 #ifdef HUSH_BRACE_EXP
2210 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2211 * first, it processes even {a} (no commas), second,
2212 * I didn't manage to make it return strings when they don't match
2213 * existing files. Need to re-implement it.
2217 static int glob_needed(const char *s)
2226 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2232 /* Return pointer to next closing brace or to comma */
2233 static const char *next_brace_sub(const char *cp)
2237 while (*cp != '\0') {
2244 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2246 if (*cp++ == '{') /*}*/
2250 return *cp != '\0' ? cp : NULL;
2252 /* Recursive brace globber. Note: may garble pattern[]. */
2253 static int glob_brace(char *pattern, o_string *o, int n)
2255 char *new_pattern_buf;
2262 debug_printf_glob("glob_brace('%s')\n", pattern);
2268 if (*begin == '{') /*}*/ {
2269 /* Find the first sub-pattern and at the same time
2270 * find the rest after the closing brace */
2271 next = next_brace_sub(begin);
2273 /* An illegal expression */
2276 /*{*/ if (*next == '}') {
2277 /* "{abc}" with no commas - illegal
2278 * brace expr, disregard and skip it */
2284 if (*begin == '\\' && begin[1] != '\0')
2288 debug_printf_glob("begin:%s\n", begin);
2289 debug_printf_glob("next:%s\n", next);
2291 /* Now find the end of the whole brace expression */
2293 /*{*/ while (*rest != '}') {
2294 rest = next_brace_sub(rest);
2296 /* An illegal expression */
2299 debug_printf_glob("rest:%s\n", rest);
2301 rest_len = strlen(++rest) + 1;
2303 /* We are sure the brace expression is well-formed */
2305 /* Allocate working buffer large enough for our work */
2306 new_pattern_buf = xmalloc(strlen(pattern));
2308 /* We have a brace expression. BEGIN points to the opening {,
2309 * NEXT points past the terminator of the first element, and REST
2310 * points past the final }. We will accumulate result names from
2311 * recursive runs for each brace alternative in the buffer using
2316 /* Construct the new glob expression */
2319 mempcpy(new_pattern_buf,
2320 /* We know the prefix for all sub-patterns */
2321 pattern, begin - pattern),
2325 /* Note: glob_brace() may garble new_pattern_buf[].
2326 * That's why we re-copy prefix every time (1st memcpy above).
2328 n = glob_brace(new_pattern_buf, o, n);
2329 /*{*/ if (*next == '}') {
2330 /* We saw the last entry */
2334 next = next_brace_sub(next);
2336 free(new_pattern_buf);
2344 memset(&globdata, 0, sizeof(globdata));
2345 gr = glob(pattern, 0, NULL, &globdata);
2346 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2348 if (gr == GLOB_NOMATCH) {
2349 globfree(&globdata);
2350 /* NB: garbles parameter */
2351 unbackslash(pattern);
2352 o_addstr_with_NUL(o, pattern);
2353 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2354 return o_save_ptr_helper(o, n);
2356 if (gr == GLOB_NOSPACE)
2357 bb_error_msg_and_die(bb_msg_memory_exhausted);
2358 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2359 * but we didn't specify it. Paranoia again. */
2360 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2362 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2363 char **argv = globdata.gl_pathv;
2365 o_addstr_with_NUL(o, *argv);
2366 n = o_save_ptr_helper(o, n);
2372 globfree(&globdata);
2376 /* Performs globbing on last list[],
2377 * saving each result as a new list[].
2379 static int o_glob(o_string *o, int n)
2381 char *pattern, *copy;
2383 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2385 return o_save_ptr_helper(o, n);
2386 pattern = o->data + o_get_last_ptr(o, n);
2387 debug_printf_glob("glob pattern '%s'\n", pattern);
2388 if (!glob_needed(pattern)) {
2389 /* unbackslash last string in o in place, fix length */
2390 o->length = unbackslash(pattern) - o->data;
2391 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2392 return o_save_ptr_helper(o, n);
2395 copy = xstrdup(pattern);
2396 /* "forget" pattern in o */
2397 o->length = pattern - o->data;
2398 n = glob_brace(copy, o, n);
2401 debug_print_list("o_glob returning", o, n);
2405 #else /* !HUSH_BRACE_EXP */
2408 static int glob_needed(const char *s)
2417 if (*s == '*' || *s == '[' || *s == '?')
2423 /* Performs globbing on last list[],
2424 * saving each result as a new list[].
2426 static int o_glob(o_string *o, int n)
2432 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2434 return o_save_ptr_helper(o, n);
2435 pattern = o->data + o_get_last_ptr(o, n);
2436 debug_printf_glob("glob pattern '%s'\n", pattern);
2437 if (!glob_needed(pattern)) {
2439 /* unbackslash last string in o in place, fix length */
2440 o->length = unbackslash(pattern) - o->data;
2441 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2442 return o_save_ptr_helper(o, n);
2445 memset(&globdata, 0, sizeof(globdata));
2446 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2447 * If we glob "*.\*" and don't find anything, we need
2448 * to fall back to using literal "*.*", but GLOB_NOCHECK
2449 * will return "*.\*"!
2451 gr = glob(pattern, 0, NULL, &globdata);
2452 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2454 if (gr == GLOB_NOMATCH) {
2455 globfree(&globdata);
2458 if (gr == GLOB_NOSPACE)
2459 bb_error_msg_and_die(bb_msg_memory_exhausted);
2460 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2461 * but we didn't specify it. Paranoia again. */
2462 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2464 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2465 char **argv = globdata.gl_pathv;
2466 /* "forget" pattern in o */
2467 o->length = pattern - o->data;
2469 o_addstr_with_NUL(o, *argv);
2470 n = o_save_ptr_helper(o, n);
2476 globfree(&globdata);
2478 debug_print_list("o_glob returning", o, n);
2482 #endif /* !HUSH_BRACE_EXP */
2484 /* If o->o_glob == 1, glob the string so far remembered.
2485 * Otherwise, just finish current list[] and start new */
2486 static int o_save_ptr(o_string *o, int n)
2488 if (o->o_glob) { /* if globbing is requested */
2489 /* If o->has_empty_slot, list[n] was already globbed
2490 * (if it was requested back then when it was filled)
2491 * so don't do that again! */
2492 if (!o->has_empty_slot)
2493 return o_glob(o, n); /* o_save_ptr_helper is inside */
2495 return o_save_ptr_helper(o, n);
2498 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2499 static char **o_finalize_list(o_string *o, int n)
2504 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2506 debug_print_list("finalized", o, n);
2507 debug_printf_expand("finalized n:%d\n", n);
2508 list = (char**)o->data;
2509 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2513 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2519 /* Expansion can recurse */
2520 #if ENABLE_HUSH_TICK
2521 static int process_command_subs(o_string *dest, const char *s);
2523 static char *expand_string_to_string(const char *str);
2525 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2526 parse_stream_dquoted(dest, input, dquote_end)
2528 static int parse_stream_dquoted(o_string *as_string,
2530 struct in_str *input,
2533 /* expand_strvec_to_strvec() takes a list of strings, expands
2534 * all variable references within and returns a pointer to
2535 * a list of expanded strings, possibly with larger number
2536 * of strings. (Think VAR="a b"; echo $VAR).
2537 * This new list is allocated as a single malloc block.
2538 * NULL-terminated list of char* pointers is at the beginning of it,
2539 * followed by strings themself.
2540 * Caller can deallocate entire list by single free(list). */
2542 /* Store given string, finalizing the word and starting new one whenever
2543 * we encounter IFS char(s). This is used for expanding variable values.
2544 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2545 static int expand_on_ifs(o_string *output, int n, const char *str)
2548 int word_len = strcspn(str, G.ifs);
2550 if (output->o_escape || !output->o_glob)
2551 o_addQblock(output, str, word_len);
2552 else /* protect backslashes against globbing up :) */
2553 o_addblock_duplicate_backslash(output, str, word_len);
2556 if (!*str) /* EOL - do not finalize word */
2558 o_addchr(output, '\0');
2559 debug_print_list("expand_on_ifs", output, n);
2560 n = o_save_ptr(output, n);
2561 str += strspn(str, G.ifs); /* skip ifs chars */
2563 debug_print_list("expand_on_ifs[1]", output, n);
2567 /* Helper to expand $((...)) and heredoc body. These act as if
2568 * they are in double quotes, with the exception that they are not :).
2569 * Just the rules are similar: "expand only $var and `cmd`"
2571 * Returns malloced string.
2572 * As an optimization, we return NULL if expansion is not needed.
2574 static char *expand_pseudo_dquoted(const char *str)
2577 struct in_str input;
2578 o_string dest = NULL_O_STRING;
2580 if (!strchr(str, '$')
2581 #if ENABLE_HUSH_TICK
2582 && !strchr(str, '`')
2588 /* We need to expand. Example:
2589 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2591 setup_string_in_str(&input, str);
2592 parse_stream_dquoted(NULL, &dest, &input, EOF);
2593 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2594 exp_str = expand_string_to_string(dest.data);
2595 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2596 o_free_unsafe(&dest);
2600 #if ENABLE_SH_MATH_SUPPORT
2601 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2603 arith_eval_hooks_t hooks;
2607 hooks.lookupvar = get_local_var_value;
2608 hooks.setvar = set_local_var_from_halves;
2609 hooks.endofname = endofname;
2610 exp_str = expand_pseudo_dquoted(arg);
2611 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2617 #if ENABLE_HUSH_BASH_COMPAT
2618 /* ${var/[/]pattern[/repl]} helpers */
2619 static char *strstr_pattern(char *val, const char *pattern, int *size)
2622 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
2623 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
2630 /* Optimization: if "*pat" did not match the start of "string",
2631 * we know that "tring", "ring" etc will not match too:
2633 if (pattern[0] == '*')
2638 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
2640 char *result = NULL;
2641 unsigned res_len = 0;
2642 unsigned repl_len = strlen(repl);
2646 char *s = strstr_pattern(val, pattern, &size);
2650 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
2651 memcpy(result + res_len, val, s - val);
2653 strcpy(result + res_len, repl);
2654 res_len += repl_len;
2655 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
2661 if (val[0] && result) {
2662 result = xrealloc(result, res_len + strlen(val) + 1);
2663 strcpy(result + res_len, val);
2664 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
2666 debug_printf_varexp("result:'%s'\n", result);
2672 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
2674 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
2676 const char *val = NULL;
2677 char *to_be_freed = NULL;
2682 char exp_save = exp_save; /* for compiler */
2683 char *exp_saveptr; /* points to expansion operator */
2684 char *exp_word = exp_word; /* for compiler */
2688 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
2689 first_char = arg[0] = first_ch & 0x7f;
2692 if (first_char == '#' && arg[1] && !exp_saveptr) {
2693 /* handle length expansion ${#var} */
2697 /* maybe handle parameter expansion */
2698 if (exp_saveptr /* if 2nd char is one of expansion operators */
2699 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2701 /* ${?:0}, ${#[:]%0} etc */
2702 exp_saveptr = var + 1;
2704 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2705 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
2707 exp_op = exp_save = *exp_saveptr;
2709 exp_word = exp_saveptr + 1;
2710 if (exp_op == ':') {
2711 exp_op = *exp_word++;
2712 if (ENABLE_HUSH_BASH_COMPAT
2713 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
2715 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2720 *exp_saveptr = '\0';
2721 } /* else: it's not an expansion op, but bare ${var} */
2724 /* lookup the variable in question */
2725 if (isdigit(var[0])) {
2726 /* parse_dollar() should have vetted var for us */
2727 int n = xatoi_positive(var);
2728 if (n < G.global_argc)
2729 val = G.global_argv[n];
2730 /* else val remains NULL: $N with too big N */
2734 val = utoa(G.root_pid);
2736 case '!': /* bg pid */
2737 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
2739 case '?': /* exitcode */
2740 val = utoa(G.last_exitcode);
2742 case '#': /* argc */
2743 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2746 val = get_local_var_value(var);
2750 /* Handle any expansions */
2751 if (exp_op == 'L') {
2752 debug_printf_expand("expand: length(%s)=", val);
2753 val = utoa(val ? strlen(val) : 0);
2754 debug_printf_expand("%s\n", val);
2755 } else if (exp_op) {
2756 if (exp_op == '%' || exp_op == '#') {
2757 /* Standard-mandated substring removal ops:
2758 * ${parameter%word} - remove smallest suffix pattern
2759 * ${parameter%%word} - remove largest suffix pattern
2760 * ${parameter#word} - remove smallest prefix pattern
2761 * ${parameter##word} - remove largest prefix pattern
2763 * Word is expanded to produce a glob pattern.
2764 * Then var's value is matched to it and matching part removed.
2766 if (val && val[0]) {
2769 unsigned scan_flags = pick_scan(exp_op, *exp_word);
2770 if (exp_op == *exp_word) /* ## or %% */
2772 //TODO: avoid xstrdup unless needed
2773 // (see HACK ALERT below)
2774 val = to_be_freed = xstrdup(val);
2775 exp_exp_word = expand_pseudo_dquoted(exp_word);
2777 exp_word = exp_exp_word;
2778 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
2779 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2780 // exp_op, to_be_freed, exp_word, loc);
2782 if (loc) { /* match was found */
2783 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
2790 #if ENABLE_HUSH_BASH_COMPAT
2791 else if (exp_op == '/' || exp_op == '\\') {
2792 /* Empty variable always gives nothing: */
2793 // "v=''; echo ${v/*/w}" prints ""
2794 if (val && val[0]) {
2795 /* It's ${var/[/]pattern[/repl]} thing */
2796 char *pattern, *repl, *t;
2797 pattern = expand_pseudo_dquoted(exp_word);
2799 pattern = xstrdup(exp_word);
2800 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
2801 *p++ = SPECIAL_VAR_SYMBOL;
2803 p = strchr(p, SPECIAL_VAR_SYMBOL);
2805 repl = expand_pseudo_dquoted(exp_word);
2806 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
2807 /* HACK ALERT. We depend here on the fact that
2808 * G.global_argv and results of utoa and get_local_var_value
2809 * are actually in writable memory:
2810 * replace_pattern momentarily stores NULs there. */
2812 to_be_freed = replace_pattern(t,
2814 (repl ? repl : exp_word),
2816 if (to_be_freed) /* at least one replace happened */
2823 else if (exp_op == ':') {
2824 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2825 /* It's ${var:N[:M]} bashism.
2826 * Note that in encoded form it has TWO parts:
2827 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2832 beg = expand_and_evaluate_arith(exp_word, &errcode);
2833 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2834 *p++ = SPECIAL_VAR_SYMBOL;
2836 p = strchr(p, SPECIAL_VAR_SYMBOL);
2838 len = expand_and_evaluate_arith(exp_word, &errcode);
2839 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2841 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2842 if (beg < 0) /* bash compat */
2844 debug_printf_varexp("from val:'%s'\n", val);
2845 if (len == 0 || !val || beg >= strlen(val))
2848 /* Paranoia. What if user entered 9999999999999
2849 * which fits in arith_t but not int? */
2852 val = to_be_freed = xstrndup(val + beg, len);
2854 debug_printf_varexp("val:'%s'\n", val);
2858 die_if_script("malformed ${%s:...}", var);
2861 } else { /* one of "-=+?" */
2862 /* Standard-mandated substitution ops:
2863 * ${var?word} - indicate error if unset
2864 * If var is unset, word (or a message indicating it is unset
2865 * if word is null) is written to standard error
2866 * and the shell exits with a non-zero exit status.
2867 * Otherwise, the value of var is substituted.
2868 * ${var-word} - use default value
2869 * If var is unset, word is substituted.
2870 * ${var=word} - assign and use default value
2871 * If var is unset, word is assigned to var.
2872 * In all cases, final value of var is substituted.
2873 * ${var+word} - use alternative value
2874 * If var is unset, null is substituted.
2875 * Otherwise, word is substituted.
2877 * Word is subjected to tilde expansion, parameter expansion,
2878 * command substitution, and arithmetic expansion.
2879 * If word is not needed, it is not expanded.
2881 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2882 * but also treat null var as if it is unset.
2884 int use_word = (!val || ((exp_save == ':') && !val[0]));
2886 use_word = !use_word;
2887 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2888 (exp_save == ':') ? "true" : "false", use_word);
2890 to_be_freed = expand_pseudo_dquoted(exp_word);
2892 exp_word = to_be_freed;
2893 if (exp_op == '?') {
2894 /* mimic bash message */
2895 die_if_script("%s: %s",
2897 exp_word[0] ? exp_word : "parameter null or not set"
2899 //TODO: how interactive bash aborts expansion mid-command?
2904 if (exp_op == '=') {
2905 /* ${var=[word]} or ${var:=[word]} */
2906 if (isdigit(var[0]) || var[0] == '#') {
2907 /* mimic bash message */
2908 die_if_script("$%s: cannot assign in this way", var);
2911 char *new_var = xasprintf("%s=%s", var, val);
2912 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2916 } /* one of "-=+?" */
2918 *exp_saveptr = exp_save;
2924 *to_be_freed_pp = to_be_freed;
2928 /* Expand all variable references in given string, adding words to list[]
2929 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2930 * to be filled). This routine is extremely tricky: has to deal with
2931 * variables/parameters with whitespace, $* and $@, and constructs like
2932 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2933 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2935 /* or_mask is either 0 (normal case) or 0x80 -
2936 * expansion of right-hand side of assignment == 1-element expand.
2937 * It will also do no globbing, and thus we must not backslash-quote!
2944 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2945 debug_print_list("expand_vars_to_list", output, n);
2946 n = o_save_ptr(output, n);
2947 debug_print_list("expand_vars_to_list[0]", output, n);
2949 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2952 char *to_be_freed = NULL;
2953 const char *val = NULL;
2954 #if ENABLE_HUSH_TICK
2955 o_string subst_result = NULL_O_STRING;
2957 #if ENABLE_SH_MATH_SUPPORT
2958 char arith_buf[sizeof(arith_t)*3 + 2];
2960 o_addblock(output, arg, p - arg);
2961 debug_print_list("expand_vars_to_list[1]", output, n);
2963 p = strchr(p, SPECIAL_VAR_SYMBOL);
2965 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2966 /* "$@" is special. Even if quoted, it can still
2967 * expand to nothing (not even an empty string) */
2968 if ((first_ch & 0x7f) != '@')
2969 ored_ch |= first_ch;
2971 switch (first_ch & 0x7f) {
2972 /* Highest bit in first_ch indicates that var is double-quoted */
2976 if (!G.global_argv[i])
2978 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2979 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2980 smallint sv = output->o_escape;
2981 /* unquoted var's contents should be globbed, so don't escape */
2982 output->o_escape = 0;
2983 while (G.global_argv[i]) {
2984 n = expand_on_ifs(output, n, G.global_argv[i]);
2985 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2986 if (G.global_argv[i++][0] && G.global_argv[i]) {
2987 /* this argv[] is not empty and not last:
2988 * put terminating NUL, start new word */
2989 o_addchr(output, '\0');
2990 debug_print_list("expand_vars_to_list[2]", output, n);
2991 n = o_save_ptr(output, n);
2992 debug_print_list("expand_vars_to_list[3]", output, n);
2995 output->o_escape = sv;
2997 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2998 * and in this case should treat it like '$*' - see 'else...' below */
2999 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
3001 o_addQstr(output, G.global_argv[i]);
3002 if (++i >= G.global_argc)
3004 o_addchr(output, '\0');
3005 debug_print_list("expand_vars_to_list[4]", output, n);
3006 n = o_save_ptr(output, n);
3008 } else { /* quoted $*: add as one word */
3010 o_addQstr(output, G.global_argv[i]);
3011 if (!G.global_argv[++i])
3014 o_addchr(output, G.ifs[0]);
3018 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
3019 /* "Empty variable", used to make "" etc to not disappear */
3023 #if ENABLE_HUSH_TICK
3024 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
3027 /* Can't just stuff it into output o_string,
3028 * expanded result may need to be globbed
3029 * and $IFS-splitted */
3030 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
3031 G.last_exitcode = process_command_subs(&subst_result, arg);
3032 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
3033 val = subst_result.data;
3036 #if ENABLE_SH_MATH_SUPPORT
3037 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
3041 arg++; /* skip '+' */
3042 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
3043 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
3044 res = expand_and_evaluate_arith(arg, &errcode);
3047 const char *msg = "error in arithmetic";
3050 msg = "exponent less than 0";
3053 msg = "divide by 0";
3056 msg = "expression recursion loop detected";
3061 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
3062 sprintf(arith_buf, arith_t_fmt, res);
3068 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
3069 IF_HUSH_TICK(store_val:)
3070 if (!(first_ch & 0x80)) { /* unquoted $VAR */
3071 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
3072 if (val && val[0]) {
3073 /* unquoted var's contents should be globbed, so don't escape */
3074 smallint sv = output->o_escape;
3075 output->o_escape = 0;
3076 n = expand_on_ifs(output, n, val);
3078 output->o_escape = sv;
3080 } else { /* quoted $VAR, val will be appended below */
3081 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
3085 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
3087 if (val && val[0]) {
3088 o_addQstr(output, val);
3091 /* Do the check to avoid writing to a const string */
3092 if (*p != SPECIAL_VAR_SYMBOL)
3093 *p = SPECIAL_VAR_SYMBOL;
3095 #if ENABLE_HUSH_TICK
3096 o_free(&subst_result);
3099 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
3102 debug_print_list("expand_vars_to_list[a]", output, n);
3103 /* this part is literal, and it was already pre-quoted
3104 * if needed (much earlier), do not use o_addQstr here! */
3105 o_addstr_with_NUL(output, arg);
3106 debug_print_list("expand_vars_to_list[b]", output, n);
3107 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
3108 && !(ored_ch & 0x80) /* and all vars were not quoted. */
3111 /* allow to reuse list[n] later without re-growth */
3112 output->has_empty_slot = 1;
3114 o_addchr(output, '\0');
3121 EXPVAR_FLAG_GLOB = 0x200,
3122 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
3123 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
3125 static char **expand_variables(char **argv, unsigned or_mask)
3130 o_string output = NULL_O_STRING;
3132 /* protect against globbing for "$var"? */
3133 /* (unquoted $var will temporarily switch it off) */
3134 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
3135 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
3140 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
3143 debug_print_list("expand_variables", &output, n);
3145 /* output.data (malloced in one block) gets returned in "list" */
3146 list = o_finalize_list(&output, n);
3147 debug_print_strings("expand_variables[1]", list);
3151 static char **expand_strvec_to_strvec(char **argv)
3153 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
3156 #if ENABLE_HUSH_BASH_COMPAT
3157 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3159 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
3163 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3164 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3169 o_string output = NULL_O_STRING;
3174 int is_var = is_well_formed_var_name(*v, '=');
3175 /* is_var * 0x80: singleword expansion for vars */
3176 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3178 /* Subtle! expand_vars_to_list did not glob last word yet.
3179 * It does this only when fed with further data.
3180 * Therefore we set globbing flags AFTER it, not before:
3183 /* if it is not recognizably abc=...; then: */
3184 output.o_escape = !is_var; /* protect against globbing for "$var" */
3185 /* (unquoted $var will temporarily switch it off) */
3186 output.o_glob = !is_var; /* and indeed do globbing */
3189 debug_print_list("expand_cond", &output, n);
3191 /* output.data (malloced in one block) gets returned in "list" */
3192 list = o_finalize_list(&output, n);
3193 debug_print_strings("expand_cond[1]", list);
3198 /* Used for expansion of right hand of assignments */
3199 /* NB: should NOT do globbing!
3200 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
3201 static char *expand_string_to_string(const char *str)
3203 char *argv[2], **list;
3205 /* This is generally an optimization, but it also
3206 * handles "", which otherwise trips over !list[0] check below.
3207 * (is this ever happens that we actually get str="" here?)
3209 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
3210 //TODO: Can use on strings with \ too, just unbackslash() them?
3211 debug_printf_expand("string_to_string(fast)='%s'\n", str);
3212 return xstrdup(str);
3215 argv[0] = (char*)str;
3217 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
3219 if (!list[0] || list[1])
3220 bb_error_msg_and_die("BUG in varexp2");
3221 /* actually, just move string 2*sizeof(char*) bytes back */
3222 overlapping_strcpy((char*)list, list[0]);
3223 unbackslash((char*)list);
3224 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3228 /* Used for "eval" builtin */
3229 static char* expand_strvec_to_string(char **argv)
3233 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
3234 /* Convert all NULs to spaces */
3239 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3240 bb_error_msg_and_die("BUG in varexp3");
3241 /* bash uses ' ' regardless of $IFS contents */
3246 overlapping_strcpy((char*)list, list[0]);
3247 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3251 static char **expand_assignments(char **argv, int count)
3256 G.expanded_assignments = p = NULL;
3257 /* Expand assignments into one string each */
3258 for (i = 0; i < count; i++) {
3259 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3261 G.expanded_assignments = NULL;
3268 void re_execute_shell(char ***to_free, const char *s,
3269 char *g_argv0, char **g_argv,
3270 char **builtin_argv) NORETURN;
3272 static void reset_traps_to_defaults(void)
3274 /* This function is always called in a child shell
3275 * after fork (not vfork, NOMMU doesn't use this function).
3280 /* Child shells are not interactive.
3281 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3282 * Testcase: (while :; do :; done) + ^Z should background.
3283 * Same goes for SIGTERM, SIGHUP, SIGINT.
3285 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
3286 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
3288 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3289 * Stupid. It can be done with *single* &= op, but we can't use
3290 * the fact that G.blocked_set is implemented as a bitmask
3292 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3296 /* Careful. Only if no trap or trap is not "" */
3297 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3298 sigdelset(&G.blocked_set, sig);
3305 /* Our homegrown sig mask is saner to work with :) */
3306 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3308 /* Resetting all traps to default except empty ones */
3309 mask = G.non_DFL_mask;
3310 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3311 if (!G.traps[sig] || !G.traps[sig][0])
3314 G.traps[sig] = NULL;
3315 /* There is no signal for 0 (EXIT) */
3318 /* There was a trap handler, we just removed it.
3319 * But if sig still has non-DFL handling,
3320 * we should not unblock the sig. */
3323 sigdelset(&G.blocked_set, sig);
3325 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3330 static void re_execute_shell(char ***to_free, const char *s,
3331 char *g_argv0, char **g_argv,
3332 char **builtin_argv) NORETURN;
3333 static void re_execute_shell(char ***to_free, const char *s,
3334 char *g_argv0, char **g_argv,
3335 char **builtin_argv)
3337 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3338 /* delims + 2 * (number of bytes in printed hex numbers) */
3339 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3340 char *heredoc_argv[4];
3341 struct variable *cur;
3342 # if ENABLE_HUSH_FUNCTIONS
3343 struct function *funcp;
3347 unsigned long long empty_trap_mask;
3349 if (!g_argv0) { /* heredoc */
3350 argv = heredoc_argv;
3351 argv[0] = (char *) G.argv0_for_re_execing;
3352 argv[1] = (char *) "-<";
3353 argv[2] = (char *) s;
3355 pp = &argv[3]; /* used as pointer to empty environment */
3361 if (pp) while (*pp++)
3364 empty_trap_mask = 0;
3367 for (sig = 1; sig < NSIG; sig++) {
3368 if (G.traps[sig] && !G.traps[sig][0])
3369 empty_trap_mask |= 1LL << sig;
3373 sprintf(param_buf, NOMMU_HACK_FMT
3374 , (unsigned) G.root_pid
3375 , (unsigned) G.root_ppid
3376 , (unsigned) G.last_bg_pid
3377 , (unsigned) G.last_exitcode
3380 IF_HUSH_LOOPS(, G.depth_of_loop)
3382 # undef NOMMU_HACK_FMT
3383 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3384 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3387 for (cur = G.top_var; cur; cur = cur->next) {
3388 if (!cur->flg_export || cur->flg_read_only)
3391 # if ENABLE_HUSH_FUNCTIONS
3392 for (funcp = G.top_func; funcp; funcp = funcp->next)
3398 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3399 *pp++ = (char *) G.argv0_for_re_execing;
3401 for (cur = G.top_var; cur; cur = cur->next) {
3402 if (strcmp(cur->varstr, hush_version_str) == 0)
3404 if (cur->flg_read_only) {
3405 *pp++ = (char *) "-R";
3406 *pp++ = cur->varstr;
3407 } else if (!cur->flg_export) {
3408 *pp++ = (char *) "-V";
3409 *pp++ = cur->varstr;
3412 # if ENABLE_HUSH_FUNCTIONS
3413 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3414 *pp++ = (char *) "-F";
3415 *pp++ = funcp->name;
3416 *pp++ = funcp->body_as_string;
3419 /* We can pass activated traps here. Say, -Tnn:trap_string
3421 * However, POSIX says that subshells reset signals with traps
3423 * I tested bash-3.2 and it not only does that with true subshells
3424 * of the form ( list ), but with any forked children shells.
3425 * I set trap "echo W" WINCH; and then tried:
3427 * { echo 1; sleep 20; echo 2; } &
3428 * while true; do echo 1; sleep 20; echo 2; break; done &
3429 * true | { echo 1; sleep 20; echo 2; } | cat
3431 * In all these cases sending SIGWINCH to the child shell
3432 * did not run the trap. If I add trap "echo V" WINCH;
3433 * _inside_ group (just before echo 1), it works.
3435 * I conclude it means we don't need to pass active traps here.
3436 * Even if we would use signal handlers instead of signal masking
3437 * in order to implement trap handling,
3438 * exec syscall below resets signals to SIG_DFL for us.
3440 *pp++ = (char *) "-c";
3443 while (*++builtin_argv)
3444 *pp++ = *builtin_argv;
3445 *pp++ = (char *) "";
3450 /* *pp = NULL; - is already there */
3454 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3455 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3456 execve(bb_busybox_exec_path, argv, pp);
3457 /* Fallback. Useful for init=/bin/hush usage etc */
3458 if (argv[0][0] == '/')
3459 execve(argv[0], argv, pp);
3460 xfunc_error_retval = 127;
3461 bb_error_msg_and_die("can't re-execute the shell");
3463 #endif /* !BB_MMU */
3466 static void setup_heredoc(struct redir_struct *redir)
3468 struct fd_pair pair;
3471 /* the _body_ of heredoc (misleading field name) */
3472 const char *heredoc = redir->rd_filename;
3479 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3480 expanded = expand_pseudo_dquoted(heredoc);
3484 len = strlen(heredoc);
3486 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3488 xmove_fd(pair.rd, redir->rd_fd);
3490 /* Try writing without forking. Newer kernels have
3491 * dynamically growing pipes. Must use non-blocking write! */
3494 written = write(pair.wr, heredoc, len);
3505 ndelay_off(pair.wr);
3507 /* Okay, pipe buffer was not big enough */
3508 /* Note: we must not create a stray child (bastard? :)
3509 * for the unsuspecting parent process. Child creates a grandchild
3510 * and exits before parent execs the process which consumes heredoc
3511 * (that exec happens after we return from this function) */
3518 disable_restore_tty_pgrp_on_exit();
3519 pid = BB_MMU ? xfork() : xvfork();
3523 close(redir->rd_fd); /* read side of the pipe */
3525 full_write(pair.wr, heredoc, len); /* may loop or block */
3528 /* Delegate blocking writes to another process */
3529 xmove_fd(pair.wr, STDOUT_FILENO);
3530 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3534 #if ENABLE_HUSH_FAST
3536 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3538 enable_restore_tty_pgrp_on_exit();
3544 wait(NULL); /* wait till child has died */
3547 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3548 * and stderr if they are redirected. */
3549 static int setup_redirects(struct command *prog, int squirrel[])
3552 struct redir_struct *redir;
3554 for (redir = prog->redirects; redir; redir = redir->next) {
3555 if (redir->rd_type == REDIRECT_HEREDOC2) {
3556 /* rd_fd<<HERE case */
3557 if (squirrel && redir->rd_fd < 3
3558 && squirrel[redir->rd_fd] < 0
3560 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3562 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3564 debug_printf_parse("set heredoc '%s'\n",
3565 redir->rd_filename);
3566 setup_heredoc(redir);
3570 if (redir->rd_dup == REDIRFD_TO_FILE) {
3571 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3573 if (redir->rd_filename == NULL) {
3574 /* Something went wrong in the parse.
3575 * Pretend it didn't happen */
3576 bb_error_msg("bug in redirect parse");
3579 mode = redir_table[redir->rd_type].mode;
3580 p = expand_string_to_string(redir->rd_filename);
3581 openfd = open_or_warn(p, mode);
3584 /* this could get lost if stderr has been redirected, but
3585 * bash and ash both lose it as well (though zsh doesn't!) */
3586 //what the above comment tries to say?
3590 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3591 openfd = redir->rd_dup;
3594 if (openfd != redir->rd_fd) {
3595 if (squirrel && redir->rd_fd < 3
3596 && squirrel[redir->rd_fd] < 0
3598 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3600 if (openfd == REDIRFD_CLOSE) {
3601 /* "n>-" means "close me" */
3602 close(redir->rd_fd);
3604 xdup2(openfd, redir->rd_fd);
3605 if (redir->rd_dup == REDIRFD_TO_FILE)
3613 static void restore_redirects(int squirrel[])
3616 for (i = 0; i < 3; i++) {
3619 /* We simply die on error */
3626 static void free_pipe_list(struct pipe *head);
3628 /* Return code is the exit status of the pipe */
3629 static void free_pipe(struct pipe *pi)
3632 struct command *command;
3633 struct redir_struct *r, *rnext;
3636 if (pi->stopped_cmds > 0) /* why? */
3638 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3639 for (i = 0; i < pi->num_cmds; i++) {
3640 command = &pi->cmds[i];
3641 debug_printf_clean(" command %d:\n", i);
3642 if (command->argv) {
3643 for (a = 0, p = command->argv; *p; a++, p++) {
3644 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3646 free_strings(command->argv);
3647 command->argv = NULL;
3649 /* not "else if": on syntax error, we may have both! */
3650 if (command->group) {
3651 debug_printf_clean(" begin group (cmd_type:%d)\n",
3653 free_pipe_list(command->group);
3654 debug_printf_clean(" end group\n");
3655 command->group = NULL;
3657 /* else is crucial here.
3658 * If group != NULL, child_func is meaningless */
3659 #if ENABLE_HUSH_FUNCTIONS
3660 else if (command->child_func) {
3661 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3662 command->child_func->parent_cmd = NULL;
3666 free(command->group_as_string);
3667 command->group_as_string = NULL;
3669 for (r = command->redirects; r; r = rnext) {
3670 debug_printf_clean(" redirect %d%s",
3671 r->rd_fd, redir_table[r->rd_type].descrip);
3672 /* guard against the case >$FOO, where foo is unset or blank */
3673 if (r->rd_filename) {
3674 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3675 free(r->rd_filename);
3676 r->rd_filename = NULL;
3678 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3682 command->redirects = NULL;
3684 free(pi->cmds); /* children are an array, they get freed all at once */
3692 static void free_pipe_list(struct pipe *head)
3694 struct pipe *pi, *next;
3696 for (pi = head; pi; pi = next) {
3698 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3701 debug_printf_clean("pipe followup code %d\n", pi->followup);
3703 /*pi->next = NULL;*/
3709 static int run_list(struct pipe *pi);
3711 #define parse_stream(pstring, input, end_trigger) \
3712 parse_stream(input, end_trigger)
3714 static struct pipe *parse_stream(char **pstring,
3715 struct in_str *input,
3717 static void parse_and_run_string(const char *s);
3720 static char *find_in_path(const char *arg)
3723 const char *PATH = get_local_var_value("PATH");
3729 const char *end = strchrnul(PATH, ':');
3730 int sz = end - PATH; /* must be int! */
3734 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3736 /* We have xxx::yyyy in $PATH,
3737 * it means "use current dir" */
3740 if (access(ret, F_OK) == 0)
3753 static const struct built_in_command* find_builtin_helper(const char *name,
3754 const struct built_in_command *x,
3755 const struct built_in_command *end)
3758 if (strcmp(name, x->b_cmd) != 0) {
3762 debug_printf_exec("found builtin '%s'\n", name);
3767 static const struct built_in_command* find_builtin1(const char *name)
3769 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3771 static const struct built_in_command* find_builtin(const char *name)
3773 const struct built_in_command *x = find_builtin1(name);
3776 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3779 #if ENABLE_HUSH_FUNCTIONS
3780 static struct function **find_function_slot(const char *name)
3782 struct function **funcpp = &G.top_func;
3784 if (strcmp(name, (*funcpp)->name) == 0) {
3787 funcpp = &(*funcpp)->next;
3792 static const struct function *find_function(const char *name)
3794 const struct function *funcp = *find_function_slot(name);
3796 debug_printf_exec("found function '%s'\n", name);
3800 /* Note: takes ownership on name ptr */
3801 static struct function *new_function(char *name)
3803 struct function **funcpp = find_function_slot(name);
3804 struct function *funcp = *funcpp;
3806 if (funcp != NULL) {
3807 struct command *cmd = funcp->parent_cmd;
3808 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3810 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3812 /* Note: if !funcp->body, do not free body_as_string!
3813 * This is a special case of "-F name body" function:
3814 * body_as_string was not malloced! */
3816 free_pipe_list(funcp->body);
3818 free(funcp->body_as_string);
3822 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3823 cmd->argv[0] = funcp->name;
3824 cmd->group = funcp->body;
3826 cmd->group_as_string = funcp->body_as_string;
3830 debug_printf_exec("remembering new function '%s'\n", name);
3831 funcp = *funcpp = xzalloc(sizeof(*funcp));
3832 /*funcp->next = NULL;*/
3839 static void unset_func(const char *name)
3841 struct function **funcpp = find_function_slot(name);
3842 struct function *funcp = *funcpp;
3844 if (funcp != NULL) {
3845 debug_printf_exec("freeing function '%s'\n", funcp->name);
3846 *funcpp = funcp->next;
3847 /* funcp is unlinked now, deleting it.
3848 * Note: if !funcp->body, the function was created by
3849 * "-F name body", do not free ->body_as_string
3850 * and ->name as they were not malloced. */
3852 free_pipe_list(funcp->body);
3855 free(funcp->body_as_string);
3863 #define exec_function(to_free, funcp, argv) \
3864 exec_function(funcp, argv)
3866 static void exec_function(char ***to_free,
3867 const struct function *funcp,
3868 char **argv) NORETURN;
3869 static void exec_function(char ***to_free,
3870 const struct function *funcp,
3876 argv[0] = G.global_argv[0];
3877 G.global_argv = argv;
3881 /* On MMU, funcp->body is always non-NULL */
3882 n = run_list(funcp->body);
3886 re_execute_shell(to_free,
3887 funcp->body_as_string,
3894 static int run_function(const struct function *funcp, char **argv)
3900 save_and_replace_G_args(&sv, argv);
3902 /* "we are in function, ok to use return" */
3903 sv_flg = G.flag_return_in_progress;
3904 G.flag_return_in_progress = -1;
3905 # if ENABLE_HUSH_LOCAL
3906 G.func_nest_level++;
3909 /* On MMU, funcp->body is always non-NULL */
3912 /* Function defined by -F */
3913 parse_and_run_string(funcp->body_as_string);
3914 rc = G.last_exitcode;
3918 rc = run_list(funcp->body);
3921 # if ENABLE_HUSH_LOCAL
3923 struct variable *var;
3924 struct variable **var_pp;
3926 var_pp = &G.top_var;
3927 while ((var = *var_pp) != NULL) {
3928 if (var->func_nest_level < G.func_nest_level) {
3929 var_pp = &var->next;
3933 if (var->flg_export)
3934 bb_unsetenv(var->varstr);
3935 /* Remove from global list */
3936 *var_pp = var->next;
3942 G.func_nest_level--;
3945 G.flag_return_in_progress = sv_flg;
3947 restore_G_args(&sv, argv);
3951 #endif /* ENABLE_HUSH_FUNCTIONS */
3955 #define exec_builtin(to_free, x, argv) \
3956 exec_builtin(x, argv)
3958 #define exec_builtin(to_free, x, argv) \
3959 exec_builtin(to_free, argv)
3961 static void exec_builtin(char ***to_free,
3962 const struct built_in_command *x,
3963 char **argv) NORETURN;
3964 static void exec_builtin(char ***to_free,
3965 const struct built_in_command *x,
3969 int rcode = x->b_function(argv);
3973 /* On NOMMU, we must never block!
3974 * Example: { sleep 99 | read line; } & echo Ok
3976 re_execute_shell(to_free,
3985 static void execvp_or_die(char **argv) NORETURN;
3986 static void execvp_or_die(char **argv)
3988 debug_printf_exec("execing '%s'\n", argv[0]);
3989 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3990 execvp(argv[0], argv);
3991 bb_perror_msg("can't execute '%s'", argv[0]);
3992 _exit(127); /* bash compat */
3995 #if ENABLE_HUSH_MODE_X
3996 static void dump_cmd_in_x_mode(char **argv)
3998 if (G_x_mode && argv) {
3999 /* We want to output the line in one write op */
4007 len += strlen(argv[n++]) + 1;
4013 p += sprintf(p, " %s", argv[n++]);
4021 # define dump_cmd_in_x_mode(argv) ((void)0)
4025 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
4026 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
4027 #define pseudo_exec(nommu_save, command, argv_expanded) \
4028 pseudo_exec(command, argv_expanded)
4031 /* Called after [v]fork() in run_pipe, or from builtin_exec.
4033 * Don't exit() here. If you don't exec, use _exit instead.
4034 * The at_exit handlers apparently confuse the calling process,
4035 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
4036 static void pseudo_exec_argv(nommu_save_t *nommu_save,
4037 char **argv, int assignment_cnt,
4038 char **argv_expanded) NORETURN;
4039 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
4040 char **argv, int assignment_cnt,
4041 char **argv_expanded)
4045 new_env = expand_assignments(argv, assignment_cnt);
4046 dump_cmd_in_x_mode(new_env);
4048 if (!argv[assignment_cnt]) {
4049 /* Case when we are here: ... | var=val | ...
4050 * (note that we do not exit early, i.e., do not optimize out
4051 * expand_assignments(): think about ... | var=`sleep 1` | ...
4053 free_strings(new_env);
4054 _exit(EXIT_SUCCESS);
4058 set_vars_and_save_old(new_env);
4059 free(new_env); /* optional */
4060 /* we can also destroy set_vars_and_save_old's return value,
4063 nommu_save->new_env = new_env;
4064 nommu_save->old_vars = set_vars_and_save_old(new_env);
4067 if (argv_expanded) {
4068 argv = argv_expanded;
4070 argv = expand_strvec_to_strvec(argv + assignment_cnt);
4072 nommu_save->argv = argv;
4075 dump_cmd_in_x_mode(argv);
4077 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
4078 if (strchr(argv[0], '/') != NULL)
4082 /* Check if the command matches any of the builtins.
4083 * Depending on context, this might be redundant. But it's
4084 * easier to waste a few CPU cycles than it is to figure out
4085 * if this is one of those cases.
4088 /* On NOMMU, it is more expensive to re-execute shell
4089 * just in order to run echo or test builtin.
4090 * It's better to skip it here and run corresponding
4091 * non-builtin later. */
4092 const struct built_in_command *x;
4093 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
4095 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
4098 #if ENABLE_HUSH_FUNCTIONS
4099 /* Check if the command matches any functions */
4101 const struct function *funcp = find_function(argv[0]);
4103 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
4108 #if ENABLE_FEATURE_SH_STANDALONE
4109 /* Check if the command matches any busybox applets */
4111 int a = find_applet_by_name(argv[0]);
4113 # if BB_MMU /* see above why on NOMMU it is not allowed */
4114 if (APPLET_IS_NOEXEC(a)) {
4115 debug_printf_exec("running applet '%s'\n", argv[0]);
4116 run_applet_no_and_exit(a, argv);
4119 /* Re-exec ourselves */
4120 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
4121 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
4122 execv(bb_busybox_exec_path, argv);
4123 /* If they called chroot or otherwise made the binary no longer
4124 * executable, fall through */
4129 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
4132 execvp_or_die(argv);
4135 /* Called after [v]fork() in run_pipe
4137 static void pseudo_exec(nommu_save_t *nommu_save,
4138 struct command *command,
4139 char **argv_expanded) NORETURN;
4140 static void pseudo_exec(nommu_save_t *nommu_save,
4141 struct command *command,
4142 char **argv_expanded)
4144 if (command->argv) {
4145 pseudo_exec_argv(nommu_save, command->argv,
4146 command->assignment_cnt, argv_expanded);
4149 if (command->group) {
4150 /* Cases when we are here:
4153 * ... | ( list ) | ...
4154 * ... | { list } | ...
4158 debug_printf_exec("pseudo_exec: run_list\n");
4159 reset_traps_to_defaults();
4160 rcode = run_list(command->group);
4161 /* OK to leak memory by not calling free_pipe_list,
4162 * since this process is about to exit */
4165 re_execute_shell(&nommu_save->argv_from_re_execing,
4166 command->group_as_string,
4173 /* Case when we are here: ... | >file */
4174 debug_printf_exec("pseudo_exec'ed null command\n");
4175 _exit(EXIT_SUCCESS);
4179 static const char *get_cmdtext(struct pipe *pi)
4185 /* This is subtle. ->cmdtext is created only on first backgrounding.
4186 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
4187 * On subsequent bg argv is trashed, but we won't use it */
4190 argv = pi->cmds[0].argv;
4191 if (!argv || !argv[0]) {
4192 pi->cmdtext = xzalloc(1);
4198 len += strlen(*argv) + 1;
4202 argv = pi->cmds[0].argv;
4204 len = strlen(*argv);
4205 memcpy(p, *argv, len);
4213 static void insert_bg_job(struct pipe *pi)
4215 struct pipe *job, **jobp;
4218 /* Linear search for the ID of the job to use */
4220 for (job = G.job_list; job; job = job->next)
4221 if (job->jobid >= pi->jobid)
4222 pi->jobid = job->jobid + 1;
4224 /* Add job to the list of running jobs */
4226 while ((job = *jobp) != NULL)
4228 job = *jobp = xmalloc(sizeof(*job));
4230 *job = *pi; /* physical copy */
4232 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4233 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
4234 for (i = 0; i < pi->num_cmds; i++) {
4235 job->cmds[i].pid = pi->cmds[i].pid;
4236 /* all other fields are not used and stay zero */
4238 job->cmdtext = xstrdup(get_cmdtext(pi));
4240 if (G_interactive_fd)
4241 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4242 G.last_jobid = job->jobid;
4245 static void remove_bg_job(struct pipe *pi)
4247 struct pipe *prev_pipe;
4249 if (pi == G.job_list) {
4250 G.job_list = pi->next;
4252 prev_pipe = G.job_list;
4253 while (prev_pipe->next != pi)
4254 prev_pipe = prev_pipe->next;
4255 prev_pipe->next = pi->next;
4258 G.last_jobid = G.job_list->jobid;
4263 /* Remove a backgrounded job */
4264 static void delete_finished_bg_job(struct pipe *pi)
4267 pi->stopped_cmds = 0;
4273 /* Check to see if any processes have exited -- if they
4274 * have, figure out why and see if a job has completed */
4275 static int checkjobs(struct pipe* fg_pipe)
4285 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4287 attributes = WUNTRACED;
4288 if (fg_pipe == NULL)
4289 attributes |= WNOHANG;
4292 #if ENABLE_HUSH_FAST
4293 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4294 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4295 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
4296 /* There was neither fork nor SIGCHLD since last waitpid */
4297 /* Avoid doing waitpid syscall if possible */
4298 if (!G.we_have_children) {
4302 if (fg_pipe == NULL) { /* is WNOHANG set? */
4303 /* We have children, but they did not exit
4304 * or stop yet (we saw no SIGCHLD) */
4307 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4311 /* Do we do this right?
4312 * bash-3.00# sleep 20 | false
4314 * [3]+ Stopped sleep 20 | false
4315 * bash-3.00# echo $?
4316 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4317 * [hush 1.14.0: yes we do it right]
4324 #if ENABLE_HUSH_FAST
4325 i = G.count_SIGCHLD;
4327 childpid = waitpid(-1, &status, attributes);
4328 if (childpid <= 0) {
4329 if (childpid && errno != ECHILD)
4330 bb_perror_msg("waitpid");
4331 #if ENABLE_HUSH_FAST
4332 else { /* Until next SIGCHLD, waitpid's are useless */
4333 G.we_have_children = (childpid == 0);
4334 G.handled_SIGCHLD = i;
4335 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4340 dead = WIFEXITED(status) || WIFSIGNALED(status);
4343 if (WIFSTOPPED(status))
4344 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4345 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4346 if (WIFSIGNALED(status))
4347 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4348 childpid, WTERMSIG(status), WEXITSTATUS(status));
4349 if (WIFEXITED(status))
4350 debug_printf_jobs("pid %d exited, exitcode %d\n",
4351 childpid, WEXITSTATUS(status));
4353 /* Were we asked to wait for fg pipe? */
4355 for (i = 0; i < fg_pipe->num_cmds; i++) {
4356 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4357 if (fg_pipe->cmds[i].pid != childpid)
4360 fg_pipe->cmds[i].pid = 0;
4361 fg_pipe->alive_cmds--;
4362 if (i == fg_pipe->num_cmds - 1) {
4363 /* last process gives overall exitstatus */
4364 rcode = WEXITSTATUS(status);
4365 /* bash prints killer signal's name for *last*
4366 * process in pipe (prints just newline for SIGINT).
4367 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4369 if (WIFSIGNALED(status)) {
4370 int sig = WTERMSIG(status);
4371 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4372 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4373 * Maybe we need to use sig | 128? */
4376 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4379 fg_pipe->cmds[i].is_stopped = 1;
4380 fg_pipe->stopped_cmds++;
4382 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4383 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4384 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4385 /* All processes in fg pipe have exited or stopped */
4386 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4387 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4388 * and "killall -STOP cat" */
4389 if (G_interactive_fd) {
4391 if (fg_pipe->alive_cmds)
4392 insert_bg_job(fg_pipe);
4396 if (!fg_pipe->alive_cmds)
4399 /* There are still running processes in the fg pipe */
4400 goto wait_more; /* do waitpid again */
4402 /* it wasnt fg_pipe, look for process in bg pipes */
4406 /* We asked to wait for bg or orphaned children */
4407 /* No need to remember exitcode in this case */
4408 for (pi = G.job_list; pi; pi = pi->next) {
4409 for (i = 0; i < pi->num_cmds; i++) {
4410 if (pi->cmds[i].pid == childpid)
4411 goto found_pi_and_prognum;
4414 /* Happens when shell is used as init process (init=/bin/sh) */
4415 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4416 continue; /* do waitpid again */
4418 found_pi_and_prognum:
4421 pi->cmds[i].pid = 0;
4423 if (!pi->alive_cmds) {
4424 if (G_interactive_fd)
4425 printf(JOB_STATUS_FORMAT, pi->jobid,
4426 "Done", pi->cmdtext);
4427 delete_finished_bg_job(pi);
4431 pi->cmds[i].is_stopped = 1;
4435 } /* while (waitpid succeeds)... */
4441 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4444 int rcode = checkjobs(fg_pipe);
4445 if (G_saved_tty_pgrp) {
4446 /* Job finished, move the shell to the foreground */
4447 p = getpgrp(); /* our process group id */
4448 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4449 tcsetpgrp(G_interactive_fd, p);
4455 /* Start all the jobs, but don't wait for anything to finish.
4458 * Return code is normally -1, when the caller has to wait for children
4459 * to finish to determine the exit status of the pipe. If the pipe
4460 * is a simple builtin command, however, the action is done by the
4461 * time run_pipe returns, and the exit code is provided as the
4464 * Returns -1 only if started some children. IOW: we have to
4465 * mask out retvals of builtins etc with 0xff!
4467 * The only case when we do not need to [v]fork is when the pipe
4468 * is single, non-backgrounded, non-subshell command. Examples:
4469 * cmd ; ... { list } ; ...
4470 * cmd && ... { list } && ...
4471 * cmd || ... { list } || ...
4472 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4473 * or (if SH_STANDALONE) an applet, and we can run the { list }
4474 * with run_list. If it isn't one of these, we fork and exec cmd.
4476 * Cases when we must fork:
4477 * non-single: cmd | cmd
4478 * backgrounded: cmd & { list } &
4479 * subshell: ( list ) [&]
4481 #if !ENABLE_HUSH_MODE_X
4482 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4483 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4485 static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4487 /* setup_redirects acts on file descriptors, not FILEs.
4488 * This is perfect for work that comes after exec().
4489 * Is it really safe for inline use? Experimentally,
4490 * things seem to work. */
4491 int rcode = setup_redirects(command, squirrel);
4493 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4494 *new_env_p = new_env;
4495 dump_cmd_in_x_mode(new_env);
4496 dump_cmd_in_x_mode(argv_expanded);
4498 *old_vars_p = set_vars_and_save_old(new_env);
4502 static NOINLINE int run_pipe(struct pipe *pi)
4504 static const char *const null_ptr = NULL;
4508 struct command *command;
4509 char **argv_expanded;
4511 /* it is not always needed, but we aim to smaller code */
4512 int squirrel[] = { -1, -1, -1 };
4515 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4518 IF_HUSH_JOB(pi->pgrp = -1;)
4519 pi->stopped_cmds = 0;
4520 command = &pi->cmds[0];
4521 argv_expanded = NULL;
4523 if (pi->num_cmds != 1
4524 || pi->followup == PIPE_BG
4525 || command->cmd_type == CMD_SUBSHELL
4532 debug_printf_exec(": group:%p argv:'%s'\n",
4533 command->group, command->argv ? command->argv[0] : "NONE");
4535 if (command->group) {
4536 #if ENABLE_HUSH_FUNCTIONS
4537 if (command->cmd_type == CMD_FUNCDEF) {
4538 /* "executing" func () { list } */
4539 struct function *funcp;
4541 funcp = new_function(command->argv[0]);
4542 /* funcp->name is already set to argv[0] */
4543 funcp->body = command->group;
4545 funcp->body_as_string = command->group_as_string;
4546 command->group_as_string = NULL;
4548 command->group = NULL;
4549 command->argv[0] = NULL;
4550 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4551 funcp->parent_cmd = command;
4552 command->child_func = funcp;
4554 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4556 return EXIT_SUCCESS;
4560 debug_printf("non-subshell group\n");
4561 rcode = 1; /* exitcode if redir failed */
4562 if (setup_redirects(command, squirrel) == 0) {
4563 debug_printf_exec(": run_list\n");
4564 rcode = run_list(command->group) & 0xff;
4566 restore_redirects(squirrel);
4567 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4569 debug_printf_exec("run_pipe: return %d\n", rcode);
4573 argv = command->argv ? command->argv : (char **) &null_ptr;
4575 const struct built_in_command *x;
4576 #if ENABLE_HUSH_FUNCTIONS
4577 const struct function *funcp;
4581 char **new_env = NULL;
4582 struct variable *old_vars = NULL;
4584 if (argv[command->assignment_cnt] == NULL) {
4585 /* Assignments, but no command */
4586 /* Ensure redirects take effect (that is, create files).
4587 * Try "a=t >file" */
4588 #if 0 /* A few cases in testsuite fail with this code. FIXME */
4589 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4590 /* Set shell variables */
4594 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4595 /* Do we need to flag set_local_var() errors?
4596 * "assignment to readonly var" and "putenv error"
4601 /* Redirect error sets $? to 1. Otherwise,
4602 * if evaluating assignment value set $?, retain it.
4603 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4605 rcode = G.last_exitcode;
4606 /* Exit, _skipping_ variable restoring code: */
4607 goto clean_up_and_ret0;
4609 #else /* Older, bigger, but more correct code */
4611 rcode = setup_redirects(command, squirrel);
4612 restore_redirects(squirrel);
4613 /* Set shell variables */
4615 bb_putchar_stderr('+');
4617 char *p = expand_string_to_string(*argv);
4619 fprintf(stderr, " %s", p);
4620 debug_printf_exec("set shell var:'%s'->'%s'\n",
4622 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4623 /* Do we need to flag set_local_var() errors?
4624 * "assignment to readonly var" and "putenv error"
4629 bb_putchar_stderr('\n');
4630 /* Redirect error sets $? to 1. Otherwise,
4631 * if evaluating assignment value set $?, retain it.
4632 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4634 rcode = G.last_exitcode;
4635 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4637 debug_printf_exec("run_pipe: return %d\n", rcode);
4642 /* Expand the rest into (possibly) many strings each */
4644 #if ENABLE_HUSH_BASH_COMPAT
4645 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4646 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4649 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4650 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4651 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4655 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4658 /* if someone gives us an empty string: `cmd with empty output` */
4659 if (!argv_expanded[0]) {
4660 free(argv_expanded);
4662 return G.last_exitcode;
4665 x = find_builtin(argv_expanded[0]);
4666 #if ENABLE_HUSH_FUNCTIONS
4669 funcp = find_function(argv_expanded[0]);
4673 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4674 debug_printf("exec with redirects only\n");
4675 rcode = setup_redirects(command, NULL);
4676 goto clean_up_and_ret1;
4679 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4682 debug_printf_exec(": builtin '%s' '%s'...\n",
4683 x->b_cmd, argv_expanded[1]);
4684 rcode = x->b_function(argv_expanded) & 0xff;
4687 #if ENABLE_HUSH_FUNCTIONS
4689 # if ENABLE_HUSH_LOCAL
4690 struct variable **sv;
4691 sv = G.shadowed_vars_pp;
4692 G.shadowed_vars_pp = &old_vars;
4694 debug_printf_exec(": function '%s' '%s'...\n",
4695 funcp->name, argv_expanded[1]);
4696 rcode = run_function(funcp, argv_expanded) & 0xff;
4697 # if ENABLE_HUSH_LOCAL
4698 G.shadowed_vars_pp = sv;
4704 unset_vars(new_env);
4706 /* clean_up_and_ret0: */
4707 restore_redirects(squirrel);
4709 free(argv_expanded);
4710 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4712 debug_printf_exec("run_pipe return %d\n", rcode);
4716 if (ENABLE_FEATURE_SH_STANDALONE) {
4717 int n = find_applet_by_name(argv_expanded[0]);
4718 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4719 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4721 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4722 argv_expanded[0], argv_expanded[1]);
4723 rcode = run_nofork_applet(n, argv_expanded);
4725 goto clean_up_and_ret;
4728 /* It is neither builtin nor applet. We must fork. */
4732 /* NB: argv_expanded may already be created, and that
4733 * might include `cmd` runs! Do not rerun it! We *must*
4734 * use argv_expanded if it's non-NULL */
4736 /* Going to fork a child per each pipe member */
4741 while (cmd_no < pi->num_cmds) {
4742 struct fd_pair pipefds;
4744 volatile nommu_save_t nommu_save;
4745 nommu_save.new_env = NULL;
4746 nommu_save.old_vars = NULL;
4747 nommu_save.argv = NULL;
4748 nommu_save.argv_from_re_execing = NULL;
4750 command = &pi->cmds[cmd_no];
4752 if (command->argv) {
4753 debug_printf_exec(": pipe member '%s' '%s'...\n",
4754 command->argv[0], command->argv[1]);
4756 debug_printf_exec(": pipe member with no argv\n");
4759 /* pipes are inserted between pairs of commands */
4762 if (cmd_no < pi->num_cmds)
4763 xpiped_pair(pipefds);
4765 command->pid = BB_MMU ? fork() : vfork();
4766 if (!command->pid) { /* child */
4768 disable_restore_tty_pgrp_on_exit();
4769 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4771 /* Every child adds itself to new process group
4772 * with pgid == pid_of_first_child_in_pipe */
4773 if (G.run_list_level == 1 && G_interactive_fd) {
4776 if (pgrp < 0) /* true for 1st process only */
4778 if (setpgid(0, pgrp) == 0
4779 && pi->followup != PIPE_BG
4780 && G_saved_tty_pgrp /* we have ctty */
4782 /* We do it in *every* child, not just first,
4784 tcsetpgrp(G_interactive_fd, pgrp);
4788 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4789 /* 1st cmd in backgrounded pipe
4790 * should have its stdin /dev/null'ed */
4792 if (open(bb_dev_null, O_RDONLY))
4793 xopen("/", O_RDONLY);
4795 xmove_fd(next_infd, 0);
4797 xmove_fd(pipefds.wr, 1);
4800 /* Like bash, explicit redirects override pipes,
4801 * and the pipe fd is available for dup'ing. */
4802 if (setup_redirects(command, NULL))
4805 /* Restore default handlers just prior to exec */
4806 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4808 /* Stores to nommu_save list of env vars putenv'ed
4809 * (NOMMU, on MMU we don't need that) */
4810 /* cast away volatility... */
4811 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4812 /* pseudo_exec() does not return */
4815 /* parent or error */
4816 #if ENABLE_HUSH_FAST
4818 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4820 enable_restore_tty_pgrp_on_exit();
4822 /* Clean up after vforked child */
4823 free(nommu_save.argv);
4824 free(nommu_save.argv_from_re_execing);
4825 unset_vars(nommu_save.new_env);
4826 add_vars(nommu_save.old_vars);
4828 free(argv_expanded);
4829 argv_expanded = NULL;
4830 if (command->pid < 0) { /* [v]fork failed */
4831 /* Clearly indicate, was it fork or vfork */
4832 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4836 /* Second and next children need to know pid of first one */
4838 pi->pgrp = command->pid;
4844 if (cmd_no < pi->num_cmds)
4846 /* Pass read (output) pipe end to next iteration */
4847 next_infd = pipefds.rd;
4850 if (!pi->alive_cmds) {
4852 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4857 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4861 #ifndef debug_print_tree
4862 static void debug_print_tree(struct pipe *pi, int lvl)
4864 static const char *const PIPE[] = {
4870 static const char *RES[] = {
4871 [RES_NONE ] = "NONE" ,
4874 [RES_THEN ] = "THEN" ,
4875 [RES_ELIF ] = "ELIF" ,
4876 [RES_ELSE ] = "ELSE" ,
4879 # if ENABLE_HUSH_LOOPS
4880 [RES_FOR ] = "FOR" ,
4881 [RES_WHILE] = "WHILE",
4882 [RES_UNTIL] = "UNTIL",
4884 [RES_DONE ] = "DONE" ,
4886 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4889 # if ENABLE_HUSH_CASE
4890 [RES_CASE ] = "CASE" ,
4891 [RES_CASE_IN ] = "CASE_IN" ,
4892 [RES_MATCH] = "MATCH",
4893 [RES_CASE_BODY] = "CASE_BODY",
4894 [RES_ESAC ] = "ESAC" ,
4896 [RES_XXXX ] = "XXXX" ,
4897 [RES_SNTX ] = "SNTX" ,
4899 static const char *const CMDTYPE[] = {
4903 # if ENABLE_HUSH_FUNCTIONS
4912 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4913 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4915 while (prn < pi->num_cmds) {
4916 struct command *command = &pi->cmds[prn];
4917 char **argv = command->argv;
4919 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4921 command->assignment_cnt);
4922 if (command->group) {
4923 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4924 CMDTYPE[command->cmd_type],
4927 , " group_as_string:", command->group_as_string
4932 debug_print_tree(command->group, lvl+1);
4936 if (argv) while (*argv) {
4937 fprintf(stderr, " '%s'", *argv);
4940 fprintf(stderr, "\n");
4947 #endif /* debug_print_tree */
4949 /* NB: called by pseudo_exec, and therefore must not modify any
4950 * global data until exec/_exit (we can be a child after vfork!) */
4951 static int run_list(struct pipe *pi)
4953 #if ENABLE_HUSH_CASE
4954 char *case_word = NULL;
4956 #if ENABLE_HUSH_LOOPS
4957 struct pipe *loop_top = NULL;
4958 char **for_lcur = NULL;
4959 char **for_list = NULL;
4961 smallint last_followup;
4963 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4964 smalluint cond_code = 0;
4966 enum { cond_code = 0 };
4969 smallint rword; /* enum reserved_style */
4970 smallint last_rword; /* ditto */
4973 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4976 #if ENABLE_HUSH_LOOPS
4977 /* Check syntax for "for" */
4978 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4979 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4981 /* current word is FOR or IN (BOLD in comments below) */
4982 if (cpipe->next == NULL) {
4983 syntax_error("malformed for");
4985 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4988 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4989 if (cpipe->next->res_word == RES_DO)
4991 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4992 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4993 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4995 syntax_error("malformed for");
4997 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
5003 /* Past this point, all code paths should jump to ret: label
5004 * in order to return, no direct "return" statements please.
5005 * This helps to ensure that no memory is leaked. */
5013 last_rword = RES_XXXX;
5015 last_followup = PIPE_SEQ;
5016 rcode = G.last_exitcode;
5018 /* Go through list of pipes, (maybe) executing them. */
5019 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
5023 IF_HAS_KEYWORDS(rword = pi->res_word;)
5024 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
5025 rword, cond_code, last_rword);
5026 #if ENABLE_HUSH_LOOPS
5027 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
5028 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
5030 /* start of a loop: remember where loop starts */
5035 /* Still in the same "if...", "then..." or "do..." branch? */
5036 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
5037 if ((rcode == 0 && last_followup == PIPE_OR)
5038 || (rcode != 0 && last_followup == PIPE_AND)
5040 /* It is "<true> || CMD" or "<false> && CMD"
5041 * and we should not execute CMD */
5042 debug_printf_exec("skipped cmd because of || or &&\n");
5043 last_followup = pi->followup;
5047 last_followup = pi->followup;
5048 IF_HAS_KEYWORDS(last_rword = rword;)
5051 if (rword == RES_THEN) {
5052 /* if false; then ... fi has exitcode 0! */
5053 G.last_exitcode = rcode = EXIT_SUCCESS;
5054 /* "if <false> THEN cmd": skip cmd */
5058 if (rword == RES_ELSE || rword == RES_ELIF) {
5059 /* "if <true> then ... ELSE/ELIF cmd":
5060 * skip cmd and all following ones */
5065 #if ENABLE_HUSH_LOOPS
5066 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
5068 /* first loop through for */
5070 static const char encoded_dollar_at[] ALIGN1 = {
5071 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
5072 }; /* encoded representation of "$@" */
5073 static const char *const encoded_dollar_at_argv[] = {
5074 encoded_dollar_at, NULL
5075 }; /* argv list with one element: "$@" */
5078 vals = (char**)encoded_dollar_at_argv;
5079 if (pi->next->res_word == RES_IN) {
5080 /* if no variable values after "in" we skip "for" */
5081 if (!pi->next->cmds[0].argv) {
5082 G.last_exitcode = rcode = EXIT_SUCCESS;
5083 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
5086 vals = pi->next->cmds[0].argv;
5087 } /* else: "for var; do..." -> assume "$@" list */
5088 /* create list of variable values */
5089 debug_print_strings("for_list made from", vals);
5090 for_list = expand_strvec_to_strvec(vals);
5091 for_lcur = for_list;
5092 debug_print_strings("for_list", for_list);
5095 /* "for" loop is over, clean up */
5101 /* Insert next value from for_lcur */
5102 /* note: *for_lcur already has quotes removed, $var expanded, etc */
5103 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5106 if (rword == RES_IN) {
5107 continue; /* "for v IN list;..." - "in" has no cmds anyway */
5109 if (rword == RES_DONE) {
5110 continue; /* "done" has no cmds too */
5113 #if ENABLE_HUSH_CASE
5114 if (rword == RES_CASE) {
5115 case_word = expand_strvec_to_string(pi->cmds->argv);
5118 if (rword == RES_MATCH) {
5121 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
5123 /* all prev words didn't match, does this one match? */
5124 argv = pi->cmds->argv;
5126 char *pattern = expand_string_to_string(*argv);
5127 /* TODO: which FNM_xxx flags to use? */
5128 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
5130 if (cond_code == 0) { /* match! we will execute this branch */
5131 free(case_word); /* make future "word)" stop */
5139 if (rword == RES_CASE_BODY) { /* inside of a case branch */
5141 continue; /* not matched yet, skip this pipe */
5144 /* Just pressing <enter> in shell should check for jobs.
5145 * OTOH, in non-interactive shell this is useless
5146 * and only leads to extra job checks */
5147 if (pi->num_cmds == 0) {
5148 if (G_interactive_fd)
5149 goto check_jobs_and_continue;
5153 /* After analyzing all keywords and conditions, we decided
5154 * to execute this pipe. NB: have to do checkjobs(NULL)
5155 * after run_pipe to collect any background children,
5156 * even if list execution is to be stopped. */
5157 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
5160 #if ENABLE_HUSH_LOOPS
5161 G.flag_break_continue = 0;
5163 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5165 /* We ran a builtin, function, or group.
5166 * rcode is already known
5167 * and we don't need to wait for anything. */
5168 G.last_exitcode = rcode;
5169 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
5170 check_and_run_traps(0);
5171 #if ENABLE_HUSH_LOOPS
5172 /* Was it "break" or "continue"? */
5173 if (G.flag_break_continue) {
5174 smallint fbc = G.flag_break_continue;
5175 /* We might fall into outer *loop*,
5176 * don't want to break it too */
5178 G.depth_break_continue--;
5179 if (G.depth_break_continue == 0)
5180 G.flag_break_continue = 0;
5181 /* else: e.g. "continue 2" should *break* once, *then* continue */
5182 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
5183 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
5184 goto check_jobs_and_break;
5185 /* "continue": simulate end of loop */
5190 #if ENABLE_HUSH_FUNCTIONS
5191 if (G.flag_return_in_progress == 1) {
5192 /* same as "goto check_jobs_and_break" */
5197 } else if (pi->followup == PIPE_BG) {
5198 /* What does bash do with attempts to background builtins? */
5199 /* even bash 3.2 doesn't do that well with nested bg:
5200 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5201 * I'm NOT treating inner &'s as jobs */
5202 check_and_run_traps(0);
5204 if (G.run_list_level == 1)
5207 /* Last command's pid goes to $! */
5208 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
5209 G.last_exitcode = rcode = EXIT_SUCCESS;
5210 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
5213 if (G.run_list_level == 1 && G_interactive_fd) {
5214 /* Waits for completion, then fg's main shell */
5215 rcode = checkjobs_and_fg_shell(pi);
5216 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
5217 check_and_run_traps(0);
5220 { /* This one just waits for completion */
5221 rcode = checkjobs(pi);
5222 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
5223 check_and_run_traps(0);
5225 G.last_exitcode = rcode;
5229 /* Analyze how result affects subsequent commands */
5231 if (rword == RES_IF || rword == RES_ELIF)
5234 #if ENABLE_HUSH_LOOPS
5235 /* Beware of "while false; true; do ..."! */
5236 if (pi->next && pi->next->res_word == RES_DO) {
5237 if (rword == RES_WHILE) {
5239 /* "while false; do...done" - exitcode 0 */
5240 G.last_exitcode = rcode = EXIT_SUCCESS;
5241 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5242 goto check_jobs_and_break;
5245 if (rword == RES_UNTIL) {
5247 debug_printf_exec(": until expr is true: breaking\n");
5248 check_jobs_and_break:
5256 check_jobs_and_continue:
5263 #if ENABLE_HUSH_LOOPS
5268 #if ENABLE_HUSH_CASE
5272 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
5276 /* Select which version we will use */
5277 static int run_and_free_list(struct pipe *pi)
5280 debug_printf_exec("run_and_free_list entered\n");
5282 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
5283 rcode = run_list(pi);
5285 /* free_pipe_list has the side effect of clearing memory.
5286 * In the long run that function can be merged with run_list,
5287 * but doing that now would hobble the debugging effort. */
5289 debug_printf_exec("run_and_free_list return %d\n", rcode);
5294 static struct pipe *new_pipe(void)
5297 pi = xzalloc(sizeof(struct pipe));
5298 /*pi->followup = 0; - deliberately invalid value */
5299 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
5303 /* Command (member of a pipe) is complete, or we start a new pipe
5304 * if ctx->command is NULL.
5305 * No errors possible here.
5307 static int done_command(struct parse_context *ctx)
5309 /* The command is really already in the pipe structure, so
5310 * advance the pipe counter and make a new, null command. */
5311 struct pipe *pi = ctx->pipe;
5312 struct command *command = ctx->command;
5315 if (IS_NULL_CMD(command)) {
5316 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
5320 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
5321 //debug_print_tree(ctx->list_head, 20);
5323 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5326 /* Only real trickiness here is that the uncommitted
5327 * command structure is not counted in pi->num_cmds. */
5328 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
5329 ctx->command = command = &pi->cmds[pi->num_cmds];
5331 memset(command, 0, sizeof(*command));
5332 return pi->num_cmds; /* used only for 0/nonzero check */
5335 static void done_pipe(struct parse_context *ctx, pipe_style type)
5339 debug_printf_parse("done_pipe entered, followup %d\n", type);
5340 /* Close previous command */
5341 not_null = done_command(ctx);
5342 ctx->pipe->followup = type;
5344 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5345 ctx->ctx_inverted = 0;
5346 ctx->pipe->res_word = ctx->ctx_res_w;
5349 /* Without this check, even just <enter> on command line generates
5350 * tree of three NOPs (!). Which is harmless but annoying.
5351 * IOW: it is safe to do it unconditionally. */
5354 || ctx->ctx_res_w == RES_FI
5356 #if ENABLE_HUSH_LOOPS
5357 || ctx->ctx_res_w == RES_DONE
5358 || ctx->ctx_res_w == RES_FOR
5359 || ctx->ctx_res_w == RES_IN
5361 #if ENABLE_HUSH_CASE
5362 || ctx->ctx_res_w == RES_ESAC
5366 debug_printf_parse("done_pipe: adding new pipe: "
5367 "not_null:%d ctx->ctx_res_w:%d\n",
5368 not_null, ctx->ctx_res_w);
5370 ctx->pipe->next = new_p;
5372 /* RES_THEN, RES_DO etc are "sticky" -
5373 * they remain set for pipes inside if/while.
5374 * This is used to control execution.
5375 * RES_FOR and RES_IN are NOT sticky (needed to support
5376 * cases where variable or value happens to match a keyword):
5378 #if ENABLE_HUSH_LOOPS
5379 if (ctx->ctx_res_w == RES_FOR
5380 || ctx->ctx_res_w == RES_IN)
5381 ctx->ctx_res_w = RES_NONE;
5383 #if ENABLE_HUSH_CASE
5384 if (ctx->ctx_res_w == RES_MATCH)
5385 ctx->ctx_res_w = RES_CASE_BODY;
5386 if (ctx->ctx_res_w == RES_CASE)
5387 ctx->ctx_res_w = RES_CASE_IN;
5389 ctx->command = NULL; /* trick done_command below */
5390 /* Create the memory for command, roughly:
5391 * ctx->pipe->cmds = new struct command;
5392 * ctx->command = &ctx->pipe->cmds[0];
5395 //debug_print_tree(ctx->list_head, 10);
5397 debug_printf_parse("done_pipe return\n");
5400 static void initialize_context(struct parse_context *ctx)
5402 memset(ctx, 0, sizeof(*ctx));
5403 ctx->pipe = ctx->list_head = new_pipe();
5404 /* Create the memory for command, roughly:
5405 * ctx->pipe->cmds = new struct command;
5406 * ctx->command = &ctx->pipe->cmds[0];
5411 /* If a reserved word is found and processed, parse context is modified
5412 * and 1 is returned.
5415 struct reserved_combo {
5418 unsigned char assignment_flag;
5422 FLAG_END = (1 << RES_NONE ),
5424 FLAG_IF = (1 << RES_IF ),
5425 FLAG_THEN = (1 << RES_THEN ),
5426 FLAG_ELIF = (1 << RES_ELIF ),
5427 FLAG_ELSE = (1 << RES_ELSE ),
5428 FLAG_FI = (1 << RES_FI ),
5430 # if ENABLE_HUSH_LOOPS
5431 FLAG_FOR = (1 << RES_FOR ),
5432 FLAG_WHILE = (1 << RES_WHILE),
5433 FLAG_UNTIL = (1 << RES_UNTIL),
5434 FLAG_DO = (1 << RES_DO ),
5435 FLAG_DONE = (1 << RES_DONE ),
5436 FLAG_IN = (1 << RES_IN ),
5438 # if ENABLE_HUSH_CASE
5439 FLAG_MATCH = (1 << RES_MATCH),
5440 FLAG_ESAC = (1 << RES_ESAC ),
5442 FLAG_START = (1 << RES_XXXX ),
5445 static const struct reserved_combo* match_reserved_word(o_string *word)
5447 /* Mostly a list of accepted follow-up reserved words.
5448 * FLAG_END means we are done with the sequence, and are ready
5449 * to turn the compound list into a command.
5450 * FLAG_START means the word must start a new compound list.
5452 static const struct reserved_combo reserved_list[] = {
5454 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5455 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5456 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5457 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5458 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5459 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5461 # if ENABLE_HUSH_LOOPS
5462 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5463 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5464 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5465 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5466 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5467 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5469 # if ENABLE_HUSH_CASE
5470 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5471 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5474 const struct reserved_combo *r;
5476 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5477 if (strcmp(word->data, r->literal) == 0)
5482 /* Return 0: not a keyword, 1: keyword
5484 static int reserved_word(o_string *word, struct parse_context *ctx)
5486 # if ENABLE_HUSH_CASE
5487 static const struct reserved_combo reserved_match = {
5488 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5491 const struct reserved_combo *r;
5493 if (word->has_quoted_part)
5495 r = match_reserved_word(word);
5499 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5500 # if ENABLE_HUSH_CASE
5501 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5502 /* "case word IN ..." - IN part starts first MATCH part */
5503 r = &reserved_match;
5506 if (r->flag == 0) { /* '!' */
5507 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5508 syntax_error("! ! command");
5509 ctx->ctx_res_w = RES_SNTX;
5511 ctx->ctx_inverted = 1;
5514 if (r->flag & FLAG_START) {
5515 struct parse_context *old;
5517 old = xmalloc(sizeof(*old));
5518 debug_printf_parse("push stack %p\n", old);
5519 *old = *ctx; /* physical copy */
5520 initialize_context(ctx);
5522 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5523 syntax_error_at(word->data);
5524 ctx->ctx_res_w = RES_SNTX;
5527 /* "{...} fi" is ok. "{...} if" is not
5529 * if { echo foo; } then { echo bar; } fi */
5530 if (ctx->command->group)
5531 done_pipe(ctx, PIPE_SEQ);
5534 ctx->ctx_res_w = r->res;
5535 ctx->old_flag = r->flag;
5536 word->o_assignment = r->assignment_flag;
5538 if (ctx->old_flag & FLAG_END) {
5539 struct parse_context *old;
5541 done_pipe(ctx, PIPE_SEQ);
5542 debug_printf_parse("pop stack %p\n", ctx->stack);
5544 old->command->group = ctx->list_head;
5545 old->command->cmd_type = CMD_NORMAL;
5547 o_addstr(&old->as_string, ctx->as_string.data);
5548 o_free_unsafe(&ctx->as_string);
5549 old->command->group_as_string = xstrdup(old->as_string.data);
5550 debug_printf_parse("pop, remembering as:'%s'\n",
5551 old->command->group_as_string);
5553 *ctx = *old; /* physical copy */
5558 #endif /* HAS_KEYWORDS */
5560 /* Word is complete, look at it and update parsing context.
5561 * Normal return is 0. Syntax errors return 1.
5562 * Note: on return, word is reset, but not o_free'd!
5564 static int done_word(o_string *word, struct parse_context *ctx)
5566 struct command *command = ctx->command;
5568 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5569 if (word->length == 0 && !word->has_quoted_part) {
5570 debug_printf_parse("done_word return 0: true null, ignored\n");
5574 if (ctx->pending_redirect) {
5575 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5576 * only if run as "bash", not "sh" */
5577 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5579 * ...the word that follows the redirection operator
5580 * shall be subjected to tilde expansion, parameter expansion,
5581 * command substitution, arithmetic expansion, and quote
5582 * removal. Pathname expansion shall not be performed
5583 * on the word by a non-interactive shell; an interactive
5584 * shell may perform it, but shall do so only when
5585 * the expansion would result in one word."
5587 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5588 /* Cater for >\file case:
5589 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5590 * Same with heredocs:
5591 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5593 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5594 unbackslash(ctx->pending_redirect->rd_filename);
5595 /* Is it <<"HEREDOC"? */
5596 if (word->has_quoted_part) {
5597 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5600 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5601 ctx->pending_redirect = NULL;
5603 /* If this word wasn't an assignment, next ones definitely
5604 * can't be assignments. Even if they look like ones. */
5605 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5606 && word->o_assignment != WORD_IS_KEYWORD
5608 word->o_assignment = NOT_ASSIGNMENT;
5610 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5611 command->assignment_cnt++;
5612 word->o_assignment = MAYBE_ASSIGNMENT;
5616 # if ENABLE_HUSH_CASE
5617 if (ctx->ctx_dsemicolon
5618 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5620 /* already done when ctx_dsemicolon was set to 1: */
5621 /* ctx->ctx_res_w = RES_MATCH; */
5622 ctx->ctx_dsemicolon = 0;
5625 if (!command->argv /* if it's the first word... */
5626 # if ENABLE_HUSH_LOOPS
5627 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5628 && ctx->ctx_res_w != RES_IN
5630 # if ENABLE_HUSH_CASE
5631 && ctx->ctx_res_w != RES_CASE
5634 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5635 if (reserved_word(word, ctx)) {
5636 o_reset_to_empty_unquoted(word);
5637 debug_printf_parse("done_word return %d\n",
5638 (ctx->ctx_res_w == RES_SNTX));
5639 return (ctx->ctx_res_w == RES_SNTX);
5641 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5642 if (strcmp(word->data, "export") == 0
5643 # if ENABLE_HUSH_LOCAL
5644 || strcmp(word->data, "local") == 0
5647 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5650 # if ENABLE_HUSH_BASH_COMPAT
5651 if (strcmp(word->data, "[[") == 0) {
5652 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5658 if (command->group) {
5659 /* "{ echo foo; } echo bar" - bad */
5660 syntax_error_at(word->data);
5661 debug_printf_parse("done_word return 1: syntax error, "
5662 "groups and arglists don't mix\n");
5665 if (word->has_quoted_part
5666 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5667 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5668 /* (otherwise it's known to be not empty and is already safe) */
5670 /* exclude "$@" - it can expand to no word despite "" */
5671 char *p = word->data;
5672 while (p[0] == SPECIAL_VAR_SYMBOL
5673 && (p[1] & 0x7f) == '@'
5674 && p[2] == SPECIAL_VAR_SYMBOL
5678 if (p == word->data || p[0] != '\0') {
5679 /* saw no "$@", or not only "$@" but some
5680 * real text is there too */
5681 /* insert "empty variable" reference, this makes
5682 * e.g. "", $empty"" etc to not disappear */
5683 o_addchr(word, SPECIAL_VAR_SYMBOL);
5684 o_addchr(word, SPECIAL_VAR_SYMBOL);
5687 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5688 debug_print_strings("word appended to argv", command->argv);
5691 #if ENABLE_HUSH_LOOPS
5692 if (ctx->ctx_res_w == RES_FOR) {
5693 if (word->has_quoted_part
5694 || !is_well_formed_var_name(command->argv[0], '\0')
5696 /* bash says just "not a valid identifier" */
5697 syntax_error("not a valid identifier in for");
5700 /* Force FOR to have just one word (variable name) */
5701 /* NB: basically, this makes hush see "for v in ..."
5702 * syntax as if it is "for v; in ...". FOR and IN become
5703 * two pipe structs in parse tree. */
5704 done_pipe(ctx, PIPE_SEQ);
5707 #if ENABLE_HUSH_CASE
5708 /* Force CASE to have just one word */
5709 if (ctx->ctx_res_w == RES_CASE) {
5710 done_pipe(ctx, PIPE_SEQ);
5714 o_reset_to_empty_unquoted(word);
5716 debug_printf_parse("done_word return 0\n");
5721 /* Peek ahead in the input to find out if we have a "&n" construct,
5722 * as in "2>&1", that represents duplicating a file descriptor.
5724 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5725 * REDIRFD_SYNTAX_ERR if syntax error,
5726 * REDIRFD_TO_FILE if no & was seen,
5727 * or the number found.
5730 #define parse_redir_right_fd(as_string, input) \
5731 parse_redir_right_fd(input)
5733 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5739 return REDIRFD_TO_FILE;
5741 ch = i_getch(input); /* get the & */
5742 nommu_addchr(as_string, ch);
5745 ch = i_getch(input);
5746 nommu_addchr(as_string, ch);
5747 return REDIRFD_CLOSE;
5751 while (ch != EOF && isdigit(ch)) {
5752 d = d*10 + (ch-'0');
5754 ch = i_getch(input);
5755 nommu_addchr(as_string, ch);
5760 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5762 bb_error_msg("ambiguous redirect");
5763 return REDIRFD_SYNTAX_ERR;
5766 /* Return code is 0 normal, 1 if a syntax error is detected
5768 static int parse_redirect(struct parse_context *ctx,
5771 struct in_str *input)
5773 struct command *command = ctx->command;
5774 struct redir_struct *redir;
5775 struct redir_struct **redirp;
5778 dup_num = REDIRFD_TO_FILE;
5779 if (style != REDIRECT_HEREDOC) {
5780 /* Check for a '>&1' type redirect */
5781 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5782 if (dup_num == REDIRFD_SYNTAX_ERR)
5785 int ch = i_peek(input);
5786 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5787 if (dup_num) { /* <<-... */
5788 ch = i_getch(input);
5789 nommu_addchr(&ctx->as_string, ch);
5794 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5795 int ch = i_peek(input);
5797 /* >|FILE redirect ("clobbering" >).
5798 * Since we do not support "set -o noclobber" yet,
5799 * >| and > are the same for now. Just eat |.
5801 ch = i_getch(input);
5802 nommu_addchr(&ctx->as_string, ch);
5806 /* Create a new redir_struct and append it to the linked list */
5807 redirp = &command->redirects;
5808 while ((redir = *redirp) != NULL) {
5809 redirp = &(redir->next);
5811 *redirp = redir = xzalloc(sizeof(*redir));
5812 /* redir->next = NULL; */
5813 /* redir->rd_filename = NULL; */
5814 redir->rd_type = style;
5815 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5817 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5818 redir_table[style].descrip);
5820 redir->rd_dup = dup_num;
5821 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5822 /* Erik had a check here that the file descriptor in question
5823 * is legit; I postpone that to "run time"
5824 * A "-" representation of "close me" shows up as a -3 here */
5825 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5826 redir->rd_fd, redir->rd_dup);
5828 /* Set ctx->pending_redirect, so we know what to do at the
5829 * end of the next parsed word. */
5830 ctx->pending_redirect = redir;
5835 /* If a redirect is immediately preceded by a number, that number is
5836 * supposed to tell which file descriptor to redirect. This routine
5837 * looks for such preceding numbers. In an ideal world this routine
5838 * needs to handle all the following classes of redirects...
5839 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5840 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5841 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5842 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5844 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5846 * ... If n is quoted, the number shall not be recognized as part of
5847 * the redirection expression. For example:
5849 * writes the character 2 into file a"
5850 * We are getting it right by setting ->has_quoted_part on any \<char>
5852 * A -1 return means no valid number was found,
5853 * the caller should use the appropriate default for this redirection.
5855 static int redirect_opt_num(o_string *o)
5859 if (o->data == NULL)
5861 num = bb_strtou(o->data, NULL, 10);
5862 if (errno || num < 0)
5864 o_reset_to_empty_unquoted(o);
5869 #define fetch_till_str(as_string, input, word, skip_tabs) \
5870 fetch_till_str(input, word, skip_tabs)
5872 static char *fetch_till_str(o_string *as_string,
5873 struct in_str *input,
5877 o_string heredoc = NULL_O_STRING;
5883 ch = i_getch(input);
5884 nommu_addchr(as_string, ch);
5886 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5887 heredoc.data[past_EOL] = '\0';
5888 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5889 return heredoc.data;
5892 o_addchr(&heredoc, ch);
5893 past_EOL = heredoc.length;
5896 ch = i_getch(input);
5897 nommu_addchr(as_string, ch);
5898 } while (skip_tabs && ch == '\t');
5899 } while (ch == '\n');
5902 o_free_unsafe(&heredoc);
5905 o_addchr(&heredoc, ch);
5906 nommu_addchr(as_string, ch);
5910 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5911 * and load them all. There should be exactly heredoc_cnt of them.
5913 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5915 struct pipe *pi = ctx->list_head;
5917 while (pi && heredoc_cnt) {
5919 struct command *cmd = pi->cmds;
5921 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5923 cmd->argv ? cmd->argv[0] : "NONE");
5924 for (i = 0; i < pi->num_cmds; i++) {
5925 struct redir_struct *redir = cmd->redirects;
5927 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5928 i, cmd->argv ? cmd->argv[0] : "NONE");
5930 if (redir->rd_type == REDIRECT_HEREDOC) {
5933 redir->rd_type = REDIRECT_HEREDOC2;
5934 /* redir->rd_dup is (ab)used to indicate <<- */
5935 p = fetch_till_str(&ctx->as_string, input,
5936 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5938 syntax_error("unexpected EOF in here document");
5941 free(redir->rd_filename);
5942 redir->rd_filename = p;
5945 redir = redir->next;
5952 /* Should be 0. If it isn't, it's a parse error */
5954 bb_error_msg_and_die("heredoc BUG 2");
5960 #if ENABLE_HUSH_TICK
5961 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5966 char **to_free = NULL;
5970 pid = BB_MMU ? xfork() : xvfork();
5971 if (pid == 0) { /* child */
5972 disable_restore_tty_pgrp_on_exit();
5973 /* Process substitution is not considered to be usual
5974 * 'command execution'.
5975 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5982 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5983 close(channel[0]); /* NB: close _first_, then move fd! */
5984 xmove_fd(channel[1], 1);
5985 /* Prevent it from trying to handle ctrl-z etc */
5986 IF_HUSH_JOB(G.run_list_level = 1;)
5987 /* Awful hack for `trap` or $(trap).
5989 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5990 * contains an example where "trap" is executed in a subshell:
5992 * save_traps=$(trap)
5994 * eval "$save_traps"
5996 * Standard does not say that "trap" in subshell shall print
5997 * parent shell's traps. It only says that its output
5998 * must have suitable form, but then, in the above example
5999 * (which is not supposed to be normative), it implies that.
6001 * bash (and probably other shell) does implement it
6002 * (traps are reset to defaults, but "trap" still shows them),
6003 * but as a result, "trap" logic is hopelessly messed up:
6006 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6007 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6008 * # true | trap <--- trap is in subshell - no output (ditto)
6009 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6010 * trap -- 'echo Ho' SIGWINCH
6011 * # echo `(trap)` <--- in subshell in subshell - output
6012 * trap -- 'echo Ho' SIGWINCH
6013 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6014 * trap -- 'echo Ho' SIGWINCH
6016 * The rules when to forget and when to not forget traps
6017 * get really complex and nonsensical.
6019 * Our solution: ONLY bare $(trap) or `trap` is special.
6021 s = skip_whitespace(s);
6022 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
6024 static const char *const argv[] = { NULL, NULL };
6025 builtin_trap((char**)argv);
6026 exit(0); /* not _exit() - we need to fflush */
6029 reset_traps_to_defaults();
6030 parse_and_run_string(s);
6031 _exit(G.last_exitcode);
6033 /* We re-execute after vfork on NOMMU. This makes this script safe:
6034 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6035 * huge=`cat BIG` # was blocking here forever
6038 re_execute_shell(&to_free,
6048 # if ENABLE_HUSH_FAST
6050 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6051 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6052 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6054 enable_restore_tty_pgrp_on_exit();
6059 close_on_exec_on(channel[0]);
6060 return xfdopen_for_read(channel[0]);
6063 /* Return code is exit status of the process that is run. */
6064 static int process_command_subs(o_string *dest, const char *s)
6067 struct in_str pipe_str;
6069 int status, ch, eol_cnt;
6071 fp = generate_stream_from_string(s, &pid);
6073 /* Now send results of command back into original context */
6074 setup_file_in_str(&pipe_str, fp);
6076 while ((ch = i_getch(&pipe_str)) != EOF) {
6082 o_addchr(dest, '\n');
6085 o_addQchr(dest, ch);
6088 debug_printf("done reading from `cmd` pipe, closing it\n");
6090 /* We need to extract exitcode. Test case
6091 * "true; echo `sleep 1; false` $?"
6093 safe_waitpid(pid, &status, 0);
6094 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6095 return WEXITSTATUS(status);
6097 #endif /* ENABLE_HUSH_TICK */
6099 #if !ENABLE_HUSH_FUNCTIONS
6100 #define parse_group(dest, ctx, input, ch) \
6101 parse_group(ctx, input, ch)
6103 static int parse_group(o_string *dest, struct parse_context *ctx,
6104 struct in_str *input, int ch)
6106 /* dest contains characters seen prior to ( or {.
6107 * Typically it's empty, but for function defs,
6108 * it contains function name (without '()'). */
6109 struct pipe *pipe_list;
6111 struct command *command = ctx->command;
6113 debug_printf_parse("parse_group entered\n");
6114 #if ENABLE_HUSH_FUNCTIONS
6115 if (ch == '(' && !dest->has_quoted_part) {
6117 if (done_word(dest, ctx))
6120 goto skip; /* (... */
6121 if (command->argv[1]) { /* word word ... (... */
6122 syntax_error_unexpected_ch('(');
6125 /* it is "word(..." or "word (..." */
6127 ch = i_getch(input);
6128 while (ch == ' ' || ch == '\t');
6130 syntax_error_unexpected_ch(ch);
6133 nommu_addchr(&ctx->as_string, ch);
6135 ch = i_getch(input);
6136 while (ch == ' ' || ch == '\t' || ch == '\n');
6138 syntax_error_unexpected_ch(ch);
6141 nommu_addchr(&ctx->as_string, ch);
6142 command->cmd_type = CMD_FUNCDEF;
6147 #if 0 /* Prevented by caller */
6148 if (command->argv /* word [word]{... */
6149 || dest->length /* word{... */
6150 || dest->has_quoted_part /* ""{... */
6153 debug_printf_parse("parse_group return 1: "
6154 "syntax error, groups and arglists don't mix\n");
6159 #if ENABLE_HUSH_FUNCTIONS
6165 command->cmd_type = CMD_SUBSHELL;
6167 /* bash does not allow "{echo...", requires whitespace */
6168 ch = i_getch(input);
6169 if (ch != ' ' && ch != '\t' && ch != '\n') {
6170 syntax_error_unexpected_ch(ch);
6173 nommu_addchr(&ctx->as_string, ch);
6178 # define as_string NULL
6180 char *as_string = NULL;
6182 pipe_list = parse_stream(&as_string, input, endch);
6185 o_addstr(&ctx->as_string, as_string);
6187 /* empty ()/{} or parse error? */
6188 if (!pipe_list || pipe_list == ERR_PTR) {
6189 /* parse_stream already emitted error msg */
6192 debug_printf_parse("parse_group return 1: "
6193 "parse_stream returned %p\n", pipe_list);
6196 command->group = pipe_list;
6198 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6199 command->group_as_string = as_string;
6200 debug_printf_parse("end of group, remembering as:'%s'\n",
6201 command->group_as_string);
6205 debug_printf_parse("parse_group return 0\n");
6207 /* command remains "open", available for possible redirects */
6210 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
6211 /* Subroutines for copying $(...) and `...` things */
6212 static void add_till_backquote(o_string *dest, struct in_str *input);
6214 static void add_till_single_quote(o_string *dest, struct in_str *input)
6217 int ch = i_getch(input);
6219 syntax_error_unterm_ch('\'');
6220 /*xfunc_die(); - redundant */
6227 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
6228 static void add_till_double_quote(o_string *dest, struct in_str *input)
6231 int ch = i_getch(input);
6233 syntax_error_unterm_ch('"');
6234 /*xfunc_die(); - redundant */
6238 if (ch == '\\') { /* \x. Copy both chars. */
6240 ch = i_getch(input);
6244 add_till_backquote(dest, input);
6248 //if (ch == '$') ...
6251 /* Process `cmd` - copy contents until "`" is seen. Complicated by
6253 * "Within the backquoted style of command substitution, backslash
6254 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6255 * The search for the matching backquote shall be satisfied by the first
6256 * backquote found without a preceding backslash; during this search,
6257 * if a non-escaped backquote is encountered within a shell comment,
6258 * a here-document, an embedded command substitution of the $(command)
6259 * form, or a quoted string, undefined results occur. A single-quoted
6260 * or double-quoted string that begins, but does not end, within the
6261 * "`...`" sequence produces undefined results."
6263 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6265 static void add_till_backquote(o_string *dest, struct in_str *input)
6268 int ch = i_getch(input);
6270 syntax_error_unterm_ch('`');
6271 /*xfunc_die(); - redundant */
6276 /* \x. Copy both chars unless it is \` */
6277 int ch2 = i_getch(input);
6279 syntax_error_unterm_ch('`');
6280 /*xfunc_die(); - redundant */
6282 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
6289 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
6290 * quoting and nested ()s.
6291 * "With the $(command) style of command substitution, all characters
6292 * following the open parenthesis to the matching closing parenthesis
6293 * constitute the command. Any valid shell script can be used for command,
6294 * except a script consisting solely of redirections which produces
6295 * unspecified results."
6297 * echo $(echo '(TEST)' BEST) (TEST) BEST
6298 * echo $(echo 'TEST)' BEST) TEST) BEST
6299 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
6301 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
6302 * can contain arbitrary constructs, just like $(cmd).
6303 * In bash compat mode, it needs to also be able to stop on ':' or '/'
6304 * for ${var:N[:M]} and ${var/P[/R]} parsing.
6306 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
6307 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
6310 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
6311 # if ENABLE_HUSH_BASH_COMPAT
6312 char end_char2 = end_ch >> 8;
6314 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6317 ch = i_getch(input);
6319 syntax_error_unterm_ch(end_ch);
6320 /*xfunc_die(); - redundant */
6322 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
6325 /* we look for closing )) of $((EXPR)) */
6326 if (i_peek(input) == end_ch) {
6327 i_getch(input); /* eat second ')' */
6332 if (ch == '(' || ch == '{') {
6333 ch = (ch == '(' ? ')' : '}');
6334 add_till_closing_bracket(dest, input, ch);
6339 add_till_single_quote(dest, input);
6344 add_till_double_quote(dest, input);
6349 add_till_backquote(dest, input);
6354 /* \x. Copy verbatim. Important for \(, \) */
6355 ch = i_getch(input);
6357 syntax_error_unterm_ch(')');
6358 /*xfunc_die(); - redundant */
6366 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6368 /* Return code: 0 for OK, 1 for syntax error */
6370 #define parse_dollar(as_string, dest, input) \
6371 parse_dollar(dest, input)
6372 #define as_string NULL
6374 static int parse_dollar(o_string *as_string,
6376 struct in_str *input)
6378 int ch = i_peek(input); /* first character after the $ */
6379 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6381 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6383 ch = i_getch(input);
6384 nommu_addchr(as_string, ch);
6386 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6388 debug_printf_parse(": '%c'\n", ch);
6389 o_addchr(dest, ch | quote_mask);
6392 if (!isalnum(ch) && ch != '_')
6394 ch = i_getch(input);
6395 nommu_addchr(as_string, ch);
6397 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6398 } else if (isdigit(ch)) {
6400 ch = i_getch(input);
6401 nommu_addchr(as_string, ch);
6402 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6403 debug_printf_parse(": '%c'\n", ch);
6404 o_addchr(dest, ch | quote_mask);
6405 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6406 } else switch (ch) {
6408 case '!': /* last bg pid */
6409 case '?': /* last exit code */
6410 case '#': /* number of args */
6411 case '*': /* args */
6412 case '@': /* args */
6413 goto make_one_char_var;
6415 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6417 ch = i_getch(input); /* eat '{' */
6418 nommu_addchr(as_string, ch);
6420 ch = i_getch(input); /* first char after '{' */
6421 nommu_addchr(as_string, ch);
6422 /* It should be ${?}, or ${#var},
6423 * or even ${?+subst} - operator acting on a special variable,
6424 * or the beginning of variable name.
6426 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6428 syntax_error_unterm_str("${name}");
6429 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6434 /* It's possible to just call add_till_closing_bracket() at this point.
6435 * However, this regresses some of our testsuite cases
6436 * which check invalid constructs like ${%}.
6437 * Oh well... let's check that the var name part is fine... */
6443 debug_printf_parse(": '%c'\n", ch);
6445 ch = i_getch(input);
6446 nommu_addchr(as_string, ch);
6450 if (!isalnum(ch) && ch != '_') {
6452 unsigned char last_ch;
6453 /* handle parameter expansions
6454 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6456 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
6457 goto bad_dollar_syntax;
6459 /* Eat everything until closing '}' (or ':') */
6461 if (ENABLE_HUSH_BASH_COMPAT
6463 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
6465 /* It's ${var:N[:M]} thing */
6466 end_ch = '}' * 0x100 + ':';
6468 if (ENABLE_HUSH_BASH_COMPAT
6471 /* It's ${var/[/]pattern[/repl]} thing */
6472 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
6474 nommu_addchr(as_string, '/');
6477 end_ch = '}' * 0x100 + '/';
6483 #if ENABLE_HUSH_DOLLAR_OPS
6484 last_ch = add_till_closing_bracket(dest, input, end_ch);
6486 #error Simple code to only allow ${var} is not implemented
6489 o_addstr(as_string, dest->data + pos);
6490 o_addchr(as_string, last_ch);
6493 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6494 /* close the first block: */
6495 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6496 /* while parsing N from ${var:N[:M]}
6497 * or pattern from ${var/[/]pattern[/repl]} */
6498 if ((end_ch & 0xff) == last_ch) {
6499 /* got ':' or '/'- parse the rest */
6504 if (end_ch == '}' * 0x100 + ':') {
6505 /* it's ${var:N} - emulate :999999999 */
6506 o_addstr(dest, "999999999");
6507 } /* else: it's ${var/[/]pattern} */
6512 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6515 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6519 ch = i_getch(input);
6520 nommu_addchr(as_string, ch);
6521 # if ENABLE_SH_MATH_SUPPORT
6522 if (i_peek(input) == '(') {
6523 ch = i_getch(input);
6524 nommu_addchr(as_string, ch);
6525 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6526 o_addchr(dest, /*quote_mask |*/ '+');
6529 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6531 o_addstr(as_string, dest->data + pos);
6532 o_addchr(as_string, ')');
6533 o_addchr(as_string, ')');
6535 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6539 # if ENABLE_HUSH_TICK
6540 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6541 o_addchr(dest, quote_mask | '`');
6544 add_till_closing_bracket(dest, input, ')');
6546 o_addstr(as_string, dest->data + pos);
6547 o_addchr(as_string, ')');
6549 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6555 ch = i_getch(input);
6556 nommu_addchr(as_string, ch);
6558 if (isalnum(ch)) { /* it's $_name or $_123 */
6563 /* TODO: $_ and $-: */
6564 /* $_ Shell or shell script name; or last argument of last command
6565 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6566 * but in command's env, set to full pathname used to invoke it */
6567 /* $- Option flags set by set builtin or shell options (-i etc) */
6569 o_addQchr(dest, '$');
6571 debug_printf_parse("parse_dollar return 0\n");
6577 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6578 parse_stream_dquoted(dest, input, dquote_end)
6579 #define as_string NULL
6581 static int parse_stream_dquoted(o_string *as_string,
6583 struct in_str *input,
6590 ch = i_getch(input);
6592 nommu_addchr(as_string, ch);
6593 if (ch == dquote_end) { /* may be only '"' or EOF */
6594 if (dest->o_assignment == NOT_ASSIGNMENT)
6595 dest->o_escape ^= 1;
6596 debug_printf_parse("parse_stream_dquoted return 0\n");
6599 /* note: can't move it above ch == dquote_end check! */
6601 syntax_error_unterm_ch('"');
6602 /*xfunc_die(); - redundant */
6606 next = i_peek(input);
6608 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6609 ch, ch, dest->o_escape);
6612 syntax_error("\\<eof>");
6616 * "The backslash retains its special meaning [in "..."]
6617 * only when followed by one of the following characters:
6618 * $, `, ", \, or <newline>. A double quote may be quoted
6619 * within double quotes by preceding it with a backslash."
6621 if (strchr("$`\"\\\n", next) != NULL) {
6622 ch = i_getch(input);
6624 o_addqchr(dest, ch);
6625 nommu_addchr(as_string, ch);
6628 o_addqchr(dest, '\\');
6629 nommu_addchr(as_string, '\\');
6634 if (parse_dollar(as_string, dest, input) != 0) {
6635 debug_printf_parse("parse_stream_dquoted return 1: "
6636 "parse_dollar returned non-0\n");
6641 #if ENABLE_HUSH_TICK
6643 //unsigned pos = dest->length;
6644 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6645 o_addchr(dest, 0x80 | '`');
6646 add_till_backquote(dest, input);
6647 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6648 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6652 o_addQchr(dest, ch);
6654 && (dest->o_assignment == MAYBE_ASSIGNMENT
6655 || dest->o_assignment == WORD_IS_KEYWORD)
6656 && is_well_formed_var_name(dest->data, '=')
6658 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6665 * Scan input until EOF or end_trigger char.
6666 * Return a list of pipes to execute, or NULL on EOF
6667 * or if end_trigger character is met.
6668 * On syntax error, exit is shell is not interactive,
6669 * reset parsing machinery and start parsing anew,
6670 * or return ERR_PTR.
6672 static struct pipe *parse_stream(char **pstring,
6673 struct in_str *input,
6676 struct parse_context ctx;
6677 o_string dest = NULL_O_STRING;
6681 /* Double-quote state is handled in the state variable is_in_dquote.
6682 * A single-quote triggers a bypass of the main loop until its mate is
6683 * found. When recursing, quote state is passed in via dest->o_escape.
6685 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6686 end_trigger ? end_trigger : 'X');
6689 /* If very first arg is "" or '', dest.data may end up NULL.
6690 * Preventing this: */
6691 o_addchr(&dest, '\0');
6694 G.ifs = get_local_var_value("IFS");
6699 #if ENABLE_HUSH_INTERACTIVE
6700 input->promptmode = 0; /* PS1 */
6702 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6703 initialize_context(&ctx);
6708 const char *is_special;
6712 redir_type redir_style;
6715 /* dest.has_quoted_part = 1; - already is (see below) */
6716 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6719 /* We reached closing '"' */
6722 ch = i_getch(input);
6723 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6724 ch, ch, dest.o_escape);
6729 syntax_error_unterm_str("here document");
6732 /* end_trigger == '}' case errors out earlier,
6733 * checking only ')' */
6734 if (end_trigger == ')') {
6735 syntax_error_unterm_ch('('); /* exits */
6736 /* goto parse_error; */
6739 if (done_word(&dest, &ctx)) {
6743 done_pipe(&ctx, PIPE_SEQ);
6745 /* If we got nothing... */
6746 /* (this makes bare "&" cmd a no-op.
6747 * bash says: "syntax error near unexpected token '&'") */
6748 if (pi->num_cmds == 0
6749 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6755 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6757 *pstring = ctx.as_string.data;
6759 o_free_unsafe(&ctx.as_string);
6762 debug_printf_parse("parse_stream return %p\n", pi);
6765 nommu_addchr(&ctx.as_string, ch);
6769 next = i_peek(input);
6771 is_special = "{}<>;&|()#'" /* special outside of "str" */
6772 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6773 /* Are { and } special here? */
6774 if (ctx.command->argv /* word [word]{... - non-special */
6775 || dest.length /* word{... - non-special */
6776 || dest.has_quoted_part /* ""{... - non-special */
6777 || (next != ';' /* }; - special */
6778 && next != ')' /* }) - special */
6779 && next != '&' /* }& and }&& ... - special */
6780 && next != '|' /* }|| ... - special */
6781 && !strchr(G.ifs, next) /* {word - non-special */
6784 /* They are not special, skip "{}" */
6787 is_special = strchr(is_special, ch);
6788 is_ifs = strchr(G.ifs, ch);
6790 if (!is_special && !is_ifs) { /* ordinary char */
6792 o_addQchr(&dest, ch);
6793 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6794 || dest.o_assignment == WORD_IS_KEYWORD)
6796 && is_well_formed_var_name(dest.data, '=')
6798 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6804 if (done_word(&dest, &ctx)) {
6808 #if ENABLE_HUSH_CASE
6809 /* "case ... in <newline> word) ..." -
6810 * newlines are ignored (but ';' wouldn't be) */
6811 if (ctx.command->argv == NULL
6812 && ctx.ctx_res_w == RES_MATCH
6817 /* Treat newline as a command separator. */
6818 done_pipe(&ctx, PIPE_SEQ);
6819 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6821 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6826 dest.o_assignment = MAYBE_ASSIGNMENT;
6828 /* note: if (is_ifs) continue;
6829 * will still trigger for us */
6833 /* "cmd}" or "cmd }..." without semicolon or &:
6834 * } is an ordinary char in this case, even inside { cmd; }
6835 * Pathological example: { ""}; } should exec "}" cmd
6838 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6839 || dest.length != 0 /* word} */
6840 || dest.has_quoted_part /* ""} */
6844 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6845 goto skip_end_trigger;
6846 /* else: } does terminate a group */
6849 if (end_trigger && end_trigger == ch
6850 && (ch != ';' || heredoc_cnt == 0)
6851 #if ENABLE_HUSH_CASE
6853 || ctx.ctx_res_w != RES_MATCH
6854 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
6859 /* This is technically valid:
6860 * { cat <<HERE; }; echo Ok
6864 * but we don't support this.
6865 * We require heredoc to be in enclosing {}/(),
6868 syntax_error_unterm_str("here document");
6871 if (done_word(&dest, &ctx)) {
6874 done_pipe(&ctx, PIPE_SEQ);
6875 dest.o_assignment = MAYBE_ASSIGNMENT;
6876 /* Do we sit outside of any if's, loops or case's? */
6878 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6882 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6884 *pstring = ctx.as_string.data;
6886 o_free_unsafe(&ctx.as_string);
6889 debug_printf_parse("parse_stream return %p: "
6890 "end_trigger char found\n",
6892 return ctx.list_head;
6899 /* Catch <, > before deciding whether this word is
6900 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6903 redir_fd = redirect_opt_num(&dest);
6904 if (done_word(&dest, &ctx)) {
6907 redir_style = REDIRECT_OVERWRITE;
6909 redir_style = REDIRECT_APPEND;
6910 ch = i_getch(input);
6911 nommu_addchr(&ctx.as_string, ch);
6914 else if (next == '(') {
6915 syntax_error(">(process) not supported");
6919 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6921 continue; /* back to top of while (1) */
6923 redir_fd = redirect_opt_num(&dest);
6924 if (done_word(&dest, &ctx)) {
6927 redir_style = REDIRECT_INPUT;
6929 redir_style = REDIRECT_HEREDOC;
6931 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6932 ch = i_getch(input);
6933 nommu_addchr(&ctx.as_string, ch);
6934 } else if (next == '>') {
6935 redir_style = REDIRECT_IO;
6936 ch = i_getch(input);
6937 nommu_addchr(&ctx.as_string, ch);
6940 else if (next == '(') {
6941 syntax_error("<(process) not supported");
6945 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6947 continue; /* back to top of while (1) */
6950 if (dest.o_assignment == MAYBE_ASSIGNMENT
6951 /* check that we are not in word in "a=1 2>word b=1": */
6952 && !ctx.pending_redirect
6954 /* ch is a special char and thus this word
6955 * cannot be an assignment */
6956 dest.o_assignment = NOT_ASSIGNMENT;
6959 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6963 if (dest.length == 0) {
6966 if (ch == EOF || ch == '\n')
6969 /* note: we do not add it to &ctx.as_string */
6971 nommu_addchr(&ctx.as_string, '\n');
6973 o_addQchr(&dest, ch);
6978 syntax_error("\\<eof>");
6981 ch = i_getch(input);
6983 o_addchr(&dest, '\\');
6984 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6985 o_addchr(&dest, ch);
6986 nommu_addchr(&ctx.as_string, ch);
6987 /* Example: echo Hello \2>file
6988 * we need to know that word 2 is quoted */
6989 dest.has_quoted_part = 1;
6993 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6994 ctx.as_string.data[--ctx.as_string.length] = '\0';
6999 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
7000 debug_printf_parse("parse_stream parse error: "
7001 "parse_dollar returned non-0\n");
7006 dest.has_quoted_part = 1;
7008 ch = i_getch(input);
7010 syntax_error_unterm_ch('\'');
7011 /*xfunc_die(); - redundant */
7013 nommu_addchr(&ctx.as_string, ch);
7016 o_addqchr(&dest, ch);
7020 dest.has_quoted_part = 1;
7021 is_in_dquote ^= 1; /* invert */
7022 if (dest.o_assignment == NOT_ASSIGNMENT)
7025 #if ENABLE_HUSH_TICK
7029 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
7030 o_addchr(&dest, '`');
7032 add_till_backquote(&dest, input);
7034 o_addstr(&ctx.as_string, dest.data + pos);
7035 o_addchr(&ctx.as_string, '`');
7037 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
7038 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
7043 #if ENABLE_HUSH_CASE
7046 if (done_word(&dest, &ctx)) {
7049 done_pipe(&ctx, PIPE_SEQ);
7050 #if ENABLE_HUSH_CASE
7051 /* Eat multiple semicolons, detect
7052 * whether it means something special */
7057 ch = i_getch(input);
7058 nommu_addchr(&ctx.as_string, ch);
7059 if (ctx.ctx_res_w == RES_CASE_BODY) {
7060 ctx.ctx_dsemicolon = 1;
7061 ctx.ctx_res_w = RES_MATCH;
7067 /* We just finished a cmd. New one may start
7068 * with an assignment */
7069 dest.o_assignment = MAYBE_ASSIGNMENT;
7072 if (done_word(&dest, &ctx)) {
7076 ch = i_getch(input);
7077 nommu_addchr(&ctx.as_string, ch);
7078 done_pipe(&ctx, PIPE_AND);
7080 done_pipe(&ctx, PIPE_BG);
7084 if (done_word(&dest, &ctx)) {
7087 #if ENABLE_HUSH_CASE
7088 if (ctx.ctx_res_w == RES_MATCH)
7089 break; /* we are in case's "word | word)" */
7091 if (next == '|') { /* || */
7092 ch = i_getch(input);
7093 nommu_addchr(&ctx.as_string, ch);
7094 done_pipe(&ctx, PIPE_OR);
7096 /* we could pick up a file descriptor choice here
7097 * with redirect_opt_num(), but bash doesn't do it.
7098 * "echo foo 2| cat" yields "foo 2". */
7101 o_reset_to_empty_unquoted(&ctx.as_string);
7106 #if ENABLE_HUSH_CASE
7107 /* "case... in [(]word)..." - skip '(' */
7108 if (ctx.ctx_res_w == RES_MATCH
7109 && ctx.command->argv == NULL /* not (word|(... */
7110 && dest.length == 0 /* not word(... */
7111 && dest.has_quoted_part == 0 /* not ""(... */
7117 if (parse_group(&dest, &ctx, input, ch) != 0) {
7122 #if ENABLE_HUSH_CASE
7123 if (ctx.ctx_res_w == RES_MATCH)
7127 /* proper use of this character is caught by end_trigger:
7128 * if we see {, we call parse_group(..., end_trigger='}')
7129 * and it will match } earlier (not here). */
7130 syntax_error_unexpected_ch(ch);
7134 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
7140 struct parse_context *pctx;
7141 IF_HAS_KEYWORDS(struct parse_context *p2;)
7143 /* Clean up allocated tree.
7144 * Sample for finding leaks on syntax error recovery path.
7145 * Run it from interactive shell, watch pmap `pidof hush`.
7146 * while if false; then false; fi; do break; fi
7147 * Samples to catch leaks at execution:
7148 * while if (true | {true;}); then echo ok; fi; do break; done
7149 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
7153 /* Update pipe/command counts,
7154 * otherwise freeing may miss some */
7155 done_pipe(pctx, PIPE_SEQ);
7156 debug_printf_clean("freeing list %p from ctx %p\n",
7157 pctx->list_head, pctx);
7158 debug_print_tree(pctx->list_head, 0);
7159 free_pipe_list(pctx->list_head);
7160 debug_printf_clean("freed list %p\n", pctx->list_head);
7162 o_free_unsafe(&pctx->as_string);
7164 IF_HAS_KEYWORDS(p2 = pctx->stack;)
7168 IF_HAS_KEYWORDS(pctx = p2;)
7169 } while (HAS_KEYWORDS && pctx);
7170 /* Free text, clear all dest fields */
7172 /* If we are not in top-level parse, we return,
7173 * our caller will propagate error.
7175 if (end_trigger != ';') {
7183 /* Discard cached input, force prompt */
7185 IF_HUSH_INTERACTIVE(input->promptme = 1;)
7190 /* Executing from string: eval, sh -c '...'
7191 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7192 * end_trigger controls how often we stop parsing
7193 * NUL: parse all, execute, return
7194 * ';': parse till ';' or newline, execute, repeat till EOF
7196 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7198 /* Why we need empty flag?
7199 * An obscure corner case "false; ``; echo $?":
7200 * empty command in `` should still set $? to 0.
7201 * But we can't just set $? to 0 at the start,
7202 * this breaks "false; echo `echo $?`" case.
7206 struct pipe *pipe_list;
7208 pipe_list = parse_stream(NULL, inp, end_trigger);
7209 if (!pipe_list) { /* EOF */
7211 G.last_exitcode = 0;
7214 debug_print_tree(pipe_list, 0);
7215 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7216 run_and_free_list(pipe_list);
7221 static void parse_and_run_string(const char *s)
7223 struct in_str input;
7224 setup_string_in_str(&input, s);
7225 parse_and_run_stream(&input, '\0');
7228 static void parse_and_run_file(FILE *f)
7230 struct in_str input;
7231 setup_file_in_str(&input, f);
7232 parse_and_run_stream(&input, ';');
7235 /* Called a few times only (or even once if "sh -c") */
7236 static void init_sigmasks(void)
7240 sigset_t old_blocked_set;
7242 if (!G.inherited_set_is_saved) {
7243 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7244 G.inherited_set = G.blocked_set;
7246 old_blocked_set = G.blocked_set;
7248 mask = (1 << SIGQUIT);
7249 if (G_interactive_fd) {
7250 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7251 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7252 mask |= SPECIAL_JOB_SIGS;
7254 G.non_DFL_mask = mask;
7259 sigaddset(&G.blocked_set, sig);
7263 sigdelset(&G.blocked_set, SIGCHLD);
7265 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7266 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7268 /* POSIX allows shell to re-enable SIGCHLD
7269 * even if it was SIG_IGN on entry */
7270 #if ENABLE_HUSH_FAST
7271 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7272 if (!G.inherited_set_is_saved)
7273 signal(SIGCHLD, SIGCHLD_handler);
7275 if (!G.inherited_set_is_saved)
7276 signal(SIGCHLD, SIG_DFL);
7279 G.inherited_set_is_saved = 1;
7284 static void maybe_set_to_sigexit(int sig)
7286 void (*handler)(int);
7287 /* non_DFL_mask'ed signals are, well, masked,
7288 * no need to set handler for them.
7290 if (!((G.non_DFL_mask >> sig) & 1)) {
7291 handler = signal(sig, sigexit);
7292 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7293 signal(sig, handler);
7296 /* Set handlers to restore tty pgrp and exit */
7297 static void set_fatal_handlers(void)
7299 /* We _must_ restore tty pgrp on fatal signals */
7301 maybe_set_to_sigexit(SIGILL );
7302 maybe_set_to_sigexit(SIGFPE );
7303 maybe_set_to_sigexit(SIGBUS );
7304 maybe_set_to_sigexit(SIGSEGV);
7305 maybe_set_to_sigexit(SIGTRAP);
7306 } /* else: hush is perfect. what SEGV? */
7307 maybe_set_to_sigexit(SIGABRT);
7308 /* bash 3.2 seems to handle these just like 'fatal' ones */
7309 maybe_set_to_sigexit(SIGPIPE);
7310 maybe_set_to_sigexit(SIGALRM);
7311 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7312 * if we aren't interactive... but in this case
7313 * we never want to restore pgrp on exit, and this fn is not called */
7314 /*maybe_set_to_sigexit(SIGHUP );*/
7315 /*maybe_set_to_sigexit(SIGTERM);*/
7316 /*maybe_set_to_sigexit(SIGINT );*/
7320 static int set_mode(const char cstate, const char mode)
7322 int state = (cstate == '-' ? 1 : 0);
7324 case 'n': G.n_mode = state; break;
7325 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7326 default: return EXIT_FAILURE;
7328 return EXIT_SUCCESS;
7331 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7332 int hush_main(int argc, char **argv)
7335 unsigned builtin_argc;
7337 struct variable *cur_var;
7340 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7341 G.last_exitcode = EXIT_SUCCESS;
7343 G.argv0_for_re_execing = argv[0];
7345 /* Deal with HUSH_VERSION */
7346 G.shell_ver.flg_export = 1;
7347 G.shell_ver.flg_read_only = 1;
7348 /* Code which handles ${var/P/R} needs writable values for all variables,
7349 * therefore we xstrdup: */
7350 G.shell_ver.varstr = xstrdup(hush_version_str),
7351 G.top_var = &G.shell_ver;
7352 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7353 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7354 /* reinstate HUSH_VERSION in environment */
7355 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7356 putenv(G.shell_ver.varstr);
7358 /* Initialize our shell local variables with the values
7359 * currently living in the environment */
7360 cur_var = G.top_var;
7363 char *value = strchr(*e, '=');
7364 if (value) { /* paranoia */
7365 cur_var->next = xzalloc(sizeof(*cur_var));
7366 cur_var = cur_var->next;
7367 cur_var->varstr = *e;
7368 cur_var->max_len = strlen(*e);
7369 cur_var->flg_export = 1;
7375 set_pwd_var(/*exp:*/ 1);
7376 /* bash also exports SHLVL and _,
7377 * and sets (but doesn't export) the following variables:
7379 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7380 * BASH_VERSION='3.2.0(1)-release'
7382 * MACHTYPE=i386-pc-linux-gnu
7384 * HOSTNAME=<xxxxxxxxxx>
7385 * PPID=<NNNNN> - we also do it elsewhere
7396 * PIPESTATUS=([0]="0")
7397 * HISTFILE=/<xxx>/.bash_history
7401 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7403 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7413 #if ENABLE_FEATURE_EDITING
7414 G.line_input_state = new_line_input_t(FOR_SHELL);
7416 G.global_argc = argc;
7417 G.global_argv = argv;
7418 /* Initialize some more globals to non-zero values */
7419 cmdedit_update_prompt();
7421 if (setjmp(die_jmp)) {
7422 /* xfunc has failed! die die die */
7423 /* no EXIT traps, this is an escape hatch! */
7425 hush_exit(xfunc_error_retval);
7428 /* Shell is non-interactive at first. We need to call
7429 * init_sigmasks() if we are going to execute "sh <script>",
7430 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7431 * If we later decide that we are interactive, we run init_sigmasks()
7432 * in order to intercept (more) signals.
7436 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7439 opt = getopt(argc, argv, "+c:xins"
7442 # if ENABLE_HUSH_FUNCTIONS
7452 * sh ... -c 'script'
7453 * sh ... -c 'script' ARG0 [ARG1...]
7454 * On NOMMU, if builtin_argc != 0,
7455 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7456 * "" needs to be replaced with NULL
7457 * and BARGV vector fed to builtin function.
7458 * Note: the form without ARG0 never happens:
7459 * sh ... -c 'builtin' BARGV... ""
7462 G.root_pid = getpid();
7463 G.root_ppid = getppid();
7465 G.global_argv = argv + optind;
7466 G.global_argc = argc - optind;
7468 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7469 const struct built_in_command *x;
7472 x = find_builtin(optarg);
7473 if (x) { /* paranoia */
7474 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7475 G.global_argv += builtin_argc;
7476 G.global_argv[-1] = NULL; /* replace "" */
7477 G.last_exitcode = x->b_function(argv + optind - 1);
7481 if (!G.global_argv[0]) {
7482 /* -c 'script' (no params): prevent empty $0 */
7483 G.global_argv--; /* points to argv[i] of 'script' */
7484 G.global_argv[0] = argv[0];
7486 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7488 parse_and_run_string(optarg);
7491 /* Well, we cannot just declare interactiveness,
7492 * we have to have some stuff (ctty, etc) */
7493 /* G_interactive_fd++; */
7496 /* "-s" means "read from stdin", but this is how we always
7497 * operate, so simply do nothing here. */
7500 case '<': /* "big heredoc" support */
7501 full_write1_str(optarg);
7504 unsigned long long empty_trap_mask;
7506 G.root_pid = bb_strtou(optarg, &optarg, 16);
7508 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7510 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7512 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7514 builtin_argc = bb_strtou(optarg, &optarg, 16);
7516 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7517 if (empty_trap_mask != 0) {
7520 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7521 for (sig = 1; sig < NSIG; sig++) {
7522 if (empty_trap_mask & (1LL << sig)) {
7523 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7524 sigaddset(&G.blocked_set, sig);
7527 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7529 # if ENABLE_HUSH_LOOPS
7531 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7537 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7539 # if ENABLE_HUSH_FUNCTIONS
7541 struct function *funcp = new_function(optarg);
7542 /* funcp->name is already set to optarg */
7543 /* funcp->body is set to NULL. It's a special case. */
7544 funcp->body_as_string = argv[optind];
7552 if (set_mode('-', opt) == 0) /* no error */
7556 fprintf(stderr, "Usage: sh [FILE]...\n"
7557 " or: sh -c command [args]...\n\n");
7563 } /* option parsing loop */
7566 G.root_pid = getpid();
7567 G.root_ppid = getppid();
7570 /* If we are login shell... */
7571 if (argv[0] && argv[0][0] == '-') {
7573 debug_printf("sourcing /etc/profile\n");
7574 input = fopen_for_read("/etc/profile");
7575 if (input != NULL) {
7576 close_on_exec_on(fileno(input));
7578 parse_and_run_file(input);
7581 /* bash: after sourcing /etc/profile,
7582 * tries to source (in the given order):
7583 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7584 * stopping on first found. --noprofile turns this off.
7585 * bash also sources ~/.bash_logout on exit.
7586 * If called as sh, skips .bash_XXX files.
7593 * "bash <script>" (which is never interactive (unless -i?))
7594 * sources $BASH_ENV here (without scanning $PATH).
7595 * If called as sh, does the same but with $ENV.
7597 debug_printf("running script '%s'\n", argv[optind]);
7598 G.global_argv = argv + optind;
7599 G.global_argc = argc - optind;
7600 input = xfopen_for_read(argv[optind]);
7601 close_on_exec_on(fileno(input));
7603 parse_and_run_file(input);
7604 #if ENABLE_FEATURE_CLEAN_UP
7610 /* Up to here, shell was non-interactive. Now it may become one.
7611 * NB: don't forget to (re)run init_sigmasks() as needed.
7614 /* A shell is interactive if the '-i' flag was given,
7615 * or if all of the following conditions are met:
7617 * no arguments remaining or the -s flag given
7618 * standard input is a terminal
7619 * standard output is a terminal
7620 * Refer to Posix.2, the description of the 'sh' utility.
7623 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7624 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7625 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7626 if (G_saved_tty_pgrp < 0)
7627 G_saved_tty_pgrp = 0;
7629 /* try to dup stdin to high fd#, >= 255 */
7630 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7631 if (G_interactive_fd < 0) {
7632 /* try to dup to any fd */
7633 G_interactive_fd = dup(STDIN_FILENO);
7634 if (G_interactive_fd < 0) {
7636 G_interactive_fd = 0;
7637 G_saved_tty_pgrp = 0;
7640 // TODO: track & disallow any attempts of user
7641 // to (inadvertently) close/redirect G_interactive_fd
7643 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7644 if (G_interactive_fd) {
7645 close_on_exec_on(G_interactive_fd);
7647 if (G_saved_tty_pgrp) {
7648 /* If we were run as 'hush &', sleep until we are
7649 * in the foreground (tty pgrp == our pgrp).
7650 * If we get started under a job aware app (like bash),
7651 * make sure we are now in charge so we don't fight over
7652 * who gets the foreground */
7654 pid_t shell_pgrp = getpgrp();
7655 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7656 if (G_saved_tty_pgrp == shell_pgrp)
7658 /* send TTIN to ourself (should stop us) */
7659 kill(- shell_pgrp, SIGTTIN);
7663 /* Block some signals */
7666 if (G_saved_tty_pgrp) {
7667 /* Set other signals to restore saved_tty_pgrp */
7668 set_fatal_handlers();
7669 /* Put ourselves in our own process group
7670 * (bash, too, does this only if ctty is available) */
7671 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7672 /* Grab control of the terminal */
7673 tcsetpgrp(G_interactive_fd, getpid());
7675 /* -1 is special - makes xfuncs longjmp, not exit
7676 * (we reset die_sleep = 0 whereever we [v]fork) */
7677 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7681 #elif ENABLE_HUSH_INTERACTIVE
7682 /* No job control compiled in, only prompt/line editing */
7683 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7684 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7685 if (G_interactive_fd < 0) {
7686 /* try to dup to any fd */
7687 G_interactive_fd = dup(STDIN_FILENO);
7688 if (G_interactive_fd < 0)
7690 G_interactive_fd = 0;
7693 if (G_interactive_fd) {
7694 close_on_exec_on(G_interactive_fd);
7698 /* We have interactiveness code disabled */
7702 * if interactive but not a login shell, sources ~/.bashrc
7703 * (--norc turns this off, --rcfile <file> overrides)
7706 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7707 /* note: ash and hush share this string */
7708 printf("\n\n%s %s\n"
7709 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7712 "hush - the humble shell"
7716 parse_and_run_file(stdin);
7719 #if ENABLE_FEATURE_CLEAN_UP
7720 if (G.cwd != bb_msg_unknown)
7722 cur_var = G.top_var->next;
7724 struct variable *tmp = cur_var;
7725 if (!cur_var->max_len)
7726 free(cur_var->varstr);
7727 cur_var = cur_var->next;
7731 hush_exit(G.last_exitcode);
7736 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7737 int lash_main(int argc, char **argv)
7739 bb_error_msg("lash is deprecated, please use hush instead");
7740 return hush_main(argc, argv);
7745 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7746 int msh_main(int argc, char **argv)
7748 //bb_error_msg("msh is deprecated, please use hush instead");
7749 return hush_main(argc, argv);
7757 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7762 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7769 return applet_main_func(argc, argv - argc);
7772 static int FAST_FUNC builtin_test(char **argv)
7774 return run_applet_main(argv, test_main);
7777 static int FAST_FUNC builtin_echo(char **argv)
7779 return run_applet_main(argv, echo_main);
7783 static int FAST_FUNC builtin_printf(char **argv)
7785 return run_applet_main(argv, printf_main);
7789 static char **skip_dash_dash(char **argv)
7792 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7797 static int FAST_FUNC builtin_eval(char **argv)
7799 int rcode = EXIT_SUCCESS;
7801 argv = skip_dash_dash(argv);
7803 char *str = expand_strvec_to_string(argv);
7805 * eval "echo Hi; done" ("done" is syntax error):
7806 * "echo Hi" will not execute too.
7808 parse_and_run_string(str);
7810 rcode = G.last_exitcode;
7815 static int FAST_FUNC builtin_cd(char **argv)
7819 argv = skip_dash_dash(argv);
7821 if (newdir == NULL) {
7822 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7823 * bash says "bash: cd: HOME not set" and does nothing
7826 const char *home = get_local_var_value("HOME");
7827 newdir = home ? home : "/";
7829 if (chdir(newdir)) {
7830 /* Mimic bash message exactly */
7831 bb_perror_msg("cd: %s", newdir);
7832 return EXIT_FAILURE;
7834 /* Read current dir (get_cwd(1) is inside) and set PWD.
7835 * Note: do not enforce exporting. If PWD was unset or unexported,
7836 * set it again, but do not export. bash does the same.
7838 set_pwd_var(/*exp:*/ 0);
7839 return EXIT_SUCCESS;
7842 static int FAST_FUNC builtin_exec(char **argv)
7844 argv = skip_dash_dash(argv);
7845 if (argv[0] == NULL)
7846 return EXIT_SUCCESS; /* bash does this */
7848 /* Careful: we can end up here after [v]fork. Do not restore
7849 * tty pgrp then, only top-level shell process does that */
7850 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7851 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7853 /* TODO: if exec fails, bash does NOT exit! We do.
7854 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7855 * and tcsetpgrp, and this is inherently racy.
7857 execvp_or_die(argv);
7860 static int FAST_FUNC builtin_exit(char **argv)
7862 debug_printf_exec("%s()\n", __func__);
7864 /* interactive bash:
7865 * # trap "echo EEE" EXIT
7868 * There are stopped jobs.
7869 * (if there are _stopped_ jobs, running ones don't count)
7872 # EEE (then bash exits)
7874 * we can use G.exiting = -1 as indicator "last cmd was exit"
7877 /* note: EXIT trap is run by hush_exit */
7878 argv = skip_dash_dash(argv);
7879 if (argv[0] == NULL)
7880 hush_exit(G.last_exitcode);
7881 /* mimic bash: exit 123abc == exit 255 + error msg */
7882 xfunc_error_retval = 255;
7883 /* bash: exit -2 == exit 254, no error msg */
7884 hush_exit(xatoi(argv[0]) & 0xff);
7887 static void print_escaped(const char *s)
7892 const char *p = strchrnul(s, '\'');
7893 /* print 'xxxx', possibly just '' */
7894 printf("'%.*s'", (int)(p - s), s);
7899 /* s points to '; print "'''...'''" */
7901 do putchar('\''); while (*++s == '\'');
7906 #if !ENABLE_HUSH_LOCAL
7907 #define helper_export_local(argv, exp, lvl) \
7908 helper_export_local(argv, exp)
7910 static void helper_export_local(char **argv, int exp, int lvl)
7915 /* So far we do not check that name is valid (TODO?) */
7917 if (strchr(name, '=') == NULL) {
7918 struct variable *var;
7920 var = get_local_var(name);
7921 if (exp == -1) { /* unexporting? */
7922 /* export -n NAME (without =VALUE) */
7924 var->flg_export = 0;
7925 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7927 } /* else: export -n NOT_EXISTING_VAR: no-op */
7930 if (exp == 1) { /* exporting? */
7931 /* export NAME (without =VALUE) */
7933 var->flg_export = 1;
7934 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7935 putenv(var->varstr);
7939 /* Exporting non-existing variable.
7940 * bash does not put it in environment,
7941 * but remembers that it is exported,
7942 * and does put it in env when it is set later.
7943 * We just set it to "" and export. */
7944 /* Or, it's "local NAME" (without =VALUE).
7945 * bash sets the value to "". */
7946 name = xasprintf("%s=", name);
7948 /* (Un)exporting/making local NAME=VALUE */
7949 name = xstrdup(name);
7951 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7955 static int FAST_FUNC builtin_export(char **argv)
7957 unsigned opt_unexport;
7959 #if ENABLE_HUSH_EXPORT_N
7960 /* "!": do not abort on errors */
7961 opt_unexport = getopt32(argv, "!n");
7962 if (opt_unexport == (uint32_t)-1)
7963 return EXIT_FAILURE;
7970 if (argv[0] == NULL) {
7977 /* ash emits: export VAR='VAL'
7978 * bash: declare -x VAR="VAL"
7979 * we follow ash example */
7980 const char *s = *e++;
7981 const char *p = strchr(s, '=');
7983 if (!p) /* wtf? take next variable */
7986 printf("export %.*s", (int)(p - s) + 1, s);
7987 print_escaped(p + 1);
7991 /*fflush_all(); - done after each builtin anyway */
7993 return EXIT_SUCCESS;
7996 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7998 return EXIT_SUCCESS;
8001 #if ENABLE_HUSH_LOCAL
8002 static int FAST_FUNC builtin_local(char **argv)
8004 if (G.func_nest_level == 0) {
8005 bb_error_msg("%s: not in a function", argv[0]);
8006 return EXIT_FAILURE; /* bash compat */
8008 helper_export_local(argv, 0, G.func_nest_level);
8009 return EXIT_SUCCESS;
8013 static int FAST_FUNC builtin_trap(char **argv)
8019 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8024 /* No args: print all trapped */
8025 for (i = 0; i < NSIG; ++i) {
8028 print_escaped(G.traps[i]);
8029 /* note: bash adds "SIG", but only if invoked
8030 * as "bash". If called as "sh", or if set -o posix,
8031 * then it prints short signal names.
8032 * We are printing short names: */
8033 printf(" %s\n", get_signame(i));
8036 /*fflush_all(); - done after each builtin anyway */
8037 return EXIT_SUCCESS;
8041 /* If first arg is a number: reset all specified signals */
8042 sig = bb_strtou(*argv, NULL, 10);
8048 sig = get_signum(*argv++);
8049 if (sig < 0 || sig >= NSIG) {
8051 /* Mimic bash message exactly */
8052 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8057 G.traps[sig] = xstrdup(new_cmd);
8059 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8060 get_signame(sig), sig, G.traps[sig]);
8062 /* There is no signal for 0 (EXIT) */
8067 sigaddset(&G.blocked_set, sig);
8069 /* There was a trap handler, we are removing it
8070 * (if sig has non-DFL handling,
8071 * we don't need to do anything) */
8072 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8074 sigdelset(&G.blocked_set, sig);
8077 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8081 if (!argv[1]) { /* no second arg */
8082 bb_error_msg("trap: invalid arguments");
8083 return EXIT_FAILURE;
8086 /* First arg is "-": reset all specified to default */
8087 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8088 /* Everything else: set arg as signal handler
8089 * (includes "" case, which ignores signal) */
8090 if (argv[0][0] == '-') {
8091 if (argv[0][1] == '\0') { /* "-" */
8092 /* new_cmd remains NULL: "reset these sigs" */
8095 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8098 /* else: "-something", no special meaning */
8103 goto process_sig_list;
8106 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8107 static int FAST_FUNC builtin_type(char **argv)
8109 int ret = EXIT_SUCCESS;
8115 if (0) {} /* make conditional compile easier below */
8116 /*else if (find_alias(*argv))
8117 type = "an alias";*/
8118 #if ENABLE_HUSH_FUNCTIONS
8119 else if (find_function(*argv))
8120 type = "a function";
8122 else if (find_builtin(*argv))
8123 type = "a shell builtin";
8124 else if ((path = find_in_path(*argv)) != NULL)
8127 bb_error_msg("type: %s: not found", *argv);
8132 printf("%s is %s\n", *argv, type);
8140 /* built-in 'fg' and 'bg' handler */
8141 static int FAST_FUNC builtin_fg_bg(char **argv)
8146 if (!G_interactive_fd)
8147 return EXIT_FAILURE;
8149 /* If they gave us no args, assume they want the last backgrounded task */
8151 for (pi = G.job_list; pi; pi = pi->next) {
8152 if (pi->jobid == G.last_jobid) {
8156 bb_error_msg("%s: no current job", argv[0]);
8157 return EXIT_FAILURE;
8159 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8160 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8161 return EXIT_FAILURE;
8163 for (pi = G.job_list; pi; pi = pi->next) {
8164 if (pi->jobid == jobnum) {
8168 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8169 return EXIT_FAILURE;
8171 /* TODO: bash prints a string representation
8172 * of job being foregrounded (like "sleep 1 | cat") */
8173 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8174 /* Put the job into the foreground. */
8175 tcsetpgrp(G_interactive_fd, pi->pgrp);
8178 /* Restart the processes in the job */
8179 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8180 for (i = 0; i < pi->num_cmds; i++) {
8181 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8182 pi->cmds[i].is_stopped = 0;
8184 pi->stopped_cmds = 0;
8186 i = kill(- pi->pgrp, SIGCONT);
8188 if (errno == ESRCH) {
8189 delete_finished_bg_job(pi);
8190 return EXIT_SUCCESS;
8192 bb_perror_msg("kill (SIGCONT)");
8195 if (argv[0][0] == 'f') {
8197 return checkjobs_and_fg_shell(pi);
8199 return EXIT_SUCCESS;
8203 #if ENABLE_HUSH_HELP
8204 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8206 const struct built_in_command *x;
8209 "Built-in commands:\n"
8210 "------------------\n");
8211 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8213 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8216 return EXIT_SUCCESS;
8221 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8224 const char *status_string;
8226 for (job = G.job_list; job; job = job->next) {
8227 if (job->alive_cmds == job->stopped_cmds)
8228 status_string = "Stopped";
8230 status_string = "Running";
8232 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8234 return EXIT_SUCCESS;
8239 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8244 # ifdef M_TRIM_THRESHOLD
8245 /* Optional. Reduces probability of false positives */
8248 /* Crude attempt to find where "free memory" starts,
8249 * sans fragmentation. */
8251 l = (unsigned long)p;
8254 if (l < (unsigned long)p) l = (unsigned long)p;
8257 if (!G.memleak_value)
8258 G.memleak_value = l;
8260 l -= G.memleak_value;
8267 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8272 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8275 return EXIT_SUCCESS;
8278 static int FAST_FUNC builtin_read(char **argv)
8287 /* "!": do not abort on errors.
8288 * Option string must start with "sr" to match BUILTIN_READ_xxx
8290 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8291 if (read_flags == (uint32_t)-1)
8292 return EXIT_FAILURE;
8295 r = shell_builtin_read(set_local_var_from_halves,
8297 get_local_var_value("IFS"), /* can be NULL */
8305 if ((uintptr_t)r > 1) {
8306 bb_error_msg("%s", r);
8307 r = (char*)(uintptr_t)1;
8310 return (uintptr_t)r;
8313 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8314 * built-in 'set' handler
8316 * set [-abCefhmnuvx] [-o option] [argument...]
8317 * set [+abCefhmnuvx] [+o option] [argument...]
8318 * set -- [argument...]
8321 * Implementations shall support the options in both their hyphen and
8322 * plus-sign forms. These options can also be specified as options to sh.
8324 * Write out all variables and their values: set
8325 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8326 * Turn on the -x and -v options: set -xv
8327 * Unset all positional parameters: set --
8328 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8329 * Set the positional parameters to the expansion of x, even if x expands
8330 * with a leading '-' or '+': set -- $x
8332 * So far, we only support "set -- [argument...]" and some of the short names.
8334 static int FAST_FUNC builtin_set(char **argv)
8337 char **pp, **g_argv;
8338 char *arg = *++argv;
8342 for (e = G.top_var; e; e = e->next)
8344 return EXIT_SUCCESS;
8348 if (!strcmp(arg, "--")) {
8352 if (arg[0] != '+' && arg[0] != '-')
8354 for (n = 1; arg[n]; ++n)
8355 if (set_mode(arg[0], arg[n]))
8357 } while ((arg = *++argv) != NULL);
8358 /* Now argv[0] is 1st argument */
8361 return EXIT_SUCCESS;
8364 /* NB: G.global_argv[0] ($0) is never freed/changed */
8365 g_argv = G.global_argv;
8366 if (G.global_args_malloced) {
8372 G.global_args_malloced = 1;
8373 pp = xzalloc(sizeof(pp[0]) * 2);
8374 pp[0] = g_argv[0]; /* retain $0 */
8377 /* This realloc's G.global_argv */
8378 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8385 return EXIT_SUCCESS;
8387 /* Nothing known, so abort */
8389 bb_error_msg("set: %s: invalid option", arg);
8390 return EXIT_FAILURE;
8393 static int FAST_FUNC builtin_shift(char **argv)
8396 argv = skip_dash_dash(argv);
8400 if (n >= 0 && n < G.global_argc) {
8401 if (G.global_args_malloced) {
8404 free(G.global_argv[m++]);
8407 memmove(&G.global_argv[1], &G.global_argv[n+1],
8408 G.global_argc * sizeof(G.global_argv[0]));
8409 return EXIT_SUCCESS;
8411 return EXIT_FAILURE;
8414 static int FAST_FUNC builtin_source(char **argv)
8416 char *arg_path, *filename;
8419 #if ENABLE_HUSH_FUNCTIONS
8423 argv = skip_dash_dash(argv);
8426 /* bash says: "bash: .: filename argument required" */
8427 return 2; /* bash compat */
8430 if (!strchr(filename, '/')) {
8431 arg_path = find_in_path(filename);
8433 filename = arg_path;
8435 input = fopen_or_warn(filename, "r");
8438 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8439 return EXIT_FAILURE;
8441 close_on_exec_on(fileno(input));
8443 #if ENABLE_HUSH_FUNCTIONS
8444 sv_flg = G.flag_return_in_progress;
8445 /* "we are inside sourced file, ok to use return" */
8446 G.flag_return_in_progress = -1;
8448 save_and_replace_G_args(&sv, argv);
8450 parse_and_run_file(input);
8453 restore_G_args(&sv, argv);
8454 #if ENABLE_HUSH_FUNCTIONS
8455 G.flag_return_in_progress = sv_flg;
8458 return G.last_exitcode;
8461 static int FAST_FUNC builtin_umask(char **argv)
8467 argv = skip_dash_dash(argv);
8469 mode_t old_mask = mask;
8472 rc = bb_parse_mode(argv[0], &mask);
8477 * bash: umask: 'q': invalid symbolic mode operator
8478 * bash: umask: 999: octal number out of range
8480 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8485 printf("%04o\n", (unsigned) mask);
8486 /* fall through and restore mask which we set to 0 */
8490 return !rc; /* rc != 0 - success */
8493 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8494 static int FAST_FUNC builtin_unset(char **argv)
8499 /* "!": do not abort on errors */
8500 /* "+": stop at 1st non-option */
8501 opts = getopt32(argv, "!+vf");
8502 if (opts == (unsigned)-1)
8503 return EXIT_FAILURE;
8505 bb_error_msg("unset: -v and -f are exclusive");
8506 return EXIT_FAILURE;
8512 if (!(opts & 2)) { /* not -f */
8513 if (unset_local_var(*argv)) {
8514 /* unset <nonexistent_var> doesn't fail.
8515 * Error is when one tries to unset RO var.
8516 * Message was printed by unset_local_var. */
8520 #if ENABLE_HUSH_FUNCTIONS
8530 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8531 static int FAST_FUNC builtin_wait(char **argv)
8533 int ret = EXIT_SUCCESS;
8536 argv = skip_dash_dash(argv);
8537 if (argv[0] == NULL) {
8538 /* Don't care about wait results */
8539 /* Note 1: must wait until there are no more children */
8540 /* Note 2: must be interruptible */
8542 * $ sleep 3 & sleep 6 & wait
8547 * $ sleep 3 & sleep 6 & wait
8551 * ^C <-- after ~4 sec from keyboard
8554 sigaddset(&G.blocked_set, SIGCHLD);
8555 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8558 if (errno == ECHILD)
8560 /* Wait for SIGCHLD or any other signal of interest */
8561 /* sigtimedwait with infinite timeout: */
8562 sig = sigwaitinfo(&G.blocked_set, NULL);
8564 sig = check_and_run_traps(sig);
8565 if (sig && sig != SIGCHLD) { /* see note 2 */
8571 sigdelset(&G.blocked_set, SIGCHLD);
8572 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8576 /* This is probably buggy wrt interruptible-ness */
8578 pid_t pid = bb_strtou(*argv, NULL, 10);
8580 /* mimic bash message */
8581 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8582 return EXIT_FAILURE;
8584 if (waitpid(pid, &status, 0) == pid) {
8585 if (WIFSIGNALED(status))
8586 ret = 128 + WTERMSIG(status);
8587 else if (WIFEXITED(status))
8588 ret = WEXITSTATUS(status);
8592 bb_perror_msg("wait %s", *argv);
8601 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8602 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8605 def = bb_strtou(argv[1], NULL, 10);
8606 if (errno || def < def_min || argv[2]) {
8607 bb_error_msg("%s: bad arguments", argv[0]);
8615 #if ENABLE_HUSH_LOOPS
8616 static int FAST_FUNC builtin_break(char **argv)
8619 if (G.depth_of_loop == 0) {
8620 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8621 return EXIT_SUCCESS; /* bash compat */
8623 G.flag_break_continue++; /* BC_BREAK = 1 */
8625 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8626 if (depth == UINT_MAX)
8627 G.flag_break_continue = BC_BREAK;
8628 if (G.depth_of_loop < depth)
8629 G.depth_break_continue = G.depth_of_loop;
8631 return EXIT_SUCCESS;
8634 static int FAST_FUNC builtin_continue(char **argv)
8636 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8637 return builtin_break(argv);
8641 #if ENABLE_HUSH_FUNCTIONS
8642 static int FAST_FUNC builtin_return(char **argv)
8646 if (G.flag_return_in_progress != -1) {
8647 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8648 return EXIT_FAILURE; /* bash compat */
8651 G.flag_return_in_progress = 1;
8654 * out of range: wraps around at 256, does not error out
8655 * non-numeric param:
8656 * f() { false; return qwe; }; f; echo $?
8657 * bash: return: qwe: numeric argument required <== we do this
8658 * 255 <== we also do this
8660 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);