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...) die_if_script(fmt)
667 # define syntax_error(lineno, msg) syntax_error(msg)
668 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
669 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
670 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
673 static void die_if_script(unsigned lineno, const char *fmt, ...)
678 bb_error_msg("hush.c:%u", lineno);
681 bb_verror_msg(fmt, p, NULL);
683 if (!G_interactive_fd)
687 static void syntax_error(unsigned lineno, const char *msg)
690 die_if_script(lineno, "syntax error: %s", msg);
692 die_if_script(lineno, "syntax error", NULL);
695 static void syntax_error_at(unsigned lineno, const char *msg)
697 die_if_script(lineno, "syntax error at '%s'", msg);
700 static void syntax_error_unterm_ch(unsigned lineno, char ch)
705 die_if_script(lineno, "syntax error: unterminated %s", msg);
708 static void syntax_error_unterm_str(unsigned lineno, const char *s)
710 die_if_script(lineno, "syntax error: unterminated %s", s);
714 # undef die_if_script
716 # undef syntax_error_at
717 # undef syntax_error_unterm_ch
718 # undef syntax_error_unterm_str
720 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
721 # define syntax_error(msg) syntax_error(__LINE__, msg)
722 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
723 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
724 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
730 static int glob_needed(const char *s)
735 if (*s == '*' || *s == '[' || *s == '?')
742 static int is_well_formed_var_name(const char *s, char terminator)
744 if (!s || !(isalpha(*s) || *s == '_'))
747 while (isalnum(*s) || *s == '_')
749 return *s == terminator;
752 /* Replace each \x with x in place, return ptr past NUL. */
753 static char *unbackslash(char *src)
759 if ((*dst++ = *src++) == '\0')
765 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
786 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
787 v[count1 + count2] = NULL;
790 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
794 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
796 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
797 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
800 #define add_strings_to_strings(strings, add, need_to_dup) \
801 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
804 static char **add_string_to_strings(char **strings, char *add)
809 return add_strings_to_strings(strings, v, /*dup:*/ 0);
812 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
814 char **ptr = add_string_to_strings(strings, add);
815 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
818 #define add_string_to_strings(strings, add) \
819 xx_add_string_to_strings(__LINE__, strings, add)
822 static void putenv_all(char **strings)
827 debug_printf_env("putenv '%s'\n", *strings);
832 static char **putenv_all_and_save_old(char **strings)
842 eq = strchr(*strings, '=');
845 v = getenv(*strings);
848 /* v points to VAL in VAR=VAL, go back to VAR */
849 v -= (eq - *strings) + 1;
850 old = add_string_to_strings(old, v);
859 static void free_strings_and_unsetenv(char **strings, int unset)
869 debug_printf_env("unsetenv '%s'\n", *v);
877 static void free_strings(char **strings)
879 free_strings_and_unsetenv(strings, 0);
883 /* Basic theory of signal handling in shell
884 * ========================================
885 * This does not describe what hush does, rather, it is current understanding
886 * what it _should_ do. If it doesn't, it's a bug.
887 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
889 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
890 * is finished or backgrounded. It is the same in interactive and
891 * non-interactive shells, and is the same regardless of whether
892 * a user trap handler is installed or a shell special one is in effect.
893 * ^C or ^Z from keyboard seem to execute "at once" because it usually
894 * backgrounds (i.e. stops) or kills all members of currently running
897 * Wait builtin in interruptible by signals for which user trap is set
898 * or by SIGINT in interactive shell.
900 * Trap handlers will execute even within trap handlers. (right?)
902 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
904 * If job control is off, backgrounded commands ("cmd &")
905 * have SIGINT, SIGQUIT set to SIG_IGN.
907 * Commands run in command substitution ("`cmd`")
908 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
910 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
911 * by the shell from its parent.
913 * Siganls which differ from SIG_DFL action
914 * (note: child (i.e., [v]forked) shell is not an interactive shell):
917 * SIGTERM (interactive): ignore
918 * SIGHUP (interactive):
919 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
920 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
921 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
922 * that all pipe members are stopped) (right?)
923 * SIGINT (interactive): wait for last pipe, ignore the rest
924 * of the command line, show prompt. NB: ^C does not send SIGINT
925 * to interactive shell while shell is waiting for a pipe,
926 * since shell is bg'ed (is not in foreground process group).
927 * (check/expand this)
928 * Example 1: this waits 5 sec, but does not execute ls:
929 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
930 * Example 2: this does not wait and does not execute ls:
931 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
932 * Example 3: this does not wait 5 sec, but executes ls:
933 * "sleep 5; ls -l" + press ^C
935 * (What happens to signals which are IGN on shell start?)
936 * (What happens with signal mask on shell start?)
938 * Implementation in hush
939 * ======================
940 * We use in-kernel pending signal mask to determine which signals were sent.
941 * We block all signals which we don't want to take action immediately,
942 * i.e. we block all signals which need to have special handling as described
943 * above, and all signals which have traps set.
944 * After each pipe execution, we extract any pending signals via sigtimedwait()
947 * unsigned non_DFL_mask: a mask of such "special" signals
948 * sigset_t blocked_set: current blocked signal set
951 * clear bit in blocked_set unless it is also in non_DFL_mask
952 * "trap 'cmd' SIGxxx":
953 * set bit in blocked_set (even if 'cmd' is '')
954 * after [v]fork, if we plan to be a shell:
955 * nothing for {} child shell (say, "true | { true; true; } | true")
956 * unset all traps if () shell.
957 * after [v]fork, if we plan to exec:
958 * POSIX says pending signal mask is cleared in child - no need to clear it.
959 * Restore blocked signal set to one inherited by shell just prior to exec.
961 * Note: as a result, we do not use signal handlers much. The only uses
962 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
963 * and to restore tty pgrp on signal-induced exit.
966 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
968 // G.count_SIGCHLD++;
971 static int check_and_run_traps(int sig)
973 static const struct timespec zero_timespec = { 0, 0 };
974 smalluint save_rcode;
980 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
985 if (G.traps && G.traps[sig]) {
986 if (G.traps[sig][0]) {
987 /* We have user-defined handler */
988 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
989 save_rcode = G.last_exitcode;
992 G.last_exitcode = save_rcode;
993 } /* else: "" trap, ignoring signal */
996 /* not a trap: special action */
999 // G.count_SIGCHLD++;
1008 default: /* ignored: */
1009 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1018 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1019 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1020 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1021 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1023 /* Restores tty foreground process group, and exits.
1024 * May be called as signal handler for fatal signal
1025 * (will faithfully resend signal to itself, producing correct exit state)
1026 * or called directly with -EXITCODE.
1027 * We also call it if xfunc is exiting. */
1028 static void sigexit(int sig) NORETURN;
1029 static void sigexit(int sig)
1031 /* Disable all signals: job control, SIGPIPE, etc. */
1032 sigprocmask_allsigs(SIG_BLOCK);
1034 /* Careful: we can end up here after [v]fork. Do not restore
1035 * tty pgrp then, only top-level shell process does that */
1036 if (G_interactive_fd && getpid() == G.root_pid)
1037 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
1039 /* Not a signal, just exit */
1043 kill_myself_with_sig(sig); /* does not return */
1047 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1048 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1052 /* Restores tty foreground process group, and exits. */
1053 static void hush_exit(int exitcode) NORETURN;
1054 static void hush_exit(int exitcode)
1056 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1057 /* Prevent recursion:
1058 * trap "echo Hi; exit" EXIT; exit
1060 char *argv[] = { NULL, G.traps[0], NULL };
1068 fflush(NULL); /* flush all streams */
1069 sigexit(- (exitcode & 0xff));
1076 static const char *set_cwd(void)
1078 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1079 * we must not try to free(bb_msg_unknown) */
1080 if (G.cwd == bb_msg_unknown)
1082 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1084 G.cwd = bb_msg_unknown;
1089 /* Get/check local shell variables */
1090 static struct variable *get_local_var(const char *name)
1092 struct variable *cur;
1098 for (cur = G.top_var; cur; cur = cur->next) {
1099 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1105 static const char *get_local_var_value(const char *src)
1107 struct variable *var = get_local_var(src);
1109 return strchr(var->varstr, '=') + 1;
1113 /* str holds "NAME=VAL" and is expected to be malloced.
1114 * We take ownership of it.
1118 * -1: if NAME is set, leave export status alone
1119 * if NAME is not set, do not export
1120 * flg_read_only is set only when we handle -R var=val
1123 #define set_local_var(str, flg_export, flg_read_only) \
1124 set_local_var(str, flg_export)
1126 static int set_local_var(char *str, int flg_export, int flg_read_only)
1128 struct variable *cur;
1132 value = strchr(str, '=');
1133 if (!value) { /* not expected to ever happen? */
1138 name_len = value - str + 1; /* including '=' */
1139 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1141 if (strncmp(cur->varstr, str, name_len) != 0) {
1143 /* Bail out. Note that now cur points
1144 * to last var in linked list */
1150 /* We found an existing var with this name */
1152 if (cur->flg_read_only) {
1156 bb_error_msg("%s: readonly variable", str);
1160 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1161 unsetenv(str); /* just in case */
1163 if (strcmp(cur->varstr, str) == 0) {
1168 if (cur->max_len >= strlen(str)) {
1169 /* This one is from startup env, reuse space */
1170 strcpy(cur->varstr, str);
1173 /* max_len == 0 signifies "malloced" var, which we can
1174 * (and has to) free */
1178 goto set_str_and_exp;
1181 /* Not found - create next variable struct */
1182 cur->next = xzalloc(sizeof(*cur));
1188 cur->flg_read_only = flg_read_only;
1191 if (flg_export == 1)
1192 cur->flg_export = 1;
1193 if (cur->flg_export) {
1194 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1195 return putenv(cur->varstr);
1200 static int unset_local_var(const char *name)
1202 struct variable *cur;
1203 struct variable *prev = prev; /* for gcc */
1207 return EXIT_SUCCESS;
1208 name_len = strlen(name);
1211 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1212 if (cur->flg_read_only) {
1213 bb_error_msg("%s: readonly variable", name);
1214 return EXIT_FAILURE;
1216 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1217 * is ro, and we cannot reach this code on the 1st pass */
1218 prev->next = cur->next;
1219 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1220 bb_unsetenv(cur->varstr);
1224 return EXIT_SUCCESS;
1229 return EXIT_SUCCESS;
1232 #if ENABLE_SH_MATH_SUPPORT
1233 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1234 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1235 static char *endofname(const char *name)
1243 if (!is_in_name(*p))
1249 static void arith_set_local_var(const char *name, const char *val, int flags)
1251 /* arith code doesnt malloc space, so do it for it */
1252 char *var = xasprintf("%s=%s", name, val);
1253 set_local_var(var, flags, 0);
1261 static int static_get(struct in_str *i)
1270 static int static_peek(struct in_str *i)
1275 #if ENABLE_HUSH_INTERACTIVE
1277 static void cmdedit_set_initial_prompt(void)
1279 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1280 G.PS1 = getenv("PS1");
1287 static const char* setup_prompt_string(int promptmode)
1289 const char *prompt_str;
1290 debug_printf("setup_prompt_string %d ", promptmode);
1291 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1292 /* Set up the prompt */
1293 if (promptmode == 0) { /* PS1 */
1295 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1300 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1301 debug_printf("result '%s'\n", prompt_str);
1305 static void get_user_input(struct in_str *i)
1308 const char *prompt_str;
1310 prompt_str = setup_prompt_string(i->promptmode);
1311 #if ENABLE_FEATURE_EDITING
1312 /* Enable command line editing only while a command line
1313 * is actually being read */
1316 /* buglet: SIGINT will not make new prompt to appear _at once_,
1317 * only after <Enter>. (^C will work) */
1318 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1319 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1320 check_and_run_traps(0);
1321 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1322 i->eof_flag = (r < 0);
1323 if (i->eof_flag) { /* EOF/error detected */
1324 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1325 G.user_input_buf[1] = '\0';
1330 fputs(prompt_str, stdout);
1332 G.user_input_buf[0] = r = fgetc(i->file);
1333 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1334 //do we need check_and_run_traps(0)? (maybe only if stdin)
1335 } while (G.flag_SIGINT);
1336 i->eof_flag = (r == EOF);
1338 i->p = G.user_input_buf;
1341 #endif /* INTERACTIVE */
1343 /* This is the magic location that prints prompts
1344 * and gets data back from the user */
1345 static int file_get(struct in_str *i)
1349 /* If there is data waiting, eat it up */
1350 if (i->p && *i->p) {
1351 #if ENABLE_HUSH_INTERACTIVE
1355 if (i->eof_flag && !*i->p)
1357 /* note: ch is never NUL */
1359 /* need to double check i->file because we might be doing something
1360 * more complicated by now, like sourcing or substituting. */
1361 #if ENABLE_HUSH_INTERACTIVE
1362 if (G_interactive_fd && i->promptme && i->file == stdin) {
1365 } while (!*i->p); /* need non-empty line */
1366 i->promptmode = 1; /* PS2 */
1371 do ch = fgetc(i->file); while (ch == '\0');
1373 debug_printf("file_get: got '%c' %d\n", ch, ch);
1374 #if ENABLE_HUSH_INTERACTIVE
1381 /* All callers guarantee this routine will never
1382 * be used right after a newline, so prompting is not needed.
1384 static int file_peek(struct in_str *i)
1387 if (i->p && *i->p) {
1388 if (i->eof_flag && !i->p[1])
1391 /* note: ch is never NUL */
1393 do ch = fgetc(i->file); while (ch == '\0');
1394 i->eof_flag = (ch == EOF);
1395 i->peek_buf[0] = ch;
1396 i->peek_buf[1] = '\0';
1398 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1402 static void setup_file_in_str(struct in_str *i, FILE *f)
1404 i->peek = file_peek;
1406 #if ENABLE_HUSH_INTERACTIVE
1408 i->promptmode = 0; /* PS1 */
1414 static void setup_string_in_str(struct in_str *i, const char *s)
1416 i->peek = static_peek;
1417 i->get = static_get;
1418 #if ENABLE_HUSH_INTERACTIVE
1420 i->promptmode = 0; /* PS1 */
1430 #define B_CHUNK (32 * sizeof(char*))
1432 static void o_reset(o_string *o)
1440 static void o_free(o_string *o)
1443 memset(o, 0, sizeof(*o));
1446 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1451 static void o_grow_by(o_string *o, int len)
1453 if (o->length + len > o->maxlen) {
1454 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1455 o->data = xrealloc(o->data, 1 + o->maxlen);
1459 static void o_addchr(o_string *o, int ch)
1461 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1463 o->data[o->length] = ch;
1465 o->data[o->length] = '\0';
1468 static void o_addblock(o_string *o, const char *str, int len)
1471 memcpy(&o->data[o->length], str, len);
1473 o->data[o->length] = '\0';
1477 static void o_addstr(o_string *o, const char *str)
1479 o_addblock(o, str, strlen(str));
1481 static void nommu_addchr(o_string *o, int ch)
1487 #define nommu_addchr(o, str) ((void)0)
1490 static void o_addstr_with_NUL(o_string *o, const char *str)
1492 o_addblock(o, str, strlen(str) + 1);
1495 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1500 && (*str != '*' && *str != '?' && *str != '[')
1508 /* My analysis of quoting semantics tells me that state information
1509 * is associated with a destination, not a source.
1511 static void o_addqchr(o_string *o, int ch)
1514 char *found = strchr("*?[\\", ch);
1519 o->data[o->length] = '\\';
1522 o->data[o->length] = ch;
1524 o->data[o->length] = '\0';
1527 static void o_addQchr(o_string *o, int ch)
1530 if (o->o_escape && strchr("*?[\\", ch)) {
1532 o->data[o->length] = '\\';
1536 o->data[o->length] = ch;
1538 o->data[o->length] = '\0';
1541 static void o_addQstr(o_string *o, const char *str, int len)
1544 o_addblock(o, str, len);
1550 int ordinary_cnt = strcspn(str, "*?[\\");
1551 if (ordinary_cnt > len) /* paranoia */
1553 o_addblock(o, str, ordinary_cnt);
1554 if (ordinary_cnt == len)
1556 str += ordinary_cnt;
1557 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1561 if (ch) { /* it is necessarily one of "*?[\\" */
1563 o->data[o->length] = '\\';
1567 o->data[o->length] = ch;
1569 o->data[o->length] = '\0';
1573 /* A special kind of o_string for $VAR and `cmd` expansion.
1574 * It contains char* list[] at the beginning, which is grown in 16 element
1575 * increments. Actual string data starts at the next multiple of 16 * (char*).
1576 * list[i] contains an INDEX (int!) into this string data.
1577 * It means that if list[] needs to grow, data needs to be moved higher up
1578 * but list[i]'s need not be modified.
1579 * NB: remembering how many list[i]'s you have there is crucial.
1580 * o_finalize_list() operation post-processes this structure - calculates
1581 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1583 #if DEBUG_EXPAND || DEBUG_GLOB
1584 static void debug_print_list(const char *prefix, o_string *o, int n)
1586 char **list = (char**)o->data;
1587 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1589 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1590 prefix, list, n, string_start, o->length, o->maxlen);
1592 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1593 o->data + (int)list[i] + string_start,
1594 o->data + (int)list[i] + string_start);
1598 const char *p = o->data + (int)list[n - 1] + string_start;
1599 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1603 #define debug_print_list(prefix, o, n) ((void)0)
1606 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1607 * in list[n] so that it points past last stored byte so far.
1608 * It returns n+1. */
1609 static int o_save_ptr_helper(o_string *o, int n)
1611 char **list = (char**)o->data;
1615 if (!o->has_empty_slot) {
1616 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1617 string_len = o->length - string_start;
1618 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1619 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1620 /* list[n] points to string_start, make space for 16 more pointers */
1621 o->maxlen += 0x10 * sizeof(list[0]);
1622 o->data = xrealloc(o->data, o->maxlen + 1);
1623 list = (char**)o->data;
1624 memmove(list + n + 0x10, list + n, string_len);
1625 o->length += 0x10 * sizeof(list[0]);
1627 debug_printf_list("list[%d]=%d string_start=%d\n",
1628 n, string_len, string_start);
1631 /* We have empty slot at list[n], reuse without growth */
1632 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1633 string_len = o->length - string_start;
1634 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1635 n, string_len, string_start);
1636 o->has_empty_slot = 0;
1638 list[n] = (char*)(ptrdiff_t)string_len;
1642 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1643 static int o_get_last_ptr(o_string *o, int n)
1645 char **list = (char**)o->data;
1646 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1648 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1651 /* o_glob performs globbing on last list[], saving each result
1652 * as a new list[]. */
1653 static int o_glob(o_string *o, int n)
1659 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1661 return o_save_ptr_helper(o, n);
1662 pattern = o->data + o_get_last_ptr(o, n);
1663 debug_printf_glob("glob pattern '%s'\n", pattern);
1664 if (!glob_needed(pattern)) {
1666 o->length = unbackslash(pattern) - o->data;
1667 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1668 return o_save_ptr_helper(o, n);
1671 memset(&globdata, 0, sizeof(globdata));
1672 gr = glob(pattern, 0, NULL, &globdata);
1673 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1674 if (gr == GLOB_NOSPACE)
1675 bb_error_msg_and_die("out of memory during glob");
1676 if (gr == GLOB_NOMATCH) {
1677 globfree(&globdata);
1680 if (gr != 0) { /* GLOB_ABORTED ? */
1681 //TODO: testcase for bad glob pattern behavior
1682 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1684 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1685 char **argv = globdata.gl_pathv;
1686 o->length = pattern - o->data; /* "forget" pattern */
1688 o_addstr_with_NUL(o, *argv);
1689 n = o_save_ptr_helper(o, n);
1695 globfree(&globdata);
1697 debug_print_list("o_glob returning", o, n);
1701 /* If o->o_glob == 1, glob the string so far remembered.
1702 * Otherwise, just finish current list[] and start new */
1703 static int o_save_ptr(o_string *o, int n)
1705 if (o->o_glob) { /* if globbing is requested */
1706 /* If o->has_empty_slot, list[n] was already globbed
1707 * (if it was requested back then when it was filled)
1708 * so don't do that again! */
1709 if (!o->has_empty_slot)
1710 return o_glob(o, n); /* o_save_ptr_helper is inside */
1712 return o_save_ptr_helper(o, n);
1715 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1716 static char **o_finalize_list(o_string *o, int n)
1721 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1723 debug_print_list("finalized", o, n);
1724 debug_printf_expand("finalized n:%d\n", n);
1725 list = (char**)o->data;
1726 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1730 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1736 /* Expansion can recurse */
1737 #if ENABLE_HUSH_TICK
1738 static int process_command_subs(o_string *dest, const char *s);
1740 static char *expand_string_to_string(const char *str);
1742 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1743 parse_stream_dquoted(dest, input, dquote_end)
1745 static int parse_stream_dquoted(o_string *as_string,
1747 struct in_str *input,
1750 /* expand_strvec_to_strvec() takes a list of strings, expands
1751 * all variable references within and returns a pointer to
1752 * a list of expanded strings, possibly with larger number
1753 * of strings. (Think VAR="a b"; echo $VAR).
1754 * This new list is allocated as a single malloc block.
1755 * NULL-terminated list of char* pointers is at the beginning of it,
1756 * followed by strings themself.
1757 * Caller can deallocate entire list by single free(list). */
1759 /* Store given string, finalizing the word and starting new one whenever
1760 * we encounter IFS char(s). This is used for expanding variable values.
1761 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1762 static int expand_on_ifs(o_string *output, int n, const char *str)
1765 int word_len = strcspn(str, G.ifs);
1767 if (output->o_escape || !output->o_glob)
1768 o_addQstr(output, str, word_len);
1769 else /* protect backslashes against globbing up :) */
1770 o_addblock_duplicate_backslash(output, str, word_len);
1773 if (!*str) /* EOL - do not finalize word */
1775 o_addchr(output, '\0');
1776 debug_print_list("expand_on_ifs", output, n);
1777 n = o_save_ptr(output, n);
1778 str += strspn(str, G.ifs); /* skip ifs chars */
1780 debug_print_list("expand_on_ifs[1]", output, n);
1784 /* Helper to expand $((...)) and heredoc body. These act as if
1785 * they are in double quotes, with the exception that they are not :).
1786 * Just the rules are similar: "expand only $var and `cmd`"
1788 * Returns malloced string.
1789 * As an optimization, we return NULL if expansion is not needed.
1791 static char *expand_pseudo_dquoted(const char *str)
1794 struct in_str input;
1795 o_string dest = NULL_O_STRING;
1797 if (strchr(str, '$') == NULL
1798 #if ENABLE_HUSH_TICK
1799 && strchr(str, '`') == NULL
1805 /* We need to expand. Example:
1806 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1808 setup_string_in_str(&input, str);
1809 parse_stream_dquoted(NULL, &dest, &input, EOF);
1810 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1811 exp_str = expand_string_to_string(dest.data);
1812 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1813 o_free_unsafe(&dest);
1817 /* Expand all variable references in given string, adding words to list[]
1818 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1819 * to be filled). This routine is extremely tricky: has to deal with
1820 * variables/parameters with whitespace, $* and $@, and constructs like
1821 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1822 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1824 /* or_mask is either 0 (normal case) or 0x80
1825 * (expansion of right-hand side of assignment == 1-element expand.
1826 * It will also do no globbing, and thus we must not backslash-quote!) */
1828 char first_ch, ored_ch;
1836 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1837 debug_print_list("expand_vars_to_list", output, n);
1838 n = o_save_ptr(output, n);
1839 debug_print_list("expand_vars_to_list[0]", output, n);
1841 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1842 #if ENABLE_HUSH_TICK
1843 o_string subst_result = NULL_O_STRING;
1845 #if ENABLE_SH_MATH_SUPPORT
1846 char arith_buf[sizeof(arith_t)*3 + 2];
1848 o_addblock(output, arg, p - arg);
1849 debug_print_list("expand_vars_to_list[1]", output, n);
1851 p = strchr(p, SPECIAL_VAR_SYMBOL);
1853 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1854 /* "$@" is special. Even if quoted, it can still
1855 * expand to nothing (not even an empty string) */
1856 if ((first_ch & 0x7f) != '@')
1857 ored_ch |= first_ch;
1860 switch (first_ch & 0x7f) {
1861 /* Highest bit in first_ch indicates that var is double-quoted */
1863 val = utoa(G.root_pid);
1865 case '!': /* bg pid */
1866 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1868 case '?': /* exitcode */
1869 val = utoa(G.last_exitcode);
1871 case '#': /* argc */
1872 if (arg[1] != SPECIAL_VAR_SYMBOL)
1873 /* actually, it's a ${#var} */
1875 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1880 if (!G.global_argv[i])
1882 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1883 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1884 smallint sv = output->o_escape;
1885 /* unquoted var's contents should be globbed, so don't escape */
1886 output->o_escape = 0;
1887 while (G.global_argv[i]) {
1888 n = expand_on_ifs(output, n, G.global_argv[i]);
1889 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1890 if (G.global_argv[i++][0] && G.global_argv[i]) {
1891 /* this argv[] is not empty and not last:
1892 * put terminating NUL, start new word */
1893 o_addchr(output, '\0');
1894 debug_print_list("expand_vars_to_list[2]", output, n);
1895 n = o_save_ptr(output, n);
1896 debug_print_list("expand_vars_to_list[3]", output, n);
1899 output->o_escape = sv;
1901 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1902 * and in this case should treat it like '$*' - see 'else...' below */
1903 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1905 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1906 if (++i >= G.global_argc)
1908 o_addchr(output, '\0');
1909 debug_print_list("expand_vars_to_list[4]", output, n);
1910 n = o_save_ptr(output, n);
1912 } else { /* quoted $*: add as one word */
1914 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1915 if (!G.global_argv[++i])
1918 o_addchr(output, G.ifs[0]);
1922 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1923 /* "Empty variable", used to make "" etc to not disappear */
1927 #if ENABLE_HUSH_TICK
1928 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1931 //TODO: can we just stuff it into "output" directly?
1932 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1933 process_command_subs(&subst_result, arg);
1934 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1935 val = subst_result.data;
1938 #if ENABLE_SH_MATH_SUPPORT
1939 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1940 arith_eval_hooks_t hooks;
1945 arg++; /* skip '+' */
1946 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1947 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1949 exp_str = expand_pseudo_dquoted(arg);
1950 hooks.lookupvar = get_local_var_value;
1951 hooks.setvar = arith_set_local_var;
1952 hooks.endofname = endofname;
1953 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1957 const char *msg = "error in arithmetic";
1960 msg = "exponent less than 0";
1963 msg = "divide by 0";
1966 msg = "expression recursion loop detected";
1971 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1972 sprintf(arith_buf, arith_t_fmt, res);
1977 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1979 bool exp_len = false;
1980 bool exp_null = false;
1982 char exp_save = exp_save; /* for compiler */
1983 char exp_op = exp_op; /* for compiler */
1984 char *exp_word = exp_word; /* for compiler */
1988 arg[0] = first_ch & 0x7f;
1990 /* prepare for expansions */
1991 if (var[0] == '#') {
1992 /* handle length expansion ${#var} */
1996 /* maybe handle parameter expansion */
1997 exp_off = strcspn(var, ":-=+?%#");
2001 exp_save = var[exp_off];
2002 exp_null = exp_save == ':';
2003 exp_word = var + exp_off;
2006 exp_op = *exp_word++;
2007 var[exp_off] = '\0';
2011 /* lookup the variable in question */
2012 if (isdigit(var[0])) {
2013 /* handle_dollar() should have vetted var for us */
2015 if (i < G.global_argc)
2016 val = G.global_argv[i];
2017 /* else val remains NULL: $N with too big N */
2019 val = get_local_var_value(var);
2021 /* handle any expansions */
2023 debug_printf_expand("expand: length of '%s' = ", val);
2024 val = utoa(val ? strlen(val) : 0);
2025 debug_printf_expand("%s\n", val);
2026 } else if (exp_off) {
2027 if (exp_op == '%' || exp_op == '#') {
2028 /* we need to do a pattern match */
2031 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
2032 if (exp_op == *exp_word) /* ## or %% */
2034 val = dyn_val = xstrdup(val);
2035 loc = scan(dyn_val, exp_word, zero);
2041 /* we need to do an expansion */
2042 int exp_test = (!val || (exp_null && !val[0]));
2044 exp_test = !exp_test;
2045 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2046 exp_null ? "true" : "false", exp_test);
2048 if (exp_op == '?') {
2049 //TODO: how interactive bash aborts expansion mid-command?
2050 /* ${var?[error_msg_if_unset]} */
2051 /* ${var:?[error_msg_if_unset_or_null]} */
2052 /* mimic bash message */
2053 die_if_script("%s: %s",
2055 exp_word[0] ? exp_word : "parameter null or not set"
2061 if (exp_op == '=') {
2062 /* ${var=[word]} or ${var:=[word]} */
2063 if (isdigit(var[0]) || var[0] == '#') {
2064 /* mimic bash message */
2065 die_if_script("$%s: cannot assign in this way", var);
2068 char *new_var = xasprintf("%s=%s", var, val);
2069 set_local_var(new_var, -1, 0);
2075 var[exp_off] = exp_save;
2079 #if ENABLE_HUSH_TICK
2082 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2083 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2085 /* unquoted var's contents should be globbed, so don't escape */
2086 smallint sv = output->o_escape;
2087 output->o_escape = 0;
2088 n = expand_on_ifs(output, n, val);
2090 output->o_escape = sv;
2092 } else { /* quoted $VAR, val will be appended below */
2093 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2096 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2098 o_addQstr(output, val, strlen(val));
2102 /* Do the check to avoid writing to a const string */
2103 if (*p != SPECIAL_VAR_SYMBOL)
2104 *p = SPECIAL_VAR_SYMBOL;
2106 #if ENABLE_HUSH_TICK
2107 o_free(&subst_result);
2110 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2113 debug_print_list("expand_vars_to_list[a]", output, n);
2114 /* this part is literal, and it was already pre-quoted
2115 * if needed (much earlier), do not use o_addQstr here! */
2116 o_addstr_with_NUL(output, arg);
2117 debug_print_list("expand_vars_to_list[b]", output, n);
2118 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2119 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2122 /* allow to reuse list[n] later without re-growth */
2123 output->has_empty_slot = 1;
2125 o_addchr(output, '\0');
2130 static char **expand_variables(char **argv, int or_mask)
2135 o_string output = NULL_O_STRING;
2137 if (or_mask & 0x100) {
2138 output.o_escape = 1; /* protect against globbing for "$var" */
2139 /* (unquoted $var will temporarily switch it off) */
2146 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2149 debug_print_list("expand_variables", &output, n);
2151 /* output.data (malloced in one block) gets returned in "list" */
2152 list = o_finalize_list(&output, n);
2153 debug_print_strings("expand_variables[1]", list);
2157 static char **expand_strvec_to_strvec(char **argv)
2159 return expand_variables(argv, 0x100);
2162 /* Used for expansion of right hand of assignments */
2163 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2165 static char *expand_string_to_string(const char *str)
2167 char *argv[2], **list;
2169 argv[0] = (char*)str;
2171 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2173 if (!list[0] || list[1])
2174 bb_error_msg_and_die("BUG in varexp2");
2175 /* actually, just move string 2*sizeof(char*) bytes back */
2176 overlapping_strcpy((char*)list, list[0]);
2177 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2181 /* Used for "eval" builtin */
2182 static char* expand_strvec_to_string(char **argv)
2186 list = expand_variables(argv, 0x80);
2187 /* Convert all NULs to spaces */
2192 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2193 bb_error_msg_and_die("BUG in varexp3");
2194 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2198 overlapping_strcpy((char*)list, list[0]);
2199 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2203 static char **expand_assignments(char **argv, int count)
2207 /* Expand assignments into one string each */
2208 for (i = 0; i < count; i++) {
2209 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2216 void re_execute_shell(const char *s, int is_heredoc); /* never called */
2217 #define clean_up_after_re_execute() ((void)0)
2218 static void reset_traps_to_defaults(void)
2226 for (sig = 0; sig < NSIG; sig++) {
2230 G.traps[sig] = NULL;
2231 /* There is no signal for 0 (EXIT) */
2234 /* there was a trap handler, we are removing it
2235 * (if sig has non-DFL handling,
2236 * we don't need to do anything) */
2237 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2239 sigdelset(&G.blocked_set, sig);
2243 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2248 static void re_execute_shell(const char *s, int is_heredoc) NORETURN;
2249 static void re_execute_shell(const char *s, int is_heredoc)
2251 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2252 char *heredoc_argv[4];
2253 struct variable *cur;
2254 char **argv, **pp, **pp2;
2258 argv = heredoc_argv;
2259 argv[0] = (char *) G.argv0_for_re_execing;
2260 argv[1] = (char *) "-<";
2261 argv[2] = (char *) s;
2263 pp = &argv[3]; /* used as pointer to empty environment */
2267 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2268 , (unsigned) G.root_pid
2269 , (unsigned) G.last_bg_pid
2270 , (unsigned) G.last_exitcode
2271 USE_HUSH_LOOPS(, G.depth_of_loop)
2273 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2274 * 3:-c 4:<cmd> <argN...> 5:NULL
2276 cnt = 5 + G.global_argc;
2277 for (cur = G.top_var; cur; cur = cur->next) {
2278 if (!cur->flg_export || cur->flg_read_only)
2281 G.argv_from_re_execing = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2282 *pp++ = (char *) G.argv0_for_re_execing;
2284 for (cur = G.top_var; cur; cur = cur->next) {
2285 if (cur->varstr == hush_version_str)
2287 if (cur->flg_read_only) {
2288 *pp++ = (char *) "-R";
2289 *pp++ = cur->varstr;
2290 } else if (!cur->flg_export) {
2291 *pp++ = (char *) "-V";
2292 *pp++ = cur->varstr;
2295 //TODO: pass functions
2296 /* We can pass activated traps here. Say, -Tnn:trap_string
2298 * However, POSIX says that subshells reset signals with traps
2300 * I tested bash-3.2 and it not only does that with true subshells
2301 * of the form ( list ), but with any forked children shells.
2302 * I set trap "echo W" WINCH; and then tried:
2304 * { echo 1; sleep 20; echo 2; } &
2305 * while true; do echo 1; sleep 20; echo 2; break; done &
2306 * true | { echo 1; sleep 20; echo 2; } | cat
2308 * In all these cases sending SIGWINCH to the child shell
2309 * did not run the trap. If I add trap "echo V" WINCH;
2310 * _inside_ group (just before echo 1), it works.
2312 * I conclude it means we don't need to pass active traps here.
2313 * exec syscall below resets them to SIG_DFL for us.
2315 *pp++ = (char *) "-c";
2317 pp2 = G.global_argv;
2320 /* *pp = NULL; - is already there */
2324 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2325 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2326 execve(bb_busybox_exec_path, argv, pp);
2327 /* Fallback. Useful for init=/bin/hush usage etc */
2328 if (argv[0][0] == '/')
2329 execve(argv[0], argv, pp);
2330 xfunc_error_retval = 127;
2331 bb_error_msg_and_die("can't re-execute the shell");
2334 static void clean_up_after_re_execute(void)
2336 char **pp = G.argv_from_re_execing;
2338 /* Must match re_execute_shell's allocations (if any) */
2340 G.argv_from_re_execing = NULL;
2343 #endif /* !BB_MMU */
2346 static void setup_heredoc(struct redir_struct *redir)
2348 struct fd_pair pair;
2351 /* the _body_ of heredoc (misleading field name) */
2352 const char *heredoc = redir->rd_filename;
2356 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2357 expanded = expand_pseudo_dquoted(heredoc);
2361 len = strlen(heredoc);
2363 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2365 xmove_fd(pair.rd, redir->rd_fd);
2367 /* Try writing without forking. Newer kernels have
2368 * dynamically growing pipes. Must use non-blocking write! */
2371 written = write(pair.wr, heredoc, len);
2382 ndelay_off(pair.wr);
2384 /* Okay, pipe buffer was not big enough */
2385 /* Note: we must not create a stray child (bastard? :)
2386 * for the unsuspecting parent process. Child creates a grandchild
2387 * and exits before parent execs the process which consumes heredoc
2388 * (that exec happens after we return from this function) */
2391 bb_perror_msg_and_die("vfork");
2394 pid = BB_MMU ? fork() : vfork();
2396 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2400 close(redir->rd_fd); /* read side of the pipe */
2402 full_write(pair.wr, heredoc, len); /* may loop or block */
2405 /* Delegate blocking writes to another process */
2406 disable_restore_tty_pgrp_on_exit();
2407 xmove_fd(pair.wr, STDOUT_FILENO);
2408 re_execute_shell(heredoc, 1);
2412 enable_restore_tty_pgrp_on_exit();
2413 clean_up_after_re_execute();
2416 wait(NULL); /* wait till child has died */
2419 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2420 * and stderr if they are redirected. */
2421 static int setup_redirects(struct command *prog, int squirrel[])
2424 struct redir_struct *redir;
2426 for (redir = prog->redirects; redir; redir = redir->next) {
2427 if (redir->rd_type == REDIRECT_HEREDOC2) {
2428 if (squirrel && redir->rd_fd < 3) {
2429 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2431 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2433 debug_printf_parse("set heredoc '%s'\n",
2434 redir->rd_filename);
2435 setup_heredoc(redir);
2439 if (redir->rd_dup == -1) {
2441 if (redir->rd_filename == NULL) {
2442 /* Something went wrong in the parse.
2443 * Pretend it didn't happen */
2446 mode = redir_table[redir->rd_type].mode;
2447 //TODO: check redir for names like '\\'
2448 p = expand_string_to_string(redir->rd_filename);
2449 openfd = open_or_warn(p, mode);
2452 /* this could get lost if stderr has been redirected, but
2453 * bash and ash both lose it as well (though zsh doesn't!) */
2454 //what the above comment tries to say?
2458 openfd = redir->rd_dup;
2461 if (openfd != redir->rd_fd) {
2462 if (squirrel && redir->rd_fd < 3) {
2463 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2465 if (openfd == REDIRFD_CLOSE) {
2466 /* "n>-" means "close me" */
2467 close(redir->rd_fd);
2469 xdup2(openfd, redir->rd_fd);
2470 if (redir->rd_dup == -1)
2478 static void restore_redirects(int squirrel[])
2481 for (i = 0; i < 3; i++) {
2484 /* We simply die on error */
2492 #define free_pipe_list(head, indent) free_pipe_list(head)
2493 #define free_pipe(pi, indent) free_pipe(pi)
2495 static void free_pipe_list(struct pipe *head, int indent);
2497 /* Return code is the exit status of the pipe */
2498 static void free_pipe(struct pipe *pi, int indent)
2501 struct command *command;
2502 struct redir_struct *r, *rnext;
2505 if (pi->stopped_cmds > 0) /* why? */
2507 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2508 for (i = 0; i < pi->num_cmds; i++) {
2509 command = &pi->cmds[i];
2510 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2511 if (command->argv) {
2512 for (a = 0, p = command->argv; *p; a++, p++) {
2513 debug_printf_clean("%s argv[%d] = %s\n",
2514 indenter(indent), a, *p);
2516 free_strings(command->argv);
2517 command->argv = NULL;
2519 /* not "else if": on syntax error, we may have both! */
2520 if (command->group) {
2521 debug_printf_clean("%s begin group (grp_type:%d)\n",
2522 indenter(indent), command->grp_type);
2523 free_pipe_list(command->group, indent+3);
2524 debug_printf_clean("%s end group\n", indenter(indent));
2525 command->group = NULL;
2528 free(command->group_as_string);
2529 command->group_as_string = NULL;
2531 for (r = command->redirects; r; r = rnext) {
2532 debug_printf_clean("%s redirect %d%s", indenter(indent),
2533 r->fd, redir_table[r->rd_type].descrip);
2534 /* guard against the case >$FOO, where foo is unset or blank */
2535 if (r->rd_filename) {
2536 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2537 free(r->rd_filename);
2538 r->rd_filename = NULL;
2540 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2544 command->redirects = NULL;
2546 free(pi->cmds); /* children are an array, they get freed all at once */
2554 static void free_pipe_list(struct pipe *head, int indent)
2556 struct pipe *pi, *next;
2558 for (pi = head; pi; pi = next) {
2560 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2562 free_pipe(pi, indent);
2563 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2565 /*pi->next = NULL;*/
2572 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2573 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2574 #define pseudo_exec(nommu_save, command, argv_expanded) \
2575 pseudo_exec(command, argv_expanded)
2578 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2580 * XXX no exit() here. If you don't exec, use _exit instead.
2581 * The at_exit handlers apparently confuse the calling process,
2582 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2583 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2584 char **argv, int assignment_cnt,
2585 char **argv_expanded) NORETURN;
2586 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2587 char **argv, int assignment_cnt,
2588 char **argv_expanded)
2592 /* Case when we are here: ... | var=val | ... */
2593 if (!argv[assignment_cnt])
2594 _exit(EXIT_SUCCESS);
2596 new_env = expand_assignments(argv, assignment_cnt);
2598 putenv_all(new_env);
2599 free(new_env); /* optional */
2601 nommu_save->new_env = new_env;
2602 nommu_save->old_env = putenv_all_and_save_old(new_env);
2604 if (argv_expanded) {
2605 argv = argv_expanded;
2607 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2609 nommu_save->argv = argv;
2613 /* On NOMMU, we must never block!
2614 * Example: { sleep 99999 | read line } & echo Ok
2615 * read builtin will block on read syscall, leaving parent blocked
2616 * in vfork. Therefore we can't do this:
2619 /* Check if the command matches any of the builtins.
2620 * Depending on context, this might be redundant. But it's
2621 * easier to waste a few CPU cycles than it is to figure out
2622 * if this is one of those cases.
2626 const struct built_in_command *x;
2627 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2628 if (strcmp(argv[0], x->cmd) == 0) {
2629 debug_printf_exec("running builtin '%s'\n",
2631 rcode = x->function(argv);
2639 #if ENABLE_FEATURE_SH_STANDALONE
2640 /* Check if the command matches any busybox applets */
2641 if (strchr(argv[0], '/') == NULL) {
2642 int a = find_applet_by_name(argv[0]);
2644 #if BB_MMU /* see above why on NOMMU it is not allowed */
2645 if (APPLET_IS_NOEXEC(a)) {
2646 debug_printf_exec("running applet '%s'\n", argv[0]);
2647 run_applet_no_and_exit(a, argv);
2650 /* Re-exec ourselves */
2651 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2652 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2653 execv(bb_busybox_exec_path, argv);
2654 /* If they called chroot or otherwise made the binary no longer
2655 * executable, fall through */
2660 debug_printf_exec("execing '%s'\n", argv[0]);
2661 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2662 execvp(argv[0], argv);
2663 bb_perror_msg("can't exec '%s'", argv[0]);
2664 _exit(EXIT_FAILURE);
2667 static int run_list(struct pipe *pi);
2669 /* Called after [v]fork() in run_pipe
2671 static void pseudo_exec(nommu_save_t *nommu_save,
2672 struct command *command,
2673 char **argv_expanded) NORETURN;
2674 static void pseudo_exec(nommu_save_t *nommu_save,
2675 struct command *command,
2676 char **argv_expanded)
2678 if (command->argv) {
2679 pseudo_exec_argv(nommu_save, command->argv,
2680 command->assignment_cnt, argv_expanded);
2683 if (command->group) {
2684 /* Cases when we are here:
2687 * ... | ( list ) | ...
2688 * ... | { list } | ...
2692 debug_printf_exec("pseudo_exec: run_list\n");
2693 reset_traps_to_defaults();
2694 rcode = run_list(command->group);
2695 /* OK to leak memory by not calling free_pipe_list,
2696 * since this process is about to exit */
2699 re_execute_shell(command->group_as_string, 0);
2703 /* Case when we are here: ... | >file */
2704 debug_printf_exec("pseudo_exec'ed null command\n");
2705 _exit(EXIT_SUCCESS);
2709 static const char *get_cmdtext(struct pipe *pi)
2715 /* This is subtle. ->cmdtext is created only on first backgrounding.
2716 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2717 * On subsequent bg argv is trashed, but we won't use it */
2720 argv = pi->cmds[0].argv;
2721 if (!argv || !argv[0]) {
2722 pi->cmdtext = xzalloc(1);
2727 do len += strlen(*argv) + 1; while (*++argv);
2728 pi->cmdtext = p = xmalloc(len);
2729 argv = pi->cmds[0].argv;
2731 len = strlen(*argv);
2732 memcpy(p, *argv, len);
2740 static void insert_bg_job(struct pipe *pi)
2742 struct pipe *thejob;
2745 /* Linear search for the ID of the job to use */
2747 for (thejob = G.job_list; thejob; thejob = thejob->next)
2748 if (thejob->jobid >= pi->jobid)
2749 pi->jobid = thejob->jobid + 1;
2751 /* Add thejob to the list of running jobs */
2753 thejob = G.job_list = xmalloc(sizeof(*thejob));
2755 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2757 thejob->next = xmalloc(sizeof(*thejob));
2758 thejob = thejob->next;
2761 /* Physically copy the struct job */
2762 memcpy(thejob, pi, sizeof(struct pipe));
2763 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2764 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2765 for (i = 0; i < pi->num_cmds; i++) {
2766 // TODO: do we really need to have so many fields which are just dead weight
2767 // at execution stage?
2768 thejob->cmds[i].pid = pi->cmds[i].pid;
2769 /* all other fields are not used and stay zero */
2771 thejob->next = NULL;
2772 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2774 /* We don't wait for background thejobs to return -- append it
2775 to the list of backgrounded thejobs and leave it alone */
2776 if (G_interactive_fd)
2777 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2778 G.last_bg_pid = thejob->cmds[0].pid;
2779 G.last_jobid = thejob->jobid;
2782 static void remove_bg_job(struct pipe *pi)
2784 struct pipe *prev_pipe;
2786 if (pi == G.job_list) {
2787 G.job_list = pi->next;
2789 prev_pipe = G.job_list;
2790 while (prev_pipe->next != pi)
2791 prev_pipe = prev_pipe->next;
2792 prev_pipe->next = pi->next;
2795 G.last_jobid = G.job_list->jobid;
2800 /* Remove a backgrounded job */
2801 static void delete_finished_bg_job(struct pipe *pi)
2804 pi->stopped_cmds = 0;
2810 /* Check to see if any processes have exited -- if they
2811 * have, figure out why and see if a job has completed */
2812 static int checkjobs(struct pipe* fg_pipe)
2822 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2825 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2826 // /* avoid doing syscall, nothing there anyway */
2829 attributes = WUNTRACED;
2830 if (fg_pipe == NULL)
2831 attributes |= WNOHANG;
2833 /* Do we do this right?
2834 * bash-3.00# sleep 20 | false
2836 * [3]+ Stopped sleep 20 | false
2837 * bash-3.00# echo $?
2838 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2841 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2842 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2843 // + killall -STOP cat
2850 // i = G.count_SIGCHLD;
2851 childpid = waitpid(-1, &status, attributes);
2852 if (childpid <= 0) {
2853 if (childpid && errno != ECHILD)
2854 bb_perror_msg("waitpid");
2855 // else /* Until next SIGCHLD, waitpid's are useless */
2856 // G.handled_SIGCHLD = i;
2859 dead = WIFEXITED(status) || WIFSIGNALED(status);
2862 if (WIFSTOPPED(status))
2863 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2864 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2865 if (WIFSIGNALED(status))
2866 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2867 childpid, WTERMSIG(status), WEXITSTATUS(status));
2868 if (WIFEXITED(status))
2869 debug_printf_jobs("pid %d exited, exitcode %d\n",
2870 childpid, WEXITSTATUS(status));
2872 /* Were we asked to wait for fg pipe? */
2874 for (i = 0; i < fg_pipe->num_cmds; i++) {
2875 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2876 if (fg_pipe->cmds[i].pid != childpid)
2878 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2880 fg_pipe->cmds[i].pid = 0;
2881 fg_pipe->alive_cmds--;
2882 if (i == fg_pipe->num_cmds - 1) {
2883 /* last process gives overall exitstatus */
2884 rcode = WEXITSTATUS(status);
2885 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2888 fg_pipe->cmds[i].is_stopped = 1;
2889 fg_pipe->stopped_cmds++;
2891 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2892 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2893 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2894 /* All processes in fg pipe have exited/stopped */
2896 if (fg_pipe->alive_cmds)
2897 insert_bg_job(fg_pipe);
2901 /* There are still running processes in the fg pipe */
2902 goto wait_more; /* do waitpid again */
2904 /* it wasnt fg_pipe, look for process in bg pipes */
2908 /* We asked to wait for bg or orphaned children */
2909 /* No need to remember exitcode in this case */
2910 for (pi = G.job_list; pi; pi = pi->next) {
2911 for (i = 0; i < pi->num_cmds; i++) {
2912 if (pi->cmds[i].pid == childpid)
2913 goto found_pi_and_prognum;
2916 /* Happens when shell is used as init process (init=/bin/sh) */
2917 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2918 continue; /* do waitpid again */
2920 found_pi_and_prognum:
2923 pi->cmds[i].pid = 0;
2925 if (!pi->alive_cmds) {
2926 if (G_interactive_fd)
2927 printf(JOB_STATUS_FORMAT, pi->jobid,
2928 "Done", pi->cmdtext);
2929 delete_finished_bg_job(pi);
2933 pi->cmds[i].is_stopped = 1;
2937 } /* while (waitpid succeeds)... */
2943 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2946 int rcode = checkjobs(fg_pipe);
2947 /* Job finished, move the shell to the foreground */
2948 p = getpgid(0); /* pgid of our process */
2949 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2950 tcsetpgrp(G_interactive_fd, p);
2955 /* Start all the jobs, but don't wait for anything to finish.
2958 * Return code is normally -1, when the caller has to wait for children
2959 * to finish to determine the exit status of the pipe. If the pipe
2960 * is a simple builtin command, however, the action is done by the
2961 * time run_pipe returns, and the exit code is provided as the
2964 * Returns -1 only if started some children. IOW: we have to
2965 * mask out retvals of builtins etc with 0xff!
2967 * The only case when we do not need to [v]fork is when the pipe
2968 * is single, non-backgrounded, non-subshell command. Examples:
2969 * cmd ; ... { list } ; ...
2970 * cmd && ... { list } && ...
2971 * cmd || ... { list } || ...
2972 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2973 * or (if SH_STANDALONE) an applet, and we can run the { list }
2974 * with run_list(). If it isn't one of these, we fork and exec cmd.
2976 * Cases when we must fork:
2977 * non-single: cmd | cmd
2978 * backgrounded: cmd & { list } &
2979 * subshell: ( list ) [&]
2981 static int run_pipe(struct pipe *pi)
2983 static const char *const null_ptr = NULL;
2986 int pipefds[2]; /* pipefds[0] is for reading */
2987 struct command *command;
2988 char **argv_expanded;
2991 /* it is not always needed, but we aim to smaller code */
2992 int squirrel[] = { -1, -1, -1 };
2995 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2997 USE_HUSH_JOB(pi->pgrp = -1;)
2998 pi->stopped_cmds = 0;
2999 command = &(pi->cmds[0]);
3000 argv_expanded = NULL;
3002 if (pi->num_cmds != 1
3003 || pi->followup == PIPE_BG
3004 || command->grp_type == GRP_SUBSHELL
3011 debug_printf_exec(": group:%p argv:'%s'\n",
3012 command->group, command->argv ? command->argv[0] : "NONE");
3014 if (command->group) {
3015 #if ENABLE_HUSH_FUNCTIONS
3016 if (command->grp_type == GRP_FUNCTION) {
3017 /* func () { list } */
3018 bb_error_msg("here we ought to remember function definition, and go on");
3019 return EXIT_SUCCESS;
3023 debug_printf("non-subshell group\n");
3024 rcode = 1; /* exitcode if redir failed */
3025 if (setup_redirects(command, squirrel) == 0) {
3026 debug_printf_exec(": run_list\n");
3027 rcode = run_list(command->group) & 0xff;
3028 debug_printf_exec("run_pipe return %d\n", rcode);
3030 restore_redirects(squirrel);
3031 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3035 argv = command->argv ? command->argv : (char **) &null_ptr;
3037 const struct built_in_command *x;
3038 char **new_env = NULL;
3039 char **old_env = NULL;
3041 if (argv[command->assignment_cnt] == NULL) {
3042 /* Assignments, but no command */
3043 /* Ensure redirects take effect. Try "a=t >file" */
3044 rcode = setup_redirects(command, squirrel);
3045 restore_redirects(squirrel);
3046 /* Set shell variables */
3048 p = expand_string_to_string(*argv);
3049 debug_printf_exec("set shell var:'%s'->'%s'\n",
3051 set_local_var(p, 0, 0);
3054 /* Do we need to flag set_local_var() errors?
3055 * "assignment to readonly var" and "putenv error"
3057 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3061 /* Expand the rest into (possibly) many strings each */
3062 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3064 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
3065 if (strcmp(argv_expanded[0], x->cmd) != 0)
3067 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3068 debug_printf("exec with redirects only\n");
3069 rcode = setup_redirects(command, NULL);
3070 goto clean_up_and_ret1;
3072 debug_printf("builtin inline %s\n", argv_expanded[0]);
3073 /* XXX setup_redirects acts on file descriptors, not FILEs.
3074 * This is perfect for work that comes after exec().
3075 * Is it really safe for inline use? Experimentally,
3076 * things seem to work with glibc. */
3077 rcode = setup_redirects(command, squirrel);
3079 new_env = expand_assignments(argv, command->assignment_cnt);
3080 old_env = putenv_all_and_save_old(new_env);
3081 debug_printf_exec(": builtin '%s' '%s'...\n",
3082 x->cmd, argv_expanded[1]);
3083 rcode = x->function(argv_expanded) & 0xff;
3085 #if ENABLE_FEATURE_SH_STANDALONE
3088 restore_redirects(squirrel);
3089 free_strings_and_unsetenv(new_env, 1);
3090 putenv_all(old_env);
3091 /* Free the pointers, but the strings themselves
3092 * are in environ now, don't use free_strings! */
3095 free(argv_expanded);
3096 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3097 debug_printf_exec("run_pipe return %d\n", rcode);
3100 #if ENABLE_FEATURE_SH_STANDALONE
3101 i = find_applet_by_name(argv_expanded[0]);
3102 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3103 rcode = setup_redirects(command, squirrel);
3105 save_nofork_data(&G.nofork_save);
3106 new_env = expand_assignments(argv, command->assignment_cnt);
3107 old_env = putenv_all_and_save_old(new_env);
3108 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3109 argv_expanded[0], argv_expanded[1]);
3110 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
3112 goto clean_up_and_ret;
3115 /* It is neither builtin nor applet. We must fork. */
3119 /* NB: argv_expanded may already be created, and that
3120 * might include `cmd` runs! Do not rerun it! We *must*
3121 * use argv_expanded if it's non-NULL */
3123 /* Going to fork a child per each pipe member */
3127 for (i = 0; i < pi->num_cmds; i++) {
3129 volatile nommu_save_t nommu_save;
3130 nommu_save.new_env = NULL;
3131 nommu_save.old_env = NULL;
3132 nommu_save.argv = NULL;
3134 command = &(pi->cmds[i]);
3135 if (command->argv) {
3136 debug_printf_exec(": pipe member '%s' '%s'...\n",
3137 command->argv[0], command->argv[1]);
3139 debug_printf_exec(": pipe member with no argv\n");
3142 /* pipes are inserted between pairs of commands */
3145 if ((i + 1) < pi->num_cmds)
3148 command->pid = BB_MMU ? fork() : vfork();
3149 if (!command->pid) { /* child */
3151 disable_restore_tty_pgrp_on_exit();
3153 /* Every child adds itself to new process group
3154 * with pgid == pid_of_first_child_in_pipe */
3155 if (G.run_list_level == 1 && G_interactive_fd) {
3158 if (pgrp < 0) /* true for 1st process only */
3160 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
3161 /* We do it in *every* child, not just first,
3163 tcsetpgrp(G_interactive_fd, pgrp);
3167 xmove_fd(nextin, 0);
3168 xmove_fd(pipefds[1], 1); /* write end */
3170 close(pipefds[0]); /* read end */
3171 /* Like bash, explicit redirects override pipes,
3172 * and the pipe fd is available for dup'ing. */
3173 if (setup_redirects(command, NULL))
3176 /* Restore default handlers just prior to exec */
3177 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3179 /* Stores to nommu_save list of env vars putenv'ed
3180 * (NOMMU, on MMU we don't need that) */
3181 /* cast away volatility... */
3182 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3183 /* pseudo_exec() does not return */
3186 /* parent or error */
3187 enable_restore_tty_pgrp_on_exit();
3189 /* Clean up after vforked child */
3190 clean_up_after_re_execute();
3191 free(nommu_save.argv);
3192 free_strings_and_unsetenv(nommu_save.new_env, 1);
3193 putenv_all(nommu_save.old_env);
3194 /* Free the pointers, but the strings themselves
3195 * are in environ now, don't use free_strings! */
3196 free(nommu_save.old_env);
3198 free(argv_expanded);
3199 argv_expanded = NULL;
3200 if (command->pid < 0) { /* [v]fork failed */
3201 /* Clearly indicate, was it fork or vfork */
3202 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3206 /* Second and next children need to know pid of first one */
3208 pi->pgrp = command->pid;
3214 if ((i + 1) < pi->num_cmds)
3215 close(pipefds[1]); /* write end */
3216 /* Pass read (output) pipe end to next iteration */
3217 nextin = pipefds[0];
3220 if (!pi->alive_cmds) {
3221 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3225 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3229 #ifndef debug_print_tree
3230 static void debug_print_tree(struct pipe *pi, int lvl)
3232 static const char *const PIPE[] = {
3238 static const char *RES[] = {
3239 [RES_NONE ] = "NONE" ,
3242 [RES_THEN ] = "THEN" ,
3243 [RES_ELIF ] = "ELIF" ,
3244 [RES_ELSE ] = "ELSE" ,
3247 #if ENABLE_HUSH_LOOPS
3248 [RES_FOR ] = "FOR" ,
3249 [RES_WHILE] = "WHILE",
3250 [RES_UNTIL] = "UNTIL",
3252 [RES_DONE ] = "DONE" ,
3254 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3257 #if ENABLE_HUSH_CASE
3258 [RES_CASE ] = "CASE" ,
3259 [RES_MATCH] = "MATCH",
3260 [RES_CASEI] = "CASEI",
3261 [RES_ESAC ] = "ESAC" ,
3263 [RES_XXXX ] = "XXXX" ,
3264 [RES_SNTX ] = "SNTX" ,
3266 static const char *const GRPTYPE[] = {
3269 #if ENABLE_HUSH_FUNCTIONS
3278 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3279 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3281 while (prn < pi->num_cmds) {
3282 struct command *command = &pi->cmds[prn];
3283 char **argv = command->argv;
3285 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3287 command->assignment_cnt);
3288 if (command->group) {
3289 fprintf(stderr, " group %s: (argv=%p)\n",
3290 GRPTYPE[command->grp_type],
3292 debug_print_tree(command->group, lvl+1);
3296 if (argv) while (*argv) {
3297 fprintf(stderr, " '%s'", *argv);
3300 fprintf(stderr, "\n");
3309 /* NB: called by pseudo_exec, and therefore must not modify any
3310 * global data until exec/_exit (we can be a child after vfork!) */
3311 static int run_list(struct pipe *pi)
3313 #if ENABLE_HUSH_CASE
3314 char *case_word = NULL;
3316 #if ENABLE_HUSH_LOOPS
3317 struct pipe *loop_top = NULL;
3318 char *for_varname = NULL;
3319 char **for_lcur = NULL;
3320 char **for_list = NULL;
3322 smallint last_followup;
3324 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3325 smalluint cond_code = 0;
3327 enum { cond_code = 0 };
3330 smallint rword; /* enum reserved_style */
3331 smallint last_rword; /* ditto */
3334 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3336 #if ENABLE_HUSH_LOOPS
3337 /* Check syntax for "for" */
3338 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3339 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3341 /* current word is FOR or IN (BOLD in comments below) */
3342 if (cpipe->next == NULL) {
3343 syntax_error("malformed for");
3344 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3347 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3348 if (cpipe->next->res_word == RES_DO)
3350 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3351 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3352 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3354 syntax_error("malformed for");
3355 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3361 /* Past this point, all code paths should jump to ret: label
3362 * in order to return, no direct "return" statements please.
3363 * This helps to ensure that no memory is leaked. */
3365 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3368 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3369 * We are saving state before entering outermost list ("while...done")
3370 * so that ctrl-Z will correctly background _entire_ outermost list,
3371 * not just a part of it (like "sleep 1 | exit 2") */
3372 if (++G.run_list_level == 1 && G_interactive_fd) {
3373 if (sigsetjmp(G.toplevel_jb, 1)) {
3374 /* ctrl-Z forked and we are parent; or ctrl-C.
3375 * Sighandler has longjmped us here */
3376 signal(SIGINT, SIG_IGN);
3377 signal(SIGTSTP, SIG_IGN);
3378 /* Restore level (we can be coming from deep inside
3380 G.run_list_level = 1;
3381 #if ENABLE_FEATURE_SH_STANDALONE
3382 if (G.nofork_save.saved) { /* if save area is valid */
3383 debug_printf_jobs("exiting nofork early\n");
3384 restore_nofork_data(&G.nofork_save);
3387 //// if (G.ctrl_z_flag) {
3388 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3389 //// * Remember this child as background job */
3390 //// insert_bg_job(pi);
3392 /* ctrl-C. We just stop doing whatever we were doing */
3395 USE_HUSH_LOOPS(loop_top = NULL;)
3396 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3400 //// /* ctrl-Z handler will store pid etc in pi */
3401 //// G.toplevel_list = pi;
3402 //// G.ctrl_z_flag = 0;
3403 #if ENABLE_FEATURE_SH_STANDALONE
3404 G.nofork_save.saved = 0; /* in case we will run a nofork later */
3406 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3407 //// signal(SIGINT, handler_ctrl_c);
3413 last_rword = RES_XXXX;
3415 last_followup = PIPE_SEQ;
3416 rcode = G.last_exitcode;
3418 /* Go through list of pipes, (maybe) executing them. */
3419 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3423 IF_HAS_KEYWORDS(rword = pi->res_word;)
3424 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3425 rword, cond_code, last_rword);
3426 #if ENABLE_HUSH_LOOPS
3427 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3428 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3430 /* start of a loop: remember where loop starts */
3435 /* Still in the same "if...", "then..." or "do..." branch? */
3436 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3437 if ((rcode == 0 && last_followup == PIPE_OR)
3438 || (rcode != 0 && last_followup == PIPE_AND)
3440 /* It is "<true> || CMD" or "<false> && CMD"
3441 * and we should not execute CMD */
3442 debug_printf_exec("skipped cmd because of || or &&\n");
3443 last_followup = pi->followup;
3447 last_followup = pi->followup;
3448 IF_HAS_KEYWORDS(last_rword = rword;)
3451 if (rword == RES_THEN) {
3452 /* if false; then ... fi has exitcode 0! */
3453 G.last_exitcode = rcode = EXIT_SUCCESS;
3454 /* "if <false> THEN cmd": skip cmd */
3458 if (rword == RES_ELSE || rword == RES_ELIF) {
3459 /* "if <true> then ... ELSE/ELIF cmd":
3460 * skip cmd and all following ones */
3465 #if ENABLE_HUSH_LOOPS
3466 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3468 /* first loop through for */
3470 static const char encoded_dollar_at[] ALIGN1 = {
3471 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3472 }; /* encoded representation of "$@" */
3473 static const char *const encoded_dollar_at_argv[] = {
3474 encoded_dollar_at, NULL
3475 }; /* argv list with one element: "$@" */
3478 vals = (char**)encoded_dollar_at_argv;
3479 if (pi->next->res_word == RES_IN) {
3480 /* if no variable values after "in" we skip "for" */
3481 if (!pi->next->cmds[0].argv) {
3482 G.last_exitcode = rcode = EXIT_SUCCESS;
3483 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3486 vals = pi->next->cmds[0].argv;
3487 } /* else: "for var; do..." -> assume "$@" list */
3488 /* create list of variable values */
3489 debug_print_strings("for_list made from", vals);
3490 for_list = expand_strvec_to_strvec(vals);
3491 for_lcur = for_list;
3492 debug_print_strings("for_list", for_list);
3493 for_varname = pi->cmds[0].argv[0];
3494 pi->cmds[0].argv[0] = NULL;
3496 free(pi->cmds[0].argv[0]);
3498 /* "for" loop is over, clean up */
3502 pi->cmds[0].argv[0] = for_varname;
3505 /* Insert next value from for_lcur */
3506 /* note: *for_lcur already has quotes removed, $var expanded, etc */
3507 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3508 pi->cmds[0].assignment_cnt = 1;
3510 if (rword == RES_IN) {
3511 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3513 if (rword == RES_DONE) {
3514 continue; /* "done" has no cmds too */
3517 #if ENABLE_HUSH_CASE
3518 if (rword == RES_CASE) {
3519 case_word = expand_strvec_to_string(pi->cmds->argv);
3522 if (rword == RES_MATCH) {
3525 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3527 /* all prev words didn't match, does this one match? */
3528 argv = pi->cmds->argv;
3530 char *pattern = expand_string_to_string(*argv);
3531 /* TODO: which FNM_xxx flags to use? */
3532 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3534 if (cond_code == 0) { /* match! we will execute this branch */
3535 free(case_word); /* make future "word)" stop */
3543 if (rword == RES_CASEI) { /* inside of a case branch */
3545 continue; /* not matched yet, skip this pipe */
3548 /* Just pressing <enter> in shell should check for jobs.
3549 * OTOH, in non-interactive shell this is useless
3550 * and only leads to extra job checks */
3551 if (pi->num_cmds == 0) {
3552 if (G_interactive_fd)
3553 goto check_jobs_and_continue;
3557 /* After analyzing all keywords and conditions, we decided
3558 * to execute this pipe. NB: have to do checkjobs(NULL)
3559 * after run_pipe to collect any background children,
3560 * even if list execution is to be stopped. */
3561 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3564 #if ENABLE_HUSH_LOOPS
3565 G.flag_break_continue = 0;
3567 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3569 /* We only ran a builtin: rcode is already known
3570 * and we don't need to wait for anything. */
3571 G.last_exitcode = rcode;
3572 debug_printf_exec(": builtin exitcode %d\n", rcode);
3573 check_and_run_traps(0);
3574 #if ENABLE_HUSH_LOOPS
3575 /* Was it "break" or "continue"? */
3576 if (G.flag_break_continue) {
3577 smallint fbc = G.flag_break_continue;
3578 /* We might fall into outer *loop*,
3579 * don't want to break it too */
3581 G.depth_break_continue--;
3582 if (G.depth_break_continue == 0)
3583 G.flag_break_continue = 0;
3584 /* else: e.g. "continue 2" should *break* once, *then* continue */
3585 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3586 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3587 goto check_jobs_and_break;
3588 /* "continue": simulate end of loop */
3593 } else if (pi->followup == PIPE_BG) {
3594 /* What does bash do with attempts to background builtins? */
3595 /* even bash 3.2 doesn't do that well with nested bg:
3596 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3597 * I'm NOT treating inner &'s as jobs */
3598 check_and_run_traps(0);
3600 if (G.run_list_level == 1)
3603 G.last_exitcode = rcode = EXIT_SUCCESS;
3604 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3607 if (G.run_list_level == 1 && G_interactive_fd) {
3608 /* Waits for completion, then fg's main shell */
3609 rcode = checkjobs_and_fg_shell(pi);
3610 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3611 check_and_run_traps(0);
3614 { /* This one just waits for completion */
3615 rcode = checkjobs(pi);
3616 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3617 check_and_run_traps(0);
3619 G.last_exitcode = rcode;
3623 /* Analyze how result affects subsequent commands */
3625 if (rword == RES_IF || rword == RES_ELIF)
3628 #if ENABLE_HUSH_LOOPS
3629 /* Beware of "while false; true; do ..."! */
3630 if (pi->next && pi->next->res_word == RES_DO) {
3631 if (rword == RES_WHILE) {
3633 /* "while false; do...done" - exitcode 0 */
3634 G.last_exitcode = rcode = EXIT_SUCCESS;
3635 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3636 goto check_jobs_and_break;
3639 if (rword == RES_UNTIL) {
3641 debug_printf_exec(": until expr is true: breaking\n");
3642 check_jobs_and_break:
3650 check_jobs_and_continue:
3655 //// if (G.ctrl_z_flag) {
3656 //// /* ctrl-Z forked somewhere in the past, we are the child,
3657 //// * and now we completed running the list. Exit. */
3663 //// if (!G.run_list_level && G_interactive_fd) {
3664 //// signal(SIGTSTP, SIG_IGN);
3665 //// signal(SIGINT, SIG_IGN);
3668 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3669 #if ENABLE_HUSH_LOOPS
3674 #if ENABLE_HUSH_CASE
3680 /* Select which version we will use */
3681 static int run_and_free_list(struct pipe *pi)
3684 debug_printf_exec("run_and_free_list entered\n");
3686 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3687 rcode = run_list(pi);
3689 /* free_pipe_list has the side effect of clearing memory.
3690 * In the long run that function can be merged with run_list,
3691 * but doing that now would hobble the debugging effort. */
3692 free_pipe_list(pi, /* indent: */ 0);
3693 debug_printf_exec("run_and_free_list return %d\n", rcode);
3698 static struct pipe *new_pipe(void)
3701 pi = xzalloc(sizeof(struct pipe));
3702 /*pi->followup = 0; - deliberately invalid value */
3703 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3707 /* Command (member of a pipe) is complete. The only possible error here
3708 * is out of memory, in which case xmalloc exits. */
3709 static int done_command(struct parse_context *ctx)
3711 /* The command is really already in the pipe structure, so
3712 * advance the pipe counter and make a new, null command. */
3713 struct pipe *pi = ctx->pipe;
3714 struct command *command = ctx->command;
3717 if (command->group == NULL
3718 && command->argv == NULL
3719 && command->redirects == NULL
3721 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3722 memset(command, 0, sizeof(*command)); /* paranoia */
3723 return pi->num_cmds;
3726 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3727 //debug_print_tree(ctx->list_head, 20);
3729 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3732 /* Only real trickiness here is that the uncommitted
3733 * command structure is not counted in pi->num_cmds. */
3734 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3735 command = &pi->cmds[pi->num_cmds];
3736 memset(command, 0, sizeof(*command));
3738 ctx->command = command;
3739 /* but ctx->pipe and ctx->list_head remain unchanged */
3741 return pi->num_cmds; /* used only for 0/nonzero check */
3744 static void done_pipe(struct parse_context *ctx, pipe_style type)
3748 debug_printf_parse("done_pipe entered, followup %d\n", type);
3749 /* Close previous command */
3750 not_null = done_command(ctx);
3751 ctx->pipe->followup = type;
3753 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3754 ctx->ctx_inverted = 0;
3755 ctx->pipe->res_word = ctx->ctx_res_w;
3758 /* Without this check, even just <enter> on command line generates
3759 * tree of three NOPs (!). Which is harmless but annoying.
3760 * IOW: it is safe to do it unconditionally.
3761 * RES_NONE case is for "for a in; do ..." (empty IN set)
3762 * and other cases to work. */
3765 || ctx->ctx_res_w == RES_FI
3766 || ctx->ctx_res_w == RES_DONE
3767 || ctx->ctx_res_w == RES_FOR
3768 || ctx->ctx_res_w == RES_IN
3769 || ctx->ctx_res_w == RES_ESAC
3773 debug_printf_parse("done_pipe: adding new pipe: "
3774 "not_null:%d ctx->ctx_res_w:%d\n",
3775 not_null, ctx->ctx_res_w);
3777 ctx->pipe->next = new_p;
3779 /* RES_THEN, RES_DO etc are "sticky" -
3780 * they remain set for commands inside if/while.
3781 * This is used to control execution.
3782 * RES_FOR and RES_IN are NOT sticky (needed to support
3783 * cases where variable or value happens to match a keyword):
3785 #if ENABLE_HUSH_LOOPS
3786 if (ctx->ctx_res_w == RES_FOR
3787 || ctx->ctx_res_w == RES_IN)
3788 ctx->ctx_res_w = RES_NONE;
3790 #if ENABLE_HUSH_CASE
3791 if (ctx->ctx_res_w == RES_MATCH)
3792 ctx->ctx_res_w = RES_CASEI;
3794 ctx->command = NULL; /* trick done_command below */
3795 /* Create the memory for command, roughly:
3796 * ctx->pipe->cmds = new struct command;
3797 * ctx->command = &ctx->pipe->cmds[0];
3800 //debug_print_tree(ctx->list_head, 10);
3802 debug_printf_parse("done_pipe return\n");
3805 static void initialize_context(struct parse_context *ctx)
3807 memset(ctx, 0, sizeof(*ctx));
3808 ctx->pipe = ctx->list_head = new_pipe();
3809 /* Create the memory for command, roughly:
3810 * ctx->pipe->cmds = new struct command;
3811 * ctx->command = &ctx->pipe->cmds[0];
3816 /* If a reserved word is found and processed, parse context is modified
3817 * and 1 is returned.
3820 struct reserved_combo {
3823 unsigned char assignment_flag;
3827 FLAG_END = (1 << RES_NONE ),
3829 FLAG_IF = (1 << RES_IF ),
3830 FLAG_THEN = (1 << RES_THEN ),
3831 FLAG_ELIF = (1 << RES_ELIF ),
3832 FLAG_ELSE = (1 << RES_ELSE ),
3833 FLAG_FI = (1 << RES_FI ),
3835 #if ENABLE_HUSH_LOOPS
3836 FLAG_FOR = (1 << RES_FOR ),
3837 FLAG_WHILE = (1 << RES_WHILE),
3838 FLAG_UNTIL = (1 << RES_UNTIL),
3839 FLAG_DO = (1 << RES_DO ),
3840 FLAG_DONE = (1 << RES_DONE ),
3841 FLAG_IN = (1 << RES_IN ),
3843 #if ENABLE_HUSH_CASE
3844 FLAG_MATCH = (1 << RES_MATCH),
3845 FLAG_ESAC = (1 << RES_ESAC ),
3847 FLAG_START = (1 << RES_XXXX ),
3850 static const struct reserved_combo* match_reserved_word(o_string *word)
3852 /* Mostly a list of accepted follow-up reserved words.
3853 * FLAG_END means we are done with the sequence, and are ready
3854 * to turn the compound list into a command.
3855 * FLAG_START means the word must start a new compound list.
3857 static const struct reserved_combo reserved_list[] = {
3859 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3860 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3861 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3862 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3863 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3864 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3866 #if ENABLE_HUSH_LOOPS
3867 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3868 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3869 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3870 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3871 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3872 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3874 #if ENABLE_HUSH_CASE
3875 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3876 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3879 const struct reserved_combo *r;
3881 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3882 if (strcmp(word->data, r->literal) == 0)
3887 static int reserved_word(o_string *word, struct parse_context *ctx)
3889 #if ENABLE_HUSH_CASE
3890 static const struct reserved_combo reserved_match = {
3891 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3894 const struct reserved_combo *r;
3896 r = match_reserved_word(word);
3900 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3901 #if ENABLE_HUSH_CASE
3902 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3903 /* "case word IN ..." - IN part starts first match part */
3904 r = &reserved_match;
3907 if (r->flag == 0) { /* '!' */
3908 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3909 syntax_error("! ! command");
3910 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3912 ctx->ctx_inverted = 1;
3915 if (r->flag & FLAG_START) {
3916 struct parse_context *old;
3917 old = xmalloc(sizeof(*old));
3918 debug_printf_parse("push stack %p\n", old);
3919 *old = *ctx; /* physical copy */
3920 initialize_context(ctx);
3922 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3923 syntax_error_at(word->data);
3924 ctx->ctx_res_w = RES_SNTX;
3927 ctx->ctx_res_w = r->res;
3928 ctx->old_flag = r->flag;
3929 if (ctx->old_flag & FLAG_END) {
3930 struct parse_context *old;
3931 done_pipe(ctx, PIPE_SEQ);
3932 debug_printf_parse("pop stack %p\n", ctx->stack);
3934 old->command->group = ctx->list_head;
3935 old->command->grp_type = GRP_NORMAL;
3937 o_addstr(&old->as_string, ctx->as_string.data);
3938 o_free_unsafe(&ctx->as_string);
3939 old->command->group_as_string = xstrdup(old->as_string.data);
3940 debug_printf_parse("pop, remembering as:'%s'\n",
3941 old->command->group_as_string);
3943 *ctx = *old; /* physical copy */
3946 word->o_assignment = r->assignment_flag;
3951 /* Word is complete, look at it and update parsing context.
3952 * Normal return is 0. Syntax errors return 1.
3953 * Note: on return, word is reset, but not o_free'd!
3955 static int done_word(o_string *word, struct parse_context *ctx)
3957 struct command *command = ctx->command;
3959 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3960 if (word->length == 0 && word->o_quoted == 0) {
3961 debug_printf_parse("done_word return 0: true null, ignored\n");
3964 /* If this word wasn't an assignment, next ones definitely
3965 * can't be assignments. Even if they look like ones. */
3966 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3967 && word->o_assignment != WORD_IS_KEYWORD
3969 word->o_assignment = NOT_ASSIGNMENT;
3971 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3972 command->assignment_cnt++;
3973 word->o_assignment = MAYBE_ASSIGNMENT;
3976 if (ctx->pending_redirect) {
3977 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3978 * only if run as "bash", not "sh" */
3979 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3981 * ...the word that follows the redirection operator
3982 * shall be subjected to tilde expansion, parameter expansion,
3983 * command substitution, arithmetic expansion, and quote
3984 * removal. Pathname expansion shall not be performed
3985 * on the word by a non-interactive shell; an interactive
3986 * shell may perform it, but shall do so only when
3987 * the expansion would result in one word."
3989 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3990 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
3993 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3995 word->o_assignment = NOT_ASSIGNMENT;
3996 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3998 /* "{ echo foo; } echo bar" - bad */
3999 /* NB: bash allows e.g.:
4000 * if true; then { echo foo; } fi
4001 * while if false; then false; fi do break; done
4003 * while if false; then false; fi; do; break; done
4005 if (command->group) {
4006 syntax_error_at(word->data);
4007 debug_printf_parse("done_word return 1: syntax error, "
4008 "groups and arglists don't mix\n");
4012 #if ENABLE_HUSH_CASE
4013 if (ctx->ctx_dsemicolon
4014 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4016 /* already done when ctx_dsemicolon was set to 1: */
4017 /* ctx->ctx_res_w = RES_MATCH; */
4018 ctx->ctx_dsemicolon = 0;
4021 if (!command->argv /* if it's the first word... */
4022 #if ENABLE_HUSH_LOOPS
4023 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4024 && ctx->ctx_res_w != RES_IN
4027 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
4028 if (reserved_word(word, ctx)) {
4030 debug_printf_parse("done_word return %d\n",
4031 (ctx->ctx_res_w == RES_SNTX));
4032 return (ctx->ctx_res_w == RES_SNTX);
4036 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4037 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4038 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4039 /* (otherwise it's known to be not empty and is already safe) */
4041 /* exclude "$@" - it can expand to no word despite "" */
4042 char *p = word->data;
4043 while (p[0] == SPECIAL_VAR_SYMBOL
4044 && (p[1] & 0x7f) == '@'
4045 && p[2] == SPECIAL_VAR_SYMBOL
4049 if (p == word->data || p[0] != '\0') {
4050 /* saw no "$@", or not only "$@" but some
4051 * real text is there too */
4052 /* insert "empty variable" reference, this makes
4053 * e.g. "", $empty"" etc to not disappear */
4054 o_addchr(word, SPECIAL_VAR_SYMBOL);
4055 o_addchr(word, SPECIAL_VAR_SYMBOL);
4058 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4059 debug_print_strings("word appended to argv", command->argv);
4063 ctx->pending_redirect = NULL;
4065 #if ENABLE_HUSH_LOOPS
4066 /* Force FOR to have just one word (variable name) */
4067 /* NB: basically, this makes hush see "for v in ..." syntax as if
4068 * as it is "for v; in ...". FOR and IN become two pipe structs
4070 if (ctx->ctx_res_w == RES_FOR) {
4071 if (!is_well_formed_var_name(command->argv[0], '\0')) {
4072 syntax_error("malformed variable name in for");
4075 done_pipe(ctx, PIPE_SEQ);
4078 #if ENABLE_HUSH_CASE
4079 /* Force CASE to have just one word */
4080 if (ctx->ctx_res_w == RES_CASE) {
4081 done_pipe(ctx, PIPE_SEQ);
4084 debug_printf_parse("done_word return 0\n");
4089 /* Peek ahead in the input to find out if we have a "&n" construct,
4090 * as in "2>&1", that represents duplicating a file descriptor.
4091 * Return: REDIRFD_CLOSE (-3) if >&- "close fd" construct is seen,
4092 * -2 (syntax error), -1 if no & was seen, or the number found.
4095 #define redirect_dup_num(as_string, input) \
4096 redirect_dup_num(input)
4098 static int redirect_dup_num(o_string *as_string, struct in_str *input)
4106 ch = i_getch(input); /* get the & */
4107 nommu_addchr(as_string, ch);
4110 ch = i_getch(input);
4111 nommu_addchr(as_string, ch);
4112 return REDIRFD_CLOSE;
4116 while (ch != EOF && isdigit(ch)) {
4117 d = d*10 + (ch-'0');
4119 ch = i_getch(input);
4120 nommu_addchr(as_string, ch);
4125 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4127 bb_error_msg("ambiguous redirect");
4131 /* Return code is 0 normally, 1 if a syntax error is detected
4133 static int parse_redirect(struct parse_context *ctx,
4136 struct in_str *input)
4138 struct command *command = ctx->command;
4139 struct redir_struct *redir;
4140 struct redir_struct **redirp;
4144 if (style != REDIRECT_HEREDOC) {
4145 /* Check for a '2>&1' type redirect */
4146 dup_num = redirect_dup_num(&ctx->as_string, input);
4148 return 1; /* syntax error */
4150 int ch = i_peek(input);
4151 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4152 if (dup_num) { /* <<-... */
4153 ch = i_getch(input);
4154 nommu_addchr(&ctx->as_string, ch);
4159 if (style == REDIRECT_OVERWRITE && dup_num == -1) {
4160 int ch = i_peek(input);
4162 /* >|FILE redirect ("clobbering" >).
4163 * Since we do not support "set -o noclobber" yet,
4164 * >| and > are the same for now. Just eat |.
4166 ch = i_getch(input);
4167 nommu_addchr(&ctx->as_string, ch);
4171 /* Create a new redir_struct and append it to the linked list */
4172 redirp = &command->redirects;
4173 while ((redir = *redirp) != NULL) {
4174 redirp = &(redir->next);
4176 *redirp = redir = xzalloc(sizeof(*redir));
4177 /* redir->next = NULL; */
4178 /* redir->rd_filename = NULL; */
4179 redir->rd_type = style;
4180 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4182 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4183 redir_table[style].descrip);
4185 redir->rd_dup = dup_num;
4186 if (style != REDIRECT_HEREDOC && dup_num != -1) {
4187 /* Erik had a check here that the file descriptor in question
4188 * is legit; I postpone that to "run time"
4189 * A "-" representation of "close me" shows up as a -3 here */
4190 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4191 redir->rd_fd, redir->rd_dup);
4193 /* Set ctx->pending_redirect, so we know what to do at the
4194 * end of the next parsed word. */
4195 ctx->pending_redirect = redir;
4200 /* If a redirect is immediately preceded by a number, that number is
4201 * supposed to tell which file descriptor to redirect. This routine
4202 * looks for such preceding numbers. In an ideal world this routine
4203 * needs to handle all the following classes of redirects...
4204 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4205 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4206 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4207 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4209 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4211 * ... If n is quoted, the number shall not be recognized as part of
4212 * the redirection expression. For example:
4214 * writes the character 2 into file a"
4215 * We are getting it right by setting ->o_quoted on any \<char>
4217 * A -1 return means no valid number was found,
4218 * the caller should use the appropriate default for this redirection.
4220 static int redirect_opt_num(o_string *o)
4224 if (o->data == NULL)
4226 num = bb_strtou(o->data, NULL, 10);
4227 if (errno || num < 0)
4234 #define fetch_till_str(as_string, input, word, skip_tabs) \
4235 fetch_till_str(input, word, skip_tabs)
4237 static char *fetch_till_str(o_string *as_string,
4238 struct in_str *input,
4242 o_string heredoc = NULL_O_STRING;
4248 ch = i_getch(input);
4249 nommu_addchr(as_string, ch);
4251 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4252 heredoc.data[past_EOL] = '\0';
4253 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4254 return heredoc.data;
4257 o_addchr(&heredoc, ch);
4258 past_EOL = heredoc.length;
4261 ch = i_getch(input);
4262 nommu_addchr(as_string, ch);
4263 } while (skip_tabs && ch == '\t');
4264 } while (ch == '\n');
4267 o_free_unsafe(&heredoc);
4270 o_addchr(&heredoc, ch);
4271 nommu_addchr(as_string, ch);
4275 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4276 * and load them all. There should be exactly heredoc_cnt of them.
4278 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4280 struct pipe *pi = ctx->list_head;
4282 while (pi && heredoc_cnt) {
4284 struct command *cmd = pi->cmds;
4286 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4288 cmd->argv ? cmd->argv[0] : "NONE");
4289 for (i = 0; i < pi->num_cmds; i++) {
4290 struct redir_struct *redir = cmd->redirects;
4292 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4293 i, cmd->argv ? cmd->argv[0] : "NONE");
4295 if (redir->rd_type == REDIRECT_HEREDOC) {
4298 redir->rd_type = REDIRECT_HEREDOC2;
4299 /* redir->dup is (ab)used to indicate <<- */
4300 p = fetch_till_str(&ctx->as_string, input,
4301 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4303 syntax_error("unexpected EOF in here document");
4306 free(redir->rd_filename);
4307 redir->rd_filename = p;
4310 redir = redir->next;
4317 /* Should be 0. If it isn't, it's a parse error */
4319 bb_error_msg_and_die("heredoc BUG 2");
4326 #define parse_stream(pstring, input, end_trigger) \
4327 parse_stream(input, end_trigger)
4329 static struct pipe *parse_stream(char **pstring,
4330 struct in_str *input,
4332 static void parse_and_run_string(const char *s);
4334 #if ENABLE_HUSH_TICK
4335 static FILE *generate_stream_from_string(const char *s)
4338 int pid, channel[2];
4341 pid = BB_MMU ? fork() : vfork();
4343 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4345 if (pid == 0) { /* child */
4346 disable_restore_tty_pgrp_on_exit();
4347 /* Process substitution is not considered to be usual
4348 * 'command execution'.
4349 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4356 close(channel[0]); /* NB: close _first_, then move fd! */
4357 xmove_fd(channel[1], 1);
4358 /* Prevent it from trying to handle ctrl-z etc */
4359 USE_HUSH_JOB(G.run_list_level = 1;)
4361 reset_traps_to_defaults();
4362 parse_and_run_string(s);
4363 _exit(G.last_exitcode);
4365 /* We re-execute after vfork on NOMMU. This makes this script safe:
4366 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4367 * huge=`cat BIG` # was blocking here forever
4370 re_execute_shell(s, 0);
4375 enable_restore_tty_pgrp_on_exit();
4376 clean_up_after_re_execute();
4378 pf = fdopen(channel[0], "r");
4382 /* Return code is exit status of the process that is run. */
4383 static int process_command_subs(o_string *dest, const char *s)
4386 struct in_str pipe_str;
4389 pf = generate_stream_from_string(s);
4392 close_on_exec_on(fileno(pf));
4394 /* Now send results of command back into original context */
4395 setup_file_in_str(&pipe_str, pf);
4397 while ((ch = i_getch(&pipe_str)) != EOF) {
4403 o_addchr(dest, '\n');
4406 o_addQchr(dest, ch);
4409 debug_printf("done reading from pipe, pclose()ing\n");
4410 /* Note: we got EOF, and we just close the read end of the pipe.
4411 * We do not wait for the `cmd` child to terminate. bash and ash do.
4413 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4414 * `false`; echo $? - bash outputs "1"
4417 debug_printf("closed FILE from child. return 0\n");
4422 static int parse_group(o_string *dest, struct parse_context *ctx,
4423 struct in_str *input, int ch)
4425 /* dest contains characters seen prior to ( or {.
4426 * Typically it's empty, but for function defs,
4427 * it contains function name (without '()'). */
4428 struct pipe *pipe_list;
4430 struct command *command = ctx->command;
4432 debug_printf_parse("parse_group entered\n");
4433 #if ENABLE_HUSH_FUNCTIONS
4434 if (ch == 'F') { /* function definition? */
4435 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4436 //command->fname = dest->data;
4437 command->grp_type = GRP_FUNCTION;
4438 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4439 memset(dest, 0, sizeof(*dest));
4442 if (command->argv /* word [word](... */
4443 || dest->length /* word(... */
4444 || dest->o_quoted /* ""(... */
4447 debug_printf_parse("parse_group return 1: "
4448 "syntax error, groups and arglists don't mix\n");
4454 command->grp_type = GRP_SUBSHELL;
4458 char *as_string = NULL;
4460 pipe_list = parse_stream(&as_string, input, endch);
4463 o_addstr(&ctx->as_string, as_string);
4465 /* empty ()/{} or parse error? */
4466 if (!pipe_list || pipe_list == ERR_PTR) {
4471 debug_printf_parse("parse_group return 1: "
4472 "parse_stream returned %p\n", pipe_list);
4475 command->group = pipe_list;
4477 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4478 command->group_as_string = as_string;
4479 debug_printf_parse("end of group, remembering as:'%s'\n",
4480 command->group_as_string);
4483 debug_printf_parse("parse_group return 0\n");
4485 /* command remains "open", available for possible redirects */
4488 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4489 /* Subroutines for copying $(...) and `...` things */
4490 static int add_till_backquote(o_string *dest, struct in_str *input);
4492 static int add_till_single_quote(o_string *dest, struct in_str *input)
4495 int ch = i_getch(input);
4497 syntax_error_unterm_ch('\'');
4505 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4506 static int add_till_double_quote(o_string *dest, struct in_str *input)
4509 int ch = i_getch(input);
4511 syntax_error_unterm_ch('"');
4516 if (ch == '\\') { /* \x. Copy both chars. */
4518 ch = i_getch(input);
4522 if (add_till_backquote(dest, input))
4527 //if (ch == '$') ...
4530 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4532 * "Within the backquoted style of command substitution, backslash
4533 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4534 * The search for the matching backquote shall be satisfied by the first
4535 * backquote found without a preceding backslash; during this search,
4536 * if a non-escaped backquote is encountered within a shell comment,
4537 * a here-document, an embedded command substitution of the $(command)
4538 * form, or a quoted string, undefined results occur. A single-quoted
4539 * or double-quoted string that begins, but does not end, within the
4540 * "`...`" sequence produces undefined results."
4542 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4544 static int add_till_backquote(o_string *dest, struct in_str *input)
4547 int ch = i_getch(input);
4549 syntax_error_unterm_ch('`');
4555 /* \x. Copy both chars unless it is \` */
4556 int ch2 = i_getch(input);
4558 syntax_error_unterm_ch('`');
4561 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4568 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4569 * quoting and nested ()s.
4570 * "With the $(command) style of command substitution, all characters
4571 * following the open parenthesis to the matching closing parenthesis
4572 * constitute the command. Any valid shell script can be used for command,
4573 * except a script consisting solely of redirections which produces
4574 * unspecified results."
4576 * echo $(echo '(TEST)' BEST) (TEST) BEST
4577 * echo $(echo 'TEST)' BEST) TEST) BEST
4578 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4580 static int add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4584 int ch = i_getch(input);
4586 syntax_error_unterm_ch(')');
4595 if (i_peek(input) == ')') {
4603 if (add_till_single_quote(dest, input))
4609 if (add_till_double_quote(dest, input))
4615 /* \x. Copy verbatim. Important for \(, \) */
4616 ch = i_getch(input);
4618 syntax_error_unterm_ch(')');
4627 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4629 /* Return code: 0 for OK, 1 for syntax error */
4631 #define handle_dollar(as_string, dest, input) \
4632 handle_dollar(dest, input)
4634 static int handle_dollar(o_string *as_string,
4636 struct in_str *input)
4639 int ch = i_peek(input); /* first character after the $ */
4640 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4642 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4644 ch = i_getch(input);
4645 nommu_addchr(as_string, ch);
4647 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4649 debug_printf_parse(": '%c'\n", ch);
4650 o_addchr(dest, ch | quote_mask);
4653 if (!isalnum(ch) && ch != '_')
4655 ch = i_getch(input);
4656 nommu_addchr(as_string, ch);
4658 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4659 } else if (isdigit(ch)) {
4661 ch = i_getch(input);
4662 nommu_addchr(as_string, ch);
4663 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4664 debug_printf_parse(": '%c'\n", ch);
4665 o_addchr(dest, ch | quote_mask);
4666 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4667 } else switch (ch) {
4669 case '!': /* last bg pid */
4670 case '?': /* last exit code */
4671 case '#': /* number of args */
4672 case '*': /* args */
4673 case '@': /* args */
4674 goto make_one_char_var;
4676 bool first_char, all_digits;
4678 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4679 ch = i_getch(input);
4680 nommu_addchr(as_string, ch);
4681 /* XXX maybe someone will try to escape the '}' */
4686 ch = i_getch(input);
4687 nommu_addchr(as_string, ch);
4693 /* ${#var}: length of var contents */
4695 else if (isdigit(ch)) {
4702 && ( (all_digits && !isdigit(ch))
4703 || (!all_digits && !isalnum(ch) && ch != '_')
4706 /* handle parameter expansions
4707 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4712 case ':': /* null modifier */
4713 if (expansion == 0) {
4714 debug_printf_parse(": null modifier\n");
4719 case '#': /* remove prefix */
4720 case '%': /* remove suffix */
4721 if (expansion == 0) {
4722 debug_printf_parse(": remove suffix/prefix\n");
4727 case '-': /* default value */
4728 case '=': /* assign default */
4729 case '+': /* alternative */
4730 case '?': /* error indicate */
4731 debug_printf_parse(": parameter expansion\n");
4736 syntax_error_unterm_str("${name}");
4737 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4742 debug_printf_parse(": '%c'\n", ch);
4743 o_addchr(dest, ch | quote_mask);
4747 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4750 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4755 ch = i_getch(input);
4756 nommu_addchr(as_string, ch);
4757 # if ENABLE_SH_MATH_SUPPORT
4758 if (i_peek(input) == '(') {
4759 ch = i_getch(input);
4760 nommu_addchr(as_string, ch);
4761 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4762 o_addchr(dest, /*quote_mask |*/ '+');
4766 if (add_till_closing_paren(dest, input, true))
4770 o_addstr(as_string, dest->data + pos);
4771 o_addchr(as_string, ')');
4772 o_addchr(as_string, ')');
4775 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4779 # if ENABLE_HUSH_TICK
4780 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4781 o_addchr(dest, quote_mask | '`');
4785 if (add_till_closing_paren(dest, input, false))
4789 o_addstr(as_string, dest->data + pos);
4790 o_addchr(as_string, '`');
4793 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4799 ch = i_getch(input);
4800 nommu_addchr(as_string, ch);
4802 if (isalnum(ch)) { /* it's $_name or $_123 */
4808 /* $_ Shell or shell script name; or last cmd name */
4809 /* $- Option flags set by set builtin or shell options (-i etc) */
4811 o_addQchr(dest, '$');
4813 debug_printf_parse("handle_dollar return 0\n");
4818 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4819 parse_stream_dquoted(dest, input, dquote_end)
4821 static int parse_stream_dquoted(o_string *as_string,
4823 struct in_str *input,
4830 ch = i_getch(input);
4832 nommu_addchr(as_string, ch);
4833 if (ch == dquote_end) { /* may be only '"' or EOF */
4834 if (dest->o_assignment == NOT_ASSIGNMENT)
4835 dest->o_escape ^= 1;
4836 debug_printf_parse("parse_stream_dquoted return 0\n");
4839 /* note: can't move it above ch == dquote_end check! */
4841 syntax_error_unterm_ch('"');
4842 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4847 next = i_peek(input);
4849 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4850 ch, ch, dest->o_escape);
4852 //TODO: check interactive behavior
4854 syntax_error("\\<eof>");
4855 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4859 * "The backslash retains its special meaning [in "..."]
4860 * only when followed by one of the following characters:
4861 * $, `, ", \, or <newline>. A double quote may be quoted
4862 * within double quotes by preceding it with a backslash.
4863 * If enabled, history expansion will be performed unless
4864 * an ! appearing in double quotes is escaped using
4865 * a backslash. The backslash preceding the ! is not removed."
4867 if (strchr("$`\"\\", next) != NULL) {
4868 o_addqchr(dest, i_getch(input));
4870 o_addqchr(dest, '\\');
4875 if (handle_dollar(as_string, dest, input) != 0) {
4876 debug_printf_parse("parse_stream_dquoted return 1: "
4877 "handle_dollar returned non-0\n");
4882 #if ENABLE_HUSH_TICK
4884 //int pos = dest->length;
4885 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4886 o_addchr(dest, 0x80 | '`');
4887 if (add_till_backquote(dest, input))
4889 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4890 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4894 o_addQchr(dest, ch);
4896 && (dest->o_assignment == MAYBE_ASSIGNMENT
4897 || dest->o_assignment == WORD_IS_KEYWORD)
4898 && is_well_formed_var_name(dest->data, '=')
4900 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4906 * Scan input until EOF or end_trigger char.
4907 * Return a list of pipes to execute, or NULL on EOF
4908 * or if end_trigger character is met.
4909 * On syntax error, exit is shell is not interactive,
4910 * reset parsing machinery and start parsing anew,
4911 * or return ERR_PTR.
4913 static struct pipe *parse_stream(char **pstring,
4914 struct in_str *input,
4917 struct parse_context ctx;
4918 o_string dest = NULL_O_STRING;
4922 /* Double-quote state is handled in the state variable is_in_dquote.
4923 * A single-quote triggers a bypass of the main loop until its mate is
4924 * found. When recursing, quote state is passed in via dest->o_escape.
4926 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4927 end_trigger ? : 'X');
4929 G.ifs = get_local_var_value("IFS");
4934 #if ENABLE_HUSH_INTERACTIVE
4935 input->promptmode = 0; /* PS1 */
4937 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4938 initialize_context(&ctx);
4943 const char *is_special;
4947 redir_type redir_style;
4950 /* dest.o_quoted = 1; - already is (see below) */
4951 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4954 /* We reached closing '"' */
4957 ch = i_getch(input);
4958 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4959 ch, ch, dest.o_escape);
4964 syntax_error_unterm_str("here document");
4967 if (done_word(&dest, &ctx)) {
4971 done_pipe(&ctx, PIPE_SEQ);
4973 /* If we got nothing... */
4974 // TODO: test script consisting of just "&"
4975 if (pi->num_cmds == 0
4976 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4978 free_pipe_list(pi, 0);
4981 debug_printf_parse("parse_stream return %p\n", pi);
4983 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4985 *pstring = ctx.as_string.data;
4987 o_free_unsafe(&ctx.as_string);
4991 nommu_addchr(&ctx.as_string, ch);
4992 is_ifs = strchr(G.ifs, ch);
4993 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4994 "\\$\"" USE_HUSH_TICK("`") /* always special */
4997 if (!is_special && !is_ifs) { /* ordinary char */
4998 o_addQchr(&dest, ch);
4999 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5000 || dest.o_assignment == WORD_IS_KEYWORD)
5002 && is_well_formed_var_name(dest.data, '=')
5004 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5010 if (done_word(&dest, &ctx)) {
5014 #if ENABLE_HUSH_CASE
5015 /* "case ... in <newline> word) ..." -
5016 * newlines are ignored (but ';' wouldn't be) */
5017 if (ctx.command->argv == NULL
5018 && ctx.ctx_res_w == RES_MATCH
5023 /* Treat newline as a command separator. */
5024 done_pipe(&ctx, PIPE_SEQ);
5025 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5027 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5032 dest.o_assignment = MAYBE_ASSIGNMENT;
5034 /* note: if (is_ifs) continue;
5035 * will still trigger for us */
5038 if (end_trigger && end_trigger == ch
5039 && (heredoc_cnt == 0 || end_trigger != ';')
5041 //TODO: disallow "{ cmd }" without semicolon
5043 /* This is technically valid:
5044 * { cat <<HERE; }; echo Ok
5049 * but we don't support this.
5050 * We require heredoc to be in enclosing {}/(),
5053 syntax_error_unterm_str("here document");
5056 if (done_word(&dest, &ctx)) {
5059 done_pipe(&ctx, PIPE_SEQ);
5060 dest.o_assignment = MAYBE_ASSIGNMENT;
5061 /* Do we sit outside of any if's, loops or case's? */
5063 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5065 debug_printf_parse("parse_stream return %p: "
5066 "end_trigger char found\n",
5070 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5072 *pstring = ctx.as_string.data;
5074 o_free_unsafe(&ctx.as_string);
5076 return ctx.list_head;
5082 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
5083 /* ch is a special char and thus this word
5084 * cannot be an assignment */
5085 dest.o_assignment = NOT_ASSIGNMENT;
5090 next = i_peek(input);
5095 if (dest.length == 0) {
5098 if (ch == EOF || ch == '\n')
5101 /* note: we do not add it to &ctx.as_string */
5103 nommu_addchr(&ctx.as_string, '\n');
5105 o_addQchr(&dest, ch);
5110 syntax_error("\\<eof>");
5113 o_addchr(&dest, '\\');
5114 ch = i_getch(input);
5115 nommu_addchr(&ctx.as_string, ch);
5116 o_addchr(&dest, ch);
5117 /* Example: echo Hello \2>file
5118 * we need to know that word 2 is quoted */
5122 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5123 debug_printf_parse("parse_stream parse error: "
5124 "handle_dollar returned non-0\n");
5131 ch = i_getch(input);
5133 syntax_error_unterm_ch('\'');
5136 nommu_addchr(&ctx.as_string, ch);
5139 if (dest.o_assignment == NOT_ASSIGNMENT)
5140 o_addqchr(&dest, ch);
5142 o_addchr(&dest, ch);
5147 is_in_dquote ^= 1; /* invert */
5148 if (dest.o_assignment == NOT_ASSIGNMENT)
5151 #if ENABLE_HUSH_TICK
5156 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5157 o_addchr(&dest, '`');
5161 if (add_till_backquote(&dest, input))
5164 o_addstr(&ctx.as_string, dest.data + pos);
5165 o_addchr(&ctx.as_string, '`');
5167 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5168 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5173 redir_fd = redirect_opt_num(&dest);
5174 if (done_word(&dest, &ctx)) {
5177 redir_style = REDIRECT_OVERWRITE;
5179 redir_style = REDIRECT_APPEND;
5180 ch = i_getch(input);
5181 nommu_addchr(&ctx.as_string, ch);
5184 else if (next == '(') {
5185 syntax_error(">(process) not supported");
5189 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5193 redir_fd = redirect_opt_num(&dest);
5194 if (done_word(&dest, &ctx)) {
5197 redir_style = REDIRECT_INPUT;
5199 redir_style = REDIRECT_HEREDOC;
5201 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5202 ch = i_getch(input);
5203 nommu_addchr(&ctx.as_string, ch);
5204 } else if (next == '>') {
5205 redir_style = REDIRECT_IO;
5206 ch = i_getch(input);
5207 nommu_addchr(&ctx.as_string, ch);
5210 else if (next == '(') {
5211 syntax_error("<(process) not supported");
5215 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5219 #if ENABLE_HUSH_CASE
5222 if (done_word(&dest, &ctx)) {
5225 done_pipe(&ctx, PIPE_SEQ);
5226 #if ENABLE_HUSH_CASE
5227 /* Eat multiple semicolons, detect
5228 * whether it means something special */
5233 ch = i_getch(input);
5234 nommu_addchr(&ctx.as_string, ch);
5235 if (ctx.ctx_res_w == RES_CASEI) {
5236 ctx.ctx_dsemicolon = 1;
5237 ctx.ctx_res_w = RES_MATCH;
5243 /* We just finished a cmd. New one may start
5244 * with an assignment */
5245 dest.o_assignment = MAYBE_ASSIGNMENT;
5248 if (done_word(&dest, &ctx)) {
5252 ch = i_getch(input);
5253 nommu_addchr(&ctx.as_string, ch);
5254 done_pipe(&ctx, PIPE_AND);
5256 done_pipe(&ctx, PIPE_BG);
5260 if (done_word(&dest, &ctx)) {
5263 #if ENABLE_HUSH_CASE
5264 if (ctx.ctx_res_w == RES_MATCH)
5265 break; /* we are in case's "word | word)" */
5267 if (next == '|') { /* || */
5268 ch = i_getch(input);
5269 nommu_addchr(&ctx.as_string, ch);
5270 done_pipe(&ctx, PIPE_OR);
5272 /* we could pick up a file descriptor choice here
5273 * with redirect_opt_num(), but bash doesn't do it.
5274 * "echo foo 2| cat" yields "foo 2". */
5279 #if ENABLE_HUSH_CASE
5280 /* "case... in [(]word)..." - skip '(' */
5281 if (ctx.ctx_res_w == RES_MATCH
5282 && ctx.command->argv == NULL /* not (word|(... */
5283 && dest.length == 0 /* not word(... */
5284 && dest.o_quoted == 0 /* not ""(... */
5289 #if ENABLE_HUSH_FUNCTIONS
5290 if (dest.length != 0 /* not just () but word() */
5291 && dest.o_quoted == 0 /* not a"b"c() */
5292 && ctx.command->argv == NULL /* it's the first word */
5293 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5294 && i_peek(input) == ')'
5295 && !match_reserved_word(&dest)
5297 bb_error_msg("seems like a function definition");
5299 //if !BB_MMU o_addchr(&ctx.as_string...
5301 //TODO: do it properly.
5302 ch = i_getch(input);
5303 } while (ch == ' ' || ch == '\n');
5305 syntax_error("was expecting {");
5308 ch = 'F'; /* magic value */
5312 if (parse_group(&dest, &ctx, input, ch) != 0) {
5317 #if ENABLE_HUSH_CASE
5318 if (ctx.ctx_res_w == RES_MATCH)
5322 /* proper use of this character is caught by end_trigger:
5323 * if we see {, we call parse_group(..., end_trigger='}')
5324 * and it will match } earlier (not here). */
5325 syntax_error("unexpected } or )");
5329 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5335 struct parse_context *pctx;
5336 IF_HAS_KEYWORDS(struct parse_context *p2;)
5338 /* Clean up allocated tree.
5339 * Samples for finding leaks on syntax error recovery path.
5340 * Run them from interactive shell, watch pmap `pidof hush`.
5341 * while if false; then false; fi do break; done
5343 * while if false; then false; fi; do break; fi
5344 * Samples to catch leaks at execution:
5345 * while if (true | {true;}); then echo ok; fi; do break; done
5346 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5350 /* Update pipe/command counts,
5351 * otherwise freeing may miss some */
5352 done_pipe(pctx, PIPE_SEQ);
5353 debug_printf_clean("freeing list %p from ctx %p\n",
5354 pctx->list_head, pctx);
5355 debug_print_tree(pctx->list_head, 0);
5356 free_pipe_list(pctx->list_head, 0);
5357 debug_printf_clean("freed list %p\n", pctx->list_head);
5359 o_free_unsafe(&pctx->as_string);
5361 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5365 IF_HAS_KEYWORDS(pctx = p2;)
5366 } while (HAS_KEYWORDS && pctx);
5367 /* Free text, clear all dest fields */
5369 /* If we are not in top-level parse, we return,
5370 * our caller will propagate error.
5372 if (end_trigger != ';') {
5379 /* Discard cached input, force prompt */
5381 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5386 /* Executing from string: eval, sh -c '...'
5387 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5388 * end_trigger controls how often we stop parsing
5389 * NUL: parse all, execute, return
5390 * ';': parse till ';' or newline, execute, repeat till EOF
5392 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5395 struct pipe *pipe_list;
5397 pipe_list = parse_stream(NULL, inp, end_trigger);
5398 if (!pipe_list) /* EOF */
5400 debug_print_tree(pipe_list, 0);
5401 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5402 run_and_free_list(pipe_list);
5406 static void parse_and_run_string(const char *s)
5408 struct in_str input;
5409 setup_string_in_str(&input, s);
5410 parse_and_run_stream(&input, '\0');
5413 static void parse_and_run_file(FILE *f)
5415 struct in_str input;
5416 setup_file_in_str(&input, f);
5417 parse_and_run_stream(&input, ';');
5420 /* Called a few times only (or even once if "sh -c") */
5421 static void block_signals(int second_time)
5426 mask = (1 << SIGQUIT);
5427 if (G_interactive_fd) {
5431 //TODO | (1 << SIGHUP)
5433 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5438 G.non_DFL_mask = mask;
5441 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5445 sigaddset(&G.blocked_set, sig);
5449 sigdelset(&G.blocked_set, SIGCHLD);
5451 sigprocmask(SIG_SETMASK, &G.blocked_set,
5452 second_time ? NULL : &G.inherited_set);
5453 /* POSIX allows shell to re-enable SIGCHLD
5454 * even if it was SIG_IGN on entry */
5455 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5457 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5462 static void maybe_set_to_sigexit(int sig)
5464 void (*handler)(int);
5465 /* non_DFL_mask'ed signals are, well, masked,
5466 * no need to set handler for them.
5468 if (!((G.non_DFL_mask >> sig) & 1)) {
5469 handler = signal(sig, sigexit);
5470 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5471 signal(sig, handler);
5474 /* Set handlers to restore tty pgrp and exit */
5475 static void set_fatal_handlers(void)
5477 /* We _must_ restore tty pgrp on fatal signals */
5479 maybe_set_to_sigexit(SIGILL );
5480 maybe_set_to_sigexit(SIGFPE );
5481 maybe_set_to_sigexit(SIGBUS );
5482 maybe_set_to_sigexit(SIGSEGV);
5483 maybe_set_to_sigexit(SIGTRAP);
5484 } /* else: hush is perfect. what SEGV? */
5485 maybe_set_to_sigexit(SIGABRT);
5486 /* bash 3.2 seems to handle these just like 'fatal' ones */
5487 maybe_set_to_sigexit(SIGPIPE);
5488 maybe_set_to_sigexit(SIGALRM);
5489 //TODO: disable and move down when proper SIGHUP handling is added
5490 maybe_set_to_sigexit(SIGHUP );
5491 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5492 * if we aren't interactive... but in this case
5493 * we never want to restore pgrp on exit, and this fn is not called */
5494 /*maybe_set_to_sigexit(SIGTERM);*/
5495 /*maybe_set_to_sigexit(SIGINT );*/
5499 static int set_mode(const char cstate, const char mode)
5501 int state = (cstate == '-' ? 1 : 0);
5503 case 'n': G.fake_mode = state; break;
5504 case 'x': /*G.debug_mode = state;*/ break;
5505 default: return EXIT_FAILURE;
5507 return EXIT_SUCCESS;
5510 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5511 int hush_main(int argc, char **argv)
5513 static const struct variable const_shell_ver = {
5515 .varstr = (char*)hush_version_str,
5516 .max_len = 1, /* 0 can provoke free(name) */
5520 int signal_mask_is_inited = 0;
5523 struct variable *cur_var;
5526 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5527 G.last_exitcode = EXIT_SUCCESS;
5529 G.argv0_for_re_execing = argv[0];
5531 /* Deal with HUSH_VERSION */
5532 G.shell_ver = const_shell_ver; /* copying struct here */
5533 G.top_var = &G.shell_ver;
5534 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5535 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5536 /* Initialize our shell local variables with the values
5537 * currently living in the environment */
5538 cur_var = G.top_var;
5541 char *value = strchr(*e, '=');
5542 if (value) { /* paranoia */
5543 cur_var->next = xzalloc(sizeof(*cur_var));
5544 cur_var = cur_var->next;
5545 cur_var->varstr = *e;
5546 cur_var->max_len = strlen(*e);
5547 cur_var->flg_export = 1;
5551 debug_printf_env("putenv '%s'\n", hush_version_str);
5552 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5553 #if ENABLE_FEATURE_EDITING
5554 G.line_input_state = new_line_input_t(FOR_SHELL);
5556 G.global_argc = argc;
5557 G.global_argv = argv;
5558 /* Initialize some more globals to non-zero values */
5560 #if ENABLE_HUSH_INTERACTIVE
5561 if (ENABLE_FEATURE_EDITING)
5562 cmdedit_set_initial_prompt();
5566 /* Shell is non-interactive at first. We need to call
5567 * block_signals(0) if we are going to execute "sh <script>",
5568 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5569 * If we later decide that we are interactive, we run block_signals(0)
5570 * (or re-run block_signals(1) if we ran block_signals(0) before)
5571 * in order to intercept (more) signals.
5575 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5577 opt = getopt(argc, argv, "c:xins"
5587 G.root_pid = getpid();
5588 G.global_argv = argv + optind;
5589 if (!argv[optind]) {
5590 /* -c 'script' (no params): prevent empty $0 */
5591 *--G.global_argv = argv[0];
5593 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5594 G.global_argc = argc - optind;
5595 block_signals(0); /* 0: called 1st time */
5596 parse_and_run_string(optarg);
5599 /* Well, we cannot just declare interactiveness,
5600 * we have to have some stuff (ctty, etc) */
5601 /* G_interactive_fd++; */
5604 /* "-s" means "read from stdin", but this is how we always
5605 * operate, so simply do nothing here. */
5608 case '<': /* "big heredoc" support */
5609 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5612 G.root_pid = bb_strtou(optarg, &optarg, 16);
5614 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5616 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5617 # if ENABLE_HUSH_LOOPS
5619 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5624 set_local_var(xstrdup(optarg), 0, opt == 'R');
5629 if (!set_mode('-', opt))
5633 fprintf(stderr, "Usage: sh [FILE]...\n"
5634 " or: sh -c command [args]...\n\n");
5640 } /* option parsing loop */
5643 G.root_pid = getpid();
5645 /* If we are login shell... */
5646 if (argv[0] && argv[0][0] == '-') {
5648 /* XXX what should argv be while sourcing /etc/profile? */
5649 debug_printf("sourcing /etc/profile\n");
5650 input = fopen_for_read("/etc/profile");
5651 if (input != NULL) {
5652 close_on_exec_on(fileno(input));
5653 block_signals(0); /* 0: called 1st time */
5654 signal_mask_is_inited = 1;
5655 parse_and_run_file(input);
5658 /* bash: after sourcing /etc/profile,
5659 * tries to source (in the given order):
5660 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5661 * stopping of first found. --noprofile turns this off.
5662 * bash also sources ~/.bash_logout on exit.
5663 * If called as sh, skips .bash_XXX files.
5670 * "bash <script>" (which is never interactive (unless -i?))
5671 * sources $BASH_ENV here (without scanning $PATH).
5672 * If called as sh, does the same but with $ENV.
5674 debug_printf("running script '%s'\n", argv[optind]);
5675 G.global_argv = argv + optind;
5676 G.global_argc = argc - optind;
5677 input = xfopen_for_read(argv[optind]);
5678 close_on_exec_on(fileno(input));
5679 if (!signal_mask_is_inited)
5680 block_signals(0); /* 0: called 1st time */
5681 parse_and_run_file(input);
5682 #if ENABLE_FEATURE_CLEAN_UP
5688 /* Up to here, shell was non-interactive. Now it may become one.
5689 * NB: don't forget to (re)run block_signals(0/1) as needed.
5692 /* A shell is interactive if the '-i' flag was given, or if all of
5693 * the following conditions are met:
5695 * no arguments remaining or the -s flag given
5696 * standard input is a terminal
5697 * standard output is a terminal
5698 * Refer to Posix.2, the description of the 'sh' utility.
5701 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5702 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5703 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5704 //TODO: "interactive" and "have job control" are two different things.
5705 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5706 //should stay on! Currently, we mix these into one.
5707 if (G.saved_tty_pgrp >= 0) {
5708 /* try to dup stdin to high fd#, >= 255 */
5709 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5710 if (G_interactive_fd < 0) {
5711 /* try to dup to any fd */
5712 G_interactive_fd = dup(STDIN_FILENO);
5713 if (G_interactive_fd < 0)
5715 G_interactive_fd = 0;
5717 // TODO: track & disallow any attempts of user
5718 // to (inadvertently) close/redirect it
5721 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5722 if (G_interactive_fd) {
5725 /* We are indeed interactive shell, and we will perform
5726 * job control. Setting up for that. */
5728 close_on_exec_on(G_interactive_fd);
5729 /* If we were run as 'hush &', sleep until we are
5730 * in the foreground (tty pgrp == our pgrp).
5731 * If we get started under a job aware app (like bash),
5732 * make sure we are now in charge so we don't fight over
5733 * who gets the foreground */
5735 shell_pgrp = getpgrp();
5736 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5737 if (G.saved_tty_pgrp == shell_pgrp)
5739 /* send TTIN to ourself (should stop us) */
5740 kill(- shell_pgrp, SIGTTIN);
5742 /* Block some signals */
5743 block_signals(signal_mask_is_inited);
5744 /* Set other signals to restore saved_tty_pgrp */
5745 set_fatal_handlers();
5746 /* Put ourselves in our own process group */
5747 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5748 /* Grab control of the terminal */
5749 tcsetpgrp(G_interactive_fd, getpid());
5750 /* -1 is special - makes xfuncs longjmp, not exit
5751 * (we reset die_sleep = 0 whereever we [v]fork) */
5752 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
5753 if (setjmp(die_jmp)) {
5754 /* xfunc has failed! die die die */
5755 /* no EXIT traps, this is an escape hatch! */
5757 hush_exit(xfunc_error_retval);
5759 } else if (!signal_mask_is_inited) {
5760 block_signals(0); /* 0: called 1st time */
5761 } /* else: block_signals(0) was done before */
5762 #elif ENABLE_HUSH_INTERACTIVE
5763 /* No job control compiled in, only prompt/line editing */
5764 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5765 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5766 if (G_interactive_fd < 0) {
5767 /* try to dup to any fd */
5768 G_interactive_fd = dup(STDIN_FILENO);
5769 if (G_interactive_fd < 0)
5771 G_interactive_fd = 0;
5774 if (G_interactive_fd) {
5775 close_on_exec_on(G_interactive_fd);
5776 block_signals(signal_mask_is_inited);
5777 } else if (!signal_mask_is_inited) {
5781 /* We have interactiveness code disabled */
5782 if (!signal_mask_is_inited) {
5787 * if interactive but not a login shell, sources ~/.bashrc
5788 * (--norc turns this off, --rcfile <file> overrides)
5791 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5792 printf("\n\n%s hush - the humble shell\n", bb_banner);
5793 printf("Enter 'help' for a list of built-in commands.\n\n");
5796 parse_and_run_file(stdin);
5799 #if ENABLE_FEATURE_CLEAN_UP
5800 if (G.cwd != bb_msg_unknown)
5802 cur_var = G.top_var->next;
5804 struct variable *tmp = cur_var;
5805 if (!cur_var->max_len)
5806 free(cur_var->varstr);
5807 cur_var = cur_var->next;
5811 hush_exit(G.last_exitcode);
5816 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5817 int lash_main(int argc, char **argv)
5819 //bb_error_msg("lash is deprecated, please use hush instead");
5820 return hush_main(argc, argv);
5828 static int builtin_trap(char **argv)
5835 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5839 /* No args: print all trapped. This isn't 100% correct as we
5840 * should be escaping the cmd so that it can be pasted back in
5842 for (i = 0; i < NSIG; ++i)
5844 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5845 return EXIT_SUCCESS;
5850 /* If first arg is decimal: reset all specified signals */
5851 sig = bb_strtou(*argv, NULL, 10);
5857 sig = get_signum(*argv++);
5858 if (sig < 0 || sig >= NSIG) {
5860 /* Mimic bash message exactly */
5861 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5866 G.traps[sig] = xstrdup(new_cmd);
5868 debug_printf("trap: setting SIG%s (%i) to '%s'",
5869 get_signame(sig), sig, G.traps[sig]);
5871 /* There is no signal for 0 (EXIT) */
5876 sigaddset(&G.blocked_set, sig);
5878 /* There was a trap handler, we are removing it
5879 * (if sig has non-DFL handling,
5880 * we don't need to do anything) */
5881 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5883 sigdelset(&G.blocked_set, sig);
5885 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5890 /* First arg is "-": reset all specified to default */
5891 /* First arg is "": ignore all specified */
5892 /* Everything else: execute first arg upon signal */
5894 bb_error_msg("trap: invalid arguments");
5895 return EXIT_FAILURE;
5897 if (NOT_LONE_DASH(*argv))
5903 static int builtin_true(char **argv UNUSED_PARAM)
5908 static int builtin_test(char **argv)
5915 return test_main(argc, argv - argc);
5918 static int builtin_echo(char **argv)
5925 return echo_main(argc, argv - argc);
5928 static int builtin_eval(char **argv)
5930 int rcode = EXIT_SUCCESS;
5933 char *str = expand_strvec_to_string(argv);
5935 * eval "echo Hi; done" ("done" is syntax error):
5936 * "echo Hi" will not execute too.
5938 parse_and_run_string(str);
5940 rcode = G.last_exitcode;
5945 static int builtin_cd(char **argv)
5947 const char *newdir = argv[1];
5948 if (newdir == NULL) {
5949 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5950 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5952 newdir = getenv("HOME") ? : "/";
5954 if (chdir(newdir)) {
5955 /* Mimic bash message exactly */
5956 bb_perror_msg("cd: %s", newdir);
5957 return EXIT_FAILURE;
5960 return EXIT_SUCCESS;
5963 static int builtin_exec(char **argv)
5965 if (*++argv == NULL)
5966 return EXIT_SUCCESS; /* bash does this */
5971 // FIXME: if exec fails, bash does NOT exit! We do...
5972 pseudo_exec_argv(&dummy, argv, 0, NULL);
5977 static int builtin_exit(char **argv)
5979 debug_printf_exec("%s()\n", __func__);
5980 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5981 //puts("exit"); /* bash does it */
5982 // TODO: warn if we have background jobs: "There are stopped jobs"
5983 // On second consecutive 'exit', exit anyway.
5984 // perhaps use G.exiting = -1 as indicator "last cmd was exit"
5986 /* note: EXIT trap is run by hush_exit */
5987 if (*++argv == NULL)
5988 hush_exit(G.last_exitcode);
5989 /* mimic bash: exit 123abc == exit 255 + error msg */
5990 xfunc_error_retval = 255;
5991 /* bash: exit -2 == exit 254, no error msg */
5992 hush_exit(xatoi(*argv) & 0xff);
5995 static int builtin_export(char **argv)
5997 if (*++argv == NULL) {
5999 // ash emits: export VAR='VAL'
6000 // bash: declare -x VAR="VAL"
6001 // (both also escape as needed (quotes, $, etc))
6006 return EXIT_SUCCESS;
6013 value = strchr(name, '=');
6015 /* They are exporting something without a =VALUE */
6016 struct variable *var;
6018 var = get_local_var(name);
6020 var->flg_export = 1;
6021 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6022 putenv(var->varstr);
6024 /* bash does not return an error when trying to export
6025 * an undefined variable. Do likewise. */
6028 set_local_var(xstrdup(name), 1, 0);
6031 return EXIT_SUCCESS;
6035 /* built-in 'fg' and 'bg' handler */
6036 static int builtin_fg_bg(char **argv)
6041 if (!G_interactive_fd)
6042 return EXIT_FAILURE;
6043 /* If they gave us no args, assume they want the last backgrounded task */
6045 for (pi = G.job_list; pi; pi = pi->next) {
6046 if (pi->jobid == G.last_jobid) {
6050 bb_error_msg("%s: no current job", argv[0]);
6051 return EXIT_FAILURE;
6053 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6054 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6055 return EXIT_FAILURE;
6057 for (pi = G.job_list; pi; pi = pi->next) {
6058 if (pi->jobid == jobnum) {
6062 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6063 return EXIT_FAILURE;
6065 // TODO: bash prints a string representation
6066 // of job being foregrounded (like "sleep 1 | cat")
6067 if (argv[0][0] == 'f') {
6068 /* Put the job into the foreground. */
6069 tcsetpgrp(G_interactive_fd, pi->pgrp);
6072 /* Restart the processes in the job */
6073 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6074 for (i = 0; i < pi->num_cmds; i++) {
6075 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6076 pi->cmds[i].is_stopped = 0;
6078 pi->stopped_cmds = 0;
6080 i = kill(- pi->pgrp, SIGCONT);
6082 if (errno == ESRCH) {
6083 delete_finished_bg_job(pi);
6084 return EXIT_SUCCESS;
6086 bb_perror_msg("kill (SIGCONT)");
6089 if (argv[0][0] == 'f') {
6091 return checkjobs_and_fg_shell(pi);
6093 return EXIT_SUCCESS;
6097 #if ENABLE_HUSH_HELP
6098 static int builtin_help(char **argv UNUSED_PARAM)
6100 const struct built_in_command *x;
6103 "Built-in commands:\n"
6104 "------------------\n");
6105 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6106 printf("%s\t%s\n", x->cmd, x->descr);
6109 return EXIT_SUCCESS;
6114 static int builtin_jobs(char **argv UNUSED_PARAM)
6117 const char *status_string;
6119 for (job = G.job_list; job; job = job->next) {
6120 if (job->alive_cmds == job->stopped_cmds)
6121 status_string = "Stopped";
6123 status_string = "Running";
6125 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6127 return EXIT_SUCCESS;
6132 static int builtin_memleak(char **argv UNUSED_PARAM)
6137 /* Crude attempt to find where "free memory" starts,
6138 * sans fragmentation. */
6140 l = (unsigned long)p;
6143 if (l < (unsigned long)p) l = (unsigned long)p;
6146 if (!G.memleak_value)
6147 G.memleak_value = l;
6149 l -= G.memleak_value;
6156 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6161 static int builtin_pwd(char **argv UNUSED_PARAM)
6164 return EXIT_SUCCESS;
6167 static int builtin_read(char **argv)
6170 const char *name = "REPLY";
6174 if (!is_well_formed_var_name(name, '\0')) {
6175 /* Mimic bash message */
6176 bb_error_msg("read: '%s': not a valid identifier", name);
6181 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
6182 return set_local_var(string, 0, 0);
6185 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6186 * built-in 'set' handler
6188 * set [-abCefhmnuvx] [-o option] [argument...]
6189 * set [+abCefhmnuvx] [+o option] [argument...]
6190 * set -- [argument...]
6193 * Implementations shall support the options in both their hyphen and
6194 * plus-sign forms. These options can also be specified as options to sh.
6196 * Write out all variables and their values: set
6197 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6198 * Turn on the -x and -v options: set -xv
6199 * Unset all positional parameters: set --
6200 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6201 * Set the positional parameters to the expansion of x, even if x expands
6202 * with a leading '-' or '+': set -- $x
6204 * So far, we only support "set -- [argument...]" and some of the short names.
6206 static int builtin_set(char **argv)
6209 char **pp, **g_argv;
6210 char *arg = *++argv;
6214 for (e = G.top_var; e; e = e->next)
6216 return EXIT_SUCCESS;
6220 if (!strcmp(arg, "--")) {
6225 if (arg[0] == '+' || arg[0] == '-') {
6226 for (n = 1; arg[n]; ++n)
6227 if (set_mode(arg[0], arg[n]))
6233 } while ((arg = *++argv) != NULL);
6234 /* Now argv[0] is 1st argument */
6236 /* Only reset global_argv if we didn't process anything */
6238 return EXIT_SUCCESS;
6241 /* NB: G.global_argv[0] ($0) is never freed/changed */
6242 g_argv = G.global_argv;
6243 if (G.global_args_malloced) {
6249 G.global_args_malloced = 1;
6250 pp = xzalloc(sizeof(pp[0]) * 2);
6251 pp[0] = g_argv[0]; /* retain $0 */
6254 /* This realloc's G.global_argv */
6255 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6262 return EXIT_SUCCESS;
6264 /* Nothing known, so abort */
6266 bb_error_msg("set: %s: invalid option", arg);
6267 return EXIT_FAILURE;
6270 static int builtin_shift(char **argv)
6276 if (n >= 0 && n < G.global_argc) {
6277 if (G.global_args_malloced) {
6280 free(G.global_argv[m++]);
6283 memmove(&G.global_argv[1], &G.global_argv[n+1],
6284 G.global_argc * sizeof(G.global_argv[0]));
6285 return EXIT_SUCCESS;
6287 return EXIT_FAILURE;
6290 static int builtin_source(char **argv)
6294 if (*++argv == NULL)
6295 return EXIT_FAILURE;
6297 /* XXX search through $PATH is missing */
6298 input = fopen_or_warn(*argv, "r");
6300 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
6301 return EXIT_FAILURE;
6303 close_on_exec_on(fileno(input));
6305 /* Now run the file */
6307 /* XXX argv and argc are broken; need to save old G.global_argv
6308 * (pointer only is OK!) on this stack frame,
6309 * set G.global_argv=argv+1, recurse, and restore. */
6310 parse_and_run_file(input);
6312 return G.last_exitcode;
6315 static int builtin_umask(char **argv)
6318 const char *arg = argv[1];
6320 //TODO: umask may take chmod-like symbolic masks
6321 new_umask = bb_strtou(arg, NULL, 8);
6323 //Message? bash examples:
6324 //bash: umask: 'q': invalid symbolic mode operator
6325 //bash: umask: 999: octal number out of range
6326 return EXIT_FAILURE;
6329 new_umask = umask(0);
6330 printf("%.3o\n", (unsigned) new_umask);
6331 /* fall through and restore new_umask which we set to 0 */
6334 return EXIT_SUCCESS;
6337 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6338 static int builtin_unset(char **argv)
6344 return EXIT_SUCCESS;
6347 if (argv[0][0] == '-') {
6348 switch (argv[0][1]) {
6354 bb_error_msg("unset: %s: invalid option", *argv);
6355 return EXIT_FAILURE;
6357 //TODO: disallow "unset -vf ..." too
6364 if (unset_local_var(*argv)) {
6365 /* unset <nonexistent_var> doesn't fail.
6366 * Error is when one tries to unset RO var.
6367 * Message was printed by unset_local_var. */
6371 #if ENABLE_HUSH_FUNCTIONS
6373 unset_local_func(*argv);
6381 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6382 static int builtin_wait(char **argv)
6384 int ret = EXIT_SUCCESS;
6387 if (*++argv == NULL) {
6388 /* Don't care about wait results */
6389 /* Note 1: must wait until there are no more children */
6390 /* Note 2: must be interruptible */
6392 * $ sleep 3 & sleep 6 & wait
6397 * $ sleep 3 & sleep 6 & wait
6401 * ^C <-- after ~4 sec from keyboard
6404 sigaddset(&G.blocked_set, SIGCHLD);
6405 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6408 if (errno == ECHILD)
6410 /* Wait for SIGCHLD or any other signal of interest */
6411 /* sigtimedwait with infinite timeout: */
6412 sig = sigwaitinfo(&G.blocked_set, NULL);
6414 sig = check_and_run_traps(sig);
6415 if (sig && sig != SIGCHLD) { /* see note 2 */
6421 sigdelset(&G.blocked_set, SIGCHLD);
6422 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6426 /* This is probably buggy wrt interruptible-ness */
6428 pid_t pid = bb_strtou(*argv, NULL, 10);
6430 /* mimic bash message */
6431 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6432 return EXIT_FAILURE;
6434 if (waitpid(pid, &status, 0) == pid) {
6435 if (WIFSIGNALED(status))
6436 ret = 128 + WTERMSIG(status);
6437 else if (WIFEXITED(status))
6438 ret = WEXITSTATUS(status);
6442 bb_perror_msg("wait %s", *argv);
6451 #if ENABLE_HUSH_LOOPS
6452 static int builtin_break(char **argv)
6454 if (G.depth_of_loop == 0) {
6455 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6456 return EXIT_SUCCESS; /* bash compat */
6458 G.flag_break_continue++; /* BC_BREAK = 1 */
6459 G.depth_break_continue = 1;
6461 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6462 if (errno || !G.depth_break_continue || argv[2]) {
6463 bb_error_msg("%s: bad arguments", argv[0]);
6464 G.flag_break_continue = BC_BREAK;
6465 G.depth_break_continue = UINT_MAX;
6468 if (G.depth_of_loop < G.depth_break_continue)
6469 G.depth_break_continue = G.depth_of_loop;
6470 return EXIT_SUCCESS;
6473 static int builtin_continue(char **argv)
6475 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6476 return builtin_break(argv);