1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
46 * Bash stuff (maybe optionally enable?):
47 * &> and >& redirection of stdout+stderr
49 * reserved words: [[ ]] function select
50 * substrings ${var:1:5}
53 * grep for "TODO" and fix (some of them are easy)
54 * change { and } from special chars to reserved words
55 * builtins: return, ulimit
56 * follow IFS rules more precisely, including update semantics
57 * figure out what to do with backslash-newline
58 * continuation lines, both explicit and implicit - done?
60 * ^Z handling (and explain it in comments for mere humans)
61 * separate job control from interactiveness
62 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
65 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
67 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
69 /* #include <dmalloc.h> */
76 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
80 /* Debug build knobs */
81 #define LEAK_HUNTING 0
82 #define BUILD_AS_NOMMU 0
83 /* Enable/disable sanity checks. Ok to enable in production,
84 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
85 * Keeping 1 for now even in released versions.
89 #define ENABLE_HUSH_FUNCTIONS 0
97 # define USE_FOR_NOMMU(...) __VA_ARGS__
98 # define USE_FOR_MMU(...)
101 #if defined SINGLE_APPLET_MAIN
102 /* STANDALONE does not make sense, and won't compile */
103 #undef CONFIG_FEATURE_SH_STANDALONE
104 #undef ENABLE_FEATURE_SH_STANDALONE
105 #undef USE_FEATURE_SH_STANDALONE
106 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
107 #define ENABLE_FEATURE_SH_STANDALONE 0
108 #define USE_FEATURE_SH_STANDALONE(...)
109 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
112 #if !ENABLE_HUSH_INTERACTIVE
113 #undef ENABLE_FEATURE_EDITING
114 #define ENABLE_FEATURE_EDITING 0
115 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
116 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
119 /* Do we support ANY keywords? */
120 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
121 #define HAS_KEYWORDS 1
122 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
123 #define IF_HAS_NO_KEYWORDS(...)
125 #define HAS_KEYWORDS 0
126 #define IF_HAS_KEYWORDS(...)
127 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
130 /* If you comment out one of these below, it will be #defined later
131 * to perform debug printfs to stderr: */
132 #define debug_printf(...) do {} while (0)
133 /* Finer-grained debug switches */
134 #define debug_printf_parse(...) do {} while (0)
135 #define debug_print_tree(a, b) do {} while (0)
136 #define debug_printf_exec(...) do {} while (0)
137 #define debug_printf_env(...) do {} while (0)
138 #define debug_printf_jobs(...) do {} while (0)
139 #define debug_printf_expand(...) do {} while (0)
140 #define debug_printf_glob(...) do {} while (0)
141 #define debug_printf_list(...) do {} while (0)
142 #define debug_printf_subst(...) do {} while (0)
143 #define debug_printf_clean(...) do {} while (0)
146 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
149 #ifndef debug_printf_parse
150 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
153 #ifndef debug_printf_exec
154 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
157 #ifndef debug_printf_env
158 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
161 #ifndef debug_printf_jobs
162 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
168 #ifndef debug_printf_expand
169 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
170 #define DEBUG_EXPAND 1
172 #define DEBUG_EXPAND 0
175 #ifndef debug_printf_glob
176 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
182 #ifndef debug_printf_list
183 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
186 #ifndef debug_printf_subst
187 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
190 #ifndef debug_printf_clean
191 /* broken, of course, but OK for testing */
192 static const char *indenter(int i)
194 static const char blanks[] ALIGN1 =
196 return &blanks[sizeof(blanks) - i - 1];
198 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
199 #define DEBUG_CLEAN 1
201 #define DEBUG_CLEAN 0
205 static void debug_print_strings(const char *prefix, char **vv)
207 fprintf(stderr, "%s:\n", prefix);
209 fprintf(stderr, " '%s'\n", *vv++);
212 #define debug_print_strings(prefix, vv) ((void)0)
215 #define ERR_PTR ((void*)(long)1)
217 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
219 #define SPECIAL_VAR_SYMBOL 3
221 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
223 /* This supports saving pointers malloced in vfork child,
224 * to be freed in the parent. One pointer is saved in
225 * G.argv_from_re_execing global var instead. TODO: unify.
228 typedef struct nommu_save_t {
235 /* The descrip member of this structure is only used to make
236 * debugging output pretty */
237 static const struct {
239 signed char default_fd;
243 { O_RDONLY, 0, "<" },
244 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
245 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
246 { O_RDONLY, 0, "<<" },
247 { O_CREAT|O_RDWR, 1, "<>" },
248 /* Should not be needed. Bogus default_fd helps in debugging */
249 /* { O_RDONLY, 77, "<<" }, */
252 typedef enum reserved_style {
261 #if ENABLE_HUSH_LOOPS
268 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
273 /* two pseudo-keywords support contrived "case" syntax: */
274 RES_MATCH , /* "word)" */
275 RES_CASEI , /* "this command is inside CASE" */
282 typedef struct o_string {
284 int length; /* position where data is appended */
286 /* Protect newly added chars against globbing
287 * (by prepending \ to *, ?, [, \) */
290 /* At least some part of the string was inside '' or "",
291 * possibly empty one: word"", wo''rd etc. */
293 smallint has_empty_slot;
294 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
297 MAYBE_ASSIGNMENT = 0,
298 DEFINITELY_ASSIGNMENT = 1,
300 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
302 /* Used for initialization: o_string foo = NULL_O_STRING; */
303 #define NULL_O_STRING { NULL }
305 /* I can almost use ordinary FILE*. Is open_memstream() universally
306 * available? Where is it documented? */
307 typedef struct in_str {
309 /* eof_flag=1: last char in ->p is really an EOF */
310 char eof_flag; /* meaningless if ->p == NULL */
312 #if ENABLE_HUSH_INTERACTIVE
314 smallint promptmode; /* 0: PS1, 1: PS2 */
317 int (*get) (struct in_str *);
318 int (*peek) (struct in_str *);
320 #define i_getch(input) ((input)->get(input))
321 #define i_peek(input) ((input)->peek(input))
323 struct redir_struct {
324 struct redir_struct *next;
325 char *rd_filename; /* filename */
326 int rd_fd; /* fd to redirect */
327 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
329 smallint rd_type; /* (enum redir_type) */
330 /* note: for heredocs, rd_filename contains heredoc delimiter,
331 * and subsequently heredoc itself; and rd_dup is a bitmask:
332 * 1: do we need to trim leading tabs?
333 * 2: is heredoc quoted (<<'dleim' syntax) ?
336 typedef enum redir_type {
337 REDIRECT_INVALID = 0,
339 REDIRECT_OVERWRITE = 2,
341 REDIRECT_HEREDOC = 4,
343 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
345 HEREDOC_SKIPTABS = 1,
351 pid_t pid; /* 0 if exited */
352 int assignment_cnt; /* how many argv[i] are assignments? */
353 smallint is_stopped; /* is the command currently running? */
354 smallint grp_type; /* GRP_xxx */
355 struct pipe *group; /* if non-NULL, this "command" is { list },
356 * ( list ), or a compound statement */
358 char *group_as_string;
360 char **argv; /* command name and arguments */
361 struct redir_struct *redirects; /* I/O redirections */
363 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
364 * and on execution these are substituted with their values.
365 * Substitution can make _several_ words out of one argv[n]!
366 * Example: argv[0]=='.^C*^C.' here: echo .$*.
367 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
370 #define GRP_SUBSHELL 1
371 #if ENABLE_HUSH_FUNCTIONS
372 #define GRP_FUNCTION 2
377 int num_cmds; /* total number of commands in job */
378 int alive_cmds; /* number of commands running (not exited) */
379 int stopped_cmds; /* number of commands alive, but stopped */
381 int jobid; /* job number */
382 pid_t pgrp; /* process group ID for the job */
383 char *cmdtext; /* name of job */
385 struct command *cmds; /* array of commands in pipe */
386 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
387 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
388 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
390 typedef enum pipe_style {
397 /* This holds pointers to the various results of parsing */
398 struct parse_context {
399 /* linked list of pipes */
400 struct pipe *list_head;
401 /* last pipe (being constructed right now) */
403 /* last command in pipe (being constructed right now) */
404 struct command *command;
405 /* last redirect in command->redirects list */
406 struct redir_struct *pending_redirect;
412 smallint ctx_inverted; /* "! cmd | cmd" */
414 smallint ctx_dsemicolon; /* ";;" seen */
416 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
418 /* group we are enclosed in:
419 * example: "if pipe1; pipe2; then pipe3; fi"
420 * when we see "if" or "then", we malloc and copy current context,
421 * and make ->stack point to it. then we parse pipeN.
422 * when closing "then" / fi" / whatever is found,
423 * we move list_head into ->stack->command->group,
424 * copy ->stack into current context, and delete ->stack.
425 * (parsing of { list } and ( list ) doesn't use this method)
427 struct parse_context *stack;
431 /* On program start, environ points to initial environment.
432 * putenv adds new pointers into it, unsetenv removes them.
433 * Neither of these (de)allocates the strings.
434 * setenv allocates new strings in malloc space and does putenv,
435 * and thus setenv is unusable (leaky) for shell's purposes */
436 #define setenv(...) setenv_is_leaky_dont_use()
438 struct variable *next;
439 char *varstr; /* points to "name=" portion */
440 int max_len; /* if > 0, name is part of initial env; else name is malloced */
441 smallint flg_export; /* putenv should be done on this var */
442 smallint flg_read_only;
451 /* "Globals" within this file */
452 /* Sorted roughly by size (smaller offsets == smaller code) */
454 #if ENABLE_HUSH_INTERACTIVE
455 /* 'interactive_fd' is a fd# open to ctty, if we have one
456 * _AND_ if we decided to act interactively */
460 #define G_interactive_fd (G.interactive_fd)
462 #define G_interactive_fd 0
464 #if ENABLE_FEATURE_EDITING
465 line_input_t *line_input_state;
471 pid_t saved_tty_pgrp;
473 struct pipe *job_list;
474 struct pipe *toplevel_list;
475 //// smallint ctrl_z_flag;
477 smallint flag_SIGINT;
478 #if ENABLE_HUSH_LOOPS
479 smallint flag_break_continue;
482 smallint exiting; /* used to prevent EXIT trap recursion */
483 /* These four support $?, $#, and $1 */
484 smalluint last_exitcode;
485 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
486 smalluint global_args_malloced;
487 /* how many non-NULL argv's we have. NB: $# + 1 */
491 char *argv0_for_re_execing;
492 char **argv_from_re_execing;
494 #if ENABLE_HUSH_LOOPS
495 unsigned depth_break_continue;
496 unsigned depth_of_loop;
500 struct variable *top_var; /* = &G.shell_ver (set in main()) */
501 struct variable shell_ver;
502 /* Signal and trap handling */
503 // unsigned count_SIGCHLD;
504 // unsigned handled_SIGCHLD;
505 /* which signals have non-DFL handler (even with no traps set)? */
506 unsigned non_DFL_mask;
507 char **traps; /* char *traps[NSIG] */
508 sigset_t blocked_set;
509 sigset_t inherited_set;
511 unsigned long memleak_value;
513 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
514 #if ENABLE_FEATURE_SH_STANDALONE
515 struct nofork_save_area nofork_save;
518 sigjmp_buf toplevel_jb;
521 #define G (*ptr_to_globals)
522 /* Not #defining name to G.name - this quickly gets unwieldy
523 * (too many defines). Also, I actually prefer to see when a variable
524 * is global, thus "G." prefix is a useful hint */
525 #define INIT_G() do { \
526 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
530 /* Function prototypes for builtins */
531 static int builtin_cd(char **argv);
532 static int builtin_echo(char **argv);
533 static int builtin_eval(char **argv);
534 static int builtin_exec(char **argv);
535 static int builtin_exit(char **argv);
536 static int builtin_export(char **argv);
538 static int builtin_fg_bg(char **argv);
539 static int builtin_jobs(char **argv);
542 static int builtin_help(char **argv);
545 static int builtin_memleak(char **argv);
547 static int builtin_pwd(char **argv);
548 static int builtin_read(char **argv);
549 static int builtin_set(char **argv);
550 static int builtin_shift(char **argv);
551 static int builtin_source(char **argv);
552 static int builtin_test(char **argv);
553 static int builtin_trap(char **argv);
554 static int builtin_true(char **argv);
555 static int builtin_umask(char **argv);
556 static int builtin_unset(char **argv);
557 static int builtin_wait(char **argv);
558 #if ENABLE_HUSH_LOOPS
559 static int builtin_break(char **argv);
560 static int builtin_continue(char **argv);
563 /* Table of built-in functions. They can be forked or not, depending on
564 * context: within pipes, they fork. As simple commands, they do not.
565 * When used in non-forking context, they can change global variables
566 * in the parent shell process. If forked, of course they cannot.
567 * For example, 'unset foo | whatever' will parse and run, but foo will
568 * still be set at the end. */
569 struct built_in_command {
571 int (*function)(char **argv);
574 #define BLTIN(cmd, func, help) { cmd, func, help }
576 #define BLTIN(cmd, func, help) { cmd, func }
580 /* For now, echo and test are unconditionally enabled.
581 * Maybe make it configurable? */
582 static const struct built_in_command bltins[] = {
583 BLTIN("." , builtin_source , "Run commands in a file"),
584 BLTIN(":" , builtin_true , "No-op"),
585 BLTIN("[" , builtin_test , "Test condition"),
587 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
589 #if ENABLE_HUSH_LOOPS
590 BLTIN("break" , builtin_break , "Exit from a loop"),
592 BLTIN("cd" , builtin_cd , "Change directory"),
593 #if ENABLE_HUSH_LOOPS
594 BLTIN("continue", builtin_continue, "Start new loop iteration"),
596 BLTIN("echo" , builtin_echo , "Write to stdout"),
597 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
598 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
599 BLTIN("exit" , builtin_exit , "Exit"),
600 BLTIN("export" , builtin_export , "Set environment variable"),
602 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
605 BLTIN("help" , builtin_help , "List shell built-in commands"),
608 BLTIN("jobs" , builtin_jobs , "List active jobs"),
611 BLTIN("memleak" , builtin_memleak , "Debug tool"),
613 BLTIN("pwd" , builtin_pwd , "Print current directory"),
614 BLTIN("read" , builtin_read , "Input environment variable"),
615 // BLTIN("return" , builtin_return , "Return from a function"),
616 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
617 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
618 BLTIN("test" , builtin_test , "Test condition"),
619 BLTIN("trap" , builtin_trap , "Trap signals"),
620 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
621 BLTIN("umask" , builtin_umask , "Set file creation mask"),
622 BLTIN("unset" , builtin_unset , "Unset environment variable"),
623 BLTIN("wait" , builtin_wait , "Wait for process"),
627 /* Leak hunting. Use hush_leaktool.sh for post-processing.
630 static void *xxmalloc(int lineno, size_t size)
632 void *ptr = xmalloc((size + 0xff) & ~0xff);
633 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
636 static void *xxrealloc(int lineno, void *ptr, size_t size)
638 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
639 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
642 static char *xxstrdup(int lineno, const char *str)
644 char *ptr = xstrdup(str);
645 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
648 static void xxfree(void *ptr)
650 fdprintf(2, "free %p\n", ptr);
653 #define xmalloc(s) xxmalloc(__LINE__, s)
654 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
655 #define xstrdup(s) xxstrdup(__LINE__, s)
656 #define free(p) xxfree(p)
660 /* Syntax and runtime errors. They always abort scripts.
661 * In interactive use they usually discard unparsed and/or unexecuted commands
662 * and return to the prompt.
663 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
666 # define die_if_script(lineno, fmt, msg) die_if_script(fmt, msg)
667 # define syntax_error(lineno, msg) syntax_error(msg)
668 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
669 # define syntax_error_unterminated(lineno, ch) syntax_error_unterminated(ch)
672 static void die_if_script(unsigned lineno, const char *fmt, const char *msg)
674 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
675 #if ENABLE_HUSH_INTERACTIVE
676 if (G_interactive_fd)
680 bb_error_msg("hush.c:%u", lineno);
685 static void syntax_error(unsigned lineno, const char *msg)
688 die_if_script(lineno, "syntax error: %s", msg);
690 die_if_script(lineno, "syntax error", NULL);
693 static void syntax_error_at(unsigned lineno, const char *msg)
695 die_if_script(lineno, "syntax error at '%s'", msg);
698 static void syntax_error_unterminated(unsigned lineno, char ch)
703 die_if_script(lineno, "syntax error: unterminated %s", msg);
707 # undef die_if_script
709 # undef syntax_error_at
710 # undef syntax_error_unterminated
712 # define die_if_script(fmt, msg) die_if_script(__LINE__, fmt, msg)
713 # define syntax_error(msg) syntax_error(__LINE__, msg)
714 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
715 # define syntax_error_unterminated(ch) syntax_error_unterminated(__LINE__, ch)
721 static int glob_needed(const char *s)
726 if (*s == '*' || *s == '[' || *s == '?')
733 static int is_well_formed_var_name(const char *s, char terminator)
735 if (!s || !(isalpha(*s) || *s == '_'))
738 while (isalnum(*s) || *s == '_')
740 return *s == terminator;
743 /* Replace each \x with x in place, return ptr past NUL. */
744 static char *unbackslash(char *src)
750 if ((*dst++ = *src++) == '\0')
756 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
777 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
778 v[count1 + count2] = NULL;
781 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
785 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
787 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
788 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
791 #define add_strings_to_strings(strings, add, need_to_dup) \
792 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
795 static char **add_string_to_strings(char **strings, char *add)
800 return add_strings_to_strings(strings, v, /*dup:*/ 0);
803 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
805 char **ptr = add_string_to_strings(strings, add);
806 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
809 #define add_string_to_strings(strings, add) \
810 xx_add_string_to_strings(__LINE__, strings, add)
813 static void putenv_all(char **strings)
818 debug_printf_env("putenv '%s'\n", *strings);
823 static char **putenv_all_and_save_old(char **strings)
833 eq = strchr(*strings, '=');
836 v = getenv(*strings);
839 /* v points to VAL in VAR=VAL, go back to VAR */
840 v -= (eq - *strings) + 1;
841 old = add_string_to_strings(old, v);
850 static void free_strings_and_unsetenv(char **strings, int unset)
860 debug_printf_env("unsetenv '%s'\n", *v);
868 static void free_strings(char **strings)
870 free_strings_and_unsetenv(strings, 0);
874 /* Basic theory of signal handling in shell
875 * ========================================
876 * This does not describe what hush does, rather, it is current understanding
877 * what it _should_ do. If it doesn't, it's a bug.
878 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
880 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
881 * is finished or backgrounded. It is the same in interactive and
882 * non-interactive shells, and is the same regardless of whether
883 * a user trap handler is installed or a shell special one is in effect.
884 * ^C or ^Z from keyboard seem to execute "at once" because it usually
885 * backgrounds (i.e. stops) or kills all members of currently running
888 * Wait builtin in interruptible by signals for which user trap is set
889 * or by SIGINT in interactive shell.
891 * Trap handlers will execute even within trap handlers. (right?)
893 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
895 * If job control is off, backgrounded commands ("cmd &")
896 * have SIGINT, SIGQUIT set to SIG_IGN.
898 * Commands run in command substitution ("`cmd`")
899 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
901 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
902 * by the shell from its parent.
904 * Siganls which differ from SIG_DFL action
905 * (note: child (i.e., [v]forked) shell is not an interactive shell):
908 * SIGTERM (interactive): ignore
909 * SIGHUP (interactive):
910 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
911 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
912 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
913 * that all pipe members are stopped) (right?)
914 * SIGINT (interactive): wait for last pipe, ignore the rest
915 * of the command line, show prompt. NB: ^C does not send SIGINT
916 * to interactive shell while shell is waiting for a pipe,
917 * since shell is bg'ed (is not in foreground process group).
918 * (check/expand this)
919 * Example 1: this waits 5 sec, but does not execute ls:
920 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
921 * Example 2: this does not wait and does not execute ls:
922 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
923 * Example 3: this does not wait 5 sec, but executes ls:
924 * "sleep 5; ls -l" + press ^C
926 * (What happens to signals which are IGN on shell start?)
927 * (What happens with signal mask on shell start?)
929 * Implementation in hush
930 * ======================
931 * We use in-kernel pending signal mask to determine which signals were sent.
932 * We block all signals which we don't want to take action immediately,
933 * i.e. we block all signals which need to have special handling as described
934 * above, and all signals which have traps set.
935 * After each pipe execution, we extract any pending signals via sigtimedwait()
938 * unsigned non_DFL_mask: a mask of such "special" signals
939 * sigset_t blocked_set: current blocked signal set
942 * clear bit in blocked_set unless it is also in non_DFL_mask
943 * "trap 'cmd' SIGxxx":
944 * set bit in blocked_set (even if 'cmd' is '')
945 * after [v]fork, if we plan to be a shell:
946 * nothing for {} child shell (say, "true | { true; true; } | true")
947 * unset all traps if () shell.
948 * after [v]fork, if we plan to exec:
949 * POSIX says pending signal mask is cleared in child - no need to clear it.
950 * Restore blocked signal set to one inherited by shell just prior to exec.
952 * Note: as a result, we do not use signal handlers much. The only uses
953 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
954 * and to restore tty pgrp on signal-induced exit.
957 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
959 // G.count_SIGCHLD++;
962 static int check_and_run_traps(int sig)
964 static const struct timespec zero_timespec = { 0, 0 };
965 smalluint save_rcode;
971 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
976 if (G.traps && G.traps[sig]) {
977 if (G.traps[sig][0]) {
978 /* We have user-defined handler */
979 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
980 save_rcode = G.last_exitcode;
983 G.last_exitcode = save_rcode;
984 } /* else: "" trap, ignoring signal */
987 /* not a trap: special action */
990 // G.count_SIGCHLD++;
999 default: /* ignored: */
1000 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1009 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1010 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1011 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1012 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1014 /* Restores tty foreground process group, and exits.
1015 * May be called as signal handler for fatal signal
1016 * (will faithfully resend signal to itself, producing correct exit state)
1017 * or called directly with -EXITCODE.
1018 * We also call it if xfunc is exiting. */
1019 static void sigexit(int sig) NORETURN;
1020 static void sigexit(int sig)
1022 /* Disable all signals: job control, SIGPIPE, etc. */
1023 sigprocmask_allsigs(SIG_BLOCK);
1025 /* Careful: we can end up here after [v]fork. Do not restore
1026 * tty pgrp then, only top-level shell process does that */
1027 if (G_interactive_fd && getpid() == G.root_pid)
1028 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
1030 /* Not a signal, just exit */
1034 kill_myself_with_sig(sig); /* does not return */
1038 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1039 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1043 /* Restores tty foreground process group, and exits. */
1044 static void hush_exit(int exitcode) NORETURN;
1045 static void hush_exit(int exitcode)
1047 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1048 /* Prevent recursion:
1049 * trap "echo Hi; exit" EXIT; exit
1051 char *argv[] = { NULL, G.traps[0], NULL };
1059 fflush(NULL); /* flush all streams */
1060 sigexit(- (exitcode & 0xff));
1067 static const char *set_cwd(void)
1069 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1070 * we must not try to free(bb_msg_unknown) */
1071 if (G.cwd == bb_msg_unknown)
1073 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1075 G.cwd = bb_msg_unknown;
1080 /* Get/check local shell variables */
1081 static struct variable *get_local_var(const char *name)
1083 struct variable *cur;
1089 for (cur = G.top_var; cur; cur = cur->next) {
1090 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1096 static const char *get_local_var_value(const char *src)
1098 struct variable *var = get_local_var(src);
1100 return strchr(var->varstr, '=') + 1;
1104 /* str holds "NAME=VAL" and is expected to be malloced.
1105 * We take ownership of it.
1109 * -1: if NAME is set, leave export status alone
1110 * if NAME is not set, do not export
1111 * flg_read_only is set only when we handle -R var=val
1114 #define set_local_var(str, flg_export, flg_read_only) \
1115 set_local_var(str, flg_export)
1117 static int set_local_var(char *str, int flg_export, int flg_read_only)
1119 struct variable *cur;
1123 value = strchr(str, '=');
1124 if (!value) { /* not expected to ever happen? */
1129 name_len = value - str + 1; /* including '=' */
1130 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1132 if (strncmp(cur->varstr, str, name_len) != 0) {
1134 /* Bail out. Note that now cur points
1135 * to last var in linked list */
1141 /* We found an existing var with this name */
1143 if (cur->flg_read_only) {
1147 bb_error_msg("%s: readonly variable", str);
1151 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1152 unsetenv(str); /* just in case */
1154 if (strcmp(cur->varstr, str) == 0) {
1159 if (cur->max_len >= strlen(str)) {
1160 /* This one is from startup env, reuse space */
1161 strcpy(cur->varstr, str);
1164 /* max_len == 0 signifies "malloced" var, which we can
1165 * (and has to) free */
1169 goto set_str_and_exp;
1172 /* Not found - create next variable struct */
1173 cur->next = xzalloc(sizeof(*cur));
1179 cur->flg_read_only = flg_read_only;
1182 if (flg_export == 1)
1183 cur->flg_export = 1;
1184 if (cur->flg_export) {
1185 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1186 return putenv(cur->varstr);
1191 static int unset_local_var(const char *name)
1193 struct variable *cur;
1194 struct variable *prev = prev; /* for gcc */
1198 return EXIT_SUCCESS;
1199 name_len = strlen(name);
1202 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1203 if (cur->flg_read_only) {
1204 bb_error_msg("%s: readonly variable", name);
1205 return EXIT_FAILURE;
1207 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1208 * is ro, and we cannot reach this code on the 1st pass */
1209 prev->next = cur->next;
1210 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1211 bb_unsetenv(cur->varstr);
1215 return EXIT_SUCCESS;
1220 return EXIT_SUCCESS;
1223 #if ENABLE_SH_MATH_SUPPORT
1224 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1225 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1226 static char *endofname(const char *name)
1234 if (!is_in_name(*p))
1240 static void arith_set_local_var(const char *name, const char *val, int flags)
1242 /* arith code doesnt malloc space, so do it for it */
1243 char *var = xasprintf("%s=%s", name, val);
1244 set_local_var(var, flags, 0);
1252 static int static_get(struct in_str *i)
1261 static int static_peek(struct in_str *i)
1266 #if ENABLE_HUSH_INTERACTIVE
1268 static void cmdedit_set_initial_prompt(void)
1270 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1271 G.PS1 = getenv("PS1");
1278 static const char* setup_prompt_string(int promptmode)
1280 const char *prompt_str;
1281 debug_printf("setup_prompt_string %d ", promptmode);
1282 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1283 /* Set up the prompt */
1284 if (promptmode == 0) { /* PS1 */
1286 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1291 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1292 debug_printf("result '%s'\n", prompt_str);
1296 static void get_user_input(struct in_str *i)
1299 const char *prompt_str;
1301 prompt_str = setup_prompt_string(i->promptmode);
1302 #if ENABLE_FEATURE_EDITING
1303 /* Enable command line editing only while a command line
1304 * is actually being read */
1307 /* buglet: SIGINT will not make new prompt to appear _at once_,
1308 * only after <Enter>. (^C will work) */
1309 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1310 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1311 check_and_run_traps(0);
1312 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1313 i->eof_flag = (r < 0);
1314 if (i->eof_flag) { /* EOF/error detected */
1315 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1316 G.user_input_buf[1] = '\0';
1321 fputs(prompt_str, stdout);
1323 G.user_input_buf[0] = r = fgetc(i->file);
1324 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1325 //do we need check_and_run_traps(0)? (maybe only if stdin)
1326 } while (G.flag_SIGINT);
1327 i->eof_flag = (r == EOF);
1329 i->p = G.user_input_buf;
1332 #endif /* INTERACTIVE */
1334 /* This is the magic location that prints prompts
1335 * and gets data back from the user */
1336 static int file_get(struct in_str *i)
1340 /* If there is data waiting, eat it up */
1341 if (i->p && *i->p) {
1342 #if ENABLE_HUSH_INTERACTIVE
1346 if (i->eof_flag && !*i->p)
1348 /* note: ch is never NUL */
1350 /* need to double check i->file because we might be doing something
1351 * more complicated by now, like sourcing or substituting. */
1352 #if ENABLE_HUSH_INTERACTIVE
1353 if (G_interactive_fd && i->promptme && i->file == stdin) {
1356 } while (!*i->p); /* need non-empty line */
1357 i->promptmode = 1; /* PS2 */
1362 do ch = fgetc(i->file); while (ch == '\0');
1364 debug_printf("file_get: got '%c' %d\n", ch, ch);
1365 #if ENABLE_HUSH_INTERACTIVE
1372 /* All callers guarantee this routine will never
1373 * be used right after a newline, so prompting is not needed.
1375 static int file_peek(struct in_str *i)
1378 if (i->p && *i->p) {
1379 if (i->eof_flag && !i->p[1])
1382 /* note: ch is never NUL */
1384 do ch = fgetc(i->file); while (ch == '\0');
1385 i->eof_flag = (ch == EOF);
1386 i->peek_buf[0] = ch;
1387 i->peek_buf[1] = '\0';
1389 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1393 static void setup_file_in_str(struct in_str *i, FILE *f)
1395 i->peek = file_peek;
1397 #if ENABLE_HUSH_INTERACTIVE
1399 i->promptmode = 0; /* PS1 */
1405 static void setup_string_in_str(struct in_str *i, const char *s)
1407 i->peek = static_peek;
1408 i->get = static_get;
1409 #if ENABLE_HUSH_INTERACTIVE
1411 i->promptmode = 0; /* PS1 */
1421 #define B_CHUNK (32 * sizeof(char*))
1423 static void o_reset(o_string *o)
1431 static void o_free(o_string *o)
1434 memset(o, 0, sizeof(*o));
1437 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1442 static void o_grow_by(o_string *o, int len)
1444 if (o->length + len > o->maxlen) {
1445 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1446 o->data = xrealloc(o->data, 1 + o->maxlen);
1450 static void o_addchr(o_string *o, int ch)
1452 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1454 o->data[o->length] = ch;
1456 o->data[o->length] = '\0';
1459 static void o_addblock(o_string *o, const char *str, int len)
1462 memcpy(&o->data[o->length], str, len);
1464 o->data[o->length] = '\0';
1468 static void o_addstr(o_string *o, const char *str)
1470 o_addblock(o, str, strlen(str));
1472 static void nommu_addchr(o_string *o, int ch)
1478 #define nommu_addchr(o, str) ((void)0)
1481 static void o_addstr_with_NUL(o_string *o, const char *str)
1483 o_addblock(o, str, strlen(str) + 1);
1486 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1491 && (*str != '*' && *str != '?' && *str != '[')
1499 /* My analysis of quoting semantics tells me that state information
1500 * is associated with a destination, not a source.
1502 static void o_addqchr(o_string *o, int ch)
1505 char *found = strchr("*?[\\", ch);
1510 o->data[o->length] = '\\';
1513 o->data[o->length] = ch;
1515 o->data[o->length] = '\0';
1518 static void o_addQchr(o_string *o, int ch)
1521 if (o->o_escape && strchr("*?[\\", ch)) {
1523 o->data[o->length] = '\\';
1527 o->data[o->length] = ch;
1529 o->data[o->length] = '\0';
1532 static void o_addQstr(o_string *o, const char *str, int len)
1535 o_addblock(o, str, len);
1541 int ordinary_cnt = strcspn(str, "*?[\\");
1542 if (ordinary_cnt > len) /* paranoia */
1544 o_addblock(o, str, ordinary_cnt);
1545 if (ordinary_cnt == len)
1547 str += ordinary_cnt;
1548 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1552 if (ch) { /* it is necessarily one of "*?[\\" */
1554 o->data[o->length] = '\\';
1558 o->data[o->length] = ch;
1560 o->data[o->length] = '\0';
1564 /* A special kind of o_string for $VAR and `cmd` expansion.
1565 * It contains char* list[] at the beginning, which is grown in 16 element
1566 * increments. Actual string data starts at the next multiple of 16 * (char*).
1567 * list[i] contains an INDEX (int!) into this string data.
1568 * It means that if list[] needs to grow, data needs to be moved higher up
1569 * but list[i]'s need not be modified.
1570 * NB: remembering how many list[i]'s you have there is crucial.
1571 * o_finalize_list() operation post-processes this structure - calculates
1572 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1574 #if DEBUG_EXPAND || DEBUG_GLOB
1575 static void debug_print_list(const char *prefix, o_string *o, int n)
1577 char **list = (char**)o->data;
1578 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1580 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1581 prefix, list, n, string_start, o->length, o->maxlen);
1583 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1584 o->data + (int)list[i] + string_start,
1585 o->data + (int)list[i] + string_start);
1589 const char *p = o->data + (int)list[n - 1] + string_start;
1590 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1594 #define debug_print_list(prefix, o, n) ((void)0)
1597 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1598 * in list[n] so that it points past last stored byte so far.
1599 * It returns n+1. */
1600 static int o_save_ptr_helper(o_string *o, int n)
1602 char **list = (char**)o->data;
1606 if (!o->has_empty_slot) {
1607 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1608 string_len = o->length - string_start;
1609 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1610 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1611 /* list[n] points to string_start, make space for 16 more pointers */
1612 o->maxlen += 0x10 * sizeof(list[0]);
1613 o->data = xrealloc(o->data, o->maxlen + 1);
1614 list = (char**)o->data;
1615 memmove(list + n + 0x10, list + n, string_len);
1616 o->length += 0x10 * sizeof(list[0]);
1618 debug_printf_list("list[%d]=%d string_start=%d\n",
1619 n, string_len, string_start);
1622 /* We have empty slot at list[n], reuse without growth */
1623 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1624 string_len = o->length - string_start;
1625 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1626 n, string_len, string_start);
1627 o->has_empty_slot = 0;
1629 list[n] = (char*)(ptrdiff_t)string_len;
1633 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1634 static int o_get_last_ptr(o_string *o, int n)
1636 char **list = (char**)o->data;
1637 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1639 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1642 /* o_glob performs globbing on last list[], saving each result
1643 * as a new list[]. */
1644 static int o_glob(o_string *o, int n)
1650 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1652 return o_save_ptr_helper(o, n);
1653 pattern = o->data + o_get_last_ptr(o, n);
1654 debug_printf_glob("glob pattern '%s'\n", pattern);
1655 if (!glob_needed(pattern)) {
1657 o->length = unbackslash(pattern) - o->data;
1658 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1659 return o_save_ptr_helper(o, n);
1662 memset(&globdata, 0, sizeof(globdata));
1663 gr = glob(pattern, 0, NULL, &globdata);
1664 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1665 if (gr == GLOB_NOSPACE)
1666 bb_error_msg_and_die("out of memory during glob");
1667 if (gr == GLOB_NOMATCH) {
1668 globfree(&globdata);
1671 if (gr != 0) { /* GLOB_ABORTED ? */
1672 //TODO: testcase for bad glob pattern behavior
1673 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1675 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1676 char **argv = globdata.gl_pathv;
1677 o->length = pattern - o->data; /* "forget" pattern */
1679 o_addstr_with_NUL(o, *argv);
1680 n = o_save_ptr_helper(o, n);
1686 globfree(&globdata);
1688 debug_print_list("o_glob returning", o, n);
1692 /* If o->o_glob == 1, glob the string so far remembered.
1693 * Otherwise, just finish current list[] and start new */
1694 static int o_save_ptr(o_string *o, int n)
1696 if (o->o_glob) { /* if globbing is requested */
1697 /* If o->has_empty_slot, list[n] was already globbed
1698 * (if it was requested back then when it was filled)
1699 * so don't do that again! */
1700 if (!o->has_empty_slot)
1701 return o_glob(o, n); /* o_save_ptr_helper is inside */
1703 return o_save_ptr_helper(o, n);
1706 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1707 static char **o_finalize_list(o_string *o, int n)
1712 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1714 debug_print_list("finalized", o, n);
1715 debug_printf_expand("finalized n:%d\n", n);
1716 list = (char**)o->data;
1717 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1721 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1727 /* Expansion can recurse */
1728 #if ENABLE_HUSH_TICK
1729 static int process_command_subs(o_string *dest, const char *s);
1731 static char *expand_string_to_string(const char *str);
1733 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1734 parse_stream_dquoted(dest, input, dquote_end)
1736 static int parse_stream_dquoted(o_string *as_string,
1738 struct in_str *input,
1741 /* expand_strvec_to_strvec() takes a list of strings, expands
1742 * all variable references within and returns a pointer to
1743 * a list of expanded strings, possibly with larger number
1744 * of strings. (Think VAR="a b"; echo $VAR).
1745 * This new list is allocated as a single malloc block.
1746 * NULL-terminated list of char* pointers is at the beginning of it,
1747 * followed by strings themself.
1748 * Caller can deallocate entire list by single free(list). */
1750 /* Store given string, finalizing the word and starting new one whenever
1751 * we encounter IFS char(s). This is used for expanding variable values.
1752 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1753 static int expand_on_ifs(o_string *output, int n, const char *str)
1756 int word_len = strcspn(str, G.ifs);
1758 if (output->o_escape || !output->o_glob)
1759 o_addQstr(output, str, word_len);
1760 else /* protect backslashes against globbing up :) */
1761 o_addblock_duplicate_backslash(output, str, word_len);
1764 if (!*str) /* EOL - do not finalize word */
1766 o_addchr(output, '\0');
1767 debug_print_list("expand_on_ifs", output, n);
1768 n = o_save_ptr(output, n);
1769 str += strspn(str, G.ifs); /* skip ifs chars */
1771 debug_print_list("expand_on_ifs[1]", output, n);
1775 /* Helper to expand $((...)) and heredoc body. These act as if
1776 * they are in double quotes, with the exception that they are not :).
1777 * Just the rules are similar: "expand only $var and `cmd`"
1779 * Returns malloced string.
1780 * As an optimization, we return NULL if expansion is not needed.
1782 static char *expand_pseudo_dquoted(const char *str)
1785 struct in_str input;
1786 o_string dest = NULL_O_STRING;
1788 if (strchr(str, '$') == NULL
1789 #if ENABLE_HUSH_TICK
1790 && strchr(str, '`') == NULL
1796 /* We need to expand. Example:
1797 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1799 setup_string_in_str(&input, str);
1800 parse_stream_dquoted(NULL, &dest, &input, EOF);
1801 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1802 exp_str = expand_string_to_string(dest.data);
1803 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1804 o_free_unsafe(&dest);
1808 /* Expand all variable references in given string, adding words to list[]
1809 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1810 * to be filled). This routine is extremely tricky: has to deal with
1811 * variables/parameters with whitespace, $* and $@, and constructs like
1812 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1813 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1815 /* or_mask is either 0 (normal case) or 0x80
1816 * (expansion of right-hand side of assignment == 1-element expand.
1817 * It will also do no globbing, and thus we must not backslash-quote!) */
1819 char first_ch, ored_ch;
1827 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1828 debug_print_list("expand_vars_to_list", output, n);
1829 n = o_save_ptr(output, n);
1830 debug_print_list("expand_vars_to_list[0]", output, n);
1832 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1833 #if ENABLE_HUSH_TICK
1834 o_string subst_result = NULL_O_STRING;
1836 #if ENABLE_SH_MATH_SUPPORT
1837 char arith_buf[sizeof(arith_t)*3 + 2];
1839 o_addblock(output, arg, p - arg);
1840 debug_print_list("expand_vars_to_list[1]", output, n);
1842 p = strchr(p, SPECIAL_VAR_SYMBOL);
1844 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1845 /* "$@" is special. Even if quoted, it can still
1846 * expand to nothing (not even an empty string) */
1847 if ((first_ch & 0x7f) != '@')
1848 ored_ch |= first_ch;
1851 switch (first_ch & 0x7f) {
1852 /* Highest bit in first_ch indicates that var is double-quoted */
1854 val = utoa(G.root_pid);
1856 case '!': /* bg pid */
1857 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1859 case '?': /* exitcode */
1860 val = utoa(G.last_exitcode);
1862 case '#': /* argc */
1863 if (arg[1] != SPECIAL_VAR_SYMBOL)
1864 /* actually, it's a ${#var} */
1866 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1871 if (!G.global_argv[i])
1873 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1874 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1875 smallint sv = output->o_escape;
1876 /* unquoted var's contents should be globbed, so don't escape */
1877 output->o_escape = 0;
1878 while (G.global_argv[i]) {
1879 n = expand_on_ifs(output, n, G.global_argv[i]);
1880 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1881 if (G.global_argv[i++][0] && G.global_argv[i]) {
1882 /* this argv[] is not empty and not last:
1883 * put terminating NUL, start new word */
1884 o_addchr(output, '\0');
1885 debug_print_list("expand_vars_to_list[2]", output, n);
1886 n = o_save_ptr(output, n);
1887 debug_print_list("expand_vars_to_list[3]", output, n);
1890 output->o_escape = sv;
1892 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1893 * and in this case should treat it like '$*' - see 'else...' below */
1894 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1896 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1897 if (++i >= G.global_argc)
1899 o_addchr(output, '\0');
1900 debug_print_list("expand_vars_to_list[4]", output, n);
1901 n = o_save_ptr(output, n);
1903 } else { /* quoted $*: add as one word */
1905 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1906 if (!G.global_argv[++i])
1909 o_addchr(output, G.ifs[0]);
1913 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1914 /* "Empty variable", used to make "" etc to not disappear */
1918 #if ENABLE_HUSH_TICK
1919 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1922 //TODO: can we just stuff it into "output" directly?
1923 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1924 process_command_subs(&subst_result, arg);
1925 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1926 val = subst_result.data;
1929 #if ENABLE_SH_MATH_SUPPORT
1930 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1931 arith_eval_hooks_t hooks;
1936 arg++; /* skip '+' */
1937 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1938 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1940 exp_str = expand_pseudo_dquoted(arg);
1941 hooks.lookupvar = get_local_var_value;
1942 hooks.setvar = arith_set_local_var;
1943 hooks.endofname = endofname;
1944 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1948 const char *msg = "error in arithmetic";
1951 msg = "exponent less than 0";
1954 msg = "divide by 0";
1957 msg = "expression recursion loop detected";
1960 die_if_script(msg, NULL);
1962 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1963 sprintf(arith_buf, arith_t_fmt, res);
1968 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1970 bool exp_len = false;
1971 bool exp_null = false;
1973 char exp_save = exp_save; /* for compiler */
1974 char exp_op = exp_op; /* for compiler */
1975 char *exp_word = exp_word; /* for compiler */
1979 arg[0] = first_ch & 0x7f;
1981 /* prepare for expansions */
1982 if (var[0] == '#') {
1983 /* handle length expansion ${#var} */
1987 /* maybe handle parameter expansion */
1988 exp_off = strcspn(var, ":-=+?%#");
1992 exp_save = var[exp_off];
1993 exp_null = exp_save == ':';
1994 exp_word = var + exp_off;
1997 exp_op = *exp_word++;
1998 var[exp_off] = '\0';
2002 /* lookup the variable in question */
2003 if (isdigit(var[0])) {
2004 /* handle_dollar() should have vetted var for us */
2006 if (i < G.global_argc)
2007 val = G.global_argv[i];
2008 /* else val remains NULL: $N with too big N */
2010 val = get_local_var_value(var);
2012 /* handle any expansions */
2014 debug_printf_expand("expand: length of '%s' = ", val);
2015 val = utoa(val ? strlen(val) : 0);
2016 debug_printf_expand("%s\n", val);
2017 } else if (exp_off) {
2018 if (exp_op == '%' || exp_op == '#') {
2019 /* we need to do a pattern match */
2022 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
2023 if (exp_op == *exp_word) /* ## or %% */
2025 val = dyn_val = xstrdup(val);
2026 loc = scan(dyn_val, exp_word, zero);
2032 /* we need to do an expansion */
2033 int exp_test = (!val || (exp_null && !val[0]));
2035 exp_test = !exp_test;
2036 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2037 exp_null ? "true" : "false", exp_test);
2040 //TODO: what does interactive bash
2041 /* ${var?[error_msg_if_unset]} */
2042 /* ${var:?[error_msg_if_unset_or_null]} */
2043 /* mimic bash message */
2045 char *msg = xasprintf("%s: %s", var, exp_word);
2046 die_if_script("%s", msg);
2049 die_if_script("%s: parameter null or not set", var);
2054 if (exp_op == '=') {
2055 /* ${var=[word]} or ${var:=[word]} */
2056 if (isdigit(var[0]) || var[0] == '#') {
2057 /* mimic bash message */
2058 die_if_script("$%s: cannot assign in this way", var);
2061 char *new_var = xasprintf("%s=%s", var, val);
2062 set_local_var(new_var, -1, 0);
2068 var[exp_off] = exp_save;
2072 #if ENABLE_HUSH_TICK
2075 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2076 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2078 /* unquoted var's contents should be globbed, so don't escape */
2079 smallint sv = output->o_escape;
2080 output->o_escape = 0;
2081 n = expand_on_ifs(output, n, val);
2083 output->o_escape = sv;
2085 } else { /* quoted $VAR, val will be appended below */
2086 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2089 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2091 o_addQstr(output, val, strlen(val));
2095 /* Do the check to avoid writing to a const string */
2096 if (*p != SPECIAL_VAR_SYMBOL)
2097 *p = SPECIAL_VAR_SYMBOL;
2099 #if ENABLE_HUSH_TICK
2100 o_free(&subst_result);
2103 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2106 debug_print_list("expand_vars_to_list[a]", output, n);
2107 /* this part is literal, and it was already pre-quoted
2108 * if needed (much earlier), do not use o_addQstr here! */
2109 o_addstr_with_NUL(output, arg);
2110 debug_print_list("expand_vars_to_list[b]", output, n);
2111 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2112 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2115 /* allow to reuse list[n] later without re-growth */
2116 output->has_empty_slot = 1;
2118 o_addchr(output, '\0');
2123 static char **expand_variables(char **argv, int or_mask)
2128 o_string output = NULL_O_STRING;
2130 if (or_mask & 0x100) {
2131 output.o_escape = 1; /* protect against globbing for "$var" */
2132 /* (unquoted $var will temporarily switch it off) */
2139 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2142 debug_print_list("expand_variables", &output, n);
2144 /* output.data (malloced in one block) gets returned in "list" */
2145 list = o_finalize_list(&output, n);
2146 debug_print_strings("expand_variables[1]", list);
2150 static char **expand_strvec_to_strvec(char **argv)
2152 return expand_variables(argv, 0x100);
2155 /* Used for expansion of right hand of assignments */
2156 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2158 static char *expand_string_to_string(const char *str)
2160 char *argv[2], **list;
2162 argv[0] = (char*)str;
2164 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2166 if (!list[0] || list[1])
2167 bb_error_msg_and_die("BUG in varexp2");
2168 /* actually, just move string 2*sizeof(char*) bytes back */
2169 overlapping_strcpy((char*)list, list[0]);
2170 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2174 /* Used for "eval" builtin */
2175 static char* expand_strvec_to_string(char **argv)
2179 list = expand_variables(argv, 0x80);
2180 /* Convert all NULs to spaces */
2185 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2186 bb_error_msg_and_die("BUG in varexp3");
2187 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2191 overlapping_strcpy((char*)list, list[0]);
2192 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2196 static char **expand_assignments(char **argv, int count)
2200 /* Expand assignments into one string each */
2201 for (i = 0; i < count; i++) {
2202 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2209 void re_execute_shell(const char *s, int is_heredoc); /* never called */
2210 #define clean_up_after_re_execute() ((void)0)
2211 static void reset_traps_to_defaults(void)
2219 for (sig = 0; sig < NSIG; sig++) {
2223 G.traps[sig] = NULL;
2224 /* There is no signal for 0 (EXIT) */
2227 /* there was a trap handler, we are removing it
2228 * (if sig has non-DFL handling,
2229 * we don't need to do anything) */
2230 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2232 sigdelset(&G.blocked_set, sig);
2236 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2241 static void re_execute_shell(const char *s, int is_heredoc) NORETURN;
2242 static void re_execute_shell(const char *s, int is_heredoc)
2244 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2245 char *heredoc_argv[4];
2246 struct variable *cur;
2247 char **argv, **pp, **pp2;
2251 argv = heredoc_argv;
2252 argv[0] = (char *) G.argv0_for_re_execing;
2253 argv[1] = (char *) "-<";
2254 argv[2] = (char *) s;
2256 pp = &argv[3]; /* used as pointer to empty environment */
2260 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2261 , (unsigned) G.root_pid
2262 , (unsigned) G.last_bg_pid
2263 , (unsigned) G.last_exitcode
2264 USE_HUSH_LOOPS(, G.depth_of_loop)
2266 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2267 * 3:-c 4:<cmd> <argN...> 5:NULL
2269 cnt = 5 + G.global_argc;
2270 for (cur = G.top_var; cur; cur = cur->next) {
2271 if (!cur->flg_export || cur->flg_read_only)
2274 G.argv_from_re_execing = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2275 *pp++ = (char *) G.argv0_for_re_execing;
2277 for (cur = G.top_var; cur; cur = cur->next) {
2278 if (cur->varstr == hush_version_str)
2280 if (cur->flg_read_only) {
2281 *pp++ = (char *) "-R";
2282 *pp++ = cur->varstr;
2283 } else if (!cur->flg_export) {
2284 *pp++ = (char *) "-V";
2285 *pp++ = cur->varstr;
2288 //TODO: pass functions
2289 /* We can pass activated traps here. Say, -Tnn:trap_string
2291 * However, POSIX says that subshells reset signals with traps
2293 * I tested bash-3.2 and it not only does that with true subshells
2294 * of the form ( list ), but with any forked children shells.
2295 * I set trap "echo W" WINCH; and then tried:
2297 * { echo 1; sleep 20; echo 2; } &
2298 * while true; do echo 1; sleep 20; echo 2; break; done &
2299 * true | { echo 1; sleep 20; echo 2; } | cat
2301 * In all these cases sending SIGWINCH to the child shell
2302 * did not run the trap. If I add trap "echo V" WINCH;
2303 * _inside_ group (just before echo 1), it works.
2305 * I conclude it means we don't need to pass active traps here.
2306 * exec syscall below resets them to SIG_DFL for us.
2308 *pp++ = (char *) "-c";
2310 pp2 = G.global_argv;
2313 /* *pp = NULL; - is already there */
2317 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2318 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2319 execve(bb_busybox_exec_path, argv, pp);
2320 /* Fallback. Useful for init=/bin/hush usage etc */
2321 if (argv[0][0] == '/')
2322 execve(argv[0], argv, pp);
2323 xfunc_error_retval = 127;
2324 bb_error_msg_and_die("can't re-execute the shell");
2327 static void clean_up_after_re_execute(void)
2329 char **pp = G.argv_from_re_execing;
2331 /* Must match re_execute_shell's allocations (if any) */
2333 G.argv_from_re_execing = NULL;
2336 #endif /* !BB_MMU */
2339 static void setup_heredoc(struct redir_struct *redir)
2341 struct fd_pair pair;
2344 /* the _body_ of heredoc (misleading field name) */
2345 const char *heredoc = redir->rd_filename;
2349 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2350 expanded = expand_pseudo_dquoted(heredoc);
2354 len = strlen(heredoc);
2356 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2358 xmove_fd(pair.rd, redir->rd_fd);
2360 /* Try writing without forking. Newer kernels have
2361 * dynamically growing pipes. Must use non-blocking write! */
2364 written = write(pair.wr, heredoc, len);
2375 ndelay_off(pair.wr);
2377 /* Okay, pipe buffer was not big enough */
2378 /* Note: we must not create a stray child (bastard? :)
2379 * for the unsuspecting parent process. Child creates a grandchild
2380 * and exits before parent execs the process which consumes heredoc
2381 * (that exec happens after we return from this function) */
2384 bb_perror_msg_and_die("vfork");
2387 pid = BB_MMU ? fork() : vfork();
2389 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2393 close(redir->rd_fd); /* read side of the pipe */
2395 full_write(pair.wr, heredoc, len); /* may loop or block */
2398 /* Delegate blocking writes to another process */
2399 disable_restore_tty_pgrp_on_exit();
2400 xmove_fd(pair.wr, STDOUT_FILENO);
2401 re_execute_shell(heredoc, 1);
2405 enable_restore_tty_pgrp_on_exit();
2406 clean_up_after_re_execute();
2409 wait(NULL); /* wait till child has died */
2412 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2413 * and stderr if they are redirected. */
2414 static int setup_redirects(struct command *prog, int squirrel[])
2417 struct redir_struct *redir;
2419 for (redir = prog->redirects; redir; redir = redir->next) {
2420 if (redir->rd_type == REDIRECT_HEREDOC2) {
2421 if (squirrel && redir->rd_fd < 3) {
2422 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2424 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2426 debug_printf_parse("set heredoc '%s'\n",
2427 redir->rd_filename);
2428 setup_heredoc(redir);
2432 if (redir->rd_dup == -1) {
2434 if (redir->rd_filename == NULL) {
2435 /* Something went wrong in the parse.
2436 * Pretend it didn't happen */
2439 mode = redir_table[redir->rd_type].mode;
2440 //TODO: check redir for names like '\\'
2441 p = expand_string_to_string(redir->rd_filename);
2442 openfd = open_or_warn(p, mode);
2445 /* this could get lost if stderr has been redirected, but
2446 * bash and ash both lose it as well (though zsh doesn't!) */
2447 //what the above comment tries to say?
2451 openfd = redir->rd_dup;
2454 if (openfd != redir->rd_fd) {
2455 if (squirrel && redir->rd_fd < 3) {
2456 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2458 if (openfd == REDIRFD_CLOSE) {
2459 /* "n>-" means "close me" */
2460 close(redir->rd_fd);
2462 xdup2(openfd, redir->rd_fd);
2463 if (redir->rd_dup == -1)
2471 static void restore_redirects(int squirrel[])
2474 for (i = 0; i < 3; i++) {
2477 /* We simply die on error */
2485 #define free_pipe_list(head, indent) free_pipe_list(head)
2486 #define free_pipe(pi, indent) free_pipe(pi)
2488 static void free_pipe_list(struct pipe *head, int indent);
2490 /* Return code is the exit status of the pipe */
2491 static void free_pipe(struct pipe *pi, int indent)
2494 struct command *command;
2495 struct redir_struct *r, *rnext;
2498 if (pi->stopped_cmds > 0) /* why? */
2500 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2501 for (i = 0; i < pi->num_cmds; i++) {
2502 command = &pi->cmds[i];
2503 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2504 if (command->argv) {
2505 for (a = 0, p = command->argv; *p; a++, p++) {
2506 debug_printf_clean("%s argv[%d] = %s\n",
2507 indenter(indent), a, *p);
2509 free_strings(command->argv);
2510 command->argv = NULL;
2512 /* not "else if": on syntax error, we may have both! */
2513 if (command->group) {
2514 debug_printf_clean("%s begin group (grp_type:%d)\n",
2515 indenter(indent), command->grp_type);
2516 free_pipe_list(command->group, indent+3);
2517 debug_printf_clean("%s end group\n", indenter(indent));
2518 command->group = NULL;
2521 free(command->group_as_string);
2522 command->group_as_string = NULL;
2524 for (r = command->redirects; r; r = rnext) {
2525 debug_printf_clean("%s redirect %d%s", indenter(indent),
2526 r->fd, redir_table[r->rd_type].descrip);
2527 /* guard against the case >$FOO, where foo is unset or blank */
2528 if (r->rd_filename) {
2529 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2530 free(r->rd_filename);
2531 r->rd_filename = NULL;
2533 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2537 command->redirects = NULL;
2539 free(pi->cmds); /* children are an array, they get freed all at once */
2547 static void free_pipe_list(struct pipe *head, int indent)
2549 struct pipe *pi, *next;
2551 for (pi = head; pi; pi = next) {
2553 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2555 free_pipe(pi, indent);
2556 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2558 /*pi->next = NULL;*/
2565 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2566 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2567 #define pseudo_exec(nommu_save, command, argv_expanded) \
2568 pseudo_exec(command, argv_expanded)
2571 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2573 * XXX no exit() here. If you don't exec, use _exit instead.
2574 * The at_exit handlers apparently confuse the calling process,
2575 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2576 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2577 char **argv, int assignment_cnt,
2578 char **argv_expanded) NORETURN;
2579 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2580 char **argv, int assignment_cnt,
2581 char **argv_expanded)
2585 /* Case when we are here: ... | var=val | ... */
2586 if (!argv[assignment_cnt])
2587 _exit(EXIT_SUCCESS);
2589 new_env = expand_assignments(argv, assignment_cnt);
2591 putenv_all(new_env);
2592 free(new_env); /* optional */
2594 nommu_save->new_env = new_env;
2595 nommu_save->old_env = putenv_all_and_save_old(new_env);
2597 if (argv_expanded) {
2598 argv = argv_expanded;
2600 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2602 nommu_save->argv = argv;
2606 /* On NOMMU, we must never block!
2607 * Example: { sleep 99999 | read line } & echo Ok
2608 * read builtin will block on read syscall, leaving parent blocked
2609 * in vfork. Therefore we can't do this:
2612 /* Check if the command matches any of the builtins.
2613 * Depending on context, this might be redundant. But it's
2614 * easier to waste a few CPU cycles than it is to figure out
2615 * if this is one of those cases.
2619 const struct built_in_command *x;
2620 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2621 if (strcmp(argv[0], x->cmd) == 0) {
2622 debug_printf_exec("running builtin '%s'\n",
2624 rcode = x->function(argv);
2632 #if ENABLE_FEATURE_SH_STANDALONE
2633 /* Check if the command matches any busybox applets */
2634 if (strchr(argv[0], '/') == NULL) {
2635 int a = find_applet_by_name(argv[0]);
2637 #if BB_MMU /* see above why on NOMMU it is not allowed */
2638 if (APPLET_IS_NOEXEC(a)) {
2639 debug_printf_exec("running applet '%s'\n", argv[0]);
2640 run_applet_no_and_exit(a, argv);
2643 /* Re-exec ourselves */
2644 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2645 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2646 execv(bb_busybox_exec_path, argv);
2647 /* If they called chroot or otherwise made the binary no longer
2648 * executable, fall through */
2653 debug_printf_exec("execing '%s'\n", argv[0]);
2654 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2655 execvp(argv[0], argv);
2656 bb_perror_msg("can't exec '%s'", argv[0]);
2657 _exit(EXIT_FAILURE);
2660 static int run_list(struct pipe *pi);
2662 /* Called after [v]fork() in run_pipe
2664 static void pseudo_exec(nommu_save_t *nommu_save,
2665 struct command *command,
2666 char **argv_expanded) NORETURN;
2667 static void pseudo_exec(nommu_save_t *nommu_save,
2668 struct command *command,
2669 char **argv_expanded)
2671 if (command->argv) {
2672 pseudo_exec_argv(nommu_save, command->argv,
2673 command->assignment_cnt, argv_expanded);
2676 if (command->group) {
2677 /* Cases when we are here:
2680 * ... | ( list ) | ...
2681 * ... | { list } | ...
2685 debug_printf_exec("pseudo_exec: run_list\n");
2686 reset_traps_to_defaults();
2687 rcode = run_list(command->group);
2688 /* OK to leak memory by not calling free_pipe_list,
2689 * since this process is about to exit */
2692 re_execute_shell(command->group_as_string, 0);
2696 /* Case when we are here: ... | >file */
2697 debug_printf_exec("pseudo_exec'ed null command\n");
2698 _exit(EXIT_SUCCESS);
2702 static const char *get_cmdtext(struct pipe *pi)
2708 /* This is subtle. ->cmdtext is created only on first backgrounding.
2709 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2710 * On subsequent bg argv is trashed, but we won't use it */
2713 argv = pi->cmds[0].argv;
2714 if (!argv || !argv[0]) {
2715 pi->cmdtext = xzalloc(1);
2720 do len += strlen(*argv) + 1; while (*++argv);
2721 pi->cmdtext = p = xmalloc(len);
2722 argv = pi->cmds[0].argv;
2724 len = strlen(*argv);
2725 memcpy(p, *argv, len);
2733 static void insert_bg_job(struct pipe *pi)
2735 struct pipe *thejob;
2738 /* Linear search for the ID of the job to use */
2740 for (thejob = G.job_list; thejob; thejob = thejob->next)
2741 if (thejob->jobid >= pi->jobid)
2742 pi->jobid = thejob->jobid + 1;
2744 /* Add thejob to the list of running jobs */
2746 thejob = G.job_list = xmalloc(sizeof(*thejob));
2748 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2750 thejob->next = xmalloc(sizeof(*thejob));
2751 thejob = thejob->next;
2754 /* Physically copy the struct job */
2755 memcpy(thejob, pi, sizeof(struct pipe));
2756 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2757 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2758 for (i = 0; i < pi->num_cmds; i++) {
2759 // TODO: do we really need to have so many fields which are just dead weight
2760 // at execution stage?
2761 thejob->cmds[i].pid = pi->cmds[i].pid;
2762 /* all other fields are not used and stay zero */
2764 thejob->next = NULL;
2765 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2767 /* We don't wait for background thejobs to return -- append it
2768 to the list of backgrounded thejobs and leave it alone */
2769 if (G_interactive_fd)
2770 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2771 G.last_bg_pid = thejob->cmds[0].pid;
2772 G.last_jobid = thejob->jobid;
2775 static void remove_bg_job(struct pipe *pi)
2777 struct pipe *prev_pipe;
2779 if (pi == G.job_list) {
2780 G.job_list = pi->next;
2782 prev_pipe = G.job_list;
2783 while (prev_pipe->next != pi)
2784 prev_pipe = prev_pipe->next;
2785 prev_pipe->next = pi->next;
2788 G.last_jobid = G.job_list->jobid;
2793 /* Remove a backgrounded job */
2794 static void delete_finished_bg_job(struct pipe *pi)
2797 pi->stopped_cmds = 0;
2803 /* Check to see if any processes have exited -- if they
2804 * have, figure out why and see if a job has completed */
2805 static int checkjobs(struct pipe* fg_pipe)
2815 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2818 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2819 // /* avoid doing syscall, nothing there anyway */
2822 attributes = WUNTRACED;
2823 if (fg_pipe == NULL)
2824 attributes |= WNOHANG;
2826 /* Do we do this right?
2827 * bash-3.00# sleep 20 | false
2829 * [3]+ Stopped sleep 20 | false
2830 * bash-3.00# echo $?
2831 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2834 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2835 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2836 // + killall -STOP cat
2843 // i = G.count_SIGCHLD;
2844 childpid = waitpid(-1, &status, attributes);
2845 if (childpid <= 0) {
2846 if (childpid && errno != ECHILD)
2847 bb_perror_msg("waitpid");
2848 // else /* Until next SIGCHLD, waitpid's are useless */
2849 // G.handled_SIGCHLD = i;
2852 dead = WIFEXITED(status) || WIFSIGNALED(status);
2855 if (WIFSTOPPED(status))
2856 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2857 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2858 if (WIFSIGNALED(status))
2859 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2860 childpid, WTERMSIG(status), WEXITSTATUS(status));
2861 if (WIFEXITED(status))
2862 debug_printf_jobs("pid %d exited, exitcode %d\n",
2863 childpid, WEXITSTATUS(status));
2865 /* Were we asked to wait for fg pipe? */
2867 for (i = 0; i < fg_pipe->num_cmds; i++) {
2868 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2869 if (fg_pipe->cmds[i].pid != childpid)
2871 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2873 fg_pipe->cmds[i].pid = 0;
2874 fg_pipe->alive_cmds--;
2875 if (i == fg_pipe->num_cmds - 1) {
2876 /* last process gives overall exitstatus */
2877 rcode = WEXITSTATUS(status);
2878 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2881 fg_pipe->cmds[i].is_stopped = 1;
2882 fg_pipe->stopped_cmds++;
2884 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2885 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2886 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2887 /* All processes in fg pipe have exited/stopped */
2889 if (fg_pipe->alive_cmds)
2890 insert_bg_job(fg_pipe);
2894 /* There are still running processes in the fg pipe */
2895 goto wait_more; /* do waitpid again */
2897 /* it wasnt fg_pipe, look for process in bg pipes */
2901 /* We asked to wait for bg or orphaned children */
2902 /* No need to remember exitcode in this case */
2903 for (pi = G.job_list; pi; pi = pi->next) {
2904 for (i = 0; i < pi->num_cmds; i++) {
2905 if (pi->cmds[i].pid == childpid)
2906 goto found_pi_and_prognum;
2909 /* Happens when shell is used as init process (init=/bin/sh) */
2910 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2911 continue; /* do waitpid again */
2913 found_pi_and_prognum:
2916 pi->cmds[i].pid = 0;
2918 if (!pi->alive_cmds) {
2919 if (G_interactive_fd)
2920 printf(JOB_STATUS_FORMAT, pi->jobid,
2921 "Done", pi->cmdtext);
2922 delete_finished_bg_job(pi);
2926 pi->cmds[i].is_stopped = 1;
2930 } /* while (waitpid succeeds)... */
2936 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2939 int rcode = checkjobs(fg_pipe);
2940 /* Job finished, move the shell to the foreground */
2941 p = getpgid(0); /* pgid of our process */
2942 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2943 tcsetpgrp(G_interactive_fd, p);
2948 /* Start all the jobs, but don't wait for anything to finish.
2951 * Return code is normally -1, when the caller has to wait for children
2952 * to finish to determine the exit status of the pipe. If the pipe
2953 * is a simple builtin command, however, the action is done by the
2954 * time run_pipe returns, and the exit code is provided as the
2957 * Returns -1 only if started some children. IOW: we have to
2958 * mask out retvals of builtins etc with 0xff!
2960 * The only case when we do not need to [v]fork is when the pipe
2961 * is single, non-backgrounded, non-subshell command. Examples:
2962 * cmd ; ... { list } ; ...
2963 * cmd && ... { list } && ...
2964 * cmd || ... { list } || ...
2965 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2966 * or (if SH_STANDALONE) an applet, and we can run the { list }
2967 * with run_list(). If it isn't one of these, we fork and exec cmd.
2969 * Cases when we must fork:
2970 * non-single: cmd | cmd
2971 * backgrounded: cmd & { list } &
2972 * subshell: ( list ) [&]
2974 static int run_pipe(struct pipe *pi)
2976 static const char *const null_ptr = NULL;
2979 int pipefds[2]; /* pipefds[0] is for reading */
2980 struct command *command;
2981 char **argv_expanded;
2984 /* it is not always needed, but we aim to smaller code */
2985 int squirrel[] = { -1, -1, -1 };
2988 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2990 USE_HUSH_JOB(pi->pgrp = -1;)
2991 pi->stopped_cmds = 0;
2992 command = &(pi->cmds[0]);
2993 argv_expanded = NULL;
2995 if (pi->num_cmds != 1
2996 || pi->followup == PIPE_BG
2997 || command->grp_type == GRP_SUBSHELL
3004 debug_printf_exec(": group:%p argv:'%s'\n",
3005 command->group, command->argv ? command->argv[0] : "NONE");
3007 if (command->group) {
3008 #if ENABLE_HUSH_FUNCTIONS
3009 if (command->grp_type == GRP_FUNCTION) {
3010 /* func () { list } */
3011 bb_error_msg("here we ought to remember function definition, and go on");
3012 return EXIT_SUCCESS;
3016 debug_printf("non-subshell group\n");
3017 rcode = 1; /* exitcode if redir failed */
3018 if (setup_redirects(command, squirrel) == 0) {
3019 debug_printf_exec(": run_list\n");
3020 rcode = run_list(command->group) & 0xff;
3021 debug_printf_exec("run_pipe return %d\n", rcode);
3023 restore_redirects(squirrel);
3024 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3028 argv = command->argv ? command->argv : (char **) &null_ptr;
3030 const struct built_in_command *x;
3031 char **new_env = NULL;
3032 char **old_env = NULL;
3034 if (argv[command->assignment_cnt] == NULL) {
3035 /* Assignments, but no command */
3036 /* Ensure redirects take effect. Try "a=t >file" */
3037 rcode = setup_redirects(command, squirrel);
3038 restore_redirects(squirrel);
3039 /* Set shell variables */
3041 p = expand_string_to_string(*argv);
3042 debug_printf_exec("set shell var:'%s'->'%s'\n",
3044 set_local_var(p, 0, 0);
3047 /* Do we need to flag set_local_var() errors?
3048 * "assignment to readonly var" and "putenv error"
3050 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3054 /* Expand the rest into (possibly) many strings each */
3055 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3057 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
3058 if (strcmp(argv_expanded[0], x->cmd) != 0)
3060 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3061 debug_printf("exec with redirects only\n");
3062 rcode = setup_redirects(command, NULL);
3063 goto clean_up_and_ret1;
3065 debug_printf("builtin inline %s\n", argv_expanded[0]);
3066 /* XXX setup_redirects acts on file descriptors, not FILEs.
3067 * This is perfect for work that comes after exec().
3068 * Is it really safe for inline use? Experimentally,
3069 * things seem to work with glibc. */
3070 rcode = setup_redirects(command, squirrel);
3072 new_env = expand_assignments(argv, command->assignment_cnt);
3073 old_env = putenv_all_and_save_old(new_env);
3074 debug_printf_exec(": builtin '%s' '%s'...\n",
3075 x->cmd, argv_expanded[1]);
3076 rcode = x->function(argv_expanded) & 0xff;
3078 #if ENABLE_FEATURE_SH_STANDALONE
3081 restore_redirects(squirrel);
3082 free_strings_and_unsetenv(new_env, 1);
3083 putenv_all(old_env);
3084 /* Free the pointers, but the strings themselves
3085 * are in environ now, don't use free_strings! */
3088 free(argv_expanded);
3089 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3090 debug_printf_exec("run_pipe return %d\n", rcode);
3093 #if ENABLE_FEATURE_SH_STANDALONE
3094 i = find_applet_by_name(argv_expanded[0]);
3095 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3096 rcode = setup_redirects(command, squirrel);
3098 save_nofork_data(&G.nofork_save);
3099 new_env = expand_assignments(argv, command->assignment_cnt);
3100 old_env = putenv_all_and_save_old(new_env);
3101 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3102 argv_expanded[0], argv_expanded[1]);
3103 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
3105 goto clean_up_and_ret;
3108 /* It is neither builtin nor applet. We must fork. */
3112 /* NB: argv_expanded may already be created, and that
3113 * might include `cmd` runs! Do not rerun it! We *must*
3114 * use argv_expanded if it's non-NULL */
3116 /* Going to fork a child per each pipe member */
3120 for (i = 0; i < pi->num_cmds; i++) {
3122 volatile nommu_save_t nommu_save;
3123 nommu_save.new_env = NULL;
3124 nommu_save.old_env = NULL;
3125 nommu_save.argv = NULL;
3127 command = &(pi->cmds[i]);
3128 if (command->argv) {
3129 debug_printf_exec(": pipe member '%s' '%s'...\n",
3130 command->argv[0], command->argv[1]);
3132 debug_printf_exec(": pipe member with no argv\n");
3135 /* pipes are inserted between pairs of commands */
3138 if ((i + 1) < pi->num_cmds)
3141 command->pid = BB_MMU ? fork() : vfork();
3142 if (!command->pid) { /* child */
3144 disable_restore_tty_pgrp_on_exit();
3146 /* Every child adds itself to new process group
3147 * with pgid == pid_of_first_child_in_pipe */
3148 if (G.run_list_level == 1 && G_interactive_fd) {
3151 if (pgrp < 0) /* true for 1st process only */
3153 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
3154 /* We do it in *every* child, not just first,
3156 tcsetpgrp(G_interactive_fd, pgrp);
3160 xmove_fd(nextin, 0);
3161 xmove_fd(pipefds[1], 1); /* write end */
3163 close(pipefds[0]); /* read end */
3164 /* Like bash, explicit redirects override pipes,
3165 * and the pipe fd is available for dup'ing. */
3166 if (setup_redirects(command, NULL))
3169 /* Restore default handlers just prior to exec */
3170 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3172 /* Stores to nommu_save list of env vars putenv'ed
3173 * (NOMMU, on MMU we don't need that) */
3174 /* cast away volatility... */
3175 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3176 /* pseudo_exec() does not return */
3179 /* parent or error */
3180 enable_restore_tty_pgrp_on_exit();
3182 /* Clean up after vforked child */
3183 clean_up_after_re_execute();
3184 free(nommu_save.argv);
3185 free_strings_and_unsetenv(nommu_save.new_env, 1);
3186 putenv_all(nommu_save.old_env);
3187 /* Free the pointers, but the strings themselves
3188 * are in environ now, don't use free_strings! */
3189 free(nommu_save.old_env);
3191 free(argv_expanded);
3192 argv_expanded = NULL;
3193 if (command->pid < 0) { /* [v]fork failed */
3194 /* Clearly indicate, was it fork or vfork */
3195 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3199 /* Second and next children need to know pid of first one */
3201 pi->pgrp = command->pid;
3207 if ((i + 1) < pi->num_cmds)
3208 close(pipefds[1]); /* write end */
3209 /* Pass read (output) pipe end to next iteration */
3210 nextin = pipefds[0];
3213 if (!pi->alive_cmds) {
3214 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3218 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3222 #ifndef debug_print_tree
3223 static void debug_print_tree(struct pipe *pi, int lvl)
3225 static const char *const PIPE[] = {
3231 static const char *RES[] = {
3232 [RES_NONE ] = "NONE" ,
3235 [RES_THEN ] = "THEN" ,
3236 [RES_ELIF ] = "ELIF" ,
3237 [RES_ELSE ] = "ELSE" ,
3240 #if ENABLE_HUSH_LOOPS
3241 [RES_FOR ] = "FOR" ,
3242 [RES_WHILE] = "WHILE",
3243 [RES_UNTIL] = "UNTIL",
3245 [RES_DONE ] = "DONE" ,
3247 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3250 #if ENABLE_HUSH_CASE
3251 [RES_CASE ] = "CASE" ,
3252 [RES_MATCH] = "MATCH",
3253 [RES_CASEI] = "CASEI",
3254 [RES_ESAC ] = "ESAC" ,
3256 [RES_XXXX ] = "XXXX" ,
3257 [RES_SNTX ] = "SNTX" ,
3259 static const char *const GRPTYPE[] = {
3262 #if ENABLE_HUSH_FUNCTIONS
3271 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3272 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3274 while (prn < pi->num_cmds) {
3275 struct command *command = &pi->cmds[prn];
3276 char **argv = command->argv;
3278 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3280 command->assignment_cnt);
3281 if (command->group) {
3282 fprintf(stderr, " group %s: (argv=%p)\n",
3283 GRPTYPE[command->grp_type],
3285 debug_print_tree(command->group, lvl+1);
3289 if (argv) while (*argv) {
3290 fprintf(stderr, " '%s'", *argv);
3293 fprintf(stderr, "\n");
3302 /* NB: called by pseudo_exec, and therefore must not modify any
3303 * global data until exec/_exit (we can be a child after vfork!) */
3304 static int run_list(struct pipe *pi)
3306 #if ENABLE_HUSH_CASE
3307 char *case_word = NULL;
3309 #if ENABLE_HUSH_LOOPS
3310 struct pipe *loop_top = NULL;
3311 char *for_varname = NULL;
3312 char **for_lcur = NULL;
3313 char **for_list = NULL;
3315 smallint last_followup;
3317 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3318 smalluint cond_code = 0;
3320 enum { cond_code = 0 };
3323 smallint rword; /* enum reserved_style */
3324 smallint last_rword; /* ditto */
3327 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3329 #if ENABLE_HUSH_LOOPS
3330 /* Check syntax for "for" */
3331 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3332 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3334 /* current word is FOR or IN (BOLD in comments below) */
3335 if (cpipe->next == NULL) {
3336 syntax_error("malformed for");
3337 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3340 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3341 if (cpipe->next->res_word == RES_DO)
3343 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3344 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3345 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3347 syntax_error("malformed for");
3348 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3354 /* Past this point, all code paths should jump to ret: label
3355 * in order to return, no direct "return" statements please.
3356 * This helps to ensure that no memory is leaked. */
3358 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3361 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3362 * We are saving state before entering outermost list ("while...done")
3363 * so that ctrl-Z will correctly background _entire_ outermost list,
3364 * not just a part of it (like "sleep 1 | exit 2") */
3365 if (++G.run_list_level == 1 && G_interactive_fd) {
3366 if (sigsetjmp(G.toplevel_jb, 1)) {
3367 /* ctrl-Z forked and we are parent; or ctrl-C.
3368 * Sighandler has longjmped us here */
3369 signal(SIGINT, SIG_IGN);
3370 signal(SIGTSTP, SIG_IGN);
3371 /* Restore level (we can be coming from deep inside
3373 G.run_list_level = 1;
3374 #if ENABLE_FEATURE_SH_STANDALONE
3375 if (G.nofork_save.saved) { /* if save area is valid */
3376 debug_printf_jobs("exiting nofork early\n");
3377 restore_nofork_data(&G.nofork_save);
3380 //// if (G.ctrl_z_flag) {
3381 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3382 //// * Remember this child as background job */
3383 //// insert_bg_job(pi);
3385 /* ctrl-C. We just stop doing whatever we were doing */
3388 USE_HUSH_LOOPS(loop_top = NULL;)
3389 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3393 //// /* ctrl-Z handler will store pid etc in pi */
3394 //// G.toplevel_list = pi;
3395 //// G.ctrl_z_flag = 0;
3396 #if ENABLE_FEATURE_SH_STANDALONE
3397 G.nofork_save.saved = 0; /* in case we will run a nofork later */
3399 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3400 //// signal(SIGINT, handler_ctrl_c);
3406 last_rword = RES_XXXX;
3408 last_followup = PIPE_SEQ;
3409 rcode = G.last_exitcode;
3411 /* Go through list of pipes, (maybe) executing them. */
3412 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3416 IF_HAS_KEYWORDS(rword = pi->res_word;)
3417 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3418 rword, cond_code, last_rword);
3419 #if ENABLE_HUSH_LOOPS
3420 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3421 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3423 /* start of a loop: remember where loop starts */
3428 /* Still in the same "if...", "then..." or "do..." branch? */
3429 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3430 if ((rcode == 0 && last_followup == PIPE_OR)
3431 || (rcode != 0 && last_followup == PIPE_AND)
3433 /* It is "<true> || CMD" or "<false> && CMD"
3434 * and we should not execute CMD */
3435 debug_printf_exec("skipped cmd because of || or &&\n");
3436 last_followup = pi->followup;
3440 last_followup = pi->followup;
3441 IF_HAS_KEYWORDS(last_rword = rword;)
3444 if (rword == RES_THEN) {
3445 /* if false; then ... fi has exitcode 0! */
3446 G.last_exitcode = rcode = EXIT_SUCCESS;
3447 /* "if <false> THEN cmd": skip cmd */
3451 if (rword == RES_ELSE || rword == RES_ELIF) {
3452 /* "if <true> then ... ELSE/ELIF cmd":
3453 * skip cmd and all following ones */
3458 #if ENABLE_HUSH_LOOPS
3459 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3461 /* first loop through for */
3463 static const char encoded_dollar_at[] ALIGN1 = {
3464 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3465 }; /* encoded representation of "$@" */
3466 static const char *const encoded_dollar_at_argv[] = {
3467 encoded_dollar_at, NULL
3468 }; /* argv list with one element: "$@" */
3471 vals = (char**)encoded_dollar_at_argv;
3472 if (pi->next->res_word == RES_IN) {
3473 /* if no variable values after "in" we skip "for" */
3474 if (!pi->next->cmds[0].argv) {
3475 G.last_exitcode = rcode = EXIT_SUCCESS;
3476 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3479 vals = pi->next->cmds[0].argv;
3480 } /* else: "for var; do..." -> assume "$@" list */
3481 /* create list of variable values */
3482 debug_print_strings("for_list made from", vals);
3483 for_list = expand_strvec_to_strvec(vals);
3484 for_lcur = for_list;
3485 debug_print_strings("for_list", for_list);
3486 for_varname = pi->cmds[0].argv[0];
3487 pi->cmds[0].argv[0] = NULL;
3489 free(pi->cmds[0].argv[0]);
3491 /* "for" loop is over, clean up */
3495 pi->cmds[0].argv[0] = for_varname;
3498 /* Insert next value from for_lcur */
3499 /* note: *for_lcur already has quotes removed, $var expanded, etc */
3500 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3501 pi->cmds[0].assignment_cnt = 1;
3503 if (rword == RES_IN) {
3504 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3506 if (rword == RES_DONE) {
3507 continue; /* "done" has no cmds too */
3510 #if ENABLE_HUSH_CASE
3511 if (rword == RES_CASE) {
3512 case_word = expand_strvec_to_string(pi->cmds->argv);
3515 if (rword == RES_MATCH) {
3518 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3520 /* all prev words didn't match, does this one match? */
3521 argv = pi->cmds->argv;
3523 char *pattern = expand_string_to_string(*argv);
3524 /* TODO: which FNM_xxx flags to use? */
3525 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3527 if (cond_code == 0) { /* match! we will execute this branch */
3528 free(case_word); /* make future "word)" stop */
3536 if (rword == RES_CASEI) { /* inside of a case branch */
3538 continue; /* not matched yet, skip this pipe */
3541 /* Just pressing <enter> in shell should check for jobs.
3542 * OTOH, in non-interactive shell this is useless
3543 * and only leads to extra job checks */
3544 if (pi->num_cmds == 0) {
3545 if (G_interactive_fd)
3546 goto check_jobs_and_continue;
3550 /* After analyzing all keywords and conditions, we decided
3551 * to execute this pipe. NB: have to do checkjobs(NULL)
3552 * after run_pipe to collect any background children,
3553 * even if list execution is to be stopped. */
3554 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3557 #if ENABLE_HUSH_LOOPS
3558 G.flag_break_continue = 0;
3560 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3562 /* We only ran a builtin: rcode is already known
3563 * and we don't need to wait for anything. */
3564 G.last_exitcode = rcode;
3565 debug_printf_exec(": builtin exitcode %d\n", rcode);
3566 check_and_run_traps(0);
3567 #if ENABLE_HUSH_LOOPS
3568 /* Was it "break" or "continue"? */
3569 if (G.flag_break_continue) {
3570 smallint fbc = G.flag_break_continue;
3571 /* We might fall into outer *loop*,
3572 * don't want to break it too */
3574 G.depth_break_continue--;
3575 if (G.depth_break_continue == 0)
3576 G.flag_break_continue = 0;
3577 /* else: e.g. "continue 2" should *break* once, *then* continue */
3578 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3579 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3580 goto check_jobs_and_break;
3581 /* "continue": simulate end of loop */
3586 } else if (pi->followup == PIPE_BG) {
3587 /* What does bash do with attempts to background builtins? */
3588 /* even bash 3.2 doesn't do that well with nested bg:
3589 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3590 * I'm NOT treating inner &'s as jobs */
3591 check_and_run_traps(0);
3593 if (G.run_list_level == 1)
3596 G.last_exitcode = rcode = EXIT_SUCCESS;
3597 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3600 if (G.run_list_level == 1 && G_interactive_fd) {
3601 /* Waits for completion, then fg's main shell */
3602 rcode = checkjobs_and_fg_shell(pi);
3603 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3604 check_and_run_traps(0);
3607 { /* This one just waits for completion */
3608 rcode = checkjobs(pi);
3609 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3610 check_and_run_traps(0);
3612 G.last_exitcode = rcode;
3616 /* Analyze how result affects subsequent commands */
3618 if (rword == RES_IF || rword == RES_ELIF)
3621 #if ENABLE_HUSH_LOOPS
3622 /* Beware of "while false; true; do ..."! */
3623 if (pi->next && pi->next->res_word == RES_DO) {
3624 if (rword == RES_WHILE) {
3626 /* "while false; do...done" - exitcode 0 */
3627 G.last_exitcode = rcode = EXIT_SUCCESS;
3628 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3629 goto check_jobs_and_break;
3632 if (rword == RES_UNTIL) {
3634 debug_printf_exec(": until expr is true: breaking\n");
3635 check_jobs_and_break:
3643 check_jobs_and_continue:
3648 //// if (G.ctrl_z_flag) {
3649 //// /* ctrl-Z forked somewhere in the past, we are the child,
3650 //// * and now we completed running the list. Exit. */
3656 //// if (!G.run_list_level && G_interactive_fd) {
3657 //// signal(SIGTSTP, SIG_IGN);
3658 //// signal(SIGINT, SIG_IGN);
3661 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3662 #if ENABLE_HUSH_LOOPS
3667 #if ENABLE_HUSH_CASE
3673 /* Select which version we will use */
3674 static int run_and_free_list(struct pipe *pi)
3677 debug_printf_exec("run_and_free_list entered\n");
3679 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3680 rcode = run_list(pi);
3682 /* free_pipe_list has the side effect of clearing memory.
3683 * In the long run that function can be merged with run_list,
3684 * but doing that now would hobble the debugging effort. */
3685 free_pipe_list(pi, /* indent: */ 0);
3686 debug_printf_exec("run_and_free_list return %d\n", rcode);
3691 static struct pipe *new_pipe(void)
3694 pi = xzalloc(sizeof(struct pipe));
3695 /*pi->followup = 0; - deliberately invalid value */
3696 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3700 /* Command (member of a pipe) is complete. The only possible error here
3701 * is out of memory, in which case xmalloc exits. */
3702 static int done_command(struct parse_context *ctx)
3704 /* The command is really already in the pipe structure, so
3705 * advance the pipe counter and make a new, null command. */
3706 struct pipe *pi = ctx->pipe;
3707 struct command *command = ctx->command;
3710 if (command->group == NULL
3711 && command->argv == NULL
3712 && command->redirects == NULL
3714 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3715 memset(command, 0, sizeof(*command)); /* paranoia */
3716 return pi->num_cmds;
3719 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3720 //debug_print_tree(ctx->list_head, 20);
3722 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3725 /* Only real trickiness here is that the uncommitted
3726 * command structure is not counted in pi->num_cmds. */
3727 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3728 command = &pi->cmds[pi->num_cmds];
3729 memset(command, 0, sizeof(*command));
3731 ctx->command = command;
3732 /* but ctx->pipe and ctx->list_head remain unchanged */
3734 return pi->num_cmds; /* used only for 0/nonzero check */
3737 static void done_pipe(struct parse_context *ctx, pipe_style type)
3741 debug_printf_parse("done_pipe entered, followup %d\n", type);
3742 /* Close previous command */
3743 not_null = done_command(ctx);
3744 ctx->pipe->followup = type;
3746 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3747 ctx->ctx_inverted = 0;
3748 ctx->pipe->res_word = ctx->ctx_res_w;
3751 /* Without this check, even just <enter> on command line generates
3752 * tree of three NOPs (!). Which is harmless but annoying.
3753 * IOW: it is safe to do it unconditionally.
3754 * RES_NONE case is for "for a in; do ..." (empty IN set)
3755 * and other cases to work. */
3758 || ctx->ctx_res_w == RES_FI
3759 || ctx->ctx_res_w == RES_DONE
3760 || ctx->ctx_res_w == RES_FOR
3761 || ctx->ctx_res_w == RES_IN
3762 || ctx->ctx_res_w == RES_ESAC
3766 debug_printf_parse("done_pipe: adding new pipe: "
3767 "not_null:%d ctx->ctx_res_w:%d\n",
3768 not_null, ctx->ctx_res_w);
3770 ctx->pipe->next = new_p;
3772 /* RES_THEN, RES_DO etc are "sticky" -
3773 * they remain set for commands inside if/while.
3774 * This is used to control execution.
3775 * RES_FOR and RES_IN are NOT sticky (needed to support
3776 * cases where variable or value happens to match a keyword):
3778 #if ENABLE_HUSH_LOOPS
3779 if (ctx->ctx_res_w == RES_FOR
3780 || ctx->ctx_res_w == RES_IN)
3781 ctx->ctx_res_w = RES_NONE;
3783 #if ENABLE_HUSH_CASE
3784 if (ctx->ctx_res_w == RES_MATCH)
3785 ctx->ctx_res_w = RES_CASEI;
3787 ctx->command = NULL; /* trick done_command below */
3788 /* Create the memory for command, roughly:
3789 * ctx->pipe->cmds = new struct command;
3790 * ctx->command = &ctx->pipe->cmds[0];
3793 //debug_print_tree(ctx->list_head, 10);
3795 debug_printf_parse("done_pipe return\n");
3798 static void initialize_context(struct parse_context *ctx)
3800 memset(ctx, 0, sizeof(*ctx));
3801 ctx->pipe = ctx->list_head = new_pipe();
3802 /* Create the memory for command, roughly:
3803 * ctx->pipe->cmds = new struct command;
3804 * ctx->command = &ctx->pipe->cmds[0];
3809 /* If a reserved word is found and processed, parse context is modified
3810 * and 1 is returned.
3813 struct reserved_combo {
3816 unsigned char assignment_flag;
3820 FLAG_END = (1 << RES_NONE ),
3822 FLAG_IF = (1 << RES_IF ),
3823 FLAG_THEN = (1 << RES_THEN ),
3824 FLAG_ELIF = (1 << RES_ELIF ),
3825 FLAG_ELSE = (1 << RES_ELSE ),
3826 FLAG_FI = (1 << RES_FI ),
3828 #if ENABLE_HUSH_LOOPS
3829 FLAG_FOR = (1 << RES_FOR ),
3830 FLAG_WHILE = (1 << RES_WHILE),
3831 FLAG_UNTIL = (1 << RES_UNTIL),
3832 FLAG_DO = (1 << RES_DO ),
3833 FLAG_DONE = (1 << RES_DONE ),
3834 FLAG_IN = (1 << RES_IN ),
3836 #if ENABLE_HUSH_CASE
3837 FLAG_MATCH = (1 << RES_MATCH),
3838 FLAG_ESAC = (1 << RES_ESAC ),
3840 FLAG_START = (1 << RES_XXXX ),
3843 static const struct reserved_combo* match_reserved_word(o_string *word)
3845 /* Mostly a list of accepted follow-up reserved words.
3846 * FLAG_END means we are done with the sequence, and are ready
3847 * to turn the compound list into a command.
3848 * FLAG_START means the word must start a new compound list.
3850 static const struct reserved_combo reserved_list[] = {
3852 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3853 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3854 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3855 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3856 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3857 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3859 #if ENABLE_HUSH_LOOPS
3860 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3861 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3862 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3863 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3864 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3865 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3867 #if ENABLE_HUSH_CASE
3868 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3869 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3872 const struct reserved_combo *r;
3874 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3875 if (strcmp(word->data, r->literal) == 0)
3880 static int reserved_word(o_string *word, struct parse_context *ctx)
3882 #if ENABLE_HUSH_CASE
3883 static const struct reserved_combo reserved_match = {
3884 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3887 const struct reserved_combo *r;
3889 r = match_reserved_word(word);
3893 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3894 #if ENABLE_HUSH_CASE
3895 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3896 /* "case word IN ..." - IN part starts first match part */
3897 r = &reserved_match;
3900 if (r->flag == 0) { /* '!' */
3901 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3902 syntax_error("! ! command");
3903 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3905 ctx->ctx_inverted = 1;
3908 if (r->flag & FLAG_START) {
3909 struct parse_context *old;
3910 old = xmalloc(sizeof(*old));
3911 debug_printf_parse("push stack %p\n", old);
3912 *old = *ctx; /* physical copy */
3913 initialize_context(ctx);
3915 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3916 syntax_error_at(word->data);
3917 ctx->ctx_res_w = RES_SNTX;
3920 ctx->ctx_res_w = r->res;
3921 ctx->old_flag = r->flag;
3922 if (ctx->old_flag & FLAG_END) {
3923 struct parse_context *old;
3924 done_pipe(ctx, PIPE_SEQ);
3925 debug_printf_parse("pop stack %p\n", ctx->stack);
3927 old->command->group = ctx->list_head;
3928 old->command->grp_type = GRP_NORMAL;
3930 o_addstr(&old->as_string, ctx->as_string.data);
3931 o_free_unsafe(&ctx->as_string);
3932 old->command->group_as_string = xstrdup(old->as_string.data);
3933 debug_printf_parse("pop, remembering as:'%s'\n",
3934 old->command->group_as_string);
3936 *ctx = *old; /* physical copy */
3939 word->o_assignment = r->assignment_flag;
3944 /* Word is complete, look at it and update parsing context.
3945 * Normal return is 0. Syntax errors return 1.
3946 * Note: on return, word is reset, but not o_free'd!
3948 static int done_word(o_string *word, struct parse_context *ctx)
3950 struct command *command = ctx->command;
3952 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3953 if (word->length == 0 && word->o_quoted == 0) {
3954 debug_printf_parse("done_word return 0: true null, ignored\n");
3957 /* If this word wasn't an assignment, next ones definitely
3958 * can't be assignments. Even if they look like ones. */
3959 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3960 && word->o_assignment != WORD_IS_KEYWORD
3962 word->o_assignment = NOT_ASSIGNMENT;
3964 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3965 command->assignment_cnt++;
3966 word->o_assignment = MAYBE_ASSIGNMENT;
3969 if (ctx->pending_redirect) {
3970 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3971 * only if run as "bash", not "sh" */
3972 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3974 * ...the word that follows the redirection operator
3975 * shall be subjected to tilde expansion, parameter expansion,
3976 * command substitution, arithmetic expansion, and quote
3977 * removal. Pathname expansion shall not be performed
3978 * on the word by a non-interactive shell; an interactive
3979 * shell may perform it, but shall do so only when
3980 * the expansion would result in one word."
3982 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3983 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
3986 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3988 word->o_assignment = NOT_ASSIGNMENT;
3989 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3991 /* "{ echo foo; } echo bar" - bad */
3992 /* NB: bash allows e.g.:
3993 * if true; then { echo foo; } fi
3994 * while if false; then false; fi do break; done
3996 * while if false; then false; fi; do; break; done
3998 if (command->group) {
3999 syntax_error_at(word->data);
4000 debug_printf_parse("done_word return 1: syntax error, "
4001 "groups and arglists don't mix\n");
4005 #if ENABLE_HUSH_CASE
4006 if (ctx->ctx_dsemicolon
4007 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4009 /* already done when ctx_dsemicolon was set to 1: */
4010 /* ctx->ctx_res_w = RES_MATCH; */
4011 ctx->ctx_dsemicolon = 0;
4014 if (!command->argv /* if it's the first word... */
4015 #if ENABLE_HUSH_LOOPS
4016 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4017 && ctx->ctx_res_w != RES_IN
4020 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
4021 if (reserved_word(word, ctx)) {
4023 debug_printf_parse("done_word return %d\n",
4024 (ctx->ctx_res_w == RES_SNTX));
4025 return (ctx->ctx_res_w == RES_SNTX);
4029 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4030 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4031 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4032 /* (otherwise it's known to be not empty and is already safe) */
4034 /* exclude "$@" - it can expand to no word despite "" */
4035 char *p = word->data;
4036 while (p[0] == SPECIAL_VAR_SYMBOL
4037 && (p[1] & 0x7f) == '@'
4038 && p[2] == SPECIAL_VAR_SYMBOL
4042 if (p == word->data || p[0] != '\0') {
4043 /* saw no "$@", or not only "$@" but some
4044 * real text is there too */
4045 /* insert "empty variable" reference, this makes
4046 * e.g. "", $empty"" etc to not disappear */
4047 o_addchr(word, SPECIAL_VAR_SYMBOL);
4048 o_addchr(word, SPECIAL_VAR_SYMBOL);
4051 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4052 debug_print_strings("word appended to argv", command->argv);
4056 ctx->pending_redirect = NULL;
4058 #if ENABLE_HUSH_LOOPS
4059 /* Force FOR to have just one word (variable name) */
4060 /* NB: basically, this makes hush see "for v in ..." syntax as if
4061 * as it is "for v; in ...". FOR and IN become two pipe structs
4063 if (ctx->ctx_res_w == RES_FOR) {
4064 if (!is_well_formed_var_name(command->argv[0], '\0')) {
4065 syntax_error("malformed variable name in for");
4068 done_pipe(ctx, PIPE_SEQ);
4071 #if ENABLE_HUSH_CASE
4072 /* Force CASE to have just one word */
4073 if (ctx->ctx_res_w == RES_CASE) {
4074 done_pipe(ctx, PIPE_SEQ);
4077 debug_printf_parse("done_word return 0\n");
4082 /* Peek ahead in the input to find out if we have a "&n" construct,
4083 * as in "2>&1", that represents duplicating a file descriptor.
4084 * Return: REDIRFD_CLOSE (-3) if >&- "close fd" construct is seen,
4085 * -2 (syntax error), -1 if no & was seen, or the number found.
4088 #define redirect_dup_num(as_string, input) \
4089 redirect_dup_num(input)
4091 static int redirect_dup_num(o_string *as_string, struct in_str *input)
4099 ch = i_getch(input); /* get the & */
4100 nommu_addchr(as_string, ch);
4103 ch = i_getch(input);
4104 nommu_addchr(as_string, ch);
4105 return REDIRFD_CLOSE;
4109 while (ch != EOF && isdigit(ch)) {
4110 d = d*10 + (ch-'0');
4112 ch = i_getch(input);
4113 nommu_addchr(as_string, ch);
4118 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4120 bb_error_msg("ambiguous redirect");
4124 /* Return code is 0 normally, 1 if a syntax error is detected
4126 static int parse_redirect(struct parse_context *ctx,
4129 struct in_str *input)
4131 struct command *command = ctx->command;
4132 struct redir_struct *redir;
4133 struct redir_struct **redirp;
4137 if (style != REDIRECT_HEREDOC) {
4138 /* Check for a '2>&1' type redirect */
4139 dup_num = redirect_dup_num(&ctx->as_string, input);
4141 return 1; /* syntax error */
4143 int ch = i_peek(input);
4144 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4145 if (dup_num) { /* <<-... */
4146 ch = i_getch(input);
4147 nommu_addchr(&ctx->as_string, ch);
4152 if (style == REDIRECT_OVERWRITE && dup_num == -1) {
4153 int ch = i_peek(input);
4155 /* >|FILE redirect ("clobbering" >).
4156 * Since we do not support "set -o noclobber" yet,
4157 * >| and > are the same for now. Just eat |.
4159 ch = i_getch(input);
4160 nommu_addchr(&ctx->as_string, ch);
4164 /* Create a new redir_struct and append it to the linked list */
4165 redirp = &command->redirects;
4166 while ((redir = *redirp) != NULL) {
4167 redirp = &(redir->next);
4169 *redirp = redir = xzalloc(sizeof(*redir));
4170 /* redir->next = NULL; */
4171 /* redir->rd_filename = NULL; */
4172 redir->rd_type = style;
4173 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4175 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4176 redir_table[style].descrip);
4178 redir->rd_dup = dup_num;
4179 if (style != REDIRECT_HEREDOC && dup_num != -1) {
4180 /* Erik had a check here that the file descriptor in question
4181 * is legit; I postpone that to "run time"
4182 * A "-" representation of "close me" shows up as a -3 here */
4183 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4184 redir->rd_fd, redir->rd_dup);
4186 /* Set ctx->pending_redirect, so we know what to do at the
4187 * end of the next parsed word. */
4188 ctx->pending_redirect = redir;
4193 /* If a redirect is immediately preceded by a number, that number is
4194 * supposed to tell which file descriptor to redirect. This routine
4195 * looks for such preceding numbers. In an ideal world this routine
4196 * needs to handle all the following classes of redirects...
4197 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4198 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4199 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4200 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4202 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4204 * ... If n is quoted, the number shall not be recognized as part of
4205 * the redirection expression. For example:
4207 * writes the character 2 into file a"
4208 * We are getting it right by setting ->o_quoted on any \<char>
4210 * A -1 return means no valid number was found,
4211 * the caller should use the appropriate default for this redirection.
4213 static int redirect_opt_num(o_string *o)
4217 if (o->data == NULL)
4219 num = bb_strtou(o->data, NULL, 10);
4220 if (errno || num < 0)
4227 #define fetch_till_str(as_string, input, word, skip_tabs) \
4228 fetch_till_str(input, word, skip_tabs)
4230 static char *fetch_till_str(o_string *as_string,
4231 struct in_str *input,
4235 o_string heredoc = NULL_O_STRING;
4241 ch = i_getch(input);
4242 nommu_addchr(as_string, ch);
4244 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4245 heredoc.data[past_EOL] = '\0';
4246 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4247 return heredoc.data;
4250 o_addchr(&heredoc, ch);
4251 past_EOL = heredoc.length;
4254 ch = i_getch(input);
4255 nommu_addchr(as_string, ch);
4256 } while (skip_tabs && ch == '\t');
4257 } while (ch == '\n');
4260 o_free_unsafe(&heredoc);
4263 o_addchr(&heredoc, ch);
4264 nommu_addchr(as_string, ch);
4268 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4269 * and load them all. There should be exactly heredoc_cnt of them.
4271 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4273 struct pipe *pi = ctx->list_head;
4275 while (pi && heredoc_cnt) {
4277 struct command *cmd = pi->cmds;
4279 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4281 cmd->argv ? cmd->argv[0] : "NONE");
4282 for (i = 0; i < pi->num_cmds; i++) {
4283 struct redir_struct *redir = cmd->redirects;
4285 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4286 i, cmd->argv ? cmd->argv[0] : "NONE");
4288 if (redir->rd_type == REDIRECT_HEREDOC) {
4291 redir->rd_type = REDIRECT_HEREDOC2;
4292 /* redir->dup is (ab)used to indicate <<- */
4293 p = fetch_till_str(&ctx->as_string, input,
4294 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4296 syntax_error("unexpected EOF in here document");
4299 free(redir->rd_filename);
4300 redir->rd_filename = p;
4303 redir = redir->next;
4310 /* Should be 0. If it isn't, it's a parse error */
4312 bb_error_msg_and_die("heredoc BUG 2");
4319 #define parse_stream(pstring, input, end_trigger) \
4320 parse_stream(input, end_trigger)
4322 static struct pipe *parse_stream(char **pstring,
4323 struct in_str *input,
4325 static void parse_and_run_string(const char *s);
4327 #if ENABLE_HUSH_TICK
4328 static FILE *generate_stream_from_string(const char *s)
4331 int pid, channel[2];
4334 pid = BB_MMU ? fork() : vfork();
4336 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4338 if (pid == 0) { /* child */
4339 disable_restore_tty_pgrp_on_exit();
4340 /* Process substitution is not considered to be usual
4341 * 'command execution'.
4342 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4349 close(channel[0]); /* NB: close _first_, then move fd! */
4350 xmove_fd(channel[1], 1);
4351 /* Prevent it from trying to handle ctrl-z etc */
4352 USE_HUSH_JOB(G.run_list_level = 1;)
4354 reset_traps_to_defaults();
4355 parse_and_run_string(s);
4356 _exit(G.last_exitcode);
4358 /* We re-execute after vfork on NOMMU. This makes this script safe:
4359 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4360 * huge=`cat BIG` # was blocking here forever
4363 re_execute_shell(s, 0);
4368 enable_restore_tty_pgrp_on_exit();
4369 clean_up_after_re_execute();
4371 pf = fdopen(channel[0], "r");
4375 /* Return code is exit status of the process that is run. */
4376 static int process_command_subs(o_string *dest, const char *s)
4379 struct in_str pipe_str;
4382 pf = generate_stream_from_string(s);
4385 close_on_exec_on(fileno(pf));
4387 /* Now send results of command back into original context */
4388 setup_file_in_str(&pipe_str, pf);
4390 while ((ch = i_getch(&pipe_str)) != EOF) {
4396 o_addchr(dest, '\n');
4399 o_addQchr(dest, ch);
4402 debug_printf("done reading from pipe, pclose()ing\n");
4403 /* Note: we got EOF, and we just close the read end of the pipe.
4404 * We do not wait for the `cmd` child to terminate. bash and ash do.
4406 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4407 * `false`; echo $? - bash outputs "1"
4410 debug_printf("closed FILE from child. return 0\n");
4415 static int parse_group(o_string *dest, struct parse_context *ctx,
4416 struct in_str *input, int ch)
4418 /* dest contains characters seen prior to ( or {.
4419 * Typically it's empty, but for function defs,
4420 * it contains function name (without '()'). */
4421 struct pipe *pipe_list;
4423 struct command *command = ctx->command;
4425 debug_printf_parse("parse_group entered\n");
4426 #if ENABLE_HUSH_FUNCTIONS
4427 if (ch == 'F') { /* function definition? */
4428 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4429 //command->fname = dest->data;
4430 command->grp_type = GRP_FUNCTION;
4431 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4432 memset(dest, 0, sizeof(*dest));
4435 if (command->argv /* word [word](... */
4436 || dest->length /* word(... */
4437 || dest->o_quoted /* ""(... */
4440 debug_printf_parse("parse_group return 1: "
4441 "syntax error, groups and arglists don't mix\n");
4447 command->grp_type = GRP_SUBSHELL;
4451 char *as_string = NULL;
4453 pipe_list = parse_stream(&as_string, input, endch);
4456 o_addstr(&ctx->as_string, as_string);
4458 /* empty ()/{} or parse error? */
4459 if (!pipe_list || pipe_list == ERR_PTR) {
4464 debug_printf_parse("parse_group return 1: "
4465 "parse_stream returned %p\n", pipe_list);
4468 command->group = pipe_list;
4470 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4471 command->group_as_string = as_string;
4472 debug_printf_parse("end of group, remembering as:'%s'\n",
4473 command->group_as_string);
4476 debug_printf_parse("parse_group return 0\n");
4478 /* command remains "open", available for possible redirects */
4481 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4482 /* Subroutines for copying $(...) and `...` things */
4483 static int add_till_backquote(o_string *dest, struct in_str *input);
4485 static int add_till_single_quote(o_string *dest, struct in_str *input)
4488 int ch = i_getch(input);
4490 syntax_error_unterminated('\'');
4498 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4499 static int add_till_double_quote(o_string *dest, struct in_str *input)
4502 int ch = i_getch(input);
4504 syntax_error_unterminated('"');
4509 if (ch == '\\') { /* \x. Copy both chars. */
4511 ch = i_getch(input);
4515 if (add_till_backquote(dest, input))
4520 //if (ch == '$') ...
4523 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4525 * "Within the backquoted style of command substitution, backslash
4526 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4527 * The search for the matching backquote shall be satisfied by the first
4528 * backquote found without a preceding backslash; during this search,
4529 * if a non-escaped backquote is encountered within a shell comment,
4530 * a here-document, an embedded command substitution of the $(command)
4531 * form, or a quoted string, undefined results occur. A single-quoted
4532 * or double-quoted string that begins, but does not end, within the
4533 * "`...`" sequence produces undefined results."
4535 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4537 static int add_till_backquote(o_string *dest, struct in_str *input)
4540 int ch = i_getch(input);
4542 syntax_error_unterminated('`');
4548 /* \x. Copy both chars unless it is \` */
4549 int ch2 = i_getch(input);
4551 syntax_error_unterminated('`');
4554 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4561 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4562 * quoting and nested ()s.
4563 * "With the $(command) style of command substitution, all characters
4564 * following the open parenthesis to the matching closing parenthesis
4565 * constitute the command. Any valid shell script can be used for command,
4566 * except a script consisting solely of redirections which produces
4567 * unspecified results."
4569 * echo $(echo '(TEST)' BEST) (TEST) BEST
4570 * echo $(echo 'TEST)' BEST) TEST) BEST
4571 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4573 static int add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4577 int ch = i_getch(input);
4579 syntax_error_unterminated(')');
4588 if (i_peek(input) == ')') {
4596 if (add_till_single_quote(dest, input))
4602 if (add_till_double_quote(dest, input))
4608 /* \x. Copy verbatim. Important for \(, \) */
4609 ch = i_getch(input);
4611 syntax_error_unterminated(')');
4620 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4622 /* Return code: 0 for OK, 1 for syntax error */
4624 #define handle_dollar(as_string, dest, input) \
4625 handle_dollar(dest, input)
4627 static int handle_dollar(o_string *as_string,
4629 struct in_str *input)
4632 int ch = i_peek(input); /* first character after the $ */
4633 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4635 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4637 ch = i_getch(input);
4638 nommu_addchr(as_string, ch);
4640 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4642 debug_printf_parse(": '%c'\n", ch);
4643 o_addchr(dest, ch | quote_mask);
4646 if (!isalnum(ch) && ch != '_')
4648 ch = i_getch(input);
4649 nommu_addchr(as_string, ch);
4651 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4652 } else if (isdigit(ch)) {
4654 ch = i_getch(input);
4655 nommu_addchr(as_string, ch);
4656 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4657 debug_printf_parse(": '%c'\n", ch);
4658 o_addchr(dest, ch | quote_mask);
4659 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4660 } else switch (ch) {
4662 case '!': /* last bg pid */
4663 case '?': /* last exit code */
4664 case '#': /* number of args */
4665 case '*': /* args */
4666 case '@': /* args */
4667 goto make_one_char_var;
4669 bool first_char, all_digits;
4671 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4672 ch = i_getch(input);
4673 nommu_addchr(as_string, ch);
4674 /* XXX maybe someone will try to escape the '}' */
4679 ch = i_getch(input);
4680 nommu_addchr(as_string, ch);
4686 /* ${#var}: length of var contents */
4688 else if (isdigit(ch)) {
4695 && ( (all_digits && !isdigit(ch))
4696 || (!all_digits && !isalnum(ch) && ch != '_')
4699 /* handle parameter expansions
4700 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4705 case ':': /* null modifier */
4706 if (expansion == 0) {
4707 debug_printf_parse(": null modifier\n");
4712 case '#': /* remove prefix */
4713 case '%': /* remove suffix */
4714 if (expansion == 0) {
4715 debug_printf_parse(": remove suffix/prefix\n");
4720 case '-': /* default value */
4721 case '=': /* assign default */
4722 case '+': /* alternative */
4723 case '?': /* error indicate */
4724 debug_printf_parse(": parameter expansion\n");
4729 syntax_error("unterminated ${name}");
4730 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4735 debug_printf_parse(": '%c'\n", ch);
4736 o_addchr(dest, ch | quote_mask);
4740 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4743 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4748 ch = i_getch(input);
4749 nommu_addchr(as_string, ch);
4750 # if ENABLE_SH_MATH_SUPPORT
4751 if (i_peek(input) == '(') {
4752 ch = i_getch(input);
4753 nommu_addchr(as_string, ch);
4754 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4755 o_addchr(dest, /*quote_mask |*/ '+');
4759 if (add_till_closing_paren(dest, input, true))
4763 o_addstr(as_string, dest->data + pos);
4764 o_addchr(as_string, ')');
4765 o_addchr(as_string, ')');
4768 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4772 # if ENABLE_HUSH_TICK
4773 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4774 o_addchr(dest, quote_mask | '`');
4778 if (add_till_closing_paren(dest, input, false))
4782 o_addstr(as_string, dest->data + pos);
4783 o_addchr(as_string, '`');
4786 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4792 ch = i_getch(input);
4793 nommu_addchr(as_string, ch);
4795 if (isalnum(ch)) { /* it's $_name or $_123 */
4801 /* $_ Shell or shell script name; or last cmd name */
4802 /* $- Option flags set by set builtin or shell options (-i etc) */
4804 o_addQchr(dest, '$');
4806 debug_printf_parse("handle_dollar return 0\n");
4811 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4812 parse_stream_dquoted(dest, input, dquote_end)
4814 static int parse_stream_dquoted(o_string *as_string,
4816 struct in_str *input,
4823 ch = i_getch(input);
4825 nommu_addchr(as_string, ch);
4826 if (ch == dquote_end) { /* may be only '"' or EOF */
4827 if (dest->o_assignment == NOT_ASSIGNMENT)
4828 dest->o_escape ^= 1;
4829 debug_printf_parse("parse_stream_dquoted return 0\n");
4832 /* note: can't move it above ch == dquote_end check! */
4834 syntax_error_unterminated('"');
4835 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4840 next = i_peek(input);
4842 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4843 ch, ch, dest->o_escape);
4845 //TODO: check interactive behavior
4847 syntax_error("\\<eof>");
4848 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4852 * "The backslash retains its special meaning [in "..."]
4853 * only when followed by one of the following characters:
4854 * $, `, ", \, or <newline>. A double quote may be quoted
4855 * within double quotes by preceding it with a backslash.
4856 * If enabled, history expansion will be performed unless
4857 * an ! appearing in double quotes is escaped using
4858 * a backslash. The backslash preceding the ! is not removed."
4860 if (strchr("$`\"\\", next) != NULL) {
4861 o_addqchr(dest, i_getch(input));
4863 o_addqchr(dest, '\\');
4868 if (handle_dollar(as_string, dest, input) != 0) {
4869 debug_printf_parse("parse_stream_dquoted return 1: "
4870 "handle_dollar returned non-0\n");
4875 #if ENABLE_HUSH_TICK
4877 //int pos = dest->length;
4878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4879 o_addchr(dest, 0x80 | '`');
4880 if (add_till_backquote(dest, input))
4882 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4883 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4887 o_addQchr(dest, ch);
4889 && (dest->o_assignment == MAYBE_ASSIGNMENT
4890 || dest->o_assignment == WORD_IS_KEYWORD)
4891 && is_well_formed_var_name(dest->data, '=')
4893 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4899 * Scan input until EOF or end_trigger char.
4900 * Return a list of pipes to execute, or NULL on EOF
4901 * or if end_trigger character is met.
4902 * On syntax error, exit is shell is not interactive,
4903 * reset parsing machinery and start parsing anew,
4904 * or return ERR_PTR.
4906 static struct pipe *parse_stream(char **pstring,
4907 struct in_str *input,
4910 struct parse_context ctx;
4911 o_string dest = NULL_O_STRING;
4915 /* Double-quote state is handled in the state variable is_in_dquote.
4916 * A single-quote triggers a bypass of the main loop until its mate is
4917 * found. When recursing, quote state is passed in via dest->o_escape.
4919 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4920 end_trigger ? : 'X');
4922 G.ifs = get_local_var_value("IFS");
4927 #if ENABLE_HUSH_INTERACTIVE
4928 input->promptmode = 0; /* PS1 */
4930 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4931 initialize_context(&ctx);
4936 const char *is_special;
4940 redir_type redir_style;
4943 /* dest.o_quoted = 1; - already is (see below) */
4944 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4947 /* We reached closing '"' */
4950 ch = i_getch(input);
4951 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4952 ch, ch, dest.o_escape);
4957 syntax_error("unterminated here document");
4960 if (done_word(&dest, &ctx)) {
4964 done_pipe(&ctx, PIPE_SEQ);
4966 /* If we got nothing... */
4967 // TODO: test script consisting of just "&"
4968 if (pi->num_cmds == 0
4969 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4971 free_pipe_list(pi, 0);
4974 debug_printf_parse("parse_stream return %p\n", pi);
4976 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4978 *pstring = ctx.as_string.data;
4980 o_free_unsafe(&ctx.as_string);
4984 nommu_addchr(&ctx.as_string, ch);
4985 is_ifs = strchr(G.ifs, ch);
4986 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4987 "\\$\"" USE_HUSH_TICK("`") /* always special */
4990 if (!is_special && !is_ifs) { /* ordinary char */
4991 o_addQchr(&dest, ch);
4992 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4993 || dest.o_assignment == WORD_IS_KEYWORD)
4995 && is_well_formed_var_name(dest.data, '=')
4997 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5003 if (done_word(&dest, &ctx)) {
5007 #if ENABLE_HUSH_CASE
5008 /* "case ... in <newline> word) ..." -
5009 * newlines are ignored (but ';' wouldn't be) */
5010 if (ctx.command->argv == NULL
5011 && ctx.ctx_res_w == RES_MATCH
5016 /* Treat newline as a command separator. */
5017 done_pipe(&ctx, PIPE_SEQ);
5018 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5020 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5025 dest.o_assignment = MAYBE_ASSIGNMENT;
5027 /* note: if (is_ifs) continue;
5028 * will still trigger for us */
5031 if (end_trigger && end_trigger == ch
5032 && (heredoc_cnt == 0 || end_trigger != ';')
5034 //TODO: disallow "{ cmd }" without semicolon
5036 /* This is technically valid:
5037 * { cat <<HERE; }; echo Ok
5042 * but we don't support this.
5043 * We require heredoc to be in enclosing {}/(),
5046 syntax_error("unterminated here document");
5049 if (done_word(&dest, &ctx)) {
5052 done_pipe(&ctx, PIPE_SEQ);
5053 dest.o_assignment = MAYBE_ASSIGNMENT;
5054 /* Do we sit outside of any if's, loops or case's? */
5056 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5058 debug_printf_parse("parse_stream return %p: "
5059 "end_trigger char found\n",
5063 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5065 *pstring = ctx.as_string.data;
5067 o_free_unsafe(&ctx.as_string);
5069 return ctx.list_head;
5075 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
5076 /* ch is a special char and thus this word
5077 * cannot be an assignment */
5078 dest.o_assignment = NOT_ASSIGNMENT;
5083 next = i_peek(input);
5088 if (dest.length == 0) {
5091 if (ch == EOF || ch == '\n')
5094 /* note: we do not add it to &ctx.as_string */
5096 nommu_addchr(&ctx.as_string, '\n');
5098 o_addQchr(&dest, ch);
5103 syntax_error("\\<eof>");
5106 o_addchr(&dest, '\\');
5107 ch = i_getch(input);
5108 nommu_addchr(&ctx.as_string, ch);
5109 o_addchr(&dest, ch);
5110 /* Example: echo Hello \2>file
5111 * we need to know that word 2 is quoted */
5115 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5116 debug_printf_parse("parse_stream parse error: "
5117 "handle_dollar returned non-0\n");
5124 ch = i_getch(input);
5126 syntax_error_unterminated('\'');
5129 nommu_addchr(&ctx.as_string, ch);
5132 if (dest.o_assignment == NOT_ASSIGNMENT)
5133 o_addqchr(&dest, ch);
5135 o_addchr(&dest, ch);
5140 is_in_dquote ^= 1; /* invert */
5141 if (dest.o_assignment == NOT_ASSIGNMENT)
5144 #if ENABLE_HUSH_TICK
5149 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5150 o_addchr(&dest, '`');
5154 if (add_till_backquote(&dest, input))
5157 o_addstr(&ctx.as_string, dest.data + pos);
5158 o_addchr(&ctx.as_string, '`');
5160 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5161 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5166 redir_fd = redirect_opt_num(&dest);
5167 if (done_word(&dest, &ctx)) {
5170 redir_style = REDIRECT_OVERWRITE;
5172 redir_style = REDIRECT_APPEND;
5173 ch = i_getch(input);
5174 nommu_addchr(&ctx.as_string, ch);
5177 else if (next == '(') {
5178 syntax_error(">(process) not supported");
5182 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5186 redir_fd = redirect_opt_num(&dest);
5187 if (done_word(&dest, &ctx)) {
5190 redir_style = REDIRECT_INPUT;
5192 redir_style = REDIRECT_HEREDOC;
5194 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5195 ch = i_getch(input);
5196 nommu_addchr(&ctx.as_string, ch);
5197 } else if (next == '>') {
5198 redir_style = REDIRECT_IO;
5199 ch = i_getch(input);
5200 nommu_addchr(&ctx.as_string, ch);
5203 else if (next == '(') {
5204 syntax_error("<(process) not supported");
5208 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5212 #if ENABLE_HUSH_CASE
5215 if (done_word(&dest, &ctx)) {
5218 done_pipe(&ctx, PIPE_SEQ);
5219 #if ENABLE_HUSH_CASE
5220 /* Eat multiple semicolons, detect
5221 * whether it means something special */
5226 ch = i_getch(input);
5227 nommu_addchr(&ctx.as_string, ch);
5228 if (ctx.ctx_res_w == RES_CASEI) {
5229 ctx.ctx_dsemicolon = 1;
5230 ctx.ctx_res_w = RES_MATCH;
5236 /* We just finished a cmd. New one may start
5237 * with an assignment */
5238 dest.o_assignment = MAYBE_ASSIGNMENT;
5241 if (done_word(&dest, &ctx)) {
5245 ch = i_getch(input);
5246 nommu_addchr(&ctx.as_string, ch);
5247 done_pipe(&ctx, PIPE_AND);
5249 done_pipe(&ctx, PIPE_BG);
5253 if (done_word(&dest, &ctx)) {
5256 #if ENABLE_HUSH_CASE
5257 if (ctx.ctx_res_w == RES_MATCH)
5258 break; /* we are in case's "word | word)" */
5260 if (next == '|') { /* || */
5261 ch = i_getch(input);
5262 nommu_addchr(&ctx.as_string, ch);
5263 done_pipe(&ctx, PIPE_OR);
5265 /* we could pick up a file descriptor choice here
5266 * with redirect_opt_num(), but bash doesn't do it.
5267 * "echo foo 2| cat" yields "foo 2". */
5272 #if ENABLE_HUSH_CASE
5273 /* "case... in [(]word)..." - skip '(' */
5274 if (ctx.ctx_res_w == RES_MATCH
5275 && ctx.command->argv == NULL /* not (word|(... */
5276 && dest.length == 0 /* not word(... */
5277 && dest.o_quoted == 0 /* not ""(... */
5282 #if ENABLE_HUSH_FUNCTIONS
5283 if (dest.length != 0 /* not just () but word() */
5284 && dest.o_quoted == 0 /* not a"b"c() */
5285 && ctx.command->argv == NULL /* it's the first word */
5286 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5287 && i_peek(input) == ')'
5288 && !match_reserved_word(&dest)
5290 bb_error_msg("seems like a function definition");
5292 //if !BB_MMU o_addchr(&ctx.as_string...
5294 //TODO: do it properly.
5295 ch = i_getch(input);
5296 } while (ch == ' ' || ch == '\n');
5298 syntax_error("was expecting {");
5301 ch = 'F'; /* magic value */
5305 if (parse_group(&dest, &ctx, input, ch) != 0) {
5310 #if ENABLE_HUSH_CASE
5311 if (ctx.ctx_res_w == RES_MATCH)
5315 /* proper use of this character is caught by end_trigger:
5316 * if we see {, we call parse_group(..., end_trigger='}')
5317 * and it will match } earlier (not here). */
5318 syntax_error("unexpected } or )");
5322 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5328 struct parse_context *pctx;
5329 IF_HAS_KEYWORDS(struct parse_context *p2;)
5331 /* Clean up allocated tree.
5332 * Samples for finding leaks on syntax error recovery path.
5333 * Run them from interactive shell, watch pmap `pidof hush`.
5334 * while if false; then false; fi do break; done
5336 * while if false; then false; fi; do break; fi
5337 * Samples to catch leaks at execution:
5338 * while if (true | {true;}); then echo ok; fi; do break; done
5339 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5343 /* Update pipe/command counts,
5344 * otherwise freeing may miss some */
5345 done_pipe(pctx, PIPE_SEQ);
5346 debug_printf_clean("freeing list %p from ctx %p\n",
5347 pctx->list_head, pctx);
5348 debug_print_tree(pctx->list_head, 0);
5349 free_pipe_list(pctx->list_head, 0);
5350 debug_printf_clean("freed list %p\n", pctx->list_head);
5352 o_free_unsafe(&pctx->as_string);
5354 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5358 IF_HAS_KEYWORDS(pctx = p2;)
5359 } while (HAS_KEYWORDS && pctx);
5360 /* Free text, clear all dest fields */
5362 /* If we are not in top-level parse, we return,
5363 * our caller will propagate error.
5365 if (end_trigger != ';') {
5372 /* Discard cached input, force prompt */
5374 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5379 /* Executing from string: eval, sh -c '...'
5380 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5381 * end_trigger controls how often we stop parsing
5382 * NUL: parse all, execute, return
5383 * ';': parse till ';' or newline, execute, repeat till EOF
5385 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5388 struct pipe *pipe_list;
5390 pipe_list = parse_stream(NULL, inp, end_trigger);
5391 if (!pipe_list) /* EOF */
5393 debug_print_tree(pipe_list, 0);
5394 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5395 run_and_free_list(pipe_list);
5399 static void parse_and_run_string(const char *s)
5401 struct in_str input;
5402 setup_string_in_str(&input, s);
5403 parse_and_run_stream(&input, '\0');
5406 static void parse_and_run_file(FILE *f)
5408 struct in_str input;
5409 setup_file_in_str(&input, f);
5410 parse_and_run_stream(&input, ';');
5413 /* Called a few times only (or even once if "sh -c") */
5414 static void block_signals(int second_time)
5419 mask = (1 << SIGQUIT);
5420 if (G_interactive_fd) {
5424 //TODO | (1 << SIGHUP)
5426 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5431 G.non_DFL_mask = mask;
5434 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5438 sigaddset(&G.blocked_set, sig);
5442 sigdelset(&G.blocked_set, SIGCHLD);
5444 sigprocmask(SIG_SETMASK, &G.blocked_set,
5445 second_time ? NULL : &G.inherited_set);
5446 /* POSIX allows shell to re-enable SIGCHLD
5447 * even if it was SIG_IGN on entry */
5448 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5450 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5455 static void maybe_set_to_sigexit(int sig)
5457 void (*handler)(int);
5458 /* non_DFL_mask'ed signals are, well, masked,
5459 * no need to set handler for them.
5461 if (!((G.non_DFL_mask >> sig) & 1)) {
5462 handler = signal(sig, sigexit);
5463 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5464 signal(sig, handler);
5467 /* Set handlers to restore tty pgrp and exit */
5468 static void set_fatal_handlers(void)
5470 /* We _must_ restore tty pgrp on fatal signals */
5472 maybe_set_to_sigexit(SIGILL );
5473 maybe_set_to_sigexit(SIGFPE );
5474 maybe_set_to_sigexit(SIGBUS );
5475 maybe_set_to_sigexit(SIGSEGV);
5476 maybe_set_to_sigexit(SIGTRAP);
5477 } /* else: hush is perfect. what SEGV? */
5478 maybe_set_to_sigexit(SIGABRT);
5479 /* bash 3.2 seems to handle these just like 'fatal' ones */
5480 maybe_set_to_sigexit(SIGPIPE);
5481 maybe_set_to_sigexit(SIGALRM);
5482 //TODO: disable and move down when proper SIGHUP handling is added
5483 maybe_set_to_sigexit(SIGHUP );
5484 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5485 * if we aren't interactive... but in this case
5486 * we never want to restore pgrp on exit, and this fn is not called */
5487 /*maybe_set_to_sigexit(SIGTERM);*/
5488 /*maybe_set_to_sigexit(SIGINT );*/
5492 static int set_mode(const char cstate, const char mode)
5494 int state = (cstate == '-' ? 1 : 0);
5496 case 'n': G.fake_mode = state; break;
5497 case 'x': /*G.debug_mode = state;*/ break;
5498 default: return EXIT_FAILURE;
5500 return EXIT_SUCCESS;
5503 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5504 int hush_main(int argc, char **argv)
5506 static const struct variable const_shell_ver = {
5508 .varstr = (char*)hush_version_str,
5509 .max_len = 1, /* 0 can provoke free(name) */
5513 int signal_mask_is_inited = 0;
5516 struct variable *cur_var;
5519 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5520 G.last_exitcode = EXIT_SUCCESS;
5522 G.argv0_for_re_execing = argv[0];
5524 /* Deal with HUSH_VERSION */
5525 G.shell_ver = const_shell_ver; /* copying struct here */
5526 G.top_var = &G.shell_ver;
5527 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5528 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5529 /* Initialize our shell local variables with the values
5530 * currently living in the environment */
5531 cur_var = G.top_var;
5534 char *value = strchr(*e, '=');
5535 if (value) { /* paranoia */
5536 cur_var->next = xzalloc(sizeof(*cur_var));
5537 cur_var = cur_var->next;
5538 cur_var->varstr = *e;
5539 cur_var->max_len = strlen(*e);
5540 cur_var->flg_export = 1;
5544 debug_printf_env("putenv '%s'\n", hush_version_str);
5545 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5546 #if ENABLE_FEATURE_EDITING
5547 G.line_input_state = new_line_input_t(FOR_SHELL);
5549 G.global_argc = argc;
5550 G.global_argv = argv;
5551 /* Initialize some more globals to non-zero values */
5553 #if ENABLE_HUSH_INTERACTIVE
5554 if (ENABLE_FEATURE_EDITING)
5555 cmdedit_set_initial_prompt();
5559 /* Shell is non-interactive at first. We need to call
5560 * block_signals(0) if we are going to execute "sh <script>",
5561 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5562 * If we later decide that we are interactive, we run block_signals(0)
5563 * (or re-run block_signals(1) if we ran block_signals(0) before)
5564 * in order to intercept (more) signals.
5568 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5570 opt = getopt(argc, argv, "c:xins"
5580 G.root_pid = getpid();
5581 G.global_argv = argv + optind;
5582 if (!argv[optind]) {
5583 /* -c 'script' (no params): prevent empty $0 */
5584 *--G.global_argv = argv[0];
5586 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5587 G.global_argc = argc - optind;
5588 block_signals(0); /* 0: called 1st time */
5589 parse_and_run_string(optarg);
5592 /* Well, we cannot just declare interactiveness,
5593 * we have to have some stuff (ctty, etc) */
5594 /* G_interactive_fd++; */
5597 /* "-s" means "read from stdin", but this is how we always
5598 * operate, so simply do nothing here. */
5601 case '<': /* "big heredoc" support */
5602 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5605 G.root_pid = bb_strtou(optarg, &optarg, 16);
5607 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5609 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5610 # if ENABLE_HUSH_LOOPS
5612 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5617 set_local_var(xstrdup(optarg), 0, opt == 'R');
5622 if (!set_mode('-', opt))
5626 fprintf(stderr, "Usage: sh [FILE]...\n"
5627 " or: sh -c command [args]...\n\n");
5633 } /* option parsing loop */
5636 G.root_pid = getpid();
5638 /* If we are login shell... */
5639 if (argv[0] && argv[0][0] == '-') {
5641 /* XXX what should argv be while sourcing /etc/profile? */
5642 debug_printf("sourcing /etc/profile\n");
5643 input = fopen_for_read("/etc/profile");
5644 if (input != NULL) {
5645 close_on_exec_on(fileno(input));
5646 block_signals(0); /* 0: called 1st time */
5647 signal_mask_is_inited = 1;
5648 parse_and_run_file(input);
5651 /* bash: after sourcing /etc/profile,
5652 * tries to source (in the given order):
5653 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5654 * stopping of first found. --noprofile turns this off.
5655 * bash also sources ~/.bash_logout on exit.
5656 * If called as sh, skips .bash_XXX files.
5663 * "bash <script>" (which is never interactive (unless -i?))
5664 * sources $BASH_ENV here (without scanning $PATH).
5665 * If called as sh, does the same but with $ENV.
5667 debug_printf("running script '%s'\n", argv[optind]);
5668 G.global_argv = argv + optind;
5669 G.global_argc = argc - optind;
5670 input = xfopen_for_read(argv[optind]);
5671 close_on_exec_on(fileno(input));
5672 if (!signal_mask_is_inited)
5673 block_signals(0); /* 0: called 1st time */
5674 parse_and_run_file(input);
5675 #if ENABLE_FEATURE_CLEAN_UP
5681 /* Up to here, shell was non-interactive. Now it may become one.
5682 * NB: don't forget to (re)run block_signals(0/1) as needed.
5685 /* A shell is interactive if the '-i' flag was given, or if all of
5686 * the following conditions are met:
5688 * no arguments remaining or the -s flag given
5689 * standard input is a terminal
5690 * standard output is a terminal
5691 * Refer to Posix.2, the description of the 'sh' utility.
5694 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5695 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5696 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5697 //TODO: "interactive" and "have job control" are two different things.
5698 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5699 //should stay on! Currently, we mix these into one.
5700 if (G.saved_tty_pgrp >= 0) {
5701 /* try to dup stdin to high fd#, >= 255 */
5702 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5703 if (G_interactive_fd < 0) {
5704 /* try to dup to any fd */
5705 G_interactive_fd = dup(STDIN_FILENO);
5706 if (G_interactive_fd < 0)
5708 G_interactive_fd = 0;
5710 // TODO: track & disallow any attempts of user
5711 // to (inadvertently) close/redirect it
5714 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5715 if (G_interactive_fd) {
5718 /* We are indeed interactive shell, and we will perform
5719 * job control. Setting up for that. */
5721 close_on_exec_on(G_interactive_fd);
5722 /* If we were run as 'hush &', sleep until we are
5723 * in the foreground (tty pgrp == our pgrp).
5724 * If we get started under a job aware app (like bash),
5725 * make sure we are now in charge so we don't fight over
5726 * who gets the foreground */
5728 shell_pgrp = getpgrp();
5729 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5730 if (G.saved_tty_pgrp == shell_pgrp)
5732 /* send TTIN to ourself (should stop us) */
5733 kill(- shell_pgrp, SIGTTIN);
5735 /* Block some signals */
5736 block_signals(signal_mask_is_inited);
5737 /* Set other signals to restore saved_tty_pgrp */
5738 set_fatal_handlers();
5739 /* Put ourselves in our own process group */
5740 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5741 /* Grab control of the terminal */
5742 tcsetpgrp(G_interactive_fd, getpid());
5743 /* -1 is special - makes xfuncs longjmp, not exit
5744 * (we reset die_sleep = 0 whereever we [v]fork) */
5745 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
5746 if (setjmp(die_jmp)) {
5747 /* xfunc has failed! die die die */
5748 /* no EXIT traps, this is an escape hatch! */
5750 hush_exit(xfunc_error_retval);
5752 } else if (!signal_mask_is_inited) {
5753 block_signals(0); /* 0: called 1st time */
5754 } /* else: block_signals(0) was done before */
5755 #elif ENABLE_HUSH_INTERACTIVE
5756 /* No job control compiled in, only prompt/line editing */
5757 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5758 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5759 if (G_interactive_fd < 0) {
5760 /* try to dup to any fd */
5761 G_interactive_fd = dup(STDIN_FILENO);
5762 if (G_interactive_fd < 0)
5764 G_interactive_fd = 0;
5767 if (G_interactive_fd) {
5768 close_on_exec_on(G_interactive_fd);
5769 block_signals(signal_mask_is_inited);
5770 } else if (!signal_mask_is_inited) {
5774 /* We have interactiveness code disabled */
5775 if (!signal_mask_is_inited) {
5780 * if interactive but not a login shell, sources ~/.bashrc
5781 * (--norc turns this off, --rcfile <file> overrides)
5784 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5785 printf("\n\n%s hush - the humble shell\n", bb_banner);
5786 printf("Enter 'help' for a list of built-in commands.\n\n");
5789 parse_and_run_file(stdin);
5792 #if ENABLE_FEATURE_CLEAN_UP
5793 if (G.cwd != bb_msg_unknown)
5795 cur_var = G.top_var->next;
5797 struct variable *tmp = cur_var;
5798 if (!cur_var->max_len)
5799 free(cur_var->varstr);
5800 cur_var = cur_var->next;
5804 hush_exit(G.last_exitcode);
5809 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5810 int lash_main(int argc, char **argv)
5812 //bb_error_msg("lash is deprecated, please use hush instead");
5813 return hush_main(argc, argv);
5821 static int builtin_trap(char **argv)
5828 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5832 /* No args: print all trapped. This isn't 100% correct as we
5833 * should be escaping the cmd so that it can be pasted back in
5835 for (i = 0; i < NSIG; ++i)
5837 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5838 return EXIT_SUCCESS;
5843 /* If first arg is decimal: reset all specified signals */
5844 sig = bb_strtou(*argv, NULL, 10);
5850 sig = get_signum(*argv++);
5851 if (sig < 0 || sig >= NSIG) {
5853 /* Mimic bash message exactly */
5854 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5859 G.traps[sig] = xstrdup(new_cmd);
5861 debug_printf("trap: setting SIG%s (%i) to '%s'",
5862 get_signame(sig), sig, G.traps[sig]);
5864 /* There is no signal for 0 (EXIT) */
5869 sigaddset(&G.blocked_set, sig);
5871 /* There was a trap handler, we are removing it
5872 * (if sig has non-DFL handling,
5873 * we don't need to do anything) */
5874 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5876 sigdelset(&G.blocked_set, sig);
5878 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5883 /* First arg is "-": reset all specified to default */
5884 /* First arg is "": ignore all specified */
5885 /* Everything else: execute first arg upon signal */
5887 bb_error_msg("trap: invalid arguments");
5888 return EXIT_FAILURE;
5890 if (NOT_LONE_DASH(*argv))
5896 static int builtin_true(char **argv UNUSED_PARAM)
5901 static int builtin_test(char **argv)
5908 return test_main(argc, argv - argc);
5911 static int builtin_echo(char **argv)
5918 return echo_main(argc, argv - argc);
5921 static int builtin_eval(char **argv)
5923 int rcode = EXIT_SUCCESS;
5926 char *str = expand_strvec_to_string(argv);
5928 * eval "echo Hi; done" ("done" is syntax error):
5929 * "echo Hi" will not execute too.
5931 parse_and_run_string(str);
5933 rcode = G.last_exitcode;
5938 static int builtin_cd(char **argv)
5940 const char *newdir = argv[1];
5941 if (newdir == NULL) {
5942 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5943 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5945 newdir = getenv("HOME") ? : "/";
5947 if (chdir(newdir)) {
5948 /* Mimic bash message exactly */
5949 bb_perror_msg("cd: %s", newdir);
5950 return EXIT_FAILURE;
5953 return EXIT_SUCCESS;
5956 static int builtin_exec(char **argv)
5958 if (*++argv == NULL)
5959 return EXIT_SUCCESS; /* bash does this */
5964 // FIXME: if exec fails, bash does NOT exit! We do...
5965 pseudo_exec_argv(&dummy, argv, 0, NULL);
5970 static int builtin_exit(char **argv)
5972 debug_printf_exec("%s()\n", __func__);
5973 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5974 //puts("exit"); /* bash does it */
5975 // TODO: warn if we have background jobs: "There are stopped jobs"
5976 // On second consecutive 'exit', exit anyway.
5977 // perhaps use G.exiting = -1 as indicator "last cmd was exit"
5979 /* note: EXIT trap is run by hush_exit */
5980 if (*++argv == NULL)
5981 hush_exit(G.last_exitcode);
5982 /* mimic bash: exit 123abc == exit 255 + error msg */
5983 xfunc_error_retval = 255;
5984 /* bash: exit -2 == exit 254, no error msg */
5985 hush_exit(xatoi(*argv) & 0xff);
5988 static int builtin_export(char **argv)
5990 if (*++argv == NULL) {
5992 // ash emits: export VAR='VAL'
5993 // bash: declare -x VAR="VAL"
5994 // (both also escape as needed (quotes, $, etc))
5999 return EXIT_SUCCESS;
6006 value = strchr(name, '=');
6008 /* They are exporting something without a =VALUE */
6009 struct variable *var;
6011 var = get_local_var(name);
6013 var->flg_export = 1;
6014 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6015 putenv(var->varstr);
6017 /* bash does not return an error when trying to export
6018 * an undefined variable. Do likewise. */
6021 set_local_var(xstrdup(name), 1, 0);
6024 return EXIT_SUCCESS;
6028 /* built-in 'fg' and 'bg' handler */
6029 static int builtin_fg_bg(char **argv)
6034 if (!G_interactive_fd)
6035 return EXIT_FAILURE;
6036 /* If they gave us no args, assume they want the last backgrounded task */
6038 for (pi = G.job_list; pi; pi = pi->next) {
6039 if (pi->jobid == G.last_jobid) {
6043 bb_error_msg("%s: no current job", argv[0]);
6044 return EXIT_FAILURE;
6046 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6047 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6048 return EXIT_FAILURE;
6050 for (pi = G.job_list; pi; pi = pi->next) {
6051 if (pi->jobid == jobnum) {
6055 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6056 return EXIT_FAILURE;
6058 // TODO: bash prints a string representation
6059 // of job being foregrounded (like "sleep 1 | cat")
6060 if (argv[0][0] == 'f') {
6061 /* Put the job into the foreground. */
6062 tcsetpgrp(G_interactive_fd, pi->pgrp);
6065 /* Restart the processes in the job */
6066 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6067 for (i = 0; i < pi->num_cmds; i++) {
6068 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6069 pi->cmds[i].is_stopped = 0;
6071 pi->stopped_cmds = 0;
6073 i = kill(- pi->pgrp, SIGCONT);
6075 if (errno == ESRCH) {
6076 delete_finished_bg_job(pi);
6077 return EXIT_SUCCESS;
6079 bb_perror_msg("kill (SIGCONT)");
6082 if (argv[0][0] == 'f') {
6084 return checkjobs_and_fg_shell(pi);
6086 return EXIT_SUCCESS;
6090 #if ENABLE_HUSH_HELP
6091 static int builtin_help(char **argv UNUSED_PARAM)
6093 const struct built_in_command *x;
6096 "Built-in commands:\n"
6097 "------------------\n");
6098 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6099 printf("%s\t%s\n", x->cmd, x->descr);
6102 return EXIT_SUCCESS;
6107 static int builtin_jobs(char **argv UNUSED_PARAM)
6110 const char *status_string;
6112 for (job = G.job_list; job; job = job->next) {
6113 if (job->alive_cmds == job->stopped_cmds)
6114 status_string = "Stopped";
6116 status_string = "Running";
6118 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6120 return EXIT_SUCCESS;
6125 static int builtin_memleak(char **argv UNUSED_PARAM)
6130 /* Crude attempt to find where "free memory" starts,
6131 * sans fragmentation. */
6133 l = (unsigned long)p;
6136 if (l < (unsigned long)p) l = (unsigned long)p;
6139 if (!G.memleak_value)
6140 G.memleak_value = l;
6142 l -= G.memleak_value;
6149 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6154 static int builtin_pwd(char **argv UNUSED_PARAM)
6157 return EXIT_SUCCESS;
6160 static int builtin_read(char **argv)
6163 const char *name = "REPLY";
6167 if (!is_well_formed_var_name(name, '\0')) {
6168 /* Mimic bash message */
6169 bb_error_msg("read: '%s': not a valid identifier", name);
6174 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
6175 return set_local_var(string, 0, 0);
6178 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6179 * built-in 'set' handler
6181 * set [-abCefhmnuvx] [-o option] [argument...]
6182 * set [+abCefhmnuvx] [+o option] [argument...]
6183 * set -- [argument...]
6186 * Implementations shall support the options in both their hyphen and
6187 * plus-sign forms. These options can also be specified as options to sh.
6189 * Write out all variables and their values: set
6190 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6191 * Turn on the -x and -v options: set -xv
6192 * Unset all positional parameters: set --
6193 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6194 * Set the positional parameters to the expansion of x, even if x expands
6195 * with a leading '-' or '+': set -- $x
6197 * So far, we only support "set -- [argument...]" and some of the short names.
6199 static int builtin_set(char **argv)
6202 char **pp, **g_argv;
6203 char *arg = *++argv;
6207 for (e = G.top_var; e; e = e->next)
6209 return EXIT_SUCCESS;
6213 if (!strcmp(arg, "--")) {
6218 if (arg[0] == '+' || arg[0] == '-') {
6219 for (n = 1; arg[n]; ++n)
6220 if (set_mode(arg[0], arg[n]))
6226 } while ((arg = *++argv) != NULL);
6227 /* Now argv[0] is 1st argument */
6229 /* Only reset global_argv if we didn't process anything */
6231 return EXIT_SUCCESS;
6234 /* NB: G.global_argv[0] ($0) is never freed/changed */
6235 g_argv = G.global_argv;
6236 if (G.global_args_malloced) {
6242 G.global_args_malloced = 1;
6243 pp = xzalloc(sizeof(pp[0]) * 2);
6244 pp[0] = g_argv[0]; /* retain $0 */
6247 /* This realloc's G.global_argv */
6248 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6255 return EXIT_SUCCESS;
6257 /* Nothing known, so abort */
6259 bb_error_msg("set: %s: invalid option", arg);
6260 return EXIT_FAILURE;
6263 static int builtin_shift(char **argv)
6269 if (n >= 0 && n < G.global_argc) {
6270 if (G.global_args_malloced) {
6273 free(G.global_argv[m++]);
6276 memmove(&G.global_argv[1], &G.global_argv[n+1],
6277 G.global_argc * sizeof(G.global_argv[0]));
6278 return EXIT_SUCCESS;
6280 return EXIT_FAILURE;
6283 static int builtin_source(char **argv)
6287 if (*++argv == NULL)
6288 return EXIT_FAILURE;
6290 /* XXX search through $PATH is missing */
6291 input = fopen_or_warn(*argv, "r");
6293 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
6294 return EXIT_FAILURE;
6296 close_on_exec_on(fileno(input));
6298 /* Now run the file */
6300 /* XXX argv and argc are broken; need to save old G.global_argv
6301 * (pointer only is OK!) on this stack frame,
6302 * set G.global_argv=argv+1, recurse, and restore. */
6303 parse_and_run_file(input);
6305 return G.last_exitcode;
6308 static int builtin_umask(char **argv)
6311 const char *arg = argv[1];
6313 //TODO: umask may take chmod-like symbolic masks
6314 new_umask = bb_strtou(arg, NULL, 8);
6316 //Message? bash examples:
6317 //bash: umask: 'q': invalid symbolic mode operator
6318 //bash: umask: 999: octal number out of range
6319 return EXIT_FAILURE;
6322 new_umask = umask(0);
6323 printf("%.3o\n", (unsigned) new_umask);
6324 /* fall through and restore new_umask which we set to 0 */
6327 return EXIT_SUCCESS;
6330 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6331 static int builtin_unset(char **argv)
6337 return EXIT_SUCCESS;
6340 if (argv[0][0] == '-') {
6341 switch (argv[0][1]) {
6347 bb_error_msg("unset: %s: invalid option", *argv);
6348 return EXIT_FAILURE;
6350 //TODO: disallow "unset -vf ..." too
6357 if (unset_local_var(*argv)) {
6358 /* unset <nonexistent_var> doesn't fail.
6359 * Error is when one tries to unset RO var.
6360 * Message was printed by unset_local_var. */
6364 #if ENABLE_HUSH_FUNCTIONS
6366 unset_local_func(*argv);
6374 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6375 static int builtin_wait(char **argv)
6377 int ret = EXIT_SUCCESS;
6380 if (*++argv == NULL) {
6381 /* Don't care about wait results */
6382 /* Note 1: must wait until there are no more children */
6383 /* Note 2: must be interruptible */
6385 * $ sleep 3 & sleep 6 & wait
6390 * $ sleep 3 & sleep 6 & wait
6394 * ^C <-- after ~4 sec from keyboard
6397 sigaddset(&G.blocked_set, SIGCHLD);
6398 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6401 if (errno == ECHILD)
6403 /* Wait for SIGCHLD or any other signal of interest */
6404 /* sigtimedwait with infinite timeout: */
6405 sig = sigwaitinfo(&G.blocked_set, NULL);
6407 sig = check_and_run_traps(sig);
6408 if (sig && sig != SIGCHLD) { /* see note 2 */
6414 sigdelset(&G.blocked_set, SIGCHLD);
6415 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6419 /* This is probably buggy wrt interruptible-ness */
6421 pid_t pid = bb_strtou(*argv, NULL, 10);
6423 /* mimic bash message */
6424 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6425 return EXIT_FAILURE;
6427 if (waitpid(pid, &status, 0) == pid) {
6428 if (WIFSIGNALED(status))
6429 ret = 128 + WTERMSIG(status);
6430 else if (WIFEXITED(status))
6431 ret = WEXITSTATUS(status);
6435 bb_perror_msg("wait %s", *argv);
6444 #if ENABLE_HUSH_LOOPS
6445 static int builtin_break(char **argv)
6447 if (G.depth_of_loop == 0) {
6448 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6449 return EXIT_SUCCESS; /* bash compat */
6451 G.flag_break_continue++; /* BC_BREAK = 1 */
6452 G.depth_break_continue = 1;
6454 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6455 if (errno || !G.depth_break_continue || argv[2]) {
6456 bb_error_msg("%s: bad arguments", argv[0]);
6457 G.flag_break_continue = BC_BREAK;
6458 G.depth_break_continue = UINT_MAX;
6461 if (G.depth_of_loop < G.depth_break_continue)
6462 G.depth_break_continue = G.depth_of_loop;
6463 return EXIT_SUCCESS;
6466 static int builtin_continue(char **argv)
6468 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6469 return builtin_break(argv);