1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * make complex ${var%...} constructs support optional
45 * make here documents optional
46 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
50 * builtins mandated by standards we don't support:
51 * [un]alias, command, fc:
52 * command -v CMD: print "/path/to/CMD"
53 * prints "CMD" for builtins
54 * prints "alias ALIAS='EXPANSION'" for aliases
55 * prints nothing and sets $? to 1 if not found
56 * command -V CMD: print "CMD is /path/CMD|a shell builtin|etc"
57 * command [-p] CMD: run CMD, even if a function CMD also exists
58 * (can use this to override standalone shell as well)
59 * -p: use default $PATH
60 * command BLTIN: disables special-ness (e.g. errors do not abort)
61 * fc -l[nr] [BEG] [END]: list range of commands in history
62 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
63 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
66 * redirection of stdout+stderr: &> and >&
67 * reserved words: function select
68 * advanced test: [[ ]]
69 * process substitution: <(list) and >(list)
72 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
73 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
74 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
76 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
77 * This is exactly equivalent to let "EXPR".
78 * $[EXPR]: synonym for $((EXPR))
79 * indirect expansion: ${!VAR}
80 * substring op on @: ${@:n:m}
83 * Some builtins mandated by standards:
84 * newgrp [GRP]: not a builtin in bash but a suid binary
85 * which spawns a new shell with new group ID
86 * In bash, export builtin is special, its arguments are assignments
87 * and therefore expansion of them should be "one-word" expansion:
88 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
90 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
91 * ls: cannot access i=a: No such file or directory
92 * ls: cannot access b: No such file or directory
93 * Note1: same applies to local builtin.
94 * Note2: bash 3.2.33(1) does this only if export word itself
96 * $ export i=`echo 'aaa bbb'`; echo "$i"
98 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
102 //config: bool "hush (64 kb)"
105 //config: hush is a small shell. It handles the normal flow control
106 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
107 //config: case/esac. Redirections, here documents, $((arithmetic))
108 //config: and functions are supported.
110 //config: It will compile and work on no-mmu systems.
112 //config: It does not handle select, aliases, tilde expansion,
113 //config: &>file and >&file redirection of stdout+stderr.
115 //config:config HUSH_BASH_COMPAT
116 //config: bool "bash-compatible extensions"
118 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
120 //config:config HUSH_BRACE_EXPANSION
121 //config: bool "Brace expansion"
123 //config: depends on HUSH_BASH_COMPAT
125 //config: Enable {abc,def} extension.
127 //config:config HUSH_INTERACTIVE
128 //config: bool "Interactive mode"
130 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
132 //config: Enable interactive mode (prompt and command editing).
133 //config: Without this, hush simply reads and executes commands
134 //config: from stdin just like a shell script from a file.
135 //config: No prompt, no PS1/PS2 magic shell variables.
137 //config:config HUSH_SAVEHISTORY
138 //config: bool "Save command history to .hush_history"
140 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
142 //config:config HUSH_JOB
143 //config: bool "Job control"
145 //config: depends on HUSH_INTERACTIVE
147 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
148 //config: command (not entire shell), fg/bg builtins work. Without this option,
149 //config: "cmd &" still works by simply spawning a process and immediately
150 //config: prompting for next command (or executing next command in a script),
151 //config: but no separate process group is formed.
153 //config:config HUSH_TICK
154 //config: bool "Support process substitution"
156 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
158 //config: Enable `command` and $(command).
160 //config:config HUSH_IF
161 //config: bool "Support if/then/elif/else/fi"
163 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
165 //config:config HUSH_LOOPS
166 //config: bool "Support for, while and until loops"
168 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
170 //config:config HUSH_CASE
171 //config: bool "Support case ... esac statement"
173 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
175 //config: Enable case ... esac statement. +400 bytes.
177 //config:config HUSH_FUNCTIONS
178 //config: bool "Support funcname() { commands; } syntax"
180 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
182 //config: Enable support for shell functions. +800 bytes.
184 //config:config HUSH_LOCAL
185 //config: bool "local builtin"
187 //config: depends on HUSH_FUNCTIONS
189 //config: Enable support for local variables in functions.
191 //config:config HUSH_RANDOM_SUPPORT
192 //config: bool "Pseudorandom generator and $RANDOM variable"
194 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
196 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
197 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
199 //config:config HUSH_MODE_X
200 //config: bool "Support 'hush -x' option and 'set -x' command"
202 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
204 //config: This instructs hush to print commands before execution.
205 //config: Adds ~300 bytes.
207 //config:config HUSH_ECHO
208 //config: bool "echo builtin"
210 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
212 //config:config HUSH_PRINTF
213 //config: bool "printf builtin"
215 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
217 //config:config HUSH_TEST
218 //config: bool "test builtin"
220 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
222 //config:config HUSH_HELP
223 //config: bool "help builtin"
225 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
227 //config:config HUSH_EXPORT
228 //config: bool "export builtin"
230 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
232 //config:config HUSH_EXPORT_N
233 //config: bool "Support 'export -n' option"
235 //config: depends on HUSH_EXPORT
237 //config: export -n unexports variables. It is a bash extension.
239 //config:config HUSH_READONLY
240 //config: bool "readonly builtin"
242 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
244 //config: Enable support for read-only variables.
246 //config:config HUSH_KILL
247 //config: bool "kill builtin (supports kill %jobspec)"
249 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
251 //config:config HUSH_WAIT
252 //config: bool "wait builtin"
254 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
256 //config:config HUSH_TRAP
257 //config: bool "trap builtin"
259 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
261 //config:config HUSH_TYPE
262 //config: bool "type builtin"
264 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
266 //config:config HUSH_TIMES
267 //config: bool "times builtin"
269 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
271 //config:config HUSH_READ
272 //config: bool "read builtin"
274 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
276 //config:config HUSH_SET
277 //config: bool "set builtin"
279 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
281 //config:config HUSH_UNSET
282 //config: bool "unset builtin"
284 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
286 //config:config HUSH_ULIMIT
287 //config: bool "ulimit builtin"
289 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
291 //config:config HUSH_UMASK
292 //config: bool "umask builtin"
294 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
296 //config:config HUSH_GETOPTS
297 //config: bool "getopts builtin"
299 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
301 //config:config HUSH_MEMLEAK
302 //config: bool "memleak builtin (debugging)"
304 //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
306 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
307 // APPLET_ODDNAME:name main location suid_type help
308 //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
309 //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
311 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
312 //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
313 //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
314 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
316 /* -i (interactive) and -s (read stdin) are also accepted,
317 * but currently do nothing, therefore aren't shown in help.
318 * NOMMU-specific options are not meant to be used by users,
319 * therefore we don't show them either.
321 //usage:#define hush_trivial_usage
322 //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
323 //usage:#define hush_full_usage "\n\n"
324 //usage: "Unix shell interpreter"
326 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
327 || defined(__APPLE__) \
329 # include <malloc.h> /* for malloc_trim */
332 /* #include <dmalloc.h> */
334 # include <fnmatch.h>
336 #include <sys/times.h>
337 #include <sys/utsname.h> /* for setting $HOSTNAME */
339 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
341 #include "shell_common.h"
344 #if ENABLE_HUSH_RANDOM_SUPPORT
347 # define CLEAR_RANDOM_T(rnd) ((void)0)
349 #ifndef F_DUPFD_CLOEXEC
350 # define F_DUPFD_CLOEXEC F_DUPFD
353 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
357 /* So far, all bash compat is controlled by one config option */
358 /* Separate defines document which part of code implements what */
359 #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
360 #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
361 #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
362 #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
363 #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
364 #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
368 #define LEAK_HUNTING 0
369 #define BUILD_AS_NOMMU 0
370 /* Enable/disable sanity checks. Ok to enable in production,
371 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
372 * Keeping 1 for now even in released versions.
375 /* Slightly bigger (+200 bytes), but faster hush.
376 * So far it only enables a trick with counting SIGCHLDs and forks,
377 * which allows us to do fewer waitpid's.
378 * (we can detect a case where neither forks were done nor SIGCHLDs happened
379 * and therefore waitpid will return the same result as last time)
381 #define ENABLE_HUSH_FAST 0
382 /* TODO: implement simplified code for users which do not need ${var%...} ops
383 * So far ${var%...} ops are always enabled:
385 #define ENABLE_HUSH_DOLLAR_OPS 1
390 # undef USE_FOR_NOMMU
393 # define USE_FOR_NOMMU(...) __VA_ARGS__
394 # define USE_FOR_MMU(...)
397 #include "NUM_APPLETS.h"
399 /* STANDALONE does not make sense, and won't compile */
400 # undef CONFIG_FEATURE_SH_STANDALONE
401 # undef ENABLE_FEATURE_SH_STANDALONE
402 # undef IF_FEATURE_SH_STANDALONE
403 # undef IF_NOT_FEATURE_SH_STANDALONE
404 # define ENABLE_FEATURE_SH_STANDALONE 0
405 # define IF_FEATURE_SH_STANDALONE(...)
406 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
409 #if !ENABLE_HUSH_INTERACTIVE
410 # undef ENABLE_FEATURE_EDITING
411 # define ENABLE_FEATURE_EDITING 0
412 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
413 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
414 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
415 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
418 /* Do we support ANY keywords? */
419 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
420 # define HAS_KEYWORDS 1
421 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
422 # define IF_HAS_NO_KEYWORDS(...)
424 # define HAS_KEYWORDS 0
425 # define IF_HAS_KEYWORDS(...)
426 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
429 /* If you comment out one of these below, it will be #defined later
430 * to perform debug printfs to stderr: */
431 #define debug_printf(...) do {} while (0)
432 /* Finer-grained debug switches */
433 #define debug_printf_parse(...) do {} while (0)
434 #define debug_print_tree(a, b) do {} while (0)
435 #define debug_printf_exec(...) do {} while (0)
436 #define debug_printf_env(...) do {} while (0)
437 #define debug_printf_jobs(...) do {} while (0)
438 #define debug_printf_expand(...) do {} while (0)
439 #define debug_printf_varexp(...) do {} while (0)
440 #define debug_printf_glob(...) do {} while (0)
441 #define debug_printf_redir(...) do {} while (0)
442 #define debug_printf_list(...) do {} while (0)
443 #define debug_printf_subst(...) do {} while (0)
444 #define debug_printf_clean(...) do {} while (0)
446 #define ERR_PTR ((void*)(long)1)
448 #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
450 #define _SPECIAL_VARS_STR "_*@$!?#"
451 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
452 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
453 #if BASH_PATTERN_SUBST
454 /* Support / and // replace ops */
455 /* Note that // is stored as \ in "encoded" string representation */
456 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
457 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
458 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
460 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
461 # define VAR_SUBST_OPS "%#:-=+?"
462 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
465 #define SPECIAL_VAR_SYMBOL_STR "\3"
466 #define SPECIAL_VAR_SYMBOL 3
467 /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
468 #define SPECIAL_VAR_QUOTED_SVS 1
472 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
474 /* This supports saving pointers malloced in vfork child,
475 * to be freed in the parent.
478 typedef struct nommu_save_t {
480 struct variable *old_vars;
482 char **argv_from_re_execing;
495 #if ENABLE_HUSH_LOOPS
502 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
507 /* three pseudo-keywords support contrived "case" syntax: */
508 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
509 RES_MATCH , /* "word)" */
510 RES_CASE_BODY, /* "this command is inside CASE" */
517 typedef struct o_string {
519 int length; /* position where data is appended */
522 /* At least some part of the string was inside '' or "",
523 * possibly empty one: word"", wo''rd etc. */
524 smallint has_quoted_part;
525 smallint has_empty_slot;
526 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
529 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
531 /* Protect newly added chars against globbing
532 * by prepending \ to *, ?, [, \ */
533 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
536 MAYBE_ASSIGNMENT = 0,
537 DEFINITELY_ASSIGNMENT = 1,
539 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
542 /* Used for initialization: o_string foo = NULL_O_STRING; */
543 #define NULL_O_STRING { NULL }
545 #ifndef debug_printf_parse
546 static const char *const assignment_flag[] = {
548 "DEFINITELY_ASSIGNMENT",
554 typedef struct in_str {
556 #if ENABLE_HUSH_INTERACTIVE
557 smallint promptmode; /* 0: PS1, 1: PS2 */
564 /* The descrip member of this structure is only used to make
565 * debugging output pretty */
566 static const struct {
568 signed char default_fd;
571 { O_RDONLY, 0, "<" },
572 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
573 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
574 { O_CREAT|O_RDWR, 1, "<>" },
575 { O_RDONLY, 0, "<<" },
576 /* Should not be needed. Bogus default_fd helps in debugging */
577 /* { O_RDONLY, 77, "<<" }, */
580 struct redir_struct {
581 struct redir_struct *next;
582 char *rd_filename; /* filename */
583 int rd_fd; /* fd to redirect */
584 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
586 smallint rd_type; /* (enum redir_type) */
587 /* note: for heredocs, rd_filename contains heredoc delimiter,
588 * and subsequently heredoc itself; and rd_dup is a bitmask:
589 * bit 0: do we need to trim leading tabs?
590 * bit 1: is heredoc quoted (<<'delim' syntax) ?
593 typedef enum redir_type {
595 REDIRECT_OVERWRITE = 1,
598 REDIRECT_HEREDOC = 4,
599 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
602 REDIRFD_SYNTAX_ERR = -2,
603 REDIRFD_TO_FILE = -1,
604 /* otherwise, rd_fd is redirected to rd_dup */
606 HEREDOC_SKIPTABS = 1,
612 pid_t pid; /* 0 if exited */
613 int assignment_cnt; /* how many argv[i] are assignments? */
614 smallint cmd_type; /* CMD_xxx */
616 #define CMD_SUBSHELL 1
618 /* used for "[[ EXPR ]]" */
619 # define CMD_SINGLEWORD_NOGLOB 2
621 #if ENABLE_HUSH_FUNCTIONS
622 # define CMD_FUNCDEF 3
625 smalluint cmd_exitcode;
626 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
629 char *group_as_string;
631 #if ENABLE_HUSH_FUNCTIONS
632 struct function *child_func;
633 /* This field is used to prevent a bug here:
634 * while...do f1() {a;}; f1; f1() {b;}; f1; done
635 * When we execute "f1() {a;}" cmd, we create new function and clear
636 * cmd->group, cmd->group_as_string, cmd->argv[0].
637 * When we execute "f1() {b;}", we notice that f1 exists,
638 * and that its "parent cmd" struct is still "alive",
639 * we put those fields back into cmd->xxx
640 * (struct function has ->parent_cmd ptr to facilitate that).
641 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
642 * Without this trick, loop would execute a;b;b;b;...
643 * instead of correct sequence a;b;a;b;...
644 * When command is freed, it severs the link
645 * (sets ->child_func->parent_cmd to NULL).
648 char **argv; /* command name and arguments */
649 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
650 * and on execution these are substituted with their values.
651 * Substitution can make _several_ words out of one argv[n]!
652 * Example: argv[0]=='.^C*^C.' here: echo .$*.
653 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
655 struct redir_struct *redirects; /* I/O redirections */
657 /* Is there anything in this command at all? */
658 #define IS_NULL_CMD(cmd) \
659 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
663 int num_cmds; /* total number of commands in pipe */
664 int alive_cmds; /* number of commands running (not exited) */
665 int stopped_cmds; /* number of commands alive, but stopped */
667 unsigned jobid; /* job number */
668 pid_t pgrp; /* process group ID for the job */
669 char *cmdtext; /* name of job */
671 struct command *cmds; /* array of commands in pipe */
672 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
673 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
674 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
676 typedef enum pipe_style {
682 /* Is there anything in this pipe at all? */
683 #define IS_NULL_PIPE(pi) \
684 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
686 /* This holds pointers to the various results of parsing */
687 struct parse_context {
688 /* linked list of pipes */
689 struct pipe *list_head;
690 /* last pipe (being constructed right now) */
692 /* last command in pipe (being constructed right now) */
693 struct command *command;
694 /* last redirect in command->redirects list */
695 struct redir_struct *pending_redirect;
701 smallint ctx_inverted; /* "! cmd | cmd" */
703 smallint ctx_dsemicolon; /* ";;" seen */
705 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
707 /* group we are enclosed in:
708 * example: "if pipe1; pipe2; then pipe3; fi"
709 * when we see "if" or "then", we malloc and copy current context,
710 * and make ->stack point to it. then we parse pipeN.
711 * when closing "then" / fi" / whatever is found,
712 * we move list_head into ->stack->command->group,
713 * copy ->stack into current context, and delete ->stack.
714 * (parsing of { list } and ( list ) doesn't use this method)
716 struct parse_context *stack;
720 /* On program start, environ points to initial environment.
721 * putenv adds new pointers into it, unsetenv removes them.
722 * Neither of these (de)allocates the strings.
723 * setenv allocates new strings in malloc space and does putenv,
724 * and thus setenv is unusable (leaky) for shell's purposes */
725 #define setenv(...) setenv_is_leaky_dont_use()
727 struct variable *next;
728 char *varstr; /* points to "name=" portion */
729 #if ENABLE_HUSH_LOCAL
730 unsigned func_nest_level;
732 int max_len; /* if > 0, name is part of initial env; else name is malloced */
733 smallint flg_export; /* putenv should be done on this var */
734 smallint flg_read_only;
742 #if ENABLE_HUSH_FUNCTIONS
744 struct function *next;
746 struct command *parent_cmd;
749 char *body_as_string;
755 /* set -/+o OPT support. (TODO: make it optional)
756 * bash supports the following opts:
767 * interactive-comments on
785 static const char o_opt_strings[] ALIGN1 =
789 #if ENABLE_HUSH_MODE_X
797 #if ENABLE_HUSH_MODE_X
805 struct FILE_list *next;
811 /* "Globals" within this file */
812 /* Sorted roughly by size (smaller offsets == smaller code) */
814 /* interactive_fd != 0 means we are an interactive shell.
815 * If we are, then saved_tty_pgrp can also be != 0, meaning
816 * that controlling tty is available. With saved_tty_pgrp == 0,
817 * job control still works, but terminal signals
818 * (^C, ^Z, ^Y, ^\) won't work at all, and background
819 * process groups can only be created with "cmd &".
820 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
821 * to give tty to the foreground process group,
822 * and will take it back when the group is stopped (^Z)
825 #if ENABLE_HUSH_INTERACTIVE
826 /* 'interactive_fd' is a fd# open to ctty, if we have one
827 * _AND_ if we decided to act interactively */
831 # define G_interactive_fd (G.interactive_fd)
833 # define G_interactive_fd 0
835 #if ENABLE_FEATURE_EDITING
836 line_input_t *line_input_state;
841 #if ENABLE_HUSH_RANDOM_SUPPORT
847 pid_t saved_tty_pgrp;
848 struct pipe *job_list;
849 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
851 # define G_saved_tty_pgrp 0
853 /* How deeply are we in context where "set -e" is ignored */
855 /* "set -e" rules (do we follow them correctly?):
856 * Exit if pipe, list, or compound command exits with a non-zero status.
857 * Shell does not exit if failed command is part of condition in
858 * if/while, part of && or || list except the last command, any command
859 * in a pipe but the last, or if the command's return value is being
860 * inverted with !. If a compound command other than a subshell returns a
861 * non-zero status because a command failed while -e was being ignored, the
862 * shell does not exit. A trap on ERR, if set, is executed before the shell
863 * exits [ERR is a bashism].
865 * If a compound command or function executes in a context where -e is
866 * ignored, none of the commands executed within are affected by the -e
867 * setting. If a compound command or function sets -e while executing in a
868 * context where -e is ignored, that setting does not have any effect until
869 * the compound command or the command containing the function call completes.
872 char o_opt[NUM_OPT_O];
873 #if ENABLE_HUSH_MODE_X
874 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
878 smallint flag_SIGINT;
879 #if ENABLE_HUSH_LOOPS
880 smallint flag_break_continue;
882 #if ENABLE_HUSH_FUNCTIONS
883 /* 0: outside of a function (or sourced file)
884 * -1: inside of a function, ok to use return builtin
885 * 1: return is invoked, skip all till end of func
887 smallint flag_return_in_progress;
888 # define G_flag_return_in_progress (G.flag_return_in_progress)
890 # define G_flag_return_in_progress 0
892 smallint exiting; /* used to prevent EXIT trap recursion */
893 /* These four support $?, $#, and $1 */
894 smalluint last_exitcode;
895 smalluint last_bg_pid_exitcode;
897 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
898 smalluint global_args_malloced;
899 # define G_global_args_malloced (G.global_args_malloced)
901 # define G_global_args_malloced 0
903 /* how many non-NULL argv's we have. NB: $# + 1 */
907 char *argv0_for_re_execing;
909 #if ENABLE_HUSH_LOOPS
910 unsigned depth_break_continue;
911 unsigned depth_of_loop;
913 #if ENABLE_HUSH_GETOPTS
914 unsigned getopt_count;
918 struct variable *top_var;
919 char **expanded_assignments;
920 #if ENABLE_HUSH_FUNCTIONS
921 struct function *top_func;
922 # if ENABLE_HUSH_LOCAL
923 struct variable **shadowed_vars_pp;
924 unsigned func_nest_level;
927 /* Signal and trap handling */
929 unsigned count_SIGCHLD;
930 unsigned handled_SIGCHLD;
931 smallint we_have_children;
933 struct FILE_list *FILE_list;
934 /* Which signals have non-DFL handler (even with no traps set)?
935 * Set at the start to:
936 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
937 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
938 * The rest is cleared right before execv syscalls.
939 * Other than these two times, never modified.
941 unsigned special_sig_mask;
943 unsigned fatal_sig_mask;
944 # define G_fatal_sig_mask (G.fatal_sig_mask)
946 # define G_fatal_sig_mask 0
949 char **traps; /* char *traps[NSIG] */
950 # define G_traps G.traps
952 # define G_traps ((char**)NULL)
954 sigset_t pending_set;
955 #if ENABLE_HUSH_MEMLEAK
956 unsigned long memleak_value;
962 #if ENABLE_FEATURE_EDITING
963 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
966 #define G (*ptr_to_globals)
967 /* Not #defining name to G.name - this quickly gets unwieldy
968 * (too many defines). Also, I actually prefer to see when a variable
969 * is global, thus "G." prefix is a useful hint */
970 #define INIT_G() do { \
971 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
972 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
973 sigfillset(&G.sa.sa_mask); \
974 G.sa.sa_flags = SA_RESTART; \
978 /* Function prototypes for builtins */
979 static int builtin_cd(char **argv) FAST_FUNC;
981 static int builtin_echo(char **argv) FAST_FUNC;
983 static int builtin_eval(char **argv) FAST_FUNC;
984 static int builtin_exec(char **argv) FAST_FUNC;
985 static int builtin_exit(char **argv) FAST_FUNC;
986 #if ENABLE_HUSH_EXPORT
987 static int builtin_export(char **argv) FAST_FUNC;
989 #if ENABLE_HUSH_READONLY
990 static int builtin_readonly(char **argv) FAST_FUNC;
993 static int builtin_fg_bg(char **argv) FAST_FUNC;
994 static int builtin_jobs(char **argv) FAST_FUNC;
996 #if ENABLE_HUSH_GETOPTS
997 static int builtin_getopts(char **argv) FAST_FUNC;
1000 static int builtin_help(char **argv) FAST_FUNC;
1002 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1003 static int builtin_history(char **argv) FAST_FUNC;
1005 #if ENABLE_HUSH_LOCAL
1006 static int builtin_local(char **argv) FAST_FUNC;
1008 #if ENABLE_HUSH_MEMLEAK
1009 static int builtin_memleak(char **argv) FAST_FUNC;
1011 #if ENABLE_HUSH_PRINTF
1012 static int builtin_printf(char **argv) FAST_FUNC;
1014 static int builtin_pwd(char **argv) FAST_FUNC;
1015 #if ENABLE_HUSH_READ
1016 static int builtin_read(char **argv) FAST_FUNC;
1019 static int builtin_set(char **argv) FAST_FUNC;
1021 static int builtin_shift(char **argv) FAST_FUNC;
1022 static int builtin_source(char **argv) FAST_FUNC;
1023 #if ENABLE_HUSH_TEST || BASH_TEST2
1024 static int builtin_test(char **argv) FAST_FUNC;
1026 #if ENABLE_HUSH_TRAP
1027 static int builtin_trap(char **argv) FAST_FUNC;
1029 #if ENABLE_HUSH_TYPE
1030 static int builtin_type(char **argv) FAST_FUNC;
1032 #if ENABLE_HUSH_TIMES
1033 static int builtin_times(char **argv) FAST_FUNC;
1035 static int builtin_true(char **argv) FAST_FUNC;
1036 #if ENABLE_HUSH_UMASK
1037 static int builtin_umask(char **argv) FAST_FUNC;
1039 #if ENABLE_HUSH_UNSET
1040 static int builtin_unset(char **argv) FAST_FUNC;
1042 #if ENABLE_HUSH_KILL
1043 static int builtin_kill(char **argv) FAST_FUNC;
1045 #if ENABLE_HUSH_WAIT
1046 static int builtin_wait(char **argv) FAST_FUNC;
1048 #if ENABLE_HUSH_LOOPS
1049 static int builtin_break(char **argv) FAST_FUNC;
1050 static int builtin_continue(char **argv) FAST_FUNC;
1052 #if ENABLE_HUSH_FUNCTIONS
1053 static int builtin_return(char **argv) FAST_FUNC;
1056 /* Table of built-in functions. They can be forked or not, depending on
1057 * context: within pipes, they fork. As simple commands, they do not.
1058 * When used in non-forking context, they can change global variables
1059 * in the parent shell process. If forked, of course they cannot.
1060 * For example, 'unset foo | whatever' will parse and run, but foo will
1061 * still be set at the end. */
1062 struct built_in_command {
1064 int (*b_function)(char **argv) FAST_FUNC;
1065 #if ENABLE_HUSH_HELP
1066 const char *b_descr;
1067 # define BLTIN(cmd, func, help) { cmd, func, help }
1069 # define BLTIN(cmd, func, help) { cmd, func }
1073 static const struct built_in_command bltins1[] = {
1074 BLTIN("." , builtin_source , "Run commands in file"),
1075 BLTIN(":" , builtin_true , NULL),
1077 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
1079 #if ENABLE_HUSH_LOOPS
1080 BLTIN("break" , builtin_break , "Exit loop"),
1082 BLTIN("cd" , builtin_cd , "Change directory"),
1083 #if ENABLE_HUSH_LOOPS
1084 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
1086 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1087 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1088 BLTIN("exit" , builtin_exit , NULL),
1089 #if ENABLE_HUSH_EXPORT
1090 BLTIN("export" , builtin_export , "Set environment variables"),
1093 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
1095 #if ENABLE_HUSH_GETOPTS
1096 BLTIN("getopts" , builtin_getopts , NULL),
1098 #if ENABLE_HUSH_HELP
1099 BLTIN("help" , builtin_help , NULL),
1101 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
1102 BLTIN("history" , builtin_history , "Show history"),
1105 BLTIN("jobs" , builtin_jobs , "List jobs"),
1107 #if ENABLE_HUSH_KILL
1108 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1110 #if ENABLE_HUSH_LOCAL
1111 BLTIN("local" , builtin_local , "Set local variables"),
1113 #if ENABLE_HUSH_MEMLEAK
1114 BLTIN("memleak" , builtin_memleak , NULL),
1116 #if ENABLE_HUSH_READ
1117 BLTIN("read" , builtin_read , "Input into variable"),
1119 #if ENABLE_HUSH_READONLY
1120 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1122 #if ENABLE_HUSH_FUNCTIONS
1123 BLTIN("return" , builtin_return , "Return from function"),
1126 BLTIN("set" , builtin_set , "Set positional parameters"),
1128 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
1130 BLTIN("source" , builtin_source , NULL),
1132 #if ENABLE_HUSH_TIMES
1133 BLTIN("times" , builtin_times , NULL),
1135 #if ENABLE_HUSH_TRAP
1136 BLTIN("trap" , builtin_trap , "Trap signals"),
1138 BLTIN("true" , builtin_true , NULL),
1139 #if ENABLE_HUSH_TYPE
1140 BLTIN("type" , builtin_type , "Show command type"),
1142 #if ENABLE_HUSH_ULIMIT
1143 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
1145 #if ENABLE_HUSH_UMASK
1146 BLTIN("umask" , builtin_umask , "Set file creation mask"),
1148 #if ENABLE_HUSH_UNSET
1149 BLTIN("unset" , builtin_unset , "Unset variables"),
1151 #if ENABLE_HUSH_WAIT
1152 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
1155 /* These builtins won't be used if we are on NOMMU and need to re-exec
1156 * (it's cheaper to run an external program in this case):
1158 static const struct built_in_command bltins2[] = {
1159 #if ENABLE_HUSH_TEST
1160 BLTIN("[" , builtin_test , NULL),
1163 BLTIN("[[" , builtin_test , NULL),
1165 #if ENABLE_HUSH_ECHO
1166 BLTIN("echo" , builtin_echo , NULL),
1168 #if ENABLE_HUSH_PRINTF
1169 BLTIN("printf" , builtin_printf , NULL),
1171 BLTIN("pwd" , builtin_pwd , NULL),
1172 #if ENABLE_HUSH_TEST
1173 BLTIN("test" , builtin_test , NULL),
1181 /* prevent disasters with G.debug_indent < 0 */
1182 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
1183 # define debug_enter() (G.debug_indent++)
1184 # define debug_leave() (G.debug_indent--)
1186 # define indent() ((void)0)
1187 # define debug_enter() ((void)0)
1188 # define debug_leave() ((void)0)
1191 #ifndef debug_printf
1192 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
1195 #ifndef debug_printf_parse
1196 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1199 #ifndef debug_printf_exec
1200 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1203 #ifndef debug_printf_env
1204 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1207 #ifndef debug_printf_jobs
1208 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1209 # define DEBUG_JOBS 1
1211 # define DEBUG_JOBS 0
1214 #ifndef debug_printf_expand
1215 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1216 # define DEBUG_EXPAND 1
1218 # define DEBUG_EXPAND 0
1221 #ifndef debug_printf_varexp
1222 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1225 #ifndef debug_printf_glob
1226 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1227 # define DEBUG_GLOB 1
1229 # define DEBUG_GLOB 0
1232 #ifndef debug_printf_redir
1233 # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1236 #ifndef debug_printf_list
1237 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1240 #ifndef debug_printf_subst
1241 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1244 #ifndef debug_printf_clean
1245 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1246 # define DEBUG_CLEAN 1
1248 # define DEBUG_CLEAN 0
1252 static void debug_print_strings(const char *prefix, char **vv)
1255 fdprintf(2, "%s:\n", prefix);
1257 fdprintf(2, " '%s'\n", *vv++);
1260 # define debug_print_strings(prefix, vv) ((void)0)
1264 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1267 static void *xxmalloc(int lineno, size_t size)
1269 void *ptr = xmalloc((size + 0xff) & ~0xff);
1270 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1273 static void *xxrealloc(int lineno, void *ptr, size_t size)
1275 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1276 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1279 static char *xxstrdup(int lineno, const char *str)
1281 char *ptr = xstrdup(str);
1282 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1285 static void xxfree(void *ptr)
1287 fdprintf(2, "free %p\n", ptr);
1290 # define xmalloc(s) xxmalloc(__LINE__, s)
1291 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1292 # define xstrdup(s) xxstrdup(__LINE__, s)
1293 # define free(p) xxfree(p)
1297 /* Syntax and runtime errors. They always abort scripts.
1298 * In interactive use they usually discard unparsed and/or unexecuted commands
1299 * and return to the prompt.
1300 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1303 # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
1304 # define syntax_error(lineno, msg) syntax_error(msg)
1305 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1306 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1307 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1308 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1311 static void die_if_script(void)
1313 if (!G_interactive_fd) {
1314 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1315 xfunc_error_retval = G.last_exitcode;
1320 static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
1325 bb_error_msg("hush.c:%u", lineno);
1328 bb_verror_msg(fmt, p, NULL);
1333 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1336 bb_error_msg("syntax error: %s", msg);
1338 bb_error_msg("syntax error");
1342 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1344 bb_error_msg("syntax error at '%s'", msg);
1348 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1350 bb_error_msg("syntax error: unterminated %s", s);
1351 //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1355 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1357 char msg[2] = { ch, '\0' };
1358 syntax_error_unterm_str(lineno, msg);
1361 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1367 bb_error_msg("hush.c:%u", lineno);
1369 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1374 # undef msg_and_die_if_script
1375 # undef syntax_error
1376 # undef syntax_error_at
1377 # undef syntax_error_unterm_ch
1378 # undef syntax_error_unterm_str
1379 # undef syntax_error_unexpected_ch
1381 # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
1382 # define syntax_error(msg) syntax_error(__LINE__, msg)
1383 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1384 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1385 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1386 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1390 #if ENABLE_HUSH_INTERACTIVE
1391 static void cmdedit_update_prompt(void);
1393 # define cmdedit_update_prompt() ((void)0)
1397 /* Utility functions
1399 /* Replace each \x with x in place, return ptr past NUL. */
1400 static char *unbackslash(char *src)
1402 char *dst = src = strchrnul(src, '\\');
1406 if ((*dst++ = *src++) == '\0')
1412 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1433 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1434 v[count1 + count2] = NULL;
1437 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1441 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1443 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1444 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1447 #define add_strings_to_strings(strings, add, need_to_dup) \
1448 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1451 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1452 static char **add_string_to_strings(char **strings, char *add)
1457 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1460 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1462 char **ptr = add_string_to_strings(strings, add);
1463 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1466 #define add_string_to_strings(strings, add) \
1467 xx_add_string_to_strings(__LINE__, strings, add)
1470 static void free_strings(char **strings)
1484 static int fcntl_F_DUPFD(int fd, int avoid_fd)
1488 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
1498 static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
1502 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1508 /* fd was not open? */
1513 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1514 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1520 /* Manipulating the list of open FILEs */
1521 static FILE *remember_FILE(FILE *fp)
1524 struct FILE_list *n = xmalloc(sizeof(*n));
1525 n->next = G.FILE_list;
1529 close_on_exec_on(n->fd);
1533 static void fclose_and_forget(FILE *fp)
1535 struct FILE_list **pp = &G.FILE_list;
1537 struct FILE_list *cur = *pp;
1538 if (cur->fp == fp) {
1547 static int save_FILEs_on_redirect(int fd, int avoid_fd)
1549 struct FILE_list *fl = G.FILE_list;
1552 /* We use it only on script files, they are all CLOEXEC */
1553 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
1554 debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
1561 static void restore_redirected_FILEs(void)
1563 struct FILE_list *fl = G.FILE_list;
1565 int should_be = fileno(fl->fp);
1566 if (fl->fd != should_be) {
1567 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
1568 xmove_fd(fl->fd, should_be);
1574 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
1575 static void close_all_FILE_list(void)
1577 struct FILE_list *fl = G.FILE_list;
1579 /* fclose would also free FILE object.
1580 * It is disastrous if we share memory with a vforked parent.
1581 * I'm not sure we never come here after vfork.
1582 * Therefore just close fd, nothing more.
1584 /*fclose(fl->fp); - unsafe */
1590 static int fd_in_FILEs(int fd)
1592 struct FILE_list *fl = G.FILE_list;
1602 /* Helpers for setting new $n and restoring them back
1604 typedef struct save_arg_t {
1608 IF_HUSH_SET(smallint sv_g_malloced;)
1611 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1613 sv->sv_argv0 = argv[0];
1614 sv->sv_g_argv = G.global_argv;
1615 sv->sv_g_argc = G.global_argc;
1616 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
1618 argv[0] = G.global_argv[0]; /* retain $0 */
1619 G.global_argv = argv;
1620 IF_HUSH_SET(G.global_args_malloced = 0;)
1622 G.global_argc = 1 + string_array_len(argv + 1);
1625 static void restore_G_args(save_arg_t *sv, char **argv)
1628 if (G.global_args_malloced) {
1629 /* someone ran "set -- arg1 arg2 ...", undo */
1630 char **pp = G.global_argv;
1631 while (*++pp) /* note: does not free $0 */
1633 free(G.global_argv);
1636 argv[0] = sv->sv_argv0;
1637 G.global_argv = sv->sv_g_argv;
1638 G.global_argc = sv->sv_g_argc;
1639 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
1643 /* Basic theory of signal handling in shell
1644 * ========================================
1645 * This does not describe what hush does, rather, it is current understanding
1646 * what it _should_ do. If it doesn't, it's a bug.
1647 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1649 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1650 * is finished or backgrounded. It is the same in interactive and
1651 * non-interactive shells, and is the same regardless of whether
1652 * a user trap handler is installed or a shell special one is in effect.
1653 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1654 * backgrounds (i.e. stops) or kills all members of currently running
1657 * Wait builtin is interruptible by signals for which user trap is set
1658 * or by SIGINT in interactive shell.
1660 * Trap handlers will execute even within trap handlers. (right?)
1662 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1663 * except for handlers set to '' (empty string).
1665 * If job control is off, backgrounded commands ("cmd &")
1666 * have SIGINT, SIGQUIT set to SIG_IGN.
1668 * Commands which are run in command substitution ("`cmd`")
1669 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1671 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1672 * by the shell from its parent.
1674 * Signals which differ from SIG_DFL action
1675 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1678 * SIGTERM (interactive): ignore
1679 * SIGHUP (interactive):
1680 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1681 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1682 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1683 * that all pipe members are stopped. Try this in bash:
1684 * while :; do :; done - ^Z does not background it
1685 * (while :; do :; done) - ^Z backgrounds it
1686 * SIGINT (interactive): wait for last pipe, ignore the rest
1687 * of the command line, show prompt. NB: ^C does not send SIGINT
1688 * to interactive shell while shell is waiting for a pipe,
1689 * since shell is bg'ed (is not in foreground process group).
1690 * Example 1: this waits 5 sec, but does not execute ls:
1691 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1692 * Example 2: this does not wait and does not execute ls:
1693 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1694 * Example 3: this does not wait 5 sec, but executes ls:
1695 * "sleep 5; ls -l" + press ^C
1696 * Example 4: this does not wait and does not execute ls:
1697 * "sleep 5 & wait; ls -l" + press ^C
1699 * (What happens to signals which are IGN on shell start?)
1700 * (What happens with signal mask on shell start?)
1702 * Old implementation
1703 * ==================
1704 * We use in-kernel pending signal mask to determine which signals were sent.
1705 * We block all signals which we don't want to take action immediately,
1706 * i.e. we block all signals which need to have special handling as described
1707 * above, and all signals which have traps set.
1708 * After each pipe execution, we extract any pending signals via sigtimedwait()
1711 * unsigned special_sig_mask: a mask of such "special" signals
1712 * sigset_t blocked_set: current blocked signal set
1715 * clear bit in blocked_set unless it is also in special_sig_mask
1716 * "trap 'cmd' SIGxxx":
1717 * set bit in blocked_set (even if 'cmd' is '')
1718 * after [v]fork, if we plan to be a shell:
1719 * unblock signals with special interactive handling
1720 * (child shell is not interactive),
1721 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1722 * after [v]fork, if we plan to exec:
1723 * POSIX says fork clears pending signal mask in child - no need to clear it.
1724 * Restore blocked signal set to one inherited by shell just prior to exec.
1726 * Note: as a result, we do not use signal handlers much. The only uses
1727 * are to count SIGCHLDs
1728 * and to restore tty pgrp on signal-induced exit.
1731 * Standard says "When a subshell is entered, traps that are not being ignored
1732 * are set to the default actions". bash interprets it so that traps which
1733 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1735 * Problem: the above approach makes it unwieldy to catch signals while
1736 * we are in read builtin, or while we read commands from stdin:
1737 * masked signals are not visible!
1739 * New implementation
1740 * ==================
1741 * We record each signal we are interested in by installing signal handler
1742 * for them - a bit like emulating kernel pending signal mask in userspace.
1743 * We are interested in: signals which need to have special handling
1744 * as described above, and all signals which have traps set.
1745 * Signals are recorded in pending_set.
1746 * After each pipe execution, we extract any pending signals
1749 * unsigned special_sig_mask: a mask of shell-special signals.
1750 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1751 * char *traps[sig] if trap for sig is set (even if it's '').
1752 * sigset_t pending_set: set of sigs we received.
1755 * if sig is in special_sig_mask, set handler back to:
1756 * record_pending_signo, or to IGN if it's a tty stop signal
1757 * if sig is in fatal_sig_mask, set handler back to sigexit.
1758 * else: set handler back to SIG_DFL
1759 * "trap 'cmd' SIGxxx":
1760 * set handler to record_pending_signo.
1762 * set handler to SIG_IGN.
1763 * after [v]fork, if we plan to be a shell:
1764 * set signals with special interactive handling to SIG_DFL
1765 * (because child shell is not interactive),
1766 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1767 * after [v]fork, if we plan to exec:
1768 * POSIX says fork clears pending signal mask in child - no need to clear it.
1770 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1771 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1774 * Standard says "When a subshell is entered, traps that are not being ignored
1775 * are set to the default actions". bash interprets it so that traps which
1776 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1779 SPECIAL_INTERACTIVE_SIGS = 0
1784 SPECIAL_JOBSTOP_SIGS = 0
1793 static void record_pending_signo(int sig)
1795 sigaddset(&G.pending_set, sig);
1796 #if ENABLE_HUSH_FAST
1797 if (sig == SIGCHLD) {
1799 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1804 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1806 struct sigaction old_sa;
1808 /* We could use signal() to install handlers... almost:
1809 * except that we need to mask ALL signals while handlers run.
1810 * I saw signal nesting in strace, race window isn't small.
1811 * SA_RESTART is also needed, but in Linux, signal()
1812 * sets SA_RESTART too.
1814 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1815 /* sigfillset(&G.sa.sa_mask); - already done */
1816 /* G.sa.sa_flags = SA_RESTART; - already done */
1817 G.sa.sa_handler = handler;
1818 sigaction(sig, &G.sa, &old_sa);
1819 return old_sa.sa_handler;
1822 static void hush_exit(int exitcode) NORETURN;
1824 static void restore_ttypgrp_and__exit(void) NORETURN;
1825 static void restore_ttypgrp_and__exit(void)
1827 /* xfunc has failed! die die die */
1828 /* no EXIT traps, this is an escape hatch! */
1830 hush_exit(xfunc_error_retval);
1835 /* Needed only on some libc:
1836 * It was observed that on exit(), fgetc'ed buffered data
1837 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1838 * With the net effect that even after fork(), not vfork(),
1839 * exit() in NOEXECed applet in "sh SCRIPT":
1840 * noexec_applet_here
1841 * echo END_OF_SCRIPT
1842 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1843 * This makes "echo END_OF_SCRIPT" executed twice.
1844 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
1845 * and in `cmd` handling.
1846 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1848 static void fflush_and__exit(void) NORETURN;
1849 static void fflush_and__exit(void)
1852 _exit(xfunc_error_retval);
1855 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1856 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1857 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1858 # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
1860 /* Restores tty foreground process group, and exits.
1861 * May be called as signal handler for fatal signal
1862 * (will resend signal to itself, producing correct exit state)
1863 * or called directly with -EXITCODE.
1864 * We also call it if xfunc is exiting.
1866 static void sigexit(int sig) NORETURN;
1867 static void sigexit(int sig)
1869 /* Careful: we can end up here after [v]fork. Do not restore
1870 * tty pgrp then, only top-level shell process does that */
1871 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1872 /* Disable all signals: job control, SIGPIPE, etc.
1873 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1875 sigprocmask_allsigs(SIG_BLOCK);
1876 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1879 /* Not a signal, just exit */
1883 kill_myself_with_sig(sig); /* does not return */
1887 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1888 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1892 static sighandler_t pick_sighandler(unsigned sig)
1894 sighandler_t handler = SIG_DFL;
1895 if (sig < sizeof(unsigned)*8) {
1896 unsigned sigmask = (1 << sig);
1900 if (G_fatal_sig_mask & sigmask)
1904 /* sig has special handling? */
1905 if (G.special_sig_mask & sigmask) {
1906 handler = record_pending_signo;
1907 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1908 * in order to ignore them: they will be raised
1909 * in an endless loop when we try to do some
1910 * terminal ioctls! We do have to _ignore_ these.
1912 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1919 /* Restores tty foreground process group, and exits. */
1920 static void hush_exit(int exitcode)
1922 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1923 save_history(G.line_input_state);
1927 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
1929 /* argv[0] is unused */
1930 argv[1] = G_traps[0];
1932 G.exiting = 1; /* prevent EXIT trap recursion */
1933 /* Note: G_traps[0] is not cleared!
1934 * "trap" will still show it, if executed
1939 #if ENABLE_FEATURE_CLEAN_UP
1941 struct variable *cur_var;
1942 if (G.cwd != bb_msg_unknown)
1944 cur_var = G.top_var;
1946 struct variable *tmp = cur_var;
1947 if (!cur_var->max_len)
1948 free(cur_var->varstr);
1949 cur_var = cur_var->next;
1957 sigexit(- (exitcode & 0xff));
1964 //TODO: return a mask of ALL handled sigs?
1965 static int check_and_run_traps(void)
1972 if (sigisemptyset(&G.pending_set))
1977 if (sigismember(&G.pending_set, sig)) {
1978 sigdelset(&G.pending_set, sig);
1981 } while (sig < NSIG);
1984 if (G_traps && G_traps[sig]) {
1985 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1986 if (G_traps[sig][0]) {
1987 /* We have user-defined handler */
1988 smalluint save_rcode;
1990 /* argv[0] is unused */
1991 argv[1] = G_traps[sig];
1993 save_rcode = G.last_exitcode;
1995 //FIXME: shouldn't it be set to 128 + sig instead?
1996 G.last_exitcode = save_rcode;
1998 } /* else: "" trap, ignoring signal */
2001 /* not a trap: special action */
2004 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
2010 //TODO: why are we doing this? ash and dash don't do this,
2011 //they have no handler for SIGHUP at all,
2012 //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
2014 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
2015 /* bash is observed to signal whole process groups,
2016 * not individual processes */
2017 for (job = G.job_list; job; job = job->next) {
2020 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2021 if (kill(- job->pgrp, SIGHUP) == 0)
2022 kill(- job->pgrp, SIGCONT);
2027 #if ENABLE_HUSH_FAST
2029 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
2031 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2033 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2034 * This simplifies wait builtin a bit.
2038 default: /* ignored: */
2039 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
2040 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
2042 * We don't do 'last_sig = sig' here -> NOT returning this sig.
2043 * Example: wait is not interrupted by TERM
2044 * in interactive shell, because TERM is ignored.
2053 static const char *get_cwd(int force)
2055 if (force || G.cwd == NULL) {
2056 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2057 * we must not try to free(bb_msg_unknown) */
2058 if (G.cwd == bb_msg_unknown)
2060 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2062 G.cwd = bb_msg_unknown;
2069 * Shell and environment variable support
2071 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
2073 struct variable **pp;
2074 struct variable *cur;
2077 while ((cur = *pp) != NULL) {
2078 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2085 static const char* FAST_FUNC get_local_var_value(const char *name)
2087 struct variable **vpp;
2088 unsigned len = strlen(name);
2090 if (G.expanded_assignments) {
2091 char **cpp = G.expanded_assignments;
2094 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2095 return cp + len + 1;
2100 vpp = get_ptr_to_local_var(name, len);
2102 return (*vpp)->varstr + len + 1;
2104 if (strcmp(name, "PPID") == 0)
2105 return utoa(G.root_ppid);
2106 // bash compat: UID? EUID?
2107 #if ENABLE_HUSH_RANDOM_SUPPORT
2108 if (strcmp(name, "RANDOM") == 0)
2109 return utoa(next_random(&G.random_gen));
2114 /* str holds "NAME=VAL" and is expected to be malloced.
2115 * We take ownership of it.
2117 #define SETFLAG_EXPORT (1 << 0)
2118 #define SETFLAG_UNEXPORT (1 << 1)
2119 #define SETFLAG_MAKE_RO (1 << 2)
2120 #define SETFLAG_LOCAL_SHIFT 3
2121 static int set_local_var(char *str, unsigned flags)
2123 struct variable **var_pp;
2124 struct variable *cur;
2125 char *free_me = NULL;
2128 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
2130 eq_sign = strchr(str, '=');
2131 if (!eq_sign) { /* not expected to ever happen? */
2136 name_len = eq_sign - str + 1; /* including '=' */
2137 var_pp = &G.top_var;
2138 while ((cur = *var_pp) != NULL) {
2139 if (strncmp(cur->varstr, str, name_len) != 0) {
2140 var_pp = &cur->next;
2144 /* We found an existing var with this name */
2145 if (cur->flg_read_only) {
2146 bb_error_msg("%s: readonly variable", str);
2148 //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2149 //but export per se succeeds (does put the var in env). We don't mimic that.
2152 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
2153 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2158 #if ENABLE_HUSH_LOCAL
2159 if (cur->func_nest_level < local_lvl) {
2160 /* New variable is declared as local,
2161 * and existing one is global, or local
2162 * from enclosing function.
2163 * Remove and save old one: */
2164 *var_pp = cur->next;
2165 cur->next = *G.shadowed_vars_pp;
2166 *G.shadowed_vars_pp = cur;
2167 /* bash 3.2.33(1) and exported vars:
2169 * # f() { local z=a; env | grep ^z; }
2175 if (cur->flg_export)
2176 flags |= SETFLAG_EXPORT;
2180 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
2185 if (cur->max_len != 0) {
2186 if (cur->max_len >= strlen(str)) {
2187 /* This one is from startup env, reuse space */
2188 strcpy(cur->varstr, str);
2193 goto set_str_and_exp;
2195 /* max_len == 0 signifies "malloced" var, which we can
2196 * (and have to) free. But we can't free(cur->varstr) here:
2197 * if cur->flg_export is 1, it is in the environment.
2198 * We should either unsetenv+free, or wait until putenv,
2199 * then putenv(new)+free(old).
2201 free_me = cur->varstr;
2202 goto set_str_and_exp;
2205 /* Not found - create new variable struct */
2206 cur = xzalloc(sizeof(*cur));
2207 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
2208 cur->next = *var_pp;
2214 #if !BB_MMU || ENABLE_HUSH_READONLY
2215 if (flags & SETFLAG_MAKE_RO) {
2216 cur->flg_read_only = 1;
2219 if (flags & SETFLAG_EXPORT)
2220 cur->flg_export = 1;
2221 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2222 cmdedit_update_prompt();
2223 #if ENABLE_HUSH_GETOPTS
2224 /* defoptindvar is a "OPTIND=..." constant string */
2225 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
2228 if (cur->flg_export) {
2229 if (flags & SETFLAG_UNEXPORT) {
2230 cur->flg_export = 0;
2231 /* unsetenv was already done */
2234 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2235 i = putenv(cur->varstr);
2236 /* only now we can free old exported malloced string */
2245 /* Used at startup and after each cd */
2246 static void set_pwd_var(unsigned flag)
2248 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
2251 static int unset_local_var_len(const char *name, int name_len)
2253 struct variable *cur;
2254 struct variable **var_pp;
2257 return EXIT_SUCCESS;
2258 #if ENABLE_HUSH_GETOPTS
2259 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2262 var_pp = &G.top_var;
2263 while ((cur = *var_pp) != NULL) {
2264 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2265 if (cur->flg_read_only) {
2266 bb_error_msg("%s: readonly variable", name);
2267 return EXIT_FAILURE;
2269 *var_pp = cur->next;
2270 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2271 bb_unsetenv(cur->varstr);
2272 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2273 cmdedit_update_prompt();
2277 return EXIT_SUCCESS;
2279 var_pp = &cur->next;
2281 return EXIT_SUCCESS;
2284 #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
2285 static int unset_local_var(const char *name)
2287 return unset_local_var_len(name, strlen(name));
2291 static void unset_vars(char **strings)
2299 const char *eq = strchrnul(*v, '=');
2300 unset_local_var_len(*v, (int)(eq - *v));
2306 #if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
2307 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2309 char *var = xasprintf("%s=%s", name, val);
2310 set_local_var(var, /*flag:*/ 0);
2316 * Helpers for "var1=val1 var2=val2 cmd" feature
2318 static void add_vars(struct variable *var)
2320 struct variable *next;
2324 var->next = G.top_var;
2326 if (var->flg_export) {
2327 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2328 putenv(var->varstr);
2330 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2336 static struct variable *set_vars_and_save_old(char **strings)
2339 struct variable *old = NULL;
2345 struct variable *var_p;
2346 struct variable **var_pp;
2349 eq = strchr(*s, '=');
2351 var_pp = get_ptr_to_local_var(*s, eq - *s);
2354 if (var_p->flg_read_only) {
2356 bb_error_msg("%s: readonly variable", *s);
2358 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2359 * If VAR is readonly, leaving it in the list
2360 * after asssignment error (msg above)
2361 * causes doubled error message later, on unset.
2363 debug_printf_env("removing/freeing '%s' element\n", *s);
2366 do { *p = p[1]; p++; } while (*p);
2369 /* Remove variable from global linked list */
2370 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2371 *var_pp = var_p->next;
2372 /* Add it to returned list */
2376 set_local_var(*s, SETFLAG_EXPORT);
2388 static void reinit_unicode_for_hush(void)
2390 /* Unicode support should be activated even if LANG is set
2391 * _during_ shell execution, not only if it was set when
2392 * shell was started. Therefore, re-check LANG every time:
2394 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2395 || ENABLE_UNICODE_USING_LOCALE
2397 const char *s = get_local_var_value("LC_ALL");
2398 if (!s) s = get_local_var_value("LC_CTYPE");
2399 if (!s) s = get_local_var_value("LANG");
2405 * in_str support (strings, and "strings" read from files).
2408 #if ENABLE_HUSH_INTERACTIVE
2409 /* To test correct lineedit/interactive behavior, type from command line:
2415 * It exercises a lot of corner cases.
2417 static void cmdedit_update_prompt(void)
2419 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2420 G.PS1 = get_local_var_value("PS1");
2423 G.PS2 = get_local_var_value("PS2");
2430 static const char *setup_prompt_string(int promptmode)
2432 const char *prompt_str;
2433 debug_printf("setup_prompt_string %d ", promptmode);
2434 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2435 /* Set up the prompt */
2436 if (promptmode == 0) { /* PS1 */
2438 /* bash uses $PWD value, even if it is set by user.
2439 * It uses current dir only if PWD is unset.
2440 * We always use current dir. */
2441 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2446 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2447 debug_printf("prompt_str '%s'\n", prompt_str);
2450 static int get_user_input(struct in_str *i)
2453 const char *prompt_str;
2455 prompt_str = setup_prompt_string(i->promptmode);
2456 # if ENABLE_FEATURE_EDITING
2458 reinit_unicode_for_hush();
2459 if (G.flag_SIGINT) {
2460 /* There was ^C'ed, make it look prettier: */
2464 /* buglet: SIGINT will not make new prompt to appear _at once_,
2465 * only after <Enter>. (^C works immediately) */
2466 r = read_line_input(G.line_input_state, prompt_str,
2467 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
2469 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2472 check_and_run_traps();
2473 if (r != 0 && !G.flag_SIGINT)
2475 /* ^C or SIGINT: repeat */
2476 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2477 write(STDOUT_FILENO, "^C", 2);
2478 G.last_exitcode = 128 + SIGINT;
2481 /* EOF/error detected */
2483 i->peek_buf[0] = r = EOF;
2486 i->p = G.user_input_buf;
2487 return (unsigned char)*i->p++;
2491 if (i->last_char == '\0' || i->last_char == '\n') {
2492 /* Why check_and_run_traps here? Try this interactively:
2493 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2494 * $ <[enter], repeatedly...>
2495 * Without check_and_run_traps, handler never runs.
2497 check_and_run_traps();
2498 fputs(prompt_str, stdout);
2501 //FIXME: here ^C or SIGINT will have effect only after <Enter>
2503 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2504 * no ^C masking happens during fgetc, no special code for ^C:
2505 * it generates SIGINT as usual.
2507 check_and_run_traps();
2509 G.last_exitcode = 128 + SIGINT;
2516 /* This is the magic location that prints prompts
2517 * and gets data back from the user */
2518 static int fgetc_interactive(struct in_str *i)
2521 /* If it's interactive stdin, get new line. */
2522 if (G_interactive_fd && i->file == stdin) {
2523 /* Returns first char (or EOF), the rest is in i->p[] */
2524 ch = get_user_input(i);
2525 i->promptmode = 1; /* PS2 */
2527 /* Not stdin: script file, sourced file, etc */
2528 do ch = fgetc(i->file); while (ch == '\0');
2533 static inline int fgetc_interactive(struct in_str *i)
2536 do ch = fgetc(i->file); while (ch == '\0');
2539 #endif /* INTERACTIVE */
2541 static int i_getch(struct in_str *i)
2546 /* string-based in_str */
2547 ch = (unsigned char)*i->p;
2556 /* FILE-based in_str */
2558 #if ENABLE_FEATURE_EDITING
2559 /* This can be stdin, check line editing char[] buffer */
2560 if (i->p && *i->p != '\0') {
2561 ch = (unsigned char)*i->p++;
2565 /* peek_buf[] is an int array, not char. Can contain EOF. */
2566 ch = i->peek_buf[0];
2568 int ch2 = i->peek_buf[1];
2569 i->peek_buf[0] = ch2;
2570 if (ch2 == 0) /* very likely, avoid redundant write */
2576 ch = fgetc_interactive(i);
2578 debug_printf("file_get: got '%c' %d\n", ch, ch);
2583 static int i_peek(struct in_str *i)
2588 /* string-based in_str */
2589 /* Doesn't report EOF on NUL. None of the callers care. */
2590 return (unsigned char)*i->p;
2593 /* FILE-based in_str */
2595 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2596 /* This can be stdin, check line editing char[] buffer */
2597 if (i->p && *i->p != '\0')
2598 return (unsigned char)*i->p;
2600 /* peek_buf[] is an int array, not char. Can contain EOF. */
2601 ch = i->peek_buf[0];
2605 /* Need to get a new char */
2606 ch = fgetc_interactive(i);
2607 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2609 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2610 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2616 i->peek_buf[0] = ch;
2617 /*i->peek_buf[1] = 0; - already is */
2621 /* Only ever called if i_peek() was called, and did not return EOF.
2622 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2623 * not end-of-line. Therefore we never need to read a new editing line here.
2625 static int i_peek2(struct in_str *i)
2629 /* There are two cases when i->p[] buffer exists.
2630 * (1) it's a string in_str.
2631 * (2) It's a file, and we have a saved line editing buffer.
2632 * In both cases, we know that i->p[0] exists and not NUL, and
2633 * the peek2 result is in i->p[1].
2636 return (unsigned char)i->p[1];
2638 /* Now we know it is a file-based in_str. */
2640 /* peek_buf[] is an int array, not char. Can contain EOF. */
2641 /* Is there 2nd char? */
2642 ch = i->peek_buf[1];
2644 /* We did not read it yet, get it now */
2645 do ch = fgetc(i->file); while (ch == '\0');
2646 i->peek_buf[1] = ch;
2649 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2653 static void setup_file_in_str(struct in_str *i, FILE *f)
2655 memset(i, 0, sizeof(*i));
2656 /* i->promptmode = 0; - PS1 (memset did it) */
2661 static void setup_string_in_str(struct in_str *i, const char *s)
2663 memset(i, 0, sizeof(*i));
2664 /* i->promptmode = 0; - PS1 (memset did it) */
2665 /*i->file = NULL */;
2673 #define B_CHUNK (32 * sizeof(char*))
2675 static void o_reset_to_empty_unquoted(o_string *o)
2678 o->has_quoted_part = 0;
2683 static void o_free(o_string *o)
2686 memset(o, 0, sizeof(*o));
2689 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2694 static void o_grow_by(o_string *o, int len)
2696 if (o->length + len > o->maxlen) {
2697 o->maxlen += (2 * len) | (B_CHUNK-1);
2698 o->data = xrealloc(o->data, 1 + o->maxlen);
2702 static void o_addchr(o_string *o, int ch)
2704 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2705 if (o->length < o->maxlen) {
2706 /* likely. avoid o_grow_by() call */
2708 o->data[o->length] = ch;
2710 o->data[o->length] = '\0';
2718 /* Valid only if we know o_string is not empty */
2719 static void o_delchr(o_string *o)
2722 o->data[o->length] = '\0';
2726 static void o_addblock(o_string *o, const char *str, int len)
2729 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
2733 static void o_addstr(o_string *o, const char *str)
2735 o_addblock(o, str, strlen(str));
2739 static void nommu_addchr(o_string *o, int ch)
2745 # define nommu_addchr(o, str) ((void)0)
2748 static void o_addstr_with_NUL(o_string *o, const char *str)
2750 o_addblock(o, str, strlen(str) + 1);
2754 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2755 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2756 * Apparently, on unquoted $v bash still does globbing
2757 * ("v='*.txt'; echo $v" prints all .txt files),
2758 * but NOT brace expansion! Thus, there should be TWO independent
2759 * quoting mechanisms on $v expansion side: one protects
2760 * $v from brace expansion, and other additionally protects "$v" against globbing.
2761 * We have only second one.
2764 #if ENABLE_HUSH_BRACE_EXPANSION
2765 # define MAYBE_BRACES "{}"
2767 # define MAYBE_BRACES ""
2770 /* My analysis of quoting semantics tells me that state information
2771 * is associated with a destination, not a source.
2773 static void o_addqchr(o_string *o, int ch)
2776 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2781 o->data[o->length] = '\\';
2784 o->data[o->length] = ch;
2786 o->data[o->length] = '\0';
2789 static void o_addQchr(o_string *o, int ch)
2792 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2793 && strchr("*?[\\" MAYBE_BRACES, ch)
2796 o->data[o->length] = '\\';
2800 o->data[o->length] = ch;
2802 o->data[o->length] = '\0';
2805 static void o_addqblock(o_string *o, const char *str, int len)
2810 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2811 if (ordinary_cnt > len) /* paranoia */
2813 o_addblock(o, str, ordinary_cnt);
2814 if (ordinary_cnt == len)
2815 return; /* NUL is already added by o_addblock */
2816 str += ordinary_cnt;
2817 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2821 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2823 o->data[o->length] = '\\';
2827 o->data[o->length] = ch;
2830 o->data[o->length] = '\0';
2833 static void o_addQblock(o_string *o, const char *str, int len)
2835 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2836 o_addblock(o, str, len);
2839 o_addqblock(o, str, len);
2842 static void o_addQstr(o_string *o, const char *str)
2844 o_addQblock(o, str, strlen(str));
2847 /* A special kind of o_string for $VAR and `cmd` expansion.
2848 * It contains char* list[] at the beginning, which is grown in 16 element
2849 * increments. Actual string data starts at the next multiple of 16 * (char*).
2850 * list[i] contains an INDEX (int!) into this string data.
2851 * It means that if list[] needs to grow, data needs to be moved higher up
2852 * but list[i]'s need not be modified.
2853 * NB: remembering how many list[i]'s you have there is crucial.
2854 * o_finalize_list() operation post-processes this structure - calculates
2855 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2857 #if DEBUG_EXPAND || DEBUG_GLOB
2858 static void debug_print_list(const char *prefix, o_string *o, int n)
2860 char **list = (char**)o->data;
2861 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2865 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2866 prefix, list, n, string_start, o->length, o->maxlen,
2867 !!(o->o_expflags & EXP_FLAG_GLOB),
2869 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2872 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2873 o->data + (int)(uintptr_t)list[i] + string_start,
2874 o->data + (int)(uintptr_t)list[i] + string_start);
2878 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2880 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2884 # define debug_print_list(prefix, o, n) ((void)0)
2887 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2888 * in list[n] so that it points past last stored byte so far.
2889 * It returns n+1. */
2890 static int o_save_ptr_helper(o_string *o, int n)
2892 char **list = (char**)o->data;
2896 if (!o->has_empty_slot) {
2897 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2898 string_len = o->length - string_start;
2899 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2900 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2901 /* list[n] points to string_start, make space for 16 more pointers */
2902 o->maxlen += 0x10 * sizeof(list[0]);
2903 o->data = xrealloc(o->data, o->maxlen + 1);
2904 list = (char**)o->data;
2905 memmove(list + n + 0x10, list + n, string_len);
2906 o->length += 0x10 * sizeof(list[0]);
2908 debug_printf_list("list[%d]=%d string_start=%d\n",
2909 n, string_len, string_start);
2912 /* We have empty slot at list[n], reuse without growth */
2913 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2914 string_len = o->length - string_start;
2915 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2916 n, string_len, string_start);
2917 o->has_empty_slot = 0;
2919 o->has_quoted_part = 0;
2920 list[n] = (char*)(uintptr_t)string_len;
2924 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2925 static int o_get_last_ptr(o_string *o, int n)
2927 char **list = (char**)o->data;
2928 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2930 return ((int)(uintptr_t)list[n-1]) + string_start;
2933 #if ENABLE_HUSH_BRACE_EXPANSION
2934 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2935 * first, it processes even {a} (no commas), second,
2936 * I didn't manage to make it return strings when they don't match
2937 * existing files. Need to re-implement it.
2941 static int glob_needed(const char *s)
2950 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2956 /* Return pointer to next closing brace or to comma */
2957 static const char *next_brace_sub(const char *cp)
2961 while (*cp != '\0') {
2968 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2974 return *cp != '\0' ? cp : NULL;
2976 /* Recursive brace globber. Note: may garble pattern[]. */
2977 static int glob_brace(char *pattern, o_string *o, int n)
2979 char *new_pattern_buf;
2986 debug_printf_glob("glob_brace('%s')\n", pattern);
2992 if (*begin == '{') {
2993 /* Find the first sub-pattern and at the same time
2994 * find the rest after the closing brace */
2995 next = next_brace_sub(begin);
2997 /* An illegal expression */
3001 /* "{abc}" with no commas - illegal
3002 * brace expr, disregard and skip it */
3008 if (*begin == '\\' && begin[1] != '\0')
3012 debug_printf_glob("begin:%s\n", begin);
3013 debug_printf_glob("next:%s\n", next);
3015 /* Now find the end of the whole brace expression */
3017 while (*rest != '}') {
3018 rest = next_brace_sub(rest);
3020 /* An illegal expression */
3023 debug_printf_glob("rest:%s\n", rest);
3025 rest_len = strlen(++rest) + 1;
3027 /* We are sure the brace expression is well-formed */
3029 /* Allocate working buffer large enough for our work */
3030 new_pattern_buf = xmalloc(strlen(pattern));
3032 /* We have a brace expression. BEGIN points to the opening {,
3033 * NEXT points past the terminator of the first element, and REST
3034 * points past the final }. We will accumulate result names from
3035 * recursive runs for each brace alternative in the buffer using
3040 /* Construct the new glob expression */
3043 mempcpy(new_pattern_buf,
3044 /* We know the prefix for all sub-patterns */
3045 pattern, begin - pattern),
3049 /* Note: glob_brace() may garble new_pattern_buf[].
3050 * That's why we re-copy prefix every time (1st memcpy above).
3052 n = glob_brace(new_pattern_buf, o, n);
3054 /* We saw the last entry */
3058 next = next_brace_sub(next);
3060 free(new_pattern_buf);
3068 memset(&globdata, 0, sizeof(globdata));
3069 gr = glob(pattern, 0, NULL, &globdata);
3070 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3072 if (gr == GLOB_NOMATCH) {
3073 globfree(&globdata);
3074 /* NB: garbles parameter */
3075 unbackslash(pattern);
3076 o_addstr_with_NUL(o, pattern);
3077 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3078 return o_save_ptr_helper(o, n);
3080 if (gr == GLOB_NOSPACE)
3081 bb_error_msg_and_die(bb_msg_memory_exhausted);
3082 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3083 * but we didn't specify it. Paranoia again. */
3084 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3086 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3087 char **argv = globdata.gl_pathv;
3089 o_addstr_with_NUL(o, *argv);
3090 n = o_save_ptr_helper(o, n);
3096 globfree(&globdata);
3100 /* Performs globbing on last list[],
3101 * saving each result as a new list[].
3103 static int perform_glob(o_string *o, int n)
3105 char *pattern, *copy;
3107 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3109 return o_save_ptr_helper(o, n);
3110 pattern = o->data + o_get_last_ptr(o, n);
3111 debug_printf_glob("glob pattern '%s'\n", pattern);
3112 if (!glob_needed(pattern)) {
3113 /* unbackslash last string in o in place, fix length */
3114 o->length = unbackslash(pattern) - o->data;
3115 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3116 return o_save_ptr_helper(o, n);
3119 copy = xstrdup(pattern);
3120 /* "forget" pattern in o */
3121 o->length = pattern - o->data;
3122 n = glob_brace(copy, o, n);
3125 debug_print_list("perform_glob returning", o, n);
3129 #else /* !HUSH_BRACE_EXPANSION */
3132 static int glob_needed(const char *s)
3141 if (*s == '*' || *s == '[' || *s == '?')
3147 /* Performs globbing on last list[],
3148 * saving each result as a new list[].
3150 static int perform_glob(o_string *o, int n)
3156 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
3158 return o_save_ptr_helper(o, n);
3159 pattern = o->data + o_get_last_ptr(o, n);
3160 debug_printf_glob("glob pattern '%s'\n", pattern);
3161 if (!glob_needed(pattern)) {
3163 /* unbackslash last string in o in place, fix length */
3164 o->length = unbackslash(pattern) - o->data;
3165 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3166 return o_save_ptr_helper(o, n);
3169 memset(&globdata, 0, sizeof(globdata));
3170 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3171 * If we glob "*.\*" and don't find anything, we need
3172 * to fall back to using literal "*.*", but GLOB_NOCHECK
3173 * will return "*.\*"!
3175 gr = glob(pattern, 0, NULL, &globdata);
3176 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3178 if (gr == GLOB_NOMATCH) {
3179 globfree(&globdata);
3182 if (gr == GLOB_NOSPACE)
3183 bb_error_msg_and_die(bb_msg_memory_exhausted);
3184 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3185 * but we didn't specify it. Paranoia again. */
3186 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3188 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3189 char **argv = globdata.gl_pathv;
3190 /* "forget" pattern in o */
3191 o->length = pattern - o->data;
3193 o_addstr_with_NUL(o, *argv);
3194 n = o_save_ptr_helper(o, n);
3200 globfree(&globdata);
3202 debug_print_list("perform_glob returning", o, n);
3206 #endif /* !HUSH_BRACE_EXPANSION */
3208 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
3209 * Otherwise, just finish current list[] and start new */
3210 static int o_save_ptr(o_string *o, int n)
3212 if (o->o_expflags & EXP_FLAG_GLOB) {
3213 /* If o->has_empty_slot, list[n] was already globbed
3214 * (if it was requested back then when it was filled)
3215 * so don't do that again! */
3216 if (!o->has_empty_slot)
3217 return perform_glob(o, n); /* o_save_ptr_helper is inside */
3219 return o_save_ptr_helper(o, n);
3222 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
3223 static char **o_finalize_list(o_string *o, int n)
3228 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3230 debug_print_list("finalized", o, n);
3231 debug_printf_expand("finalized n:%d\n", n);
3232 list = (char**)o->data;
3233 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3237 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
3242 static void free_pipe_list(struct pipe *pi);
3244 /* Returns pi->next - next pipe in the list */
3245 static struct pipe *free_pipe(struct pipe *pi)
3250 debug_printf_clean("free_pipe (pid %d)\n", getpid());
3251 for (i = 0; i < pi->num_cmds; i++) {
3252 struct command *command;
3253 struct redir_struct *r, *rnext;
3255 command = &pi->cmds[i];
3256 debug_printf_clean(" command %d:\n", i);
3257 if (command->argv) {
3261 for (a = 0, p = command->argv; *p; a++, p++) {
3262 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3265 free_strings(command->argv);
3266 //command->argv = NULL;
3268 /* not "else if": on syntax error, we may have both! */
3269 if (command->group) {
3270 debug_printf_clean(" begin group (cmd_type:%d)\n",
3272 free_pipe_list(command->group);
3273 debug_printf_clean(" end group\n");
3274 //command->group = NULL;
3276 /* else is crucial here.
3277 * If group != NULL, child_func is meaningless */
3278 #if ENABLE_HUSH_FUNCTIONS
3279 else if (command->child_func) {
3280 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3281 command->child_func->parent_cmd = NULL;
3285 free(command->group_as_string);
3286 //command->group_as_string = NULL;
3288 for (r = command->redirects; r; r = rnext) {
3289 debug_printf_clean(" redirect %d%s",
3290 r->rd_fd, redir_table[r->rd_type].descrip);
3291 /* guard against the case >$FOO, where foo is unset or blank */
3292 if (r->rd_filename) {
3293 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3294 free(r->rd_filename);
3295 //r->rd_filename = NULL;
3297 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3301 //command->redirects = NULL;
3303 free(pi->cmds); /* children are an array, they get freed all at once */
3307 //pi->cmdtext = NULL;
3315 static void free_pipe_list(struct pipe *pi)
3319 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3321 debug_printf_clean("pipe followup code %d\n", pi->followup);
3327 /*** Parsing routines ***/
3329 #ifndef debug_print_tree
3330 static void debug_print_tree(struct pipe *pi, int lvl)
3332 static const char *const PIPE[] = {
3338 static const char *RES[] = {
3339 [RES_NONE ] = "NONE" ,
3342 [RES_THEN ] = "THEN" ,
3343 [RES_ELIF ] = "ELIF" ,
3344 [RES_ELSE ] = "ELSE" ,
3347 # if ENABLE_HUSH_LOOPS
3348 [RES_FOR ] = "FOR" ,
3349 [RES_WHILE] = "WHILE",
3350 [RES_UNTIL] = "UNTIL",
3352 [RES_DONE ] = "DONE" ,
3354 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3357 # if ENABLE_HUSH_CASE
3358 [RES_CASE ] = "CASE" ,
3359 [RES_CASE_IN ] = "CASE_IN" ,
3360 [RES_MATCH] = "MATCH",
3361 [RES_CASE_BODY] = "CASE_BODY",
3362 [RES_ESAC ] = "ESAC" ,
3364 [RES_XXXX ] = "XXXX" ,
3365 [RES_SNTX ] = "SNTX" ,
3367 static const char *const CMDTYPE[] = {
3371 # if ENABLE_HUSH_FUNCTIONS
3380 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3381 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3383 while (prn < pi->num_cmds) {
3384 struct command *command = &pi->cmds[prn];
3385 char **argv = command->argv;
3387 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3389 command->assignment_cnt);
3390 if (command->group) {
3391 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3392 CMDTYPE[command->cmd_type],
3395 , " group_as_string:", command->group_as_string
3400 debug_print_tree(command->group, lvl+1);
3404 if (argv) while (*argv) {
3405 fdprintf(2, " '%s'", *argv);
3415 #endif /* debug_print_tree */
3417 static struct pipe *new_pipe(void)
3420 pi = xzalloc(sizeof(struct pipe));
3421 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3425 /* Command (member of a pipe) is complete, or we start a new pipe
3426 * if ctx->command is NULL.
3427 * No errors possible here.
3429 static int done_command(struct parse_context *ctx)
3431 /* The command is really already in the pipe structure, so
3432 * advance the pipe counter and make a new, null command. */
3433 struct pipe *pi = ctx->pipe;
3434 struct command *command = ctx->command;
3436 #if 0 /* Instead we emit error message at run time */
3437 if (ctx->pending_redirect) {
3438 /* For example, "cmd >" (no filename to redirect to) */
3439 syntax_error("invalid redirect");
3440 ctx->pending_redirect = NULL;
3445 if (IS_NULL_CMD(command)) {
3446 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3450 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3451 //debug_print_tree(ctx->list_head, 20);
3453 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3456 /* Only real trickiness here is that the uncommitted
3457 * command structure is not counted in pi->num_cmds. */
3458 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3459 ctx->command = command = &pi->cmds[pi->num_cmds];
3461 memset(command, 0, sizeof(*command));
3462 return pi->num_cmds; /* used only for 0/nonzero check */
3465 static void done_pipe(struct parse_context *ctx, pipe_style type)
3469 debug_printf_parse("done_pipe entered, followup %d\n", type);
3470 /* Close previous command */
3471 not_null = done_command(ctx);
3473 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3474 ctx->ctx_inverted = 0;
3475 ctx->pipe->res_word = ctx->ctx_res_w;
3477 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3478 /* Necessary since && and || have precedence over &:
3479 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3480 * in a backgrounded subshell.
3483 struct command *command;
3485 /* Is this actually this construct, all pipes end with && or ||? */
3486 pi = ctx->list_head;
3487 while (pi != ctx->pipe) {
3488 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3493 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3494 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3495 pi = xzalloc(sizeof(*pi));
3496 pi->followup = PIPE_BG;
3498 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3499 command = &pi->cmds[0];
3500 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3501 command->cmd_type = CMD_NORMAL;
3502 command->group = ctx->list_head;
3504 command->group_as_string = xstrndup(
3505 ctx->as_string.data,
3506 ctx->as_string.length - 1 /* do not copy last char, "&" */
3509 /* Replace all pipes in ctx with one newly created */
3510 ctx->list_head = ctx->pipe = pi;
3513 ctx->pipe->followup = type;
3516 /* Without this check, even just <enter> on command line generates
3517 * tree of three NOPs (!). Which is harmless but annoying.
3518 * IOW: it is safe to do it unconditionally. */
3521 || ctx->ctx_res_w == RES_FI
3523 #if ENABLE_HUSH_LOOPS
3524 || ctx->ctx_res_w == RES_DONE
3525 || ctx->ctx_res_w == RES_FOR
3526 || ctx->ctx_res_w == RES_IN
3528 #if ENABLE_HUSH_CASE
3529 || ctx->ctx_res_w == RES_ESAC
3533 debug_printf_parse("done_pipe: adding new pipe: "
3534 "not_null:%d ctx->ctx_res_w:%d\n",
3535 not_null, ctx->ctx_res_w);
3537 ctx->pipe->next = new_p;
3539 /* RES_THEN, RES_DO etc are "sticky" -
3540 * they remain set for pipes inside if/while.
3541 * This is used to control execution.
3542 * RES_FOR and RES_IN are NOT sticky (needed to support
3543 * cases where variable or value happens to match a keyword):
3545 #if ENABLE_HUSH_LOOPS
3546 if (ctx->ctx_res_w == RES_FOR
3547 || ctx->ctx_res_w == RES_IN)
3548 ctx->ctx_res_w = RES_NONE;
3550 #if ENABLE_HUSH_CASE
3551 if (ctx->ctx_res_w == RES_MATCH)
3552 ctx->ctx_res_w = RES_CASE_BODY;
3553 if (ctx->ctx_res_w == RES_CASE)
3554 ctx->ctx_res_w = RES_CASE_IN;
3556 ctx->command = NULL; /* trick done_command below */
3557 /* Create the memory for command, roughly:
3558 * ctx->pipe->cmds = new struct command;
3559 * ctx->command = &ctx->pipe->cmds[0];
3562 //debug_print_tree(ctx->list_head, 10);
3564 debug_printf_parse("done_pipe return\n");
3567 static void initialize_context(struct parse_context *ctx)
3569 memset(ctx, 0, sizeof(*ctx));
3570 ctx->pipe = ctx->list_head = new_pipe();
3571 /* Create the memory for command, roughly:
3572 * ctx->pipe->cmds = new struct command;
3573 * ctx->command = &ctx->pipe->cmds[0];
3578 /* If a reserved word is found and processed, parse context is modified
3579 * and 1 is returned.
3582 struct reserved_combo {
3585 unsigned char assignment_flag;
3589 FLAG_END = (1 << RES_NONE ),
3591 FLAG_IF = (1 << RES_IF ),
3592 FLAG_THEN = (1 << RES_THEN ),
3593 FLAG_ELIF = (1 << RES_ELIF ),
3594 FLAG_ELSE = (1 << RES_ELSE ),
3595 FLAG_FI = (1 << RES_FI ),
3597 # if ENABLE_HUSH_LOOPS
3598 FLAG_FOR = (1 << RES_FOR ),
3599 FLAG_WHILE = (1 << RES_WHILE),
3600 FLAG_UNTIL = (1 << RES_UNTIL),
3601 FLAG_DO = (1 << RES_DO ),
3602 FLAG_DONE = (1 << RES_DONE ),
3603 FLAG_IN = (1 << RES_IN ),
3605 # if ENABLE_HUSH_CASE
3606 FLAG_MATCH = (1 << RES_MATCH),
3607 FLAG_ESAC = (1 << RES_ESAC ),
3609 FLAG_START = (1 << RES_XXXX ),
3612 static const struct reserved_combo* match_reserved_word(o_string *word)
3614 /* Mostly a list of accepted follow-up reserved words.
3615 * FLAG_END means we are done with the sequence, and are ready
3616 * to turn the compound list into a command.
3617 * FLAG_START means the word must start a new compound list.
3619 static const struct reserved_combo reserved_list[] = {
3621 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3622 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3623 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3624 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3625 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3626 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3628 # if ENABLE_HUSH_LOOPS
3629 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3630 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3631 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3632 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3633 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3634 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3636 # if ENABLE_HUSH_CASE
3637 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3638 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3641 const struct reserved_combo *r;
3643 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3644 if (strcmp(word->data, r->literal) == 0)
3649 /* Return 0: not a keyword, 1: keyword
3651 static int reserved_word(o_string *word, struct parse_context *ctx)
3653 # if ENABLE_HUSH_CASE
3654 static const struct reserved_combo reserved_match = {
3655 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3658 const struct reserved_combo *r;
3660 if (word->has_quoted_part)
3662 r = match_reserved_word(word);
3666 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3667 # if ENABLE_HUSH_CASE
3668 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3669 /* "case word IN ..." - IN part starts first MATCH part */
3670 r = &reserved_match;
3673 if (r->flag == 0) { /* '!' */
3674 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3675 syntax_error("! ! command");
3676 ctx->ctx_res_w = RES_SNTX;
3678 ctx->ctx_inverted = 1;
3681 if (r->flag & FLAG_START) {
3682 struct parse_context *old;
3684 old = xmemdup(ctx, sizeof(*ctx));
3685 debug_printf_parse("push stack %p\n", old);
3686 initialize_context(ctx);
3688 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3689 syntax_error_at(word->data);
3690 ctx->ctx_res_w = RES_SNTX;
3693 /* "{...} fi" is ok. "{...} if" is not
3695 * if { echo foo; } then { echo bar; } fi */
3696 if (ctx->command->group)
3697 done_pipe(ctx, PIPE_SEQ);
3700 ctx->ctx_res_w = r->res;
3701 ctx->old_flag = r->flag;
3702 word->o_assignment = r->assignment_flag;
3703 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3705 if (ctx->old_flag & FLAG_END) {
3706 struct parse_context *old;
3708 done_pipe(ctx, PIPE_SEQ);
3709 debug_printf_parse("pop stack %p\n", ctx->stack);
3711 old->command->group = ctx->list_head;
3712 old->command->cmd_type = CMD_NORMAL;
3714 /* At this point, the compound command's string is in
3715 * ctx->as_string... except for the leading keyword!
3716 * Consider this example: "echo a | if true; then echo a; fi"
3717 * ctx->as_string will contain "true; then echo a; fi",
3718 * with "if " remaining in old->as_string!
3722 int len = old->as_string.length;
3723 /* Concatenate halves */
3724 o_addstr(&old->as_string, ctx->as_string.data);
3725 o_free_unsafe(&ctx->as_string);
3726 /* Find where leading keyword starts in first half */
3727 str = old->as_string.data + len;
3728 if (str > old->as_string.data)
3729 str--; /* skip whitespace after keyword */
3730 while (str > old->as_string.data && isalpha(str[-1]))
3732 /* Ugh, we're done with this horrid hack */
3733 old->command->group_as_string = xstrdup(str);
3734 debug_printf_parse("pop, remembering as:'%s'\n",
3735 old->command->group_as_string);
3738 *ctx = *old; /* physical copy */
3743 #endif /* HAS_KEYWORDS */
3745 /* Word is complete, look at it and update parsing context.
3746 * Normal return is 0. Syntax errors return 1.
3747 * Note: on return, word is reset, but not o_free'd!
3749 static int done_word(o_string *word, struct parse_context *ctx)
3751 struct command *command = ctx->command;
3753 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3754 if (word->length == 0 && !word->has_quoted_part) {
3755 debug_printf_parse("done_word return 0: true null, ignored\n");
3759 if (ctx->pending_redirect) {
3760 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3761 * only if run as "bash", not "sh" */
3762 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3764 * ...the word that follows the redirection operator
3765 * shall be subjected to tilde expansion, parameter expansion,
3766 * command substitution, arithmetic expansion, and quote
3767 * removal. Pathname expansion shall not be performed
3768 * on the word by a non-interactive shell; an interactive
3769 * shell may perform it, but shall do so only when
3770 * the expansion would result in one word."
3772 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3773 /* Cater for >\file case:
3774 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3775 * Same with heredocs:
3776 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3778 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3779 unbackslash(ctx->pending_redirect->rd_filename);
3780 /* Is it <<"HEREDOC"? */
3781 if (word->has_quoted_part) {
3782 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3785 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3786 ctx->pending_redirect = NULL;
3789 # if ENABLE_HUSH_CASE
3790 if (ctx->ctx_dsemicolon
3791 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3793 /* already done when ctx_dsemicolon was set to 1: */
3794 /* ctx->ctx_res_w = RES_MATCH; */
3795 ctx->ctx_dsemicolon = 0;
3798 if (!command->argv /* if it's the first word... */
3799 # if ENABLE_HUSH_LOOPS
3800 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3801 && ctx->ctx_res_w != RES_IN
3803 # if ENABLE_HUSH_CASE
3804 && ctx->ctx_res_w != RES_CASE
3807 int reserved = reserved_word(word, ctx);
3808 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3810 o_reset_to_empty_unquoted(word);
3811 debug_printf_parse("done_word return %d\n",
3812 (ctx->ctx_res_w == RES_SNTX));
3813 return (ctx->ctx_res_w == RES_SNTX);
3816 if (strcmp(word->data, "[[") == 0) {
3817 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3823 if (command->group) {
3824 /* "{ echo foo; } echo bar" - bad */
3825 syntax_error_at(word->data);
3826 debug_printf_parse("done_word return 1: syntax error, "
3827 "groups and arglists don't mix\n");
3831 /* If this word wasn't an assignment, next ones definitely
3832 * can't be assignments. Even if they look like ones. */
3833 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3834 && word->o_assignment != WORD_IS_KEYWORD
3836 word->o_assignment = NOT_ASSIGNMENT;
3838 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3839 command->assignment_cnt++;
3840 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3842 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3843 word->o_assignment = MAYBE_ASSIGNMENT;
3845 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3846 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3847 debug_print_strings("word appended to argv", command->argv);
3850 #if ENABLE_HUSH_LOOPS
3851 if (ctx->ctx_res_w == RES_FOR) {
3852 if (word->has_quoted_part
3853 || !is_well_formed_var_name(command->argv[0], '\0')
3855 /* bash says just "not a valid identifier" */
3856 syntax_error("not a valid identifier in for");
3859 /* Force FOR to have just one word (variable name) */
3860 /* NB: basically, this makes hush see "for v in ..."
3861 * syntax as if it is "for v; in ...". FOR and IN become
3862 * two pipe structs in parse tree. */
3863 done_pipe(ctx, PIPE_SEQ);
3866 #if ENABLE_HUSH_CASE
3867 /* Force CASE to have just one word */
3868 if (ctx->ctx_res_w == RES_CASE) {
3869 done_pipe(ctx, PIPE_SEQ);
3873 o_reset_to_empty_unquoted(word);
3875 debug_printf_parse("done_word return 0\n");
3880 /* Peek ahead in the input to find out if we have a "&n" construct,
3881 * as in "2>&1", that represents duplicating a file descriptor.
3883 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3884 * REDIRFD_SYNTAX_ERR if syntax error,
3885 * REDIRFD_TO_FILE if no & was seen,
3886 * or the number found.
3889 #define parse_redir_right_fd(as_string, input) \
3890 parse_redir_right_fd(input)
3892 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3898 return REDIRFD_TO_FILE;
3900 ch = i_getch(input); /* get the & */
3901 nommu_addchr(as_string, ch);
3904 ch = i_getch(input);
3905 nommu_addchr(as_string, ch);
3906 return REDIRFD_CLOSE;
3910 while (ch != EOF && isdigit(ch)) {
3911 d = d*10 + (ch-'0');
3913 ch = i_getch(input);
3914 nommu_addchr(as_string, ch);
3919 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3921 bb_error_msg("ambiguous redirect");
3922 return REDIRFD_SYNTAX_ERR;
3925 /* Return code is 0 normal, 1 if a syntax error is detected
3927 static int parse_redirect(struct parse_context *ctx,
3930 struct in_str *input)
3932 struct command *command = ctx->command;
3933 struct redir_struct *redir;
3934 struct redir_struct **redirp;
3937 dup_num = REDIRFD_TO_FILE;
3938 if (style != REDIRECT_HEREDOC) {
3939 /* Check for a '>&1' type redirect */
3940 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3941 if (dup_num == REDIRFD_SYNTAX_ERR)
3944 int ch = i_peek(input);
3945 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3946 if (dup_num) { /* <<-... */
3947 ch = i_getch(input);
3948 nommu_addchr(&ctx->as_string, ch);
3953 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3954 int ch = i_peek(input);
3956 /* >|FILE redirect ("clobbering" >).
3957 * Since we do not support "set -o noclobber" yet,
3958 * >| and > are the same for now. Just eat |.
3960 ch = i_getch(input);
3961 nommu_addchr(&ctx->as_string, ch);
3965 /* Create a new redir_struct and append it to the linked list */
3966 redirp = &command->redirects;
3967 while ((redir = *redirp) != NULL) {
3968 redirp = &(redir->next);
3970 *redirp = redir = xzalloc(sizeof(*redir));
3971 /* redir->next = NULL; */
3972 /* redir->rd_filename = NULL; */
3973 redir->rd_type = style;
3974 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3976 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3977 redir_table[style].descrip);
3979 redir->rd_dup = dup_num;
3980 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3981 /* Erik had a check here that the file descriptor in question
3982 * is legit; I postpone that to "run time"
3983 * A "-" representation of "close me" shows up as a -3 here */
3984 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3985 redir->rd_fd, redir->rd_dup);
3987 #if 0 /* Instead we emit error message at run time */
3988 if (ctx->pending_redirect) {
3989 /* For example, "cmd > <file" */
3990 syntax_error("invalid redirect");
3993 /* Set ctx->pending_redirect, so we know what to do at the
3994 * end of the next parsed word. */
3995 ctx->pending_redirect = redir;
4000 /* If a redirect is immediately preceded by a number, that number is
4001 * supposed to tell which file descriptor to redirect. This routine
4002 * looks for such preceding numbers. In an ideal world this routine
4003 * needs to handle all the following classes of redirects...
4004 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4005 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4006 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4007 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4009 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4011 * ... If n is quoted, the number shall not be recognized as part of
4012 * the redirection expression. For example:
4014 * writes the character 2 into file a"
4015 * We are getting it right by setting ->has_quoted_part on any \<char>
4017 * A -1 return means no valid number was found,
4018 * the caller should use the appropriate default for this redirection.
4020 static int redirect_opt_num(o_string *o)
4024 if (o->data == NULL)
4026 num = bb_strtou(o->data, NULL, 10);
4027 if (errno || num < 0)
4029 o_reset_to_empty_unquoted(o);
4034 #define fetch_till_str(as_string, input, word, skip_tabs) \
4035 fetch_till_str(input, word, skip_tabs)
4037 static char *fetch_till_str(o_string *as_string,
4038 struct in_str *input,
4042 o_string heredoc = NULL_O_STRING;
4044 int prev = 0; /* not \ */
4050 ch = i_getch(input);
4052 nommu_addchr(as_string, ch);
4053 if (ch == '\n' || ch == EOF) {
4055 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4056 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4057 heredoc.data[past_EOL] = '\0';
4058 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4059 return heredoc.data;
4062 /* This is a new line.
4063 * Remember position and backslash-escaping status.
4065 o_addchr(&heredoc, ch);
4068 past_EOL = heredoc.length;
4069 /* Get 1st char of next line, possibly skipping leading tabs */
4071 ch = i_getch(input);
4073 nommu_addchr(as_string, ch);
4074 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4075 /* If this immediately ended the line,
4076 * go back to end-of-line checks.
4079 goto check_heredoc_end;
4084 o_free_unsafe(&heredoc);
4087 o_addchr(&heredoc, ch);
4088 nommu_addchr(as_string, ch);
4089 if (prev == '\\' && ch == '\\')
4090 /* Correctly handle foo\\<eol> (not a line cont.) */
4091 prev = 0; /* not \ */
4097 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4098 * and load them all. There should be exactly heredoc_cnt of them.
4100 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4102 struct pipe *pi = ctx->list_head;
4104 while (pi && heredoc_cnt) {
4106 struct command *cmd = pi->cmds;
4108 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4110 cmd->argv ? cmd->argv[0] : "NONE");
4111 for (i = 0; i < pi->num_cmds; i++) {
4112 struct redir_struct *redir = cmd->redirects;
4114 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4115 i, cmd->argv ? cmd->argv[0] : "NONE");
4117 if (redir->rd_type == REDIRECT_HEREDOC) {
4120 redir->rd_type = REDIRECT_HEREDOC2;
4121 /* redir->rd_dup is (ab)used to indicate <<- */
4122 p = fetch_till_str(&ctx->as_string, input,
4123 redir->rd_filename, redir->rd_dup);
4125 syntax_error("unexpected EOF in here document");
4128 free(redir->rd_filename);
4129 redir->rd_filename = p;
4132 redir = redir->next;
4139 /* Should be 0. If it isn't, it's a parse error */
4141 bb_error_msg_and_die("heredoc BUG 2");
4147 static int run_list(struct pipe *pi);
4149 #define parse_stream(pstring, input, end_trigger) \
4150 parse_stream(input, end_trigger)
4152 static struct pipe *parse_stream(char **pstring,
4153 struct in_str *input,
4157 #if !ENABLE_HUSH_FUNCTIONS
4158 #define parse_group(dest, ctx, input, ch) \
4159 parse_group(ctx, input, ch)
4161 static int parse_group(o_string *dest, struct parse_context *ctx,
4162 struct in_str *input, int ch)
4164 /* dest contains characters seen prior to ( or {.
4165 * Typically it's empty, but for function defs,
4166 * it contains function name (without '()'). */
4167 struct pipe *pipe_list;
4169 struct command *command = ctx->command;
4171 debug_printf_parse("parse_group entered\n");
4172 #if ENABLE_HUSH_FUNCTIONS
4173 if (ch == '(' && !dest->has_quoted_part) {
4175 if (done_word(dest, ctx))
4178 goto skip; /* (... */
4179 if (command->argv[1]) { /* word word ... (... */
4180 syntax_error_unexpected_ch('(');
4183 /* it is "word(..." or "word (..." */
4185 ch = i_getch(input);
4186 while (ch == ' ' || ch == '\t');
4188 syntax_error_unexpected_ch(ch);
4191 nommu_addchr(&ctx->as_string, ch);
4193 ch = i_getch(input);
4194 while (ch == ' ' || ch == '\t' || ch == '\n');
4196 syntax_error_unexpected_ch(ch);
4199 nommu_addchr(&ctx->as_string, ch);
4200 command->cmd_type = CMD_FUNCDEF;
4205 #if 0 /* Prevented by caller */
4206 if (command->argv /* word [word]{... */
4207 || dest->length /* word{... */
4208 || dest->has_quoted_part /* ""{... */
4211 debug_printf_parse("parse_group return 1: "
4212 "syntax error, groups and arglists don't mix\n");
4217 #if ENABLE_HUSH_FUNCTIONS
4223 command->cmd_type = CMD_SUBSHELL;
4225 /* bash does not allow "{echo...", requires whitespace */
4227 if (ch != ' ' && ch != '\t' && ch != '\n'
4228 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4230 syntax_error_unexpected_ch(ch);
4234 ch = i_getch(input);
4235 nommu_addchr(&ctx->as_string, ch);
4241 # define as_string NULL
4243 char *as_string = NULL;
4245 pipe_list = parse_stream(&as_string, input, endch);
4248 o_addstr(&ctx->as_string, as_string);
4250 /* empty ()/{} or parse error? */
4251 if (!pipe_list || pipe_list == ERR_PTR) {
4252 /* parse_stream already emitted error msg */
4255 debug_printf_parse("parse_group return 1: "
4256 "parse_stream returned %p\n", pipe_list);
4259 command->group = pipe_list;
4261 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4262 command->group_as_string = as_string;
4263 debug_printf_parse("end of group, remembering as:'%s'\n",
4264 command->group_as_string);
4268 debug_printf_parse("parse_group return 0\n");
4270 /* command remains "open", available for possible redirects */
4273 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4278 ch = i_getch(input);
4281 ch2 = i_peek(input);
4284 /* backslash+newline, skip it */
4289 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4297 ch2 = i_peek2(input);
4300 /* backslash+newline, skip it */
4306 #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
4307 /* Subroutines for copying $(...) and `...` things */
4308 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
4310 static int add_till_single_quote(o_string *dest, struct in_str *input)
4313 int ch = i_getch(input);
4315 syntax_error_unterm_ch('\'');
4323 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4324 static int add_till_double_quote(o_string *dest, struct in_str *input)
4327 int ch = i_getch(input);
4329 syntax_error_unterm_ch('"');
4334 if (ch == '\\') { /* \x. Copy both chars. */
4336 ch = i_getch(input);
4340 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4345 //if (ch == '$') ...
4348 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4350 * "Within the backquoted style of command substitution, backslash
4351 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4352 * The search for the matching backquote shall be satisfied by the first
4353 * backquote found without a preceding backslash; during this search,
4354 * if a non-escaped backquote is encountered within a shell comment,
4355 * a here-document, an embedded command substitution of the $(command)
4356 * form, or a quoted string, undefined results occur. A single-quoted
4357 * or double-quoted string that begins, but does not end, within the
4358 * "`...`" sequence produces undefined results."
4360 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4362 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4365 int ch = i_getch(input);
4369 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4370 ch = i_getch(input);
4374 && (!in_dquote || ch != '"')
4376 o_addchr(dest, '\\');
4380 syntax_error_unterm_ch('`');
4386 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4387 * quoting and nested ()s.
4388 * "With the $(command) style of command substitution, all characters
4389 * following the open parenthesis to the matching closing parenthesis
4390 * constitute the command. Any valid shell script can be used for command,
4391 * except a script consisting solely of redirections which produces
4392 * unspecified results."
4394 * echo $(echo '(TEST)' BEST) (TEST) BEST
4395 * echo $(echo 'TEST)' BEST) TEST) BEST
4396 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4398 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4399 * can contain arbitrary constructs, just like $(cmd).
4400 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4401 * for ${var:N[:M]} and ${var/P[/R]} parsing.
4403 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4404 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4407 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4408 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4409 char end_char2 = end_ch >> 8;
4411 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4414 ch = i_getch(input);
4416 syntax_error_unterm_ch(end_ch);
4420 # if BASH_SUBSTR || BASH_PATTERN_SUBST
4426 /* we look for closing )) of $((EXPR)) */
4427 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4428 i_getch(input); /* eat second ')' */
4433 if (ch == '(' || ch == '{') {
4434 ch = (ch == '(' ? ')' : '}');
4435 if (!add_till_closing_bracket(dest, input, ch))
4441 if (!add_till_single_quote(dest, input))
4447 if (!add_till_double_quote(dest, input))
4453 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4459 /* \x. Copy verbatim. Important for \(, \) */
4460 ch = i_getch(input);
4462 syntax_error_unterm_ch(')');
4467 /* "backslash+newline", ignore both */
4468 o_delchr(dest); /* undo insertion of '\' */
4478 #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
4480 /* Return code: 0 for OK, 1 for syntax error */
4482 #define parse_dollar(as_string, dest, input, quote_mask) \
4483 parse_dollar(dest, input, quote_mask)
4484 #define as_string NULL
4486 static int parse_dollar(o_string *as_string,
4488 struct in_str *input, unsigned char quote_mask)
4490 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
4492 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4494 ch = i_getch(input);
4495 nommu_addchr(as_string, ch);
4497 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4499 debug_printf_parse(": '%c'\n", ch);
4500 o_addchr(dest, ch | quote_mask);
4502 ch = i_peek_and_eat_bkslash_nl(input);
4503 if (!isalnum(ch) && ch != '_') {
4504 /* End of variable name reached */
4507 ch = i_getch(input);
4508 nommu_addchr(as_string, ch);
4510 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4511 } else if (isdigit(ch)) {
4513 ch = i_getch(input);
4514 nommu_addchr(as_string, ch);
4515 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4516 debug_printf_parse(": '%c'\n", ch);
4517 o_addchr(dest, ch | quote_mask);
4518 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4519 } else switch (ch) {
4521 case '!': /* last bg pid */
4522 case '?': /* last exit code */
4523 case '#': /* number of args */
4524 case '*': /* args */
4525 case '@': /* args */
4526 goto make_one_char_var;
4530 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4532 ch = i_getch(input); /* eat '{' */
4533 nommu_addchr(as_string, ch);
4535 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4536 /* It should be ${?}, or ${#var},
4537 * or even ${?+subst} - operator acting on a special variable,
4538 * or the beginning of variable name.
4541 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4544 syntax_error_unterm_str("${name}");
4545 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4548 nommu_addchr(as_string, ch);
4552 /* It's possible to just call add_till_closing_bracket() at this point.
4553 * However, this regresses some of our testsuite cases
4554 * which check invalid constructs like ${%}.
4555 * Oh well... let's check that the var name part is fine... */
4561 debug_printf_parse(": '%c'\n", ch);
4563 ch = i_getch(input);
4564 nommu_addchr(as_string, ch);
4568 if (!isalnum(ch) && ch != '_') {
4570 unsigned char last_ch;
4571 /* handle parameter expansions
4572 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4574 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4575 if (len_single_ch != '#'
4576 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4577 || i_peek(input) != '}'
4579 goto bad_dollar_syntax;
4581 /* else: it's "length of C" ${#C} op,
4582 * where C is a single char
4583 * special var name, e.g. ${#!}.
4586 /* Eat everything until closing '}' (or ':') */
4590 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4592 /* It's ${var:N[:M]} thing */
4593 end_ch = '}' * 0x100 + ':';
4595 if (BASH_PATTERN_SUBST
4598 /* It's ${var/[/]pattern[/repl]} thing */
4599 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4601 nommu_addchr(as_string, '/');
4604 end_ch = '}' * 0x100 + '/';
4610 #if ENABLE_HUSH_DOLLAR_OPS
4611 last_ch = add_till_closing_bracket(dest, input, end_ch);
4612 if (last_ch == 0) /* error? */
4615 #error Simple code to only allow ${var} is not implemented
4618 o_addstr(as_string, dest->data + pos);
4619 o_addchr(as_string, last_ch);
4622 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4623 && (end_ch & 0xff00)
4625 /* close the first block: */
4626 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4627 /* while parsing N from ${var:N[:M]}
4628 * or pattern from ${var/[/]pattern[/repl]} */
4629 if ((end_ch & 0xff) == last_ch) {
4630 /* got ':' or '/'- parse the rest */
4635 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
4636 /* it's ${var:N} - emulate :999999999 */
4637 o_addstr(dest, "999999999");
4638 } /* else: it's ${var/[/]pattern} */
4642 len_single_ch = 0; /* it can't be ${#C} op */
4644 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4647 #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
4651 ch = i_getch(input);
4652 nommu_addchr(as_string, ch);
4653 # if ENABLE_FEATURE_SH_MATH
4654 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4655 ch = i_getch(input);
4656 nommu_addchr(as_string, ch);
4657 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4658 o_addchr(dest, /*quote_mask |*/ '+');
4661 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4662 return 0; /* error */
4664 o_addstr(as_string, dest->data + pos);
4665 o_addchr(as_string, ')');
4666 o_addchr(as_string, ')');
4668 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4672 # if ENABLE_HUSH_TICK
4673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4674 o_addchr(dest, quote_mask | '`');
4677 if (!add_till_closing_bracket(dest, input, ')'))
4678 return 0; /* error */
4680 o_addstr(as_string, dest->data + pos);
4681 o_addchr(as_string, ')');
4683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4689 ch = i_getch(input);
4690 nommu_addchr(as_string, ch);
4691 ch = i_peek_and_eat_bkslash_nl(input);
4692 if (isalnum(ch)) { /* it's $_name or $_123 */
4697 /* TODO: $_ and $-: */
4698 /* $_ Shell or shell script name; or last argument of last command
4699 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4700 * but in command's env, set to full pathname used to invoke it */
4701 /* $- Option flags set by set builtin or shell options (-i etc) */
4703 o_addQchr(dest, '$');
4705 debug_printf_parse("parse_dollar return 1 (ok)\n");
4711 # if BASH_PATTERN_SUBST
4712 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4713 encode_string(dest, input, dquote_end, process_bkslash)
4715 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4716 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4717 encode_string(dest, input, dquote_end)
4719 #define as_string NULL
4723 # if BASH_PATTERN_SUBST
4724 /* all parameters are needed, no macro tricks */
4726 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4727 encode_string(as_string, dest, input, dquote_end)
4730 static int encode_string(o_string *as_string,
4732 struct in_str *input,
4734 int process_bkslash)
4736 #if !BASH_PATTERN_SUBST
4737 const int process_bkslash = 1;
4743 ch = i_getch(input);
4745 nommu_addchr(as_string, ch);
4746 if (ch == dquote_end) { /* may be only '"' or EOF */
4747 debug_printf_parse("encode_string return 1 (ok)\n");
4750 /* note: can't move it above ch == dquote_end check! */
4752 syntax_error_unterm_ch('"');
4753 return 0; /* error */
4757 next = i_peek(input);
4759 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4760 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4761 if (process_bkslash && ch == '\\') {
4763 syntax_error("\\<eof>");
4767 * "The backslash retains its special meaning [in "..."]
4768 * only when followed by one of the following characters:
4769 * $, `, ", \, or <newline>. A double quote may be quoted
4770 * within double quotes by preceding it with a backslash."
4771 * NB: in (unquoted) heredoc, above does not apply to ",
4772 * therefore we check for it by "next == dquote_end" cond.
4774 if (next == dquote_end || strchr("$`\\\n", next)) {
4775 ch = i_getch(input); /* eat next */
4777 goto again; /* skip \<newline> */
4778 } /* else: ch remains == '\\', and we double it below: */
4779 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4780 nommu_addchr(as_string, ch);
4784 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4785 debug_printf_parse("encode_string return 0: "
4786 "parse_dollar returned 0 (error)\n");
4791 #if ENABLE_HUSH_TICK
4793 //unsigned pos = dest->length;
4794 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4795 o_addchr(dest, 0x80 | '`');
4796 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4797 return 0; /* error */
4798 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4799 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4803 o_addQchr(dest, ch);
4809 * Scan input until EOF or end_trigger char.
4810 * Return a list of pipes to execute, or NULL on EOF
4811 * or if end_trigger character is met.
4812 * On syntax error, exit if shell is not interactive,
4813 * reset parsing machinery and start parsing anew,
4814 * or return ERR_PTR.
4816 static struct pipe *parse_stream(char **pstring,
4817 struct in_str *input,
4820 struct parse_context ctx;
4821 o_string dest = NULL_O_STRING;
4824 /* Single-quote triggers a bypass of the main loop until its mate is
4825 * found. When recursing, quote state is passed in via dest->o_expflags.
4827 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4828 end_trigger ? end_trigger : 'X');
4831 /* If very first arg is "" or '', dest.data may end up NULL.
4832 * Preventing this: */
4833 o_addchr(&dest, '\0');
4836 /* We used to separate words on $IFS here. This was wrong.
4837 * $IFS is used only for word splitting when $var is expanded,
4838 * here we should use blank chars as separators, not $IFS
4841 if (MAYBE_ASSIGNMENT != 0)
4842 dest.o_assignment = MAYBE_ASSIGNMENT;
4843 initialize_context(&ctx);
4846 const char *is_blank;
4847 const char *is_special;
4851 redir_type redir_style;
4853 ch = i_getch(input);
4854 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4855 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4860 syntax_error_unterm_str("here document");
4863 if (end_trigger == ')') {
4864 syntax_error_unterm_ch('(');
4867 if (end_trigger == '}') {
4868 syntax_error_unterm_ch('{');
4872 if (done_word(&dest, &ctx)) {
4876 done_pipe(&ctx, PIPE_SEQ);
4878 /* If we got nothing... */
4879 /* (this makes bare "&" cmd a no-op.
4880 * bash says: "syntax error near unexpected token '&'") */
4881 if (pi->num_cmds == 0
4882 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4888 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4890 *pstring = ctx.as_string.data;
4892 o_free_unsafe(&ctx.as_string);
4895 debug_printf_parse("parse_stream return %p\n", pi);
4898 nommu_addchr(&ctx.as_string, ch);
4902 next = i_peek(input);
4904 is_special = "{}<>;&|()#'" /* special outside of "str" */
4905 "\\$\"" IF_HUSH_TICK("`") /* always special */
4906 SPECIAL_VAR_SYMBOL_STR;
4907 /* Are { and } special here? */
4908 if (ctx.command->argv /* word [word]{... - non-special */
4909 || dest.length /* word{... - non-special */
4910 || dest.has_quoted_part /* ""{... - non-special */
4911 || (next != ';' /* }; - special */
4912 && next != ')' /* }) - special */
4913 && next != '(' /* {( - special */
4914 && next != '&' /* }& and }&& ... - special */
4915 && next != '|' /* }|| ... - special */
4916 && !strchr(defifs, next) /* {word - non-special */
4919 /* They are not special, skip "{}" */
4922 is_special = strchr(is_special, ch);
4923 is_blank = strchr(defifs, ch);
4925 if (!is_special && !is_blank) { /* ordinary char */
4927 o_addQchr(&dest, ch);
4928 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4929 || dest.o_assignment == WORD_IS_KEYWORD)
4931 && is_well_formed_var_name(dest.data, '=')
4933 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4934 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4940 if (done_word(&dest, &ctx)) {
4944 /* Is this a case when newline is simply ignored?
4946 * "cmd | <newline> cmd ..."
4947 * "case ... in <newline> word) ..."
4949 if (IS_NULL_CMD(ctx.command)
4950 && dest.length == 0 && !dest.has_quoted_part
4952 /* This newline can be ignored. But...
4953 * Without check #1, interactive shell
4954 * ignores even bare <newline>,
4955 * and shows the continuation prompt:
4956 * ps1_prompt$ <enter>
4957 * ps2> _ <=== wrong, should be ps1
4958 * Without check #2, "cmd & <newline>"
4959 * is similarly mistreated.
4960 * (BTW, this makes "cmd & cmd"
4961 * and "cmd && cmd" non-orthogonal.
4962 * Really, ask yourself, why
4963 * "cmd && <newline>" doesn't start
4964 * cmd but waits for more input?
4965 * The only reason is that it might be
4966 * a "cmd1 && <nl> cmd2 &" construct,
4967 * cmd1 may need to run in BG).
4969 struct pipe *pi = ctx.list_head;
4970 if (pi->num_cmds != 0 /* check #1 */
4971 && pi->followup != PIPE_BG /* check #2 */
4976 /* Treat newline as a command separator. */
4977 done_pipe(&ctx, PIPE_SEQ);
4978 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4980 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4985 dest.o_assignment = MAYBE_ASSIGNMENT;
4986 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4988 /* note: if (is_blank) continue;
4989 * will still trigger for us */
4993 /* "cmd}" or "cmd }..." without semicolon or &:
4994 * } is an ordinary char in this case, even inside { cmd; }
4995 * Pathological example: { ""}; } should exec "}" cmd
4998 if (dest.length != 0 /* word} */
4999 || dest.has_quoted_part /* ""} */
5003 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5004 /* Generally, there should be semicolon: "cmd; }"
5005 * However, bash allows to omit it if "cmd" is
5006 * a group. Examples:
5009 * { echo 0 >&2 | { echo 1; } }
5010 * { while false; do :; done }
5011 * { case a in b) ;; esac }
5013 if (ctx.command->group)
5017 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5018 /* Can't be an end of {cmd}, skip the check */
5019 goto skip_end_trigger;
5020 /* else: } does terminate a group */
5023 if (end_trigger && end_trigger == ch
5024 && (ch != ';' || heredoc_cnt == 0)
5025 #if ENABLE_HUSH_CASE
5027 || ctx.ctx_res_w != RES_MATCH
5028 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
5033 /* This is technically valid:
5034 * { cat <<HERE; }; echo Ok
5038 * but we don't support this.
5039 * We require heredoc to be in enclosing {}/(),
5042 syntax_error_unterm_str("here document");
5045 if (done_word(&dest, &ctx)) {
5048 done_pipe(&ctx, PIPE_SEQ);
5049 dest.o_assignment = MAYBE_ASSIGNMENT;
5050 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5051 /* Do we sit outside of any if's, loops or case's? */
5053 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5057 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
5059 *pstring = ctx.as_string.data;
5061 o_free_unsafe(&ctx.as_string);
5063 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5064 /* Example: bare "{ }", "()" */
5065 G.last_exitcode = 2; /* bash compat */
5066 syntax_error_unexpected_ch(ch);
5069 debug_printf_parse("parse_stream return %p: "
5070 "end_trigger char found\n",
5073 return ctx.list_head;
5080 /* Catch <, > before deciding whether this word is
5081 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5084 redir_fd = redirect_opt_num(&dest);
5085 if (done_word(&dest, &ctx)) {
5088 redir_style = REDIRECT_OVERWRITE;
5090 redir_style = REDIRECT_APPEND;
5091 ch = i_getch(input);
5092 nommu_addchr(&ctx.as_string, ch);
5095 else if (next == '(') {
5096 syntax_error(">(process) not supported");
5100 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5102 continue; /* back to top of while (1) */
5104 redir_fd = redirect_opt_num(&dest);
5105 if (done_word(&dest, &ctx)) {
5108 redir_style = REDIRECT_INPUT;
5110 redir_style = REDIRECT_HEREDOC;
5112 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5113 ch = i_getch(input);
5114 nommu_addchr(&ctx.as_string, ch);
5115 } else if (next == '>') {
5116 redir_style = REDIRECT_IO;
5117 ch = i_getch(input);
5118 nommu_addchr(&ctx.as_string, ch);
5121 else if (next == '(') {
5122 syntax_error("<(process) not supported");
5126 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5128 continue; /* back to top of while (1) */
5130 if (dest.length == 0 && !dest.has_quoted_part) {
5131 /* skip "#comment" */
5132 /* note: we do not add it to &ctx.as_string */
5134 * comment inside $() goes to the next \n, even inside quoted string (!):
5135 * cmd "$(cmd2 #comment)" - syntax error
5136 * cmd "`cmd2 #comment`" - ok
5137 * We accept both (comment ends where command subst ends, in both cases).
5142 nommu_addchr(&ctx.as_string, '\n');
5145 ch = i_getch(input);
5149 continue; /* back to top of while (1) */
5154 /* It's "\<newline>" */
5156 /* Remove trailing '\' from ctx.as_string */
5157 ctx.as_string.data[--ctx.as_string.length] = '\0';
5159 ch = i_getch(input); /* eat it */
5160 continue; /* back to top of while (1) */
5165 if (dest.o_assignment == MAYBE_ASSIGNMENT
5166 /* check that we are not in word in "a=1 2>word b=1": */
5167 && !ctx.pending_redirect
5169 /* ch is a special char and thus this word
5170 * cannot be an assignment */
5171 dest.o_assignment = NOT_ASSIGNMENT;
5172 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5175 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5178 case SPECIAL_VAR_SYMBOL:
5179 /* Convert raw ^C to corresponding special variable reference */
5180 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5181 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5184 /* non-comment #: "echo a#b" etc */
5185 o_addchr(&dest, ch);
5189 syntax_error("\\<eof>");
5192 ch = i_getch(input);
5193 /* note: ch != '\n' (that case does not reach this place) */
5194 o_addchr(&dest, '\\');
5195 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5196 o_addchr(&dest, ch);
5197 nommu_addchr(&ctx.as_string, ch);
5198 /* Example: echo Hello \2>file
5199 * we need to know that word 2 is quoted */
5200 dest.has_quoted_part = 1;
5203 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
5204 debug_printf_parse("parse_stream parse error: "
5205 "parse_dollar returned 0 (error)\n");
5210 dest.has_quoted_part = 1;
5211 if (next == '\'' && !ctx.pending_redirect) {
5212 insert_empty_quoted_str_marker:
5213 nommu_addchr(&ctx.as_string, next);
5214 i_getch(input); /* eat second ' */
5215 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5216 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5219 ch = i_getch(input);
5221 syntax_error_unterm_ch('\'');
5224 nommu_addchr(&ctx.as_string, ch);
5227 o_addqchr(&dest, ch);
5232 dest.has_quoted_part = 1;
5233 if (next == '"' && !ctx.pending_redirect)
5234 goto insert_empty_quoted_str_marker;
5235 if (dest.o_assignment == NOT_ASSIGNMENT)
5236 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
5237 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
5239 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
5241 #if ENABLE_HUSH_TICK
5243 USE_FOR_NOMMU(unsigned pos;)
5245 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5246 o_addchr(&dest, '`');
5247 USE_FOR_NOMMU(pos = dest.length;)
5248 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5251 o_addstr(&ctx.as_string, dest.data + pos);
5252 o_addchr(&ctx.as_string, '`');
5254 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5255 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5260 #if ENABLE_HUSH_CASE
5263 if (done_word(&dest, &ctx)) {
5266 done_pipe(&ctx, PIPE_SEQ);
5267 #if ENABLE_HUSH_CASE
5268 /* Eat multiple semicolons, detect
5269 * whether it means something special */
5274 ch = i_getch(input);
5275 nommu_addchr(&ctx.as_string, ch);
5276 if (ctx.ctx_res_w == RES_CASE_BODY) {
5277 ctx.ctx_dsemicolon = 1;
5278 ctx.ctx_res_w = RES_MATCH;
5284 /* We just finished a cmd. New one may start
5285 * with an assignment */
5286 dest.o_assignment = MAYBE_ASSIGNMENT;
5287 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
5290 if (done_word(&dest, &ctx)) {
5294 ch = i_getch(input);
5295 nommu_addchr(&ctx.as_string, ch);
5296 done_pipe(&ctx, PIPE_AND);
5298 done_pipe(&ctx, PIPE_BG);
5302 if (done_word(&dest, &ctx)) {
5305 #if ENABLE_HUSH_CASE
5306 if (ctx.ctx_res_w == RES_MATCH)
5307 break; /* we are in case's "word | word)" */
5309 if (next == '|') { /* || */
5310 ch = i_getch(input);
5311 nommu_addchr(&ctx.as_string, ch);
5312 done_pipe(&ctx, PIPE_OR);
5314 /* we could pick up a file descriptor choice here
5315 * with redirect_opt_num(), but bash doesn't do it.
5316 * "echo foo 2| cat" yields "foo 2". */
5321 #if ENABLE_HUSH_CASE
5322 /* "case... in [(]word)..." - skip '(' */
5323 if (ctx.ctx_res_w == RES_MATCH
5324 && ctx.command->argv == NULL /* not (word|(... */
5325 && dest.length == 0 /* not word(... */
5326 && dest.has_quoted_part == 0 /* not ""(... */
5332 if (parse_group(&dest, &ctx, input, ch) != 0) {
5337 #if ENABLE_HUSH_CASE
5338 if (ctx.ctx_res_w == RES_MATCH)
5342 /* proper use of this character is caught by end_trigger:
5343 * if we see {, we call parse_group(..., end_trigger='}')
5344 * and it will match } earlier (not here). */
5345 G.last_exitcode = 2;
5346 syntax_error_unexpected_ch(ch);
5350 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5355 G.last_exitcode = 1;
5358 struct parse_context *pctx;
5359 IF_HAS_KEYWORDS(struct parse_context *p2;)
5361 /* Clean up allocated tree.
5362 * Sample for finding leaks on syntax error recovery path.
5363 * Run it from interactive shell, watch pmap `pidof hush`.
5364 * while if false; then false; fi; do break; fi
5365 * Samples to catch leaks at execution:
5366 * while if (true | { true;}); then echo ok; fi; do break; done
5367 * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5371 /* Update pipe/command counts,
5372 * otherwise freeing may miss some */
5373 done_pipe(pctx, PIPE_SEQ);
5374 debug_printf_clean("freeing list %p from ctx %p\n",
5375 pctx->list_head, pctx);
5376 debug_print_tree(pctx->list_head, 0);
5377 free_pipe_list(pctx->list_head);
5378 debug_printf_clean("freed list %p\n", pctx->list_head);
5380 o_free_unsafe(&pctx->as_string);
5382 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5386 IF_HAS_KEYWORDS(pctx = p2;)
5387 } while (HAS_KEYWORDS && pctx);
5400 /*** Execution routines ***/
5402 /* Expansion can recurse, need forward decls: */
5403 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
5404 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5405 #define expand_string_to_string(str, do_unbackslash) \
5406 expand_string_to_string(str)
5408 static char *expand_string_to_string(const char *str, int do_unbackslash);
5409 #if ENABLE_HUSH_TICK
5410 static int process_command_subs(o_string *dest, const char *s);
5413 /* expand_strvec_to_strvec() takes a list of strings, expands
5414 * all variable references within and returns a pointer to
5415 * a list of expanded strings, possibly with larger number
5416 * of strings. (Think VAR="a b"; echo $VAR).
5417 * This new list is allocated as a single malloc block.
5418 * NULL-terminated list of char* pointers is at the beginning of it,
5419 * followed by strings themselves.
5420 * Caller can deallocate entire list by single free(list). */
5422 /* A horde of its helpers come first: */
5424 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5426 while (--len >= 0) {
5429 #if ENABLE_HUSH_BRACE_EXPANSION
5430 if (c == '{' || c == '}') {
5431 /* { -> \{, } -> \} */
5433 /* And now we want to add { or } and continue:
5436 * luckily, just falling through achieves this.
5442 /* \z -> \\\z; \<eol> -> \\<eol> */
5447 o_addchr(o, *str++);
5453 /* Store given string, finalizing the word and starting new one whenever
5454 * we encounter IFS char(s). This is used for expanding variable values.
5455 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5456 * Return in *ended_with_ifs:
5457 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5459 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5461 int last_is_ifs = 0;
5466 if (!*str) /* EOL - do not finalize word */
5468 word_len = strcspn(str, G.ifs);
5470 /* We have WORD_LEN leading non-IFS chars */
5471 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5472 o_addblock(output, str, word_len);
5474 /* Protect backslashes against globbing up :)
5475 * Example: "v='\*'; echo b$v" prints "b\*"
5476 * (and does not try to glob on "*")
5478 o_addblock_duplicate_backslash(output, str, word_len);
5479 /*/ Why can't we do it easier? */
5480 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5481 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5485 if (!*str) /* EOL - do not finalize word */
5489 /* We know str here points to at least one IFS char */
5491 str += strspn(str, G.ifs); /* skip IFS chars */
5492 if (!*str) /* EOL - do not finalize word */
5495 /* Start new word... but not always! */
5496 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5497 if (output->has_quoted_part
5498 /* Case "v=' a'; echo $v":
5499 * here nothing precedes the space in $v expansion,
5500 * therefore we should not finish the word
5501 * (IOW: if there *is* word to finalize, only then do it):
5503 || (n > 0 && output->data[output->length - 1])
5505 o_addchr(output, '\0');
5506 debug_print_list("expand_on_ifs", output, n);
5507 n = o_save_ptr(output, n);
5512 *ended_with_ifs = last_is_ifs;
5513 debug_print_list("expand_on_ifs[1]", output, n);
5517 /* Helper to expand $((...)) and heredoc body. These act as if
5518 * they are in double quotes, with the exception that they are not :).
5519 * Just the rules are similar: "expand only $var and `cmd`"
5521 * Returns malloced string.
5522 * As an optimization, we return NULL if expansion is not needed.
5524 #if !BASH_PATTERN_SUBST
5525 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5526 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5527 encode_then_expand_string(str)
5529 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5531 #if !BASH_PATTERN_SUBST
5532 enum { do_unbackslash = 1 };
5535 struct in_str input;
5536 o_string dest = NULL_O_STRING;
5538 if (!strchr(str, '$')
5539 && !strchr(str, '\\')
5540 #if ENABLE_HUSH_TICK
5541 && !strchr(str, '`')
5547 /* We need to expand. Example:
5548 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5550 setup_string_in_str(&input, str);
5551 encode_string(NULL, &dest, &input, EOF, process_bkslash);
5552 //TODO: error check (encode_string returns 0 on error)?
5553 //bb_error_msg("'%s' -> '%s'", str, dest.data);
5554 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5555 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5556 o_free_unsafe(&dest);
5560 #if ENABLE_FEATURE_SH_MATH
5561 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5563 arith_state_t math_state;
5567 math_state.lookupvar = get_local_var_value;
5568 math_state.setvar = set_local_var_from_halves;
5569 //math_state.endofname = endofname;
5570 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5571 res = arith(&math_state, exp_str ? exp_str : arg);
5574 *errmsg_p = math_state.errmsg;
5575 if (math_state.errmsg)
5576 msg_and_die_if_script(math_state.errmsg);
5581 #if BASH_PATTERN_SUBST
5582 /* ${var/[/]pattern[/repl]} helpers */
5583 static char *strstr_pattern(char *val, const char *pattern, int *size)
5586 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5587 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5594 /* Optimization: if "*pat" did not match the start of "string",
5595 * we know that "tring", "ring" etc will not match too:
5597 if (pattern[0] == '*')
5602 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5604 char *result = NULL;
5605 unsigned res_len = 0;
5606 unsigned repl_len = strlen(repl);
5610 char *s = strstr_pattern(val, pattern, &size);
5614 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5615 strcpy(mempcpy(result + res_len, val, s - val), repl);
5616 res_len += (s - val) + repl_len;
5617 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5623 if (*val && result) {
5624 result = xrealloc(result, res_len + strlen(val) + 1);
5625 strcpy(result + res_len, val);
5626 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5628 debug_printf_varexp("result:'%s'\n", result);
5631 #endif /* BASH_PATTERN_SUBST */
5634 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5636 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5638 const char *val = NULL;
5639 char *to_be_freed = NULL;
5644 char exp_save = exp_save; /* for compiler */
5645 char *exp_saveptr; /* points to expansion operator */
5646 char *exp_word = exp_word; /* for compiler */
5649 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5651 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5653 first_char = arg[0] = arg0 & 0x7f;
5656 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5657 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5658 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5659 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
5661 /* It must be length operator: ${#var} */
5665 /* Maybe handle parameter expansion */
5666 if (exp_saveptr /* if 2nd char is one of expansion operators */
5667 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5669 /* ${?:0}, ${#[:]%0} etc */
5670 exp_saveptr = var + 1;
5672 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5673 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5675 exp_op = exp_save = *exp_saveptr;
5677 exp_word = exp_saveptr + 1;
5678 if (exp_op == ':') {
5679 exp_op = *exp_word++;
5680 //TODO: try ${var:} and ${var:bogus} in non-bash config
5682 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5684 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5689 *exp_saveptr = '\0';
5690 } /* else: it's not an expansion op, but bare ${var} */
5693 /* Look up the variable in question */
5694 if (isdigit(var[0])) {
5695 /* parse_dollar should have vetted var for us */
5696 int n = xatoi_positive(var);
5697 if (n < G.global_argc)
5698 val = G.global_argv[n];
5699 /* else val remains NULL: $N with too big N */
5703 val = utoa(G.root_pid);
5705 case '!': /* bg pid */
5706 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5708 case '?': /* exitcode */
5709 val = utoa(G.last_exitcode);
5711 case '#': /* argc */
5712 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5715 val = get_local_var_value(var);
5719 /* Handle any expansions */
5720 if (exp_op == 'L') {
5721 reinit_unicode_for_hush();
5722 debug_printf_expand("expand: length(%s)=", val);
5723 val = utoa(val ? unicode_strlen(val) : 0);
5724 debug_printf_expand("%s\n", val);
5725 } else if (exp_op) {
5726 if (exp_op == '%' || exp_op == '#') {
5727 /* Standard-mandated substring removal ops:
5728 * ${parameter%word} - remove smallest suffix pattern
5729 * ${parameter%%word} - remove largest suffix pattern
5730 * ${parameter#word} - remove smallest prefix pattern
5731 * ${parameter##word} - remove largest prefix pattern
5733 * Word is expanded to produce a glob pattern.
5734 * Then var's value is matched to it and matching part removed.
5736 if (val && val[0]) {
5740 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5741 if (exp_op == *exp_word) /* ## or %% */
5743 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5745 exp_word = exp_exp_word;
5746 /* HACK ALERT. We depend here on the fact that
5747 * G.global_argv and results of utoa and get_local_var_value
5748 * are actually in writable memory:
5749 * scan_and_match momentarily stores NULs there. */
5751 loc = scan_and_match(t, exp_word, scan_flags);
5752 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5753 // exp_op, t, exp_word, loc);
5755 if (loc) { /* match was found */
5756 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5757 val = loc; /* take right part */
5759 val = to_be_freed = xstrndup(val, loc - val); /* left */
5763 #if BASH_PATTERN_SUBST
5764 else if (exp_op == '/' || exp_op == '\\') {
5765 /* It's ${var/[/]pattern[/repl]} thing.
5766 * Note that in encoded form it has TWO parts:
5767 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5768 * and if // is used, it is encoded as \:
5769 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5771 /* Empty variable always gives nothing: */
5772 // "v=''; echo ${v/*/w}" prints "", not "w"
5773 if (val && val[0]) {
5774 /* pattern uses non-standard expansion.
5775 * repl should be unbackslashed and globbed
5776 * by the usual expansion rules:
5778 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5779 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5780 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5781 * v='a bz'; echo ${v/a*z/\z} prints "z"
5782 * (note that a*z _pattern_ is never globbed!)
5784 char *pattern, *repl, *t;
5785 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5787 pattern = xstrdup(exp_word);
5788 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5789 *p++ = SPECIAL_VAR_SYMBOL;
5791 p = strchr(p, SPECIAL_VAR_SYMBOL);
5793 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5794 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5795 /* HACK ALERT. We depend here on the fact that
5796 * G.global_argv and results of utoa and get_local_var_value
5797 * are actually in writable memory:
5798 * replace_pattern momentarily stores NULs there. */
5800 to_be_freed = replace_pattern(t,
5802 (repl ? repl : exp_word),
5804 if (to_be_freed) /* at least one replace happened */
5810 #endif /* BASH_PATTERN_SUBST */
5811 else if (exp_op == ':') {
5812 #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
5813 /* It's ${var:N[:M]} bashism.
5814 * Note that in encoded form it has TWO parts:
5815 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5820 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5823 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5824 *p++ = SPECIAL_VAR_SYMBOL;
5826 p = strchr(p, SPECIAL_VAR_SYMBOL);
5828 len = expand_and_evaluate_arith(exp_word, &errmsg);
5831 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5833 /* negative beg counts from the end */
5834 beg = (arith_t)strlen(val) + beg;
5835 if (beg < 0) /* ${v: -999999} is "" */
5838 debug_printf_varexp("from val:'%s'\n", val);
5840 /* in bash, len=-n means strlen()-n */
5841 len = (arith_t)strlen(val) - beg + len;
5842 if (len < 0) /* bash compat */
5843 msg_and_die_if_script("%s: substring expression < 0", var);
5845 if (len <= 0 || !val || beg >= strlen(val)) {
5849 /* Paranoia. What if user entered 9999999999999
5850 * which fits in arith_t but not int? */
5853 val = to_be_freed = xstrndup(val + beg, len);
5855 debug_printf_varexp("val:'%s'\n", val);
5856 #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
5857 msg_and_die_if_script("malformed ${%s:...}", var);
5860 } else { /* one of "-=+?" */
5861 /* Standard-mandated substitution ops:
5862 * ${var?word} - indicate error if unset
5863 * If var is unset, word (or a message indicating it is unset
5864 * if word is null) is written to standard error
5865 * and the shell exits with a non-zero exit status.
5866 * Otherwise, the value of var is substituted.
5867 * ${var-word} - use default value
5868 * If var is unset, word is substituted.
5869 * ${var=word} - assign and use default value
5870 * If var is unset, word is assigned to var.
5871 * In all cases, final value of var is substituted.
5872 * ${var+word} - use alternative value
5873 * If var is unset, null is substituted.
5874 * Otherwise, word is substituted.
5876 * Word is subjected to tilde expansion, parameter expansion,
5877 * command substitution, and arithmetic expansion.
5878 * If word is not needed, it is not expanded.
5880 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5881 * but also treat null var as if it is unset.
5883 int use_word = (!val || ((exp_save == ':') && !val[0]));
5885 use_word = !use_word;
5886 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5887 (exp_save == ':') ? "true" : "false", use_word);
5889 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5891 exp_word = to_be_freed;
5892 if (exp_op == '?') {
5893 /* mimic bash message */
5894 msg_and_die_if_script("%s: %s",
5898 : "parameter null or not set"
5899 /* ash has more specific messages, a-la: */
5900 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
5902 //TODO: how interactive bash aborts expansion mid-command?
5907 if (exp_op == '=') {
5908 /* ${var=[word]} or ${var:=[word]} */
5909 if (isdigit(var[0]) || var[0] == '#') {
5910 /* mimic bash message */
5911 msg_and_die_if_script("$%s: cannot assign in this way", var);
5914 char *new_var = xasprintf("%s=%s", var, val);
5915 set_local_var(new_var, /*flag:*/ 0);
5919 } /* one of "-=+?" */
5921 *exp_saveptr = exp_save;
5927 *to_be_freed_pp = to_be_freed;
5931 /* Expand all variable references in given string, adding words to list[]
5932 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5933 * to be filled). This routine is extremely tricky: has to deal with
5934 * variables/parameters with whitespace, $* and $@, and constructs like
5935 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5936 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5938 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5939 * expansion of right-hand side of assignment == 1-element expand.
5941 char cant_be_null = 0; /* only bit 0x80 matters */
5942 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5945 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5946 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5947 debug_print_list("expand_vars_to_list", output, n);
5948 n = o_save_ptr(output, n);
5949 debug_print_list("expand_vars_to_list[0]", output, n);
5951 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5953 char *to_be_freed = NULL;
5954 const char *val = NULL;
5955 #if ENABLE_HUSH_TICK
5956 o_string subst_result = NULL_O_STRING;
5958 #if ENABLE_FEATURE_SH_MATH
5959 char arith_buf[sizeof(arith_t)*3 + 2];
5963 o_addchr(output, '\0');
5964 n = o_save_ptr(output, n);
5968 o_addblock(output, arg, p - arg);
5969 debug_print_list("expand_vars_to_list[1]", output, n);
5971 p = strchr(p, SPECIAL_VAR_SYMBOL);
5973 /* Fetch special var name (if it is indeed one of them)
5974 * and quote bit, force the bit on if singleword expansion -
5975 * important for not getting v=$@ expand to many words. */
5976 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5978 /* Is this variable quoted and thus expansion can't be null?
5979 * "$@" is special. Even if quoted, it can still
5980 * expand to nothing (not even an empty string),
5981 * thus it is excluded. */
5982 if ((first_ch & 0x7f) != '@')
5983 cant_be_null |= first_ch;
5985 switch (first_ch & 0x7f) {
5986 /* Highest bit in first_ch indicates that var is double-quoted */
5990 if (!G.global_argv[1])
5993 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5994 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5995 while (G.global_argv[i]) {
5996 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5997 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5998 if (G.global_argv[i++][0] && G.global_argv[i]) {
5999 /* this argv[] is not empty and not last:
6000 * put terminating NUL, start new word */
6001 o_addchr(output, '\0');
6002 debug_print_list("expand_vars_to_list[2]", output, n);
6003 n = o_save_ptr(output, n);
6004 debug_print_list("expand_vars_to_list[3]", output, n);
6008 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
6009 * and in this case should treat it like '$*' - see 'else...' below */
6010 if (first_ch == ('@'|0x80) /* quoted $@ */
6011 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
6014 o_addQstr(output, G.global_argv[i]);
6015 if (++i >= G.global_argc)
6017 o_addchr(output, '\0');
6018 debug_print_list("expand_vars_to_list[4]", output, n);
6019 n = o_save_ptr(output, n);
6021 } else { /* quoted $* (or v="$@" case): add as one word */
6023 o_addQstr(output, G.global_argv[i]);
6024 if (!G.global_argv[++i])
6027 o_addchr(output, G.ifs[0]);
6029 output->has_quoted_part = 1;
6033 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6034 /* "Empty variable", used to make "" etc to not disappear */
6035 output->has_quoted_part = 1;
6037 cant_be_null = 0x80;
6039 case SPECIAL_VAR_QUOTED_SVS:
6040 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6042 val = SPECIAL_VAR_SYMBOL_STR;
6044 #if ENABLE_HUSH_TICK
6045 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
6046 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6048 /* Can't just stuff it into output o_string,
6049 * expanded result may need to be globbed
6051 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6052 G.last_exitcode = process_command_subs(&subst_result, arg);
6053 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6054 val = subst_result.data;
6057 #if ENABLE_FEATURE_SH_MATH
6058 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6061 arg++; /* skip '+' */
6062 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6063 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
6064 res = expand_and_evaluate_arith(arg, NULL);
6065 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6066 sprintf(arith_buf, ARITH_FMT, res);
6072 val = expand_one_var(&to_be_freed, arg, &p);
6073 IF_HUSH_TICK(store_val:)
6074 if (!(first_ch & 0x80)) { /* unquoted $VAR */
6075 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6076 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6077 if (val && val[0]) {
6078 n = expand_on_ifs(&ended_in_ifs, output, n, val);
6081 } else { /* quoted $VAR, val will be appended below */
6082 output->has_quoted_part = 1;
6083 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6084 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
6087 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6089 if (val && val[0]) {
6090 o_addQstr(output, val);
6094 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6095 * Do the check to avoid writing to a const string. */
6096 if (*p != SPECIAL_VAR_SYMBOL)
6097 *p = SPECIAL_VAR_SYMBOL;
6099 #if ENABLE_HUSH_TICK
6100 o_free(&subst_result);
6103 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6107 o_addchr(output, '\0');
6108 n = o_save_ptr(output, n);
6110 debug_print_list("expand_vars_to_list[a]", output, n);
6111 /* this part is literal, and it was already pre-quoted
6112 * if needed (much earlier), do not use o_addQstr here! */
6113 o_addstr_with_NUL(output, arg);
6114 debug_print_list("expand_vars_to_list[b]", output, n);
6115 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
6116 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
6119 /* allow to reuse list[n] later without re-growth */
6120 output->has_empty_slot = 1;
6122 o_addchr(output, '\0');
6128 static char **expand_variables(char **argv, unsigned expflags)
6132 o_string output = NULL_O_STRING;
6134 output.o_expflags = expflags;
6138 n = expand_vars_to_list(&output, n, *argv);
6141 debug_print_list("expand_variables", &output, n);
6143 /* output.data (malloced in one block) gets returned in "list" */
6144 list = o_finalize_list(&output, n);
6145 debug_print_strings("expand_variables[1]", list);
6149 static char **expand_strvec_to_strvec(char **argv)
6151 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
6155 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6157 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
6161 /* Used for expansion of right hand of assignments,
6162 * $((...)), heredocs, variable espansion parts.
6164 * NB: should NOT do globbing!
6165 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6167 static char *expand_string_to_string(const char *str, int do_unbackslash)
6169 #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
6170 const int do_unbackslash = 1;
6172 char *argv[2], **list;
6174 debug_printf_expand("string_to_string<='%s'\n", str);
6175 /* This is generally an optimization, but it also
6176 * handles "", which otherwise trips over !list[0] check below.
6177 * (is this ever happens that we actually get str="" here?)
6179 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6180 //TODO: Can use on strings with \ too, just unbackslash() them?
6181 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
6182 return xstrdup(str);
6185 argv[0] = (char*)str;
6187 list = expand_variables(argv, do_unbackslash
6188 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6189 : EXP_FLAG_SINGLEWORD
6192 if (!list[0] || list[1])
6193 bb_error_msg_and_die("BUG in varexp2");
6194 /* actually, just move string 2*sizeof(char*) bytes back */
6195 overlapping_strcpy((char*)list, list[0]);
6197 unbackslash((char*)list);
6198 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
6202 #if ENABLE_HUSH_CASE
6203 static char* expand_strvec_to_string(char **argv)
6207 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
6208 /* Convert all NULs to spaces */
6213 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6214 bb_error_msg_and_die("BUG in varexp3");
6215 /* bash uses ' ' regardless of $IFS contents */
6220 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
6221 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6226 static char **expand_assignments(char **argv, int count)
6231 G.expanded_assignments = p = NULL;
6232 /* Expand assignments into one string each */
6233 for (i = 0; i < count; i++) {
6234 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
6236 G.expanded_assignments = NULL;
6241 static void switch_off_special_sigs(unsigned mask)
6244 while ((mask >>= 1) != 0) {
6248 #if ENABLE_HUSH_TRAP
6250 if (G_traps[sig] && !G_traps[sig][0])
6251 /* trap is '', has to remain SIG_IGN */
6254 G_traps[sig] = NULL;
6257 /* We are here only if no trap or trap was not '' */
6258 install_sighandler(sig, SIG_DFL);
6264 void re_execute_shell(char ***to_free, const char *s,
6265 char *g_argv0, char **g_argv,
6266 char **builtin_argv) NORETURN;
6268 static void reset_traps_to_defaults(void)
6270 /* This function is always called in a child shell
6271 * after fork (not vfork, NOMMU doesn't use this function).
6273 IF_HUSH_TRAP(unsigned sig;)
6276 /* Child shells are not interactive.
6277 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6278 * Testcase: (while :; do :; done) + ^Z should background.
6279 * Same goes for SIGTERM, SIGHUP, SIGINT.
6281 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
6282 if (!G_traps && !mask)
6283 return; /* already no traps and no special sigs */
6285 /* Switch off special sigs */
6286 switch_off_special_sigs(mask);
6287 # if ENABLE_HUSH_JOB
6288 G_fatal_sig_mask = 0;
6290 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
6291 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6292 * remain set in G.special_sig_mask */
6294 # if ENABLE_HUSH_TRAP
6298 /* Reset all sigs to default except ones with empty traps */
6299 for (sig = 0; sig < NSIG; sig++) {
6301 continue; /* no trap: nothing to do */
6302 if (!G_traps[sig][0])
6303 continue; /* empty trap: has to remain SIG_IGN */
6304 /* sig has non-empty trap, reset it: */
6306 G_traps[sig] = NULL;
6307 /* There is no signal for trap 0 (EXIT) */
6310 install_sighandler(sig, pick_sighandler(sig));
6317 static void re_execute_shell(char ***to_free, const char *s,
6318 char *g_argv0, char **g_argv,
6319 char **builtin_argv) NORETURN;
6320 static void re_execute_shell(char ***to_free, const char *s,
6321 char *g_argv0, char **g_argv,
6322 char **builtin_argv)
6324 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6325 /* delims + 2 * (number of bytes in printed hex numbers) */
6326 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6327 char *heredoc_argv[4];
6328 struct variable *cur;
6329 # if ENABLE_HUSH_FUNCTIONS
6330 struct function *funcp;
6334 unsigned long long empty_trap_mask;
6336 if (!g_argv0) { /* heredoc */
6337 argv = heredoc_argv;
6338 argv[0] = (char *) G.argv0_for_re_execing;
6339 argv[1] = (char *) "-<";
6340 argv[2] = (char *) s;
6342 pp = &argv[3]; /* used as pointer to empty environment */
6348 if (pp) while (*pp++)
6351 empty_trap_mask = 0;
6354 for (sig = 1; sig < NSIG; sig++) {
6355 if (G_traps[sig] && !G_traps[sig][0])
6356 empty_trap_mask |= 1LL << sig;
6360 sprintf(param_buf, NOMMU_HACK_FMT
6361 , (unsigned) G.root_pid
6362 , (unsigned) G.root_ppid
6363 , (unsigned) G.last_bg_pid
6364 , (unsigned) G.last_exitcode
6367 IF_HUSH_LOOPS(, G.depth_of_loop)
6369 # undef NOMMU_HACK_FMT
6370 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6371 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6374 for (cur = G.top_var; cur; cur = cur->next) {
6375 if (!cur->flg_export || cur->flg_read_only)
6378 # if ENABLE_HUSH_FUNCTIONS
6379 for (funcp = G.top_func; funcp; funcp = funcp->next)
6385 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6386 *pp++ = (char *) G.argv0_for_re_execing;
6388 for (cur = G.top_var; cur; cur = cur->next) {
6389 if (strcmp(cur->varstr, hush_version_str) == 0)
6391 if (cur->flg_read_only) {
6392 *pp++ = (char *) "-R";
6393 *pp++ = cur->varstr;
6394 } else if (!cur->flg_export) {
6395 *pp++ = (char *) "-V";
6396 *pp++ = cur->varstr;
6399 # if ENABLE_HUSH_FUNCTIONS
6400 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6401 *pp++ = (char *) "-F";
6402 *pp++ = funcp->name;
6403 *pp++ = funcp->body_as_string;
6406 /* We can pass activated traps here. Say, -Tnn:trap_string
6408 * However, POSIX says that subshells reset signals with traps
6410 * I tested bash-3.2 and it not only does that with true subshells
6411 * of the form ( list ), but with any forked children shells.
6412 * I set trap "echo W" WINCH; and then tried:
6414 * { echo 1; sleep 20; echo 2; } &
6415 * while true; do echo 1; sleep 20; echo 2; break; done &
6416 * true | { echo 1; sleep 20; echo 2; } | cat
6418 * In all these cases sending SIGWINCH to the child shell
6419 * did not run the trap. If I add trap "echo V" WINCH;
6420 * _inside_ group (just before echo 1), it works.
6422 * I conclude it means we don't need to pass active traps here.
6424 *pp++ = (char *) "-c";
6427 while (*++builtin_argv)
6428 *pp++ = *builtin_argv;
6429 *pp++ = (char *) "";
6434 /* *pp = NULL; - is already there */
6438 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6439 /* Don't propagate SIG_IGN to the child */
6440 if (SPECIAL_JOBSTOP_SIGS != 0)
6441 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6442 execve(bb_busybox_exec_path, argv, pp);
6443 /* Fallback. Useful for init=/bin/hush usage etc */
6444 if (argv[0][0] == '/')
6445 execve(argv[0], argv, pp);
6446 xfunc_error_retval = 127;
6447 bb_error_msg_and_die("can't re-execute the shell");
6449 #endif /* !BB_MMU */
6452 static int run_and_free_list(struct pipe *pi);
6454 /* Executing from string: eval, sh -c '...'
6455 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6456 * end_trigger controls how often we stop parsing
6457 * NUL: parse all, execute, return
6458 * ';': parse till ';' or newline, execute, repeat till EOF
6460 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6462 /* Why we need empty flag?
6463 * An obscure corner case "false; ``; echo $?":
6464 * empty command in `` should still set $? to 0.
6465 * But we can't just set $? to 0 at the start,
6466 * this breaks "false; echo `echo $?`" case.
6470 struct pipe *pipe_list;
6472 #if ENABLE_HUSH_INTERACTIVE
6473 if (end_trigger == ';')
6474 inp->promptmode = 0; /* PS1 */
6476 pipe_list = parse_stream(NULL, inp, end_trigger);
6477 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6478 /* If we are in "big" script
6479 * (not in `cmd` or something similar)...
6481 if (pipe_list == ERR_PTR && end_trigger == ';') {
6482 /* Discard cached input (rest of line) */
6483 int ch = inp->last_char;
6484 while (ch != EOF && ch != '\n') {
6485 //bb_error_msg("Discarded:'%c'", ch);
6490 /* This stream isn't empty */
6494 if (!pipe_list && empty)
6495 G.last_exitcode = 0;
6498 debug_print_tree(pipe_list, 0);
6499 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6500 run_and_free_list(pipe_list);
6502 if (G_flag_return_in_progress == 1)
6507 static void parse_and_run_string(const char *s)
6509 struct in_str input;
6510 setup_string_in_str(&input, s);
6511 parse_and_run_stream(&input, '\0');
6514 static void parse_and_run_file(FILE *f)
6516 struct in_str input;
6517 setup_file_in_str(&input, f);
6518 parse_and_run_stream(&input, ';');
6521 #if ENABLE_HUSH_TICK
6522 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6527 char **to_free = NULL;
6531 pid = BB_MMU ? xfork() : xvfork();
6532 if (pid == 0) { /* child */
6533 disable_restore_tty_pgrp_on_exit();
6534 /* Process substitution is not considered to be usual
6535 * 'command execution'.
6536 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6543 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6544 close(channel[0]); /* NB: close _first_, then move fd! */
6545 xmove_fd(channel[1], 1);
6546 /* Prevent it from trying to handle ctrl-z etc */
6547 IF_HUSH_JOB(G.run_list_level = 1;)
6548 # if ENABLE_HUSH_TRAP
6549 /* Awful hack for `trap` or $(trap).
6551 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6552 * contains an example where "trap" is executed in a subshell:
6554 * save_traps=$(trap)
6556 * eval "$save_traps"
6558 * Standard does not say that "trap" in subshell shall print
6559 * parent shell's traps. It only says that its output
6560 * must have suitable form, but then, in the above example
6561 * (which is not supposed to be normative), it implies that.
6563 * bash (and probably other shell) does implement it
6564 * (traps are reset to defaults, but "trap" still shows them),
6565 * but as a result, "trap" logic is hopelessly messed up:
6568 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6569 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6570 * # true | trap <--- trap is in subshell - no output (ditto)
6571 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6572 * trap -- 'echo Ho' SIGWINCH
6573 * # echo `(trap)` <--- in subshell in subshell - output
6574 * trap -- 'echo Ho' SIGWINCH
6575 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6576 * trap -- 'echo Ho' SIGWINCH
6578 * The rules when to forget and when to not forget traps
6579 * get really complex and nonsensical.
6581 * Our solution: ONLY bare $(trap) or `trap` is special.
6583 s = skip_whitespace(s);
6584 if (is_prefixed_with(s, "trap")
6585 && skip_whitespace(s + 4)[0] == '\0'
6587 static const char *const argv[] = { NULL, NULL };
6588 builtin_trap((char**)argv);
6589 fflush_all(); /* important */
6594 reset_traps_to_defaults();
6595 parse_and_run_string(s);
6596 _exit(G.last_exitcode);
6598 /* We re-execute after vfork on NOMMU. This makes this script safe:
6599 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6600 * huge=`cat BIG` # was blocking here forever
6603 re_execute_shell(&to_free,
6613 # if ENABLE_HUSH_FAST
6615 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6616 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6617 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6619 enable_restore_tty_pgrp_on_exit();
6624 return remember_FILE(xfdopen_for_read(channel[0]));
6627 /* Return code is exit status of the process that is run. */
6628 static int process_command_subs(o_string *dest, const char *s)
6631 struct in_str pipe_str;
6633 int status, ch, eol_cnt;
6635 fp = generate_stream_from_string(s, &pid);
6637 /* Now send results of command back into original context */
6638 setup_file_in_str(&pipe_str, fp);
6640 while ((ch = i_getch(&pipe_str)) != EOF) {
6646 o_addchr(dest, '\n');
6649 o_addQchr(dest, ch);
6652 debug_printf("done reading from `cmd` pipe, closing it\n");
6653 fclose_and_forget(fp);
6654 /* We need to extract exitcode. Test case
6655 * "true; echo `sleep 1; false` $?"
6657 safe_waitpid(pid, &status, 0);
6658 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6659 return WEXITSTATUS(status);
6661 #endif /* ENABLE_HUSH_TICK */
6664 static void setup_heredoc(struct redir_struct *redir)
6666 struct fd_pair pair;
6669 /* the _body_ of heredoc (misleading field name) */
6670 const char *heredoc = redir->rd_filename;
6677 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6678 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6682 len = strlen(heredoc);
6684 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6686 xmove_fd(pair.rd, redir->rd_fd);
6688 /* Try writing without forking. Newer kernels have
6689 * dynamically growing pipes. Must use non-blocking write! */
6692 written = write(pair.wr, heredoc, len);
6703 ndelay_off(pair.wr);
6705 /* Okay, pipe buffer was not big enough */
6706 /* Note: we must not create a stray child (bastard? :)
6707 * for the unsuspecting parent process. Child creates a grandchild
6708 * and exits before parent execs the process which consumes heredoc
6709 * (that exec happens after we return from this function) */
6716 disable_restore_tty_pgrp_on_exit();
6717 pid = BB_MMU ? xfork() : xvfork();
6721 close(redir->rd_fd); /* read side of the pipe */
6723 full_write(pair.wr, heredoc, len); /* may loop or block */
6726 /* Delegate blocking writes to another process */
6727 xmove_fd(pair.wr, STDOUT_FILENO);
6728 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6732 #if ENABLE_HUSH_FAST
6734 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6736 enable_restore_tty_pgrp_on_exit();
6742 wait(NULL); /* wait till child has died */
6748 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6749 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6752 static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6754 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6755 sq[i].orig_fd = orig;
6756 sq[i].moved_to = moved;
6757 sq[i+1].orig_fd = -1; /* end marker */
6761 static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6767 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6768 /* If we collide with an already moved fd... */
6769 if (fd == sq[i].moved_to) {
6770 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6771 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6772 if (sq[i].moved_to < 0) /* what? */
6776 if (fd == sq[i].orig_fd) {
6777 /* Example: echo Hello >/dev/null 1>&2 */
6778 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6783 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
6784 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6785 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6786 if (moved_to < 0 && errno != EBADF)
6788 return append_squirrel(sq, i, fd, moved_to);
6791 static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6796 if (sq) for (; sq[i].orig_fd >= 0; i++) {
6797 /* If we collide with an already moved fd... */
6798 if (fd == sq[i].orig_fd) {
6800 * "echo 3>FILE 3>&- 3>FILE"
6801 * "echo 3>&- 3>FILE"
6802 * No need for last redirect to insert
6803 * another "need to close 3" indicator.
6805 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6810 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6811 return append_squirrel(sq, i, fd, -1);
6814 /* fd: redirect wants this fd to be used (e.g. 3>file).
6815 * Move all conflicting internally used fds,
6816 * and remember them so that we can restore them later.
6818 static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
6820 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6823 #if ENABLE_HUSH_INTERACTIVE
6824 if (fd == G.interactive_fd) {
6825 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
6826 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
6827 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6828 return 1; /* "we closed fd" */
6831 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6832 * (1) Redirect in a forked child. No need to save FILEs' fds,
6833 * we aren't going to use them anymore, ok to trash.
6834 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6835 * but how are we doing to restore them?
6836 * "fileno(fd) = new_fd" can't be done.
6841 /* If this one of script's fds? */
6842 if (save_FILEs_on_redirect(fd, avoid_fd))
6843 return 1; /* yes. "we closed fd" */
6845 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6846 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6847 return 0; /* "we did not close fd" */
6850 static void restore_redirects(struct squirrel *sq)
6854 for (i = 0; sq[i].orig_fd >= 0; i++) {
6855 if (sq[i].moved_to >= 0) {
6856 /* We simply die on error */
6857 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6858 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6860 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6861 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6862 close(sq[i].orig_fd);
6868 /* If moved, G.interactive_fd stays on new fd, not restoring it */
6870 restore_redirected_FILEs();
6873 #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
6874 static void close_saved_fds_and_FILE_fds(void)
6876 if (G_interactive_fd)
6877 close(G_interactive_fd);
6878 close_all_FILE_list();
6882 static int internally_opened_fd(int fd, struct squirrel *sq)
6886 #if ENABLE_HUSH_INTERACTIVE
6887 if (fd == G.interactive_fd)
6890 /* If this one of script's fds? */
6891 if (fd_in_FILEs(fd))
6894 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
6895 if (fd == sq[i].moved_to)
6901 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6902 * and stderr if they are redirected. */
6903 static int setup_redirects(struct command *prog, struct squirrel **sqp)
6905 struct redir_struct *redir;
6907 for (redir = prog->redirects; redir; redir = redir->next) {
6911 if (redir->rd_type == REDIRECT_HEREDOC2) {
6912 /* "rd_fd<<HERE" case */
6913 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
6914 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6916 debug_printf_parse("set heredoc '%s'\n",
6917 redir->rd_filename);
6918 setup_heredoc(redir);
6922 if (redir->rd_dup == REDIRFD_TO_FILE) {
6923 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6927 if (redir->rd_filename == NULL) {
6930 * "cmd >" (no filename)
6931 * "cmd > <file" (2nd redirect starts too early)
6933 syntax_error("invalid redirect");
6936 mode = redir_table[redir->rd_type].mode;
6937 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6938 newfd = open_or_warn(p, mode);
6941 /* Error message from open_or_warn can be lost
6942 * if stderr has been redirected, but bash
6943 * and ash both lose it as well
6944 * (though zsh doesn't!)
6948 if (newfd == redir->rd_fd && sqp) {
6949 /* open() gave us precisely the fd we wanted.
6950 * This means that this fd was not busy
6951 * (not opened to anywhere).
6952 * Remember to close it on restore:
6954 *sqp = add_squirrel_closed(*sqp, newfd);
6955 debug_printf_redir("redir to previously closed fd %d\n", newfd);
6958 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
6959 newfd = redir->rd_dup;
6962 if (newfd == redir->rd_fd)
6965 /* if "N>FILE": move newfd to redir->rd_fd */
6966 /* if "N>&M": dup newfd to redir->rd_fd */
6967 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
6969 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
6970 if (newfd == REDIRFD_CLOSE) {
6971 /* "N>&-" means "close me" */
6973 /* ^^^ optimization: saving may already
6974 * have closed it. If not... */
6975 close(redir->rd_fd);
6977 /* Sometimes we do another close on restore, getting EBADF.
6978 * Consider "echo 3>FILE 3>&-"
6979 * first redirect remembers "need to close 3",
6980 * and second redirect closes 3! Restore code then closes 3 again.
6983 /* if newfd is a script fd or saved fd, simulate EBADF */
6984 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
6986 //bb_perror_msg_and_die("can't duplicate file descriptor");
6987 newfd = -1; /* same effect as code above */
6989 xdup2(newfd, redir->rd_fd);
6990 if (redir->rd_dup == REDIRFD_TO_FILE)
6991 /* "rd_fd > FILE" */
6993 /* else: "rd_fd > rd_dup" */
6999 static char *find_in_path(const char *arg)
7002 const char *PATH = get_local_var_value("PATH");
7008 const char *end = strchrnul(PATH, ':');
7009 int sz = end - PATH; /* must be int! */
7013 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7015 /* We have xxx::yyyy in $PATH,
7016 * it means "use current dir" */
7019 if (access(ret, F_OK) == 0)
7032 static const struct built_in_command *find_builtin_helper(const char *name,
7033 const struct built_in_command *x,
7034 const struct built_in_command *end)
7037 if (strcmp(name, x->b_cmd) != 0) {
7041 debug_printf_exec("found builtin '%s'\n", name);
7046 static const struct built_in_command *find_builtin1(const char *name)
7048 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7050 static const struct built_in_command *find_builtin(const char *name)
7052 const struct built_in_command *x = find_builtin1(name);
7055 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7058 #if ENABLE_HUSH_FUNCTIONS
7059 static struct function **find_function_slot(const char *name)
7061 struct function **funcpp = &G.top_func;
7063 if (strcmp(name, (*funcpp)->name) == 0) {
7066 funcpp = &(*funcpp)->next;
7071 static const struct function *find_function(const char *name)
7073 const struct function *funcp = *find_function_slot(name);
7075 debug_printf_exec("found function '%s'\n", name);
7079 /* Note: takes ownership on name ptr */
7080 static struct function *new_function(char *name)
7082 struct function **funcpp = find_function_slot(name);
7083 struct function *funcp = *funcpp;
7085 if (funcp != NULL) {
7086 struct command *cmd = funcp->parent_cmd;
7087 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7089 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7091 /* Note: if !funcp->body, do not free body_as_string!
7092 * This is a special case of "-F name body" function:
7093 * body_as_string was not malloced! */
7095 free_pipe_list(funcp->body);
7097 free(funcp->body_as_string);
7101 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7102 cmd->argv[0] = funcp->name;
7103 cmd->group = funcp->body;
7105 cmd->group_as_string = funcp->body_as_string;
7109 debug_printf_exec("remembering new function '%s'\n", name);
7110 funcp = *funcpp = xzalloc(sizeof(*funcp));
7111 /*funcp->next = NULL;*/
7118 # if ENABLE_HUSH_UNSET
7119 static void unset_func(const char *name)
7121 struct function **funcpp = find_function_slot(name);
7122 struct function *funcp = *funcpp;
7124 if (funcp != NULL) {
7125 debug_printf_exec("freeing function '%s'\n", funcp->name);
7126 *funcpp = funcp->next;
7127 /* funcp is unlinked now, deleting it.
7128 * Note: if !funcp->body, the function was created by
7129 * "-F name body", do not free ->body_as_string
7130 * and ->name as they were not malloced. */
7132 free_pipe_list(funcp->body);
7135 free(funcp->body_as_string);
7144 #define exec_function(to_free, funcp, argv) \
7145 exec_function(funcp, argv)
7147 static void exec_function(char ***to_free,
7148 const struct function *funcp,
7149 char **argv) NORETURN;
7150 static void exec_function(char ***to_free,
7151 const struct function *funcp,
7157 argv[0] = G.global_argv[0];
7158 G.global_argv = argv;
7159 G.global_argc = n = 1 + string_array_len(argv + 1);
7161 // Example when we are here: "cmd | func"
7162 // func will run with saved-redirect fds open.
7163 // $ f() { echo /proc/self/fd/*; }
7165 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7166 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7169 // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7170 // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7171 // They are CLOEXEC so external programs won't see them, but
7172 // for "more correctness" we might want to close those extra fds here:
7173 //? close_saved_fds_and_FILE_fds();
7175 /* "we are in function, ok to use return" */
7176 G_flag_return_in_progress = -1;
7177 IF_HUSH_LOCAL(G.func_nest_level++;)
7179 /* On MMU, funcp->body is always non-NULL */
7180 n = run_list(funcp->body);
7184 //? close_saved_fds_and_FILE_fds();
7186 //TODO: check whether "true | func_with_return" works
7188 re_execute_shell(to_free,
7189 funcp->body_as_string,
7196 static int run_function(const struct function *funcp, char **argv)
7202 save_and_replace_G_args(&sv, argv);
7204 /* "we are in function, ok to use return" */
7205 sv_flg = G_flag_return_in_progress;
7206 G_flag_return_in_progress = -1;
7207 IF_HUSH_LOCAL(G.func_nest_level++;)
7209 /* On MMU, funcp->body is always non-NULL */
7212 /* Function defined by -F */
7213 parse_and_run_string(funcp->body_as_string);
7214 rc = G.last_exitcode;
7218 rc = run_list(funcp->body);
7221 # if ENABLE_HUSH_LOCAL
7223 struct variable *var;
7224 struct variable **var_pp;
7226 var_pp = &G.top_var;
7227 while ((var = *var_pp) != NULL) {
7228 if (var->func_nest_level < G.func_nest_level) {
7229 var_pp = &var->next;
7233 if (var->flg_export)
7234 bb_unsetenv(var->varstr);
7235 /* Remove from global list */
7236 *var_pp = var->next;
7242 G.func_nest_level--;
7245 G_flag_return_in_progress = sv_flg;
7247 restore_G_args(&sv, argv);
7251 #endif /* ENABLE_HUSH_FUNCTIONS */
7255 #define exec_builtin(to_free, x, argv) \
7256 exec_builtin(x, argv)
7258 #define exec_builtin(to_free, x, argv) \
7259 exec_builtin(to_free, argv)
7261 static void exec_builtin(char ***to_free,
7262 const struct built_in_command *x,
7263 char **argv) NORETURN;
7264 static void exec_builtin(char ***to_free,
7265 const struct built_in_command *x,
7271 //? close_saved_fds_and_FILE_fds();
7272 rcode = x->b_function(argv);
7277 /* On NOMMU, we must never block!
7278 * Example: { sleep 99 | read line; } & echo Ok
7280 re_execute_shell(to_free,
7289 static void execvp_or_die(char **argv) NORETURN;
7290 static void execvp_or_die(char **argv)
7293 debug_printf_exec("execing '%s'\n", argv[0]);
7294 /* Don't propagate SIG_IGN to the child */
7295 if (SPECIAL_JOBSTOP_SIGS != 0)
7296 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7297 execvp(argv[0], argv);
7299 if (errno == EACCES) e = 126;
7300 if (errno == ENOENT) e = 127;
7301 bb_perror_msg("can't execute '%s'", argv[0]);
7305 #if ENABLE_HUSH_MODE_X
7306 static void dump_cmd_in_x_mode(char **argv)
7308 if (G_x_mode && argv) {
7309 /* We want to output the line in one write op */
7317 len += strlen(argv[n++]) + 1;
7323 p += sprintf(p, " %s", argv[n++]);
7331 # define dump_cmd_in_x_mode(argv) ((void)0)
7335 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7336 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7337 #define pseudo_exec(nommu_save, command, argv_expanded) \
7338 pseudo_exec(command, argv_expanded)
7341 /* Called after [v]fork() in run_pipe, or from builtin_exec.
7343 * Don't exit() here. If you don't exec, use _exit instead.
7344 * The at_exit handlers apparently confuse the calling process,
7345 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
7347 static void pseudo_exec_argv(nommu_save_t *nommu_save,
7348 char **argv, int assignment_cnt,
7349 char **argv_expanded) NORETURN;
7350 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7351 char **argv, int assignment_cnt,
7352 char **argv_expanded)
7356 new_env = expand_assignments(argv, assignment_cnt);
7357 dump_cmd_in_x_mode(new_env);
7359 if (!argv[assignment_cnt]) {
7360 /* Case when we are here: ... | var=val | ...
7361 * (note that we do not exit early, i.e., do not optimize out
7362 * expand_assignments(): think about ... | var=`sleep 1` | ...
7364 free_strings(new_env);
7365 _exit(EXIT_SUCCESS);
7369 set_vars_and_save_old(new_env);
7370 free(new_env); /* optional */
7371 /* we can also destroy set_vars_and_save_old's return value,
7374 nommu_save->new_env = new_env;
7375 nommu_save->old_vars = set_vars_and_save_old(new_env);
7378 if (argv_expanded) {
7379 argv = argv_expanded;
7381 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7383 nommu_save->argv = argv;
7386 dump_cmd_in_x_mode(argv);
7388 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7389 if (strchr(argv[0], '/') != NULL)
7393 #if ENABLE_HUSH_FUNCTIONS
7394 /* Check if the command matches any functions (this goes before bltins) */
7396 const struct function *funcp = find_function(argv[0]);
7398 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7403 /* Check if the command matches any of the builtins.
7404 * Depending on context, this might be redundant. But it's
7405 * easier to waste a few CPU cycles than it is to figure out
7406 * if this is one of those cases.
7409 /* On NOMMU, it is more expensive to re-execute shell
7410 * just in order to run echo or test builtin.
7411 * It's better to skip it here and run corresponding
7412 * non-builtin later. */
7413 const struct built_in_command *x;
7414 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7416 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7420 #if ENABLE_FEATURE_SH_STANDALONE
7421 /* Check if the command matches any busybox applets */
7423 int a = find_applet_by_name(argv[0]);
7425 # if BB_MMU /* see above why on NOMMU it is not allowed */
7426 if (APPLET_IS_NOEXEC(a)) {
7427 /* Do not leak open fds from opened script files etc.
7428 * Testcase: interactive "ls -l /proc/self/fd"
7429 * should not show tty fd open.
7431 close_saved_fds_and_FILE_fds();
7432 //FIXME: should also close saved redir fds
7433 /* Without this, "rm -i FILE" can't be ^C'ed: */
7434 switch_off_special_sigs(G.special_sig_mask);
7435 debug_printf_exec("running applet '%s'\n", argv[0]);
7436 run_noexec_applet_and_exit(a, argv[0], argv);
7439 /* Re-exec ourselves */
7440 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
7441 /* Don't propagate SIG_IGN to the child */
7442 if (SPECIAL_JOBSTOP_SIGS != 0)
7443 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
7444 execv(bb_busybox_exec_path, argv);
7445 /* If they called chroot or otherwise made the binary no longer
7446 * executable, fall through */
7451 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7454 execvp_or_die(argv);
7457 /* Called after [v]fork() in run_pipe
7459 static void pseudo_exec(nommu_save_t *nommu_save,
7460 struct command *command,
7461 char **argv_expanded) NORETURN;
7462 static void pseudo_exec(nommu_save_t *nommu_save,
7463 struct command *command,
7464 char **argv_expanded)
7466 if (command->argv) {
7467 pseudo_exec_argv(nommu_save, command->argv,
7468 command->assignment_cnt, argv_expanded);
7471 if (command->group) {
7472 /* Cases when we are here:
7475 * ... | ( list ) | ...
7476 * ... | { list } | ...
7480 debug_printf_exec("pseudo_exec: run_list\n");
7481 reset_traps_to_defaults();
7482 rcode = run_list(command->group);
7483 /* OK to leak memory by not calling free_pipe_list,
7484 * since this process is about to exit */
7487 re_execute_shell(&nommu_save->argv_from_re_execing,
7488 command->group_as_string,
7495 /* Case when we are here: ... | >file */
7496 debug_printf_exec("pseudo_exec'ed null command\n");
7497 _exit(EXIT_SUCCESS);
7501 static const char *get_cmdtext(struct pipe *pi)
7507 /* This is subtle. ->cmdtext is created only on first backgrounding.
7508 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7509 * On subsequent bg argv is trashed, but we won't use it */
7513 argv = pi->cmds[0].argv;
7515 pi->cmdtext = xzalloc(1);
7520 len += strlen(*argv) + 1;
7524 argv = pi->cmds[0].argv;
7526 p = stpcpy(p, *argv);
7533 static void remove_job_from_table(struct pipe *pi)
7535 struct pipe *prev_pipe;
7537 if (pi == G.job_list) {
7538 G.job_list = pi->next;
7540 prev_pipe = G.job_list;
7541 while (prev_pipe->next != pi)
7542 prev_pipe = prev_pipe->next;
7543 prev_pipe->next = pi->next;
7547 G.last_jobid = G.job_list->jobid;
7550 static void delete_finished_job(struct pipe *pi)
7552 remove_job_from_table(pi);
7556 static void clean_up_last_dead_job(void)
7558 if (G.job_list && !G.job_list->alive_cmds)
7559 delete_finished_job(G.job_list);
7562 static void insert_job_into_table(struct pipe *pi)
7564 struct pipe *job, **jobp;
7567 clean_up_last_dead_job();
7569 /* Find the end of the list, and find next job ID to use */
7572 while ((job = *jobp) != NULL) {
7579 /* Create a new job struct at the end */
7580 job = *jobp = xmemdup(pi, sizeof(*pi));
7582 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7583 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7584 for (i = 0; i < pi->num_cmds; i++) {
7585 job->cmds[i].pid = pi->cmds[i].pid;
7586 /* all other fields are not used and stay zero */
7588 job->cmdtext = xstrdup(get_cmdtext(pi));
7590 if (G_interactive_fd)
7591 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
7592 G.last_jobid = job->jobid;
7596 static int job_exited_or_stopped(struct pipe *pi)
7600 if (pi->alive_cmds != pi->stopped_cmds)
7603 /* All processes in fg pipe have exited or stopped */
7607 rcode = pi->cmds[i].cmd_exitcode;
7608 /* usually last process gives overall exitstatus,
7609 * but with "set -o pipefail", last *failed* process does */
7610 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7613 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7617 static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
7624 dead = WIFEXITED(status) || WIFSIGNALED(status);
7627 if (WIFSTOPPED(status))
7628 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7629 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7630 if (WIFSIGNALED(status))
7631 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7632 childpid, WTERMSIG(status), WEXITSTATUS(status));
7633 if (WIFEXITED(status))
7634 debug_printf_jobs("pid %d exited, exitcode %d\n",
7635 childpid, WEXITSTATUS(status));
7637 /* Were we asked to wait for a fg pipe? */
7639 i = fg_pipe->num_cmds;
7644 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7645 if (fg_pipe->cmds[i].pid != childpid)
7649 fg_pipe->cmds[i].pid = 0;
7650 fg_pipe->alive_cmds--;
7651 ex = WEXITSTATUS(status);
7652 /* bash prints killer signal's name for *last*
7653 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7654 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7656 if (WIFSIGNALED(status)) {
7657 int sig = WTERMSIG(status);
7658 if (i == fg_pipe->num_cmds-1)
7659 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7660 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7661 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7662 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7663 * Maybe we need to use sig | 128? */
7666 fg_pipe->cmds[i].cmd_exitcode = ex;
7668 fg_pipe->stopped_cmds++;
7670 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7671 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7672 rcode = job_exited_or_stopped(fg_pipe);
7674 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7675 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7676 * and "killall -STOP cat" */
7677 if (G_interactive_fd) {
7679 if (fg_pipe->alive_cmds != 0)
7680 insert_job_into_table(fg_pipe);
7684 if (fg_pipe->alive_cmds == 0)
7687 /* There are still running processes in the fg_pipe */
7690 /* It wasn't in fg_pipe, look for process in bg pipes */
7694 /* We were asked to wait for bg or orphaned children */
7695 /* No need to remember exitcode in this case */
7696 for (pi = G.job_list; pi; pi = pi->next) {
7697 for (i = 0; i < pi->num_cmds; i++) {
7698 if (pi->cmds[i].pid == childpid)
7699 goto found_pi_and_prognum;
7702 /* Happens when shell is used as init process (init=/bin/sh) */
7703 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7704 return -1; /* this wasn't a process from fg_pipe */
7706 found_pi_and_prognum:
7709 int rcode = WEXITSTATUS(status);
7710 if (WIFSIGNALED(status))
7711 rcode = 128 + WTERMSIG(status);
7712 pi->cmds[i].cmd_exitcode = rcode;
7713 if (G.last_bg_pid == pi->cmds[i].pid)
7714 G.last_bg_pid_exitcode = rcode;
7715 pi->cmds[i].pid = 0;
7717 if (!pi->alive_cmds) {
7718 if (G_interactive_fd) {
7719 printf(JOB_STATUS_FORMAT, pi->jobid,
7720 "Done", pi->cmdtext);
7721 delete_finished_job(pi);
7724 * bash deletes finished jobs from job table only in interactive mode,
7725 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7726 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7727 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7728 * We only retain one "dead" job, if it's the single job on the list.
7729 * This covers most of real-world scenarios where this is useful.
7731 if (pi != G.job_list)
7732 delete_finished_job(pi);
7740 return -1; /* this wasn't a process from fg_pipe */
7743 /* Check to see if any processes have exited -- if they have,
7744 * figure out why and see if a job has completed.
7746 * If non-NULL fg_pipe: wait for its completion or stop.
7747 * Return its exitcode or zero if stopped.
7749 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7750 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7751 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7752 * or 0 if no children changed status.
7754 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7755 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7756 * or 0 if no children changed status.
7758 static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7764 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7766 attributes = WUNTRACED;
7767 if (fg_pipe == NULL)
7768 attributes |= WNOHANG;
7771 #if ENABLE_HUSH_FAST
7772 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7773 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7774 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7775 /* There was neither fork nor SIGCHLD since last waitpid */
7776 /* Avoid doing waitpid syscall if possible */
7777 if (!G.we_have_children) {
7781 if (fg_pipe == NULL) { /* is WNOHANG set? */
7782 /* We have children, but they did not exit
7783 * or stop yet (we saw no SIGCHLD) */
7786 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7790 /* Do we do this right?
7791 * bash-3.00# sleep 20 | false
7793 * [3]+ Stopped sleep 20 | false
7794 * bash-3.00# echo $?
7795 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7796 * [hush 1.14.0: yes we do it right]
7800 #if ENABLE_HUSH_FAST
7802 i = G.count_SIGCHLD;
7804 childpid = waitpid(-1, &status, attributes);
7805 if (childpid <= 0) {
7806 if (childpid && errno != ECHILD)
7807 bb_perror_msg("waitpid");
7808 #if ENABLE_HUSH_FAST
7809 else { /* Until next SIGCHLD, waitpid's are useless */
7810 G.we_have_children = (childpid == 0);
7811 G.handled_SIGCHLD = i;
7812 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7815 /* ECHILD (no children), or 0 (no change in children status) */
7819 rcode = process_wait_result(fg_pipe, childpid, status);
7821 /* fg_pipe exited or stopped */
7824 if (childpid == waitfor_pid) {
7825 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
7826 rcode = WEXITSTATUS(status);
7827 if (WIFSIGNALED(status))
7828 rcode = 128 + WTERMSIG(status);
7829 if (WIFSTOPPED(status))
7830 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7831 rcode = 128 + WSTOPSIG(status);
7833 break; /* "wait PID" called us, give it exitcode+1 */
7835 /* This wasn't one of our processes, or */
7836 /* fg_pipe still has running processes, do waitpid again */
7837 } /* while (waitpid succeeds)... */
7843 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7846 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
7847 if (G_saved_tty_pgrp) {
7848 /* Job finished, move the shell to the foreground */
7849 p = getpgrp(); /* our process group id */
7850 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7851 tcsetpgrp(G_interactive_fd, p);
7857 /* Start all the jobs, but don't wait for anything to finish.
7860 * Return code is normally -1, when the caller has to wait for children
7861 * to finish to determine the exit status of the pipe. If the pipe
7862 * is a simple builtin command, however, the action is done by the
7863 * time run_pipe returns, and the exit code is provided as the
7866 * Returns -1 only if started some children. IOW: we have to
7867 * mask out retvals of builtins etc with 0xff!
7869 * The only case when we do not need to [v]fork is when the pipe
7870 * is single, non-backgrounded, non-subshell command. Examples:
7871 * cmd ; ... { list } ; ...
7872 * cmd && ... { list } && ...
7873 * cmd || ... { list } || ...
7874 * If it is, then we can run cmd as a builtin, NOFORK,
7875 * or (if SH_STANDALONE) an applet, and we can run the { list }
7876 * with run_list. If it isn't one of these, we fork and exec cmd.
7878 * Cases when we must fork:
7879 * non-single: cmd | cmd
7880 * backgrounded: cmd & { list } &
7881 * subshell: ( list ) [&]
7883 #if !ENABLE_HUSH_MODE_X
7884 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7885 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7887 static int redirect_and_varexp_helper(char ***new_env_p,
7888 struct variable **old_vars_p,
7889 struct command *command,
7890 struct squirrel **sqp,
7891 char **argv_expanded)
7893 /* setup_redirects acts on file descriptors, not FILEs.
7894 * This is perfect for work that comes after exec().
7895 * Is it really safe for inline use? Experimentally,
7896 * things seem to work. */
7897 int rcode = setup_redirects(command, sqp);
7899 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7900 *new_env_p = new_env;
7901 dump_cmd_in_x_mode(new_env);
7902 dump_cmd_in_x_mode(argv_expanded);
7904 *old_vars_p = set_vars_and_save_old(new_env);
7908 static NOINLINE int run_pipe(struct pipe *pi)
7910 static const char *const null_ptr = NULL;
7914 struct command *command;
7915 char **argv_expanded;
7917 struct squirrel *squirrel = NULL;
7920 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7923 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7924 * Result should be 3 lines: q w e, qwe, q w e
7926 G.ifs = get_local_var_value("IFS");
7930 IF_HUSH_JOB(pi->pgrp = -1;)
7931 pi->stopped_cmds = 0;
7932 command = &pi->cmds[0];
7933 argv_expanded = NULL;
7935 if (pi->num_cmds != 1
7936 || pi->followup == PIPE_BG
7937 || command->cmd_type == CMD_SUBSHELL
7944 debug_printf_exec(": group:%p argv:'%s'\n",
7945 command->group, command->argv ? command->argv[0] : "NONE");
7947 if (command->group) {
7948 #if ENABLE_HUSH_FUNCTIONS
7949 if (command->cmd_type == CMD_FUNCDEF) {
7950 /* "executing" func () { list } */
7951 struct function *funcp;
7953 funcp = new_function(command->argv[0]);
7954 /* funcp->name is already set to argv[0] */
7955 funcp->body = command->group;
7957 funcp->body_as_string = command->group_as_string;
7958 command->group_as_string = NULL;
7960 command->group = NULL;
7961 command->argv[0] = NULL;
7962 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7963 funcp->parent_cmd = command;
7964 command->child_func = funcp;
7966 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7968 return EXIT_SUCCESS;
7972 debug_printf("non-subshell group\n");
7973 rcode = 1; /* exitcode if redir failed */
7974 if (setup_redirects(command, &squirrel) == 0) {
7975 debug_printf_exec(": run_list\n");
7976 rcode = run_list(command->group) & 0xff;
7978 restore_redirects(squirrel);
7979 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7981 debug_printf_exec("run_pipe: return %d\n", rcode);
7985 argv = command->argv ? command->argv : (char **) &null_ptr;
7987 const struct built_in_command *x;
7988 #if ENABLE_HUSH_FUNCTIONS
7989 const struct function *funcp;
7993 char **new_env = NULL;
7994 struct variable *old_vars = NULL;
7996 if (argv[command->assignment_cnt] == NULL) {
7997 /* Assignments, but no command */
7998 /* Ensure redirects take effect (that is, create files).
7999 * Try "a=t >file" */
8000 #if 0 /* A few cases in testsuite fail with this code. FIXME */
8001 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
8002 /* Set shell variables */
8006 if (set_local_var(*argv, /*flag:*/ 0)) {
8007 /* assignment to readonly var / putenv error? */
8013 /* Redirect error sets $? to 1. Otherwise,
8014 * if evaluating assignment value set $?, retain it.
8015 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8017 rcode = G.last_exitcode;
8018 /* Exit, _skipping_ variable restoring code: */
8019 goto clean_up_and_ret0;
8021 #else /* Older, bigger, but more correct code */
8023 rcode = setup_redirects(command, &squirrel);
8024 restore_redirects(squirrel);
8025 /* Set shell variables */
8027 bb_putchar_stderr('+');
8029 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
8031 fprintf(stderr, " %s", p);
8032 debug_printf_exec("set shell var:'%s'->'%s'\n",
8034 if (set_local_var(p, /*flag:*/ 0)) {
8035 /* assignment to readonly var / putenv error? */
8041 bb_putchar_stderr('\n');
8042 /* Redirect error sets $? to 1. Otherwise,
8043 * if evaluating assignment value set $?, retain it.
8044 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8046 rcode = G.last_exitcode;
8047 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8049 debug_printf_exec("run_pipe: return %d\n", rcode);
8054 /* Expand the rest into (possibly) many strings each */
8056 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
8057 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
8061 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8064 /* if someone gives us an empty string: `cmd with empty output` */
8065 if (!argv_expanded[0]) {
8066 free(argv_expanded);
8068 return G.last_exitcode;
8071 #if ENABLE_HUSH_FUNCTIONS
8072 /* Check if argv[0] matches any functions (this goes before bltins) */
8073 funcp = find_function(argv_expanded[0]);
8077 x = find_builtin(argv_expanded[0]);
8080 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8081 debug_printf("exec with redirects only\n");
8082 rcode = setup_redirects(command, NULL);
8083 /* rcode=1 can be if redir file can't be opened */
8084 goto clean_up_and_ret1;
8087 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8090 debug_printf_exec(": builtin '%s' '%s'...\n",
8091 x->b_cmd, argv_expanded[1]);
8093 rcode = x->b_function(argv_expanded) & 0xff;
8096 #if ENABLE_HUSH_FUNCTIONS
8098 # if ENABLE_HUSH_LOCAL
8099 struct variable **sv;
8100 sv = G.shadowed_vars_pp;
8101 G.shadowed_vars_pp = &old_vars;
8103 debug_printf_exec(": function '%s' '%s'...\n",
8104 funcp->name, argv_expanded[1]);
8105 rcode = run_function(funcp, argv_expanded) & 0xff;
8106 # if ENABLE_HUSH_LOCAL
8107 G.shadowed_vars_pp = sv;
8113 unset_vars(new_env);
8115 /* clean_up_and_ret0: */
8116 restore_redirects(squirrel);
8118 * Try "usleep 99999999" + ^C + "echo $?"
8119 * with FEATURE_SH_NOFORK=y.
8122 /* It was builtin or nofork.
8123 * if this would be a real fork/execed program,
8124 * it should have died if a fatal sig was received.
8125 * But OTOH, there was no separate process,
8126 * the sig was sent to _shell_, not to non-existing
8128 * Let's just handle ^C only, this one is obvious:
8129 * we aren't ok with exitcode 0 when ^C was pressed
8130 * during builtin/nofork.
8132 if (sigismember(&G.pending_set, SIGINT))
8133 rcode = 128 + SIGINT;
8136 free(argv_expanded);
8137 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8139 debug_printf_exec("run_pipe return %d\n", rcode);
8143 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
8144 int n = find_applet_by_name(argv_expanded[0]);
8145 if (n >= 0 && APPLET_IS_NOFORK(n)) {
8146 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
8148 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8149 argv_expanded[0], argv_expanded[1]);
8151 * Note: signals (^C) can't interrupt here.
8152 * We remember them and they will be acted upon
8153 * after applet returns.
8154 * This makes applets which can run for a long time
8155 * and/or wait for user input ineligible for NOFORK:
8156 * for example, "yes" or "rm" (rm -i waits for input).
8158 rcode = run_nofork_applet(n, argv_expanded);
8160 goto clean_up_and_ret;
8163 /* It is neither builtin nor applet. We must fork. */
8167 /* NB: argv_expanded may already be created, and that
8168 * might include `cmd` runs! Do not rerun it! We *must*
8169 * use argv_expanded if it's non-NULL */
8171 /* Going to fork a child per each pipe member */
8176 while (cmd_no < pi->num_cmds) {
8177 struct fd_pair pipefds;
8179 volatile nommu_save_t nommu_save;
8180 nommu_save.new_env = NULL;
8181 nommu_save.old_vars = NULL;
8182 nommu_save.argv = NULL;
8183 nommu_save.argv_from_re_execing = NULL;
8185 command = &pi->cmds[cmd_no];
8187 if (command->argv) {
8188 debug_printf_exec(": pipe member '%s' '%s'...\n",
8189 command->argv[0], command->argv[1]);
8191 debug_printf_exec(": pipe member with no argv\n");
8194 /* pipes are inserted between pairs of commands */
8197 if (cmd_no < pi->num_cmds)
8198 xpiped_pair(pipefds);
8200 command->pid = BB_MMU ? fork() : vfork();
8201 if (!command->pid) { /* child */
8203 disable_restore_tty_pgrp_on_exit();
8204 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8206 /* Every child adds itself to new process group
8207 * with pgid == pid_of_first_child_in_pipe */
8208 if (G.run_list_level == 1 && G_interactive_fd) {
8211 if (pgrp < 0) /* true for 1st process only */
8213 if (setpgid(0, pgrp) == 0
8214 && pi->followup != PIPE_BG
8215 && G_saved_tty_pgrp /* we have ctty */
8217 /* We do it in *every* child, not just first,
8219 tcsetpgrp(G_interactive_fd, pgrp);
8223 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8224 /* 1st cmd in backgrounded pipe
8225 * should have its stdin /dev/null'ed */
8227 if (open(bb_dev_null, O_RDONLY))
8228 xopen("/", O_RDONLY);
8230 xmove_fd(next_infd, 0);
8232 xmove_fd(pipefds.wr, 1);
8235 /* Like bash, explicit redirects override pipes,
8236 * and the pipe fd (fd#1) is available for dup'ing:
8237 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8238 * of cmd1 goes into pipe.
8240 if (setup_redirects(command, NULL)) {
8241 /* Happens when redir file can't be opened:
8242 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8244 * hush: can't open '/qwe/rty': No such file or directory
8246 * (echo BAR is not executed, it hits _exit(1) below)
8251 /* Stores to nommu_save list of env vars putenv'ed
8252 * (NOMMU, on MMU we don't need that) */
8253 /* cast away volatility... */
8254 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8255 /* pseudo_exec() does not return */
8258 /* parent or error */
8259 #if ENABLE_HUSH_FAST
8261 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8263 enable_restore_tty_pgrp_on_exit();
8265 /* Clean up after vforked child */
8266 free(nommu_save.argv);
8267 free(nommu_save.argv_from_re_execing);
8268 unset_vars(nommu_save.new_env);
8269 add_vars(nommu_save.old_vars);
8271 free(argv_expanded);
8272 argv_expanded = NULL;
8273 if (command->pid < 0) { /* [v]fork failed */
8274 /* Clearly indicate, was it fork or vfork */
8275 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8279 /* Second and next children need to know pid of first one */
8281 pi->pgrp = command->pid;
8287 if (cmd_no < pi->num_cmds)
8289 /* Pass read (output) pipe end to next iteration */
8290 next_infd = pipefds.rd;
8293 if (!pi->alive_cmds) {
8295 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8300 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8304 /* NB: called by pseudo_exec, and therefore must not modify any
8305 * global data until exec/_exit (we can be a child after vfork!) */
8306 static int run_list(struct pipe *pi)
8308 #if ENABLE_HUSH_CASE
8309 char *case_word = NULL;
8311 #if ENABLE_HUSH_LOOPS
8312 struct pipe *loop_top = NULL;
8313 char **for_lcur = NULL;
8314 char **for_list = NULL;
8316 smallint last_followup;
8318 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8319 smalluint cond_code = 0;
8321 enum { cond_code = 0 };
8324 smallint rword; /* RES_foo */
8325 smallint last_rword; /* ditto */
8328 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8331 #if ENABLE_HUSH_LOOPS
8332 /* Check syntax for "for" */
8335 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8336 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8338 /* current word is FOR or IN (BOLD in comments below) */
8339 if (cpipe->next == NULL) {
8340 syntax_error("malformed for");
8342 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8345 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8346 if (cpipe->next->res_word == RES_DO)
8348 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8349 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8350 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8352 syntax_error("malformed for");
8354 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8361 /* Past this point, all code paths should jump to ret: label
8362 * in order to return, no direct "return" statements please.
8363 * This helps to ensure that no memory is leaked. */
8371 last_rword = RES_XXXX;
8373 last_followup = PIPE_SEQ;
8374 rcode = G.last_exitcode;
8376 /* Go through list of pipes, (maybe) executing them. */
8377 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
8379 int sv_errexit_depth;
8383 if (G_flag_return_in_progress == 1)
8386 IF_HAS_KEYWORDS(rword = pi->res_word;)
8387 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8388 rword, cond_code, last_rword);
8390 sv_errexit_depth = G.errexit_depth;
8393 rword == RES_IF || rword == RES_ELIF ||
8395 pi->followup != PIPE_SEQ
8399 #if ENABLE_HUSH_LOOPS
8400 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8401 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8403 /* start of a loop: remember where loop starts */
8408 /* Still in the same "if...", "then..." or "do..." branch? */
8409 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8410 if ((rcode == 0 && last_followup == PIPE_OR)
8411 || (rcode != 0 && last_followup == PIPE_AND)
8413 /* It is "<true> || CMD" or "<false> && CMD"
8414 * and we should not execute CMD */
8415 debug_printf_exec("skipped cmd because of || or &&\n");
8416 last_followup = pi->followup;
8417 goto dont_check_jobs_but_continue;
8420 last_followup = pi->followup;
8421 IF_HAS_KEYWORDS(last_rword = rword;)
8424 if (rword == RES_THEN) {
8425 /* if false; then ... fi has exitcode 0! */
8426 G.last_exitcode = rcode = EXIT_SUCCESS;
8427 /* "if <false> THEN cmd": skip cmd */
8431 if (rword == RES_ELSE || rword == RES_ELIF) {
8432 /* "if <true> then ... ELSE/ELIF cmd":
8433 * skip cmd and all following ones */
8438 #if ENABLE_HUSH_LOOPS
8439 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8441 /* first loop through for */
8443 static const char encoded_dollar_at[] ALIGN1 = {
8444 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8445 }; /* encoded representation of "$@" */
8446 static const char *const encoded_dollar_at_argv[] = {
8447 encoded_dollar_at, NULL
8448 }; /* argv list with one element: "$@" */
8451 vals = (char**)encoded_dollar_at_argv;
8452 if (pi->next->res_word == RES_IN) {
8453 /* if no variable values after "in" we skip "for" */
8454 if (!pi->next->cmds[0].argv) {
8455 G.last_exitcode = rcode = EXIT_SUCCESS;
8456 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8459 vals = pi->next->cmds[0].argv;
8460 } /* else: "for var; do..." -> assume "$@" list */
8461 /* create list of variable values */
8462 debug_print_strings("for_list made from", vals);
8463 for_list = expand_strvec_to_strvec(vals);
8464 for_lcur = for_list;
8465 debug_print_strings("for_list", for_list);
8468 /* "for" loop is over, clean up */
8474 /* Insert next value from for_lcur */
8475 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8476 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
8479 if (rword == RES_IN) {
8480 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8482 if (rword == RES_DONE) {
8483 continue; /* "done" has no cmds too */
8486 #if ENABLE_HUSH_CASE
8487 if (rword == RES_CASE) {
8488 debug_printf_exec("CASE cond_code:%d\n", cond_code);
8489 case_word = expand_strvec_to_string(pi->cmds->argv);
8490 unbackslash(case_word);
8493 if (rword == RES_MATCH) {
8496 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
8497 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8499 /* all prev words didn't match, does this one match? */
8500 argv = pi->cmds->argv;
8502 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
8503 /* TODO: which FNM_xxx flags to use? */
8504 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8505 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
8507 if (cond_code == 0) { /* match! we will execute this branch */
8509 case_word = NULL; /* make future "word)" stop */
8516 if (rword == RES_CASE_BODY) { /* inside of a case branch */
8517 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
8519 continue; /* not matched yet, skip this pipe */
8521 if (rword == RES_ESAC) {
8522 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8524 /* "case" did not match anything: still set $? (to 0) */
8525 G.last_exitcode = rcode = EXIT_SUCCESS;
8529 /* Just pressing <enter> in shell should check for jobs.
8530 * OTOH, in non-interactive shell this is useless
8531 * and only leads to extra job checks */
8532 if (pi->num_cmds == 0) {
8533 if (G_interactive_fd)
8534 goto check_jobs_and_continue;
8538 /* After analyzing all keywords and conditions, we decided
8539 * to execute this pipe. NB: have to do checkjobs(NULL)
8540 * after run_pipe to collect any background children,
8541 * even if list execution is to be stopped. */
8542 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
8543 #if ENABLE_HUSH_LOOPS
8544 G.flag_break_continue = 0;
8546 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8548 /* We ran a builtin, function, or group.
8549 * rcode is already known
8550 * and we don't need to wait for anything. */
8551 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8552 G.last_exitcode = rcode;
8553 check_and_run_traps();
8554 #if ENABLE_HUSH_LOOPS
8555 /* Was it "break" or "continue"? */
8556 if (G.flag_break_continue) {
8557 smallint fbc = G.flag_break_continue;
8558 /* We might fall into outer *loop*,
8559 * don't want to break it too */
8561 G.depth_break_continue--;
8562 if (G.depth_break_continue == 0)
8563 G.flag_break_continue = 0;
8564 /* else: e.g. "continue 2" should *break* once, *then* continue */
8565 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8566 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
8567 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8570 /* "continue": simulate end of loop */
8575 if (G_flag_return_in_progress == 1) {
8576 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8579 } else if (pi->followup == PIPE_BG) {
8580 /* What does bash do with attempts to background builtins? */
8581 /* even bash 3.2 doesn't do that well with nested bg:
8582 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8583 * I'm NOT treating inner &'s as jobs */
8585 if (G.run_list_level == 1)
8586 insert_job_into_table(pi);
8588 /* Last command's pid goes to $! */
8589 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8590 G.last_bg_pid_exitcode = 0;
8591 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8592 /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
8593 rcode = EXIT_SUCCESS;
8597 if (G.run_list_level == 1 && G_interactive_fd) {
8598 /* Waits for completion, then fg's main shell */
8599 rcode = checkjobs_and_fg_shell(pi);
8600 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8604 /* This one just waits for completion */
8605 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8606 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8608 G.last_exitcode = rcode;
8609 check_and_run_traps();
8612 /* Handle "set -e" */
8613 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8614 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8615 if (G.errexit_depth == 0)
8618 G.errexit_depth = sv_errexit_depth;
8620 /* Analyze how result affects subsequent commands */
8622 if (rword == RES_IF || rword == RES_ELIF)
8625 check_jobs_and_continue:
8626 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8627 dont_check_jobs_but_continue: ;
8628 #if ENABLE_HUSH_LOOPS
8629 /* Beware of "while false; true; do ..."! */
8631 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
8632 /* check for RES_DONE is needed for "while ...; do \n done" case */
8634 if (rword == RES_WHILE) {
8636 /* "while false; do...done" - exitcode 0 */
8637 G.last_exitcode = rcode = EXIT_SUCCESS;
8638 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
8642 if (rword == RES_UNTIL) {
8644 debug_printf_exec(": until expr is true: breaking\n");
8655 #if ENABLE_HUSH_LOOPS
8660 #if ENABLE_HUSH_CASE
8664 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8668 /* Select which version we will use */
8669 static int run_and_free_list(struct pipe *pi)
8672 debug_printf_exec("run_and_free_list entered\n");
8673 if (!G.o_opt[OPT_O_NOEXEC]) {
8674 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8675 rcode = run_list(pi);
8677 /* free_pipe_list has the side effect of clearing memory.
8678 * In the long run that function can be merged with run_list,
8679 * but doing that now would hobble the debugging effort. */
8681 debug_printf_exec("run_and_free_list return %d\n", rcode);
8686 static void install_sighandlers(unsigned mask)
8688 sighandler_t old_handler;
8690 while ((mask >>= 1) != 0) {
8694 old_handler = install_sighandler(sig, pick_sighandler(sig));
8695 /* POSIX allows shell to re-enable SIGCHLD
8696 * even if it was SIG_IGN on entry.
8697 * Therefore we skip IGN check for it:
8701 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8702 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8704 //if (sig == SIGHUP) continue; - TODO?
8705 if (old_handler == SIG_IGN) {
8706 /* oops... restore back to IGN, and record this fact */
8707 install_sighandler(sig, old_handler);
8708 #if ENABLE_HUSH_TRAP
8710 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8712 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8718 /* Called a few times only (or even once if "sh -c") */
8719 static void install_special_sighandlers(void)
8723 /* Which signals are shell-special? */
8724 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8725 if (G_interactive_fd) {
8726 mask |= SPECIAL_INTERACTIVE_SIGS;
8727 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8728 mask |= SPECIAL_JOBSTOP_SIGS;
8730 /* Careful, do not re-install handlers we already installed */
8731 if (G.special_sig_mask != mask) {
8732 unsigned diff = mask & ~G.special_sig_mask;
8733 G.special_sig_mask = mask;
8734 install_sighandlers(diff);
8740 /* Set handlers to restore tty pgrp and exit */
8741 static void install_fatal_sighandlers(void)
8745 /* We will restore tty pgrp on these signals */
8747 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8748 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
8749 + (1 << SIGBUS ) * HUSH_DEBUG
8750 + (1 << SIGSEGV) * HUSH_DEBUG
8751 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
8753 /* bash 3.2 seems to handle these just like 'fatal' ones */
8756 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8757 * if we aren't interactive... but in this case
8758 * we never want to restore pgrp on exit, and this fn is not called
8760 /*+ (1 << SIGHUP )*/
8761 /*+ (1 << SIGTERM)*/
8762 /*+ (1 << SIGINT )*/
8764 G_fatal_sig_mask = mask;
8766 install_sighandlers(mask);
8770 static int set_mode(int state, char mode, const char *o_opt)
8775 G.o_opt[OPT_O_NOEXEC] = state;
8778 IF_HUSH_MODE_X(G_x_mode = state;)
8782 /* "set -+o" without parameter.
8783 * in bash, set -o produces this output:
8787 * We always use the second form.
8789 const char *p = o_opt_strings;
8792 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8798 idx = index_in_strings(o_opt_strings, o_opt);
8800 G.o_opt[idx] = state;
8804 G.o_opt[OPT_O_ERREXIT] = state;
8807 return EXIT_FAILURE;
8809 return EXIT_SUCCESS;
8812 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8813 int hush_main(int argc, char **argv)
8816 OPT_login = (1 << 0),
8820 unsigned builtin_argc;
8822 struct variable *cur_var;
8823 struct variable *shell_ver;
8826 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8827 G.last_exitcode = EXIT_SUCCESS;
8829 #if ENABLE_HUSH_FAST
8830 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8833 G.argv0_for_re_execing = argv[0];
8835 /* Deal with HUSH_VERSION */
8836 shell_ver = xzalloc(sizeof(*shell_ver));
8837 shell_ver->flg_export = 1;
8838 shell_ver->flg_read_only = 1;
8839 /* Code which handles ${var<op>...} needs writable values for all variables,
8840 * therefore we xstrdup: */
8841 shell_ver->varstr = xstrdup(hush_version_str);
8842 /* Create shell local variables from the values
8843 * currently living in the environment */
8844 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8845 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8846 G.top_var = shell_ver;
8847 cur_var = G.top_var;
8850 char *value = strchr(*e, '=');
8851 if (value) { /* paranoia */
8852 cur_var->next = xzalloc(sizeof(*cur_var));
8853 cur_var = cur_var->next;
8854 cur_var->varstr = *e;
8855 cur_var->max_len = strlen(*e);
8856 cur_var->flg_export = 1;
8860 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8861 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8862 putenv(shell_ver->varstr);
8865 set_pwd_var(SETFLAG_EXPORT);
8867 #if BASH_HOSTNAME_VAR
8868 /* Set (but not export) HOSTNAME unless already set */
8869 if (!get_local_var_value("HOSTNAME")) {
8872 set_local_var_from_halves("HOSTNAME", uts.nodename);
8874 /* bash also exports SHLVL and _,
8875 * and sets (but doesn't export) the following variables:
8877 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8878 * BASH_VERSION='3.2.0(1)-release'
8880 * MACHTYPE=i386-pc-linux-gnu
8882 * PPID=<NNNNN> - we also do it elsewhere
8893 * PIPESTATUS=([0]="0")
8894 * HISTFILE=/<xxx>/.bash_history
8898 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8900 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8911 #if ENABLE_FEATURE_EDITING
8912 G.line_input_state = new_line_input_t(FOR_SHELL);
8915 /* Initialize some more globals to non-zero values */
8916 cmdedit_update_prompt();
8918 die_func = restore_ttypgrp_and__exit;
8920 /* Shell is non-interactive at first. We need to call
8921 * install_special_sighandlers() if we are going to execute "sh <script>",
8922 * "sh -c <cmds>" or login shell's /etc/profile and friends.
8923 * If we later decide that we are interactive, we run install_special_sighandlers()
8924 * in order to intercept (more) signals.
8928 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8929 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8932 opt = getopt(argc, argv, "+c:exinsl"
8935 # if ENABLE_HUSH_FUNCTIONS
8945 * sh ... -c 'script'
8946 * sh ... -c 'script' ARG0 [ARG1...]
8947 * On NOMMU, if builtin_argc != 0,
8948 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8949 * "" needs to be replaced with NULL
8950 * and BARGV vector fed to builtin function.
8951 * Note: the form without ARG0 never happens:
8952 * sh ... -c 'builtin' BARGV... ""
8955 G.root_pid = getpid();
8956 G.root_ppid = getppid();
8958 G.global_argv = argv + optind;
8959 G.global_argc = argc - optind;
8961 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8962 const struct built_in_command *x;
8964 install_special_sighandlers();
8965 x = find_builtin(optarg);
8966 if (x) { /* paranoia */
8967 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8968 G.global_argv += builtin_argc;
8969 G.global_argv[-1] = NULL; /* replace "" */
8971 G.last_exitcode = x->b_function(argv + optind - 1);
8975 if (!G.global_argv[0]) {
8976 /* -c 'script' (no params): prevent empty $0 */
8977 G.global_argv--; /* points to argv[i] of 'script' */
8978 G.global_argv[0] = argv[0];
8980 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8981 install_special_sighandlers();
8982 parse_and_run_string(optarg);
8985 /* Well, we cannot just declare interactiveness,
8986 * we have to have some stuff (ctty, etc) */
8987 /* G_interactive_fd++; */
8990 /* "-s" means "read from stdin", but this is how we always
8991 * operate, so simply do nothing here. */
8997 case '<': /* "big heredoc" support */
8998 full_write1_str(optarg);
9001 unsigned long long empty_trap_mask;
9003 G.root_pid = bb_strtou(optarg, &optarg, 16);
9005 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9007 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9009 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
9011 builtin_argc = bb_strtou(optarg, &optarg, 16);
9013 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9014 if (empty_trap_mask != 0) {
9015 IF_HUSH_TRAP(int sig;)
9016 install_special_sighandlers();
9017 # if ENABLE_HUSH_TRAP
9018 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
9019 for (sig = 1; sig < NSIG; sig++) {
9020 if (empty_trap_mask & (1LL << sig)) {
9021 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
9022 install_sighandler(sig, SIG_IGN);
9027 # if ENABLE_HUSH_LOOPS
9029 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
9035 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
9037 # if ENABLE_HUSH_FUNCTIONS
9039 struct function *funcp = new_function(optarg);
9040 /* funcp->name is already set to optarg */
9041 /* funcp->body is set to NULL. It's a special case. */
9042 funcp->body_as_string = argv[optind];
9051 if (set_mode(1, opt, NULL) == 0) /* no error */
9055 fprintf(stderr, "Usage: sh [FILE]...\n"
9056 " or: sh -c command [args]...\n\n");
9062 } /* option parsing loop */
9064 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9065 G.global_argc = argc - (optind - 1);
9066 G.global_argv = argv + (optind - 1);
9067 G.global_argv[0] = argv[0];
9070 G.root_pid = getpid();
9071 G.root_ppid = getppid();
9074 /* If we are login shell... */
9075 if (flags & OPT_login) {
9077 debug_printf("sourcing /etc/profile\n");
9078 input = fopen_for_read("/etc/profile");
9079 if (input != NULL) {
9080 remember_FILE(input);
9081 install_special_sighandlers();
9082 parse_and_run_file(input);
9083 fclose_and_forget(input);
9085 /* bash: after sourcing /etc/profile,
9086 * tries to source (in the given order):
9087 * ~/.bash_profile, ~/.bash_login, ~/.profile,
9088 * stopping on first found. --noprofile turns this off.
9089 * bash also sources ~/.bash_logout on exit.
9090 * If called as sh, skips .bash_XXX files.
9094 if (G.global_argv[1]) {
9097 * "bash <script>" (which is never interactive (unless -i?))
9098 * sources $BASH_ENV here (without scanning $PATH).
9099 * If called as sh, does the same but with $ENV.
9100 * Also NB, per POSIX, $ENV should undergo parameter expansion.
9104 debug_printf("running script '%s'\n", G.global_argv[0]);
9105 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
9106 input = xfopen_for_read(G.global_argv[0]);
9107 xfunc_error_retval = 1;
9108 remember_FILE(input);
9109 install_special_sighandlers();
9110 parse_and_run_file(input);
9111 #if ENABLE_FEATURE_CLEAN_UP
9112 fclose_and_forget(input);
9117 /* Up to here, shell was non-interactive. Now it may become one.
9118 * NB: don't forget to (re)run install_special_sighandlers() as needed.
9121 /* A shell is interactive if the '-i' flag was given,
9122 * or if all of the following conditions are met:
9124 * no arguments remaining or the -s flag given
9125 * standard input is a terminal
9126 * standard output is a terminal
9127 * Refer to Posix.2, the description of the 'sh' utility.
9130 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9131 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9132 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9133 if (G_saved_tty_pgrp < 0)
9134 G_saved_tty_pgrp = 0;
9136 /* try to dup stdin to high fd#, >= 255 */
9137 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9138 if (G_interactive_fd < 0) {
9139 /* try to dup to any fd */
9140 G_interactive_fd = dup(STDIN_FILENO);
9141 if (G_interactive_fd < 0) {
9143 G_interactive_fd = 0;
9144 G_saved_tty_pgrp = 0;
9147 // TODO: track & disallow any attempts of user
9148 // to (inadvertently) close/redirect G_interactive_fd
9150 debug_printf("interactive_fd:%d\n", G_interactive_fd);
9151 if (G_interactive_fd) {
9152 close_on_exec_on(G_interactive_fd);
9154 if (G_saved_tty_pgrp) {
9155 /* If we were run as 'hush &', sleep until we are
9156 * in the foreground (tty pgrp == our pgrp).
9157 * If we get started under a job aware app (like bash),
9158 * make sure we are now in charge so we don't fight over
9159 * who gets the foreground */
9161 pid_t shell_pgrp = getpgrp();
9162 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9163 if (G_saved_tty_pgrp == shell_pgrp)
9165 /* send TTIN to ourself (should stop us) */
9166 kill(- shell_pgrp, SIGTTIN);
9170 /* Install more signal handlers */
9171 install_special_sighandlers();
9173 if (G_saved_tty_pgrp) {
9174 /* Set other signals to restore saved_tty_pgrp */
9175 install_fatal_sighandlers();
9176 /* Put ourselves in our own process group
9177 * (bash, too, does this only if ctty is available) */
9178 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9179 /* Grab control of the terminal */
9180 tcsetpgrp(G_interactive_fd, getpid());
9182 enable_restore_tty_pgrp_on_exit();
9184 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9186 const char *hp = get_local_var_value("HISTFILE");
9188 hp = get_local_var_value("HOME");
9190 hp = concat_path_file(hp, ".hush_history");
9195 G.line_input_state->hist_file = hp;
9196 //set_local_var(xasprintf("HISTFILE=%s", ...));
9198 # if ENABLE_FEATURE_SH_HISTFILESIZE
9199 hp = get_local_var_value("HISTFILESIZE");
9200 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9205 install_special_sighandlers();
9207 #elif ENABLE_HUSH_INTERACTIVE
9208 /* No job control compiled in, only prompt/line editing */
9209 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
9210 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
9211 if (G_interactive_fd < 0) {
9212 /* try to dup to any fd */
9213 G_interactive_fd = dup(STDIN_FILENO);
9214 if (G_interactive_fd < 0)
9216 G_interactive_fd = 0;
9219 if (G_interactive_fd) {
9220 close_on_exec_on(G_interactive_fd);
9222 install_special_sighandlers();
9224 /* We have interactiveness code disabled */
9225 install_special_sighandlers();
9228 * if interactive but not a login shell, sources ~/.bashrc
9229 * (--norc turns this off, --rcfile <file> overrides)
9232 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
9233 /* note: ash and hush share this string */
9234 printf("\n\n%s %s\n"
9235 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9238 "hush - the humble shell"
9242 parse_and_run_file(stdin);
9245 hush_exit(G.last_exitcode);
9252 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
9257 #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
9258 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
9260 int argc = string_array_len(argv);
9261 return applet_main_func(argc, argv);
9264 #if ENABLE_HUSH_TEST || BASH_TEST2
9265 static int FAST_FUNC builtin_test(char **argv)
9267 return run_applet_main(argv, test_main);
9270 #if ENABLE_HUSH_ECHO
9271 static int FAST_FUNC builtin_echo(char **argv)
9273 return run_applet_main(argv, echo_main);
9276 #if ENABLE_HUSH_PRINTF
9277 static int FAST_FUNC builtin_printf(char **argv)
9279 return run_applet_main(argv, printf_main);
9283 #if ENABLE_HUSH_HELP
9284 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9286 const struct built_in_command *x;
9289 "Built-in commands:\n"
9290 "------------------\n");
9291 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9293 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9295 return EXIT_SUCCESS;
9299 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9300 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9302 show_history(G.line_input_state);
9303 return EXIT_SUCCESS;
9307 static char **skip_dash_dash(char **argv)
9310 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9315 static int FAST_FUNC builtin_cd(char **argv)
9319 argv = skip_dash_dash(argv);
9321 if (newdir == NULL) {
9322 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
9323 * bash says "bash: cd: HOME not set" and does nothing
9326 const char *home = get_local_var_value("HOME");
9327 newdir = home ? home : "/";
9329 if (chdir(newdir)) {
9330 /* Mimic bash message exactly */
9331 bb_perror_msg("cd: %s", newdir);
9332 return EXIT_FAILURE;
9334 /* Read current dir (get_cwd(1) is inside) and set PWD.
9335 * Note: do not enforce exporting. If PWD was unset or unexported,
9336 * set it again, but do not export. bash does the same.
9338 set_pwd_var(/*flag:*/ 0);
9339 return EXIT_SUCCESS;
9342 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9345 return EXIT_SUCCESS;
9348 static int FAST_FUNC builtin_eval(char **argv)
9350 int rcode = EXIT_SUCCESS;
9352 argv = skip_dash_dash(argv);
9357 /* "The eval utility shall construct a command by
9358 * concatenating arguments together, separating
9359 * each with a <space> character."
9365 len += strlen(*pp) + 1;
9367 str = p = xmalloc(len);
9377 * eval "echo Hi; done" ("done" is syntax error):
9378 * "echo Hi" will not execute too.
9380 parse_and_run_string(str ? str : argv[0]);
9382 rcode = G.last_exitcode;
9387 static int FAST_FUNC builtin_exec(char **argv)
9389 argv = skip_dash_dash(argv);
9390 if (argv[0] == NULL)
9391 return EXIT_SUCCESS; /* bash does this */
9393 /* Careful: we can end up here after [v]fork. Do not restore
9394 * tty pgrp then, only top-level shell process does that */
9395 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9396 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9398 /* Saved-redirect fds, script fds and G_interactive_fd are still
9399 * open here. However, they are all CLOEXEC, and execv below
9400 * closes them. Try interactive "exec ls -l /proc/self/fd",
9401 * it should show no extra open fds in the "ls" process.
9402 * If we'd try to run builtins/NOEXECs, this would need improving.
9404 //close_saved_fds_and_FILE_fds();
9406 /* TODO: if exec fails, bash does NOT exit! We do.
9407 * We'll need to undo trap cleanup (it's inside execvp_or_die)
9408 * and tcsetpgrp, and this is inherently racy.
9410 execvp_or_die(argv);
9413 static int FAST_FUNC builtin_exit(char **argv)
9415 debug_printf_exec("%s()\n", __func__);
9417 /* interactive bash:
9418 * # trap "echo EEE" EXIT
9421 * There are stopped jobs.
9422 * (if there are _stopped_ jobs, running ones don't count)
9425 * EEE (then bash exits)
9427 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
9430 /* note: EXIT trap is run by hush_exit */
9431 argv = skip_dash_dash(argv);
9432 if (argv[0] == NULL)
9433 hush_exit(G.last_exitcode);
9434 /* mimic bash: exit 123abc == exit 255 + error msg */
9435 xfunc_error_retval = 255;
9436 /* bash: exit -2 == exit 254, no error msg */
9437 hush_exit(xatoi(argv[0]) & 0xff);
9440 #if ENABLE_HUSH_TYPE
9441 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9442 static int FAST_FUNC builtin_type(char **argv)
9444 int ret = EXIT_SUCCESS;
9450 if (0) {} /* make conditional compile easier below */
9451 /*else if (find_alias(*argv))
9452 type = "an alias";*/
9453 #if ENABLE_HUSH_FUNCTIONS
9454 else if (find_function(*argv))
9455 type = "a function";
9457 else if (find_builtin(*argv))
9458 type = "a shell builtin";
9459 else if ((path = find_in_path(*argv)) != NULL)
9462 bb_error_msg("type: %s: not found", *argv);
9467 printf("%s is %s\n", *argv, type);
9475 #if ENABLE_HUSH_READ
9476 /* Interruptibility of read builtin in bash
9477 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9479 * Empty trap makes read ignore corresponding signal, for any signal.
9482 * - terminates non-interactive shell;
9483 * - interrupts read in interactive shell;
9484 * if it has non-empty trap:
9485 * - executes trap and returns to command prompt in interactive shell;
9486 * - executes trap and returns to read in non-interactive shell;
9488 * - is ignored (does not interrupt) read in interactive shell;
9489 * - terminates non-interactive shell;
9490 * if it has non-empty trap:
9491 * - executes trap and returns to read;
9493 * - terminates shell (regardless of interactivity);
9494 * if it has non-empty trap:
9495 * - executes trap and returns to read;
9496 * SIGCHLD from children:
9497 * - does not interrupt read regardless of interactivity:
9498 * try: sleep 1 & read x; echo $x
9500 static int FAST_FUNC builtin_read(char **argv)
9507 char *opt_d = NULL; /* optimized out if !BASH */
9511 /* "!": do not abort on errors.
9512 * Option string must start with "sr" to match BUILTIN_READ_xxx
9514 read_flags = getopt32(argv,
9516 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9518 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9521 if (read_flags == (uint32_t)-1)
9522 return EXIT_FAILURE;
9524 ifs = get_local_var_value("IFS"); /* can be NULL */
9527 r = shell_builtin_read(set_local_var_from_halves,
9538 if ((uintptr_t)r == 1 && errno == EINTR) {
9539 unsigned sig = check_and_run_traps();
9544 if ((uintptr_t)r > 1) {
9545 bb_error_msg("%s", r);
9546 r = (char*)(uintptr_t)1;
9549 return (uintptr_t)r;
9553 #if ENABLE_HUSH_UMASK
9554 static int FAST_FUNC builtin_umask(char **argv)
9561 argv = skip_dash_dash(argv);
9563 mode_t old_mask = mask;
9565 /* numeric umasks are taken as-is */
9566 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9567 if (!isdigit(argv[0][0]))
9569 mask = bb_parse_mode(argv[0], mask);
9570 if (!isdigit(argv[0][0]))
9572 if ((unsigned)mask > 0777) {
9575 * bash: umask: 'q': invalid symbolic mode operator
9576 * bash: umask: 999: octal number out of range
9578 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9583 printf("%04o\n", (unsigned) mask);
9584 /* fall through and restore mask which we set to 0 */
9588 return !rc; /* rc != 0 - success */
9592 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
9593 static void print_escaped(const char *s)
9598 const char *p = strchrnul(s, '\'');
9599 /* print 'xxxx', possibly just '' */
9600 printf("'%.*s'", (int)(p - s), s);
9605 /* s points to '; print "'''...'''" */
9607 do putchar('\''); while (*++s == '\'');
9613 #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
9614 static int helper_export_local(char **argv, unsigned flags)
9618 char *name_end = strchrnul(name, '=');
9620 /* So far we do not check that name is valid (TODO?) */
9622 if (*name_end == '\0') {
9623 struct variable *var, **vpp;
9625 vpp = get_ptr_to_local_var(name, name_end - name);
9626 var = vpp ? *vpp : NULL;
9628 if (flags & SETFLAG_UNEXPORT) {
9629 /* export -n NAME (without =VALUE) */
9631 var->flg_export = 0;
9632 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9634 } /* else: export -n NOT_EXISTING_VAR: no-op */
9637 if (flags & SETFLAG_EXPORT) {
9638 /* export NAME (without =VALUE) */
9640 var->flg_export = 1;
9641 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9642 putenv(var->varstr);
9646 if (flags & SETFLAG_MAKE_RO) {
9647 /* readonly NAME (without =VALUE) */
9649 var->flg_read_only = 1;
9653 # if ENABLE_HUSH_LOCAL
9654 /* Is this "local" bltin? */
9655 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9656 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
9657 if (var && var->func_nest_level == lvl) {
9658 /* "local x=abc; ...; local x" - ignore second local decl */
9663 /* Exporting non-existing variable.
9664 * bash does not put it in environment,
9665 * but remembers that it is exported,
9666 * and does put it in env when it is set later.
9667 * We just set it to "" and export.
9669 /* Or, it's "local NAME" (without =VALUE).
9670 * bash sets the value to "".
9672 /* Or, it's "readonly NAME" (without =VALUE).
9673 * bash remembers NAME and disallows its creation
9676 name = xasprintf("%s=", name);
9678 /* (Un)exporting/making local NAME=VALUE */
9679 name = xstrdup(name);
9681 if (set_local_var(name, flags))
9682 return EXIT_FAILURE;
9684 return EXIT_SUCCESS;
9688 #if ENABLE_HUSH_EXPORT
9689 static int FAST_FUNC builtin_export(char **argv)
9691 unsigned opt_unexport;
9693 #if ENABLE_HUSH_EXPORT_N
9694 /* "!": do not abort on errors */
9695 opt_unexport = getopt32(argv, "!n");
9696 if (opt_unexport == (uint32_t)-1)
9697 return EXIT_FAILURE;
9704 if (argv[0] == NULL) {
9711 /* ash emits: export VAR='VAL'
9712 * bash: declare -x VAR="VAL"
9713 * we follow ash example */
9714 const char *s = *e++;
9715 const char *p = strchr(s, '=');
9717 if (!p) /* wtf? take next variable */
9720 printf("export %.*s", (int)(p - s) + 1, s);
9721 print_escaped(p + 1);
9725 /*fflush_all(); - done after each builtin anyway */
9727 return EXIT_SUCCESS;
9730 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
9734 #if ENABLE_HUSH_LOCAL
9735 static int FAST_FUNC builtin_local(char **argv)
9737 if (G.func_nest_level == 0) {
9738 bb_error_msg("%s: not in a function", argv[0]);
9739 return EXIT_FAILURE; /* bash compat */
9742 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
9746 #if ENABLE_HUSH_READONLY
9747 static int FAST_FUNC builtin_readonly(char **argv)
9750 if (*argv == NULL) {
9751 /* bash: readonly [-p]: list all readonly VARs
9752 * (-p has no effect in bash)
9755 for (e = G.top_var; e; e = e->next) {
9756 if (e->flg_read_only) {
9757 //TODO: quote value: readonly VAR='VAL'
9758 printf("readonly %s\n", e->varstr);
9761 return EXIT_SUCCESS;
9763 return helper_export_local(argv, SETFLAG_MAKE_RO);
9767 #if ENABLE_HUSH_UNSET
9768 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9769 static int FAST_FUNC builtin_unset(char **argv)
9774 /* "!": do not abort on errors */
9775 /* "+": stop at 1st non-option */
9776 opts = getopt32(argv, "!+vf");
9777 if (opts == (unsigned)-1)
9778 return EXIT_FAILURE;
9780 bb_error_msg("unset: -v and -f are exclusive");
9781 return EXIT_FAILURE;
9787 if (!(opts & 2)) { /* not -f */
9788 if (unset_local_var(*argv)) {
9789 /* unset <nonexistent_var> doesn't fail.
9790 * Error is when one tries to unset RO var.
9791 * Message was printed by unset_local_var. */
9795 # if ENABLE_HUSH_FUNCTIONS
9807 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9808 * built-in 'set' handler
9810 * set [-abCefhmnuvx] [-o option] [argument...]
9811 * set [+abCefhmnuvx] [+o option] [argument...]
9812 * set -- [argument...]
9815 * Implementations shall support the options in both their hyphen and
9816 * plus-sign forms. These options can also be specified as options to sh.
9818 * Write out all variables and their values: set
9819 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9820 * Turn on the -x and -v options: set -xv
9821 * Unset all positional parameters: set --
9822 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9823 * Set the positional parameters to the expansion of x, even if x expands
9824 * with a leading '-' or '+': set -- $x
9826 * So far, we only support "set -- [argument...]" and some of the short names.
9828 static int FAST_FUNC builtin_set(char **argv)
9831 char **pp, **g_argv;
9832 char *arg = *++argv;
9836 for (e = G.top_var; e; e = e->next)
9838 return EXIT_SUCCESS;
9842 if (strcmp(arg, "--") == 0) {
9846 if (arg[0] != '+' && arg[0] != '-')
9848 for (n = 1; arg[n]; ++n) {
9849 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9851 if (arg[n] == 'o' && argv[1])
9854 } while ((arg = *++argv) != NULL);
9855 /* Now argv[0] is 1st argument */
9858 return EXIT_SUCCESS;
9861 /* NB: G.global_argv[0] ($0) is never freed/changed */
9862 g_argv = G.global_argv;
9863 if (G.global_args_malloced) {
9869 G.global_args_malloced = 1;
9870 pp = xzalloc(sizeof(pp[0]) * 2);
9871 pp[0] = g_argv[0]; /* retain $0 */
9874 /* This realloc's G.global_argv */
9875 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9877 G.global_argc = 1 + string_array_len(pp + 1);
9879 return EXIT_SUCCESS;
9881 /* Nothing known, so abort */
9883 bb_error_msg("set: %s: invalid option", arg);
9884 return EXIT_FAILURE;
9888 static int FAST_FUNC builtin_shift(char **argv)
9891 argv = skip_dash_dash(argv);
9893 n = bb_strtou(argv[0], NULL, 10);
9894 if (errno || n < 0) {
9895 /* shared string with ash.c */
9896 bb_error_msg("Illegal number: %s", argv[0]);
9898 * ash aborts in this case.
9899 * bash prints error message and set $? to 1.
9900 * Interestingly, for "shift 99999" bash does not
9901 * print error message, but does set $? to 1
9902 * (and does no shifting at all).
9906 if (n >= 0 && n < G.global_argc) {
9907 if (G_global_args_malloced) {
9910 free(G.global_argv[m++]);
9913 memmove(&G.global_argv[1], &G.global_argv[n+1],
9914 G.global_argc * sizeof(G.global_argv[0]));
9915 return EXIT_SUCCESS;
9917 return EXIT_FAILURE;
9920 #if ENABLE_HUSH_GETOPTS
9921 static int FAST_FUNC builtin_getopts(char **argv)
9923 /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
9926 If a required argument is not found, and getopts is not silent,
9927 a question mark (?) is placed in VAR, OPTARG is unset, and a
9928 diagnostic message is printed. If getopts is silent, then a
9929 colon (:) is placed in VAR and OPTARG is set to the option
9932 Test that VAR is a valid variable name?
9934 "Whenever the shell is invoked, OPTIND shall be initialized to 1"
9937 const char *cp, *optstring, *var;
9938 int c, n, exitcode, my_opterr;
9941 optstring = *++argv;
9942 if (!optstring || !(var = *++argv)) {
9943 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
9944 return EXIT_FAILURE;
9948 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
9950 argv = G.global_argv;
9954 if (optstring[0] != ':') {
9955 cp = get_local_var_value("OPTERR");
9956 /* 0 if "OPTERR=0", 1 otherwise */
9957 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
9960 /* getopts stops on first non-option. Add "+" to force that */
9961 /*if (optstring[0] != '+')*/ {
9962 char *s = alloca(strlen(optstring) + 2);
9963 sprintf(s, "+%s", optstring);
9967 /* Naively, now we should just
9968 * cp = get_local_var_value("OPTIND");
9969 * optind = cp ? atoi(cp) : 0;
9971 * opterr = my_opterr;
9972 * c = getopt(string_array_len(argv), argv, optstring);
9973 * and be done? Not so fast...
9974 * Unlike normal getopt() usage in C programs, here
9975 * each successive call will (usually) have the same argv[] CONTENTS,
9976 * but not the ADDRESSES. Worse yet, it's possible that between
9977 * invocations of "getopts", there will be calls to shell builtins
9978 * which use getopt() internally. Example:
9979 * while getopts "abc" RES -a -bc -abc de; do
9982 * This would not work correctly: getopt() call inside "unset"
9983 * modifies internal libc state which is tracking position in
9984 * multi-option strings ("-abc"). At best, it can skip options
9985 * or return the same option infinitely. With glibc implementation
9986 * of getopt(), it would use outright invalid pointers and return
9987 * garbage even _without_ "unset" mangling internal state.
9989 * We resort to resetting getopt() state and calling it N times,
9990 * until we get Nth result (or failure).
9991 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
9995 n = string_array_len(argv);
9998 opterr = (count < G.getopt_count) ? 0 : my_opterr;
9999 c = getopt(n, argv, optstring);
10003 } while (count <= G.getopt_count);
10005 /* Set OPTIND. Prevent resetting of the magic counter! */
10006 set_local_var_from_halves("OPTIND", utoa(optind));
10007 G.getopt_count = count; /* "next time, give me N+1'th result" */
10008 GETOPT_RESET(); /* just in case */
10011 /* Always set or unset, never left as-is, even on exit/error:
10012 * "If no option was found, or if the option that was found
10013 * does not have an option-argument, OPTARG shall be unset."
10017 /* If ":optstring" and unknown option is seen,
10018 * it is stored to OPTARG.
10020 if (optstring[1] == ':') {
10026 set_local_var_from_halves("OPTARG", cp);
10028 unset_local_var("OPTARG");
10030 /* Convert -1 to "?" */
10031 exitcode = EXIT_SUCCESS;
10032 if (c < 0) { /* -1: end of options */
10033 exitcode = EXIT_FAILURE;
10039 set_local_var_from_halves(var, cbuf);
10045 static int FAST_FUNC builtin_source(char **argv)
10047 char *arg_path, *filename;
10050 char *args_need_save;
10051 #if ENABLE_HUSH_FUNCTIONS
10055 argv = skip_dash_dash(argv);
10056 filename = argv[0];
10058 /* bash says: "bash: .: filename argument required" */
10059 return 2; /* bash compat */
10062 if (!strchr(filename, '/')) {
10063 arg_path = find_in_path(filename);
10065 filename = arg_path;
10067 input = remember_FILE(fopen_or_warn(filename, "r"));
10070 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10071 /* POSIX: non-interactive shell should abort here,
10072 * not merely fail. So far no one complained :)
10074 return EXIT_FAILURE;
10077 #if ENABLE_HUSH_FUNCTIONS
10078 sv_flg = G_flag_return_in_progress;
10079 /* "we are inside sourced file, ok to use return" */
10080 G_flag_return_in_progress = -1;
10082 args_need_save = argv[1]; /* used as a boolean variable */
10083 if (args_need_save)
10084 save_and_replace_G_args(&sv, argv);
10086 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10087 G.last_exitcode = 0;
10088 parse_and_run_file(input);
10089 fclose_and_forget(input);
10091 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10092 restore_G_args(&sv, argv);
10093 #if ENABLE_HUSH_FUNCTIONS
10094 G_flag_return_in_progress = sv_flg;
10097 return G.last_exitcode;
10100 #if ENABLE_HUSH_TRAP
10101 static int FAST_FUNC builtin_trap(char **argv)
10107 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
10112 /* No args: print all trapped */
10113 for (i = 0; i < NSIG; ++i) {
10115 printf("trap -- ");
10116 print_escaped(G_traps[i]);
10117 /* note: bash adds "SIG", but only if invoked
10118 * as "bash". If called as "sh", or if set -o posix,
10119 * then it prints short signal names.
10120 * We are printing short names: */
10121 printf(" %s\n", get_signame(i));
10124 /*fflush_all(); - done after each builtin anyway */
10125 return EXIT_SUCCESS;
10129 /* If first arg is a number: reset all specified signals */
10130 sig = bb_strtou(*argv, NULL, 10);
10134 ret = EXIT_SUCCESS;
10136 sighandler_t handler;
10138 sig = get_signum(*argv++);
10140 ret = EXIT_FAILURE;
10141 /* Mimic bash message exactly */
10142 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
10146 free(G_traps[sig]);
10147 G_traps[sig] = xstrdup(new_cmd);
10149 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
10150 get_signame(sig), sig, G_traps[sig]);
10152 /* There is no signal for 0 (EXIT) */
10157 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10159 /* We are removing trap handler */
10160 handler = pick_sighandler(sig);
10161 install_sighandler(sig, handler);
10166 if (!argv[1]) { /* no second arg */
10167 bb_error_msg("trap: invalid arguments");
10168 return EXIT_FAILURE;
10171 /* First arg is "-": reset all specified to default */
10172 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10173 /* Everything else: set arg as signal handler
10174 * (includes "" case, which ignores signal) */
10175 if (argv[0][0] == '-') {
10176 if (argv[0][1] == '\0') { /* "-" */
10177 /* new_cmd remains NULL: "reset these sigs" */
10180 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10183 /* else: "-something", no special meaning */
10188 goto process_sig_list;
10192 #if ENABLE_HUSH_JOB
10193 static struct pipe *parse_jobspec(const char *str)
10198 if (sscanf(str, "%%%u", &jobnum) != 1) {
10200 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10202 bb_error_msg("bad argument '%s'", str);
10205 /* It is "%%", "%+" or "%" - current job */
10206 jobnum = G.last_jobid;
10208 bb_error_msg("no current job");
10212 for (pi = G.job_list; pi; pi = pi->next) {
10213 if (pi->jobid == jobnum) {
10217 bb_error_msg("%u: no such job", jobnum);
10221 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10224 const char *status_string;
10226 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10227 for (job = G.job_list; job; job = job->next) {
10228 if (job->alive_cmds == job->stopped_cmds)
10229 status_string = "Stopped";
10231 status_string = "Running";
10233 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10236 clean_up_last_dead_job();
10238 return EXIT_SUCCESS;
10241 /* built-in 'fg' and 'bg' handler */
10242 static int FAST_FUNC builtin_fg_bg(char **argv)
10247 if (!G_interactive_fd)
10248 return EXIT_FAILURE;
10250 /* If they gave us no args, assume they want the last backgrounded task */
10252 for (pi = G.job_list; pi; pi = pi->next) {
10253 if (pi->jobid == G.last_jobid) {
10257 bb_error_msg("%s: no current job", argv[0]);
10258 return EXIT_FAILURE;
10261 pi = parse_jobspec(argv[1]);
10263 return EXIT_FAILURE;
10265 /* TODO: bash prints a string representation
10266 * of job being foregrounded (like "sleep 1 | cat") */
10267 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
10268 /* Put the job into the foreground. */
10269 tcsetpgrp(G_interactive_fd, pi->pgrp);
10272 /* Restart the processes in the job */
10273 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10274 for (i = 0; i < pi->num_cmds; i++) {
10275 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
10277 pi->stopped_cmds = 0;
10279 i = kill(- pi->pgrp, SIGCONT);
10281 if (errno == ESRCH) {
10282 delete_finished_job(pi);
10283 return EXIT_SUCCESS;
10285 bb_perror_msg("kill (SIGCONT)");
10288 if (argv[0][0] == 'f') {
10289 remove_job_from_table(pi); /* FG job shouldn't be in job table */
10290 return checkjobs_and_fg_shell(pi);
10292 return EXIT_SUCCESS;
10296 #if ENABLE_HUSH_KILL
10297 static int FAST_FUNC builtin_kill(char **argv)
10301 # if ENABLE_HUSH_JOB
10302 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10310 if (argv[i][0] != '%')
10313 * "kill %N" - job kill
10314 * Converting to pgrp / pid kill
10316 pi = parse_jobspec(argv[i]);
10318 /* Eat bad jobspec */
10322 argv[j - 1] = argv[j];
10329 * In jobs started under job control, we signal
10330 * entire process group by kill -PGRP_ID.
10331 * This happens, f.e., in interactive shell.
10333 * Otherwise, we signal each child via
10334 * kill PID1 PID2 PID3.
10336 * sh -c 'sleep 1|sleep 1 & kill %1'
10337 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10338 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10340 n = G_interactive_fd ? 1 : pi->num_cmds;
10341 dst = alloca(n * sizeof(int)*4);
10343 if (G_interactive_fd)
10344 dst += sprintf(dst, " -%u", (int)pi->pgrp);
10345 else for (j = 0; j < n; j++) {
10346 struct command *cmd = &pi->cmds[j];
10347 /* Skip exited members of the job */
10351 * kill_main has matching code to expect
10352 * leading space. Needed to not confuse
10353 * negative pids with "kill -SIGNAL_NO" syntax
10355 dst += sprintf(dst, " %u", (int)cmd->pid);
10358 } while (argv[++i]);
10362 if (argv[1] || ret == 0) {
10363 ret = run_applet_main(argv, kill_main);
10365 /* else: ret = 1, "kill %bad_jobspec" case */
10370 #if ENABLE_HUSH_WAIT
10371 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
10372 #if !ENABLE_HUSH_JOB
10373 # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10375 static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
10382 if (!sigisemptyset(&G.pending_set))
10385 /* waitpid is not interruptible by SA_RESTARTed
10386 * signals which we use. Thus, this ugly dance:
10389 /* Make sure possible SIGCHLD is stored in kernel's
10390 * pending signal mask before we call waitpid.
10391 * Or else we may race with SIGCHLD, lose it,
10392 * and get stuck in sigsuspend...
10394 sigfillset(&oldset); /* block all signals, remember old set */
10395 sigprocmask(SIG_SETMASK, &oldset, &oldset);
10397 if (!sigisemptyset(&G.pending_set)) {
10398 /* Crap! we raced with some signal! */
10402 /*errno = 0; - checkjobs does this */
10403 /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
10404 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
10405 debug_printf_exec("checkjobs:%d\n", ret);
10406 #if ENABLE_HUSH_JOB
10407 if (waitfor_pipe) {
10408 int rcode = job_exited_or_stopped(waitfor_pipe);
10409 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10412 sigprocmask(SIG_SETMASK, &oldset, NULL);
10417 /* if ECHILD, there are no children (ret is -1 or 0) */
10418 /* if ret == 0, no children changed state */
10419 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
10420 if (errno == ECHILD || ret) {
10422 if (ret < 0) /* if ECHILD, may need to fix "ret" */
10424 sigprocmask(SIG_SETMASK, &oldset, NULL);
10427 /* Wait for SIGCHLD or any other signal */
10428 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10429 /* Note: sigsuspend invokes signal handler */
10430 sigsuspend(&oldset);
10432 sigprocmask(SIG_SETMASK, &oldset, NULL);
10434 /* So, did we get a signal? */
10435 sig = check_and_run_traps();
10436 if (sig /*&& sig != SIGCHLD - always true */) {
10437 /* Do this for any (non-ignored) signal, not only for ^C */
10441 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10446 static int FAST_FUNC builtin_wait(char **argv)
10451 argv = skip_dash_dash(argv);
10452 if (argv[0] == NULL) {
10453 /* Don't care about wait results */
10454 /* Note 1: must wait until there are no more children */
10455 /* Note 2: must be interruptible */
10457 * $ sleep 3 & sleep 6 & wait
10458 * [1] 30934 sleep 3
10459 * [2] 30935 sleep 6
10462 * $ sleep 3 & sleep 6 & wait
10463 * [1] 30936 sleep 3
10464 * [2] 30937 sleep 6
10466 * ^C <-- after ~4 sec from keyboard
10469 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
10473 pid_t pid = bb_strtou(*argv, NULL, 10);
10474 if (errno || pid <= 0) {
10475 #if ENABLE_HUSH_JOB
10476 if (argv[0][0] == '%') {
10477 struct pipe *wait_pipe;
10478 ret = 127; /* bash compat for bad jobspecs */
10479 wait_pipe = parse_jobspec(*argv);
10481 ret = job_exited_or_stopped(wait_pipe);
10483 ret = wait_for_child_or_signal(wait_pipe, 0);
10485 /* waiting on "last dead job" removes it */
10486 clean_up_last_dead_job();
10489 /* else: parse_jobspec() already emitted error msg */
10493 /* mimic bash message */
10494 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
10495 ret = EXIT_FAILURE;
10496 continue; /* bash checks all argv[] */
10499 /* Do we have such child? */
10500 ret = waitpid(pid, &status, WNOHANG);
10504 if (errno == ECHILD) {
10505 if (pid == G.last_bg_pid) {
10506 /* "wait $!" but last bg task has already exited. Try:
10507 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10508 * In bash it prints exitcode 0, then 3.
10509 * In dash, it is 127.
10511 ret = G.last_bg_pid_exitcode;
10513 /* Example: "wait 1". mimic bash message */
10514 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
10518 bb_perror_msg("wait %s", *argv);
10520 continue; /* bash checks all argv[] */
10523 /* Yes, and it still runs */
10524 ret = wait_for_child_or_signal(NULL, pid);
10526 /* Yes, and it just exited */
10527 process_wait_result(NULL, pid, status);
10528 ret = WEXITSTATUS(status);
10529 if (WIFSIGNALED(status))
10530 ret = 128 + WTERMSIG(status);
10538 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10539 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10542 def = bb_strtou(argv[1], NULL, 10);
10543 if (errno || def < def_min || argv[2]) {
10544 bb_error_msg("%s: bad arguments", argv[0]);
10552 #if ENABLE_HUSH_LOOPS
10553 static int FAST_FUNC builtin_break(char **argv)
10556 if (G.depth_of_loop == 0) {
10557 bb_error_msg("%s: only meaningful in a loop", argv[0]);
10558 /* if we came from builtin_continue(), need to undo "= 1" */
10559 G.flag_break_continue = 0;
10560 return EXIT_SUCCESS; /* bash compat */
10562 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
10564 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10565 if (depth == UINT_MAX)
10566 G.flag_break_continue = BC_BREAK;
10567 if (G.depth_of_loop < depth)
10568 G.depth_break_continue = G.depth_of_loop;
10570 return EXIT_SUCCESS;
10573 static int FAST_FUNC builtin_continue(char **argv)
10575 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10576 return builtin_break(argv);
10580 #if ENABLE_HUSH_FUNCTIONS
10581 static int FAST_FUNC builtin_return(char **argv)
10585 if (G_flag_return_in_progress != -1) {
10586 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10587 return EXIT_FAILURE; /* bash compat */
10590 G_flag_return_in_progress = 1;
10593 * out of range: wraps around at 256, does not error out
10594 * non-numeric param:
10595 * f() { false; return qwe; }; f; echo $?
10596 * bash: return: qwe: numeric argument required <== we do this
10597 * 255 <== we also do this
10599 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10604 #if ENABLE_HUSH_TIMES
10605 static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10607 static const uint8_t times_tbl[] ALIGN1 = {
10608 ' ', offsetof(struct tms, tms_utime),
10609 '\n', offsetof(struct tms, tms_stime),
10610 ' ', offsetof(struct tms, tms_cutime),
10611 '\n', offsetof(struct tms, tms_cstime),
10618 clk_tck = bb_clk_tck();
10623 unsigned sec, frac;
10625 t = *(clock_t *)(((char *) &buf) + p[1]);
10627 frac = t % clk_tck;
10628 printf("%um%u.%03us%c",
10629 sec / 60, sec % 60,
10630 (frac * 1000) / clk_tck,
10635 return EXIT_SUCCESS;
10639 #if ENABLE_HUSH_MEMLEAK
10640 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10645 # ifdef M_TRIM_THRESHOLD
10646 /* Optional. Reduces probability of false positives */
10649 /* Crude attempt to find where "free memory" starts,
10650 * sans fragmentation. */
10652 l = (unsigned long)p;
10655 if (l < (unsigned long)p) l = (unsigned long)p;
10661 struct mallinfo mi = mallinfo();
10662 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10663 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10667 if (!G.memleak_value)
10668 G.memleak_value = l;
10670 l -= G.memleak_value;
10677 /* Exitcode is "how many kilobytes we leaked since 1st call" */