1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
87 # include <malloc.h> /* for malloc_trim */
90 /* #include <dmalloc.h> */
95 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
97 #include "shell_common.h"
100 #if ENABLE_HUSH_RANDOM_SUPPORT
103 # define CLEAR_RANDOM_T(rnd) ((void)0)
106 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
109 /* Not every libc has sighandler_t. Fix it */
110 typedef void (*hush_sighandler_t
)(int);
111 #define sighandler_t hush_sighandler_t
114 //config: bool "hush"
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
122 //config: It will compile and work on no-mmu systems.
124 //config: It does not handle select, aliases, tilde expansion,
125 //config: &>file and >&file redirection of stdout+stderr.
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
130 //config: depends on HUSH
132 //config: Enable bash-compatible extensions.
134 //config:config HUSH_BRACE_EXPANSION
135 //config: bool "Brace expansion"
137 //config: depends on HUSH_BASH_COMPAT
139 //config: Enable {abc,def} extension.
141 //config:config HUSH_HELP
142 //config: bool "help builtin"
144 //config: depends on HUSH
146 //config: Enable help builtin in hush. Code size + ~1 kbyte.
148 //config:config HUSH_INTERACTIVE
149 //config: bool "Interactive mode"
151 //config: depends on HUSH
153 //config: Enable interactive mode (prompt and command editing).
154 //config: Without this, hush simply reads and executes commands
155 //config: from stdin just like a shell script from a file.
156 //config: No prompt, no PS1/PS2 magic shell variables.
158 //config:config HUSH_SAVEHISTORY
159 //config: bool "Save command history to .hush_history"
161 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
163 //config: Enable history saving in hush.
165 //config:config HUSH_JOB
166 //config: bool "Job control"
168 //config: depends on HUSH_INTERACTIVE
170 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171 //config: command (not entire shell), fg/bg builtins work. Without this option,
172 //config: "cmd &" still works by simply spawning a process and immediately
173 //config: prompting for next command (or executing next command in a script),
174 //config: but no separate process group is formed.
176 //config:config HUSH_TICK
177 //config: bool "Process substitution"
179 //config: depends on HUSH
181 //config: Enable process substitution `command` and $(command) in hush.
183 //config:config HUSH_IF
184 //config: bool "Support if/then/elif/else/fi"
186 //config: depends on HUSH
188 //config: Enable if/then/elif/else/fi in hush.
190 //config:config HUSH_LOOPS
191 //config: bool "Support for, while and until loops"
193 //config: depends on HUSH
195 //config: Enable for, while and until loops in hush.
197 //config:config HUSH_CASE
198 //config: bool "Support case ... esac statement"
200 //config: depends on HUSH
202 //config: Enable case ... esac statement in hush. +400 bytes.
204 //config:config HUSH_FUNCTIONS
205 //config: bool "Support funcname() { commands; } syntax"
207 //config: depends on HUSH
209 //config: Enable support for shell functions in hush. +800 bytes.
211 //config:config HUSH_LOCAL
212 //config: bool "Support local builtin"
214 //config: depends on HUSH_FUNCTIONS
216 //config: Enable support for local variables in functions.
218 //config:config HUSH_RANDOM_SUPPORT
219 //config: bool "Pseudorandom generator and $RANDOM variable"
221 //config: depends on HUSH
223 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
226 //config:config HUSH_EXPORT_N
227 //config: bool "Support 'export -n' option"
229 //config: depends on HUSH
231 //config: export -n unexports variables. It is a bash extension.
233 //config:config HUSH_MODE_X
234 //config: bool "Support 'hush -x' option and 'set -x' command"
236 //config: depends on HUSH
238 //config: This instructs hush to print commands before execution.
239 //config: Adds ~300 bytes.
242 //config: bool "msh (deprecated: aliased to hush)"
244 //config: select HUSH
246 //config: msh is deprecated and will be removed, please migrate to hush.
249 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257 /* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
262 //usage:#define hush_trivial_usage
263 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
264 //usage:#define hush_full_usage "\n\n"
265 //usage: "Unix shell interpreter"
267 //usage:#define msh_trivial_usage hush_trivial_usage
268 //usage:#define msh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
271 //usage:# define sh_trivial_usage hush_trivial_usage
272 //usage:# define sh_full_usage hush_full_usage
274 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275 //usage:# define bash_trivial_usage hush_trivial_usage
276 //usage:# define bash_full_usage hush_full_usage
281 #define LEAK_HUNTING 0
282 #define BUILD_AS_NOMMU 0
283 /* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
288 /* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
294 #define ENABLE_HUSH_FAST 0
295 /* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
298 #define ENABLE_HUSH_DOLLAR_OPS 1
303 # undef USE_FOR_NOMMU
306 # define USE_FOR_NOMMU(...) __VA_ARGS__
307 # define USE_FOR_MMU(...)
310 #include "NUM_APPLETS.h"
312 /* STANDALONE does not make sense, and won't compile */
313 # undef CONFIG_FEATURE_SH_STANDALONE
314 # undef ENABLE_FEATURE_SH_STANDALONE
315 # undef IF_FEATURE_SH_STANDALONE
316 # undef IF_NOT_FEATURE_SH_STANDALONE
317 # define ENABLE_FEATURE_SH_STANDALONE 0
318 # define IF_FEATURE_SH_STANDALONE(...)
319 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
322 #if !ENABLE_HUSH_INTERACTIVE
323 # undef ENABLE_FEATURE_EDITING
324 # define ENABLE_FEATURE_EDITING 0
325 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
327 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
328 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
331 /* Do we support ANY keywords? */
332 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
333 # define HAS_KEYWORDS 1
334 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
335 # define IF_HAS_NO_KEYWORDS(...)
337 # define HAS_KEYWORDS 0
338 # define IF_HAS_KEYWORDS(...)
339 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
342 /* If you comment out one of these below, it will be #defined later
343 * to perform debug printfs to stderr: */
344 #define debug_printf(...) do {} while (0)
345 /* Finer-grained debug switches */
346 #define debug_printf_parse(...) do {} while (0)
347 #define debug_print_tree(a, b) do {} while (0)
348 #define debug_printf_exec(...) do {} while (0)
349 #define debug_printf_env(...) do {} while (0)
350 #define debug_printf_jobs(...) do {} while (0)
351 #define debug_printf_expand(...) do {} while (0)
352 #define debug_printf_varexp(...) do {} while (0)
353 #define debug_printf_glob(...) do {} while (0)
354 #define debug_printf_list(...) do {} while (0)
355 #define debug_printf_subst(...) do {} while (0)
356 #define debug_printf_clean(...) do {} while (0)
358 #define ERR_PTR ((void*)(long)1)
360 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
362 #define _SPECIAL_VARS_STR "_*@$!?#"
363 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
364 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
365 #if ENABLE_HUSH_BASH_COMPAT
366 /* Support / and // replace ops */
367 /* Note that // is stored as \ in "encoded" string representation */
368 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
369 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
370 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
372 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
373 # define VAR_SUBST_OPS "%#:-=+?"
374 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
377 #define SPECIAL_VAR_SYMBOL 3
381 static const char hush_version_str
[] ALIGN1
= "HUSH_VERSION="BB_VER
;
383 /* This supports saving pointers malloced in vfork child,
384 * to be freed in the parent.
387 typedef struct nommu_save_t
{
389 struct variable
*old_vars
;
391 char **argv_from_re_execing
;
404 #if ENABLE_HUSH_LOOPS
411 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
416 /* three pseudo-keywords support contrived "case" syntax: */
417 RES_CASE_IN
, /* "case ... IN", turns into RES_MATCH when IN is observed */
418 RES_MATCH
, /* "word)" */
419 RES_CASE_BODY
, /* "this command is inside CASE" */
426 typedef struct o_string
{
428 int length
; /* position where data is appended */
431 /* At least some part of the string was inside '' or "",
432 * possibly empty one: word"", wo''rd etc. */
433 smallint has_quoted_part
;
434 smallint has_empty_slot
;
435 smallint o_assignment
; /* 0:maybe, 1:yes, 2:no */
438 EXP_FLAG_SINGLEWORD
= 0x80, /* must be 0x80 */
440 /* Protect newly added chars against globbing
441 * by prepending \ to *, ?, [, \ */
442 EXP_FLAG_ESC_GLOB_CHARS
= 0x1,
445 MAYBE_ASSIGNMENT
= 0,
446 DEFINITELY_ASSIGNMENT
= 1,
448 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
451 /* Used for initialization: o_string foo = NULL_O_STRING; */
452 #define NULL_O_STRING { NULL }
454 #ifndef debug_printf_parse
455 static const char *const assignment_flag
[] = {
457 "DEFINITELY_ASSIGNMENT",
463 typedef struct in_str
{
465 /* eof_flag=1: last char in ->p is really an EOF */
466 char eof_flag
; /* meaningless if ->p == NULL */
468 #if ENABLE_HUSH_INTERACTIVE
469 smallint promptmode
; /* 0: PS1, 1: PS2 */
473 int (*get
) (struct in_str
*) FAST_FUNC
;
474 int (*peek
) (struct in_str
*) FAST_FUNC
;
476 #define i_getch(input) ((input)->get(input))
477 #define i_peek(input) ((input)->peek(input))
479 /* The descrip member of this structure is only used to make
480 * debugging output pretty */
481 static const struct {
483 signed char default_fd
;
486 { O_RDONLY
, 0, "<" },
487 { O_CREAT
|O_TRUNC
|O_WRONLY
, 1, ">" },
488 { O_CREAT
|O_APPEND
|O_WRONLY
, 1, ">>" },
489 { O_CREAT
|O_RDWR
, 1, "<>" },
490 { O_RDONLY
, 0, "<<" },
491 /* Should not be needed. Bogus default_fd helps in debugging */
492 /* { O_RDONLY, 77, "<<" }, */
495 struct redir_struct
{
496 struct redir_struct
*next
;
497 char *rd_filename
; /* filename */
498 int rd_fd
; /* fd to redirect */
499 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
501 smallint rd_type
; /* (enum redir_type) */
502 /* note: for heredocs, rd_filename contains heredoc delimiter,
503 * and subsequently heredoc itself; and rd_dup is a bitmask:
504 * bit 0: do we need to trim leading tabs?
505 * bit 1: is heredoc quoted (<<'delim' syntax) ?
508 typedef enum redir_type
{
510 REDIRECT_OVERWRITE
= 1,
513 REDIRECT_HEREDOC
= 4,
514 REDIRECT_HEREDOC2
= 5, /* REDIRECT_HEREDOC after heredoc is loaded */
517 REDIRFD_SYNTAX_ERR
= -2,
518 REDIRFD_TO_FILE
= -1,
519 /* otherwise, rd_fd is redirected to rd_dup */
521 HEREDOC_SKIPTABS
= 1,
527 pid_t pid
; /* 0 if exited */
528 int assignment_cnt
; /* how many argv[i] are assignments? */
529 smallint cmd_type
; /* CMD_xxx */
531 #define CMD_SUBSHELL 1
532 #if ENABLE_HUSH_BASH_COMPAT
533 /* used for "[[ EXPR ]]" */
534 # define CMD_SINGLEWORD_NOGLOB 2
536 #if ENABLE_HUSH_FUNCTIONS
537 # define CMD_FUNCDEF 3
540 smalluint cmd_exitcode
;
541 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
544 char *group_as_string
;
546 #if ENABLE_HUSH_FUNCTIONS
547 struct function
*child_func
;
548 /* This field is used to prevent a bug here:
549 * while...do f1() {a;}; f1; f1() {b;}; f1; done
550 * When we execute "f1() {a;}" cmd, we create new function and clear
551 * cmd->group, cmd->group_as_string, cmd->argv[0].
552 * When we execute "f1() {b;}", we notice that f1 exists,
553 * and that its "parent cmd" struct is still "alive",
554 * we put those fields back into cmd->xxx
555 * (struct function has ->parent_cmd ptr to facilitate that).
556 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
557 * Without this trick, loop would execute a;b;b;b;...
558 * instead of correct sequence a;b;a;b;...
559 * When command is freed, it severs the link
560 * (sets ->child_func->parent_cmd to NULL).
563 char **argv
; /* command name and arguments */
564 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
565 * and on execution these are substituted with their values.
566 * Substitution can make _several_ words out of one argv[n]!
567 * Example: argv[0]=='.^C*^C.' here: echo .$*.
568 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
570 struct redir_struct
*redirects
; /* I/O redirections */
572 /* Is there anything in this command at all? */
573 #define IS_NULL_CMD(cmd) \
574 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
578 int num_cmds
; /* total number of commands in pipe */
579 int alive_cmds
; /* number of commands running (not exited) */
580 int stopped_cmds
; /* number of commands alive, but stopped */
582 int jobid
; /* job number */
583 pid_t pgrp
; /* process group ID for the job */
584 char *cmdtext
; /* name of job */
586 struct command
*cmds
; /* array of commands in pipe */
587 smallint followup
; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
588 IF_HAS_KEYWORDS(smallint pi_inverted
;) /* "! cmd | cmd" */
589 IF_HAS_KEYWORDS(smallint res_word
;) /* needed for if, for, while, until... */
591 typedef enum pipe_style
{
597 /* Is there anything in this pipe at all? */
598 #define IS_NULL_PIPE(pi) \
599 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
601 /* This holds pointers to the various results of parsing */
602 struct parse_context
{
603 /* linked list of pipes */
604 struct pipe
*list_head
;
605 /* last pipe (being constructed right now) */
607 /* last command in pipe (being constructed right now) */
608 struct command
*command
;
609 /* last redirect in command->redirects list */
610 struct redir_struct
*pending_redirect
;
616 smallint ctx_inverted
; /* "! cmd | cmd" */
618 smallint ctx_dsemicolon
; /* ";;" seen */
620 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
622 /* group we are enclosed in:
623 * example: "if pipe1; pipe2; then pipe3; fi"
624 * when we see "if" or "then", we malloc and copy current context,
625 * and make ->stack point to it. then we parse pipeN.
626 * when closing "then" / fi" / whatever is found,
627 * we move list_head into ->stack->command->group,
628 * copy ->stack into current context, and delete ->stack.
629 * (parsing of { list } and ( list ) doesn't use this method)
631 struct parse_context
*stack
;
635 /* On program start, environ points to initial environment.
636 * putenv adds new pointers into it, unsetenv removes them.
637 * Neither of these (de)allocates the strings.
638 * setenv allocates new strings in malloc space and does putenv,
639 * and thus setenv is unusable (leaky) for shell's purposes */
640 #define setenv(...) setenv_is_leaky_dont_use()
642 struct variable
*next
;
643 char *varstr
; /* points to "name=" portion */
644 #if ENABLE_HUSH_LOCAL
645 unsigned func_nest_level
;
647 int max_len
; /* if > 0, name is part of initial env; else name is malloced */
648 smallint flg_export
; /* putenv should be done on this var */
649 smallint flg_read_only
;
657 #if ENABLE_HUSH_FUNCTIONS
659 struct function
*next
;
661 struct command
*parent_cmd
;
664 char *body_as_string
;
670 /* set -/+o OPT support. (TODO: make it optional)
671 * bash supports the following opts:
682 * interactive-comments on
700 static const char o_opt_strings
[] ALIGN1
=
703 #if ENABLE_HUSH_MODE_X
710 #if ENABLE_HUSH_MODE_X
717 /* "Globals" within this file */
718 /* Sorted roughly by size (smaller offsets == smaller code) */
720 /* interactive_fd != 0 means we are an interactive shell.
721 * If we are, then saved_tty_pgrp can also be != 0, meaning
722 * that controlling tty is available. With saved_tty_pgrp == 0,
723 * job control still works, but terminal signals
724 * (^C, ^Z, ^Y, ^\) won't work at all, and background
725 * process groups can only be created with "cmd &".
726 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
727 * to give tty to the foreground process group,
728 * and will take it back when the group is stopped (^Z)
731 #if ENABLE_HUSH_INTERACTIVE
732 /* 'interactive_fd' is a fd# open to ctty, if we have one
733 * _AND_ if we decided to act interactively */
737 # define G_interactive_fd (G.interactive_fd)
739 # define G_interactive_fd 0
741 #if ENABLE_FEATURE_EDITING
742 line_input_t
*line_input_state
;
747 #if ENABLE_HUSH_RANDOM_SUPPORT
753 pid_t saved_tty_pgrp
;
754 struct pipe
*job_list
;
755 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
757 # define G_saved_tty_pgrp 0
759 char o_opt
[NUM_OPT_O
];
760 #if ENABLE_HUSH_MODE_X
761 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
765 smallint flag_SIGINT
;
766 #if ENABLE_HUSH_LOOPS
767 smallint flag_break_continue
;
769 #if ENABLE_HUSH_FUNCTIONS
770 /* 0: outside of a function (or sourced file)
771 * -1: inside of a function, ok to use return builtin
772 * 1: return is invoked, skip all till end of func
774 smallint flag_return_in_progress
;
776 smallint exiting
; /* used to prevent EXIT trap recursion */
777 /* These four support $?, $#, and $1 */
778 smalluint last_exitcode
;
779 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
780 smalluint global_args_malloced
;
781 /* how many non-NULL argv's we have. NB: $# + 1 */
785 char *argv0_for_re_execing
;
787 #if ENABLE_HUSH_LOOPS
788 unsigned depth_break_continue
;
789 unsigned depth_of_loop
;
793 struct variable
*top_var
;
794 char **expanded_assignments
;
795 #if ENABLE_HUSH_FUNCTIONS
796 struct function
*top_func
;
797 # if ENABLE_HUSH_LOCAL
798 struct variable
**shadowed_vars_pp
;
799 unsigned func_nest_level
;
802 /* Signal and trap handling */
804 unsigned count_SIGCHLD
;
805 unsigned handled_SIGCHLD
;
806 smallint we_have_children
;
808 /* Which signals have non-DFL handler (even with no traps set)?
809 * Set at the start to:
810 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
811 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
812 * The rest is cleared right before execv syscalls.
813 * Other than these two times, never modified.
815 unsigned special_sig_mask
;
817 unsigned fatal_sig_mask
;
818 # define G_fatal_sig_mask G.fatal_sig_mask
820 # define G_fatal_sig_mask 0
822 char **traps
; /* char *traps[NSIG] */
823 sigset_t pending_set
;
825 unsigned long memleak_value
;
829 char user_input_buf
[ENABLE_FEATURE_EDITING
? CONFIG_FEATURE_EDITING_MAX_LEN
: 2];
831 #define G (*ptr_to_globals)
832 /* Not #defining name to G.name - this quickly gets unwieldy
833 * (too many defines). Also, I actually prefer to see when a variable
834 * is global, thus "G." prefix is a useful hint */
835 #define INIT_G() do { \
836 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
837 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
838 sigfillset(&G.sa.sa_mask); \
839 G.sa.sa_flags = SA_RESTART; \
843 /* Function prototypes for builtins */
844 static int builtin_cd(char **argv
) FAST_FUNC
;
845 static int builtin_echo(char **argv
) FAST_FUNC
;
846 static int builtin_eval(char **argv
) FAST_FUNC
;
847 static int builtin_exec(char **argv
) FAST_FUNC
;
848 static int builtin_exit(char **argv
) FAST_FUNC
;
849 static int builtin_export(char **argv
) FAST_FUNC
;
851 static int builtin_fg_bg(char **argv
) FAST_FUNC
;
852 static int builtin_jobs(char **argv
) FAST_FUNC
;
855 static int builtin_help(char **argv
) FAST_FUNC
;
857 #if ENABLE_HUSH_LOCAL
858 static int builtin_local(char **argv
) FAST_FUNC
;
861 static int builtin_memleak(char **argv
) FAST_FUNC
;
864 static int builtin_printf(char **argv
) FAST_FUNC
;
866 static int builtin_pwd(char **argv
) FAST_FUNC
;
867 static int builtin_read(char **argv
) FAST_FUNC
;
868 static int builtin_set(char **argv
) FAST_FUNC
;
869 static int builtin_shift(char **argv
) FAST_FUNC
;
870 static int builtin_source(char **argv
) FAST_FUNC
;
871 static int builtin_test(char **argv
) FAST_FUNC
;
872 static int builtin_trap(char **argv
) FAST_FUNC
;
873 static int builtin_type(char **argv
) FAST_FUNC
;
874 static int builtin_true(char **argv
) FAST_FUNC
;
875 static int builtin_umask(char **argv
) FAST_FUNC
;
876 static int builtin_unset(char **argv
) FAST_FUNC
;
877 static int builtin_wait(char **argv
) FAST_FUNC
;
878 #if ENABLE_HUSH_LOOPS
879 static int builtin_break(char **argv
) FAST_FUNC
;
880 static int builtin_continue(char **argv
) FAST_FUNC
;
882 #if ENABLE_HUSH_FUNCTIONS
883 static int builtin_return(char **argv
) FAST_FUNC
;
886 /* Table of built-in functions. They can be forked or not, depending on
887 * context: within pipes, they fork. As simple commands, they do not.
888 * When used in non-forking context, they can change global variables
889 * in the parent shell process. If forked, of course they cannot.
890 * For example, 'unset foo | whatever' will parse and run, but foo will
891 * still be set at the end. */
892 struct built_in_command
{
894 int (*b_function
)(char **argv
) FAST_FUNC
;
897 # define BLTIN(cmd, func, help) { cmd, func, help }
899 # define BLTIN(cmd, func, help) { cmd, func }
903 static const struct built_in_command bltins1
[] = {
904 BLTIN("." , builtin_source
, "Run commands in a file"),
905 BLTIN(":" , builtin_true
, NULL
),
907 BLTIN("bg" , builtin_fg_bg
, "Resume a job in the background"),
909 #if ENABLE_HUSH_LOOPS
910 BLTIN("break" , builtin_break
, "Exit from a loop"),
912 BLTIN("cd" , builtin_cd
, "Change directory"),
913 #if ENABLE_HUSH_LOOPS
914 BLTIN("continue" , builtin_continue
, "Start new loop iteration"),
916 BLTIN("eval" , builtin_eval
, "Construct and run shell command"),
917 BLTIN("exec" , builtin_exec
, "Execute command, don't return to shell"),
918 BLTIN("exit" , builtin_exit
, "Exit"),
919 BLTIN("export" , builtin_export
, "Set environment variables"),
921 BLTIN("fg" , builtin_fg_bg
, "Bring job into the foreground"),
924 BLTIN("help" , builtin_help
, NULL
),
927 BLTIN("jobs" , builtin_jobs
, "List jobs"),
929 #if ENABLE_HUSH_LOCAL
930 BLTIN("local" , builtin_local
, "Set local variables"),
933 BLTIN("memleak" , builtin_memleak
, NULL
),
935 BLTIN("read" , builtin_read
, "Input into variable"),
936 #if ENABLE_HUSH_FUNCTIONS
937 BLTIN("return" , builtin_return
, "Return from a function"),
939 BLTIN("set" , builtin_set
, "Set/unset positional parameters"),
940 BLTIN("shift" , builtin_shift
, "Shift positional parameters"),
941 #if ENABLE_HUSH_BASH_COMPAT
942 BLTIN("source" , builtin_source
, "Run commands in a file"),
944 BLTIN("trap" , builtin_trap
, "Trap signals"),
945 BLTIN("type" , builtin_type
, "Show command type"),
946 BLTIN("ulimit" , shell_builtin_ulimit
, "Control resource limits"),
947 BLTIN("umask" , builtin_umask
, "Set file creation mask"),
948 BLTIN("unset" , builtin_unset
, "Unset variables"),
949 BLTIN("wait" , builtin_wait
, "Wait for process"),
951 /* For now, echo and test are unconditionally enabled.
952 * Maybe make it configurable? */
953 static const struct built_in_command bltins2
[] = {
954 BLTIN("[" , builtin_test
, NULL
),
955 BLTIN("echo" , builtin_echo
, NULL
),
957 BLTIN("printf" , builtin_printf
, NULL
),
959 BLTIN("pwd" , builtin_pwd
, NULL
),
960 BLTIN("test" , builtin_test
, NULL
),
967 /* prevent disasters with G.debug_indent < 0 */
968 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
969 # define debug_enter() (G.debug_indent++)
970 # define debug_leave() (G.debug_indent--)
972 # define indent() ((void)0)
973 # define debug_enter() ((void)0)
974 # define debug_leave() ((void)0)
978 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
981 #ifndef debug_printf_parse
982 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
985 #ifndef debug_printf_exec
986 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
989 #ifndef debug_printf_env
990 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
993 #ifndef debug_printf_jobs
994 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
995 # define DEBUG_JOBS 1
997 # define DEBUG_JOBS 0
1000 #ifndef debug_printf_expand
1001 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1002 # define DEBUG_EXPAND 1
1004 # define DEBUG_EXPAND 0
1007 #ifndef debug_printf_varexp
1008 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1011 #ifndef debug_printf_glob
1012 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1013 # define DEBUG_GLOB 1
1015 # define DEBUG_GLOB 0
1018 #ifndef debug_printf_list
1019 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1022 #ifndef debug_printf_subst
1023 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1026 #ifndef debug_printf_clean
1027 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1028 # define DEBUG_CLEAN 1
1030 # define DEBUG_CLEAN 0
1034 static void debug_print_strings(const char *prefix
, char **vv
)
1037 fdprintf(2, "%s:\n", prefix
);
1039 fdprintf(2, " '%s'\n", *vv
++);
1042 # define debug_print_strings(prefix, vv) ((void)0)
1046 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1049 static void *xxmalloc(int lineno
, size_t size
)
1051 void *ptr
= xmalloc((size
+ 0xff) & ~0xff);
1052 fdprintf(2, "line %d: malloc %p\n", lineno
, ptr
);
1055 static void *xxrealloc(int lineno
, void *ptr
, size_t size
)
1057 ptr
= xrealloc(ptr
, (size
+ 0xff) & ~0xff);
1058 fdprintf(2, "line %d: realloc %p\n", lineno
, ptr
);
1061 static char *xxstrdup(int lineno
, const char *str
)
1063 char *ptr
= xstrdup(str
);
1064 fdprintf(2, "line %d: strdup %p\n", lineno
, ptr
);
1067 static void xxfree(void *ptr
)
1069 fdprintf(2, "free %p\n", ptr
);
1072 # define xmalloc(s) xxmalloc(__LINE__, s)
1073 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1074 # define xstrdup(s) xxstrdup(__LINE__, s)
1075 # define free(p) xxfree(p)
1079 /* Syntax and runtime errors. They always abort scripts.
1080 * In interactive use they usually discard unparsed and/or unexecuted commands
1081 * and return to the prompt.
1082 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1085 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1086 # define syntax_error(lineno, msg) syntax_error(msg)
1087 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1088 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1089 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1090 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1093 static void die_if_script(unsigned lineno
, const char *fmt
, ...)
1098 bb_error_msg("hush.c:%u", lineno
);
1101 bb_verror_msg(fmt
, p
, NULL
);
1103 if (!G_interactive_fd
)
1107 static void syntax_error(unsigned lineno UNUSED_PARAM
, const char *msg
)
1110 bb_error_msg("syntax error: %s", msg
);
1112 bb_error_msg("syntax error");
1115 static void syntax_error_at(unsigned lineno UNUSED_PARAM
, const char *msg
)
1117 bb_error_msg("syntax error at '%s'", msg
);
1120 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM
, const char *s
)
1122 bb_error_msg("syntax error: unterminated %s", s
);
1125 static void syntax_error_unterm_ch(unsigned lineno
, char ch
)
1127 char msg
[2] = { ch
, '\0' };
1128 syntax_error_unterm_str(lineno
, msg
);
1131 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM
, int ch
)
1136 bb_error_msg("syntax error: unexpected %s", ch
== EOF
? "EOF" : msg
);
1140 # undef die_if_script
1141 # undef syntax_error
1142 # undef syntax_error_at
1143 # undef syntax_error_unterm_ch
1144 # undef syntax_error_unterm_str
1145 # undef syntax_error_unexpected_ch
1147 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1148 # define syntax_error(msg) syntax_error(__LINE__, msg)
1149 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1150 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1151 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1152 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1156 #if ENABLE_HUSH_INTERACTIVE
1157 static void cmdedit_update_prompt(void);
1159 # define cmdedit_update_prompt() ((void)0)
1163 /* Utility functions
1165 /* Replace each \x with x in place, return ptr past NUL. */
1166 static char *unbackslash(char *src
)
1168 char *dst
= src
= strchrnul(src
, '\\');
1172 if ((*dst
++ = *src
++) == '\0')
1178 static char **add_strings_to_strings(char **strings
, char **add
, int need_to_dup
)
1199 v
= xrealloc(strings
, (count1
+ count2
+ 1) * sizeof(char*));
1200 v
[count1
+ count2
] = NULL
;
1203 v
[count1
+ i
] = (need_to_dup
? xstrdup(add
[i
]) : add
[i
]);
1207 static char **xx_add_strings_to_strings(int lineno
, char **strings
, char **add
, int need_to_dup
)
1209 char **ptr
= add_strings_to_strings(strings
, add
, need_to_dup
);
1210 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno
, ptr
);
1213 #define add_strings_to_strings(strings, add, need_to_dup) \
1214 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1217 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1218 static char **add_string_to_strings(char **strings
, char *add
)
1223 return add_strings_to_strings(strings
, v
, /*dup:*/ 0);
1226 static char **xx_add_string_to_strings(int lineno
, char **strings
, char *add
)
1228 char **ptr
= add_string_to_strings(strings
, add
);
1229 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno
, ptr
);
1232 #define add_string_to_strings(strings, add) \
1233 xx_add_string_to_strings(__LINE__, strings, add)
1236 static void free_strings(char **strings
)
1251 /* Helpers for setting new $n and restoring them back
1253 typedef struct save_arg_t
{
1257 smallint sv_g_malloced
;
1260 static void save_and_replace_G_args(save_arg_t
*sv
, char **argv
)
1264 sv
->sv_argv0
= argv
[0];
1265 sv
->sv_g_argv
= G
.global_argv
;
1266 sv
->sv_g_argc
= G
.global_argc
;
1267 sv
->sv_g_malloced
= G
.global_args_malloced
;
1269 argv
[0] = G
.global_argv
[0]; /* retain $0 */
1270 G
.global_argv
= argv
;
1271 G
.global_args_malloced
= 0;
1279 static void restore_G_args(save_arg_t
*sv
, char **argv
)
1283 if (G
.global_args_malloced
) {
1284 /* someone ran "set -- arg1 arg2 ...", undo */
1286 while (*++pp
) /* note: does not free $0 */
1288 free(G
.global_argv
);
1290 argv
[0] = sv
->sv_argv0
;
1291 G
.global_argv
= sv
->sv_g_argv
;
1292 G
.global_argc
= sv
->sv_g_argc
;
1293 G
.global_args_malloced
= sv
->sv_g_malloced
;
1297 /* Basic theory of signal handling in shell
1298 * ========================================
1299 * This does not describe what hush does, rather, it is current understanding
1300 * what it _should_ do. If it doesn't, it's a bug.
1301 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1303 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1304 * is finished or backgrounded. It is the same in interactive and
1305 * non-interactive shells, and is the same regardless of whether
1306 * a user trap handler is installed or a shell special one is in effect.
1307 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1308 * backgrounds (i.e. stops) or kills all members of currently running
1311 * Wait builtin in interruptible by signals for which user trap is set
1312 * or by SIGINT in interactive shell.
1314 * Trap handlers will execute even within trap handlers. (right?)
1316 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1317 * except for handlers set to '' (empty string).
1319 * If job control is off, backgrounded commands ("cmd &")
1320 * have SIGINT, SIGQUIT set to SIG_IGN.
1322 * Commands which are run in command substitution ("`cmd`")
1323 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1325 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1326 * by the shell from its parent.
1328 * Signals which differ from SIG_DFL action
1329 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1332 * SIGTERM (interactive): ignore
1333 * SIGHUP (interactive):
1334 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1335 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1336 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1337 * that all pipe members are stopped. Try this in bash:
1338 * while :; do :; done - ^Z does not background it
1339 * (while :; do :; done) - ^Z backgrounds it
1340 * SIGINT (interactive): wait for last pipe, ignore the rest
1341 * of the command line, show prompt. NB: ^C does not send SIGINT
1342 * to interactive shell while shell is waiting for a pipe,
1343 * since shell is bg'ed (is not in foreground process group).
1344 * Example 1: this waits 5 sec, but does not execute ls:
1345 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1346 * Example 2: this does not wait and does not execute ls:
1347 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1348 * Example 3: this does not wait 5 sec, but executes ls:
1349 * "sleep 5; ls -l" + press ^C
1350 * Example 4: this does not wait and does not execute ls:
1351 * "sleep 5 & wait; ls -l" + press ^C
1353 * (What happens to signals which are IGN on shell start?)
1354 * (What happens with signal mask on shell start?)
1356 * Old implementation
1357 * ==================
1358 * We use in-kernel pending signal mask to determine which signals were sent.
1359 * We block all signals which we don't want to take action immediately,
1360 * i.e. we block all signals which need to have special handling as described
1361 * above, and all signals which have traps set.
1362 * After each pipe execution, we extract any pending signals via sigtimedwait()
1365 * unsigned special_sig_mask: a mask of such "special" signals
1366 * sigset_t blocked_set: current blocked signal set
1369 * clear bit in blocked_set unless it is also in special_sig_mask
1370 * "trap 'cmd' SIGxxx":
1371 * set bit in blocked_set (even if 'cmd' is '')
1372 * after [v]fork, if we plan to be a shell:
1373 * unblock signals with special interactive handling
1374 * (child shell is not interactive),
1375 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1376 * after [v]fork, if we plan to exec:
1377 * POSIX says fork clears pending signal mask in child - no need to clear it.
1378 * Restore blocked signal set to one inherited by shell just prior to exec.
1380 * Note: as a result, we do not use signal handlers much. The only uses
1381 * are to count SIGCHLDs
1382 * and to restore tty pgrp on signal-induced exit.
1385 * Standard says "When a subshell is entered, traps that are not being ignored
1386 * are set to the default actions". bash interprets it so that traps which
1387 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1389 * Problem: the above approach makes it unwieldy to catch signals while
1390 * we are in read builtin, of while we read commands from stdin:
1391 * masked signals are not visible!
1393 * New implementation
1394 * ==================
1395 * We record each signal we are interested in by installing signal handler
1396 * for them - a bit like emulating kernel pending signal mask in userspace.
1397 * We are interested in: signals which need to have special handling
1398 * as described above, and all signals which have traps set.
1399 * Signals are rocorded in pending_set.
1400 * After each pipe execution, we extract any pending signals
1403 * unsigned special_sig_mask: a mask of shell-special signals.
1404 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1405 * char *traps[sig] if trap for sig is set (even if it's '').
1406 * sigset_t pending_set: set of sigs we received.
1409 * if sig is in special_sig_mask, set handler back to:
1410 * record_pending_signo, or to IGN if it's a tty stop signal
1411 * if sig is in fatal_sig_mask, set handler back to sigexit.
1412 * else: set handler back to SIG_DFL
1413 * "trap 'cmd' SIGxxx":
1414 * set handler to record_pending_signo.
1416 * set handler to SIG_IGN.
1417 * after [v]fork, if we plan to be a shell:
1418 * set signals with special interactive handling to SIG_DFL
1419 * (because child shell is not interactive),
1420 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1421 * after [v]fork, if we plan to exec:
1422 * POSIX says fork clears pending signal mask in child - no need to clear it.
1424 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1425 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1428 * Standard says "When a subshell is entered, traps that are not being ignored
1429 * are set to the default actions". bash interprets it so that traps which
1430 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1433 SPECIAL_INTERACTIVE_SIGS
= 0
1438 SPECIAL_JOBSTOP_SIGS
= 0
1447 static void record_pending_signo(int sig
)
1449 sigaddset(&G
.pending_set
, sig
);
1450 #if ENABLE_HUSH_FAST
1451 if (sig
== SIGCHLD
) {
1453 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1458 static sighandler_t
install_sighandler(int sig
, sighandler_t handler
)
1460 struct sigaction old_sa
;
1462 /* We could use signal() to install handlers... almost:
1463 * except that we need to mask ALL signals while handlers run.
1464 * I saw signal nesting in strace, race window isn't small.
1465 * SA_RESTART is also needed, but in Linux, signal()
1466 * sets SA_RESTART too.
1468 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1469 /* sigfillset(&G.sa.sa_mask); - already done */
1470 /* G.sa.sa_flags = SA_RESTART; - already done */
1471 G
.sa
.sa_handler
= handler
;
1472 sigaction(sig
, &G
.sa
, &old_sa
);
1473 return old_sa
.sa_handler
;
1478 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1479 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1480 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1481 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1483 /* Restores tty foreground process group, and exits.
1484 * May be called as signal handler for fatal signal
1485 * (will resend signal to itself, producing correct exit state)
1486 * or called directly with -EXITCODE.
1487 * We also call it if xfunc is exiting. */
1488 static void sigexit(int sig
) NORETURN
;
1489 static void sigexit(int sig
)
1491 /* Careful: we can end up here after [v]fork. Do not restore
1492 * tty pgrp then, only top-level shell process does that */
1493 if (G_saved_tty_pgrp
&& getpid() == G
.root_pid
) {
1494 /* Disable all signals: job control, SIGPIPE, etc.
1495 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1497 sigprocmask_allsigs(SIG_BLOCK
);
1498 tcsetpgrp(G_interactive_fd
, G_saved_tty_pgrp
);
1501 /* Not a signal, just exit */
1505 kill_myself_with_sig(sig
); /* does not return */
1509 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1510 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1514 static sighandler_t
pick_sighandler(unsigned sig
)
1516 sighandler_t handler
= SIG_DFL
;
1517 if (sig
< sizeof(unsigned)*8) {
1518 unsigned sigmask
= (1 << sig
);
1522 if (G_fatal_sig_mask
& sigmask
)
1526 /* sig has special handling? */
1527 if (G
.special_sig_mask
& sigmask
) {
1528 handler
= record_pending_signo
;
1529 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1530 * in order to ignore them: they will be raised
1531 * in an endless loop when we try to do some
1532 * terminal ioctls! We do have to _ignore_ these.
1534 if (SPECIAL_JOBSTOP_SIGS
& sigmask
)
1541 /* Restores tty foreground process group, and exits. */
1542 static void hush_exit(int exitcode
) NORETURN
;
1543 static void hush_exit(int exitcode
)
1545 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1546 save_history(G
.line_input_state
);
1550 if (G
.exiting
<= 0 && G
.traps
&& G
.traps
[0] && G
.traps
[0][0]) {
1552 /* argv[0] is unused */
1553 argv
[1] = G
.traps
[0];
1555 G
.exiting
= 1; /* prevent EXIT trap recursion */
1556 /* Note: G.traps[0] is not cleared!
1557 * "trap" will still show it, if executed
1562 #if ENABLE_FEATURE_CLEAN_UP
1564 struct variable
*cur_var
;
1565 if (G
.cwd
!= bb_msg_unknown
)
1567 cur_var
= G
.top_var
;
1569 struct variable
*tmp
= cur_var
;
1570 if (!cur_var
->max_len
)
1571 free(cur_var
->varstr
);
1572 cur_var
= cur_var
->next
;
1580 sigexit(- (exitcode
& 0xff));
1587 //TODO: return a mask of ALL handled sigs?
1588 static int check_and_run_traps(void)
1595 if (sigisemptyset(&G
.pending_set
))
1600 if (sigismember(&G
.pending_set
, sig
)) {
1601 sigdelset(&G
.pending_set
, sig
);
1604 } while (sig
< NSIG
);
1607 if (G
.traps
&& G
.traps
[sig
]) {
1608 if (G
.traps
[sig
][0]) {
1609 /* We have user-defined handler */
1610 smalluint save_rcode
;
1612 /* argv[0] is unused */
1613 argv
[1] = G
.traps
[sig
];
1615 save_rcode
= G
.last_exitcode
;
1617 G
.last_exitcode
= save_rcode
;
1619 } /* else: "" trap, ignoring signal */
1622 /* not a trap: special action */
1625 /* Builtin was ^C'ed, make it look prettier: */
1633 /* bash is observed to signal whole process groups,
1634 * not individual processes */
1635 for (job
= G
.job_list
; job
; job
= job
->next
) {
1638 debug_printf_exec("HUPing pgrp %d\n", job
->pgrp
);
1639 if (kill(- job
->pgrp
, SIGHUP
) == 0)
1640 kill(- job
->pgrp
, SIGCONT
);
1645 #if ENABLE_HUSH_FAST
1648 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1650 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1651 * This simplifies wait builtin a bit.
1655 default: /* ignored: */
1656 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1658 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1659 * Example: wait is not interrupted by TERM
1660 * in interactive shell, because TERM is ignored.
1669 static const char *get_cwd(int force
)
1671 if (force
|| G
.cwd
== NULL
) {
1672 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1673 * we must not try to free(bb_msg_unknown) */
1674 if (G
.cwd
== bb_msg_unknown
)
1676 G
.cwd
= xrealloc_getcwd_or_warn((char *)G
.cwd
);
1678 G
.cwd
= bb_msg_unknown
;
1685 * Shell and environment variable support
1687 static struct variable
**get_ptr_to_local_var(const char *name
, unsigned len
)
1689 struct variable
**pp
;
1690 struct variable
*cur
;
1693 while ((cur
= *pp
) != NULL
) {
1694 if (strncmp(cur
->varstr
, name
, len
) == 0 && cur
->varstr
[len
] == '=')
1701 static const char* FAST_FUNC
get_local_var_value(const char *name
)
1703 struct variable
**vpp
;
1704 unsigned len
= strlen(name
);
1706 if (G
.expanded_assignments
) {
1707 char **cpp
= G
.expanded_assignments
;
1710 if (strncmp(cp
, name
, len
) == 0 && cp
[len
] == '=')
1711 return cp
+ len
+ 1;
1716 vpp
= get_ptr_to_local_var(name
, len
);
1718 return (*vpp
)->varstr
+ len
+ 1;
1720 if (strcmp(name
, "PPID") == 0)
1721 return utoa(G
.root_ppid
);
1722 // bash compat: UID? EUID?
1723 #if ENABLE_HUSH_RANDOM_SUPPORT
1724 if (strcmp(name
, "RANDOM") == 0)
1725 return utoa(next_random(&G
.random_gen
));
1730 /* str holds "NAME=VAL" and is expected to be malloced.
1731 * We take ownership of it.
1733 * 0: do not change export flag
1734 * (if creating new variable, flag will be 0)
1735 * 1: set export flag and putenv the variable
1736 * -1: clear export flag and unsetenv the variable
1737 * flg_read_only is set only when we handle -R var=val
1739 #if !BB_MMU && ENABLE_HUSH_LOCAL
1740 /* all params are used */
1741 #elif BB_MMU && ENABLE_HUSH_LOCAL
1742 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1743 set_local_var(str, flg_export, local_lvl)
1744 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1745 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1746 set_local_var(str, flg_export)
1747 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1748 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1749 set_local_var(str, flg_export, flg_read_only)
1751 static int set_local_var(char *str
, int flg_export
, int local_lvl
, int flg_read_only
)
1753 struct variable
**var_pp
;
1754 struct variable
*cur
;
1758 eq_sign
= strchr(str
, '=');
1759 if (!eq_sign
) { /* not expected to ever happen? */
1764 name_len
= eq_sign
- str
+ 1; /* including '=' */
1765 var_pp
= &G
.top_var
;
1766 while ((cur
= *var_pp
) != NULL
) {
1767 if (strncmp(cur
->varstr
, str
, name_len
) != 0) {
1768 var_pp
= &cur
->next
;
1771 /* We found an existing var with this name */
1772 if (cur
->flg_read_only
) {
1776 bb_error_msg("%s: readonly variable", str
);
1780 if (flg_export
== -1) { // "&& cur->flg_export" ?
1781 debug_printf_env("%s: unsetenv '%s'\n", __func__
, str
);
1786 #if ENABLE_HUSH_LOCAL
1787 if (cur
->func_nest_level
< local_lvl
) {
1788 /* New variable is declared as local,
1789 * and existing one is global, or local
1790 * from enclosing function.
1791 * Remove and save old one: */
1792 *var_pp
= cur
->next
;
1793 cur
->next
= *G
.shadowed_vars_pp
;
1794 *G
.shadowed_vars_pp
= cur
;
1795 /* bash 3.2.33(1) and exported vars:
1797 * # f() { local z=a; env | grep ^z; }
1803 if (cur
->flg_export
)
1808 if (strcmp(cur
->varstr
+ name_len
, eq_sign
+ 1) == 0) {
1813 if (cur
->max_len
!= 0) {
1814 if (cur
->max_len
>= strlen(str
)) {
1815 /* This one is from startup env, reuse space */
1816 strcpy(cur
->varstr
, str
);
1820 /* max_len == 0 signifies "malloced" var, which we can
1821 * (and has to) free */
1825 goto set_str_and_exp
;
1828 /* Not found - create new variable struct */
1829 cur
= xzalloc(sizeof(*cur
));
1830 #if ENABLE_HUSH_LOCAL
1831 cur
->func_nest_level
= local_lvl
;
1833 cur
->next
= *var_pp
;
1839 cur
->flg_read_only
= flg_read_only
;
1842 if (flg_export
== 1)
1843 cur
->flg_export
= 1;
1844 if (name_len
== 4 && cur
->varstr
[0] == 'P' && cur
->varstr
[1] == 'S')
1845 cmdedit_update_prompt();
1846 if (cur
->flg_export
) {
1847 if (flg_export
== -1) {
1848 cur
->flg_export
= 0;
1849 /* unsetenv was already done */
1851 debug_printf_env("%s: putenv '%s'\n", __func__
, cur
->varstr
);
1852 return putenv(cur
->varstr
);
1858 /* Used at startup and after each cd */
1859 static void set_pwd_var(int exp
)
1861 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1862 /*exp:*/ exp
, /*lvl:*/ 0, /*ro:*/ 0);
1865 static int unset_local_var_len(const char *name
, int name_len
)
1867 struct variable
*cur
;
1868 struct variable
**var_pp
;
1871 return EXIT_SUCCESS
;
1872 var_pp
= &G
.top_var
;
1873 while ((cur
= *var_pp
) != NULL
) {
1874 if (strncmp(cur
->varstr
, name
, name_len
) == 0 && cur
->varstr
[name_len
] == '=') {
1875 if (cur
->flg_read_only
) {
1876 bb_error_msg("%s: readonly variable", name
);
1877 return EXIT_FAILURE
;
1879 *var_pp
= cur
->next
;
1880 debug_printf_env("%s: unsetenv '%s'\n", __func__
, cur
->varstr
);
1881 bb_unsetenv(cur
->varstr
);
1882 if (name_len
== 3 && cur
->varstr
[0] == 'P' && cur
->varstr
[1] == 'S')
1883 cmdedit_update_prompt();
1887 return EXIT_SUCCESS
;
1889 var_pp
= &cur
->next
;
1891 return EXIT_SUCCESS
;
1894 static int unset_local_var(const char *name
)
1896 return unset_local_var_len(name
, strlen(name
));
1899 static void unset_vars(char **strings
)
1907 const char *eq
= strchrnul(*v
, '=');
1908 unset_local_var_len(*v
, (int)(eq
- *v
));
1914 static void FAST_FUNC
set_local_var_from_halves(const char *name
, const char *val
)
1916 char *var
= xasprintf("%s=%s", name
, val
);
1917 set_local_var(var
, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1922 * Helpers for "var1=val1 var2=val2 cmd" feature
1924 static void add_vars(struct variable
*var
)
1926 struct variable
*next
;
1930 var
->next
= G
.top_var
;
1932 if (var
->flg_export
) {
1933 debug_printf_env("%s: restoring exported '%s'\n", __func__
, var
->varstr
);
1934 putenv(var
->varstr
);
1936 debug_printf_env("%s: restoring variable '%s'\n", __func__
, var
->varstr
);
1942 static struct variable
*set_vars_and_save_old(char **strings
)
1945 struct variable
*old
= NULL
;
1951 struct variable
*var_p
;
1952 struct variable
**var_pp
;
1955 eq
= strchr(*s
, '=');
1957 var_pp
= get_ptr_to_local_var(*s
, eq
- *s
);
1959 /* Remove variable from global linked list */
1961 debug_printf_env("%s: removing '%s'\n", __func__
, var_p
->varstr
);
1962 *var_pp
= var_p
->next
;
1963 /* Add it to returned list */
1967 set_local_var(*s
, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1978 static int FAST_FUNC
static_get(struct in_str
*i
)
1989 static int FAST_FUNC
static_peek(struct in_str
*i
)
1994 #if ENABLE_HUSH_INTERACTIVE
1996 static void cmdedit_update_prompt(void)
1998 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT
) {
1999 G
.PS1
= get_local_var_value("PS1");
2002 G
.PS2
= get_local_var_value("PS2");
2010 static const char *setup_prompt_string(int promptmode
)
2012 const char *prompt_str
;
2013 debug_printf("setup_prompt_string %d ", promptmode
);
2014 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT
) {
2015 /* Set up the prompt */
2016 if (promptmode
== 0) { /* PS1 */
2018 /* bash uses $PWD value, even if it is set by user.
2019 * It uses current dir only if PWD is unset.
2020 * We always use current dir. */
2021 G
.PS1
= xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2026 prompt_str
= (promptmode
== 0) ? G
.PS1
: G
.PS2
;
2027 debug_printf("result '%s'\n", prompt_str
);
2031 static void get_user_input(struct in_str
*i
)
2034 const char *prompt_str
;
2036 prompt_str
= setup_prompt_string(i
->promptmode
);
2037 # if ENABLE_FEATURE_EDITING
2038 /* Enable command line editing only while a command line
2039 * is actually being read */
2041 /* Unicode support should be activated even if LANG is set
2042 * _during_ shell execution, not only if it was set when
2043 * shell was started. Therefore, re-check LANG every time:
2045 reinit_unicode(get_local_var_value("LANG"));
2048 /* buglet: SIGINT will not make new prompt to appear _at once_,
2049 * only after <Enter>. (^C will work) */
2050 r
= read_line_input(G
.line_input_state
, prompt_str
, G
.user_input_buf
, CONFIG_FEATURE_EDITING_MAX_LEN
-1, /*timeout*/ -1);
2051 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2052 check_and_run_traps();
2053 } while (r
== 0 || G
.flag_SIGINT
); /* repeat if ^C or SIGINT */
2054 i
->eof_flag
= (r
< 0);
2055 if (i
->eof_flag
) { /* EOF/error detected */
2056 G
.user_input_buf
[0] = EOF
; /* yes, it will be truncated, it's ok */
2057 G
.user_input_buf
[1] = '\0';
2062 if (i
->last_char
== '\0' || i
->last_char
== '\n') {
2063 /* Why check_and_run_traps here? Try this interactively:
2064 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2065 * $ <[enter], repeatedly...>
2066 * Without check_and_run_traps, handler never runs.
2068 check_and_run_traps();
2069 fputs(prompt_str
, stdout
);
2072 G
.user_input_buf
[0] = r
= fgetc(i
->file
);
2073 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2074 } while (G
.flag_SIGINT
);
2075 i
->eof_flag
= (r
== EOF
);
2077 i
->p
= G
.user_input_buf
;
2080 #endif /* INTERACTIVE */
2082 /* This is the magic location that prints prompts
2083 * and gets data back from the user */
2084 static int FAST_FUNC
file_get(struct in_str
*i
)
2088 /* If there is data waiting, eat it up */
2089 if (i
->p
&& *i
->p
) {
2090 #if ENABLE_HUSH_INTERACTIVE
2094 if (i
->eof_flag
&& !*i
->p
)
2096 /* note: ch is never NUL */
2098 /* need to double check i->file because we might be doing something
2099 * more complicated by now, like sourcing or substituting. */
2100 #if ENABLE_HUSH_INTERACTIVE
2101 if (G_interactive_fd
&& i
->file
== stdin
) {
2104 } while (!*i
->p
); /* need non-empty line */
2105 i
->promptmode
= 1; /* PS2 */
2109 do ch
= fgetc(i
->file
); while (ch
== '\0');
2111 debug_printf("file_get: got '%c' %d\n", ch
, ch
);
2116 /* All callers guarantee this routine will never
2117 * be used right after a newline, so prompting is not needed.
2119 static int FAST_FUNC
file_peek(struct in_str
*i
)
2122 if (i
->p
&& *i
->p
) {
2123 if (i
->eof_flag
&& !i
->p
[1])
2126 /* note: ch is never NUL */
2128 do ch
= fgetc(i
->file
); while (ch
== '\0');
2129 i
->eof_flag
= (ch
== EOF
);
2130 i
->peek_buf
[0] = ch
;
2131 i
->peek_buf
[1] = '\0';
2133 debug_printf("file_peek: got '%c' %d\n", ch
, ch
);
2137 static void setup_file_in_str(struct in_str
*i
, FILE *f
)
2139 memset(i
, 0, sizeof(*i
));
2140 i
->peek
= file_peek
;
2142 /* i->promptmode = 0; - PS1 (memset did it) */
2147 static void setup_string_in_str(struct in_str
*i
, const char *s
)
2149 memset(i
, 0, sizeof(*i
));
2150 i
->peek
= static_peek
;
2151 i
->get
= static_get
;
2152 /* i->promptmode = 0; - PS1 (memset did it) */
2154 /* i->eof_flag = 0; */
2161 #define B_CHUNK (32 * sizeof(char*))
2163 static void o_reset_to_empty_unquoted(o_string
*o
)
2166 o
->has_quoted_part
= 0;
2171 static void o_free(o_string
*o
)
2174 memset(o
, 0, sizeof(*o
));
2177 static ALWAYS_INLINE
void o_free_unsafe(o_string
*o
)
2182 static void o_grow_by(o_string
*o
, int len
)
2184 if (o
->length
+ len
> o
->maxlen
) {
2185 o
->maxlen
+= (2*len
> B_CHUNK
? 2*len
: B_CHUNK
);
2186 o
->data
= xrealloc(o
->data
, 1 + o
->maxlen
);
2190 static void o_addchr(o_string
*o
, int ch
)
2192 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch
, o
->length
, o
);
2194 o
->data
[o
->length
] = ch
;
2196 o
->data
[o
->length
] = '\0';
2199 static void o_addblock(o_string
*o
, const char *str
, int len
)
2202 memcpy(&o
->data
[o
->length
], str
, len
);
2204 o
->data
[o
->length
] = '\0';
2207 static void o_addstr(o_string
*o
, const char *str
)
2209 o_addblock(o
, str
, strlen(str
));
2213 static void nommu_addchr(o_string
*o
, int ch
)
2219 # define nommu_addchr(o, str) ((void)0)
2222 static void o_addstr_with_NUL(o_string
*o
, const char *str
)
2224 o_addblock(o
, str
, strlen(str
) + 1);
2228 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2229 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2230 * Apparently, on unquoted $v bash still does globbing
2231 * ("v='*.txt'; echo $v" prints all .txt files),
2232 * but NOT brace expansion! Thus, there should be TWO independent
2233 * quoting mechanisms on $v expansion side: one protects
2234 * $v from brace expansion, and other additionally protects "$v" against globbing.
2235 * We have only second one.
2238 #if ENABLE_HUSH_BRACE_EXPANSION
2239 # define MAYBE_BRACES "{}"
2241 # define MAYBE_BRACES ""
2244 /* My analysis of quoting semantics tells me that state information
2245 * is associated with a destination, not a source.
2247 static void o_addqchr(o_string
*o
, int ch
)
2250 char *found
= strchr("*?[\\" MAYBE_BRACES
, ch
);
2255 o
->data
[o
->length
] = '\\';
2258 o
->data
[o
->length
] = ch
;
2260 o
->data
[o
->length
] = '\0';
2263 static void o_addQchr(o_string
*o
, int ch
)
2266 if ((o
->o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
)
2267 && strchr("*?[\\" MAYBE_BRACES
, ch
)
2270 o
->data
[o
->length
] = '\\';
2274 o
->data
[o
->length
] = ch
;
2276 o
->data
[o
->length
] = '\0';
2279 static void o_addqblock(o_string
*o
, const char *str
, int len
)
2284 int ordinary_cnt
= strcspn(str
, "*?[\\" MAYBE_BRACES
);
2285 if (ordinary_cnt
> len
) /* paranoia */
2287 o_addblock(o
, str
, ordinary_cnt
);
2288 if (ordinary_cnt
== len
)
2289 return; /* NUL is already added by o_addblock */
2290 str
+= ordinary_cnt
;
2291 len
-= ordinary_cnt
+ 1; /* we are processing + 1 char below */
2295 if (ch
) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2297 o
->data
[o
->length
] = '\\';
2301 o
->data
[o
->length
] = ch
;
2304 o
->data
[o
->length
] = '\0';
2307 static void o_addQblock(o_string
*o
, const char *str
, int len
)
2309 if (!(o
->o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
)) {
2310 o_addblock(o
, str
, len
);
2313 o_addqblock(o
, str
, len
);
2316 static void o_addQstr(o_string
*o
, const char *str
)
2318 o_addQblock(o
, str
, strlen(str
));
2321 /* A special kind of o_string for $VAR and `cmd` expansion.
2322 * It contains char* list[] at the beginning, which is grown in 16 element
2323 * increments. Actual string data starts at the next multiple of 16 * (char*).
2324 * list[i] contains an INDEX (int!) into this string data.
2325 * It means that if list[] needs to grow, data needs to be moved higher up
2326 * but list[i]'s need not be modified.
2327 * NB: remembering how many list[i]'s you have there is crucial.
2328 * o_finalize_list() operation post-processes this structure - calculates
2329 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2331 #if DEBUG_EXPAND || DEBUG_GLOB
2332 static void debug_print_list(const char *prefix
, o_string
*o
, int n
)
2334 char **list
= (char**)o
->data
;
2335 int string_start
= ((n
+ 0xf) & ~0xf) * sizeof(list
[0]);
2339 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2340 prefix
, list
, n
, string_start
, o
->length
, o
->maxlen
,
2341 !!(o
->o_expflags
& EXP_FLAG_GLOB
),
2343 !!(o
->o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
));
2346 fdprintf(2, " list[%d]=%d '%s' %p\n", i
, (int)(uintptr_t)list
[i
],
2347 o
->data
+ (int)(uintptr_t)list
[i
] + string_start
,
2348 o
->data
+ (int)(uintptr_t)list
[i
] + string_start
);
2352 const char *p
= o
->data
+ (int)(uintptr_t)list
[n
- 1] + string_start
;
2354 fdprintf(2, " total_sz:%ld\n", (long)((p
+ strlen(p
) + 1) - o
->data
));
2358 # define debug_print_list(prefix, o, n) ((void)0)
2361 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2362 * in list[n] so that it points past last stored byte so far.
2363 * It returns n+1. */
2364 static int o_save_ptr_helper(o_string
*o
, int n
)
2366 char **list
= (char**)o
->data
;
2370 if (!o
->has_empty_slot
) {
2371 string_start
= ((n
+ 0xf) & ~0xf) * sizeof(list
[0]);
2372 string_len
= o
->length
- string_start
;
2373 if (!(n
& 0xf)) { /* 0, 0x10, 0x20...? */
2374 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n
, string_len
, string_start
);
2375 /* list[n] points to string_start, make space for 16 more pointers */
2376 o
->maxlen
+= 0x10 * sizeof(list
[0]);
2377 o
->data
= xrealloc(o
->data
, o
->maxlen
+ 1);
2378 list
= (char**)o
->data
;
2379 memmove(list
+ n
+ 0x10, list
+ n
, string_len
);
2380 o
->length
+= 0x10 * sizeof(list
[0]);
2382 debug_printf_list("list[%d]=%d string_start=%d\n",
2383 n
, string_len
, string_start
);
2386 /* We have empty slot at list[n], reuse without growth */
2387 string_start
= ((n
+1 + 0xf) & ~0xf) * sizeof(list
[0]); /* NB: n+1! */
2388 string_len
= o
->length
- string_start
;
2389 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2390 n
, string_len
, string_start
);
2391 o
->has_empty_slot
= 0;
2393 o
->has_quoted_part
= 0;
2394 list
[n
] = (char*)(uintptr_t)string_len
;
2398 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2399 static int o_get_last_ptr(o_string
*o
, int n
)
2401 char **list
= (char**)o
->data
;
2402 int string_start
= ((n
+ 0xf) & ~0xf) * sizeof(list
[0]);
2404 return ((int)(uintptr_t)list
[n
-1]) + string_start
;
2407 #if ENABLE_HUSH_BRACE_EXPANSION
2408 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2409 * first, it processes even {a} (no commas), second,
2410 * I didn't manage to make it return strings when they don't match
2411 * existing files. Need to re-implement it.
2415 static int glob_needed(const char *s
)
2424 if (*s
== '*' || *s
== '[' || *s
== '?' || *s
== '{')
2430 /* Return pointer to next closing brace or to comma */
2431 static const char *next_brace_sub(const char *cp
)
2435 while (*cp
!= '\0') {
2442 if ((*cp
== '}' && depth
-- == 0) || (*cp
== ',' && depth
== 0))
2448 return *cp
!= '\0' ? cp
: NULL
;
2450 /* Recursive brace globber. Note: may garble pattern[]. */
2451 static int glob_brace(char *pattern
, o_string
*o
, int n
)
2453 char *new_pattern_buf
;
2460 debug_printf_glob("glob_brace('%s')\n", pattern
);
2466 if (*begin
== '{') {
2467 /* Find the first sub-pattern and at the same time
2468 * find the rest after the closing brace */
2469 next
= next_brace_sub(begin
);
2471 /* An illegal expression */
2475 /* "{abc}" with no commas - illegal
2476 * brace expr, disregard and skip it */
2482 if (*begin
== '\\' && begin
[1] != '\0')
2486 debug_printf_glob("begin:%s\n", begin
);
2487 debug_printf_glob("next:%s\n", next
);
2489 /* Now find the end of the whole brace expression */
2491 while (*rest
!= '}') {
2492 rest
= next_brace_sub(rest
);
2494 /* An illegal expression */
2497 debug_printf_glob("rest:%s\n", rest
);
2499 rest_len
= strlen(++rest
) + 1;
2501 /* We are sure the brace expression is well-formed */
2503 /* Allocate working buffer large enough for our work */
2504 new_pattern_buf
= xmalloc(strlen(pattern
));
2506 /* We have a brace expression. BEGIN points to the opening {,
2507 * NEXT points past the terminator of the first element, and REST
2508 * points past the final }. We will accumulate result names from
2509 * recursive runs for each brace alternative in the buffer using
2514 /* Construct the new glob expression */
2517 mempcpy(new_pattern_buf
,
2518 /* We know the prefix for all sub-patterns */
2519 pattern
, begin
- pattern
),
2523 /* Note: glob_brace() may garble new_pattern_buf[].
2524 * That's why we re-copy prefix every time (1st memcpy above).
2526 n
= glob_brace(new_pattern_buf
, o
, n
);
2528 /* We saw the last entry */
2532 next
= next_brace_sub(next
);
2534 free(new_pattern_buf
);
2542 memset(&globdata
, 0, sizeof(globdata
));
2543 gr
= glob(pattern
, 0, NULL
, &globdata
);
2544 debug_printf_glob("glob('%s'):%d\n", pattern
, gr
);
2546 if (gr
== GLOB_NOMATCH
) {
2547 globfree(&globdata
);
2548 /* NB: garbles parameter */
2549 unbackslash(pattern
);
2550 o_addstr_with_NUL(o
, pattern
);
2551 debug_printf_glob("glob pattern '%s' is literal\n", pattern
);
2552 return o_save_ptr_helper(o
, n
);
2554 if (gr
== GLOB_NOSPACE
)
2555 bb_error_msg_and_die(bb_msg_memory_exhausted
);
2556 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2557 * but we didn't specify it. Paranoia again. */
2558 bb_error_msg_and_die("glob error %d on '%s'", gr
, pattern
);
2560 if (globdata
.gl_pathv
&& globdata
.gl_pathv
[0]) {
2561 char **argv
= globdata
.gl_pathv
;
2563 o_addstr_with_NUL(o
, *argv
);
2564 n
= o_save_ptr_helper(o
, n
);
2570 globfree(&globdata
);
2574 /* Performs globbing on last list[],
2575 * saving each result as a new list[].
2577 static int perform_glob(o_string
*o
, int n
)
2579 char *pattern
, *copy
;
2581 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n
, o
->data
);
2583 return o_save_ptr_helper(o
, n
);
2584 pattern
= o
->data
+ o_get_last_ptr(o
, n
);
2585 debug_printf_glob("glob pattern '%s'\n", pattern
);
2586 if (!glob_needed(pattern
)) {
2587 /* unbackslash last string in o in place, fix length */
2588 o
->length
= unbackslash(pattern
) - o
->data
;
2589 debug_printf_glob("glob pattern '%s' is literal\n", pattern
);
2590 return o_save_ptr_helper(o
, n
);
2593 copy
= xstrdup(pattern
);
2594 /* "forget" pattern in o */
2595 o
->length
= pattern
- o
->data
;
2596 n
= glob_brace(copy
, o
, n
);
2599 debug_print_list("perform_glob returning", o
, n
);
2603 #else /* !HUSH_BRACE_EXPANSION */
2606 static int glob_needed(const char *s
)
2615 if (*s
== '*' || *s
== '[' || *s
== '?')
2621 /* Performs globbing on last list[],
2622 * saving each result as a new list[].
2624 static int perform_glob(o_string
*o
, int n
)
2630 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n
, o
->data
);
2632 return o_save_ptr_helper(o
, n
);
2633 pattern
= o
->data
+ o_get_last_ptr(o
, n
);
2634 debug_printf_glob("glob pattern '%s'\n", pattern
);
2635 if (!glob_needed(pattern
)) {
2637 /* unbackslash last string in o in place, fix length */
2638 o
->length
= unbackslash(pattern
) - o
->data
;
2639 debug_printf_glob("glob pattern '%s' is literal\n", pattern
);
2640 return o_save_ptr_helper(o
, n
);
2643 memset(&globdata
, 0, sizeof(globdata
));
2644 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2645 * If we glob "*.\*" and don't find anything, we need
2646 * to fall back to using literal "*.*", but GLOB_NOCHECK
2647 * will return "*.\*"!
2649 gr
= glob(pattern
, 0, NULL
, &globdata
);
2650 debug_printf_glob("glob('%s'):%d\n", pattern
, gr
);
2652 if (gr
== GLOB_NOMATCH
) {
2653 globfree(&globdata
);
2656 if (gr
== GLOB_NOSPACE
)
2657 bb_error_msg_and_die(bb_msg_memory_exhausted
);
2658 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2659 * but we didn't specify it. Paranoia again. */
2660 bb_error_msg_and_die("glob error %d on '%s'", gr
, pattern
);
2662 if (globdata
.gl_pathv
&& globdata
.gl_pathv
[0]) {
2663 char **argv
= globdata
.gl_pathv
;
2664 /* "forget" pattern in o */
2665 o
->length
= pattern
- o
->data
;
2667 o_addstr_with_NUL(o
, *argv
);
2668 n
= o_save_ptr_helper(o
, n
);
2674 globfree(&globdata
);
2676 debug_print_list("perform_glob returning", o
, n
);
2680 #endif /* !HUSH_BRACE_EXPANSION */
2682 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2683 * Otherwise, just finish current list[] and start new */
2684 static int o_save_ptr(o_string
*o
, int n
)
2686 if (o
->o_expflags
& EXP_FLAG_GLOB
) {
2687 /* If o->has_empty_slot, list[n] was already globbed
2688 * (if it was requested back then when it was filled)
2689 * so don't do that again! */
2690 if (!o
->has_empty_slot
)
2691 return perform_glob(o
, n
); /* o_save_ptr_helper is inside */
2693 return o_save_ptr_helper(o
, n
);
2696 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2697 static char **o_finalize_list(o_string
*o
, int n
)
2702 n
= o_save_ptr(o
, n
); /* force growth for list[n] if necessary */
2704 debug_print_list("finalized", o
, n
);
2705 debug_printf_expand("finalized n:%d\n", n
);
2706 list
= (char**)o
->data
;
2707 string_start
= ((n
+ 0xf) & ~0xf) * sizeof(list
[0]);
2711 list
[n
] = o
->data
+ (int)(uintptr_t)list
[n
] + string_start
;
2716 static void free_pipe_list(struct pipe
*pi
);
2718 /* Returns pi->next - next pipe in the list */
2719 static struct pipe
*free_pipe(struct pipe
*pi
)
2724 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2725 for (i
= 0; i
< pi
->num_cmds
; i
++) {
2726 struct command
*command
;
2727 struct redir_struct
*r
, *rnext
;
2729 command
= &pi
->cmds
[i
];
2730 debug_printf_clean(" command %d:\n", i
);
2731 if (command
->argv
) {
2735 for (a
= 0, p
= command
->argv
; *p
; a
++, p
++) {
2736 debug_printf_clean(" argv[%d] = %s\n", a
, *p
);
2739 free_strings(command
->argv
);
2740 //command->argv = NULL;
2742 /* not "else if": on syntax error, we may have both! */
2743 if (command
->group
) {
2744 debug_printf_clean(" begin group (cmd_type:%d)\n",
2746 free_pipe_list(command
->group
);
2747 debug_printf_clean(" end group\n");
2748 //command->group = NULL;
2750 /* else is crucial here.
2751 * If group != NULL, child_func is meaningless */
2752 #if ENABLE_HUSH_FUNCTIONS
2753 else if (command
->child_func
) {
2754 debug_printf_exec("cmd %p releases child func at %p\n", command
, command
->child_func
);
2755 command
->child_func
->parent_cmd
= NULL
;
2759 free(command
->group_as_string
);
2760 //command->group_as_string = NULL;
2762 for (r
= command
->redirects
; r
; r
= rnext
) {
2763 debug_printf_clean(" redirect %d%s",
2764 r
->rd_fd
, redir_table
[r
->rd_type
].descrip
);
2765 /* guard against the case >$FOO, where foo is unset or blank */
2766 if (r
->rd_filename
) {
2767 debug_printf_clean(" fname:'%s'\n", r
->rd_filename
);
2768 free(r
->rd_filename
);
2769 //r->rd_filename = NULL;
2771 debug_printf_clean(" rd_dup:%d\n", r
->rd_dup
);
2775 //command->redirects = NULL;
2777 free(pi
->cmds
); /* children are an array, they get freed all at once */
2781 //pi->cmdtext = NULL;
2789 static void free_pipe_list(struct pipe
*pi
)
2793 debug_printf_clean("pipe reserved word %d\n", pi
->res_word
);
2795 debug_printf_clean("pipe followup code %d\n", pi
->followup
);
2801 /*** Parsing routines ***/
2803 #ifndef debug_print_tree
2804 static void debug_print_tree(struct pipe
*pi
, int lvl
)
2806 static const char *const PIPE
[] = {
2812 static const char *RES
[] = {
2813 [RES_NONE
] = "NONE" ,
2816 [RES_THEN
] = "THEN" ,
2817 [RES_ELIF
] = "ELIF" ,
2818 [RES_ELSE
] = "ELSE" ,
2821 # if ENABLE_HUSH_LOOPS
2822 [RES_FOR
] = "FOR" ,
2823 [RES_WHILE
] = "WHILE",
2824 [RES_UNTIL
] = "UNTIL",
2826 [RES_DONE
] = "DONE" ,
2828 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2831 # if ENABLE_HUSH_CASE
2832 [RES_CASE
] = "CASE" ,
2833 [RES_CASE_IN
] = "CASE_IN" ,
2834 [RES_MATCH
] = "MATCH",
2835 [RES_CASE_BODY
] = "CASE_BODY",
2836 [RES_ESAC
] = "ESAC" ,
2838 [RES_XXXX
] = "XXXX" ,
2839 [RES_SNTX
] = "SNTX" ,
2841 static const char *const CMDTYPE
[] = {
2845 # if ENABLE_HUSH_FUNCTIONS
2854 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl
*2, "",
2855 pin
, RES
[pi
->res_word
], pi
->followup
, PIPE
[pi
->followup
]);
2857 while (prn
< pi
->num_cmds
) {
2858 struct command
*command
= &pi
->cmds
[prn
];
2859 char **argv
= command
->argv
;
2861 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2863 command
->assignment_cnt
);
2864 if (command
->group
) {
2865 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2866 CMDTYPE
[command
->cmd_type
],
2869 , " group_as_string:", command
->group_as_string
2874 debug_print_tree(command
->group
, lvl
+1);
2878 if (argv
) while (*argv
) {
2879 fdprintf(2, " '%s'", *argv
);
2889 #endif /* debug_print_tree */
2891 static struct pipe
*new_pipe(void)
2894 pi
= xzalloc(sizeof(struct pipe
));
2895 /*pi->followup = 0; - deliberately invalid value */
2896 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2900 /* Command (member of a pipe) is complete, or we start a new pipe
2901 * if ctx->command is NULL.
2902 * No errors possible here.
2904 static int done_command(struct parse_context
*ctx
)
2906 /* The command is really already in the pipe structure, so
2907 * advance the pipe counter and make a new, null command. */
2908 struct pipe
*pi
= ctx
->pipe
;
2909 struct command
*command
= ctx
->command
;
2912 if (IS_NULL_CMD(command
)) {
2913 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi
->num_cmds
);
2917 debug_printf_parse("done_command: ++num_cmds=%d\n", pi
->num_cmds
);
2918 //debug_print_tree(ctx->list_head, 20);
2920 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi
->num_cmds
);
2923 /* Only real trickiness here is that the uncommitted
2924 * command structure is not counted in pi->num_cmds. */
2925 pi
->cmds
= xrealloc(pi
->cmds
, sizeof(*pi
->cmds
) * (pi
->num_cmds
+1));
2926 ctx
->command
= command
= &pi
->cmds
[pi
->num_cmds
];
2928 memset(command
, 0, sizeof(*command
));
2929 return pi
->num_cmds
; /* used only for 0/nonzero check */
2932 static void done_pipe(struct parse_context
*ctx
, pipe_style type
)
2936 debug_printf_parse("done_pipe entered, followup %d\n", type
);
2937 /* Close previous command */
2938 not_null
= done_command(ctx
);
2939 ctx
->pipe
->followup
= type
;
2941 ctx
->pipe
->pi_inverted
= ctx
->ctx_inverted
;
2942 ctx
->ctx_inverted
= 0;
2943 ctx
->pipe
->res_word
= ctx
->ctx_res_w
;
2946 /* Without this check, even just <enter> on command line generates
2947 * tree of three NOPs (!). Which is harmless but annoying.
2948 * IOW: it is safe to do it unconditionally. */
2951 || ctx
->ctx_res_w
== RES_FI
2953 #if ENABLE_HUSH_LOOPS
2954 || ctx
->ctx_res_w
== RES_DONE
2955 || ctx
->ctx_res_w
== RES_FOR
2956 || ctx
->ctx_res_w
== RES_IN
2958 #if ENABLE_HUSH_CASE
2959 || ctx
->ctx_res_w
== RES_ESAC
2963 debug_printf_parse("done_pipe: adding new pipe: "
2964 "not_null:%d ctx->ctx_res_w:%d\n",
2965 not_null
, ctx
->ctx_res_w
);
2967 ctx
->pipe
->next
= new_p
;
2969 /* RES_THEN, RES_DO etc are "sticky" -
2970 * they remain set for pipes inside if/while.
2971 * This is used to control execution.
2972 * RES_FOR and RES_IN are NOT sticky (needed to support
2973 * cases where variable or value happens to match a keyword):
2975 #if ENABLE_HUSH_LOOPS
2976 if (ctx
->ctx_res_w
== RES_FOR
2977 || ctx
->ctx_res_w
== RES_IN
)
2978 ctx
->ctx_res_w
= RES_NONE
;
2980 #if ENABLE_HUSH_CASE
2981 if (ctx
->ctx_res_w
== RES_MATCH
)
2982 ctx
->ctx_res_w
= RES_CASE_BODY
;
2983 if (ctx
->ctx_res_w
== RES_CASE
)
2984 ctx
->ctx_res_w
= RES_CASE_IN
;
2986 ctx
->command
= NULL
; /* trick done_command below */
2987 /* Create the memory for command, roughly:
2988 * ctx->pipe->cmds = new struct command;
2989 * ctx->command = &ctx->pipe->cmds[0];
2992 //debug_print_tree(ctx->list_head, 10);
2994 debug_printf_parse("done_pipe return\n");
2997 static void initialize_context(struct parse_context
*ctx
)
2999 memset(ctx
, 0, sizeof(*ctx
));
3000 ctx
->pipe
= ctx
->list_head
= new_pipe();
3001 /* Create the memory for command, roughly:
3002 * ctx->pipe->cmds = new struct command;
3003 * ctx->command = &ctx->pipe->cmds[0];
3008 /* If a reserved word is found and processed, parse context is modified
3009 * and 1 is returned.
3012 struct reserved_combo
{
3015 unsigned char assignment_flag
;
3019 FLAG_END
= (1 << RES_NONE
),
3021 FLAG_IF
= (1 << RES_IF
),
3022 FLAG_THEN
= (1 << RES_THEN
),
3023 FLAG_ELIF
= (1 << RES_ELIF
),
3024 FLAG_ELSE
= (1 << RES_ELSE
),
3025 FLAG_FI
= (1 << RES_FI
),
3027 # if ENABLE_HUSH_LOOPS
3028 FLAG_FOR
= (1 << RES_FOR
),
3029 FLAG_WHILE
= (1 << RES_WHILE
),
3030 FLAG_UNTIL
= (1 << RES_UNTIL
),
3031 FLAG_DO
= (1 << RES_DO
),
3032 FLAG_DONE
= (1 << RES_DONE
),
3033 FLAG_IN
= (1 << RES_IN
),
3035 # if ENABLE_HUSH_CASE
3036 FLAG_MATCH
= (1 << RES_MATCH
),
3037 FLAG_ESAC
= (1 << RES_ESAC
),
3039 FLAG_START
= (1 << RES_XXXX
),
3042 static const struct reserved_combo
* match_reserved_word(o_string
*word
)
3044 /* Mostly a list of accepted follow-up reserved words.
3045 * FLAG_END means we are done with the sequence, and are ready
3046 * to turn the compound list into a command.
3047 * FLAG_START means the word must start a new compound list.
3049 static const struct reserved_combo reserved_list
[] = {
3051 { "!", RES_NONE
, NOT_ASSIGNMENT
, 0 },
3052 { "if", RES_IF
, MAYBE_ASSIGNMENT
, FLAG_THEN
| FLAG_START
},
3053 { "then", RES_THEN
, MAYBE_ASSIGNMENT
, FLAG_ELIF
| FLAG_ELSE
| FLAG_FI
},
3054 { "elif", RES_ELIF
, MAYBE_ASSIGNMENT
, FLAG_THEN
},
3055 { "else", RES_ELSE
, MAYBE_ASSIGNMENT
, FLAG_FI
},
3056 { "fi", RES_FI
, NOT_ASSIGNMENT
, FLAG_END
},
3058 # if ENABLE_HUSH_LOOPS
3059 { "for", RES_FOR
, NOT_ASSIGNMENT
, FLAG_IN
| FLAG_DO
| FLAG_START
},
3060 { "while", RES_WHILE
, MAYBE_ASSIGNMENT
, FLAG_DO
| FLAG_START
},
3061 { "until", RES_UNTIL
, MAYBE_ASSIGNMENT
, FLAG_DO
| FLAG_START
},
3062 { "in", RES_IN
, NOT_ASSIGNMENT
, FLAG_DO
},
3063 { "do", RES_DO
, MAYBE_ASSIGNMENT
, FLAG_DONE
},
3064 { "done", RES_DONE
, NOT_ASSIGNMENT
, FLAG_END
},
3066 # if ENABLE_HUSH_CASE
3067 { "case", RES_CASE
, NOT_ASSIGNMENT
, FLAG_MATCH
| FLAG_START
},
3068 { "esac", RES_ESAC
, NOT_ASSIGNMENT
, FLAG_END
},
3071 const struct reserved_combo
*r
;
3073 for (r
= reserved_list
; r
< reserved_list
+ ARRAY_SIZE(reserved_list
); r
++) {
3074 if (strcmp(word
->data
, r
->literal
) == 0)
3079 /* Return 0: not a keyword, 1: keyword
3081 static int reserved_word(o_string
*word
, struct parse_context
*ctx
)
3083 # if ENABLE_HUSH_CASE
3084 static const struct reserved_combo reserved_match
= {
3085 "", RES_MATCH
, NOT_ASSIGNMENT
, FLAG_MATCH
| FLAG_ESAC
3088 const struct reserved_combo
*r
;
3090 if (word
->has_quoted_part
)
3092 r
= match_reserved_word(word
);
3096 debug_printf("found reserved word %s, res %d\n", r
->literal
, r
->res
);
3097 # if ENABLE_HUSH_CASE
3098 if (r
->res
== RES_IN
&& ctx
->ctx_res_w
== RES_CASE_IN
) {
3099 /* "case word IN ..." - IN part starts first MATCH part */
3100 r
= &reserved_match
;
3103 if (r
->flag
== 0) { /* '!' */
3104 if (ctx
->ctx_inverted
) { /* bash doesn't accept '! ! true' */
3105 syntax_error("! ! command");
3106 ctx
->ctx_res_w
= RES_SNTX
;
3108 ctx
->ctx_inverted
= 1;
3111 if (r
->flag
& FLAG_START
) {
3112 struct parse_context
*old
;
3114 old
= xmalloc(sizeof(*old
));
3115 debug_printf_parse("push stack %p\n", old
);
3116 *old
= *ctx
; /* physical copy */
3117 initialize_context(ctx
);
3119 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx
->old_flag
& (1 << r
->res
))) {
3120 syntax_error_at(word
->data
);
3121 ctx
->ctx_res_w
= RES_SNTX
;
3124 /* "{...} fi" is ok. "{...} if" is not
3126 * if { echo foo; } then { echo bar; } fi */
3127 if (ctx
->command
->group
)
3128 done_pipe(ctx
, PIPE_SEQ
);
3131 ctx
->ctx_res_w
= r
->res
;
3132 ctx
->old_flag
= r
->flag
;
3133 word
->o_assignment
= r
->assignment_flag
;
3134 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag
[word
->o_assignment
]);
3136 if (ctx
->old_flag
& FLAG_END
) {
3137 struct parse_context
*old
;
3139 done_pipe(ctx
, PIPE_SEQ
);
3140 debug_printf_parse("pop stack %p\n", ctx
->stack
);
3142 old
->command
->group
= ctx
->list_head
;
3143 old
->command
->cmd_type
= CMD_NORMAL
;
3145 o_addstr(&old
->as_string
, ctx
->as_string
.data
);
3146 o_free_unsafe(&ctx
->as_string
);
3147 old
->command
->group_as_string
= xstrdup(old
->as_string
.data
);
3148 debug_printf_parse("pop, remembering as:'%s'\n",
3149 old
->command
->group_as_string
);
3151 *ctx
= *old
; /* physical copy */
3156 #endif /* HAS_KEYWORDS */
3158 /* Word is complete, look at it and update parsing context.
3159 * Normal return is 0. Syntax errors return 1.
3160 * Note: on return, word is reset, but not o_free'd!
3162 static int done_word(o_string
*word
, struct parse_context
*ctx
)
3164 struct command
*command
= ctx
->command
;
3166 debug_printf_parse("done_word entered: '%s' %p\n", word
->data
, command
);
3167 if (word
->length
== 0 && !word
->has_quoted_part
) {
3168 debug_printf_parse("done_word return 0: true null, ignored\n");
3172 if (ctx
->pending_redirect
) {
3173 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3174 * only if run as "bash", not "sh" */
3175 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3177 * ...the word that follows the redirection operator
3178 * shall be subjected to tilde expansion, parameter expansion,
3179 * command substitution, arithmetic expansion, and quote
3180 * removal. Pathname expansion shall not be performed
3181 * on the word by a non-interactive shell; an interactive
3182 * shell may perform it, but shall do so only when
3183 * the expansion would result in one word."
3185 ctx
->pending_redirect
->rd_filename
= xstrdup(word
->data
);
3186 /* Cater for >\file case:
3187 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3188 * Same with heredocs:
3189 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3191 if (ctx
->pending_redirect
->rd_type
== REDIRECT_HEREDOC
) {
3192 unbackslash(ctx
->pending_redirect
->rd_filename
);
3193 /* Is it <<"HEREDOC"? */
3194 if (word
->has_quoted_part
) {
3195 ctx
->pending_redirect
->rd_dup
|= HEREDOC_QUOTED
;
3198 debug_printf_parse("word stored in rd_filename: '%s'\n", word
->data
);
3199 ctx
->pending_redirect
= NULL
;
3202 # if ENABLE_HUSH_CASE
3203 if (ctx
->ctx_dsemicolon
3204 && strcmp(word
->data
, "esac") != 0 /* not "... pattern) cmd;; esac" */
3206 /* already done when ctx_dsemicolon was set to 1: */
3207 /* ctx->ctx_res_w = RES_MATCH; */
3208 ctx
->ctx_dsemicolon
= 0;
3211 if (!command
->argv
/* if it's the first word... */
3212 # if ENABLE_HUSH_LOOPS
3213 && ctx
->ctx_res_w
!= RES_FOR
/* ...not after FOR or IN */
3214 && ctx
->ctx_res_w
!= RES_IN
3216 # if ENABLE_HUSH_CASE
3217 && ctx
->ctx_res_w
!= RES_CASE
3220 int reserved
= reserved_word(word
, ctx
);
3221 debug_printf_parse("checking for reserved-ness: %d\n", reserved
);
3223 o_reset_to_empty_unquoted(word
);
3224 debug_printf_parse("done_word return %d\n",
3225 (ctx
->ctx_res_w
== RES_SNTX
));
3226 return (ctx
->ctx_res_w
== RES_SNTX
);
3228 # if ENABLE_HUSH_BASH_COMPAT
3229 if (strcmp(word
->data
, "[[") == 0) {
3230 command
->cmd_type
= CMD_SINGLEWORD_NOGLOB
;
3236 if (command
->group
) {
3237 /* "{ echo foo; } echo bar" - bad */
3238 syntax_error_at(word
->data
);
3239 debug_printf_parse("done_word return 1: syntax error, "
3240 "groups and arglists don't mix\n");
3244 /* If this word wasn't an assignment, next ones definitely
3245 * can't be assignments. Even if they look like ones. */
3246 if (word
->o_assignment
!= DEFINITELY_ASSIGNMENT
3247 && word
->o_assignment
!= WORD_IS_KEYWORD
3249 word
->o_assignment
= NOT_ASSIGNMENT
;
3251 if (word
->o_assignment
== DEFINITELY_ASSIGNMENT
) {
3252 command
->assignment_cnt
++;
3253 debug_printf_parse("++assignment_cnt=%d\n", command
->assignment_cnt
);
3255 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag
[word
->o_assignment
]);
3256 word
->o_assignment
= MAYBE_ASSIGNMENT
;
3258 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag
[word
->o_assignment
]);
3260 if (word
->has_quoted_part
3261 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3262 && (word
->data
[0] == '\0' || word
->data
[0] == SPECIAL_VAR_SYMBOL
)
3263 /* (otherwise it's known to be not empty and is already safe) */
3265 /* exclude "$@" - it can expand to no word despite "" */
3266 char *p
= word
->data
;
3267 while (p
[0] == SPECIAL_VAR_SYMBOL
3268 && (p
[1] & 0x7f) == '@'
3269 && p
[2] == SPECIAL_VAR_SYMBOL
3274 command
->argv
= add_string_to_strings(command
->argv
, xstrdup(word
->data
));
3275 debug_print_strings("word appended to argv", command
->argv
);
3278 #if ENABLE_HUSH_LOOPS
3279 if (ctx
->ctx_res_w
== RES_FOR
) {
3280 if (word
->has_quoted_part
3281 || !is_well_formed_var_name(command
->argv
[0], '\0')
3283 /* bash says just "not a valid identifier" */
3284 syntax_error("not a valid identifier in for");
3287 /* Force FOR to have just one word (variable name) */
3288 /* NB: basically, this makes hush see "for v in ..."
3289 * syntax as if it is "for v; in ...". FOR and IN become
3290 * two pipe structs in parse tree. */
3291 done_pipe(ctx
, PIPE_SEQ
);
3294 #if ENABLE_HUSH_CASE
3295 /* Force CASE to have just one word */
3296 if (ctx
->ctx_res_w
== RES_CASE
) {
3297 done_pipe(ctx
, PIPE_SEQ
);
3301 o_reset_to_empty_unquoted(word
);
3303 debug_printf_parse("done_word return 0\n");
3308 /* Peek ahead in the input to find out if we have a "&n" construct,
3309 * as in "2>&1", that represents duplicating a file descriptor.
3311 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3312 * REDIRFD_SYNTAX_ERR if syntax error,
3313 * REDIRFD_TO_FILE if no & was seen,
3314 * or the number found.
3317 #define parse_redir_right_fd(as_string, input) \
3318 parse_redir_right_fd(input)
3320 static int parse_redir_right_fd(o_string
*as_string
, struct in_str
*input
)
3326 return REDIRFD_TO_FILE
;
3328 ch
= i_getch(input
); /* get the & */
3329 nommu_addchr(as_string
, ch
);
3332 ch
= i_getch(input
);
3333 nommu_addchr(as_string
, ch
);
3334 return REDIRFD_CLOSE
;
3338 while (ch
!= EOF
&& isdigit(ch
)) {
3339 d
= d
*10 + (ch
-'0');
3341 ch
= i_getch(input
);
3342 nommu_addchr(as_string
, ch
);
3347 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3349 bb_error_msg("ambiguous redirect");
3350 return REDIRFD_SYNTAX_ERR
;
3353 /* Return code is 0 normal, 1 if a syntax error is detected
3355 static int parse_redirect(struct parse_context
*ctx
,
3358 struct in_str
*input
)
3360 struct command
*command
= ctx
->command
;
3361 struct redir_struct
*redir
;
3362 struct redir_struct
**redirp
;
3365 dup_num
= REDIRFD_TO_FILE
;
3366 if (style
!= REDIRECT_HEREDOC
) {
3367 /* Check for a '>&1' type redirect */
3368 dup_num
= parse_redir_right_fd(&ctx
->as_string
, input
);
3369 if (dup_num
== REDIRFD_SYNTAX_ERR
)
3372 int ch
= i_peek(input
);
3373 dup_num
= (ch
== '-'); /* HEREDOC_SKIPTABS bit is 1 */
3374 if (dup_num
) { /* <<-... */
3375 ch
= i_getch(input
);
3376 nommu_addchr(&ctx
->as_string
, ch
);
3381 if (style
== REDIRECT_OVERWRITE
&& dup_num
== REDIRFD_TO_FILE
) {
3382 int ch
= i_peek(input
);
3384 /* >|FILE redirect ("clobbering" >).
3385 * Since we do not support "set -o noclobber" yet,
3386 * >| and > are the same for now. Just eat |.
3388 ch
= i_getch(input
);
3389 nommu_addchr(&ctx
->as_string
, ch
);
3393 /* Create a new redir_struct and append it to the linked list */
3394 redirp
= &command
->redirects
;
3395 while ((redir
= *redirp
) != NULL
) {
3396 redirp
= &(redir
->next
);
3398 *redirp
= redir
= xzalloc(sizeof(*redir
));
3399 /* redir->next = NULL; */
3400 /* redir->rd_filename = NULL; */
3401 redir
->rd_type
= style
;
3402 redir
->rd_fd
= (fd
== -1) ? redir_table
[style
].default_fd
: fd
;
3404 debug_printf_parse("redirect type %d %s\n", redir
->rd_fd
,
3405 redir_table
[style
].descrip
);
3407 redir
->rd_dup
= dup_num
;
3408 if (style
!= REDIRECT_HEREDOC
&& dup_num
!= REDIRFD_TO_FILE
) {
3409 /* Erik had a check here that the file descriptor in question
3410 * is legit; I postpone that to "run time"
3411 * A "-" representation of "close me" shows up as a -3 here */
3412 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3413 redir
->rd_fd
, redir
->rd_dup
);
3415 /* Set ctx->pending_redirect, so we know what to do at the
3416 * end of the next parsed word. */
3417 ctx
->pending_redirect
= redir
;
3422 /* If a redirect is immediately preceded by a number, that number is
3423 * supposed to tell which file descriptor to redirect. This routine
3424 * looks for such preceding numbers. In an ideal world this routine
3425 * needs to handle all the following classes of redirects...
3426 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3427 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3428 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3429 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3431 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3433 * ... If n is quoted, the number shall not be recognized as part of
3434 * the redirection expression. For example:
3436 * writes the character 2 into file a"
3437 * We are getting it right by setting ->has_quoted_part on any \<char>
3439 * A -1 return means no valid number was found,
3440 * the caller should use the appropriate default for this redirection.
3442 static int redirect_opt_num(o_string
*o
)
3446 if (o
->data
== NULL
)
3448 num
= bb_strtou(o
->data
, NULL
, 10);
3449 if (errno
|| num
< 0)
3451 o_reset_to_empty_unquoted(o
);
3456 #define fetch_till_str(as_string, input, word, skip_tabs) \
3457 fetch_till_str(input, word, skip_tabs)
3459 static char *fetch_till_str(o_string
*as_string
,
3460 struct in_str
*input
,
3464 o_string heredoc
= NULL_O_STRING
;
3466 int prev
= 0; /* not \ */
3472 ch
= i_getch(input
);
3474 nommu_addchr(as_string
, ch
);
3475 if ((ch
== '\n' || ch
== EOF
)
3476 && ((heredoc_flags
& HEREDOC_QUOTED
) || prev
!= '\\')
3478 if (strcmp(heredoc
.data
+ past_EOL
, word
) == 0) {
3479 heredoc
.data
[past_EOL
] = '\0';
3480 debug_printf_parse("parsed heredoc '%s'\n", heredoc
.data
);
3481 return heredoc
.data
;
3483 while (ch
== '\n') {
3484 o_addchr(&heredoc
, ch
);
3487 past_EOL
= heredoc
.length
;
3489 ch
= i_getch(input
);
3491 nommu_addchr(as_string
, ch
);
3492 } while ((heredoc_flags
& HEREDOC_SKIPTABS
) && ch
== '\t');
3496 o_free_unsafe(&heredoc
);
3499 o_addchr(&heredoc
, ch
);
3500 nommu_addchr(as_string
, ch
);
3501 if (prev
== '\\' && ch
== '\\')
3502 /* Correctly handle foo\\<eol> (not a line cont.) */
3503 prev
= 0; /* not \ */
3509 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3510 * and load them all. There should be exactly heredoc_cnt of them.
3512 static int fetch_heredocs(int heredoc_cnt
, struct parse_context
*ctx
, struct in_str
*input
)
3514 struct pipe
*pi
= ctx
->list_head
;
3516 while (pi
&& heredoc_cnt
) {
3518 struct command
*cmd
= pi
->cmds
;
3520 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3522 cmd
->argv
? cmd
->argv
[0] : "NONE");
3523 for (i
= 0; i
< pi
->num_cmds
; i
++) {
3524 struct redir_struct
*redir
= cmd
->redirects
;
3526 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3527 i
, cmd
->argv
? cmd
->argv
[0] : "NONE");
3529 if (redir
->rd_type
== REDIRECT_HEREDOC
) {
3532 redir
->rd_type
= REDIRECT_HEREDOC2
;
3533 /* redir->rd_dup is (ab)used to indicate <<- */
3534 p
= fetch_till_str(&ctx
->as_string
, input
,
3535 redir
->rd_filename
, redir
->rd_dup
);
3537 syntax_error("unexpected EOF in here document");
3540 free(redir
->rd_filename
);
3541 redir
->rd_filename
= p
;
3544 redir
= redir
->next
;
3551 /* Should be 0. If it isn't, it's a parse error */
3553 bb_error_msg_and_die("heredoc BUG 2");
3559 static int run_list(struct pipe
*pi
);
3561 #define parse_stream(pstring, input, end_trigger) \
3562 parse_stream(input, end_trigger)
3564 static struct pipe
*parse_stream(char **pstring
,
3565 struct in_str
*input
,
3569 #if !ENABLE_HUSH_FUNCTIONS
3570 #define parse_group(dest, ctx, input, ch) \
3571 parse_group(ctx, input, ch)
3573 static int parse_group(o_string
*dest
, struct parse_context
*ctx
,
3574 struct in_str
*input
, int ch
)
3576 /* dest contains characters seen prior to ( or {.
3577 * Typically it's empty, but for function defs,
3578 * it contains function name (without '()'). */
3579 struct pipe
*pipe_list
;
3581 struct command
*command
= ctx
->command
;
3583 debug_printf_parse("parse_group entered\n");
3584 #if ENABLE_HUSH_FUNCTIONS
3585 if (ch
== '(' && !dest
->has_quoted_part
) {
3587 if (done_word(dest
, ctx
))
3590 goto skip
; /* (... */
3591 if (command
->argv
[1]) { /* word word ... (... */
3592 syntax_error_unexpected_ch('(');
3595 /* it is "word(..." or "word (..." */
3597 ch
= i_getch(input
);
3598 while (ch
== ' ' || ch
== '\t');
3600 syntax_error_unexpected_ch(ch
);
3603 nommu_addchr(&ctx
->as_string
, ch
);
3605 ch
= i_getch(input
);
3606 while (ch
== ' ' || ch
== '\t' || ch
== '\n');
3608 syntax_error_unexpected_ch(ch
);
3611 nommu_addchr(&ctx
->as_string
, ch
);
3612 command
->cmd_type
= CMD_FUNCDEF
;
3617 #if 0 /* Prevented by caller */
3618 if (command
->argv
/* word [word]{... */
3619 || dest
->length
/* word{... */
3620 || dest
->has_quoted_part
/* ""{... */
3623 debug_printf_parse("parse_group return 1: "
3624 "syntax error, groups and arglists don't mix\n");
3629 #if ENABLE_HUSH_FUNCTIONS
3635 command
->cmd_type
= CMD_SUBSHELL
;
3637 /* bash does not allow "{echo...", requires whitespace */
3638 ch
= i_getch(input
);
3639 if (ch
!= ' ' && ch
!= '\t' && ch
!= '\n') {
3640 syntax_error_unexpected_ch(ch
);
3643 nommu_addchr(&ctx
->as_string
, ch
);
3648 # define as_string NULL
3650 char *as_string
= NULL
;
3652 pipe_list
= parse_stream(&as_string
, input
, endch
);
3655 o_addstr(&ctx
->as_string
, as_string
);
3657 /* empty ()/{} or parse error? */
3658 if (!pipe_list
|| pipe_list
== ERR_PTR
) {
3659 /* parse_stream already emitted error msg */
3662 debug_printf_parse("parse_group return 1: "
3663 "parse_stream returned %p\n", pipe_list
);
3666 command
->group
= pipe_list
;
3668 as_string
[strlen(as_string
) - 1] = '\0'; /* plink ')' or '}' */
3669 command
->group_as_string
= as_string
;
3670 debug_printf_parse("end of group, remembering as:'%s'\n",
3671 command
->group_as_string
);
3675 debug_printf_parse("parse_group return 0\n");
3677 /* command remains "open", available for possible redirects */
3680 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3681 /* Subroutines for copying $(...) and `...` things */
3682 static int add_till_backquote(o_string
*dest
, struct in_str
*input
, int in_dquote
);
3684 static int add_till_single_quote(o_string
*dest
, struct in_str
*input
)
3687 int ch
= i_getch(input
);
3689 syntax_error_unterm_ch('\'');
3697 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3698 static int add_till_double_quote(o_string
*dest
, struct in_str
*input
)
3701 int ch
= i_getch(input
);
3703 syntax_error_unterm_ch('"');
3708 if (ch
== '\\') { /* \x. Copy both chars. */
3710 ch
= i_getch(input
);
3714 if (!add_till_backquote(dest
, input
, /*in_dquote:*/ 1))
3719 //if (ch == '$') ...
3722 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3724 * "Within the backquoted style of command substitution, backslash
3725 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3726 * The search for the matching backquote shall be satisfied by the first
3727 * backquote found without a preceding backslash; during this search,
3728 * if a non-escaped backquote is encountered within a shell comment,
3729 * a here-document, an embedded command substitution of the $(command)
3730 * form, or a quoted string, undefined results occur. A single-quoted
3731 * or double-quoted string that begins, but does not end, within the
3732 * "`...`" sequence produces undefined results."
3734 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3736 static int add_till_backquote(o_string
*dest
, struct in_str
*input
, int in_dquote
)
3739 int ch
= i_getch(input
);
3743 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3744 ch
= i_getch(input
);
3748 && (!in_dquote
|| ch
!= '"')
3750 o_addchr(dest
, '\\');
3754 syntax_error_unterm_ch('`');
3760 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3761 * quoting and nested ()s.
3762 * "With the $(command) style of command substitution, all characters
3763 * following the open parenthesis to the matching closing parenthesis
3764 * constitute the command. Any valid shell script can be used for command,
3765 * except a script consisting solely of redirections which produces
3766 * unspecified results."
3768 * echo $(echo '(TEST)' BEST) (TEST) BEST
3769 * echo $(echo 'TEST)' BEST) TEST) BEST
3770 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3772 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3773 * can contain arbitrary constructs, just like $(cmd).
3774 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3775 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3777 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3778 static int add_till_closing_bracket(o_string
*dest
, struct in_str
*input
, unsigned end_ch
)
3781 char dbl
= end_ch
& DOUBLE_CLOSE_CHAR_FLAG
;
3782 # if ENABLE_HUSH_BASH_COMPAT
3783 char end_char2
= end_ch
>> 8;
3785 end_ch
&= (DOUBLE_CLOSE_CHAR_FLAG
- 1);
3788 ch
= i_getch(input
);
3790 syntax_error_unterm_ch(end_ch
);
3793 if (ch
== end_ch
IF_HUSH_BASH_COMPAT( || ch
== end_char2
)) {
3796 /* we look for closing )) of $((EXPR)) */
3797 if (i_peek(input
) == end_ch
) {
3798 i_getch(input
); /* eat second ')' */
3803 if (ch
== '(' || ch
== '{') {
3804 ch
= (ch
== '(' ? ')' : '}');
3805 if (!add_till_closing_bracket(dest
, input
, ch
))
3811 if (!add_till_single_quote(dest
, input
))
3817 if (!add_till_double_quote(dest
, input
))
3823 if (!add_till_backquote(dest
, input
, /*in_dquote:*/ 0))
3829 /* \x. Copy verbatim. Important for \(, \) */
3830 ch
= i_getch(input
);
3832 syntax_error_unterm_ch(')');
3841 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3843 /* Return code: 0 for OK, 1 for syntax error */
3845 #define parse_dollar(as_string, dest, input, quote_mask) \
3846 parse_dollar(dest, input, quote_mask)
3847 #define as_string NULL
3849 static int parse_dollar(o_string
*as_string
,
3851 struct in_str
*input
, unsigned char quote_mask
)
3853 int ch
= i_peek(input
); /* first character after the $ */
3855 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch
);
3857 ch
= i_getch(input
);
3858 nommu_addchr(as_string
, ch
);
3860 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3862 debug_printf_parse(": '%c'\n", ch
);
3863 o_addchr(dest
, ch
| quote_mask
);
3866 if (!isalnum(ch
) && ch
!= '_')
3868 ch
= i_getch(input
);
3869 nommu_addchr(as_string
, ch
);
3871 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3872 } else if (isdigit(ch
)) {
3874 ch
= i_getch(input
);
3875 nommu_addchr(as_string
, ch
);
3876 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3877 debug_printf_parse(": '%c'\n", ch
);
3878 o_addchr(dest
, ch
| quote_mask
);
3879 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3880 } else switch (ch
) {
3882 case '!': /* last bg pid */
3883 case '?': /* last exit code */
3884 case '#': /* number of args */
3885 case '*': /* args */
3886 case '@': /* args */
3887 goto make_one_char_var
;
3889 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3891 ch
= i_getch(input
); /* eat '{' */
3892 nommu_addchr(as_string
, ch
);
3894 ch
= i_getch(input
); /* first char after '{' */
3895 /* It should be ${?}, or ${#var},
3896 * or even ${?+subst} - operator acting on a special variable,
3897 * or the beginning of variable name.
3900 || (!strchr(_SPECIAL_VARS_STR
, ch
) && !isalnum(ch
)) /* not one of those */
3903 syntax_error_unterm_str("${name}");
3904 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3907 nommu_addchr(as_string
, ch
);
3910 /* It's possible to just call add_till_closing_bracket() at this point.
3911 * However, this regresses some of our testsuite cases
3912 * which check invalid constructs like ${%}.
3913 * Oh well... let's check that the var name part is fine... */
3919 debug_printf_parse(": '%c'\n", ch
);
3921 ch
= i_getch(input
);
3922 nommu_addchr(as_string
, ch
);
3926 if (!isalnum(ch
) && ch
!= '_') {
3928 unsigned char last_ch
;
3929 /* handle parameter expansions
3930 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3932 if (!strchr(VAR_SUBST_OPS
, ch
)) /* ${var<bad_char>... */
3933 goto bad_dollar_syntax
;
3935 /* Eat everything until closing '}' (or ':') */
3937 if (ENABLE_HUSH_BASH_COMPAT
3939 && !strchr(MINUS_PLUS_EQUAL_QUESTION
, i_peek(input
))
3941 /* It's ${var:N[:M]} thing */
3942 end_ch
= '}' * 0x100 + ':';
3944 if (ENABLE_HUSH_BASH_COMPAT
3947 /* It's ${var/[/]pattern[/repl]} thing */
3948 if (i_peek(input
) == '/') { /* ${var//pattern[/repl]}? */
3950 nommu_addchr(as_string
, '/');
3953 end_ch
= '}' * 0x100 + '/';
3959 #if ENABLE_HUSH_DOLLAR_OPS
3960 last_ch
= add_till_closing_bracket(dest
, input
, end_ch
);
3961 if (last_ch
== 0) /* error? */
3964 #error Simple code to only allow ${var} is not implemented
3967 o_addstr(as_string
, dest
->data
+ pos
);
3968 o_addchr(as_string
, last_ch
);
3971 if (ENABLE_HUSH_BASH_COMPAT
&& (end_ch
& 0xff00)) {
3972 /* close the first block: */
3973 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3974 /* while parsing N from ${var:N[:M]}
3975 * or pattern from ${var/[/]pattern[/repl]} */
3976 if ((end_ch
& 0xff) == last_ch
) {
3977 /* got ':' or '/'- parse the rest */
3982 if (end_ch
== '}' * 0x100 + ':') {
3983 /* it's ${var:N} - emulate :999999999 */
3984 o_addstr(dest
, "999999999");
3985 } /* else: it's ${var/[/]pattern} */
3990 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
3993 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3997 ch
= i_getch(input
);
3998 nommu_addchr(as_string
, ch
);
3999 # if ENABLE_SH_MATH_SUPPORT
4000 if (i_peek(input
) == '(') {
4001 ch
= i_getch(input
);
4002 nommu_addchr(as_string
, ch
);
4003 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
4004 o_addchr(dest
, /*quote_mask |*/ '+');
4007 if (!add_till_closing_bracket(dest
, input
, ')' | DOUBLE_CLOSE_CHAR_FLAG
))
4008 return 0; /* error */
4010 o_addstr(as_string
, dest
->data
+ pos
);
4011 o_addchr(as_string
, ')');
4012 o_addchr(as_string
, ')');
4014 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
4018 # if ENABLE_HUSH_TICK
4019 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
4020 o_addchr(dest
, quote_mask
| '`');
4023 if (!add_till_closing_bracket(dest
, input
, ')'))
4024 return 0; /* error */
4026 o_addstr(as_string
, dest
->data
+ pos
);
4027 o_addchr(as_string
, ')');
4029 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
4035 ch
= i_getch(input
);
4036 nommu_addchr(as_string
, ch
);
4038 if (isalnum(ch
)) { /* it's $_name or $_123 */
4043 /* TODO: $_ and $-: */
4044 /* $_ Shell or shell script name; or last argument of last command
4045 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4046 * but in command's env, set to full pathname used to invoke it */
4047 /* $- Option flags set by set builtin or shell options (-i etc) */
4049 o_addQchr(dest
, '$');
4051 debug_printf_parse("parse_dollar return 1 (ok)\n");
4057 # if ENABLE_HUSH_BASH_COMPAT
4058 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4059 encode_string(dest, input, dquote_end, process_bkslash)
4061 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4062 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4063 encode_string(dest, input, dquote_end)
4065 #define as_string NULL
4069 # if ENABLE_HUSH_BASH_COMPAT
4070 /* all parameters are needed, no macro tricks */
4072 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4073 encode_string(as_string, dest, input, dquote_end)
4076 static int encode_string(o_string
*as_string
,
4078 struct in_str
*input
,
4080 int process_bkslash
)
4082 #if !ENABLE_HUSH_BASH_COMPAT
4083 const int process_bkslash
= 1;
4089 ch
= i_getch(input
);
4091 nommu_addchr(as_string
, ch
);
4092 if (ch
== dquote_end
) { /* may be only '"' or EOF */
4093 debug_printf_parse("encode_string return 1 (ok)\n");
4096 /* note: can't move it above ch == dquote_end check! */
4098 syntax_error_unterm_ch('"');
4099 return 0; /* error */
4103 next
= i_peek(input
);
4105 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4106 ch
, ch
, !!(dest
->o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
));
4107 if (process_bkslash
&& ch
== '\\') {
4109 syntax_error("\\<eof>");
4113 * "The backslash retains its special meaning [in "..."]
4114 * only when followed by one of the following characters:
4115 * $, `, ", \, or <newline>. A double quote may be quoted
4116 * within double quotes by preceding it with a backslash."
4117 * NB: in (unquoted) heredoc, above does not apply to ",
4118 * therefore we check for it by "next == dquote_end" cond.
4120 if (next
== dquote_end
|| strchr("$`\\\n", next
)) {
4121 ch
= i_getch(input
); /* eat next */
4123 goto again
; /* skip \<newline> */
4124 } /* else: ch remains == '\\', and we double it below: */
4125 o_addqchr(dest
, ch
); /* \c if c is a glob char, else just c */
4126 nommu_addchr(as_string
, ch
);
4130 if (!parse_dollar(as_string
, dest
, input
, /*quote_mask:*/ 0x80)) {
4131 debug_printf_parse("encode_string return 0: "
4132 "parse_dollar returned 0 (error)\n");
4137 #if ENABLE_HUSH_TICK
4139 //unsigned pos = dest->length;
4140 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
4141 o_addchr(dest
, 0x80 | '`');
4142 if (!add_till_backquote(dest
, input
, /*in_dquote:*/ dquote_end
== '"'))
4143 return 0; /* error */
4144 o_addchr(dest
, SPECIAL_VAR_SYMBOL
);
4145 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4149 o_addQchr(dest
, ch
);
4155 * Scan input until EOF or end_trigger char.
4156 * Return a list of pipes to execute, or NULL on EOF
4157 * or if end_trigger character is met.
4158 * On syntax error, exit if shell is not interactive,
4159 * reset parsing machinery and start parsing anew,
4160 * or return ERR_PTR.
4162 static struct pipe
*parse_stream(char **pstring
,
4163 struct in_str
*input
,
4166 struct parse_context ctx
;
4167 o_string dest
= NULL_O_STRING
;
4170 /* Single-quote triggers a bypass of the main loop until its mate is
4171 * found. When recursing, quote state is passed in via dest->o_expflags.
4173 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4174 end_trigger
? end_trigger
: 'X');
4177 /* If very first arg is "" or '', dest.data may end up NULL.
4178 * Preventing this: */
4179 o_addchr(&dest
, '\0');
4182 /* We used to separate words on $IFS here. This was wrong.
4183 * $IFS is used only for word splitting when $var is expanded,
4184 * here we should use blank chars as separators, not $IFS
4187 if (MAYBE_ASSIGNMENT
!= 0)
4188 dest
.o_assignment
= MAYBE_ASSIGNMENT
;
4189 initialize_context(&ctx
);
4192 const char *is_blank
;
4193 const char *is_special
;
4197 redir_type redir_style
;
4199 ch
= i_getch(input
);
4200 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4201 ch
, ch
, !!(dest
.o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
));
4206 syntax_error_unterm_str("here document");
4209 /* end_trigger == '}' case errors out earlier,
4210 * checking only ')' */
4211 if (end_trigger
== ')') {
4212 syntax_error_unterm_ch('(');
4216 if (done_word(&dest
, &ctx
)) {
4220 done_pipe(&ctx
, PIPE_SEQ
);
4222 /* If we got nothing... */
4223 /* (this makes bare "&" cmd a no-op.
4224 * bash says: "syntax error near unexpected token '&'") */
4225 if (pi
->num_cmds
== 0
4226 IF_HAS_KEYWORDS( && pi
->res_word
== RES_NONE
)
4232 debug_printf_parse("as_string '%s'\n", ctx
.as_string
.data
);
4234 *pstring
= ctx
.as_string
.data
;
4236 o_free_unsafe(&ctx
.as_string
);
4239 debug_printf_parse("parse_stream return %p\n", pi
);
4242 nommu_addchr(&ctx
.as_string
, ch
);
4246 next
= i_peek(input
);
4248 is_special
= "{}<>;&|()#'" /* special outside of "str" */
4249 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4250 /* Are { and } special here? */
4251 if (ctx
.command
->argv
/* word [word]{... - non-special */
4252 || dest
.length
/* word{... - non-special */
4253 || dest
.has_quoted_part
/* ""{... - non-special */
4254 || (next
!= ';' /* }; - special */
4255 && next
!= ')' /* }) - special */
4256 && next
!= '&' /* }& and }&& ... - special */
4257 && next
!= '|' /* }|| ... - special */
4258 && !strchr(defifs
, next
) /* {word - non-special */
4261 /* They are not special, skip "{}" */
4264 is_special
= strchr(is_special
, ch
);
4265 is_blank
= strchr(defifs
, ch
);
4267 if (!is_special
&& !is_blank
) { /* ordinary char */
4269 o_addQchr(&dest
, ch
);
4270 if ((dest
.o_assignment
== MAYBE_ASSIGNMENT
4271 || dest
.o_assignment
== WORD_IS_KEYWORD
)
4273 && is_well_formed_var_name(dest
.data
, '=')
4275 dest
.o_assignment
= DEFINITELY_ASSIGNMENT
;
4276 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag
[dest
.o_assignment
]);
4282 if (done_word(&dest
, &ctx
)) {
4286 /* Is this a case when newline is simply ignored?
4288 * "cmd | <newline> cmd ..."
4289 * "case ... in <newline> word) ..."
4291 if (IS_NULL_CMD(ctx
.command
)
4292 && dest
.length
== 0 && !dest
.has_quoted_part
4294 /* This newline can be ignored. But...
4295 * Without check #1, interactive shell
4296 * ignores even bare <newline>,
4297 * and shows the continuation prompt:
4298 * ps1_prompt$ <enter>
4299 * ps2> _ <=== wrong, should be ps1
4300 * Without check #2, "cmd & <newline>"
4301 * is similarly mistreated.
4302 * (BTW, this makes "cmd & cmd"
4303 * and "cmd && cmd" non-orthogonal.
4304 * Really, ask yourself, why
4305 * "cmd && <newline>" doesn't start
4306 * cmd but waits for more input?
4309 struct pipe
*pi
= ctx
.list_head
;
4310 if (pi
->num_cmds
!= 0 /* check #1 */
4311 && pi
->followup
!= PIPE_BG
/* check #2 */
4316 /* Treat newline as a command separator. */
4317 done_pipe(&ctx
, PIPE_SEQ
);
4318 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt
);
4320 if (fetch_heredocs(heredoc_cnt
, &ctx
, input
)) {
4325 dest
.o_assignment
= MAYBE_ASSIGNMENT
;
4326 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag
[dest
.o_assignment
]);
4328 /* note: if (is_blank) continue;
4329 * will still trigger for us */
4333 /* "cmd}" or "cmd }..." without semicolon or &:
4334 * } is an ordinary char in this case, even inside { cmd; }
4335 * Pathological example: { ""}; } should exec "}" cmd
4338 if (!IS_NULL_CMD(ctx
.command
) /* cmd } */
4339 || dest
.length
!= 0 /* word} */
4340 || dest
.has_quoted_part
/* ""} */
4344 if (!IS_NULL_PIPE(ctx
.pipe
)) /* cmd | } */
4345 goto skip_end_trigger
;
4346 /* else: } does terminate a group */
4349 if (end_trigger
&& end_trigger
== ch
4350 && (ch
!= ';' || heredoc_cnt
== 0)
4351 #if ENABLE_HUSH_CASE
4353 || ctx
.ctx_res_w
!= RES_MATCH
4354 || (!dest
.has_quoted_part
&& strcmp(dest
.data
, "esac") == 0)
4359 /* This is technically valid:
4360 * { cat <<HERE; }; echo Ok
4364 * but we don't support this.
4365 * We require heredoc to be in enclosing {}/(),
4368 syntax_error_unterm_str("here document");
4371 if (done_word(&dest
, &ctx
)) {
4374 done_pipe(&ctx
, PIPE_SEQ
);
4375 dest
.o_assignment
= MAYBE_ASSIGNMENT
;
4376 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag
[dest
.o_assignment
]);
4377 /* Do we sit outside of any if's, loops or case's? */
4379 IF_HAS_KEYWORDS(|| (ctx
.ctx_res_w
== RES_NONE
&& ctx
.old_flag
== 0))
4383 debug_printf_parse("as_string '%s'\n", ctx
.as_string
.data
);
4385 *pstring
= ctx
.as_string
.data
;
4387 o_free_unsafe(&ctx
.as_string
);
4390 debug_printf_parse("parse_stream return %p: "
4391 "end_trigger char found\n",
4393 return ctx
.list_head
;
4400 /* Catch <, > before deciding whether this word is
4401 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4404 redir_fd
= redirect_opt_num(&dest
);
4405 if (done_word(&dest
, &ctx
)) {
4408 redir_style
= REDIRECT_OVERWRITE
;
4410 redir_style
= REDIRECT_APPEND
;
4411 ch
= i_getch(input
);
4412 nommu_addchr(&ctx
.as_string
, ch
);
4415 else if (next
== '(') {
4416 syntax_error(">(process) not supported");
4420 if (parse_redirect(&ctx
, redir_fd
, redir_style
, input
))
4422 continue; /* back to top of while (1) */
4424 redir_fd
= redirect_opt_num(&dest
);
4425 if (done_word(&dest
, &ctx
)) {
4428 redir_style
= REDIRECT_INPUT
;
4430 redir_style
= REDIRECT_HEREDOC
;
4432 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt
);
4433 ch
= i_getch(input
);
4434 nommu_addchr(&ctx
.as_string
, ch
);
4435 } else if (next
== '>') {
4436 redir_style
= REDIRECT_IO
;
4437 ch
= i_getch(input
);
4438 nommu_addchr(&ctx
.as_string
, ch
);
4441 else if (next
== '(') {
4442 syntax_error("<(process) not supported");
4446 if (parse_redirect(&ctx
, redir_fd
, redir_style
, input
))
4448 continue; /* back to top of while (1) */
4450 if (dest
.length
== 0 && !dest
.has_quoted_part
) {
4451 /* skip "#comment" */
4454 if (ch
== EOF
|| ch
== '\n')
4457 /* note: we do not add it to &ctx.as_string */
4459 nommu_addchr(&ctx
.as_string
, '\n');
4460 continue; /* back to top of while (1) */
4465 /* It's "\<newline>" */
4467 /* Remove trailing '\' from ctx.as_string */
4468 ctx
.as_string
.data
[--ctx
.as_string
.length
] = '\0';
4470 ch
= i_getch(input
); /* eat it */
4471 continue; /* back to top of while (1) */
4476 if (dest
.o_assignment
== MAYBE_ASSIGNMENT
4477 /* check that we are not in word in "a=1 2>word b=1": */
4478 && !ctx
.pending_redirect
4480 /* ch is a special char and thus this word
4481 * cannot be an assignment */
4482 dest
.o_assignment
= NOT_ASSIGNMENT
;
4483 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag
[dest
.o_assignment
]);
4486 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4489 case '#': /* non-comment #: "echo a#b" etc */
4490 o_addQchr(&dest
, ch
);
4494 syntax_error("\\<eof>");
4497 ch
= i_getch(input
);
4498 /* note: ch != '\n' (that case does not reach this place) */
4499 o_addchr(&dest
, '\\');
4500 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4501 o_addchr(&dest
, ch
);
4502 nommu_addchr(&ctx
.as_string
, ch
);
4503 /* Example: echo Hello \2>file
4504 * we need to know that word 2 is quoted */
4505 dest
.has_quoted_part
= 1;
4508 if (!parse_dollar(&ctx
.as_string
, &dest
, input
, /*quote_mask:*/ 0)) {
4509 debug_printf_parse("parse_stream parse error: "
4510 "parse_dollar returned 0 (error)\n");
4515 dest
.has_quoted_part
= 1;
4516 if (next
== '\'' && !ctx
.pending_redirect
) {
4517 insert_empty_quoted_str_marker
:
4518 nommu_addchr(&ctx
.as_string
, next
);
4519 i_getch(input
); /* eat second ' */
4520 o_addchr(&dest
, SPECIAL_VAR_SYMBOL
);
4521 o_addchr(&dest
, SPECIAL_VAR_SYMBOL
);
4524 ch
= i_getch(input
);
4526 syntax_error_unterm_ch('\'');
4529 nommu_addchr(&ctx
.as_string
, ch
);
4532 o_addqchr(&dest
, ch
);
4537 dest
.has_quoted_part
= 1;
4538 if (next
== '"' && !ctx
.pending_redirect
)
4539 goto insert_empty_quoted_str_marker
;
4540 if (dest
.o_assignment
== NOT_ASSIGNMENT
)
4541 dest
.o_expflags
|= EXP_FLAG_ESC_GLOB_CHARS
;
4542 if (!encode_string(&ctx
.as_string
, &dest
, input
, '"', /*process_bkslash:*/ 1))
4544 dest
.o_expflags
&= ~EXP_FLAG_ESC_GLOB_CHARS
;
4546 #if ENABLE_HUSH_TICK
4548 USE_FOR_NOMMU(unsigned pos
;)
4550 o_addchr(&dest
, SPECIAL_VAR_SYMBOL
);
4551 o_addchr(&dest
, '`');
4552 USE_FOR_NOMMU(pos
= dest
.length
;)
4553 if (!add_till_backquote(&dest
, input
, /*in_dquote:*/ 0))
4556 o_addstr(&ctx
.as_string
, dest
.data
+ pos
);
4557 o_addchr(&ctx
.as_string
, '`');
4559 o_addchr(&dest
, SPECIAL_VAR_SYMBOL
);
4560 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4565 #if ENABLE_HUSH_CASE
4568 if (done_word(&dest
, &ctx
)) {
4571 done_pipe(&ctx
, PIPE_SEQ
);
4572 #if ENABLE_HUSH_CASE
4573 /* Eat multiple semicolons, detect
4574 * whether it means something special */
4579 ch
= i_getch(input
);
4580 nommu_addchr(&ctx
.as_string
, ch
);
4581 if (ctx
.ctx_res_w
== RES_CASE_BODY
) {
4582 ctx
.ctx_dsemicolon
= 1;
4583 ctx
.ctx_res_w
= RES_MATCH
;
4589 /* We just finished a cmd. New one may start
4590 * with an assignment */
4591 dest
.o_assignment
= MAYBE_ASSIGNMENT
;
4592 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag
[dest
.o_assignment
]);
4595 if (done_word(&dest
, &ctx
)) {
4599 ch
= i_getch(input
);
4600 nommu_addchr(&ctx
.as_string
, ch
);
4601 done_pipe(&ctx
, PIPE_AND
);
4603 done_pipe(&ctx
, PIPE_BG
);
4607 if (done_word(&dest
, &ctx
)) {
4610 #if ENABLE_HUSH_CASE
4611 if (ctx
.ctx_res_w
== RES_MATCH
)
4612 break; /* we are in case's "word | word)" */
4614 if (next
== '|') { /* || */
4615 ch
= i_getch(input
);
4616 nommu_addchr(&ctx
.as_string
, ch
);
4617 done_pipe(&ctx
, PIPE_OR
);
4619 /* we could pick up a file descriptor choice here
4620 * with redirect_opt_num(), but bash doesn't do it.
4621 * "echo foo 2| cat" yields "foo 2". */
4624 o_reset_to_empty_unquoted(&ctx
.as_string
);
4629 #if ENABLE_HUSH_CASE
4630 /* "case... in [(]word)..." - skip '(' */
4631 if (ctx
.ctx_res_w
== RES_MATCH
4632 && ctx
.command
->argv
== NULL
/* not (word|(... */
4633 && dest
.length
== 0 /* not word(... */
4634 && dest
.has_quoted_part
== 0 /* not ""(... */
4640 if (parse_group(&dest
, &ctx
, input
, ch
) != 0) {
4645 #if ENABLE_HUSH_CASE
4646 if (ctx
.ctx_res_w
== RES_MATCH
)
4650 /* proper use of this character is caught by end_trigger:
4651 * if we see {, we call parse_group(..., end_trigger='}')
4652 * and it will match } earlier (not here). */
4653 syntax_error_unexpected_ch(ch
);
4657 bb_error_msg_and_die("BUG: unexpected %c\n", ch
);
4663 struct parse_context
*pctx
;
4664 IF_HAS_KEYWORDS(struct parse_context
*p2
;)
4666 /* Clean up allocated tree.
4667 * Sample for finding leaks on syntax error recovery path.
4668 * Run it from interactive shell, watch pmap `pidof hush`.
4669 * while if false; then false; fi; do break; fi
4670 * Samples to catch leaks at execution:
4671 * while if (true | {true;}); then echo ok; fi; do break; done
4672 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4676 /* Update pipe/command counts,
4677 * otherwise freeing may miss some */
4678 done_pipe(pctx
, PIPE_SEQ
);
4679 debug_printf_clean("freeing list %p from ctx %p\n",
4680 pctx
->list_head
, pctx
);
4681 debug_print_tree(pctx
->list_head
, 0);
4682 free_pipe_list(pctx
->list_head
);
4683 debug_printf_clean("freed list %p\n", pctx
->list_head
);
4685 o_free_unsafe(&pctx
->as_string
);
4687 IF_HAS_KEYWORDS(p2
= pctx
->stack
;)
4691 IF_HAS_KEYWORDS(pctx
= p2
;)
4692 } while (HAS_KEYWORDS
&& pctx
);
4695 G
.last_exitcode
= 1;
4706 /*** Execution routines ***/
4708 /* Expansion can recurse, need forward decls: */
4709 #if !ENABLE_HUSH_BASH_COMPAT
4710 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4711 #define expand_string_to_string(str, do_unbackslash) \
4712 expand_string_to_string(str)
4714 static char *expand_string_to_string(const char *str
, int do_unbackslash
);
4715 #if ENABLE_HUSH_TICK
4716 static int process_command_subs(o_string
*dest
, const char *s
);
4719 /* expand_strvec_to_strvec() takes a list of strings, expands
4720 * all variable references within and returns a pointer to
4721 * a list of expanded strings, possibly with larger number
4722 * of strings. (Think VAR="a b"; echo $VAR).
4723 * This new list is allocated as a single malloc block.
4724 * NULL-terminated list of char* pointers is at the beginning of it,
4725 * followed by strings themselves.
4726 * Caller can deallocate entire list by single free(list). */
4728 /* A horde of its helpers come first: */
4730 static void o_addblock_duplicate_backslash(o_string
*o
, const char *str
, int len
)
4732 while (--len
>= 0) {
4735 #if ENABLE_HUSH_BRACE_EXPANSION
4736 if (c
== '{' || c
== '}') {
4737 /* { -> \{, } -> \} */
4739 /* And now we want to add { or } and continue:
4742 * luckily, just falling throught achieves this.
4748 /* \z -> \\\z; \<eol> -> \\<eol> */
4753 o_addchr(o
, *str
++);
4759 /* Store given string, finalizing the word and starting new one whenever
4760 * we encounter IFS char(s). This is used for expanding variable values.
4761 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4762 * Return in *ended_with_ifs:
4763 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4765 static int expand_on_ifs(int *ended_with_ifs
, o_string
*output
, int n
, const char *str
)
4767 int last_is_ifs
= 0;
4772 if (!*str
) /* EOL - do not finalize word */
4774 word_len
= strcspn(str
, G
.ifs
);
4776 /* We have WORD_LEN leading non-IFS chars */
4777 if (!(output
->o_expflags
& EXP_FLAG_GLOB
)) {
4778 o_addblock(output
, str
, word_len
);
4780 /* Protect backslashes against globbing up :)
4781 * Example: "v='\*'; echo b$v" prints "b\*"
4782 * (and does not try to glob on "*")
4784 o_addblock_duplicate_backslash(output
, str
, word_len
);
4785 /*/ Why can't we do it easier? */
4786 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4787 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4791 if (!*str
) /* EOL - do not finalize word */
4795 /* We know str here points to at least one IFS char */
4797 str
+= strspn(str
, G
.ifs
); /* skip IFS chars */
4798 if (!*str
) /* EOL - do not finalize word */
4801 /* Start new word... but not always! */
4802 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
4803 if (output
->has_quoted_part
4804 /* Case "v=' a'; echo $v":
4805 * here nothing precedes the space in $v expansion,
4806 * therefore we should not finish the word
4807 * (IOW: if there *is* word to finalize, only then do it):
4809 || (n
> 0 && output
->data
[output
->length
- 1])
4811 o_addchr(output
, '\0');
4812 debug_print_list("expand_on_ifs", output
, n
);
4813 n
= o_save_ptr(output
, n
);
4818 *ended_with_ifs
= last_is_ifs
;
4819 debug_print_list("expand_on_ifs[1]", output
, n
);
4823 /* Helper to expand $((...)) and heredoc body. These act as if
4824 * they are in double quotes, with the exception that they are not :).
4825 * Just the rules are similar: "expand only $var and `cmd`"
4827 * Returns malloced string.
4828 * As an optimization, we return NULL if expansion is not needed.
4830 #if !ENABLE_HUSH_BASH_COMPAT
4831 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4832 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4833 encode_then_expand_string(str)
4835 static char *encode_then_expand_string(const char *str
, int process_bkslash
, int do_unbackslash
)
4838 struct in_str input
;
4839 o_string dest
= NULL_O_STRING
;
4841 if (!strchr(str
, '$')
4842 && !strchr(str
, '\\')
4843 #if ENABLE_HUSH_TICK
4844 && !strchr(str
, '`')
4850 /* We need to expand. Example:
4851 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4853 setup_string_in_str(&input
, str
);
4854 encode_string(NULL
, &dest
, &input
, EOF
, process_bkslash
);
4855 //TODO: error check (encode_string returns 0 on error)?
4856 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4857 exp_str
= expand_string_to_string(dest
.data
, /*unbackslash:*/ do_unbackslash
);
4858 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4859 o_free_unsafe(&dest
);
4863 #if ENABLE_SH_MATH_SUPPORT
4864 static arith_t
expand_and_evaluate_arith(const char *arg
, const char **errmsg_p
)
4866 arith_state_t math_state
;
4870 math_state
.lookupvar
= get_local_var_value
;
4871 math_state
.setvar
= set_local_var_from_halves
;
4872 //math_state.endofname = endofname;
4873 exp_str
= encode_then_expand_string(arg
, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4874 res
= arith(&math_state
, exp_str
? exp_str
: arg
);
4877 *errmsg_p
= math_state
.errmsg
;
4878 if (math_state
.errmsg
)
4879 die_if_script(math_state
.errmsg
);
4884 #if ENABLE_HUSH_BASH_COMPAT
4885 /* ${var/[/]pattern[/repl]} helpers */
4886 static char *strstr_pattern(char *val
, const char *pattern
, int *size
)
4889 char *end
= scan_and_match(val
, pattern
, SCAN_MOVE_FROM_RIGHT
+ SCAN_MATCH_LEFT_HALF
);
4890 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val
, pattern
, end
);
4897 /* Optimization: if "*pat" did not match the start of "string",
4898 * we know that "tring", "ring" etc will not match too:
4900 if (pattern
[0] == '*')
4905 static char *replace_pattern(char *val
, const char *pattern
, const char *repl
, char exp_op
)
4907 char *result
= NULL
;
4908 unsigned res_len
= 0;
4909 unsigned repl_len
= strlen(repl
);
4913 char *s
= strstr_pattern(val
, pattern
, &size
);
4917 result
= xrealloc(result
, res_len
+ (s
- val
) + repl_len
+ 1);
4918 memcpy(result
+ res_len
, val
, s
- val
);
4920 strcpy(result
+ res_len
, repl
);
4921 res_len
+= repl_len
;
4922 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val
, s
, result
);
4928 if (val
[0] && result
) {
4929 result
= xrealloc(result
, res_len
+ strlen(val
) + 1);
4930 strcpy(result
+ res_len
, val
);
4931 debug_printf_varexp("val:'%s' result:'%s'\n", val
, result
);
4933 debug_printf_varexp("result:'%s'\n", result
);
4939 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4941 static NOINLINE
const char *expand_one_var(char **to_be_freed_pp
, char *arg
, char **pp
)
4943 const char *val
= NULL
;
4944 char *to_be_freed
= NULL
;
4949 char exp_save
= exp_save
; /* for compiler */
4950 char *exp_saveptr
; /* points to expansion operator */
4951 char *exp_word
= exp_word
; /* for compiler */
4954 *p
= '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4956 exp_saveptr
= arg
[1] ? strchr(VAR_ENCODED_SUBST_OPS
, arg
[1]) : NULL
;
4958 first_char
= arg
[0] = arg0
& 0x7f;
4961 if (first_char
== '#' /* ${#... */
4962 && arg
[1] && !exp_saveptr
/* not ${#} and not ${#<op_char>...} */
4964 /* It must be length operator: ${#var} */
4968 /* Maybe handle parameter expansion */
4969 if (exp_saveptr
/* if 2nd char is one of expansion operators */
4970 && strchr(NUMERIC_SPECVARS_STR
, first_char
) /* 1st char is special variable */
4972 /* ${?:0}, ${#[:]%0} etc */
4973 exp_saveptr
= var
+ 1;
4975 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4976 exp_saveptr
= var
+1 + strcspn(var
+1, VAR_ENCODED_SUBST_OPS
);
4978 exp_op
= exp_save
= *exp_saveptr
;
4980 exp_word
= exp_saveptr
+ 1;
4981 if (exp_op
== ':') {
4982 exp_op
= *exp_word
++;
4983 //TODO: try ${var:} and ${var:bogus} in non-bash config
4984 if (ENABLE_HUSH_BASH_COMPAT
4985 && (!exp_op
|| !strchr(MINUS_PLUS_EQUAL_QUESTION
, exp_op
))
4987 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4992 *exp_saveptr
= '\0';
4993 } /* else: it's not an expansion op, but bare ${var} */
4996 /* Look up the variable in question */
4997 if (isdigit(var
[0])) {
4998 /* parse_dollar should have vetted var for us */
4999 int n
= xatoi_positive(var
);
5000 if (n
< G
.global_argc
)
5001 val
= G
.global_argv
[n
];
5002 /* else val remains NULL: $N with too big N */
5006 val
= utoa(G
.root_pid
);
5008 case '!': /* bg pid */
5009 val
= G
.last_bg_pid
? utoa(G
.last_bg_pid
) : "";
5011 case '?': /* exitcode */
5012 val
= utoa(G
.last_exitcode
);
5014 case '#': /* argc */
5015 val
= utoa(G
.global_argc
? G
.global_argc
-1 : 0);
5018 val
= get_local_var_value(var
);
5022 /* Handle any expansions */
5023 if (exp_op
== 'L') {
5024 debug_printf_expand("expand: length(%s)=", val
);
5025 val
= utoa(val
? strlen(val
) : 0);
5026 debug_printf_expand("%s\n", val
);
5027 } else if (exp_op
) {
5028 if (exp_op
== '%' || exp_op
== '#') {
5029 /* Standard-mandated substring removal ops:
5030 * ${parameter%word} - remove smallest suffix pattern
5031 * ${parameter%%word} - remove largest suffix pattern
5032 * ${parameter#word} - remove smallest prefix pattern
5033 * ${parameter##word} - remove largest prefix pattern
5035 * Word is expanded to produce a glob pattern.
5036 * Then var's value is matched to it and matching part removed.
5038 if (val
&& val
[0]) {
5042 unsigned scan_flags
= pick_scan(exp_op
, *exp_word
);
5043 if (exp_op
== *exp_word
) /* ## or %% */
5045 exp_exp_word
= encode_then_expand_string(exp_word
, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5047 exp_word
= exp_exp_word
;
5048 /* HACK ALERT. We depend here on the fact that
5049 * G.global_argv and results of utoa and get_local_var_value
5050 * are actually in writable memory:
5051 * scan_and_match momentarily stores NULs there. */
5053 loc
= scan_and_match(t
, exp_word
, scan_flags
);
5054 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5055 // exp_op, t, exp_word, loc);
5057 if (loc
) { /* match was found */
5058 if (scan_flags
& SCAN_MATCH_LEFT_HALF
) /* #[#] */
5059 val
= loc
; /* take right part */
5061 val
= to_be_freed
= xstrndup(val
, loc
- val
); /* left */
5065 #if ENABLE_HUSH_BASH_COMPAT
5066 else if (exp_op
== '/' || exp_op
== '\\') {
5067 /* It's ${var/[/]pattern[/repl]} thing.
5068 * Note that in encoded form it has TWO parts:
5069 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5070 * and if // is used, it is encoded as \:
5071 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5073 /* Empty variable always gives nothing: */
5074 // "v=''; echo ${v/*/w}" prints "", not "w"
5075 if (val
&& val
[0]) {
5076 /* pattern uses non-standard expansion.
5077 * repl should be unbackslashed and globbed
5078 * by the usual expansion rules:
5080 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5081 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5082 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5083 * v='a bz'; echo ${v/a*z/\z} prints "z"
5084 * (note that a*z _pattern_ is never globbed!)
5086 char *pattern
, *repl
, *t
;
5087 pattern
= encode_then_expand_string(exp_word
, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5089 pattern
= xstrdup(exp_word
);
5090 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word
, pattern
);
5091 *p
++ = SPECIAL_VAR_SYMBOL
;
5093 p
= strchr(p
, SPECIAL_VAR_SYMBOL
);
5095 repl
= encode_then_expand_string(exp_word
, /*process_bkslash:*/ arg0
& 0x80, /*unbackslash:*/ 1);
5096 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word
, repl
);
5097 /* HACK ALERT. We depend here on the fact that
5098 * G.global_argv and results of utoa and get_local_var_value
5099 * are actually in writable memory:
5100 * replace_pattern momentarily stores NULs there. */
5102 to_be_freed
= replace_pattern(t
,
5104 (repl
? repl
: exp_word
),
5106 if (to_be_freed
) /* at least one replace happened */
5113 else if (exp_op
== ':') {
5114 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5115 /* It's ${var:N[:M]} bashism.
5116 * Note that in encoded form it has TWO parts:
5117 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5122 beg
= expand_and_evaluate_arith(exp_word
, &errmsg
);
5125 debug_printf_varexp("beg:'%s'=%lld\n", exp_word
, (long long)beg
);
5126 *p
++ = SPECIAL_VAR_SYMBOL
;
5128 p
= strchr(p
, SPECIAL_VAR_SYMBOL
);
5130 len
= expand_and_evaluate_arith(exp_word
, &errmsg
);
5133 debug_printf_varexp("len:'%s'=%lld\n", exp_word
, (long long)len
);
5134 if (len
>= 0) { /* bash compat: len < 0 is illegal */
5135 if (beg
< 0) /* bash compat */
5137 debug_printf_varexp("from val:'%s'\n", val
);
5138 if (len
== 0 || !val
|| beg
>= strlen(val
)) {
5142 /* Paranoia. What if user entered 9999999999999
5143 * which fits in arith_t but not int? */
5146 val
= to_be_freed
= xstrndup(val
+ beg
, len
);
5148 debug_printf_varexp("val:'%s'\n", val
);
5152 die_if_script("malformed ${%s:...}", var
);
5155 } else { /* one of "-=+?" */
5156 /* Standard-mandated substitution ops:
5157 * ${var?word} - indicate error if unset
5158 * If var is unset, word (or a message indicating it is unset
5159 * if word is null) is written to standard error
5160 * and the shell exits with a non-zero exit status.
5161 * Otherwise, the value of var is substituted.
5162 * ${var-word} - use default value
5163 * If var is unset, word is substituted.
5164 * ${var=word} - assign and use default value
5165 * If var is unset, word is assigned to var.
5166 * In all cases, final value of var is substituted.
5167 * ${var+word} - use alternative value
5168 * If var is unset, null is substituted.
5169 * Otherwise, word is substituted.
5171 * Word is subjected to tilde expansion, parameter expansion,
5172 * command substitution, and arithmetic expansion.
5173 * If word is not needed, it is not expanded.
5175 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5176 * but also treat null var as if it is unset.
5178 int use_word
= (!val
|| ((exp_save
== ':') && !val
[0]));
5180 use_word
= !use_word
;
5181 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op
,
5182 (exp_save
== ':') ? "true" : "false", use_word
);
5184 to_be_freed
= encode_then_expand_string(exp_word
, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5186 exp_word
= to_be_freed
;
5187 if (exp_op
== '?') {
5188 /* mimic bash message */
5189 die_if_script("%s: %s",
5191 exp_word
[0] ? exp_word
: "parameter null or not set"
5193 //TODO: how interactive bash aborts expansion mid-command?
5198 if (exp_op
== '=') {
5199 /* ${var=[word]} or ${var:=[word]} */
5200 if (isdigit(var
[0]) || var
[0] == '#') {
5201 /* mimic bash message */
5202 die_if_script("$%s: cannot assign in this way", var
);
5205 char *new_var
= xasprintf("%s=%s", var
, val
);
5206 set_local_var(new_var
, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5210 } /* one of "-=+?" */
5212 *exp_saveptr
= exp_save
;
5218 *to_be_freed_pp
= to_be_freed
;
5222 /* Expand all variable references in given string, adding words to list[]
5223 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5224 * to be filled). This routine is extremely tricky: has to deal with
5225 * variables/parameters with whitespace, $* and $@, and constructs like
5226 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5227 static NOINLINE
int expand_vars_to_list(o_string
*output
, int n
, char *arg
)
5229 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5230 * expansion of right-hand side of assignment == 1-element expand.
5232 char cant_be_null
= 0; /* only bit 0x80 matters */
5233 int ended_in_ifs
= 0; /* did last unquoted expansion end with IFS chars? */
5236 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg
,
5237 !!(output
->o_expflags
& EXP_FLAG_SINGLEWORD
));
5238 debug_print_list("expand_vars_to_list", output
, n
);
5239 n
= o_save_ptr(output
, n
);
5240 debug_print_list("expand_vars_to_list[0]", output
, n
);
5242 while ((p
= strchr(arg
, SPECIAL_VAR_SYMBOL
)) != NULL
) {
5244 char *to_be_freed
= NULL
;
5245 const char *val
= NULL
;
5246 #if ENABLE_HUSH_TICK
5247 o_string subst_result
= NULL_O_STRING
;
5249 #if ENABLE_SH_MATH_SUPPORT
5250 char arith_buf
[sizeof(arith_t
)*3 + 2];
5254 o_addchr(output
, '\0');
5255 n
= o_save_ptr(output
, n
);
5259 o_addblock(output
, arg
, p
- arg
);
5260 debug_print_list("expand_vars_to_list[1]", output
, n
);
5262 p
= strchr(p
, SPECIAL_VAR_SYMBOL
);
5264 /* Fetch special var name (if it is indeed one of them)
5265 * and quote bit, force the bit on if singleword expansion -
5266 * important for not getting v=$@ expand to many words. */
5267 first_ch
= arg
[0] | (output
->o_expflags
& EXP_FLAG_SINGLEWORD
);
5269 /* Is this variable quoted and thus expansion can't be null?
5270 * "$@" is special. Even if quoted, it can still
5271 * expand to nothing (not even an empty string),
5272 * thus it is excluded. */
5273 if ((first_ch
& 0x7f) != '@')
5274 cant_be_null
|= first_ch
;
5276 switch (first_ch
& 0x7f) {
5277 /* Highest bit in first_ch indicates that var is double-quoted */
5281 if (!G
.global_argv
[1])
5284 cant_be_null
|= first_ch
; /* do it for "$@" _now_, when we know it's not empty */
5285 if (!(first_ch
& 0x80)) { /* unquoted $* or $@ */
5286 while (G
.global_argv
[i
]) {
5287 n
= expand_on_ifs(NULL
, output
, n
, G
.global_argv
[i
]);
5288 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i
, G
.global_argc
- 1);
5289 if (G
.global_argv
[i
++][0] && G
.global_argv
[i
]) {
5290 /* this argv[] is not empty and not last:
5291 * put terminating NUL, start new word */
5292 o_addchr(output
, '\0');
5293 debug_print_list("expand_vars_to_list[2]", output
, n
);
5294 n
= o_save_ptr(output
, n
);
5295 debug_print_list("expand_vars_to_list[3]", output
, n
);
5299 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5300 * and in this case should treat it like '$*' - see 'else...' below */
5301 if (first_ch
== ('@'|0x80) /* quoted $@ */
5302 && !(output
->o_expflags
& EXP_FLAG_SINGLEWORD
) /* not v="$@" case */
5305 o_addQstr(output
, G
.global_argv
[i
]);
5306 if (++i
>= G
.global_argc
)
5308 o_addchr(output
, '\0');
5309 debug_print_list("expand_vars_to_list[4]", output
, n
);
5310 n
= o_save_ptr(output
, n
);
5312 } else { /* quoted $* (or v="$@" case): add as one word */
5314 o_addQstr(output
, G
.global_argv
[i
]);
5315 if (!G
.global_argv
[++i
])
5318 o_addchr(output
, G
.ifs
[0]);
5320 output
->has_quoted_part
= 1;
5324 case SPECIAL_VAR_SYMBOL
: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5325 /* "Empty variable", used to make "" etc to not disappear */
5326 output
->has_quoted_part
= 1;
5328 cant_be_null
= 0x80;
5330 #if ENABLE_HUSH_TICK
5331 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5332 *p
= '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5334 /* Can't just stuff it into output o_string,
5335 * expanded result may need to be globbed
5336 * and $IFS-splitted */
5337 debug_printf_subst("SUBST '%s' first_ch %x\n", arg
, first_ch
);
5338 G
.last_exitcode
= process_command_subs(&subst_result
, arg
);
5339 debug_printf_subst("SUBST RES:%d '%s'\n", G
.last_exitcode
, subst_result
.data
);
5340 val
= subst_result
.data
;
5343 #if ENABLE_SH_MATH_SUPPORT
5344 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5347 arg
++; /* skip '+' */
5348 *p
= '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5349 debug_printf_subst("ARITH '%s' first_ch %x\n", arg
, first_ch
);
5350 res
= expand_and_evaluate_arith(arg
, NULL
);
5351 debug_printf_subst("ARITH RES '"ARITH_FMT
"'\n", res
);
5352 sprintf(arith_buf
, ARITH_FMT
, res
);
5358 val
= expand_one_var(&to_be_freed
, arg
, &p
);
5359 IF_HUSH_TICK(store_val
:)
5360 if (!(first_ch
& 0x80)) { /* unquoted $VAR */
5361 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val
,
5362 !!(output
->o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
));
5363 if (val
&& val
[0]) {
5364 n
= expand_on_ifs(&ended_in_ifs
, output
, n
, val
);
5367 } else { /* quoted $VAR, val will be appended below */
5368 output
->has_quoted_part
= 1;
5369 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val
,
5370 !!(output
->o_expflags
& EXP_FLAG_ESC_GLOB_CHARS
));
5374 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5376 if (val
&& val
[0]) {
5377 o_addQstr(output
, val
);
5381 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5382 * Do the check to avoid writing to a const string. */
5383 if (*p
!= SPECIAL_VAR_SYMBOL
)
5384 *p
= SPECIAL_VAR_SYMBOL
;
5386 #if ENABLE_HUSH_TICK
5387 o_free(&subst_result
);
5390 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5394 o_addchr(output
, '\0');
5395 n
= o_save_ptr(output
, n
);
5397 debug_print_list("expand_vars_to_list[a]", output
, n
);
5398 /* this part is literal, and it was already pre-quoted
5399 * if needed (much earlier), do not use o_addQstr here! */
5400 o_addstr_with_NUL(output
, arg
);
5401 debug_print_list("expand_vars_to_list[b]", output
, n
);
5402 } else if (output
->length
== o_get_last_ptr(output
, n
) /* expansion is empty */
5403 && !(cant_be_null
& 0x80) /* and all vars were not quoted. */
5406 /* allow to reuse list[n] later without re-growth */
5407 output
->has_empty_slot
= 1;
5409 o_addchr(output
, '\0');
5415 static char **expand_variables(char **argv
, unsigned expflags
)
5419 o_string output
= NULL_O_STRING
;
5421 output
.o_expflags
= expflags
;
5425 n
= expand_vars_to_list(&output
, n
, *argv
);
5428 debug_print_list("expand_variables", &output
, n
);
5430 /* output.data (malloced in one block) gets returned in "list" */
5431 list
= o_finalize_list(&output
, n
);
5432 debug_print_strings("expand_variables[1]", list
);
5436 static char **expand_strvec_to_strvec(char **argv
)
5438 return expand_variables(argv
, EXP_FLAG_GLOB
| EXP_FLAG_ESC_GLOB_CHARS
);
5441 #if ENABLE_HUSH_BASH_COMPAT
5442 static char **expand_strvec_to_strvec_singleword_noglob(char **argv
)
5444 return expand_variables(argv
, EXP_FLAG_SINGLEWORD
);
5448 /* Used for expansion of right hand of assignments,
5449 * $((...)), heredocs, variable espansion parts.
5451 * NB: should NOT do globbing!
5452 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5454 static char *expand_string_to_string(const char *str
, int do_unbackslash
)
5456 #if !ENABLE_HUSH_BASH_COMPAT
5457 const int do_unbackslash
= 1;
5459 char *argv
[2], **list
;
5461 debug_printf_expand("string_to_string<='%s'\n", str
);
5462 /* This is generally an optimization, but it also
5463 * handles "", which otherwise trips over !list[0] check below.
5464 * (is this ever happens that we actually get str="" here?)
5466 if (!strchr(str
, SPECIAL_VAR_SYMBOL
) && !strchr(str
, '\\')) {
5467 //TODO: Can use on strings with \ too, just unbackslash() them?
5468 debug_printf_expand("string_to_string(fast)=>'%s'\n", str
);
5469 return xstrdup(str
);
5472 argv
[0] = (char*)str
;
5474 list
= expand_variables(argv
, do_unbackslash
5475 ? EXP_FLAG_ESC_GLOB_CHARS
| EXP_FLAG_SINGLEWORD
5476 : EXP_FLAG_SINGLEWORD
5479 if (!list
[0] || list
[1])
5480 bb_error_msg_and_die("BUG in varexp2");
5481 /* actually, just move string 2*sizeof(char*) bytes back */
5482 overlapping_strcpy((char*)list
, list
[0]);
5484 unbackslash((char*)list
);
5485 debug_printf_expand("string_to_string=>'%s'\n", (char*)list
);
5489 /* Used for "eval" builtin */
5490 static char* expand_strvec_to_string(char **argv
)
5494 list
= expand_variables(argv
, EXP_FLAG_SINGLEWORD
);
5495 /* Convert all NULs to spaces */
5500 if (list
[n
-1] + strlen(list
[n
-1]) + 1 != list
[n
])
5501 bb_error_msg_and_die("BUG in varexp3");
5502 /* bash uses ' ' regardless of $IFS contents */
5507 overlapping_strcpy((char*)list
, list
[0]);
5508 debug_printf_expand("strvec_to_string='%s'\n", (char*)list
);
5512 static char **expand_assignments(char **argv
, int count
)
5517 G
.expanded_assignments
= p
= NULL
;
5518 /* Expand assignments into one string each */
5519 for (i
= 0; i
< count
; i
++) {
5520 G
.expanded_assignments
= p
= add_string_to_strings(p
, expand_string_to_string(argv
[i
], /*unbackslash:*/ 1));
5522 G
.expanded_assignments
= NULL
;
5527 static void switch_off_special_sigs(unsigned mask
)
5530 while ((mask
>>= 1) != 0) {
5535 if (G
.traps
[sig
] && !G
.traps
[sig
][0])
5536 /* trap is '', has to remain SIG_IGN */
5539 G
.traps
[sig
] = NULL
;
5541 /* We are here only if no trap or trap was not '' */
5542 install_sighandler(sig
, SIG_DFL
);
5548 void re_execute_shell(char ***to_free
, const char *s
,
5549 char *g_argv0
, char **g_argv
,
5550 char **builtin_argv
) NORETURN
;
5552 static void reset_traps_to_defaults(void)
5554 /* This function is always called in a child shell
5555 * after fork (not vfork, NOMMU doesn't use this function).
5560 /* Child shells are not interactive.
5561 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5562 * Testcase: (while :; do :; done) + ^Z should background.
5563 * Same goes for SIGTERM, SIGHUP, SIGINT.
5565 mask
= (G
.special_sig_mask
& SPECIAL_INTERACTIVE_SIGS
) | G_fatal_sig_mask
;
5566 if (!G
.traps
&& !mask
)
5567 return; /* already no traps and no special sigs */
5569 /* Switch off special sigs */
5570 switch_off_special_sigs(mask
);
5572 G_fatal_sig_mask
= 0;
5574 G
.special_sig_mask
&= ~SPECIAL_INTERACTIVE_SIGS
;
5575 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5576 * remain set in G.special_sig_mask */
5581 /* Reset all sigs to default except ones with empty traps */
5582 for (sig
= 0; sig
< NSIG
; sig
++) {
5584 continue; /* no trap: nothing to do */
5585 if (!G
.traps
[sig
][0])
5586 continue; /* empty trap: has to remain SIG_IGN */
5587 /* sig has non-empty trap, reset it: */
5589 G
.traps
[sig
] = NULL
;
5590 /* There is no signal for trap 0 (EXIT) */
5593 install_sighandler(sig
, pick_sighandler(sig
));
5599 static void re_execute_shell(char ***to_free
, const char *s
,
5600 char *g_argv0
, char **g_argv
,
5601 char **builtin_argv
) NORETURN
;
5602 static void re_execute_shell(char ***to_free
, const char *s
,
5603 char *g_argv0
, char **g_argv
,
5604 char **builtin_argv
)
5606 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5607 /* delims + 2 * (number of bytes in printed hex numbers) */
5608 char param_buf
[sizeof(NOMMU_HACK_FMT
) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5609 char *heredoc_argv
[4];
5610 struct variable
*cur
;
5611 # if ENABLE_HUSH_FUNCTIONS
5612 struct function
*funcp
;
5616 unsigned long long empty_trap_mask
;
5618 if (!g_argv0
) { /* heredoc */
5619 argv
= heredoc_argv
;
5620 argv
[0] = (char *) G
.argv0_for_re_execing
;
5621 argv
[1] = (char *) "-<";
5622 argv
[2] = (char *) s
;
5624 pp
= &argv
[3]; /* used as pointer to empty environment */
5630 if (pp
) while (*pp
++)
5633 empty_trap_mask
= 0;
5636 for (sig
= 1; sig
< NSIG
; sig
++) {
5637 if (G
.traps
[sig
] && !G
.traps
[sig
][0])
5638 empty_trap_mask
|= 1LL << sig
;
5642 sprintf(param_buf
, NOMMU_HACK_FMT
5643 , (unsigned) G
.root_pid
5644 , (unsigned) G
.root_ppid
5645 , (unsigned) G
.last_bg_pid
5646 , (unsigned) G
.last_exitcode
5649 IF_HUSH_LOOPS(, G
.depth_of_loop
)
5651 # undef NOMMU_HACK_FMT
5652 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5653 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5656 for (cur
= G
.top_var
; cur
; cur
= cur
->next
) {
5657 if (!cur
->flg_export
|| cur
->flg_read_only
)
5660 # if ENABLE_HUSH_FUNCTIONS
5661 for (funcp
= G
.top_func
; funcp
; funcp
= funcp
->next
)
5667 *to_free
= argv
= pp
= xzalloc(sizeof(argv
[0]) * cnt
);
5668 *pp
++ = (char *) G
.argv0_for_re_execing
;
5670 for (cur
= G
.top_var
; cur
; cur
= cur
->next
) {
5671 if (strcmp(cur
->varstr
, hush_version_str
) == 0)
5673 if (cur
->flg_read_only
) {
5674 *pp
++ = (char *) "-R";
5675 *pp
++ = cur
->varstr
;
5676 } else if (!cur
->flg_export
) {
5677 *pp
++ = (char *) "-V";
5678 *pp
++ = cur
->varstr
;
5681 # if ENABLE_HUSH_FUNCTIONS
5682 for (funcp
= G
.top_func
; funcp
; funcp
= funcp
->next
) {
5683 *pp
++ = (char *) "-F";
5684 *pp
++ = funcp
->name
;
5685 *pp
++ = funcp
->body_as_string
;
5688 /* We can pass activated traps here. Say, -Tnn:trap_string
5690 * However, POSIX says that subshells reset signals with traps
5692 * I tested bash-3.2 and it not only does that with true subshells
5693 * of the form ( list ), but with any forked children shells.
5694 * I set trap "echo W" WINCH; and then tried:
5696 * { echo 1; sleep 20; echo 2; } &
5697 * while true; do echo 1; sleep 20; echo 2; break; done &
5698 * true | { echo 1; sleep 20; echo 2; } | cat
5700 * In all these cases sending SIGWINCH to the child shell
5701 * did not run the trap. If I add trap "echo V" WINCH;
5702 * _inside_ group (just before echo 1), it works.
5704 * I conclude it means we don't need to pass active traps here.
5706 *pp
++ = (char *) "-c";
5709 while (*++builtin_argv
)
5710 *pp
++ = *builtin_argv
;
5711 *pp
++ = (char *) "";
5716 /* *pp = NULL; - is already there */
5720 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s
);
5721 /* Don't propagate SIG_IGN to the child */
5722 if (SPECIAL_JOBSTOP_SIGS
!= 0)
5723 switch_off_special_sigs(G
.special_sig_mask
& SPECIAL_JOBSTOP_SIGS
);
5724 execve(bb_busybox_exec_path
, argv
, pp
);
5725 /* Fallback. Useful for init=/bin/hush usage etc */
5726 if (argv
[0][0] == '/')
5727 execve(argv
[0], argv
, pp
);
5728 xfunc_error_retval
= 127;
5729 bb_error_msg_and_die("can't re-execute the shell");
5731 #endif /* !BB_MMU */
5734 static int run_and_free_list(struct pipe
*pi
);
5736 /* Executing from string: eval, sh -c '...'
5737 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5738 * end_trigger controls how often we stop parsing
5739 * NUL: parse all, execute, return
5740 * ';': parse till ';' or newline, execute, repeat till EOF
5742 static void parse_and_run_stream(struct in_str
*inp
, int end_trigger
)
5744 /* Why we need empty flag?
5745 * An obscure corner case "false; ``; echo $?":
5746 * empty command in `` should still set $? to 0.
5747 * But we can't just set $? to 0 at the start,
5748 * this breaks "false; echo `echo $?`" case.
5752 struct pipe
*pipe_list
;
5754 #if ENABLE_HUSH_INTERACTIVE
5755 if (end_trigger
== ';')
5756 inp
->promptmode
= 0; /* PS1 */
5758 pipe_list
= parse_stream(NULL
, inp
, end_trigger
);
5759 if (!pipe_list
|| pipe_list
== ERR_PTR
) { /* EOF/error */
5760 /* If we are in "big" script
5761 * (not in `cmd` or something similar)...
5763 if (pipe_list
== ERR_PTR
&& end_trigger
== ';') {
5764 /* Discard cached input (rest of line) */
5765 int ch
= inp
->last_char
;
5766 while (ch
!= EOF
&& ch
!= '\n') {
5767 //bb_error_msg("Discarded:'%c'", ch);
5772 /* This stream isn't empty */
5776 if (!pipe_list
&& empty
)
5777 G
.last_exitcode
= 0;
5780 debug_print_tree(pipe_list
, 0);
5781 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5782 run_and_free_list(pipe_list
);
5784 #if ENABLE_HUSH_FUNCTIONS
5785 if (G
.flag_return_in_progress
== 1)
5791 static void parse_and_run_string(const char *s
)
5793 struct in_str input
;
5794 setup_string_in_str(&input
, s
);
5795 parse_and_run_stream(&input
, '\0');
5798 static void parse_and_run_file(FILE *f
)
5800 struct in_str input
;
5801 setup_file_in_str(&input
, f
);
5802 parse_and_run_stream(&input
, ';');
5805 #if ENABLE_HUSH_TICK
5806 static FILE *generate_stream_from_string(const char *s
, pid_t
*pid_p
)
5811 char **to_free
= NULL
;
5815 pid
= BB_MMU
? xfork() : xvfork();
5816 if (pid
== 0) { /* child */
5817 disable_restore_tty_pgrp_on_exit();
5818 /* Process substitution is not considered to be usual
5819 * 'command execution'.
5820 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5827 CLEAR_RANDOM_T(&G
.random_gen
); /* or else $RANDOM repeats in child */
5828 close(channel
[0]); /* NB: close _first_, then move fd! */
5829 xmove_fd(channel
[1], 1);
5830 /* Prevent it from trying to handle ctrl-z etc */
5831 IF_HUSH_JOB(G
.run_list_level
= 1;)
5832 /* Awful hack for `trap` or $(trap).
5834 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5835 * contains an example where "trap" is executed in a subshell:
5837 * save_traps=$(trap)
5839 * eval "$save_traps"
5841 * Standard does not say that "trap" in subshell shall print
5842 * parent shell's traps. It only says that its output
5843 * must have suitable form, but then, in the above example
5844 * (which is not supposed to be normative), it implies that.
5846 * bash (and probably other shell) does implement it
5847 * (traps are reset to defaults, but "trap" still shows them),
5848 * but as a result, "trap" logic is hopelessly messed up:
5851 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5852 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5853 * # true | trap <--- trap is in subshell - no output (ditto)
5854 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5855 * trap -- 'echo Ho' SIGWINCH
5856 * # echo `(trap)` <--- in subshell in subshell - output
5857 * trap -- 'echo Ho' SIGWINCH
5858 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5859 * trap -- 'echo Ho' SIGWINCH
5861 * The rules when to forget and when to not forget traps
5862 * get really complex and nonsensical.
5864 * Our solution: ONLY bare $(trap) or `trap` is special.
5866 s
= skip_whitespace(s
);
5867 if (strncmp(s
, "trap", 4) == 0
5868 && skip_whitespace(s
+ 4)[0] == '\0'
5870 static const char *const argv
[] = { NULL
, NULL
};
5871 builtin_trap((char**)argv
);
5872 exit(0); /* not _exit() - we need to fflush */
5875 reset_traps_to_defaults();
5876 parse_and_run_string(s
);
5877 _exit(G
.last_exitcode
);
5879 /* We re-execute after vfork on NOMMU. This makes this script safe:
5880 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5881 * huge=`cat BIG` # was blocking here forever
5884 re_execute_shell(&to_free
,
5894 # if ENABLE_HUSH_FAST
5896 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5897 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5898 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5900 enable_restore_tty_pgrp_on_exit();
5905 close_on_exec_on(channel
[0]);
5906 return xfdopen_for_read(channel
[0]);
5909 /* Return code is exit status of the process that is run. */
5910 static int process_command_subs(o_string
*dest
, const char *s
)
5913 struct in_str pipe_str
;
5915 int status
, ch
, eol_cnt
;
5917 fp
= generate_stream_from_string(s
, &pid
);
5919 /* Now send results of command back into original context */
5920 setup_file_in_str(&pipe_str
, fp
);
5922 while ((ch
= i_getch(&pipe_str
)) != EOF
) {
5928 o_addchr(dest
, '\n');
5931 o_addQchr(dest
, ch
);
5934 debug_printf("done reading from `cmd` pipe, closing it\n");
5936 /* We need to extract exitcode. Test case
5937 * "true; echo `sleep 1; false` $?"
5939 safe_waitpid(pid
, &status
, 0);
5940 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status
));
5941 return WEXITSTATUS(status
);
5943 #endif /* ENABLE_HUSH_TICK */
5946 static void setup_heredoc(struct redir_struct
*redir
)
5948 struct fd_pair pair
;
5951 /* the _body_ of heredoc (misleading field name) */
5952 const char *heredoc
= redir
->rd_filename
;
5959 if (!(redir
->rd_dup
& HEREDOC_QUOTED
)) {
5960 expanded
= encode_then_expand_string(heredoc
, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5964 len
= strlen(heredoc
);
5966 close(redir
->rd_fd
); /* often saves dup2+close in xmove_fd */
5968 xmove_fd(pair
.rd
, redir
->rd_fd
);
5970 /* Try writing without forking. Newer kernels have
5971 * dynamically growing pipes. Must use non-blocking write! */
5974 written
= write(pair
.wr
, heredoc
, len
);
5985 ndelay_off(pair
.wr
);
5987 /* Okay, pipe buffer was not big enough */
5988 /* Note: we must not create a stray child (bastard? :)
5989 * for the unsuspecting parent process. Child creates a grandchild
5990 * and exits before parent execs the process which consumes heredoc
5991 * (that exec happens after we return from this function) */
5998 disable_restore_tty_pgrp_on_exit();
5999 pid
= BB_MMU
? xfork() : xvfork();
6003 close(redir
->rd_fd
); /* read side of the pipe */
6005 full_write(pair
.wr
, heredoc
, len
); /* may loop or block */
6008 /* Delegate blocking writes to another process */
6009 xmove_fd(pair
.wr
, STDOUT_FILENO
);
6010 re_execute_shell(&to_free
, heredoc
, NULL
, NULL
, NULL
);
6014 #if ENABLE_HUSH_FAST
6016 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6018 enable_restore_tty_pgrp_on_exit();
6024 wait(NULL
); /* wait till child has died */
6027 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6028 * and stderr if they are redirected. */
6029 static int setup_redirects(struct command
*prog
, int squirrel
[])
6032 struct redir_struct
*redir
;
6034 for (redir
= prog
->redirects
; redir
; redir
= redir
->next
) {
6035 if (redir
->rd_type
== REDIRECT_HEREDOC2
) {
6036 /* rd_fd<<HERE case */
6037 if (squirrel
&& redir
->rd_fd
< 3
6038 && squirrel
[redir
->rd_fd
] < 0
6040 squirrel
[redir
->rd_fd
] = dup(redir
->rd_fd
);
6042 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6044 debug_printf_parse("set heredoc '%s'\n",
6045 redir
->rd_filename
);
6046 setup_heredoc(redir
);
6050 if (redir
->rd_dup
== REDIRFD_TO_FILE
) {
6051 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6053 if (redir
->rd_filename
== NULL
) {
6054 /* Something went wrong in the parse.
6055 * Pretend it didn't happen */
6056 bb_error_msg("bug in redirect parse");
6059 mode
= redir_table
[redir
->rd_type
].mode
;
6060 p
= expand_string_to_string(redir
->rd_filename
, /*unbackslash:*/ 1);
6061 openfd
= open_or_warn(p
, mode
);
6064 /* this could get lost if stderr has been redirected, but
6065 * bash and ash both lose it as well (though zsh doesn't!) */
6066 //what the above comment tries to say?
6070 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6071 openfd
= redir
->rd_dup
;
6074 if (openfd
!= redir
->rd_fd
) {
6075 if (squirrel
&& redir
->rd_fd
< 3
6076 && squirrel
[redir
->rd_fd
] < 0
6078 squirrel
[redir
->rd_fd
] = dup(redir
->rd_fd
);
6080 if (openfd
== REDIRFD_CLOSE
) {
6081 /* "n>-" means "close me" */
6082 close(redir
->rd_fd
);
6084 xdup2(openfd
, redir
->rd_fd
);
6085 if (redir
->rd_dup
== REDIRFD_TO_FILE
)
6093 static void restore_redirects(int squirrel
[])
6096 for (i
= 0; i
< 3; i
++) {
6099 /* We simply die on error */
6105 static char *find_in_path(const char *arg
)
6108 const char *PATH
= get_local_var_value("PATH");
6114 const char *end
= strchrnul(PATH
, ':');
6115 int sz
= end
- PATH
; /* must be int! */
6119 ret
= xasprintf("%.*s/%s", sz
, PATH
, arg
);
6121 /* We have xxx::yyyy in $PATH,
6122 * it means "use current dir" */
6125 if (access(ret
, F_OK
) == 0)
6138 static const struct built_in_command
*find_builtin_helper(const char *name
,
6139 const struct built_in_command
*x
,
6140 const struct built_in_command
*end
)
6143 if (strcmp(name
, x
->b_cmd
) != 0) {
6147 debug_printf_exec("found builtin '%s'\n", name
);
6152 static const struct built_in_command
*find_builtin1(const char *name
)
6154 return find_builtin_helper(name
, bltins1
, &bltins1
[ARRAY_SIZE(bltins1
)]);
6156 static const struct built_in_command
*find_builtin(const char *name
)
6158 const struct built_in_command
*x
= find_builtin1(name
);
6161 return find_builtin_helper(name
, bltins2
, &bltins2
[ARRAY_SIZE(bltins2
)]);
6164 #if ENABLE_HUSH_FUNCTIONS
6165 static struct function
**find_function_slot(const char *name
)
6167 struct function
**funcpp
= &G
.top_func
;
6169 if (strcmp(name
, (*funcpp
)->name
) == 0) {
6172 funcpp
= &(*funcpp
)->next
;
6177 static const struct function
*find_function(const char *name
)
6179 const struct function
*funcp
= *find_function_slot(name
);
6181 debug_printf_exec("found function '%s'\n", name
);
6185 /* Note: takes ownership on name ptr */
6186 static struct function
*new_function(char *name
)
6188 struct function
**funcpp
= find_function_slot(name
);
6189 struct function
*funcp
= *funcpp
;
6191 if (funcp
!= NULL
) {
6192 struct command
*cmd
= funcp
->parent_cmd
;
6193 debug_printf_exec("func %p parent_cmd %p\n", funcp
, cmd
);
6195 debug_printf_exec("freeing & replacing function '%s'\n", funcp
->name
);
6197 /* Note: if !funcp->body, do not free body_as_string!
6198 * This is a special case of "-F name body" function:
6199 * body_as_string was not malloced! */
6201 free_pipe_list(funcp
->body
);
6203 free(funcp
->body_as_string
);
6207 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp
->name
);
6208 cmd
->argv
[0] = funcp
->name
;
6209 cmd
->group
= funcp
->body
;
6211 cmd
->group_as_string
= funcp
->body_as_string
;
6215 debug_printf_exec("remembering new function '%s'\n", name
);
6216 funcp
= *funcpp
= xzalloc(sizeof(*funcp
));
6217 /*funcp->next = NULL;*/
6224 static void unset_func(const char *name
)
6226 struct function
**funcpp
= find_function_slot(name
);
6227 struct function
*funcp
= *funcpp
;
6229 if (funcp
!= NULL
) {
6230 debug_printf_exec("freeing function '%s'\n", funcp
->name
);
6231 *funcpp
= funcp
->next
;
6232 /* funcp is unlinked now, deleting it.
6233 * Note: if !funcp->body, the function was created by
6234 * "-F name body", do not free ->body_as_string
6235 * and ->name as they were not malloced. */
6237 free_pipe_list(funcp
->body
);
6240 free(funcp
->body_as_string
);
6248 #define exec_function(to_free, funcp, argv) \
6249 exec_function(funcp, argv)
6251 static void exec_function(char ***to_free
,
6252 const struct function
*funcp
,
6253 char **argv
) NORETURN
;
6254 static void exec_function(char ***to_free
,
6255 const struct function
*funcp
,
6261 argv
[0] = G
.global_argv
[0];
6262 G
.global_argv
= argv
;
6266 /* On MMU, funcp->body is always non-NULL */
6267 n
= run_list(funcp
->body
);
6271 re_execute_shell(to_free
,
6272 funcp
->body_as_string
,
6279 static int run_function(const struct function
*funcp
, char **argv
)
6285 save_and_replace_G_args(&sv
, argv
);
6287 /* "we are in function, ok to use return" */
6288 sv_flg
= G
.flag_return_in_progress
;
6289 G
.flag_return_in_progress
= -1;
6290 # if ENABLE_HUSH_LOCAL
6291 G
.func_nest_level
++;
6294 /* On MMU, funcp->body is always non-NULL */
6297 /* Function defined by -F */
6298 parse_and_run_string(funcp
->body_as_string
);
6299 rc
= G
.last_exitcode
;
6303 rc
= run_list(funcp
->body
);
6306 # if ENABLE_HUSH_LOCAL
6308 struct variable
*var
;
6309 struct variable
**var_pp
;
6311 var_pp
= &G
.top_var
;
6312 while ((var
= *var_pp
) != NULL
) {
6313 if (var
->func_nest_level
< G
.func_nest_level
) {
6314 var_pp
= &var
->next
;
6318 if (var
->flg_export
)
6319 bb_unsetenv(var
->varstr
);
6320 /* Remove from global list */
6321 *var_pp
= var
->next
;
6327 G
.func_nest_level
--;
6330 G
.flag_return_in_progress
= sv_flg
;
6332 restore_G_args(&sv
, argv
);
6336 #endif /* ENABLE_HUSH_FUNCTIONS */
6340 #define exec_builtin(to_free, x, argv) \
6341 exec_builtin(x, argv)
6343 #define exec_builtin(to_free, x, argv) \
6344 exec_builtin(to_free, argv)
6346 static void exec_builtin(char ***to_free
,
6347 const struct built_in_command
*x
,
6348 char **argv
) NORETURN
;
6349 static void exec_builtin(char ***to_free
,
6350 const struct built_in_command
*x
,
6356 rcode
= x
->b_function(argv
);
6361 /* On NOMMU, we must never block!
6362 * Example: { sleep 99 | read line; } & echo Ok
6364 re_execute_shell(to_free
,
6373 static void execvp_or_die(char **argv
) NORETURN
;
6374 static void execvp_or_die(char **argv
)
6376 debug_printf_exec("execing '%s'\n", argv
[0]);
6377 /* Don't propagate SIG_IGN to the child */
6378 if (SPECIAL_JOBSTOP_SIGS
!= 0)
6379 switch_off_special_sigs(G
.special_sig_mask
& SPECIAL_JOBSTOP_SIGS
);
6380 execvp(argv
[0], argv
);
6381 bb_perror_msg("can't execute '%s'", argv
[0]);
6382 _exit(127); /* bash compat */
6385 #if ENABLE_HUSH_MODE_X
6386 static void dump_cmd_in_x_mode(char **argv
)
6388 if (G_x_mode
&& argv
) {
6389 /* We want to output the line in one write op */
6397 len
+= strlen(argv
[n
++]) + 1;
6403 p
+= sprintf(p
, " %s", argv
[n
++]);
6411 # define dump_cmd_in_x_mode(argv) ((void)0)
6415 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6416 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6417 #define pseudo_exec(nommu_save, command, argv_expanded) \
6418 pseudo_exec(command, argv_expanded)
6421 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6423 * Don't exit() here. If you don't exec, use _exit instead.
6424 * The at_exit handlers apparently confuse the calling process,
6425 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6426 static void pseudo_exec_argv(nommu_save_t
*nommu_save
,
6427 char **argv
, int assignment_cnt
,
6428 char **argv_expanded
) NORETURN
;
6429 static NOINLINE
void pseudo_exec_argv(nommu_save_t
*nommu_save
,
6430 char **argv
, int assignment_cnt
,
6431 char **argv_expanded
)
6435 new_env
= expand_assignments(argv
, assignment_cnt
);
6436 dump_cmd_in_x_mode(new_env
);
6438 if (!argv
[assignment_cnt
]) {
6439 /* Case when we are here: ... | var=val | ...
6440 * (note that we do not exit early, i.e., do not optimize out
6441 * expand_assignments(): think about ... | var=`sleep 1` | ...
6443 free_strings(new_env
);
6444 _exit(EXIT_SUCCESS
);
6448 set_vars_and_save_old(new_env
);
6449 free(new_env
); /* optional */
6450 /* we can also destroy set_vars_and_save_old's return value,
6453 nommu_save
->new_env
= new_env
;
6454 nommu_save
->old_vars
= set_vars_and_save_old(new_env
);
6457 if (argv_expanded
) {
6458 argv
= argv_expanded
;
6460 argv
= expand_strvec_to_strvec(argv
+ assignment_cnt
);
6462 nommu_save
->argv
= argv
;
6465 dump_cmd_in_x_mode(argv
);
6467 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6468 if (strchr(argv
[0], '/') != NULL
)
6472 /* Check if the command matches any of the builtins.
6473 * Depending on context, this might be redundant. But it's
6474 * easier to waste a few CPU cycles than it is to figure out
6475 * if this is one of those cases.
6478 /* On NOMMU, it is more expensive to re-execute shell
6479 * just in order to run echo or test builtin.
6480 * It's better to skip it here and run corresponding
6481 * non-builtin later. */
6482 const struct built_in_command
*x
;
6483 x
= BB_MMU
? find_builtin(argv
[0]) : find_builtin1(argv
[0]);
6485 exec_builtin(&nommu_save
->argv_from_re_execing
, x
, argv
);
6488 #if ENABLE_HUSH_FUNCTIONS
6489 /* Check if the command matches any functions */
6491 const struct function
*funcp
= find_function(argv
[0]);
6493 exec_function(&nommu_save
->argv_from_re_execing
, funcp
, argv
);
6498 #if ENABLE_FEATURE_SH_STANDALONE
6499 /* Check if the command matches any busybox applets */
6501 int a
= find_applet_by_name(argv
[0]);
6503 # if BB_MMU /* see above why on NOMMU it is not allowed */
6504 if (APPLET_IS_NOEXEC(a
)) {
6505 debug_printf_exec("running applet '%s'\n", argv
[0]);
6506 run_applet_no_and_exit(a
, argv
);
6509 /* Re-exec ourselves */
6510 debug_printf_exec("re-execing applet '%s'\n", argv
[0]);
6511 /* Don't propagate SIG_IGN to the child */
6512 if (SPECIAL_JOBSTOP_SIGS
!= 0)
6513 switch_off_special_sigs(G
.special_sig_mask
& SPECIAL_JOBSTOP_SIGS
);
6514 execv(bb_busybox_exec_path
, argv
);
6515 /* If they called chroot or otherwise made the binary no longer
6516 * executable, fall through */
6521 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6524 execvp_or_die(argv
);
6527 /* Called after [v]fork() in run_pipe
6529 static void pseudo_exec(nommu_save_t
*nommu_save
,
6530 struct command
*command
,
6531 char **argv_expanded
) NORETURN
;
6532 static void pseudo_exec(nommu_save_t
*nommu_save
,
6533 struct command
*command
,
6534 char **argv_expanded
)
6536 if (command
->argv
) {
6537 pseudo_exec_argv(nommu_save
, command
->argv
,
6538 command
->assignment_cnt
, argv_expanded
);
6541 if (command
->group
) {
6542 /* Cases when we are here:
6545 * ... | ( list ) | ...
6546 * ... | { list } | ...
6550 debug_printf_exec("pseudo_exec: run_list\n");
6551 reset_traps_to_defaults();
6552 rcode
= run_list(command
->group
);
6553 /* OK to leak memory by not calling free_pipe_list,
6554 * since this process is about to exit */
6557 re_execute_shell(&nommu_save
->argv_from_re_execing
,
6558 command
->group_as_string
,
6565 /* Case when we are here: ... | >file */
6566 debug_printf_exec("pseudo_exec'ed null command\n");
6567 _exit(EXIT_SUCCESS
);
6571 static const char *get_cmdtext(struct pipe
*pi
)
6577 /* This is subtle. ->cmdtext is created only on first backgrounding.
6578 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6579 * On subsequent bg argv is trashed, but we won't use it */
6582 argv
= pi
->cmds
[0].argv
;
6583 if (!argv
|| !argv
[0]) {
6584 pi
->cmdtext
= xzalloc(1);
6590 len
+= strlen(*argv
) + 1;
6594 argv
= pi
->cmds
[0].argv
;
6596 len
= strlen(*argv
);
6597 memcpy(p
, *argv
, len
);
6605 static void insert_bg_job(struct pipe
*pi
)
6607 struct pipe
*job
, **jobp
;
6610 /* Linear search for the ID of the job to use */
6612 for (job
= G
.job_list
; job
; job
= job
->next
)
6613 if (job
->jobid
>= pi
->jobid
)
6614 pi
->jobid
= job
->jobid
+ 1;
6616 /* Add job to the list of running jobs */
6618 while ((job
= *jobp
) != NULL
)
6620 job
= *jobp
= xmalloc(sizeof(*job
));
6622 *job
= *pi
; /* physical copy */
6624 job
->cmds
= xzalloc(sizeof(pi
->cmds
[0]) * pi
->num_cmds
);
6625 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6626 for (i
= 0; i
< pi
->num_cmds
; i
++) {
6627 job
->cmds
[i
].pid
= pi
->cmds
[i
].pid
;
6628 /* all other fields are not used and stay zero */
6630 job
->cmdtext
= xstrdup(get_cmdtext(pi
));
6632 if (G_interactive_fd
)
6633 printf("[%d] %d %s\n", job
->jobid
, job
->cmds
[0].pid
, job
->cmdtext
);
6634 G
.last_jobid
= job
->jobid
;
6637 static void remove_bg_job(struct pipe
*pi
)
6639 struct pipe
*prev_pipe
;
6641 if (pi
== G
.job_list
) {
6642 G
.job_list
= pi
->next
;
6644 prev_pipe
= G
.job_list
;
6645 while (prev_pipe
->next
!= pi
)
6646 prev_pipe
= prev_pipe
->next
;
6647 prev_pipe
->next
= pi
->next
;
6650 G
.last_jobid
= G
.job_list
->jobid
;
6655 /* Remove a backgrounded job */
6656 static void delete_finished_bg_job(struct pipe
*pi
)
6663 /* Check to see if any processes have exited -- if they
6664 * have, figure out why and see if a job has completed */
6665 static int checkjobs(struct pipe
*fg_pipe
)
6675 debug_printf_jobs("checkjobs %p\n", fg_pipe
);
6677 attributes
= WUNTRACED
;
6678 if (fg_pipe
== NULL
)
6679 attributes
|= WNOHANG
;
6682 #if ENABLE_HUSH_FAST
6683 if (G
.handled_SIGCHLD
== G
.count_SIGCHLD
) {
6684 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6685 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6686 /* There was neither fork nor SIGCHLD since last waitpid */
6687 /* Avoid doing waitpid syscall if possible */
6688 if (!G
.we_have_children
) {
6692 if (fg_pipe
== NULL
) { /* is WNOHANG set? */
6693 /* We have children, but they did not exit
6694 * or stop yet (we saw no SIGCHLD) */
6697 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6701 /* Do we do this right?
6702 * bash-3.00# sleep 20 | false
6704 * [3]+ Stopped sleep 20 | false
6705 * bash-3.00# echo $?
6706 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6707 * [hush 1.14.0: yes we do it right]
6714 #if ENABLE_HUSH_FAST
6715 i
= G
.count_SIGCHLD
;
6717 childpid
= waitpid(-1, &status
, attributes
);
6718 if (childpid
<= 0) {
6719 if (childpid
&& errno
!= ECHILD
)
6720 bb_perror_msg("waitpid");
6721 #if ENABLE_HUSH_FAST
6722 else { /* Until next SIGCHLD, waitpid's are useless */
6723 G
.we_have_children
= (childpid
== 0);
6724 G
.handled_SIGCHLD
= i
;
6725 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6730 dead
= WIFEXITED(status
) || WIFSIGNALED(status
);
6733 if (WIFSTOPPED(status
))
6734 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6735 childpid
, WSTOPSIG(status
), WEXITSTATUS(status
));
6736 if (WIFSIGNALED(status
))
6737 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6738 childpid
, WTERMSIG(status
), WEXITSTATUS(status
));
6739 if (WIFEXITED(status
))
6740 debug_printf_jobs("pid %d exited, exitcode %d\n",
6741 childpid
, WEXITSTATUS(status
));
6743 /* Were we asked to wait for fg pipe? */
6745 i
= fg_pipe
->num_cmds
;
6747 debug_printf_jobs("check pid %d\n", fg_pipe
->cmds
[i
].pid
);
6748 if (fg_pipe
->cmds
[i
].pid
!= childpid
)
6752 fg_pipe
->cmds
[i
].pid
= 0;
6753 fg_pipe
->alive_cmds
--;
6754 ex
= WEXITSTATUS(status
);
6755 /* bash prints killer signal's name for *last*
6756 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6757 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6759 if (WIFSIGNALED(status
)) {
6760 int sig
= WTERMSIG(status
);
6761 if (i
== fg_pipe
->num_cmds
-1)
6762 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6763 printf("%s\n", sig
== SIGINT
|| sig
== SIGPIPE
? "" : get_signame(sig
));
6764 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6765 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6766 * Maybe we need to use sig | 128? */
6769 fg_pipe
->cmds
[i
].cmd_exitcode
= ex
;
6771 fg_pipe
->stopped_cmds
++;
6773 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6774 fg_pipe
->alive_cmds
, fg_pipe
->stopped_cmds
);
6775 if (fg_pipe
->alive_cmds
== fg_pipe
->stopped_cmds
) {
6776 /* All processes in fg pipe have exited or stopped */
6777 i
= fg_pipe
->num_cmds
;
6779 rcode
= fg_pipe
->cmds
[i
].cmd_exitcode
;
6780 /* usually last process gives overall exitstatus,
6781 * but with "set -o pipefail", last *failed* process does */
6782 if (G
.o_opt
[OPT_O_PIPEFAIL
] == 0 || rcode
!= 0)
6785 IF_HAS_KEYWORDS(if (fg_pipe
->pi_inverted
) rcode
= !rcode
;)
6786 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6787 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6788 * and "killall -STOP cat" */
6789 if (G_interactive_fd
) {
6791 if (fg_pipe
->alive_cmds
!= 0)
6792 insert_bg_job(fg_pipe
);
6796 if (fg_pipe
->alive_cmds
== 0)
6799 /* There are still running processes in the fg pipe */
6800 goto wait_more
; /* do waitpid again */
6802 /* it wasnt fg_pipe, look for process in bg pipes */
6806 /* We asked to wait for bg or orphaned children */
6807 /* No need to remember exitcode in this case */
6808 for (pi
= G
.job_list
; pi
; pi
= pi
->next
) {
6809 for (i
= 0; i
< pi
->num_cmds
; i
++) {
6810 if (pi
->cmds
[i
].pid
== childpid
)
6811 goto found_pi_and_prognum
;
6814 /* Happens when shell is used as init process (init=/bin/sh) */
6815 debug_printf("checkjobs: pid %d was not in our list!\n", childpid
);
6816 continue; /* do waitpid again */
6818 found_pi_and_prognum
:
6821 pi
->cmds
[i
].pid
= 0;
6823 if (!pi
->alive_cmds
) {
6824 if (G_interactive_fd
)
6825 printf(JOB_STATUS_FORMAT
, pi
->jobid
,
6826 "Done", pi
->cmdtext
);
6827 delete_finished_bg_job(pi
);
6834 } /* while (waitpid succeeds)... */
6840 static int checkjobs_and_fg_shell(struct pipe
*fg_pipe
)
6843 int rcode
= checkjobs(fg_pipe
);
6844 if (G_saved_tty_pgrp
) {
6845 /* Job finished, move the shell to the foreground */
6846 p
= getpgrp(); /* our process group id */
6847 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p
);
6848 tcsetpgrp(G_interactive_fd
, p
);
6854 /* Start all the jobs, but don't wait for anything to finish.
6857 * Return code is normally -1, when the caller has to wait for children
6858 * to finish to determine the exit status of the pipe. If the pipe
6859 * is a simple builtin command, however, the action is done by the
6860 * time run_pipe returns, and the exit code is provided as the
6863 * Returns -1 only if started some children. IOW: we have to
6864 * mask out retvals of builtins etc with 0xff!
6866 * The only case when we do not need to [v]fork is when the pipe
6867 * is single, non-backgrounded, non-subshell command. Examples:
6868 * cmd ; ... { list } ; ...
6869 * cmd && ... { list } && ...
6870 * cmd || ... { list } || ...
6871 * If it is, then we can run cmd as a builtin, NOFORK,
6872 * or (if SH_STANDALONE) an applet, and we can run the { list }
6873 * with run_list. If it isn't one of these, we fork and exec cmd.
6875 * Cases when we must fork:
6876 * non-single: cmd | cmd
6877 * backgrounded: cmd & { list } &
6878 * subshell: ( list ) [&]
6880 #if !ENABLE_HUSH_MODE_X
6881 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6882 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6884 static int redirect_and_varexp_helper(char ***new_env_p
,
6885 struct variable
**old_vars_p
,
6886 struct command
*command
,
6888 char **argv_expanded
)
6890 /* setup_redirects acts on file descriptors, not FILEs.
6891 * This is perfect for work that comes after exec().
6892 * Is it really safe for inline use? Experimentally,
6893 * things seem to work. */
6894 int rcode
= setup_redirects(command
, squirrel
);
6896 char **new_env
= expand_assignments(command
->argv
, command
->assignment_cnt
);
6897 *new_env_p
= new_env
;
6898 dump_cmd_in_x_mode(new_env
);
6899 dump_cmd_in_x_mode(argv_expanded
);
6901 *old_vars_p
= set_vars_and_save_old(new_env
);
6905 static NOINLINE
int run_pipe(struct pipe
*pi
)
6907 static const char *const null_ptr
= NULL
;
6911 struct command
*command
;
6912 char **argv_expanded
;
6914 /* it is not always needed, but we aim to smaller code */
6915 int squirrel
[] = { -1, -1, -1 };
6918 debug_printf_exec("run_pipe start: members:%d\n", pi
->num_cmds
);
6921 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6922 * Result should be 3 lines: q w e, qwe, q w e
6924 G
.ifs
= get_local_var_value("IFS");
6928 IF_HUSH_JOB(pi
->pgrp
= -1;)
6929 pi
->stopped_cmds
= 0;
6930 command
= &pi
->cmds
[0];
6931 argv_expanded
= NULL
;
6933 if (pi
->num_cmds
!= 1
6934 || pi
->followup
== PIPE_BG
6935 || command
->cmd_type
== CMD_SUBSHELL
6942 debug_printf_exec(": group:%p argv:'%s'\n",
6943 command
->group
, command
->argv
? command
->argv
[0] : "NONE");
6945 if (command
->group
) {
6946 #if ENABLE_HUSH_FUNCTIONS
6947 if (command
->cmd_type
== CMD_FUNCDEF
) {
6948 /* "executing" func () { list } */
6949 struct function
*funcp
;
6951 funcp
= new_function(command
->argv
[0]);
6952 /* funcp->name is already set to argv[0] */
6953 funcp
->body
= command
->group
;
6955 funcp
->body_as_string
= command
->group_as_string
;
6956 command
->group_as_string
= NULL
;
6958 command
->group
= NULL
;
6959 command
->argv
[0] = NULL
;
6960 debug_printf_exec("cmd %p has child func at %p\n", command
, funcp
);
6961 funcp
->parent_cmd
= command
;
6962 command
->child_func
= funcp
;
6964 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6966 return EXIT_SUCCESS
;
6970 debug_printf("non-subshell group\n");
6971 rcode
= 1; /* exitcode if redir failed */
6972 if (setup_redirects(command
, squirrel
) == 0) {
6973 debug_printf_exec(": run_list\n");
6974 rcode
= run_list(command
->group
) & 0xff;
6976 restore_redirects(squirrel
);
6977 IF_HAS_KEYWORDS(if (pi
->pi_inverted
) rcode
= !rcode
;)
6979 debug_printf_exec("run_pipe: return %d\n", rcode
);
6983 argv
= command
->argv
? command
->argv
: (char **) &null_ptr
;
6985 const struct built_in_command
*x
;
6986 #if ENABLE_HUSH_FUNCTIONS
6987 const struct function
*funcp
;
6991 char **new_env
= NULL
;
6992 struct variable
*old_vars
= NULL
;
6994 if (argv
[command
->assignment_cnt
] == NULL
) {
6995 /* Assignments, but no command */
6996 /* Ensure redirects take effect (that is, create files).
6997 * Try "a=t >file" */
6998 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6999 rcode
= redirect_and_varexp_helper(&new_env
, /*old_vars:*/ NULL
, command
, squirrel
, /*argv_expanded:*/ NULL
);
7000 /* Set shell variables */
7004 set_local_var(*argv
, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7005 /* Do we need to flag set_local_var() errors?
7006 * "assignment to readonly var" and "putenv error"
7011 /* Redirect error sets $? to 1. Otherwise,
7012 * if evaluating assignment value set $?, retain it.
7013 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7015 rcode
= G
.last_exitcode
;
7016 /* Exit, _skipping_ variable restoring code: */
7017 goto clean_up_and_ret0
;
7019 #else /* Older, bigger, but more correct code */
7021 rcode
= setup_redirects(command
, squirrel
);
7022 restore_redirects(squirrel
);
7023 /* Set shell variables */
7025 bb_putchar_stderr('+');
7027 char *p
= expand_string_to_string(*argv
, /*unbackslash:*/ 1);
7029 fprintf(stderr
, " %s", p
);
7030 debug_printf_exec("set shell var:'%s'->'%s'\n",
7032 set_local_var(p
, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7033 /* Do we need to flag set_local_var() errors?
7034 * "assignment to readonly var" and "putenv error"
7039 bb_putchar_stderr('\n');
7040 /* Redirect error sets $? to 1. Otherwise,
7041 * if evaluating assignment value set $?, retain it.
7042 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7044 rcode
= G
.last_exitcode
;
7045 IF_HAS_KEYWORDS(if (pi
->pi_inverted
) rcode
= !rcode
;)
7047 debug_printf_exec("run_pipe: return %d\n", rcode
);
7052 /* Expand the rest into (possibly) many strings each */
7053 #if ENABLE_HUSH_BASH_COMPAT
7054 if (command
->cmd_type
== CMD_SINGLEWORD_NOGLOB
) {
7055 argv_expanded
= expand_strvec_to_strvec_singleword_noglob(argv
+ command
->assignment_cnt
);
7059 argv_expanded
= expand_strvec_to_strvec(argv
+ command
->assignment_cnt
);
7062 /* if someone gives us an empty string: `cmd with empty output` */
7063 if (!argv_expanded
[0]) {
7064 free(argv_expanded
);
7066 return G
.last_exitcode
;
7069 x
= find_builtin(argv_expanded
[0]);
7070 #if ENABLE_HUSH_FUNCTIONS
7073 funcp
= find_function(argv_expanded
[0]);
7077 if (x
->b_function
== builtin_exec
&& argv_expanded
[1] == NULL
) {
7078 debug_printf("exec with redirects only\n");
7079 rcode
= setup_redirects(command
, NULL
);
7080 goto clean_up_and_ret1
;
7083 rcode
= redirect_and_varexp_helper(&new_env
, &old_vars
, command
, squirrel
, argv_expanded
);
7086 debug_printf_exec(": builtin '%s' '%s'...\n",
7087 x
->b_cmd
, argv_expanded
[1]);
7089 rcode
= x
->b_function(argv_expanded
) & 0xff;
7092 #if ENABLE_HUSH_FUNCTIONS
7094 # if ENABLE_HUSH_LOCAL
7095 struct variable
**sv
;
7096 sv
= G
.shadowed_vars_pp
;
7097 G
.shadowed_vars_pp
= &old_vars
;
7099 debug_printf_exec(": function '%s' '%s'...\n",
7100 funcp
->name
, argv_expanded
[1]);
7101 rcode
= run_function(funcp
, argv_expanded
) & 0xff;
7102 # if ENABLE_HUSH_LOCAL
7103 G
.shadowed_vars_pp
= sv
;
7109 unset_vars(new_env
);
7111 /* clean_up_and_ret0: */
7112 restore_redirects(squirrel
);
7114 free(argv_expanded
);
7115 IF_HAS_KEYWORDS(if (pi
->pi_inverted
) rcode
= !rcode
;)
7117 debug_printf_exec("run_pipe return %d\n", rcode
);
7121 if (ENABLE_FEATURE_SH_NOFORK
) {
7122 int n
= find_applet_by_name(argv_expanded
[0]);
7123 if (n
>= 0 && APPLET_IS_NOFORK(n
)) {
7124 rcode
= redirect_and_varexp_helper(&new_env
, &old_vars
, command
, squirrel
, argv_expanded
);
7126 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7127 argv_expanded
[0], argv_expanded
[1]);
7128 rcode
= run_nofork_applet(n
, argv_expanded
);
7130 goto clean_up_and_ret
;
7133 /* It is neither builtin nor applet. We must fork. */
7137 /* NB: argv_expanded may already be created, and that
7138 * might include `cmd` runs! Do not rerun it! We *must*
7139 * use argv_expanded if it's non-NULL */
7141 /* Going to fork a child per each pipe member */
7146 while (cmd_no
< pi
->num_cmds
) {
7147 struct fd_pair pipefds
;
7149 volatile nommu_save_t nommu_save
;
7150 nommu_save
.new_env
= NULL
;
7151 nommu_save
.old_vars
= NULL
;
7152 nommu_save
.argv
= NULL
;
7153 nommu_save
.argv_from_re_execing
= NULL
;
7155 command
= &pi
->cmds
[cmd_no
];
7157 if (command
->argv
) {
7158 debug_printf_exec(": pipe member '%s' '%s'...\n",
7159 command
->argv
[0], command
->argv
[1]);
7161 debug_printf_exec(": pipe member with no argv\n");
7164 /* pipes are inserted between pairs of commands */
7167 if (cmd_no
< pi
->num_cmds
)
7168 xpiped_pair(pipefds
);
7170 command
->pid
= BB_MMU
? fork() : vfork();
7171 if (!command
->pid
) { /* child */
7173 disable_restore_tty_pgrp_on_exit();
7174 CLEAR_RANDOM_T(&G
.random_gen
); /* or else $RANDOM repeats in child */
7176 /* Every child adds itself to new process group
7177 * with pgid == pid_of_first_child_in_pipe */
7178 if (G
.run_list_level
== 1 && G_interactive_fd
) {
7181 if (pgrp
< 0) /* true for 1st process only */
7183 if (setpgid(0, pgrp
) == 0
7184 && pi
->followup
!= PIPE_BG
7185 && G_saved_tty_pgrp
/* we have ctty */
7187 /* We do it in *every* child, not just first,
7189 tcsetpgrp(G_interactive_fd
, pgrp
);
7193 if (pi
->alive_cmds
== 0 && pi
->followup
== PIPE_BG
) {
7194 /* 1st cmd in backgrounded pipe
7195 * should have its stdin /dev/null'ed */
7197 if (open(bb_dev_null
, O_RDONLY
))
7198 xopen("/", O_RDONLY
);
7200 xmove_fd(next_infd
, 0);
7202 xmove_fd(pipefds
.wr
, 1);
7205 /* Like bash, explicit redirects override pipes,
7206 * and the pipe fd is available for dup'ing. */
7207 if (setup_redirects(command
, NULL
))
7210 /* Stores to nommu_save list of env vars putenv'ed
7211 * (NOMMU, on MMU we don't need that) */
7212 /* cast away volatility... */
7213 pseudo_exec((nommu_save_t
*) &nommu_save
, command
, argv_expanded
);
7214 /* pseudo_exec() does not return */
7217 /* parent or error */
7218 #if ENABLE_HUSH_FAST
7220 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7222 enable_restore_tty_pgrp_on_exit();
7224 /* Clean up after vforked child */
7225 free(nommu_save
.argv
);
7226 free(nommu_save
.argv_from_re_execing
);
7227 unset_vars(nommu_save
.new_env
);
7228 add_vars(nommu_save
.old_vars
);
7230 free(argv_expanded
);
7231 argv_expanded
= NULL
;
7232 if (command
->pid
< 0) { /* [v]fork failed */
7233 /* Clearly indicate, was it fork or vfork */
7234 bb_perror_msg(BB_MMU
? "vfork"+1 : "vfork");
7238 /* Second and next children need to know pid of first one */
7240 pi
->pgrp
= command
->pid
;
7246 if (cmd_no
< pi
->num_cmds
)
7248 /* Pass read (output) pipe end to next iteration */
7249 next_infd
= pipefds
.rd
;
7252 if (!pi
->alive_cmds
) {
7254 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7259 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi
->alive_cmds
);
7263 /* NB: called by pseudo_exec, and therefore must not modify any
7264 * global data until exec/_exit (we can be a child after vfork!) */
7265 static int run_list(struct pipe
*pi
)
7267 #if ENABLE_HUSH_CASE
7268 char *case_word
= NULL
;
7270 #if ENABLE_HUSH_LOOPS
7271 struct pipe
*loop_top
= NULL
;
7272 char **for_lcur
= NULL
;
7273 char **for_list
= NULL
;
7275 smallint last_followup
;
7277 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7278 smalluint cond_code
= 0;
7280 enum { cond_code
= 0 };
7283 smallint rword
; /* RES_foo */
7284 smallint last_rword
; /* ditto */
7287 debug_printf_exec("run_list start lvl %d\n", G
.run_list_level
);
7290 #if ENABLE_HUSH_LOOPS
7291 /* Check syntax for "for" */
7294 for (cpipe
= pi
; cpipe
; cpipe
= cpipe
->next
) {
7295 if (cpipe
->res_word
!= RES_FOR
&& cpipe
->res_word
!= RES_IN
)
7297 /* current word is FOR or IN (BOLD in comments below) */
7298 if (cpipe
->next
== NULL
) {
7299 syntax_error("malformed for");
7301 debug_printf_exec("run_list lvl %d return 1\n", G
.run_list_level
);
7304 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7305 if (cpipe
->next
->res_word
== RES_DO
)
7307 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7308 if (cpipe
->res_word
== RES_IN
/* "for v IN a b; not_do..."? */
7309 || cpipe
->next
->res_word
!= RES_IN
/* FOR v not_do_and_not_in..."? */
7311 syntax_error("malformed for");
7313 debug_printf_exec("run_list lvl %d return 1\n", G
.run_list_level
);
7320 /* Past this point, all code paths should jump to ret: label
7321 * in order to return, no direct "return" statements please.
7322 * This helps to ensure that no memory is leaked. */
7330 last_rword
= RES_XXXX
;
7332 last_followup
= PIPE_SEQ
;
7333 rcode
= G
.last_exitcode
;
7335 /* Go through list of pipes, (maybe) executing them. */
7336 for (; pi
; pi
= IF_HUSH_LOOPS(rword
== RES_DONE
? loop_top
: ) pi
->next
) {
7340 IF_HAS_KEYWORDS(rword
= pi
->res_word
;)
7341 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7342 rword
, cond_code
, last_rword
);
7343 #if ENABLE_HUSH_LOOPS
7344 if ((rword
== RES_WHILE
|| rword
== RES_UNTIL
|| rword
== RES_FOR
)
7345 && loop_top
== NULL
/* avoid bumping G.depth_of_loop twice */
7347 /* start of a loop: remember where loop starts */
7352 /* Still in the same "if...", "then..." or "do..." branch? */
7353 if (IF_HAS_KEYWORDS(rword
== last_rword
&&) 1) {
7354 if ((rcode
== 0 && last_followup
== PIPE_OR
)
7355 || (rcode
!= 0 && last_followup
== PIPE_AND
)
7357 /* It is "<true> || CMD" or "<false> && CMD"
7358 * and we should not execute CMD */
7359 debug_printf_exec("skipped cmd because of || or &&\n");
7360 last_followup
= pi
->followup
;
7364 last_followup
= pi
->followup
;
7365 IF_HAS_KEYWORDS(last_rword
= rword
;)
7368 if (rword
== RES_THEN
) {
7369 /* if false; then ... fi has exitcode 0! */
7370 G
.last_exitcode
= rcode
= EXIT_SUCCESS
;
7371 /* "if <false> THEN cmd": skip cmd */
7375 if (rword
== RES_ELSE
|| rword
== RES_ELIF
) {
7376 /* "if <true> then ... ELSE/ELIF cmd":
7377 * skip cmd and all following ones */
7382 #if ENABLE_HUSH_LOOPS
7383 if (rword
== RES_FOR
) { /* && pi->num_cmds - always == 1 */
7385 /* first loop through for */
7387 static const char encoded_dollar_at
[] ALIGN1
= {
7388 SPECIAL_VAR_SYMBOL
, '@' | 0x80, SPECIAL_VAR_SYMBOL
, '\0'
7389 }; /* encoded representation of "$@" */
7390 static const char *const encoded_dollar_at_argv
[] = {
7391 encoded_dollar_at
, NULL
7392 }; /* argv list with one element: "$@" */
7395 vals
= (char**)encoded_dollar_at_argv
;
7396 if (pi
->next
->res_word
== RES_IN
) {
7397 /* if no variable values after "in" we skip "for" */
7398 if (!pi
->next
->cmds
[0].argv
) {
7399 G
.last_exitcode
= rcode
= EXIT_SUCCESS
;
7400 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7403 vals
= pi
->next
->cmds
[0].argv
;
7404 } /* else: "for var; do..." -> assume "$@" list */
7405 /* create list of variable values */
7406 debug_print_strings("for_list made from", vals
);
7407 for_list
= expand_strvec_to_strvec(vals
);
7408 for_lcur
= for_list
;
7409 debug_print_strings("for_list", for_list
);
7412 /* "for" loop is over, clean up */
7418 /* Insert next value from for_lcur */
7419 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7420 set_local_var(xasprintf("%s=%s", pi
->cmds
[0].argv
[0], *for_lcur
++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7423 if (rword
== RES_IN
) {
7424 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7426 if (rword
== RES_DONE
) {
7427 continue; /* "done" has no cmds too */
7430 #if ENABLE_HUSH_CASE
7431 if (rword
== RES_CASE
) {
7432 case_word
= expand_strvec_to_string(pi
->cmds
->argv
);
7435 if (rword
== RES_MATCH
) {
7438 if (!case_word
) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7440 /* all prev words didn't match, does this one match? */
7441 argv
= pi
->cmds
->argv
;
7443 char *pattern
= expand_string_to_string(*argv
, /*unbackslash:*/ 1);
7444 /* TODO: which FNM_xxx flags to use? */
7445 cond_code
= (fnmatch(pattern
, case_word
, /*flags:*/ 0) != 0);
7447 if (cond_code
== 0) { /* match! we will execute this branch */
7448 free(case_word
); /* make future "word)" stop */
7456 if (rword
== RES_CASE_BODY
) { /* inside of a case branch */
7458 continue; /* not matched yet, skip this pipe */
7461 /* Just pressing <enter> in shell should check for jobs.
7462 * OTOH, in non-interactive shell this is useless
7463 * and only leads to extra job checks */
7464 if (pi
->num_cmds
== 0) {
7465 if (G_interactive_fd
)
7466 goto check_jobs_and_continue
;
7470 /* After analyzing all keywords and conditions, we decided
7471 * to execute this pipe. NB: have to do checkjobs(NULL)
7472 * after run_pipe to collect any background children,
7473 * even if list execution is to be stopped. */
7474 debug_printf_exec(": run_pipe with %d members\n", pi
->num_cmds
);
7477 #if ENABLE_HUSH_LOOPS
7478 G
.flag_break_continue
= 0;
7480 rcode
= r
= run_pipe(pi
); /* NB: rcode is a smallint */
7482 /* We ran a builtin, function, or group.
7483 * rcode is already known
7484 * and we don't need to wait for anything. */
7485 G
.last_exitcode
= rcode
;
7486 debug_printf_exec(": builtin/func exitcode %d\n", rcode
);
7487 check_and_run_traps();
7488 #if ENABLE_HUSH_LOOPS
7489 /* Was it "break" or "continue"? */
7490 if (G
.flag_break_continue
) {
7491 smallint fbc
= G
.flag_break_continue
;
7492 /* We might fall into outer *loop*,
7493 * don't want to break it too */
7495 G
.depth_break_continue
--;
7496 if (G
.depth_break_continue
== 0)
7497 G
.flag_break_continue
= 0;
7498 /* else: e.g. "continue 2" should *break* once, *then* continue */
7499 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7500 if (G
.depth_break_continue
!= 0 || fbc
== BC_BREAK
)
7501 goto check_jobs_and_break
;
7502 /* "continue": simulate end of loop */
7507 #if ENABLE_HUSH_FUNCTIONS
7508 if (G
.flag_return_in_progress
== 1) {
7509 /* same as "goto check_jobs_and_break" */
7514 } else if (pi
->followup
== PIPE_BG
) {
7515 /* What does bash do with attempts to background builtins? */
7516 /* even bash 3.2 doesn't do that well with nested bg:
7517 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7518 * I'm NOT treating inner &'s as jobs */
7519 check_and_run_traps();
7521 if (G
.run_list_level
== 1)
7524 /* Last command's pid goes to $! */
7525 G
.last_bg_pid
= pi
->cmds
[pi
->num_cmds
- 1].pid
;
7526 G
.last_exitcode
= rcode
= EXIT_SUCCESS
;
7527 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7530 if (G
.run_list_level
== 1 && G_interactive_fd
) {
7531 /* Waits for completion, then fg's main shell */
7532 rcode
= checkjobs_and_fg_shell(pi
);
7533 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode
);
7534 check_and_run_traps();
7537 { /* This one just waits for completion */
7538 rcode
= checkjobs(pi
);
7539 debug_printf_exec(": checkjobs exitcode %d\n", rcode
);
7540 check_and_run_traps();
7542 G
.last_exitcode
= rcode
;
7546 /* Analyze how result affects subsequent commands */
7548 if (rword
== RES_IF
|| rword
== RES_ELIF
)
7551 #if ENABLE_HUSH_LOOPS
7552 /* Beware of "while false; true; do ..."! */
7554 && (pi
->next
->res_word
== RES_DO
|| pi
->next
->res_word
== RES_DONE
)
7555 /* check for RES_DONE is needed for "while ...; do \n done" case */
7557 if (rword
== RES_WHILE
) {
7559 /* "while false; do...done" - exitcode 0 */
7560 G
.last_exitcode
= rcode
= EXIT_SUCCESS
;
7561 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7562 goto check_jobs_and_break
;
7565 if (rword
== RES_UNTIL
) {
7567 debug_printf_exec(": until expr is true: breaking\n");
7568 check_jobs_and_break
:
7576 check_jobs_and_continue
:
7583 #if ENABLE_HUSH_LOOPS
7588 #if ENABLE_HUSH_CASE
7592 debug_printf_exec("run_list lvl %d return %d\n", G
.run_list_level
+ 1, rcode
);
7596 /* Select which version we will use */
7597 static int run_and_free_list(struct pipe
*pi
)
7600 debug_printf_exec("run_and_free_list entered\n");
7601 if (!G
.o_opt
[OPT_O_NOEXEC
]) {
7602 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi
->num_cmds
);
7603 rcode
= run_list(pi
);
7605 /* free_pipe_list has the side effect of clearing memory.
7606 * In the long run that function can be merged with run_list,
7607 * but doing that now would hobble the debugging effort. */
7609 debug_printf_exec("run_and_free_list return %d\n", rcode
);
7614 static void install_sighandlers(unsigned mask
)
7616 sighandler_t old_handler
;
7618 while ((mask
>>= 1) != 0) {
7622 old_handler
= install_sighandler(sig
, pick_sighandler(sig
));
7623 /* POSIX allows shell to re-enable SIGCHLD
7624 * even if it was SIG_IGN on entry.
7625 * Therefore we skip IGN check for it:
7629 if (old_handler
== SIG_IGN
) {
7630 /* oops... restore back to IGN, and record this fact */
7631 install_sighandler(sig
, old_handler
);
7633 G
.traps
= xzalloc(sizeof(G
.traps
[0]) * NSIG
);
7635 G
.traps
[sig
] = xzalloc(1); /* == xstrdup(""); */
7640 /* Called a few times only (or even once if "sh -c") */
7641 static void install_special_sighandlers(void)
7645 /* Which signals are shell-special? */
7646 mask
= (1 << SIGQUIT
) | (1 << SIGCHLD
);
7647 if (G_interactive_fd
) {
7648 mask
|= SPECIAL_INTERACTIVE_SIGS
;
7649 if (G_saved_tty_pgrp
) /* we have ctty, job control sigs work */
7650 mask
|= SPECIAL_JOBSTOP_SIGS
;
7652 /* Careful, do not re-install handlers we already installed */
7653 if (G
.special_sig_mask
!= mask
) {
7654 unsigned diff
= mask
& ~G
.special_sig_mask
;
7655 G
.special_sig_mask
= mask
;
7656 install_sighandlers(diff
);
7662 /* Set handlers to restore tty pgrp and exit */
7663 static void install_fatal_sighandlers(void)
7667 /* We will restore tty pgrp on these signals */
7669 + (1 << SIGILL
) * HUSH_DEBUG
7670 + (1 << SIGFPE
) * HUSH_DEBUG
7671 + (1 << SIGBUS
) * HUSH_DEBUG
7672 + (1 << SIGSEGV
) * HUSH_DEBUG
7673 + (1 << SIGTRAP
) * HUSH_DEBUG
7675 /* bash 3.2 seems to handle these just like 'fatal' ones */
7678 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7679 * if we aren't interactive... but in this case
7680 * we never want to restore pgrp on exit, and this fn is not called
7682 /*+ (1 << SIGHUP )*/
7683 /*+ (1 << SIGTERM)*/
7684 /*+ (1 << SIGINT )*/
7686 G_fatal_sig_mask
= mask
;
7688 install_sighandlers(mask
);
7692 static int set_mode(int state
, char mode
, const char *o_opt
)
7697 G
.o_opt
[OPT_O_NOEXEC
] = state
;
7700 IF_HUSH_MODE_X(G_x_mode
= state
;)
7704 /* "set -+o" without parameter.
7705 * in bash, set -o produces this output:
7709 * We always use the second form.
7711 const char *p
= o_opt_strings
;
7714 printf("set %co %s\n", (G
.o_opt
[idx
] ? '-' : '+'), p
);
7720 idx
= index_in_strings(o_opt_strings
, o_opt
);
7722 G
.o_opt
[idx
] = state
;
7726 return EXIT_FAILURE
;
7728 return EXIT_SUCCESS
;
7731 int hush_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
7732 int hush_main(int argc
, char **argv
)
7735 OPT_login
= (1 << 0),
7739 unsigned builtin_argc
;
7741 struct variable
*cur_var
;
7742 struct variable
*shell_ver
;
7745 if (EXIT_SUCCESS
!= 0) /* if EXIT_SUCCESS == 0, it is already done */
7746 G
.last_exitcode
= EXIT_SUCCESS
;
7747 #if ENABLE_HUSH_FAST
7748 G
.count_SIGCHLD
++; /* ensure it is != G.handled_SIGCHLD */
7751 G
.argv0_for_re_execing
= argv
[0];
7753 /* Deal with HUSH_VERSION */
7754 shell_ver
= xzalloc(sizeof(*shell_ver
));
7755 shell_ver
->flg_export
= 1;
7756 shell_ver
->flg_read_only
= 1;
7757 /* Code which handles ${var<op>...} needs writable values for all variables,
7758 * therefore we xstrdup: */
7759 shell_ver
->varstr
= xstrdup(hush_version_str
);
7760 /* Create shell local variables from the values
7761 * currently living in the environment */
7762 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7763 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7764 G
.top_var
= shell_ver
;
7765 cur_var
= G
.top_var
;
7768 char *value
= strchr(*e
, '=');
7769 if (value
) { /* paranoia */
7770 cur_var
->next
= xzalloc(sizeof(*cur_var
));
7771 cur_var
= cur_var
->next
;
7772 cur_var
->varstr
= *e
;
7773 cur_var
->max_len
= strlen(*e
);
7774 cur_var
->flg_export
= 1;
7778 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7779 debug_printf_env("putenv '%s'\n", shell_ver
->varstr
);
7780 putenv(shell_ver
->varstr
);
7783 set_pwd_var(/*exp:*/ 1);
7784 /* bash also exports SHLVL and _,
7785 * and sets (but doesn't export) the following variables:
7787 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7788 * BASH_VERSION='3.2.0(1)-release'
7790 * MACHTYPE=i386-pc-linux-gnu
7792 * HOSTNAME=<xxxxxxxxxx>
7793 * PPID=<NNNNN> - we also do it elsewhere
7804 * PIPESTATUS=([0]="0")
7805 * HISTFILE=/<xxx>/.bash_history
7809 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7811 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7821 #if ENABLE_FEATURE_EDITING
7822 G
.line_input_state
= new_line_input_t(FOR_SHELL
);
7825 /* Initialize some more globals to non-zero values */
7826 cmdedit_update_prompt();
7828 if (setjmp(die_jmp
)) {
7829 /* xfunc has failed! die die die */
7830 /* no EXIT traps, this is an escape hatch! */
7832 hush_exit(xfunc_error_retval
);
7835 /* Shell is non-interactive at first. We need to call
7836 * install_special_sighandlers() if we are going to execute "sh <script>",
7837 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7838 * If we later decide that we are interactive, we run install_special_sighandlers()
7839 * in order to intercept (more) signals.
7843 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7844 flags
= (argv
[0] && argv
[0][0] == '-') ? OPT_login
: 0;
7847 opt
= getopt(argc
, argv
, "+c:xinsl"
7850 # if ENABLE_HUSH_FUNCTIONS
7860 * sh ... -c 'script'
7861 * sh ... -c 'script' ARG0 [ARG1...]
7862 * On NOMMU, if builtin_argc != 0,
7863 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7864 * "" needs to be replaced with NULL
7865 * and BARGV vector fed to builtin function.
7866 * Note: the form without ARG0 never happens:
7867 * sh ... -c 'builtin' BARGV... ""
7870 G
.root_pid
= getpid();
7871 G
.root_ppid
= getppid();
7873 G
.global_argv
= argv
+ optind
;
7874 G
.global_argc
= argc
- optind
;
7876 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7877 const struct built_in_command
*x
;
7879 install_special_sighandlers();
7880 x
= find_builtin(optarg
);
7881 if (x
) { /* paranoia */
7882 G
.global_argc
-= builtin_argc
; /* skip [BARGV...] "" */
7883 G
.global_argv
+= builtin_argc
;
7884 G
.global_argv
[-1] = NULL
; /* replace "" */
7886 G
.last_exitcode
= x
->b_function(argv
+ optind
- 1);
7890 if (!G
.global_argv
[0]) {
7891 /* -c 'script' (no params): prevent empty $0 */
7892 G
.global_argv
--; /* points to argv[i] of 'script' */
7893 G
.global_argv
[0] = argv
[0];
7895 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7896 install_special_sighandlers();
7897 parse_and_run_string(optarg
);
7900 /* Well, we cannot just declare interactiveness,
7901 * we have to have some stuff (ctty, etc) */
7902 /* G_interactive_fd++; */
7905 /* "-s" means "read from stdin", but this is how we always
7906 * operate, so simply do nothing here. */
7912 case '<': /* "big heredoc" support */
7913 full_write1_str(optarg
);
7916 unsigned long long empty_trap_mask
;
7918 G
.root_pid
= bb_strtou(optarg
, &optarg
, 16);
7920 G
.root_ppid
= bb_strtou(optarg
, &optarg
, 16);
7922 G
.last_bg_pid
= bb_strtou(optarg
, &optarg
, 16);
7924 G
.last_exitcode
= bb_strtou(optarg
, &optarg
, 16);
7926 builtin_argc
= bb_strtou(optarg
, &optarg
, 16);
7928 empty_trap_mask
= bb_strtoull(optarg
, &optarg
, 16);
7929 if (empty_trap_mask
!= 0) {
7931 install_special_sighandlers();
7932 G
.traps
= xzalloc(sizeof(G
.traps
[0]) * NSIG
);
7933 for (sig
= 1; sig
< NSIG
; sig
++) {
7934 if (empty_trap_mask
& (1LL << sig
)) {
7935 G
.traps
[sig
] = xzalloc(1); /* == xstrdup(""); */
7936 install_sighandler(sig
, SIG_IGN
);
7940 # if ENABLE_HUSH_LOOPS
7942 G
.depth_of_loop
= bb_strtou(optarg
, &optarg
, 16);
7948 set_local_var(xstrdup(optarg
), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt
== 'R');
7950 # if ENABLE_HUSH_FUNCTIONS
7952 struct function
*funcp
= new_function(optarg
);
7953 /* funcp->name is already set to optarg */
7954 /* funcp->body is set to NULL. It's a special case. */
7955 funcp
->body_as_string
= argv
[optind
];
7963 if (set_mode(1, opt
, NULL
) == 0) /* no error */
7967 fprintf(stderr
, "Usage: sh [FILE]...\n"
7968 " or: sh -c command [args]...\n\n");
7974 } /* option parsing loop */
7976 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7977 G
.global_argc
= argc
- (optind
- 1);
7978 G
.global_argv
= argv
+ (optind
- 1);
7979 G
.global_argv
[0] = argv
[0];
7982 G
.root_pid
= getpid();
7983 G
.root_ppid
= getppid();
7986 /* If we are login shell... */
7987 if (flags
& OPT_login
) {
7989 debug_printf("sourcing /etc/profile\n");
7990 input
= fopen_for_read("/etc/profile");
7991 if (input
!= NULL
) {
7992 close_on_exec_on(fileno(input
));
7993 install_special_sighandlers();
7994 parse_and_run_file(input
);
7997 /* bash: after sourcing /etc/profile,
7998 * tries to source (in the given order):
7999 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8000 * stopping on first found. --noprofile turns this off.
8001 * bash also sources ~/.bash_logout on exit.
8002 * If called as sh, skips .bash_XXX files.
8006 if (G
.global_argv
[1]) {
8009 * "bash <script>" (which is never interactive (unless -i?))
8010 * sources $BASH_ENV here (without scanning $PATH).
8011 * If called as sh, does the same but with $ENV.
8015 debug_printf("running script '%s'\n", G
.global_argv
[0]);
8016 input
= xfopen_for_read(G
.global_argv
[0]);
8017 close_on_exec_on(fileno(input
));
8018 install_special_sighandlers();
8019 parse_and_run_file(input
);
8020 #if ENABLE_FEATURE_CLEAN_UP
8026 /* Up to here, shell was non-interactive. Now it may become one.
8027 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8030 /* A shell is interactive if the '-i' flag was given,
8031 * or if all of the following conditions are met:
8033 * no arguments remaining or the -s flag given
8034 * standard input is a terminal
8035 * standard output is a terminal
8036 * Refer to Posix.2, the description of the 'sh' utility.
8039 if (isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
)) {
8040 G_saved_tty_pgrp
= tcgetpgrp(STDIN_FILENO
);
8041 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp
);
8042 if (G_saved_tty_pgrp
< 0)
8043 G_saved_tty_pgrp
= 0;
8045 /* try to dup stdin to high fd#, >= 255 */
8046 G_interactive_fd
= fcntl(STDIN_FILENO
, F_DUPFD
, 255);
8047 if (G_interactive_fd
< 0) {
8048 /* try to dup to any fd */
8049 G_interactive_fd
= dup(STDIN_FILENO
);
8050 if (G_interactive_fd
< 0) {
8052 G_interactive_fd
= 0;
8053 G_saved_tty_pgrp
= 0;
8056 // TODO: track & disallow any attempts of user
8057 // to (inadvertently) close/redirect G_interactive_fd
8059 debug_printf("interactive_fd:%d\n", G_interactive_fd
);
8060 if (G_interactive_fd
) {
8061 close_on_exec_on(G_interactive_fd
);
8063 if (G_saved_tty_pgrp
) {
8064 /* If we were run as 'hush &', sleep until we are
8065 * in the foreground (tty pgrp == our pgrp).
8066 * If we get started under a job aware app (like bash),
8067 * make sure we are now in charge so we don't fight over
8068 * who gets the foreground */
8070 pid_t shell_pgrp
= getpgrp();
8071 G_saved_tty_pgrp
= tcgetpgrp(G_interactive_fd
);
8072 if (G_saved_tty_pgrp
== shell_pgrp
)
8074 /* send TTIN to ourself (should stop us) */
8075 kill(- shell_pgrp
, SIGTTIN
);
8079 /* Install more signal handlers */
8080 install_special_sighandlers();
8082 if (G_saved_tty_pgrp
) {
8083 /* Set other signals to restore saved_tty_pgrp */
8084 install_fatal_sighandlers();
8085 /* Put ourselves in our own process group
8086 * (bash, too, does this only if ctty is available) */
8087 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8088 /* Grab control of the terminal */
8089 tcsetpgrp(G_interactive_fd
, getpid());
8091 /* -1 is special - makes xfuncs longjmp, not exit
8092 * (we reset die_sleep = 0 whereever we [v]fork) */
8093 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8095 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8097 const char *hp
= get_local_var_value("HISTFILE");
8099 hp
= get_local_var_value("HOME");
8101 hp
= concat_path_file(hp
, ".hush_history");
8106 G
.line_input_state
->hist_file
= hp
;
8107 //set_local_var(xasprintf("HISTFILE=%s", ...));
8109 # if ENABLE_FEATURE_SH_HISTFILESIZE
8110 hp
= get_local_var_value("HISTFILESIZE");
8111 G
.line_input_state
->max_history
= size_from_HISTFILESIZE(hp
);
8116 install_special_sighandlers();
8118 #elif ENABLE_HUSH_INTERACTIVE
8119 /* No job control compiled in, only prompt/line editing */
8120 if (isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
)) {
8121 G_interactive_fd
= fcntl(STDIN_FILENO
, F_DUPFD
, 255);
8122 if (G_interactive_fd
< 0) {
8123 /* try to dup to any fd */
8124 G_interactive_fd
= dup(STDIN_FILENO
);
8125 if (G_interactive_fd
< 0)
8127 G_interactive_fd
= 0;
8130 if (G_interactive_fd
) {
8131 close_on_exec_on(G_interactive_fd
);
8133 install_special_sighandlers();
8135 /* We have interactiveness code disabled */
8136 install_special_sighandlers();
8139 * if interactive but not a login shell, sources ~/.bashrc
8140 * (--norc turns this off, --rcfile <file> overrides)
8143 if (!ENABLE_FEATURE_SH_EXTRA_QUIET
&& G_interactive_fd
) {
8144 /* note: ash and hush share this string */
8145 printf("\n\n%s %s\n"
8146 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8149 "hush - the humble shell"
8153 parse_and_run_file(stdin
);
8156 hush_exit(G
.last_exitcode
);
8161 int msh_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
8162 int msh_main(int argc
, char **argv
)
8164 //bb_error_msg("msh is deprecated, please use hush instead");
8165 return hush_main(argc
, argv
);
8173 static int FAST_FUNC
builtin_true(char **argv UNUSED_PARAM
)
8178 static int run_applet_main(char **argv
, int (*applet_main_func
)(int argc
, char **argv
))
8185 return applet_main_func(argc
, argv
- argc
);
8188 static int FAST_FUNC
builtin_test(char **argv
)
8190 return run_applet_main(argv
, test_main
);
8193 static int FAST_FUNC
builtin_echo(char **argv
)
8195 return run_applet_main(argv
, echo_main
);
8199 static int FAST_FUNC
builtin_printf(char **argv
)
8201 return run_applet_main(argv
, printf_main
);
8205 static char **skip_dash_dash(char **argv
)
8208 if (argv
[0] && argv
[0][0] == '-' && argv
[0][1] == '-' && argv
[0][2] == '\0')
8213 static int FAST_FUNC
builtin_eval(char **argv
)
8215 int rcode
= EXIT_SUCCESS
;
8217 argv
= skip_dash_dash(argv
);
8219 char *str
= expand_strvec_to_string(argv
);
8221 * eval "echo Hi; done" ("done" is syntax error):
8222 * "echo Hi" will not execute too.
8224 parse_and_run_string(str
);
8226 rcode
= G
.last_exitcode
;
8231 static int FAST_FUNC
builtin_cd(char **argv
)
8235 argv
= skip_dash_dash(argv
);
8237 if (newdir
== NULL
) {
8238 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8239 * bash says "bash: cd: HOME not set" and does nothing
8242 const char *home
= get_local_var_value("HOME");
8243 newdir
= home
? home
: "/";
8245 if (chdir(newdir
)) {
8246 /* Mimic bash message exactly */
8247 bb_perror_msg("cd: %s", newdir
);
8248 return EXIT_FAILURE
;
8250 /* Read current dir (get_cwd(1) is inside) and set PWD.
8251 * Note: do not enforce exporting. If PWD was unset or unexported,
8252 * set it again, but do not export. bash does the same.
8254 set_pwd_var(/*exp:*/ 0);
8255 return EXIT_SUCCESS
;
8258 static int FAST_FUNC
builtin_exec(char **argv
)
8260 argv
= skip_dash_dash(argv
);
8261 if (argv
[0] == NULL
)
8262 return EXIT_SUCCESS
; /* bash does this */
8264 /* Careful: we can end up here after [v]fork. Do not restore
8265 * tty pgrp then, only top-level shell process does that */
8266 if (G_saved_tty_pgrp
&& getpid() == G
.root_pid
)
8267 tcsetpgrp(G_interactive_fd
, G_saved_tty_pgrp
);
8269 /* TODO: if exec fails, bash does NOT exit! We do.
8270 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8271 * and tcsetpgrp, and this is inherently racy.
8273 execvp_or_die(argv
);
8276 static int FAST_FUNC
builtin_exit(char **argv
)
8278 debug_printf_exec("%s()\n", __func__
);
8280 /* interactive bash:
8281 * # trap "echo EEE" EXIT
8284 * There are stopped jobs.
8285 * (if there are _stopped_ jobs, running ones don't count)
8288 # EEE (then bash exits)
8290 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8293 /* note: EXIT trap is run by hush_exit */
8294 argv
= skip_dash_dash(argv
);
8295 if (argv
[0] == NULL
)
8296 hush_exit(G
.last_exitcode
);
8297 /* mimic bash: exit 123abc == exit 255 + error msg */
8298 xfunc_error_retval
= 255;
8299 /* bash: exit -2 == exit 254, no error msg */
8300 hush_exit(xatoi(argv
[0]) & 0xff);
8303 static void print_escaped(const char *s
)
8308 const char *p
= strchrnul(s
, '\'');
8309 /* print 'xxxx', possibly just '' */
8310 printf("'%.*s'", (int)(p
- s
), s
);
8315 /* s points to '; print "'''...'''" */
8317 do putchar('\''); while (*++s
== '\'');
8322 #if !ENABLE_HUSH_LOCAL
8323 #define helper_export_local(argv, exp, lvl) \
8324 helper_export_local(argv, exp)
8326 static void helper_export_local(char **argv
, int exp
, int lvl
)
8330 char *name_end
= strchrnul(name
, '=');
8332 /* So far we do not check that name is valid (TODO?) */
8334 if (*name_end
== '\0') {
8335 struct variable
*var
, **vpp
;
8337 vpp
= get_ptr_to_local_var(name
, name_end
- name
);
8338 var
= vpp
? *vpp
: NULL
;
8340 if (exp
== -1) { /* unexporting? */
8341 /* export -n NAME (without =VALUE) */
8343 var
->flg_export
= 0;
8344 debug_printf_env("%s: unsetenv '%s'\n", __func__
, name
);
8346 } /* else: export -n NOT_EXISTING_VAR: no-op */
8349 if (exp
== 1) { /* exporting? */
8350 /* export NAME (without =VALUE) */
8352 var
->flg_export
= 1;
8353 debug_printf_env("%s: putenv '%s'\n", __func__
, var
->varstr
);
8354 putenv(var
->varstr
);
8358 /* Exporting non-existing variable.
8359 * bash does not put it in environment,
8360 * but remembers that it is exported,
8361 * and does put it in env when it is set later.
8362 * We just set it to "" and export. */
8363 /* Or, it's "local NAME" (without =VALUE).
8364 * bash sets the value to "". */
8365 name
= xasprintf("%s=", name
);
8367 /* (Un)exporting/making local NAME=VALUE */
8368 name
= xstrdup(name
);
8370 set_local_var(name
, /*exp:*/ exp
, /*lvl:*/ lvl
, /*ro:*/ 0);
8374 static int FAST_FUNC
builtin_export(char **argv
)
8376 unsigned opt_unexport
;
8378 #if ENABLE_HUSH_EXPORT_N
8379 /* "!": do not abort on errors */
8380 opt_unexport
= getopt32(argv
, "!n");
8381 if (opt_unexport
== (uint32_t)-1)
8382 return EXIT_FAILURE
;
8389 if (argv
[0] == NULL
) {
8396 /* ash emits: export VAR='VAL'
8397 * bash: declare -x VAR="VAL"
8398 * we follow ash example */
8399 const char *s
= *e
++;
8400 const char *p
= strchr(s
, '=');
8402 if (!p
) /* wtf? take next variable */
8405 printf("export %.*s", (int)(p
- s
) + 1, s
);
8406 print_escaped(p
+ 1);
8410 /*fflush_all(); - done after each builtin anyway */
8412 return EXIT_SUCCESS
;
8415 helper_export_local(argv
, (opt_unexport
? -1 : 1), 0);
8417 return EXIT_SUCCESS
;
8420 #if ENABLE_HUSH_LOCAL
8421 static int FAST_FUNC
builtin_local(char **argv
)
8423 if (G
.func_nest_level
== 0) {
8424 bb_error_msg("%s: not in a function", argv
[0]);
8425 return EXIT_FAILURE
; /* bash compat */
8427 helper_export_local(argv
, 0, G
.func_nest_level
);
8428 return EXIT_SUCCESS
;
8432 static int FAST_FUNC
builtin_trap(char **argv
)
8438 G
.traps
= xzalloc(sizeof(G
.traps
[0]) * NSIG
);
8443 /* No args: print all trapped */
8444 for (i
= 0; i
< NSIG
; ++i
) {
8447 print_escaped(G
.traps
[i
]);
8448 /* note: bash adds "SIG", but only if invoked
8449 * as "bash". If called as "sh", or if set -o posix,
8450 * then it prints short signal names.
8451 * We are printing short names: */
8452 printf(" %s\n", get_signame(i
));
8455 /*fflush_all(); - done after each builtin anyway */
8456 return EXIT_SUCCESS
;
8460 /* If first arg is a number: reset all specified signals */
8461 sig
= bb_strtou(*argv
, NULL
, 10);
8467 sighandler_t handler
;
8469 sig
= get_signum(*argv
++);
8470 if (sig
< 0 || sig
>= NSIG
) {
8472 /* Mimic bash message exactly */
8473 bb_perror_msg("trap: %s: invalid signal specification", argv
[-1]);
8478 G
.traps
[sig
] = xstrdup(new_cmd
);
8480 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8481 get_signame(sig
), sig
, G
.traps
[sig
]);
8483 /* There is no signal for 0 (EXIT) */
8488 handler
= (new_cmd
[0] ? record_pending_signo
: SIG_IGN
);
8490 /* We are removing trap handler */
8491 handler
= pick_sighandler(sig
);
8492 install_sighandler(sig
, handler
);
8497 if (!argv
[1]) { /* no second arg */
8498 bb_error_msg("trap: invalid arguments");
8499 return EXIT_FAILURE
;
8502 /* First arg is "-": reset all specified to default */
8503 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8504 /* Everything else: set arg as signal handler
8505 * (includes "" case, which ignores signal) */
8506 if (argv
[0][0] == '-') {
8507 if (argv
[0][1] == '\0') { /* "-" */
8508 /* new_cmd remains NULL: "reset these sigs" */
8511 if (argv
[0][1] == '-' && argv
[0][2] == '\0') { /* "--" */
8514 /* else: "-something", no special meaning */
8519 goto process_sig_list
;
8522 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8523 static int FAST_FUNC
builtin_type(char **argv
)
8525 int ret
= EXIT_SUCCESS
;
8531 if (0) {} /* make conditional compile easier below */
8532 /*else if (find_alias(*argv))
8533 type = "an alias";*/
8534 #if ENABLE_HUSH_FUNCTIONS
8535 else if (find_function(*argv
))
8536 type
= "a function";
8538 else if (find_builtin(*argv
))
8539 type
= "a shell builtin";
8540 else if ((path
= find_in_path(*argv
)) != NULL
)
8543 bb_error_msg("type: %s: not found", *argv
);
8548 printf("%s is %s\n", *argv
, type
);
8556 /* built-in 'fg' and 'bg' handler */
8557 static int FAST_FUNC
builtin_fg_bg(char **argv
)
8562 if (!G_interactive_fd
)
8563 return EXIT_FAILURE
;
8565 /* If they gave us no args, assume they want the last backgrounded task */
8567 for (pi
= G
.job_list
; pi
; pi
= pi
->next
) {
8568 if (pi
->jobid
== G
.last_jobid
) {
8572 bb_error_msg("%s: no current job", argv
[0]);
8573 return EXIT_FAILURE
;
8575 if (sscanf(argv
[1], "%%%d", &jobnum
) != 1) {
8576 bb_error_msg("%s: bad argument '%s'", argv
[0], argv
[1]);
8577 return EXIT_FAILURE
;
8579 for (pi
= G
.job_list
; pi
; pi
= pi
->next
) {
8580 if (pi
->jobid
== jobnum
) {
8584 bb_error_msg("%s: %d: no such job", argv
[0], jobnum
);
8585 return EXIT_FAILURE
;
8587 /* TODO: bash prints a string representation
8588 * of job being foregrounded (like "sleep 1 | cat") */
8589 if (argv
[0][0] == 'f' && G_saved_tty_pgrp
) {
8590 /* Put the job into the foreground. */
8591 tcsetpgrp(G_interactive_fd
, pi
->pgrp
);
8594 /* Restart the processes in the job */
8595 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi
->num_cmds
, pi
->pgrp
);
8596 for (i
= 0; i
< pi
->num_cmds
; i
++) {
8597 debug_printf_jobs("reviving pid %d\n", pi
->cmds
[i
].pid
);
8599 pi
->stopped_cmds
= 0;
8601 i
= kill(- pi
->pgrp
, SIGCONT
);
8603 if (errno
== ESRCH
) {
8604 delete_finished_bg_job(pi
);
8605 return EXIT_SUCCESS
;
8607 bb_perror_msg("kill (SIGCONT)");
8610 if (argv
[0][0] == 'f') {
8612 return checkjobs_and_fg_shell(pi
);
8614 return EXIT_SUCCESS
;
8618 #if ENABLE_HUSH_HELP
8619 static int FAST_FUNC
builtin_help(char **argv UNUSED_PARAM
)
8621 const struct built_in_command
*x
;
8624 "Built-in commands:\n"
8625 "------------------\n");
8626 for (x
= bltins1
; x
!= &bltins1
[ARRAY_SIZE(bltins1
)]; x
++) {
8628 printf("%-10s%s\n", x
->b_cmd
, x
->b_descr
);
8631 return EXIT_SUCCESS
;
8636 static int FAST_FUNC
builtin_jobs(char **argv UNUSED_PARAM
)
8639 const char *status_string
;
8641 for (job
= G
.job_list
; job
; job
= job
->next
) {
8642 if (job
->alive_cmds
== job
->stopped_cmds
)
8643 status_string
= "Stopped";
8645 status_string
= "Running";
8647 printf(JOB_STATUS_FORMAT
, job
->jobid
, status_string
, job
->cmdtext
);
8649 return EXIT_SUCCESS
;
8654 static int FAST_FUNC
builtin_memleak(char **argv UNUSED_PARAM
)
8659 # ifdef M_TRIM_THRESHOLD
8660 /* Optional. Reduces probability of false positives */
8663 /* Crude attempt to find where "free memory" starts,
8664 * sans fragmentation. */
8666 l
= (unsigned long)p
;
8669 if (l
< (unsigned long)p
) l
= (unsigned long)p
;
8672 if (!G
.memleak_value
)
8673 G
.memleak_value
= l
;
8675 l
-= G
.memleak_value
;
8682 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8687 static int FAST_FUNC
builtin_pwd(char **argv UNUSED_PARAM
)
8690 return EXIT_SUCCESS
;
8693 /* Interruptibility of read builtin in bash
8694 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8696 * Empty trap makes read ignore corresponding signal, for any signal.
8699 * - terminates non-interactive shell;
8700 * - interrupts read in interactive shell;
8701 * if it has non-empty trap:
8702 * - executes trap and returns to command prompt in interactive shell;
8703 * - executes trap and returns to read in non-interactive shell;
8705 * - is ignored (does not interrupt) read in interactive shell;
8706 * - terminates non-interactive shell;
8707 * if it has non-empty trap:
8708 * - executes trap and returns to read;
8710 * - terminates shell (regardless of interactivity);
8711 * if it has non-empty trap:
8712 * - executes trap and returns to read;
8714 static int FAST_FUNC
builtin_read(char **argv
)
8724 /* "!": do not abort on errors.
8725 * Option string must start with "sr" to match BUILTIN_READ_xxx
8727 read_flags
= getopt32(argv
, "!srn:p:t:u:", &opt_n
, &opt_p
, &opt_t
, &opt_u
);
8728 if (read_flags
== (uint32_t)-1)
8729 return EXIT_FAILURE
;
8731 ifs
= get_local_var_value("IFS"); /* can be NULL */
8734 r
= shell_builtin_read(set_local_var_from_halves
,
8744 if ((uintptr_t)r
== 1 && errno
== EINTR
) {
8745 unsigned sig
= check_and_run_traps();
8746 if (sig
&& sig
!= SIGINT
)
8750 if ((uintptr_t)r
> 1) {
8751 bb_error_msg("%s", r
);
8752 r
= (char*)(uintptr_t)1;
8755 return (uintptr_t)r
;
8758 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8759 * built-in 'set' handler
8761 * set [-abCefhmnuvx] [-o option] [argument...]
8762 * set [+abCefhmnuvx] [+o option] [argument...]
8763 * set -- [argument...]
8766 * Implementations shall support the options in both their hyphen and
8767 * plus-sign forms. These options can also be specified as options to sh.
8769 * Write out all variables and their values: set
8770 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8771 * Turn on the -x and -v options: set -xv
8772 * Unset all positional parameters: set --
8773 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8774 * Set the positional parameters to the expansion of x, even if x expands
8775 * with a leading '-' or '+': set -- $x
8777 * So far, we only support "set -- [argument...]" and some of the short names.
8779 static int FAST_FUNC
builtin_set(char **argv
)
8782 char **pp
, **g_argv
;
8783 char *arg
= *++argv
;
8787 for (e
= G
.top_var
; e
; e
= e
->next
)
8789 return EXIT_SUCCESS
;
8793 if (strcmp(arg
, "--") == 0) {
8797 if (arg
[0] != '+' && arg
[0] != '-')
8799 for (n
= 1; arg
[n
]; ++n
) {
8800 if (set_mode((arg
[0] == '-'), arg
[n
], argv
[1]))
8802 if (arg
[n
] == 'o' && argv
[1])
8805 } while ((arg
= *++argv
) != NULL
);
8806 /* Now argv[0] is 1st argument */
8809 return EXIT_SUCCESS
;
8812 /* NB: G.global_argv[0] ($0) is never freed/changed */
8813 g_argv
= G
.global_argv
;
8814 if (G
.global_args_malloced
) {
8820 G
.global_args_malloced
= 1;
8821 pp
= xzalloc(sizeof(pp
[0]) * 2);
8822 pp
[0] = g_argv
[0]; /* retain $0 */
8825 /* This realloc's G.global_argv */
8826 G
.global_argv
= pp
= add_strings_to_strings(g_argv
, argv
, /*dup:*/ 1);
8833 return EXIT_SUCCESS
;
8835 /* Nothing known, so abort */
8837 bb_error_msg("set: %s: invalid option", arg
);
8838 return EXIT_FAILURE
;
8841 static int FAST_FUNC
builtin_shift(char **argv
)
8844 argv
= skip_dash_dash(argv
);
8848 if (n
>= 0 && n
< G
.global_argc
) {
8849 if (G
.global_args_malloced
) {
8852 free(G
.global_argv
[m
++]);
8855 memmove(&G
.global_argv
[1], &G
.global_argv
[n
+1],
8856 G
.global_argc
* sizeof(G
.global_argv
[0]));
8857 return EXIT_SUCCESS
;
8859 return EXIT_FAILURE
;
8862 static int FAST_FUNC
builtin_source(char **argv
)
8864 char *arg_path
, *filename
;
8867 #if ENABLE_HUSH_FUNCTIONS
8871 argv
= skip_dash_dash(argv
);
8874 /* bash says: "bash: .: filename argument required" */
8875 return 2; /* bash compat */
8878 if (!strchr(filename
, '/')) {
8879 arg_path
= find_in_path(filename
);
8881 filename
= arg_path
;
8883 input
= fopen_or_warn(filename
, "r");
8886 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8887 return EXIT_FAILURE
;
8889 close_on_exec_on(fileno(input
));
8891 #if ENABLE_HUSH_FUNCTIONS
8892 sv_flg
= G
.flag_return_in_progress
;
8893 /* "we are inside sourced file, ok to use return" */
8894 G
.flag_return_in_progress
= -1;
8896 save_and_replace_G_args(&sv
, argv
);
8898 parse_and_run_file(input
);
8901 restore_G_args(&sv
, argv
);
8902 #if ENABLE_HUSH_FUNCTIONS
8903 G
.flag_return_in_progress
= sv_flg
;
8906 return G
.last_exitcode
;
8909 static int FAST_FUNC
builtin_umask(char **argv
)
8915 argv
= skip_dash_dash(argv
);
8917 mode_t old_mask
= mask
;
8920 rc
= bb_parse_mode(argv
[0], &mask
);
8925 * bash: umask: 'q': invalid symbolic mode operator
8926 * bash: umask: 999: octal number out of range
8928 bb_error_msg("%s: invalid mode '%s'", "umask", argv
[0]);
8933 printf("%04o\n", (unsigned) mask
);
8934 /* fall through and restore mask which we set to 0 */
8938 return !rc
; /* rc != 0 - success */
8941 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8942 static int FAST_FUNC
builtin_unset(char **argv
)
8947 /* "!": do not abort on errors */
8948 /* "+": stop at 1st non-option */
8949 opts
= getopt32(argv
, "!+vf");
8950 if (opts
== (unsigned)-1)
8951 return EXIT_FAILURE
;
8953 bb_error_msg("unset: -v and -f are exclusive");
8954 return EXIT_FAILURE
;
8960 if (!(opts
& 2)) { /* not -f */
8961 if (unset_local_var(*argv
)) {
8962 /* unset <nonexistent_var> doesn't fail.
8963 * Error is when one tries to unset RO var.
8964 * Message was printed by unset_local_var. */
8968 #if ENABLE_HUSH_FUNCTIONS
8978 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8979 static int FAST_FUNC
builtin_wait(char **argv
)
8981 int ret
= EXIT_SUCCESS
;
8984 argv
= skip_dash_dash(argv
);
8985 if (argv
[0] == NULL
) {
8986 /* Don't care about wait results */
8987 /* Note 1: must wait until there are no more children */
8988 /* Note 2: must be interruptible */
8990 * $ sleep 3 & sleep 6 & wait
8995 * $ sleep 3 & sleep 6 & wait
8999 * ^C <-- after ~4 sec from keyboard
9004 sigset_t oldset
, allsigs
;
9006 /* waitpid is not interruptible by SA_RESTARTed
9007 * signals which we use. Thus, this ugly dance:
9010 /* Make sure possible SIGCHLD is stored in kernel's
9011 * pending signal mask before we call waitpid.
9012 * Or else we may race with SIGCHLD, lose it,
9013 * and get stuck in sigwaitinfo...
9015 sigfillset(&allsigs
);
9016 sigprocmask(SIG_SETMASK
, &allsigs
, &oldset
);
9018 if (!sigisemptyset(&G
.pending_set
)) {
9019 /* Crap! we raced with some signal! */
9024 checkjobs(NULL
); /* waitpid(WNOHANG) inside */
9025 if (errno
== ECHILD
) {
9026 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
9030 /* Wait for SIGCHLD or any other signal */
9031 //sig = sigwaitinfo(&allsigs, NULL);
9032 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9033 /* Note: sigsuspend invokes signal handler */
9034 sigsuspend(&oldset
);
9036 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
9038 /* So, did we get a signal? */
9040 // raise(sig); /* run handler */
9041 sig
= check_and_run_traps();
9042 if (sig
/*&& sig != SIGCHLD - always true */) {
9047 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9052 /* This is probably buggy wrt interruptible-ness */
9054 pid_t pid
= bb_strtou(*argv
, NULL
, 10);
9056 /* mimic bash message */
9057 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv
);
9058 return EXIT_FAILURE
;
9060 if (waitpid(pid
, &status
, 0) == pid
) {
9061 if (WIFSIGNALED(status
))
9062 ret
= 128 + WTERMSIG(status
);
9063 else if (WIFEXITED(status
))
9064 ret
= WEXITSTATUS(status
);
9068 bb_perror_msg("wait %s", *argv
);
9077 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9078 static unsigned parse_numeric_argv1(char **argv
, unsigned def
, unsigned def_min
)
9081 def
= bb_strtou(argv
[1], NULL
, 10);
9082 if (errno
|| def
< def_min
|| argv
[2]) {
9083 bb_error_msg("%s: bad arguments", argv
[0]);
9091 #if ENABLE_HUSH_LOOPS
9092 static int FAST_FUNC
builtin_break(char **argv
)
9095 if (G
.depth_of_loop
== 0) {
9096 bb_error_msg("%s: only meaningful in a loop", argv
[0]);
9097 return EXIT_SUCCESS
; /* bash compat */
9099 G
.flag_break_continue
++; /* BC_BREAK = 1 */
9101 G
.depth_break_continue
= depth
= parse_numeric_argv1(argv
, 1, 1);
9102 if (depth
== UINT_MAX
)
9103 G
.flag_break_continue
= BC_BREAK
;
9104 if (G
.depth_of_loop
< depth
)
9105 G
.depth_break_continue
= G
.depth_of_loop
;
9107 return EXIT_SUCCESS
;
9110 static int FAST_FUNC
builtin_continue(char **argv
)
9112 G
.flag_break_continue
= 1; /* BC_CONTINUE = 2 = 1+1 */
9113 return builtin_break(argv
);
9117 #if ENABLE_HUSH_FUNCTIONS
9118 static int FAST_FUNC
builtin_return(char **argv
)
9122 if (G
.flag_return_in_progress
!= -1) {
9123 bb_error_msg("%s: not in a function or sourced script", argv
[0]);
9124 return EXIT_FAILURE
; /* bash compat */
9127 G
.flag_return_in_progress
= 1;
9130 * out of range: wraps around at 256, does not error out
9131 * non-numeric param:
9132 * f() { false; return qwe; }; f; echo $?
9133 * bash: return: qwe: numeric argument required <== we do this
9134 * 255 <== we also do this
9136 rc
= parse_numeric_argv1(argv
, G
.last_exitcode
, 0);